Repository navigation
Release a failed dict-literal build's operands and half-built dict - #961
Conversation
`build_dict` consumed its operands through a plain `into_iter()` and held the half-built `Dict` in a plain local, so an insertion that raises — an unhashable key, or a colliding `__eq__` — dropped both by ordinary Rust drop instead of `drop_with`. The reference counts of every heap value already inserted, plus every pair the loop never reached, stayed elevated forever. `build_set`, `Set::from_iterable` and `hr_update` already carry the guard pattern for exactly this; `build_dict` was the remaining site in the family reported in pydantic#718. Route both the operand iterator and the half-built dict through `defer_drop_mut!` / `DropGuard`, matching `build_set` in this file. `Dict::set` already releases the failing key and value itself, so the guards are only responsible for what it never receives. Adds `refcount__dict_build_failure.py`, mirroring the existing `refcount__set_build_failure.py`, covering the dict literal, `dict(pairs)`, `dict(**mapping)` and a colliding `__eq__` during `update`. On the unfixed VM the four operand tuples settle at 3 rather than 1; with the fix they settle at 1 and the strict reachability check reports no unreachable heap objects.
Branch diff:
|
| Commit | Message | Production | Test | Other |
|---|---|---|---|---|
| 6d65ffa | Release a failed dict-literal… | +18 -9 | +65 -0 | +0 -0 |
| TOTAL | +18 -9 | +65 -0 | +0 -0 |
There was a problem hiding this comment.
2 issues found across 2 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="crates/monty/test_cases/refcount__dict_build_failure.py">
<violation number="1" location="crates/monty/test_cases/refcount__dict_build_failure.py:31">
P2: This case never reaches `dict(**mapping)`: the nested dict literal raises before `dict` is called, and the fixture has no `{**mapping}` failure case. Add a real mapping-source test for `dict(**mapping)` and a separate `{**mapping}` test so the new cleanup paths are actually covered.</violation>
<violation number="2" location="crates/monty/test_cases/refcount__dict_build_failure.py:65">
P2: Add an unapplied heap value such as `[2]` before the final ref-count marker. This gives `memory-model-checks` a heap-backed `Value::Ref` to validate on teardown instead of relying only on named values and the optional ref-count-return check.</violation>
</file>
Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.
Fix all with cubic | Re-trigger cubic
|
|
||
| assert len(target) == 1 | ||
| assert len(source) == 2 | ||
| # ref-counts={'first_key': 1, 'first_value': 1, 'last_key': 1, 'last_value': 1, 'unhashable': 1, 'Tripwire': 2, 'Colliding': 3, 'source_first': 2, 'source_last': 2, 'source': 1, 'target': 1} |
There was a problem hiding this comment.
P2: Add an unapplied heap value such as [2] before the final ref-count marker. This gives memory-model-checks a heap-backed Value::Ref to validate on teardown instead of relying only on named values and the optional ref-count-return check.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/test_cases/refcount__dict_build_failure.py, line 65:
<comment>Add an unapplied heap value such as `[2]` before the final ref-count marker. This gives `memory-model-checks` a heap-backed `Value::Ref` to validate on teardown instead of relying only on named values and the optional ref-count-return check.</comment>
<file context>
@@ -0,0 +1,65 @@
+
+assert len(target) == 1
+assert len(source) == 2
+# ref-counts={'first_key': 1, 'first_value': 1, 'last_key': 1, 'last_value': 1, 'unhashable': 1, 'Tripwire': 2, 'Colliding': 3, 'source_first': 2, 'source_last': 2, 'source': 1, 'target': 1}
</file context>
| assert str(e) == "cannot use 'list' as a dict key (unhashable type: 'list')" | ||
|
|
||
| try: | ||
| dict(**{first_key: first_value, unhashable: 1, last_key: last_value}) |
There was a problem hiding this comment.
P2: This case never reaches dict(**mapping): the nested dict literal raises before dict is called, and the fixture has no {**mapping} failure case. Add a real mapping-source test for dict(**mapping) and a separate {**mapping} test so the new cleanup paths are actually covered.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/test_cases/refcount__dict_build_failure.py, line 31:
<comment>This case never reaches `dict(**mapping)`: the nested dict literal raises before `dict` is called, and the fixture has no `{**mapping}` failure case. Add a real mapping-source test for `dict(**mapping)` and a separate `{**mapping}` test so the new cleanup paths are actually covered.</comment>
<file context>
@@ -0,0 +1,65 @@
+ assert str(e) == "cannot use 'list' as a dict key (unhashable type: 'list')"
+
+try:
+ dict(**{first_key: first_value, unhashable: 1, last_key: last_value})
+ assert False, 'dict(**mapping) should reject the list key'
+except TypeError as e:
</file context>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Merging this PR will not alter performance
Comparing Footnotes
|
Closes #718
What
VM::build_dictwas the one site left in the collection-literal error-pathfamily from #718. It consumed its operands through a plain
into_iter()andkept the half-built
Dictin a plain local, so an insertion that raises — anunhashable key, or a colliding
__eq__— dropped both by ordinary Rust dropinstead of
drop_with. The reference counts of every heap value alreadyinserted, and of every pair the loop never reached, stayed elevated for the
rest of the run.
The other three sites named in that report already carry the guard pattern
(
build_setin this same file,Set::from_iterable, andhr_updateviaextend_from_entries). This change routesbuild_dict's operand iterator andhalf-built dict through the same
defer_drop_mut!/DropGuardpair, so allfour read alike.
Dict::setalready releases the failing key and value itself, so the guardsare only responsible for what
setnever receives: the pairs already foldedinto the dict, and the operand tail.
Test
Adds
crates/monty/test_cases/refcount__dict_build_failure.py, mirroring theexisting
refcount__set_build_failure.py. It covers the dict literal,dict(pairs),dict(**mapping), and a colliding__eq__duringupdate—the four ways a dict build takes ownership of keys and values before an
insertion raises. As a
ref-countsfixture it is Monty-only, so the CPythondual-run skips it, matching the set fixture.
Validation
Built and run locally against
mainat3f9d6ef:MontyRun::run_ref_countsratherthan hand-written. On the unfixed VM the four operand tuples settle at
3instead of1— one reference inside the half-built dict and one in theunreached operand tail — so the fixture fails as intended; with the fix they
settle at
1and the strict reachability check reports no unreachable heapobjects.
memory-model-checksthe same repro aborts on the unfixed VM insideValue::drop→vec::IntoIter<Value>::drop→VM::build_dict, which is theleak surfacing; it is clean with the fix.
cargo test -p monty --features "memory-model-checks test-hooks"— 30 testbinaries, all passing, no failures.
cargo clippy -p monty --features "memory-model-checks test-hooks" --lib—clean, no warnings in
vm/collections.rs.cargo +nightly fmt --check -p monty— clean.Two environment notes, neither caused by this branch:
monty-datatestcould not be linked here: this box has nolibpython3.13.soand no root to install it, so the pyo3-backed harness andthe two test targets that pull it in (
abort,binary_serde) do not build.That is why the fixture's numbers were taken from
run_ref_countsdirectlyinstead of from a harness run — same code path, minus the CPython comparison.
cargo clippy --workspace -- -D warningscurrently fails on threepre-existing
must_uselints inmonty-types, from a clippy newer than theone on this box. Unrelated to this change; left alone.
AI assistance was used to prepare this change.
Summary by cubic
Fixes a reference-count leak in
build_dictwhere raising during an insertion (unhashable key or colliding__eq__) left the operand tail and half-built dict with elevated refcounts. Operands and the dict now travel throughdefer_drop_mut!/DropGuard, matching the other three collection sites from issue #718.Test
dict(pairs),dict(**mapping), and a colliding__eq__duringupdate) and asserts the operand refcounts settle at 1.Written for commit 6d65ffa. Summary will update on new commits.