Skip to content

Stress re-init with finalizers against lock-free readers - #1621

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:reinit-finalizer-stress
Sep 28, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:reinit-finalizer-stress

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Adds a threaded stress test for the case #1619 left uncovered: one thread re-initializes a shared MultiDict / CIMultiDict, alternating d.__init__(pairs) (md_init() then extend) and d.__init__(same_kind_md) (md_clone_from_ht()), with values whose __del__ reads the multidict and adds to it. Four other threads run lock-free get(), getone(), __getitem__, __contains__ and len(), iterate items() / keys() / values(), and take copy() 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 two clear() calls every token must be freed.

Under TSan the test found two data races, both fixed here:

  • md_clone_from_ht() did one memcpy() of the whole source table, header included, so it read num_readers while 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 single memcpy().
  • _md_install_keys() stored md->is_ci on every re-init while lock-free lookups read it in md_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

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A, no documented behaviour changed)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A)
  • Add a new news fragment into the CHANGES/ folder
  • 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 .

Agent run details (optional, for reviewers)

Each leg used its own venv and its own copy of the tree.

  • FT 3.14.7t release: full suite 2867 passed, 186 skipped; new test about 0.4s per class.
  • FT 3.14.7t MULTIDICT_DEBUG_BUILD=1: full suite 2867 passed; new test 10/10.
  • GIL 3.14.7 and 3.10.17: full suite 2879 passed, 174 skipped; tests/test_free_threading.py at 100% line and branch coverage on FT release, FT debug and 3.10.
  • Pure Python (MULTIDICT_NO_EXTENSIONS=1, --no-c-extensions): 1355 passed.
  • TSan (3.14.7t --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 (the memcpy() in md_clone_from_ht() against _md_reader_enter() / _md_reader_exit(), and _md_install_keys() against md_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.
  • Regression check: with the drain made to ignore num_active_readers and per-table num_readers, freed tables poisoned, and a 20µs Py_BEGIN_ALLOW_THREADS + nanosleep() inside the lock-free get() / __contains__, the FT debug build aborted on an assert 3/3. Without the sleep, 1 run in 5. These changes were reverted.
  • callgrind, PYTHONHASHSEED=0: GIL ctor_*, copy* and update +1 to 2 Ir (at most +0.27%, on ctor_empty); no other row moved. FT copy_small +5 Ir (+0.18%), ctor_* +1 Ir.
  • make doc-spelling, pre-commit: pass.

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__().
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 28, 2026
@codspeed

codspeed Bot commented Sep 28, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 706 untouched benchmarks


Comparing asvetlov:reinit-finalizer-stress (69e636a) with master (e04369b)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 28, 2026 08:49
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 28, 2026 08:49
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[High risk] Fixes data races in multidict initialization under free-threaded Python.

The test-quality issue is non-blocking; it does not make this change unsafe to merge.

Reviews (1) · Last reviewed commit: "Stress re-init with finalizers against l..."

Comment thread tests/test_free_threading.py Resolved
@greptile-apps

greptile-apps Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These 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.

  • P2 Membership-count assertion cannot detect an invalid dictionary ▶

    • Bug
      • At tests/test_free_threading.py:318, the assertion passes for malformed contents as well as valid contents, so it adds lookups without checking the intended state.
    • Cause
      • The sum of 16 Boolean membership results is always at most len(keys), which is 16.
    • Fix
      • Replace the bound with a check of an intended property, such as the expected keys or snapshot contents, while retaining the lookups if they are needed for stress coverage.

@codecov

codecov Bot commented Sep 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (43978bd) to head (69e636a).
⚠️ Report is 2 commits behind head on master.

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     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@asvetlov
asvetlov merged commit 3524c51 into aio-libs:master Sep 28, 2026
84 of 89 checks passed
@asvetlov
asvetlov deleted the reinit-finalizer-stress branch September 28, 2026 09:13
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- 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>
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant