Repository navigation
Hold refs across lower() when copying keys from another source - #1582
Merged
Merged
Conversation
A str subclass key's lower() runs Python code that can clear or grow the source. md_update_from_ht() kept pointers into the source's entry table across it on the cross-type path, and md_update_from_dict() held only a borrowed reference to the value, so both read freed memory. Fixes aio-libs#1581
asvetlov
marked this pull request as ready for review
September 25, 2026 12:03
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1582 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 41 41
Lines 7689 7739 +50
Branches 643 648 +5
=========================================
+ Hits 7689 7739 +50
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:
|
Contributor
|
This comment has been minimized.
This comment has been minimized.
merge() drops the key and value for a key the target already has, so releasing them can run a finalizer that replaces the source's table. Reload the entry pointer after the releases instead of after lower().
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 26, 2026
#1598) <!-- Thank you for your contribution! --> ## What do these changes do? Since #1582, `md_update_from_dict()` takes its own reference to every key and value, because a `str` subclass key's `lower()` can run Python code that clears the source dict. That can only happen when the target is a `CIMultiDict` and the key is a `str` subclass other than `istr`. Every other key goes through code that runs no Python, so the dict keeps both alive and the borrowed references are enough. The loop now takes references only in that one case; `extend()` still takes them, since it moves them into the table. The `lower()` call itself, together with the `TypeError` for a non-`str` key, moves out of `_ci_str_to_identity()` into a `COLD` helper. The ASCII exact-`str` path stays inline, and every `CIMultiDict` lookup gets a little cheaper. Instructions per operation (Callgrind, `benchmarks/callgrind_driver.py`): | operation | build | `MultiDict` | `CIMultiDict` | |---|---|---:|---:| | `update` | GIL | 39,230 -> 36,613 (-6.7%) | 45,154 -> 42,661 (-5.5%) | | `update` | free-threaded | 49,260 -> 44,748 (-9.2%) | 55,060 -> 50,640 (-8.0%) | | `getitem_hit` | GIL | 148 (flat) | 209 -> 201 (-3.8%) | | `contains_hit` | GIL | 134 (flat) | 196 -> 188 (-4.1%) | | `ctor_items` | GIL | 46,832 (flat) | 59,324 -> 57,733 (-2.7%) | The pure-Python implementation holds references by construction and needs no change. ## Are there changes in behavior for the user? No, only faster `update()`, `merge()` and `CIMultiDict` key lookups. ## Is it a substantial burden for the maintainers to support this? No. The condition is one line, next to the comment explaining it. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist (the existing `test_key_lower_mutates_source` cases from #1582 cover the path that still takes references) - [x] Documentation reflects the changes (N/A, internal only) - [ ] 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); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> Tests: - C extension, 3.14.7: 2790 passed, 170 skipped - C extension, 3.14.7t: 2777 passed, 183 skipped - C extension, 3.10.17: 2790 passed, 170 skipped - Pure Python, 3.14.7 (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`): 1320 passed, 17 skipped - ASan + UBSan, 3.14.7 (`MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 MULTIDICT_NO_FREELIST=1`, `PYTHONMALLOC=malloc`, `-k "not test_leak and not test_freed_blocks_are_reused"`): 2778 passed, 170 skipped Lint: pre-commit hooks pass. `make doc-spelling` passes. Callgrind rows not listed moved less than 1%. Wall clock was measured only together with two sibling PRs (the version counter and the inlining annotations): an interleaved pyperf A/B, 3 rounds, pinned P-cores, `dict` as a flat control, gave `update` -5.4% GIL and -17.2% free-threaded on `MultiDict`, and -4.8% / -22.1% on `CIMultiDict`. Not tested: musl, macOS, Windows and Android builds. </details>
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?
A
strsubclass key'slower()runs Python code that can clear or grow the source while aCIMultiDictcopies keys out of it. On the cross-type path,md_update_from_ht()kept pointers into the source's entry table across that call, andmd_update_from_dict()held only a borrowed reference to the value, so both read freed memory.The cross-type loop now holds its own references to the key and value while computing the identity, then reloads the entry table and clamps the entry count. The dict loop increfs the value alongside the key and passes that reference on to
md_add_with_hash_steal_refs()instead of taking a second one. The same-type path runs no Python code and is unchanged. The pure-Python implementation is not affected.Are there changes in behavior for the user?
No, apart from the crash being gone.
Is it a substantial burden for the maintainers to support this?
No.
Related issue number
Fixes #1581
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 @asvetlov.
Agent run details (optional, for reviewers)
Tests:
MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 MULTIDICT_NO_FREELIST=1,PYTHONMALLOC=malloc,-k "not test_leak and not test_freed_blocks_are_reused"): 2733 passed, 167 skipped. Without the fix, all 8test_key_lower_mutates_sourcec-cases report heap-use-after-free (md_update_from_htatbulk_update.h:364for multidict sources;md_update_from_dict/md_add_for_updfor dict sources), andtest_value_finalizer_mutates_source[c-multidict]does on the first commit alone (bulk_update.h:352).MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions): 1298 passed, 11 skipped.make doc-spellingand pre-commit on the changed files: pass.Callgrind, release build,
PYTHONHASHSEED=0, 16 string keys, instructions per operation (2000-iteration run minus an empty run):MultiDict(md)(same type)CIMultiDict(ci)(same type)CIMultiDict(md)MultiDict(ci)ci.update(md)MultiDict(dict)CIMultiDict(dict)md.extend(dict)ci.extend(dict)md.update(dict)ci.update(dict)The cross-type cost is one extra incref/decref pair per entry (about 28 Ir per entry on GIL, 49 on free-threaded). The extend and constructor dict paths are flat because the value reference is now moved into the table instead of taken twice.