Skip to content

Fix key and value refleak when a table resize fails on insert - #1507

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fix-add-for-upd-refleak
Sep 21, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fix-add-for-upd-refleak

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

_md_add_with_hash() and _md_add_for_upd() in hashtable.h incref the identity, key and value and pass them to the *_steal_refs() variants, which return -1 without consuming them when growing the table fails. A MemoryError at that point leaked one reference to each. Both wrappers now release them on failure. A plain Py_DECREF is safe even inside an update batch that otherwise defers decrefs, since the caller still holds its own references and none of the counts can reach zero.

The direct *_steal_refs() callers in md_update_from_dict(), md_update_from_kwnames() and md_update_from_seq() already clean up on failure, so they are unchanged. The pure-Python backend has no manual refcounting and needs no change.

The new test fails the n-th allocation with _testcapi.set_nomemory() for each n until the call succeeds, feeding items one at a time so the table grows mid-insert, and checks the key and value refcounts after every attempt. Without the fix it fails for add, setdefault, __setitem__, update and merge. It is marked c_extension and does not run on the pure-Python leg, because failing allocations inside interpreted code hits CPython's own unraisable-error paths and leaves refs held by a stray traceback.

Are there changes in behavior for the user?

No, apart from the leak being gone.

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

No.

Related issue number

N/A. The same fix is bundled in #1505, which will drop its copy once this lands.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A, internal)
  • 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 (Opus 5); to be reviewed by @asvetlov.

Agent run details (optional, for reviewers)
  • All runs in an isolated venv on CPython 3.13.2, based on upstream master 0a1770c.
  • C extension: pytest tests 2088 passed, 19 skipped.
  • Pure Python (MULTIDICT_NO_EXTENSIONS=1, --no-c-extensions): 1043 passed, 15 skipped, 1048 deselected.
  • MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 with libasan preloaded and PYTHONMALLOC=malloc, -k "not test_leak": 2077 passed, 19 skipped.
  • New test with the C change reverted: 10 of 12 fail (extend passes, it already cleaned up); with the change: 12 passed.
  • Coverage of tests/test_mutable_multidict.py on the C run: 100% lines and branches. The injection arms, calls and disarms on one line so the coverage tracer never sees the failed allocation.
  • Free-threaded build not run; the test skips there since getrefcount is not reliable.
  • pre-commit hooks and make doc-spelling pass.

_md_add_with_hash() and _md_add_for_upd() take new references and hand
them to the *_steal_refs() variants, which return -1 without consuming
them when growing the table fails. Release them on that path, so a
MemoryError from add(), setdefault(), item assignment, update() or
merge() no longer leaks one reference each to the identity, key and
value.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 21, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 21, 2026 17:39
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 21, 2026 17:39
@greptile-apps

greptile-apps Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge: the changed C insertion wrappers correctly clean up references after failed resize operations, and the affected mutation APIs were exercised under forced allocation failures.

What we checked:

  • Executed the standalone native-extension validation script against both MultiDict and CIMultiDict and verified normal update, merge, extend, add, setdefault, and item-assignment behavior across 12 class-and-method combinations. T-Rex
  • Injected allocation failures during the first successful completion for every combination; each failure raised MemoryError and returned key and value reference counts to baseline. T-Rex
  • Ran the focused parametrized regression test, which completed all 12 cases successfully. T-Rex
  • Executed the authored standalone script pr1507-native-resize-refcheck.py and reviewed the pre- and post-failure evidence in logs to confirm MemoryError allocations and clean refcounts. T-Rex
  • Checked the affected implementation regions and confirmed the refcount and ownership handling; noted no security issue. T-Rex

Reviews (1) · Last reviewed commit: "Fix key and value refleak when a table r..."

@codspeed

codspeed Bot commented Sep 21, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 266 untouched benchmarks


Comparing asvetlov:fix-add-for-upd-refleak (5a9f20f) with master (0a1770c)

Open in CodSpeed

@codecov

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0a1770c) to head (5a9f20f).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1507   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           37        37           
  Lines         6128      6160   +32     
  Branches       552       554    +2     
=========================================
+ Hits          6128      6160   +32     
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 6306226 into aio-libs:master Sep 21, 2026
61 checks passed
@asvetlov
asvetlov deleted the fix-add-for-upd-refleak branch September 21, 2026 17:56
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