Repository navigation
Replace PyIter_Next() with PyIter_NextItem() in the C extension - #1440
Merged
Merged
Conversation
PyIter_NextItem() reports iterator exhaustion and a propagated error through its return code instead of overloading a NULL result for both, so callers no longer need a separate PyErr_Occurred() check after the loop. The pythoncapi-compat shim already vendored in this repo provides PyIter_NextItem() on Python versions that predate it upstream.
CHANGES/1439.misc.rst was a guess at the next PR number; the PR was actually assigned aio-libs#1440.
asvetlov
marked this pull request as ready for review
September 11, 2026 14:19
asvetlov
enabled auto-merge (squash)
September 11, 2026 14:19
Contributor
Confidence Score: 4/5Merge is blocked because the changed behavior lacks the regression coverage required by the repository. The final scoring set contains one confirmed, repository-rule-linked P2 finding. Files Needing Attention: multidict/_multilib/hashtable.h and the relevant test files need focused iterator exhaustion and iterator-error coverage. Reviews (1): Last reviewed commit: "Rename the news fragment to the assigned..." | Re-trigger Greptile |
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 12, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? First slice of the lock-free read path deferred out of #1438: instead of a critical section, `__contains__` now protects itself with a reader-counted table retirement scheme, and the hash table a lock-free reader might still be walking is kept alive until it's safe to free. Two counters, gated entirely behind `Py_GIL_DISABLED`: - `MultiDictObject.active_readers`: a coarse "some lock-free reader is in flight on this object" gate, bumped before a reader ever dereferences a keys table and dropped once it's done (`_md_reader_enter()`/`_md_reader_exit()`). - `htkeys_t.readers`: a per-table count, advisory only, used purely as a defensive assertion once the coarse gate is already known closed. It is not itself load-bearing for safety: an embedded refcount can't safely announce "about to use this" without a bootstrap hazard, since the increment itself would dereference memory that might already be freed by the time it runs. `_md_retire()`/`_md_drain_retired()`: a resize/shrink/clear no longer frees the outgoing table immediately, only once `active_readers` reads 0 at a point synchronized (`seq_cst` on both the `md->keys` swap and the `active_readers` ops -- anything weaker leaves a real, architecture-dependent race, the same shape as Dekker's algorithm). A table that can't be freed yet moves to a per-object retired list and is freed opportunistically the next time the object resizes. `_md_shrink()` gets a second implementation under `Py_GIL_DISABLED`: the existing one compacts the currently-published table in place, which races a lock-free reader walking the very memory being rewritten. The free-threaded version reuses `_md_resize()` at the current size instead (build a new table, swap, retire the old one), which already has the right shape; the GIL build keeps the original in-place version unchanged. `md_clone_from_ht()` gets a matching fix: it `memcpy`s another live table's header wholesale, which was copying that table's in-flight reader count and retirement link along with everything else. `md_contains()` with `pret == NULL` (`__contains__`'s actual call shape) is the first lock-free consumer: `entry->identity`/`hash` are write-once-at-insertion and never mutated again outside `getall()`'s already-critical-section-only `MD_HASH_MARK` toggling, so this walk needs nothing beyond the table's own lifetime protection -- no atomic entry-field stores or `TryIncRef` machinery required, unlike `get()`'s value read (out of scope here; deferred as its own follow-up). The critical sections around `multidict_sq_contains` and `multidict_keysview_contains` are removed accordingly; view set-algebra callers of `md_contains(pret != NULL)` keep their existing critical sections untouched. Also fixes a small, pre-existing, unrelated bug noticed while rewriting `md_contains()`: `identity` was decref'd once on a match, then decref'd again via `goto fail` if `_md_ensure_key()` failed afterward. Renamed seven helpers in `hashtable.h` (`_md_reader_enter`, `_md_reader_exit`, `_md_retire`, `_md_drain_retired`, `_md_calc_key`, `_md_finder_slot`, `_md_finder_index`) to use the `_md_` prefix the file already uses for internal-only helpers, since none of them have callers outside the file. `getall()` and the view set-algebra methods stay under the critical section: `md_find_next()`/`md_finder_cleanup()` mark visited entries by mutating `entry->hash` in place (`MD_HASH_MARK`), which races any concurrent access to those entries the same way `_md_shrink()`'s in-place compaction did. Fixing that needs moving the visited-tracking to a call-local structure instead of shared entry state -- a self-contained follow-up, not attempted here. `get()`/`getone()`/ `__getitem__` likewise stay locked, needing atomic stores at every entry-mutation site plus `PyUnstable_TryIncRef` on read. ## Are there changes in behavior for the user? No behavior change for single-threaded code or the default GIL build. On the free-threaded build, `__contains__` no longer takes a critical section. ## Is it a substantial burden for the maintainers to support this? Some: this introduces the reclamation scheme the rest of the lock-free read work will build on, so it's more surface than a typical PR, but it's confined to `hashtable.h` and gated entirely behind `Py_GIL_DISABLED`; no behavior change on the GIL build and no new public API. ## Related issue number N/A, no linked issue. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` - [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: `pytest -q` on the default GIL build (1834 passed) and on a free-threaded `3.13.7t` build, both release and `MULTIDICT_DEBUG_BUILD=1` (1829 passed, 5 skipped each), re-verified after each structural change (retirement scheme, `_md_shrink` rewrite, `md_contains` conversion, the rename) and again after rebasing onto master's #1440. Added `test_contains_lock_free_thread_safety`, driving heavy concurrent `add()`/`pop()` churn against concurrent `in` checks specifically to exercise the retire/drain path, not just the (always-safe) case where `active_readers` happens to already be 0 at retirement time. Same honest caveat as on #1438's second regression test: I could not force a crash on a deliberately-unprotected version of `md_contains` by stress-testing it (release build, debug build, a heavier standalone script) -- this allocator doesn't poison freed memory, so a stale read tends to return coherent-looking bytes rather than crash. The race is real by construction (verified by manually disabling the protection and reviewing the resulting code path), just not reliably reproducible empirically in this environment. `make doc-spelling` passes clean (the pre-existing "fallbacks" wordlist gap from #1438 was fixed by #1439, already on master). Drafted with Claude Code (Sonnet 5); reviewed by [email protected]. </details> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What do these changes do?
Replaces every
PyIter_Next()call in the C extension with the newerPyIter_NextItem(). The old API returnsNULLboth when the iteratoris exhausted and when an error propagated, so every call site needed a
follow-up
PyErr_Occurred()check to tell the two apart.PyIter_NextItem()reports that through its own return code (1item,0exhausted,-1error), so the ambiguity is gone. Thepythoncapi_compat.hshim already vendored in this repo backports itfor Python versions that predate the new API upstream.
Are there changes in behavior for the user?
No.
Is it a substantial burden for the maintainers to support this?
No, it is a mechanical internal refactor with no new public surface.
Related issue number
N/A
Checklist
CONTRIBUTORS.txt(N/A: noCONTRIBUTORS.txtin this repo)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Tests:
pytest -q(1831 passed) against the default C-extension build;MULTIDICT_NO_EXTENSIONS=1 pip install -e . --force-reinstall --no-deps+pytest -q --no-c-extensions(925 passed, 905 deselected) for the pure-Python leg, matching the CI matrix invocation.Lint:
pre-commit run clang-format --files multidict/_multilib/views.h multidict/_multilib/hashtable.hpasses; the full commit also went through the repo's standard pre-commit hooks ongit commit.Docs:
make doc-spellingpasses for the content this PR adds. One pre-existing, unrelated spelling failure already exists onmasterinCHANGES.rst(plural "fallbacks" missing from the wordlist) and is untouched by this PR; flagged separately.Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.