Skip to content

PyMonitoring_FirePyStartEvent results in incorrect duplicate calls to sys.setprofile profile functions #158711

Description

@godlygeek

See bloomberg/memray#1037 and cython/cython#8032

The C API to programmatically trigger sys.monitoring events that was added in PR #116413 to solve issue #111997 and give Cython a way to trigger monitoring events for Cython frames does not work correctly with the legacy_tracing.c implementation of sys.setprofile profile functions.

When Cython uses sys.monitoring to signal that a Cython function has been entered, it creates a code object with PyCode_NewEmpty, sets a file name, function name, and line number for it, and then calls PyMonitoring_FirePyStartEvent. If there's a profile function that was installed by sys.setprofile, CPython's code in legacy_tracing.c registers an adapter callback that calls the sys.setprofile profile function. That adapter callback completely ignores the code object that is passed to it, and instead passes the sys.setprofile function the top frame of the Python stack, as returned by PyEval_GetFrame.

This interaction is completely broken: profilers installed by sys.setprofile never see the Cython frame, and instead see duplicates of the Python frame that called into Cython.

This could be fixed by CPython checking whether the code object that the monitoring callback receives is the code object held by the top frame of the Python stack, and refusing to call the tstate->c_profilefunc if not.

Or it could be fixed by CPython detecting that condition and creating a fake frame to pass to the c_profilefunc.

Or it could be fixed by Cython falling back to not using sys.monitoring whenever tstate->c_profilefunc is set.

I'm filing the issue against both CPython and Cython concurrently, in the hopes that if it's agreed this is a CPython bug the bugfix might get backported to 3.13 (which I think is, technically, getting one extra week of bug fix support, since 3.15.0 was delayed!)

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions