Skip to content

Release a failed dict-literal build's operands and half-built dict - #961

Merged
davidhewitt merged 1 commit into
pydantic:mainfrom
Yi-111-a:fix/718-dict-literal-refcount-leak
Oct 5, 2026
Merged

davidhewitt merged 1 commit into
pydantic:mainfrom
Yi-111-a:fix/718-dict-literal-refcount-leak

Conversation

@Yi-111-a

@Yi-111-a Yi-111-a commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #718

What

VM::build_dict was the one site left in the collection-literal error-path
family from #718. It consumed its operands through a plain into_iter() and
kept 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, 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_set in this same file, Set::from_iterable, and hr_update via
extend_from_entries). This change routes build_dict's operand iterator and
half-built dict through the same defer_drop_mut! / DropGuard pair, so all
four read alike.

Dict::set already releases the failing key and value itself, so the guards
are only responsible for what set never receives: the pairs already folded
into the dict, and the operand tail.

Test

Adds crates/monty/test_cases/refcount__dict_build_failure.py, mirroring the
existing refcount__set_build_failure.py. It covers the dict literal,
dict(pairs), dict(**mapping), and a colliding __eq__ during update —
the four ways a dict build takes ownership of keys and values before an
insertion raises. As a ref-counts fixture it is Monty-only, so the CPython
dual-run skips it, matching the set fixture.

Validation

Built and run locally against main at 3f9d6ef:

  • The new fixture's counts were read out of MontyRun::run_ref_counts rather
    than hand-written. On the unfixed VM the four operand tuples settle at
    3 instead of 1 — one reference inside the half-built dict and one in the
    unreached operand tail — so the fixture fails as intended; with the fix they
    settle at 1 and the strict reachability check reports no unreachable heap
    objects.
  • Under memory-model-checks the same repro aborts on the unfixed VM inside
    Value::drop → vec::IntoIter<Value>::drop → VM::build_dict, which is the
    leak surfacing; it is clean with the fix.
  • cargo test -p monty --features "memory-model-checks test-hooks" — 30 test
    binaries, 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-datatest could not be linked here: this box has no
    libpython3.13.so and no root to install it, so the pyo3-backed harness and
    the 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_counts directly
    instead of from a harness run — same code path, minus the CPython comparison.
  • cargo clippy --workspace -- -D warnings currently fails on three
    pre-existing must_use lints in monty-types, from a clippy newer than the
    one 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_dict where 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 through defer_drop_mut! / DropGuard, matching the other three collection sites from issue #718.

Test

  • Adds a fixture that exercises the four entry paths (dict literal, dict(pairs), dict(**mapping), and a colliding __eq__ during update) and asserts the operand refcounts settle at 1.

Written for commit 6d65ffa. Summary will update on new commits.

Review in cubic

`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.
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown

Branch diff: fix/718-dict-literal-refcount-leak

Commit Message Production Test Other
6d65ffa Release a failed dict-literal… +18 -9 +65 -0 +0 -0
TOTAL +18 -9 +65 -0 +0 -0

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}

@cubic-dev-ai cubic-dev-ai Bot Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Fix with cubic

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})

@cubic-dev-ai cubic-dev-ai Bot Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Fix with cubic

@codecov

codecov Bot commented Oct 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 45 untouched benchmarks
⏩ 16 skipped benchmarks1


Comparing Yi-111-a:fix/718-dict-literal-refcount-leak (6d65ffa) with main (3f9d6ef)

Open in CodSpeed

Footnotes

  1. 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@davidhewitt davidhewitt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@davidhewitt
davidhewitt merged commit 88f05e8 into pydantic:main Oct 5, 2026
47 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Collection construction/update leaks partial-container refcounts on an unhashable element

2 participants