Repository navigation
Stress re-init with finalizers against lock-free readers - #1621
Conversation
Add a threaded test that re-initializes a shared multidict, through both md_init() and md_clone_from_ht(), whose old values have a __del__ that reads and adds to it, while other threads run lock-free lookups and iterate it. Under TSan it found two data races, fixed here. md_clone_from_ht() memcpy()'d the whole source table, including the num_readers field that lock-free readers of the source update atomically; the copy now skips the reader fields. _md_install_keys() stored md->is_ci on every re-init while lock-free lookups read it; the store now happens only when the value changes, which a re-init of a live multidict never does through its own type's __init__().
|
Comments Outside DiffThese findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1621 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 44 44
Lines 8268 8373 +105
Branches 703 706 +3
==========================================
+ Hits 8268 8373 +105
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
<!-- Thank you for your contribution! --> ## What do these changes do? In the C extension, `__init__()` took the case mode from the class whose `__init__` slot was called, not from the instance. So `MultiDict.__init__(ci_md, pairs)` quietly turned a `CIMultiDict` case-sensitive (`type(d)` still `CIMultiDict`, but `"key" in d` became false for `"Key"`), and `CIMultiDict.__init__(md)` raised `TypeError`. The pure-Python implementation reads `self._ci` and has neither problem. `_multidict_tp_init()` now reads `self->is_ci`. Without the parameter the `MultiDict` and `CIMultiDict` `tp_init` slots were identical, so `CIMultiDict` inherits `MultiDict`'s, which matches pure Python, where `CIMultiDict.__init__ is MultiDict.__init__`. This came up while investigating the TSan report fixed in #1621. It is also the only way a live multidict's `is_ci` could change, which #1621's guarded store in `_md_install_keys()` otherwise relies on never happening. ## Are there changes in behavior for the user? Yes. Calling one class's `__init__()` on an instance of the other now keeps the instance's own case mode, and `CIMultiDict.__init__()` accepts a `MultiDict`, as the pure-Python implementation already did. ## Is it a substantial burden for the maintainers to support this? No. It removes a function. ## Related issue number Found while working on #1621, and stacked on it: this branch includes #1621's commit until that one merges. Without #1621, reading `self->is_ci` here races the unconditional store to `is_ci` that #1621 removes, and CI's TSan job reports it from `test_reinit_thread_safety`. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes (N/A, the documented behaviour did not change) - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` (N/A) - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` Drafted with Claude Code (Claude Opus 5.5); reviewed by <pending human review>. <details> <summary>Agent run details (optional, for reviewers)</summary> - New test `test_base_init_keeps_case_mode` on master's C extension: both C cases fail (the `AssertionError` above, and `TypeError: descriptor '__init__' requires a 'multidict._multidict.CIMultiDict' object`). The pure-Python cases pass before and after. - Full suite: FT 3.14.7t release 2869 passed; FT `MULTIDICT_DEBUG_BUILD=1` 2869 passed; GIL 3.10.17 2881 passed; pure Python (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`) 1357 passed. - callgrind on GIL 3.10.17, where construction goes through `tp_init`, `PYTHONHASHSEED=0`: no `ctor_*` row moved; `update` -10 Ir (-0.03%). - `make doc-spelling`, pre-commit: pass. </details>
<!-- Thank you for your contribution! --> ## What do these changes do? `test_reinit_finalizer_vs_lock_free_readers` (#1621) timed out on the Windows 3.10, 3.11 and 3.12 jobs, at `f.result(timeout=60)` for its readers. The faulthandler dump from a 183 s run shows every reader still inside `Value.__del__()` -> `probe()` after the writer finished, each blocked in `coverage/collector.py: lock_data`. Under coverage's C tracer (3.10 to 3.12) every traced line takes a lock the threads share, and the readers are draining the finalizers of generations their `copy()` snapshots outlived. That work is bounded (3216 finalizers, nesting depth 1), just slow: 0.4 s without coverage, 12 to 20 s with it on a Linux 3.11 box, and over three minutes on the Windows runners. The failure reports also show every reader future finished by the time pytest rendered them. The writer now gets 300 s and the readers a shared 300 s deadline, inside the job's 15-minute limit. ## Are there changes in behavior for the user? No, tests only. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number Follows #1621. Failed on #1625, #1628 (twice) and #1630; re-runs passed. ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, a test timeout) - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` (N/A) - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` <details> <summary>Agent run details (optional, for reviewers)</summary> `tests/test_free_threading.py`: GIL 3.14.7 10 passed, FT 3.14.7t 10 passed (without coverage); 3.11.13 with coverage, the two cases took 12.4 s and 19.9 s. Lint: pre-commit clean. </details> Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
What do these changes do?
Adds a threaded stress test for the case #1619 left uncovered: one thread re-initializes a shared
MultiDict/CIMultiDict, alternatingd.__init__(pairs)(md_init()then extend) andd.__init__(same_kind_md)(md_clone_from_ht()), with values whose__del__reads the multidict and adds to it. Four other threads run lock-freeget(),getone(),__getitem__,__contains__andlen(), iterateitems()/keys()/values(), and takecopy()snapshots. On free-threaded builds almost every finalizer runs in a reader's drain, not the writer. Every snapshot must hold a prefix of one generation plus"late"tokens, and after twoclear()calls every token must be freed.Under TSan the test found two data races, both fixed here:
md_clone_from_ht()did onememcpy()of the whole source table, header included, so it readnum_readerswhile lock-free readers of the source updated it atomically. On free-threaded builds the copy now skips the reader fields and zeroes them; GIL builds keep the singlememcpy()._md_install_keys()storedmd->is_cion every re-init while lock-free lookups read it inmd_calc_identity(). It now stores only when the value changes. A re-init through the type's own__init__()never changes it.Neither race was seen to crash. The first reads a value that is thrown away and the second writes the value already there, but both are undefined behaviour, and CI's TSan job (
halt_on_error=1) would fail on this test without the fixes.Are there changes in behavior for the user?
No.
Is it a substantial burden for the maintainers to support this?
No. The test runs in about 0.5s on a free-threaded release build.
Related issue number
Follow-up to #1619.
Checklist
CONTRIBUTORS.txt(N/A)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Code (Claude Opus 5.5); reviewed by .
Agent run details (optional, for reviewers)
Each leg used its own venv and its own copy of the tree.
MULTIDICT_DEBUG_BUILD=1: full suite 2867 passed; new test 10/10.tests/test_free_threading.pyat 100% line and branch coverage on FT release, FT debug and 3.10.MULTIDICT_NO_EXTENSIONS=1,--no-c-extensions): 1355 passed.--with-thread-sanitizer,MULTIDICT_DEBUG_BUILD=1 MULTIDICT_TSAN_BUILD=1, clang): new test before the fix gave 199, 300 and 763 reports over three runs (thememcpy()inmd_clone_from_ht()against_md_reader_enter()/_md_reader_exit(), and_md_install_keys()againstmd_calc_identity()). After the fix, 0 over three runs. CI's full TSan command gave 0 reports. Two pure-Python tests,test_pure_python_reciprocal_{view,raw_iterator}_ops_no_deadlock, go past their 20s join under local TSan. They fail the same way on unmodified master and don't touch the C extension.num_active_readersand per-tablenum_readers, freed tables poisoned, and a 20µsPy_BEGIN_ALLOW_THREADS+nanosleep()inside the lock-freeget()/__contains__, the FT debug build aborted on an assert 3/3. Without the sleep, 1 run in 5. These changes were reverted.PYTHONHASHSEED=0: GILctor_*,copy*andupdate+1 to 2 Ir (at most +0.27%, onctor_empty); no other row moved. FTcopy_small+5 Ir (+0.18%),ctor_*+1 Ir.make doc-spelling, pre-commit: pass.