Skip to content

Replace PyIter_Next() with PyIter_NextItem() in the C extension - #1440

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:pyiter-nextitem
Sep 11, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:pyiter-nextitem

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Replaces every PyIter_Next() call in the C extension with the newer
PyIter_NextItem(). The old API returns NULL both when the iterator
is 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 (1 item,
0 exhausted, -1 error), so the ambiguity is gone. The
pythoncapi_compat.h shim already vendored in this repo backports it
for 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

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A: no CONTRIBUTORS.txt in this repo)
  • 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
Agent 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.h passes; the full commit also went through the repo's standard pre-commit hooks on git commit.

Docs: make doc-spelling passes for the content this PR adds. One pre-existing, unrelated spelling failure already exists on master in CHANGES.rst (plural "fallbacks" missing from the wordlist) and is untouched by this PR; flagged separately.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 11, 2026
CHANGES/1439.misc.rst was a guess at the next PR number; the PR was
actually assigned aio-libs#1440.
@codspeed

codspeed Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing asvetlov:pyiter-nextitem (c1f6136) with master (286a6f8)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 11, 2026 14:19
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 11, 2026 14:19
@asvetlov
asvetlov enabled auto-merge (squash) September 11, 2026 14:19
@greptile-apps

greptile-apps Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5

Merge 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

Comment thread multidict/_multilib/hashtable.h Resolved
@asvetlov
asvetlov merged commit 88a0a85 into aio-libs:master Sep 11, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the pyiter-nextitem branch September 11, 2026 14:48
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]>
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