Visitar URL original
GH-103082: Implementation of PEP 669: Low Impact Monitoring for CPython by markshannon · Pull Request #103083 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20230408070214/https://github.com/python/cpython/pull/103083
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-103082: Implementation of PEP 669: Low Impact Monitoring for CPython #103083

Open
wants to merge 121 commits into
base: main
Choose a base branch
from

Conversation

markshannon
Copy link
Member

@markshannon markshannon commented Mar 28, 2023 •

This implements PEP 669.
There are a couple of things missing, but no harm in early review.

@gvanrossum
Copy link
Member

I'd like to invite @nedbat to review this PR, in particular, to see if it breaks or improves anything related to coverage.py. Ned, I know that you're busy, but your early feedback is really important here!

@nedbat
Copy link
Member

nedbat commented Apr 4, 2023 •

Thanks for the ping. I don't know that I'll be able to review the code, but I ran the coverage.py test suite with it, and everything passed, so "first do no harm" checks out. We should talk about what else I can do here. I don't know what effort would be required to try to take advantage of the new changes.

% tox -e anypy -r
ROOT: tox-gh won't override envlist because tox is not running in GitHub Actions
.pkg: remove tox env folder .tox/.pkg
anypy: install_deps> python -m pip install -U -r requirements/pip.pip -r requirements/pytest.pip
.pkg-cpython312: remove tox env folder .tox/.pkg-cpython312
.pkg-cpython312: install_requires> python -I -m pip install setuptools
.pkg-cpython312: _optional_hooks> python /usr/local/virtualenvs/coverage/lib/python3.7/site-packages/pyproject_api/_backend.py True setuptools.build_meta
.pkg-cpython312: get_requires_for_build_editable> python /usr/local/virtualenvs/coverage/lib/python3.7/site-packages/pyproject_api/_backend.py True setuptools.build_meta
.pkg-cpython312: install_requires_for_build_editable> python -I -m pip install wheel
.pkg-cpython312: build_editable> python /usr/local/virtualenvs/coverage/lib/python3.7/site-packages/pyproject_api/_backend.py True setuptools.build_meta
anypy: install_package_deps> python -m pip install -U 'tomli; python_full_version <= "3.11.0a6"'
anypy: install_package> python -m pip install -U --force-reinstall --no-deps .tox/.tmp/package/11/coverage-7.2.3a0.dev1-0.editable-cp312-cp312-macosx_13_0_x86_64.whl
anypy: commands[0]> python igor.py zip_mods
anypy: commands[1]> python setup.py --quiet build_ext --inplace
anypy: commands[2]> python -m pip install -q -e .
anypy: commands[3]> python igor.py test_with_tracer c
=== CPython 3.12.0a6+ (rev 44a031e255) with C tracer (.tox/anypy/bin/python) ===
bringing up nodes...
.......................................................................................................................................................... [ 11%]
...................................................................s....................s..........s.s..ss.................ss....s........................ [ 23%]
.........................................................................................s................................................................ [ 34%]
.....................................................................................s..........................................s......................... [ 46%]
.......................................................................................................................................................... [ 57%]
........................................................................................................................................................s. [ 69%]
............s......s............................s................................................................................................ss....... [ 80%]
.....................s.......................................................s............................................................................ [ 92%]
.....................................................................................................                                                      [100%]
1313 passed, 20 skipped in 34.40s
anypy: commands[4]> python igor.py remove_extension
anypy: commands[5]> python igor.py test_with_tracer py
=== CPython 3.12.0a6+ (rev 44a031e255) with Python tracer (.tox/anypy/bin/python) ===
bringing up nodes...
.......................................................................................................................................................... [ 11%]
.........................................................................s................s.........................s...ss..s......s..s.............s..... [ 23%]
...........................................s.......s....................................ss......sss...........s........................................... [ 34%]
...................................................................................s...................................................................... [ 46%]
.................................................................ss.............s.......................................................................... [ 57%]
...................s....................................................................ssss.............s.sss...........................................s [ 69%]
ss.s........................sssss............................................................................................................s............ [ 80%]
....................................s......................................................................................................s.s............ [ 92%]
..............................................................................................ss....                                                       [100%]
1288 passed, 45 skipped in 35.28s
.pkg-cpython312: _exit> python /usr/local/virtualenvs/coverage/lib/python3.7/site-packages/pyproject_api/_backend.py True setuptools.build_meta
  anypy: OK (97.89=setup[18.80]+cmd[0.55,1.33,6.01,35.33,0.21,35.66] seconds)
  congratulations :) (99.97 seconds)

