Skip to content

Fix three reference leaks in the C API layer - #20

Merged
Ivo Horák (horakivo) merged 5 commits into
developfrom
fix/capi-reference-leaks
Nov 28, 2026
Merged

Ivo Horák (horakivo) merged 5 commits into
developfrom
fix/capi-reference-leaks

Conversation

@horakivo

@horakivo Ivo Horák (horakivo) commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Fixes three reference leaks in GraalPy's C API layer. Each one is a missing release that leaves an object's reference count above MANAGED_REFCNT, so its handle table reference stays strong and the object, with everything it references, is kept until the process ends. No collection can free it.

Commit Where What leaked Seen with
PyUnicode_Decode unicodeobject.c the temporary memoryview of every call with an explicit encoding pandas' CSV parser, lxml
PyObject_GC_Del gcmodule.c the instance __dict__ of a Python subclass of a native type pandas string operations
orjson patches orjson-3.12.0.patch, orjson-3.13.0.patch every dict key created by orjson.loads orjson

All three are present in upstream master as well.

Effect on the heap

Heap after a full collection, first and last of 30 iterations of the package benchmarks, with a collection after each iteration. Measured on macOS arm64 with a native standalone:

Benchmark Before After
orjson-roundtrip 184 → 3355 MB 97 → 201 MB
pandas-str 179 → 1256 MB 158 → 163 MB
pandas-csv 283 → 2377 MB 151 → 149 MB
lxml-xpath 66 → 700 MB 46 → 43 MB
pydantic-json about 94 MB unchanged

Without a collection between iterations, which is how the benchmarks run, orjson-roundtrip still grows (97 → 1154 MB instead of 133 → 3866 MB). That remainder is not a leak: the items of a list created by C are released one nesting level per full collection. It is not addressed here.

Tests

  • One new test in test_gc.py for the instance dict. It checks reference counts inside a single C call, so it does not depend on a collection. It fails without the fix ("the instance dict lost 0 references on dealloc, expected 1") and passes with it; verified on macOS builds.
  • The C API tests passed locally with the three fixes: 759 passed, 9 skipped, none failed.
  • Both orjson patch files apply to the published orjson 3.12.0 and 3.13.0 sources with GNU patch 2.8 and with BSD patch.

Measured on the benchmark runner

One run before and one after, package benchmarks, median of the measured iterations and peak memory:

Benchmark Median Peak memory
lxml-xpath 3.60 → 1.82 s 1.7 → 0.5 GB
pandas-csv 2.52 → 1.80 s 5.6 → 0.8 GB
pandas-str 1.03 → 1.05 s 3.5 → 0.8 GB
orjson-roundtrip 3.46 → 2.98 s 13.3 → 6.0 GB

CodSpeed compares the fastest iteration of each benchmark and flags pandas-csv, pandas-str and pydantic-json as slower by that measure. Before this change, an iteration without a collection skipped the release work entirely. A pure Python benchmark that this change cannot affect (meso/pidigits) moved by 18% between the two builds as well, so differences of that size between single runs are not reliable.

Reviewed with sol-loop: 2 rounds with gpt-6.2-sol. Sol verdict: approved

🤖 Generated with Claude Code

The temporary memoryview passed to GraalPyPrivate_Unicode_Decode is a borrowed argument and was never released, so each call leaked the memoryview and its native stub. Extensions that decode many small strings this way, such as pandas' CSV parser and lxml, kept growing the heap until the process ended.
A Python subclass of a native type inherits the native base's tp_dealloc and does not get subtype_dealloc, and PyObject_ClearManagedDict is a no-op on GraalPy. The instance __dict__ kept in the pre-header was therefore never released: its reference count stayed above MANAGED_REFCNT, its handle table reference stayed strong, and the dict and everything reachable from it were never collected. Release it in PyObject_GC_Del, the last point where that is possible.

Adds regression tests to test_gc.py.
On GraalPy get_unicode_key returns a new reference, because there is no key cache, and PyDict_SetItem takes its own references. The patched reverse_pydict_incref released only the value, so every key created by orjson.loads kept a reference count above MANAGED_REFCNT and was never collected. Applies to the patches for orjson 3.12.0 and 3.13.0.
@horakivo Ivo Horák (horakivo) added the perf:bench Runs walltime bench on our infra label Nov 27, 2026
The previous tests asserted only when RELY_ON_GC is set, so they passed with the leak present. One test now allocates an instance of a Python subclass of a native type in C, gives it a dict, drops the only reference and checks that the deallocation released exactly one reference to the dict. Also corrects the comment in PyObject_GC_Del: a dict subclass with native backing can run its tp_dealloc there.
GNU patch 2.8 rejected the changed hunk for src/ffi/pydictref.rs: with nine lines of leading and three of trailing context it takes the hunk to be anchored at the end of the file. BSD patch and git apply accepted it. The hunks are regenerated with diff -u; the patched sources are unchanged.
@codspeed

codspeed Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 44.38%

1 warning

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚡ 1 improved benchmark
✅ 55 untouched benchmarks
🆕 10 new benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ meso/euler31[200] 3.6 s 2.5 s +44.38%
🆕 packages/numpy-small-ops[600] N/A 551.8 ms N/A
🆕 packages/numpy-vectorized[4000000] N/A 676.8 ms N/A
🆕 packages/pandas-apply[20000] N/A 1.1 s N/A
🆕 packages/pydantic-json[8000] N/A 1.6 s N/A
🆕 packages/pydantic-models[10000] N/A 1.3 s N/A
🆕 packages/lxml-xpath[2500] N/A 1.8 s N/A
🆕 packages/orjson-roundtrip[2500] N/A 718.9 ms N/A
🆕 packages/pandas-csv[50000] N/A 1.7 s N/A
🆕 packages/pandas-groupby-merge[150000] N/A 868.2 ms N/A
🆕 packages/pandas-str[20000] N/A 919.9 ms N/A

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/capi-reference-leaks (5f9cb41) with develop (17ac452)1

Open in CodSpeed

Footnotes

  1. No successful run was found on develop (1df9f22) during the generation of this report, so 17ac452 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@horakivo
Ivo Horák (horakivo) changed the base branch from ci/codspeed-packages to develop November 27, 2026 23:33
@horakivo
Ivo Horák (horakivo) merged commit 2fd8b45 into develop Nov 28, 2026
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:bench Runs walltime bench on our infra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant