Skip to content

Fetch list items as new references on free-threaded builds - #1437

Merged
asvetlov merged 7 commits into
aio-libs:masterfrom
rodrigobnogueira:list-item-strong-refs
Sep 20, 2026
Merged

asvetlov merged 7 commits into
aio-libs:masterfrom
rodrigobnogueira:list-item-strong-refs

Conversation

@rodrigobnogueira

@rodrigobnogueira rodrigobnogueira commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Bulk updates from a list and [key, value] in md.items() borrowed items from a list the caller still owns and increfed them in a separate step. On a free-threaded build another thread can drop the item in between, or shrink the list between its length check and the reads, and the C extension reads freed memory.

Each item is now taken as a new reference with PyList_GetItemRef on free-threaded builds, which fetches atomically and locks the list only if its lock-free attempt fails; GIL builds keep the PyList_GET_ITEM macro, so their hot paths are unchanged. Follows #1379, which fixed the stale length in the same loop.

A critical section on the list, as #1433 takes on a dict argument, would not do: it covers neither a [key, value] item inside the list nor the probe handed to in, and it is released whenever the thread detaches, which a key's __hash__ or __eq__ can cause mid-loop. A strong reference per fetch is what actually holds.

Are there changes in behavior for the user?

On free-threaded builds only: a call that finds a list item gone after the list's length was checked now raises RuntimeError("list changed size during iteration"), from update(), a [key, value] item and [key, value] in md.items() alike. A list that is simply shorter by the next iteration of update() still ends the update there, as before (#1379) and as in a plain for loop.

Is it a substantial burden for the maintainers to support this?

No. One helper in hashtable.h, used at three sites.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes -- N/A, no API change
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt -- N/A, no such file
  • Add a new news fragment into the CHANGES/ folder

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 11, 2026
Comment thread tests/test_multidict.py Fixed
@rodrigobnogueira
rodrigobnogueira marked this pull request as ready for review September 11, 2026 03:55
@codspeed

codspeed Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 266 untouched benchmarks


Comparing rodrigobnogueira:list-item-strong-refs (78e6193) with master (7310298)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (7) · Last reviewed commit: "Merge branch 'master' into list-item-str..."

Comment thread multidict/_multilib/hashtable.h Resolved
@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7310298) to head (78e6193).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1437   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           37        37           
  Lines         5851      5934   +83     
  Branches       499       514   +15     
=========================================
+ Hits          5851      5934   +83     
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.

Comment thread multidict/_multilib/hashtable.h Resolved
rodrigobnogueira and others added 6 commits September 14, 2026 00:56
Bulk updates from a list and `[key, value] in md.items()` borrowed items
from a list the caller still owns and increfed them in a separate step.
On a free-threaded build another thread can drop the item in between, or
shrink the list between its length check and the reads. Take each item as
a new reference under the list's lock there; GIL builds keep the macro.

Co-authored-by: Junhyung Lee <[email protected]>
Eight threads probing one multidict trip the finder's marking race on a
debug build, which is a different defect. The list is the shared object
this test is about, so each reader now builds its own multidict.
The GIL path is the old macro again, and the "item gone" checks expand
to nothing there, so GIL builds keep their exact code. The free-threaded
path takes the reference under the list's lock and reports a vanished
item instead of raising.
Reverting only the [key, value] fetch in _md_parse_item left every test
green: both stress tests fed tuples, so that branch only ever ran single
threaded. A builder racing a shrinking two-item list now trips it on the
first run, every run.

The update-from-list test swapped items out of the source list, which on a
four-CPU runner almost never wins the race and, when it does, tends to
corrupt the allocator and hang rather than crash. Shrinking the list and
refilling it fails fast instead, and does so on nearly every run at that
core count.

The changelog now names every entry point that reaches the patched loop,
matching the fragment rendered directly above it. The helper's comment no
longer says the reference is taken under the list's lock: PyList_GetItemRef
tries a lock-free fetch first and locks only if that fails. The bare
`probe in items` becomes an explicit call, which is what the file already
does two hundred lines up, and the one parametrize that passed a list now
passes a tuple like the rest of the tree.
_list_getitem_ref() cleared the IndexError PyList_GetItemRef sets when
the item is gone, and each caller then made something up: update()
stopped as if the list had ended, a [key, value] item reported a bad
length and items.__contains__() answered False.

The item can only be gone because another thread shrank the list after
its length was checked, so say that: the helper turns the IndexError
into RuntimeError("list changed size during iteration"), in the family
of the multidict's own "changed during iteration" error, and all three
callers propagate it.

The per-iteration length check update() re-reads (aio-libs#1379) is untouched:
a list that is simply shorter by the next iteration still ends the
update there, as it does under the GIL and in a plain for loop.
@asvetlov
asvetlov merged commit eaca953 into aio-libs:master Sep 20, 2026
61 checks passed
@asvetlov

Copy link
Copy Markdown
Member

Thanks @rodrigobnogueira

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.

3 participants