Copy link
Member

@gvanrossum gvanrossum left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I'm not going to finish the review today, here are some UX nits. (I trust Erlend to catch the C code nits. :-)

I did try to play around with it using the PEP as documentation, and I found a few things (some probably just in need of PEP tweaks).

  • All in all I really like the experience of tracing using this new API!
  • The PEP is pretty terse: This will need user documentation as part of the library reference; maybe even a tutorial. (Not in this PR of course, but let's please keep the issue open or create a separate doc issue.)
  • It took me a while to figure out that event_set is a "set" constructed by OR-ing various events together (a common C idiom of course but not apparent until you see their integer values, and I intentionally didn't look at the code for this).
  • set_local_events: tool_id and code args are swapped compared to the PEP.
  • dis.dis(code, adaptive=True) shows the RESERVED and CACHE opcodes following any INSTRUMENTED opcodes (even though show_caches defaults to False).
  • I found it a little inconvenient that instruction_offset is measured in instructions, not in bytes (I was using dis to see what I was getting). There was a lot of instr*2 in my code.
  • The naming of the CALL and RETURN/RAISE events is a bit confusing -- we have CALL (universal), C_RETURN/PY_RETURN (per language), but then C_RAISE and RAISE -- why isn't the latter PY_RAISE, just for consistency?
  • I see that the PEP prescribes that INSTRUCTION events are reported before LINE events on the same instruction. I found this confusing. Is it too late to change this around? Since a line can contain many instructions, it would appear more useful to see the LINE event first, so I can e.g. just do print("LINE", lineno) in the LINE callback and print all instructions that are logically part of the line following that point.
  • How do I retrieve additional arguments if there are more than 1?

Lib/opcode.py Show resolved Hide resolved
Include/cpython/code.h Outdated Show resolved Hide resolved
Include/internal/pycore_frame.h Outdated Show resolved Hide resolved
Include/internal/pycore_interp.h Outdated Show resolved Hide resolved
Objects/frameobject.c Show resolved Hide resolved
Python/specialize.c Outdated Show resolved Hide resolved
Python/instrumentation.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
Python/legacy_tracing.c Outdated Show resolved Hide resolved
}


PyTypeObject _PyLegacyEventHandler_Type = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be added to

static PyTypeObject* static_types[] = {

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why?

Shared static objects need to be stateless (and ideally immortal and immutable once we have immortal objects).

There can be some very minimal state provided that initializing it is idempotent and thread-safe, but that should be the responsibility not of the class, but the interpreter.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://github.com/python/cpython/blob/main/Objects/typeobject.c#L7012, it seems that _PyStaticType_InitBuiltin, called from _PyTypes_InitTypes in object.c for every type in that array, finishes initializing types (not ideal, but that's the current convention).

@markshannon
Copy link
Member Author

@gvanrossum

All in all I really like the experience of tracing using this new API!

Thanks

The PEP is pretty terse: This will need user documentation as part of the library reference; maybe even a tutorial. (Not in this PR of course, but let's please keep the issue open or create a separate doc issue.)

I've updated the issue to mention documentation
I'll add your comments on usability to that

dis.dis(code, adaptive=True) shows the RESERVED and CACHE opcodes following any INSTRUMENTED opcodes (even though show_caches defaults to False).

I didn't really give this much thought. As soon as you set adaptive = True, you are asking to see what is happening internally, so it would misleading if we hid the INSTRUMENTED opcodes.
If you think we should also show the underlying instruction, could you make an issue for that (I don't want to add that complexity to this PR).

I found it a little inconvenient that instruction_offset is measured in instructions, not in bytes (I was using dis to see what I was getting). There was a lot of instr*2 in my code.

Sure, we can change the offsets to be bytecode offsets. It would be more consistent with everything else.

The naming of the CALL and RETURN/RAISE events is a bit confusing -- we have CALL (universal), C_RETURN/PY_RETURN (per language), but then C_RAISE and RAISE -- why isn't the latter PY_RAISE, just for consistency?

The RAISE event occurs if an exception is raised, it doesn't matter how. So it can be from a raise statement or from a builtin function.

If CALL is universal, so it can be disabled. If you only saw C_CALL events for calling builtins, then it would be impossible to disable the event if the call only went to Python functions.

C_RAISE exists (even though RAISE exists as well) for profilers and similar to balance the entries to builtin functions with the exits. Each CALL event to a builtin will be matched with either a C_RETURN or C_RAISE.

I see that the PEP prescribes that INSTRUCTION events are reported before LINE events on the same instruction. I found this confusing. Is it too late to change this around? Since a line can contain many instructions, it would appear more useful to see the LINE event first, so I can e.g. just do print("LINE", lineno) in the LINE callback and print all instructions that are logically part of the line following that point.

I don't think there is a natural or correct order of events here. There is no guarantee that the compiler will put the line event on the instruction you expect.

For example:

def f():
   a = 1
   pass
   return 2

Could (and probably should) be compiled as:

  1           0 RESUME                   0
  2           2 LOAD_CONST               1 (1)
  3           4 STORE_FAST               0 (a)
  4           8 RETURN_CONST             2 (2)

How do I retrieve additional arguments if there are more than 1?

You don't. The first argument is only provided to support the strange behavior of sys.setprofile() and sys.setprofile() when calling a method descriptor.

Would it be useful to do so?
It would add quite a lot of overhead to CALL instrumentation as we would need to bundle all the positional arguments into a tuple, and all the named arguments into a dict.

@markshannon
Copy link
Member Author

I should say that I'm not surprised this works on coverage, thanks to @nedbat's tireless efforts to make sure every corner case of tracing was tested for PEP 626. Thanks to Ned, we have a pretty solid set of tests for line tracing. The tests for sys.settrace() found far more issues than the tests for sys.monitoring that I added.
Thanks @nedbat

@gvanrossum
Copy link
Member

@fabioz Just an FYI that this is about to land. Are you interested in trying this out?

@gvanrossum
Copy link
Member

@markshannon

@gvanrossum

dis.dis(code, adaptive=True) shows the RESERVED and CACHE opcodes following any INSTRUMENTED opcodes (even though show_caches defaults to False).

I didn't really give this much thought. As soon as you set adaptive = True, you are asking to see what is happening internally, so it would misleading if we hid the INSTRUMENTED opcodes. If you think we should also show the underlying instruction, could you make an issue for that (I don't want to add that complexity to this PR).

I don't want to hide the INSTRUMENTED opcodes (or even show the original opcodes), but I'd like to hide the RESERVED/CACHED opcodes unless show_caches=True is also passed. But I just realized that dis doesn't have the information needed to even show the underlying instruction -- I guess it'd have to be passed both the adaptive and the original bytecode arrays. Given this, I don't care enough to even file that issue. :-)

The naming of the CALL and RETURN/RAISE events is a bit confusing -- we have CALL (universal), C_RETURN/PY_RETURN (per language), but then C_RAISE and RAISE -- why isn't the latter PY_RAISE, just for consistency?

The RAISE event occurs if an exception is raised, it doesn't matter how. So it can be from a raise statement or from a builtin function.

If CALL is universal, so it can be disabled. If you only saw C_CALL events for calling builtins, then it would be impossible to disable the event if the call only went to Python functions.

C_RAISE exists (even though RAISE exists as well) for profilers and similar to balance the entries to builtin functions with the exits. Each CALL event to a builtin will be matched with either a C_RETURN or C_RAISE.

Okay, I think I follow this now. It's definitely worth calling out these subtleties in the user docs -- it's much easier to remember if you know the underlying model.

I see that the PEP prescribes that INSTRUCTION events are reported before LINE events on the same instruction. I found this confusing. Is it too late to change this around? Since a line can contain many instructions, it would appear more useful to see the LINE event first, so I can e.g. just do print("LINE", lineno) in the LINE callback and print all instructions that are logically part of the line following that point.

I don't think there is a natural or correct order of events here. There is no guarantee that the compiler will put the line event on the instruction you expect.

For example:

def f():
   a = 1
   pass
   return 2

Could (and probably should) be compiled as:

  1           0 RESUME                   0
  2           2 LOAD_CONST               1 (1)
  3           4 STORE_FAST               0 (a)
  4           8 RETURN_CONST             2 (2)

I don't understand why in that example the line number for the STORE_FAST shouldn't be the same as that for the LOAD_CONST. Maybe you copied/pasted the wrong function? The key point seems to be your assertion "There is no guarantee that the compiler will put the line event on the instruction you expect." Maybe not in obscure corner cases, like situations where there is code emitted that doesn't naturally belong to a given line, like the __exit__ calling logic or the except * cleanup. But for the example I gave it's pretty cut and dry. Even (especially?) if the compiler doesn't do what you expect, it might be nice to be able to tell what the compiler did by tracing the instruction sequence.

I suspect that the reason has more to do with how it's implemented -- I'm still trying to understand how INSTRUMENTED_INSTRUCTION ends up calling INSTRUMENTED_LINE (if it even does so).

Copy link
Member

@gvanrossum gvanrossum left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's some more. Still to do: instrumentation.c (not sure if I'll get to it, don't wait for me).

Python/ceval.c Outdated Show resolved Hide resolved
@@ -2973,69 +2612,6 @@ PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
return new_index;
}

static void
dtrace_function_entry(_PyInterpreterFrame *frame)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like DTRACE is now dead? There are a few relics in pyconfig.h, pydtrace.h, and in ceval_macros.h.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have DTRACE tests and there are a few open issues about it not working as expected.
Rather than get it wrong, I think it is better to not support it for now.
I think @ambv wants to fix up DTRACE support, so let's leave the pydtrace.h and the macros for now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth opening an issue to determine the fate of DTRACE support? @ambv

"\n");

#define MONITORING_USE_TOOL_ID_METHODDEF \
{"use_tool_id", _PyCFunction_CAST(monitoring_use_tool_id), METH_FASTCALL, monitoring_use_tool_id__doc__},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just discovered this. Shouldn't the fundamental functions (set_events etc.) check that the tool ID is registered? That doesn't really prevent stomping on someone else intentionally, but at least it makes people properly register their tool id.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spec is that registering IDs is a politeness, not a requirement.
The value of having IDs is that well behaved tools don't accidentally trample on each other.

Forcing tools to register might give an illusion of ownership.
There is no way to check that the tool that registered the ID is the same one as is setting events, nor is there anyway to stop a tool taking another's ID.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But checking that the ID is registered helps everyone stay polite. These IDs are like file descriptors. I like to require registration.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Come to think of it, maybe it could work like open() and return the next available ID.)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Come to think of it, maybe it could work like open() and return the next available ID.)

There are recommended IDs for tools to use. The idea being that you might want a debugger and coverage tool, but you almost certainly don't want two debuggers.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see your point, but this is a change to the PEP, with all the rigmarole that involves.

The code change should be simple enough.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The predefined IDs could be like pre-opens FDs, e.g. 0, 1, 2 for std(in,out,err). I’ll take it to the SC as well.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 on the approach of asking for the next available id.

}


PyTypeObject _PyLegacyEventHandler_Type = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://github.com/python/cpython/blob/main/Objects/typeobject.c#L7012, it seems that _PyStaticType_InitBuiltin, called from _PyTypes_InitTypes in object.c for every type in that array, finishes initializing types (not ideal, but that's the current convention).

Python/bytecodes.c Show resolved Hide resolved
Python/bytecodes.c Outdated Show resolved Hide resolved
Python/bytecodes.c Show resolved Hide resolved
Python/bytecodes.c Outdated Show resolved Hide resolved
Python/bytecodes.c Outdated Show resolved Hide resolved
Python/bytecodes.c Outdated Show resolved Hide resolved
@markshannon
Copy link
Member Author

I don't understand why in that example the line number for the STORE_FAST shouldn't be the same as that for the LOAD_CONST. Maybe you copied/pasted the wrong function?

No copy and paste error. That is a correct translation of the function. And that's the point: it is correct and does not conform to your intuition of the sequencing of line events and instructions.
See PEP 626 for what defines "correct" here.

it might be nice to be able to tell what the compiler did by tracing the instruction sequence.

dis is a much better way to do that.

@gvanrossum
Copy link
Member

I don't understand why in that example the line number for the STORE_FAST shouldn't be the same as that for the LOAD_CONST. Maybe you copied/pasted the wrong function?

