Skip to content

Code object comparison could lead to monitoring issue #136223

Open
@gaogaotiantian

Description

@gaogaotiantian

Bug report

Bug description:

Currently we compare code objects with a lot of its features, but not the file it is defined in - that might make some sense because the two code objects are "equivalent" as long as all their features match. However, the two code objects could still be two different ones - for example, if they are two exact same functions defined in two different files (this is a real case for me and it took me a while to figure it out).

The problem is, code objects can be used as keys. When we have "equal but not the same" code objects, it could affect monitoring. We thought we were monitoring one code object while we are actually monitoring another one.

The code was like this:

@cache
def get_code_lineno(code):
    ...
    return {code: [...]}

assert code1 == code2  # two code objects in two different files

for c, linenos in get_code_lineno(code1):
    sys.monitoring.set_local_events(tool, c, E.LINE)

for c, linenos in get_code_lineno(code2):
    # This does not instrument code2! This instruments code1 because of the cache!
    sys.monitoring.set_local_events(tool, c, E.LINE)

Do we consider this an expected behavior? Should we just "live with it" as it's not that common? (Again, this is a real issue I had when I was working on a project).

@markshannon

CPython versions tested on:

3.12, CPython main branch, 3.13, 3.14

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions