Skip to content

co_instrumentation and co_monitoring Unexpectedly Set #133524

Description

@ericsnowcurrently

Bug report

Bug description:

I ran into the following problematic case with gh-133221 (which had to be reverted):

import sys
import _testinternalcapi

def foo():
    pass

def trace_temporarily():
    sys._getframe().f_trace_opcodes = True
    sys.settrace(print)
    sys.settrace(None)
    sys._getframe().f_trace_opcodes = False
trace_temporarily()

_testinternalcapi.verify_stateless_code(foo.__code__)
foo()
_testinternalcapi.verify_stateless_code(foo.__code__)  # fails

(See #133221 (comment).)

I would expect co_instrumentation and co_monitoring to have remained NULL.

CC @markshannon

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Activity

  1. changed the title [-]co_instrumentation Unexpectedly Set[/-] [+]co_instrumentation and co_monitoring Unexpectedly Set[/+] on May 6, 2025
  2. gaogaotiantian commented on May 6, 2025

    @gaogaotiantian
    Member

    The root cause for this is that flipping f_trace_opcodes changes the global version of instrumentation. Therefore a new function being called allocates the instrumentation data to get up to date.

    I think we can do an optimization here by checking if any event is set globally - if not, don't bother allocating the instrumentation memory. If @markshannon thinks this is something we should do, I can do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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