No copy and paste error. That is a correct translation of the function. And that's the point: it is correct and does not conform to your intuition of the sequencing of line events and instructions. See PEP 626 for what defines "correct" here.

it might be nice to be able to tell what the compiler did by tracing the instruction sequence.

dis is a much better way to do that.

So assuming the compiler is allowed to translate it that way, I still think the instrumentation should report the lineno before the first instruction considered to be part of that line. Then the LINE callback can assign the line number to some variable inside the debugger and the INSTRUCTION callback can safely assume that that line number is the best estimate of the line to which the instruction belongs (according to the compiler).

@markshannon
Copy link
Member Author

Then the LINE callback can assign the line number to some variable inside the debugger and the INSTRUCTION callback can safely assume that that line number is the best estimate of the line to which the instruction belongs (according to the compiler).

That seems awfully complicated. You'll need to maintain a stack of line numbers to handle calls, handle every call/return call/raise, send/yield, etc pair.
frame.f_lineno has the line number, if you need it.

@markshannon
Copy link
Member Author

@gvanrossum
Changing the order of events from:

  • INSTRUCTION
  • LINE
  • All other events (only one of these events can occur per instruction)

to:

  • LINE
  • INSTRUCTION
  • All other events (only one of these events can occur per instruction)

is feasible. It's a bit of work, but not too much.
However, the PEP states the order, so we would need to discuss the change on discuss.python.org and get SC approval.
If you are willing to do that, then I'd be happy to make the code changes.

