Repository navigation
gh-162529: Run function watchers under the function's critical section #162530
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
Draft
alexmalyshev
wants to merge
1
commit into
python:main
Choose a base branch
from
alexmalyshev:func-watcher-order
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import gc | ||
| import unittest | ||
|
|
||
| from test.support import import_helper, threading_helper | ||
|
|
||
| _testcapi = import_helper.import_module("_testcapi") | ||
|
|
||
| NTHREADS = 8 | ||
| ITERS = 200 | ||
|
|
||
|
|
||
| def template(x=1, *, y=2): | ||
| return x | ||
|
|
||
|
|
||
| @threading_helper.requires_working_threading() | ||
| class TestFuncWatcherThreadSafety(unittest.TestCase): | ||
| """MODIFY events and stores to function fields must not interleave. | ||
|
|
||
| When a function watcher receives a MODIFY event, the function must still | ||
| hold the value announced by the previous event for the same attribute. | ||
| Otherwise watchers that track a function's state (e.g. a JIT) can end up | ||
| believing it holds a different value than it does. | ||
| """ | ||
|
|
||
| def setUp(self): | ||
| # Stopping the world for a garbage collection can suspend the | ||
| # function's critical section between an event and its store. Keep | ||
| # the GC out of the way so this checks what the setters guarantee. | ||
| if gc.isenabled(): | ||
| gc.disable() | ||
| self.addCleanup(gc.enable) | ||
|
|
||
| def check_events_match_stores(self, event, getter, setter, make_value): | ||
| def target(x=1, *, y=2): | ||
| return x | ||
|
|
||
| def writer(): | ||
| for _ in range(ITERS): | ||
| setter(target, make_value()) | ||
|
|
||
| _testcapi.start_func_order_watcher(target, event) | ||
| try: | ||
| threading_helper.run_concurrently(writer, NTHREADS) | ||
| finally: | ||
| history, mismatches = _testcapi.stop_func_order_watcher() | ||
|
|
||
| self.assertEqual(mismatches, 0, | ||
| f"{mismatches} of {len(history) - 1} events were " | ||
| f"delivered before the previous event's store") | ||
| self.assertEqual(len(history), NTHREADS * ITERS + 1) | ||
| self.assertIs(getter(target), history[-1]) | ||
|
|
||
| def check_attr(self, attr, event, make_value): | ||
| self.check_events_match_stores( | ||
| event, | ||
| lambda f: getattr(f, attr), | ||
| lambda f, v: setattr(f, attr, v), | ||
| make_value) | ||
|
|
||
| def test_code(self): | ||
| # Every store gets a distinct code object so that identity checks | ||
| # can't pass by coincidence. | ||
| code = template.__code__ | ||
| self.check_attr( | ||
| "__code__", _testcapi.PYFUNC_EVENT_MODIFY_CODE, | ||
| lambda: code.replace(co_name=f"template_{id(object())}")) | ||
|
|
||
| def test_defaults(self): | ||
| self.check_attr( | ||
| "__defaults__", _testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS, | ||
| lambda: (object(),)) | ||
|
|
||
| def test_kwdefaults(self): | ||
| self.check_attr( | ||
| "__kwdefaults__", _testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS, | ||
| lambda: {"y": object()}) | ||
|
|
||
| def test_qualname(self): | ||
| self.check_attr( | ||
| "__qualname__", _testcapi.PYFUNC_EVENT_MODIFY_QUALNAME, | ||
| lambda: str(object())) | ||
|
|
||
| def test_defaults_via_capi(self): | ||
| self.check_events_match_stores( | ||
| _testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS, | ||
| lambda f: f.__defaults__, | ||
| _testcapi.set_func_defaults_via_capi, | ||
| lambda: (object(),)) | ||
|
|
||
| def test_kwdefaults_via_capi(self): | ||
| self.check_events_match_stores( | ||
| _testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS, | ||
| lambda f: f.__kwdefaults__, | ||
| _testcapi.set_func_kwdefaults_via_capi, | ||
| lambda: {"y": object()}) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
1 change: 1 addition & 0 deletions
1
Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-00-41-44.gh-issue-162529.GJRQ7I.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Function watchers are now run under the function's critical section. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this opens up the opportunity for us to release the critical section, have the function be further modified before we stop the world, and then when we resume w/ the world stopped the function is modified from before we do the update.
I think in that case watchers should be in a sane state - we've fired the events in order, but here we're going to update to the 1st value which is going to lead to an inconsistent state.
I think we probably need to capture (and inc ref) the value and then validate that it's the same. I think it's similar to https://github.com/python/cpython/pull/161586/changes - @nascheme may have this paged into his head enough where he has a good idea if this is the same pattern.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I think this design has problems. It can't promise the ordering if the STW request is contended (stw->mutex, or a global STW like GC). The CS can be suspended and other threads run holding that CS before you enter STW. Also, if the callback suspends (by allocating and triggering GC, taking another critical section, or running bytecode), another setter can get in.
Two possible ideas: document that MODIFY events can arrive in different order from the stores, when threads race. I'm guessing you don't want that, seems the point of this PR to avoid it.
Another idea, record something (per-func modification count) under the CS before firing the event, in STW check and if changed the restart and retry. I think you could still get "strange" events, e.g. if T1 sets A and T2 sets B, watcher could see A B A. That approach seems similar to the counter based approach I was trying to use to fix the typeobject STW deadlock issue. Tricky to get right.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah I'd prefer not to further cement this behavior if possible.
Also would like to avoid this.
Suggesting a much larger change, but could we stop the world on just the first time we clear the function's version? IIUC, once cleared, it can never change value again. It would require hunting down all the places where these fields are loaded without holding the critical section or using atomics though. But the upside would be that we could then just use the function's critical section for all future function modifications.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that could work. There are quite a lot of readers to change. It would require atomic loads for the hot paths but should have negligible performance impact. Perhaps that should happen in a different PR and then this one would be just moving the event into the CS?