FTR: any other order is infeasible. All other events must come after INSTRUCTION and LINE.

@fabioz
Copy link

fabioz commented Apr 7, 2023 •

@gvanrossum thanks for the ping :)

@markshannon I'm testing this version (still using the tracing) with the debugger (debugpy/pydev.debugger) and I'm facing a bug (note: I confirmed it works in the main branch and fails just after this PR is applied).

Consider the code below:

import sys

if __name__ == "__main__":
    N = len(sys.argv)  # break here

    if N >= 2:  # step 1
        arg1 = sys.argv[1]  # the debugger gets here even though N=1
        print(arg1)
    else:
        arg1 = 'MyString'  # step 2

    if N >= 3:  # step 3
        arg2 = int(sys.argv[2])  # the debugger gets here even though N=1
    else:
        arg2 = int(0)  # step 4

    print(N)  # still N=1 step 5
    # print(arg1)  # if you print this then it changes the debugger behavior above

Now, if you use the current debugger version (you can use the latest vscode with the python extension or eclipse/pydev to reproduce) and place a breakpoint at the line: # break here, if you press step-over, it'll still stay in the same line once, but if you step-over again then it'll go to the next -- this happens "randomly" depending on where it's stopped (if you keep pressing step over you can see that sometimes it goes directly to the next line sometimes it needs an additional step because stepping it stays in the same line).

As far as I could see from the debugger side, this is because the frame.f_lineno is not correct when the trace_dispatch function is called, but all I know is that the machinery is calling it twice in the same line, not really the reason it happens.

Note that this doesn't reproduce in a really simple tracer as the one below (in that case it prints the lines correctly as expected).

def tracefunc(frame, event, arg):
    print(frame, event, arg)
    return tracefunc

sys.settrace(tracefunc)

I can only reproduce it when running in the actual debugger and it actually stops in a breakpoint (presumably because when the debugger is stopped at a breakpoint, lots of things happen such as getting local variables, etc).

p.s.: To see the file received in the debugger during the tracing, there's a print that can be uncommented at the top of the following method: _pydevd_bundle.pydevd_frame.PyDBFrame.trace_dispatch.

@gvanrossum
Copy link
Member

@gvanrossum Changing the order of events from:

  • INSTRUCTION
  • LINE
  • All other events (only one of these events can occur per instruction)

to:

  • LINE
  • INSTRUCTION
  • All other events (only one of these events can occur per instruction)

is feasible. It's a bit of work, but not too much. However, the PEP states the order, so we would need to discuss the change on discuss.python.org and get SC approval. If you are willing to do that, then I'd be happy to make the code changes.

I would be happy to do that. Given that this is the first user feedback on a complex PEP this shouldn’t run into opposition.

FTR: any other order is infeasible. All other events must come after INSTRUCTION and LINE.

I have no problem with that. The order LINE, INSTRUCTION, everything else makes the most sense to me.

@erlend-aasland erlend-aasland self-requested a review April 7, 2023 22:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

10 participants