Skip to content

Keep lists that C fills in managed storage - #25

Draft
Ivo Horák (horakivo) wants to merge 10 commits into
developfrom
perf/c-built-lists-stay-managed
Draft

Ivo Horák (horakivo) wants to merge 10 commits into
developfrom
perf/c-built-lists-stay-managed

Conversation

@horakivo

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

Copy link
Copy Markdown
Member

Draft, do not merge. Opened to measure the change on the benchmark host.

The problem

On real packages a large part of the run time is garbage collection. Counting what the collector copies shows why: with C extensions that build their results as lists, young collections copy almost everything that was allocated. Bytes copied per byte of young generation are 0.73 to 0.84 on pydantic-json and 0.86 to 1.02 on orjson-roundtrip; the same structures built in Python copy about 0.01.

The cause is what happens to a list that C fills:

  • PyList_New(n) creates a managed list. The first PyList_SET_ITEM replaces its storage with a native array that holds a native reference to every item.
  • Each item is then a strong root in the handle table. It is released only after the list has died, a collection has noticed that, and the reference queue has been drained. So every item survives at least one extra collection, and each level of nesting adds one more.
  • Survivors grow as large as the young generation, overflow into the old generation, and nested lists there need one full collection per nesting level. This is the heap that grows from iteration to iteration on these rows.

pydantic-core (through PyO3) and orjson build their results this way: 305,688 of 305,713 native list storages on pydantic-json and 533,769 of 533,770 on orjson-roundtrip were lists that C was filling.

The change

  • 594dca64: PyList_SET_ITEM and PyList_SetItem into a managed list are stored by Java, which takes over the stolen reference, so the items die with the list. --python.ListSetItemMaterializes=true restores the old behaviour.
  • e6226106: PyList_GetItem leaves a managed list managed. --python.ListGetItemMaterializes=true restores the old behaviour. Small effect on its own.
  • 2b9454bc: counters of the C API object tracking behind --python.CApiGCStats, off by default.
  • 417dca7c: diagnose option sets that switch the two list changes back, so one build can be measured both ways.

No change to GraalVM.

Counted effect (object and byte counts, not times; same image with the options on and off)

Old to new pydantic-json orjson-roundtrip lxml-xpath pandas-str
Strong handle table entries at the end 142 k to 9.6 k 783 k to 721 unchanged unchanged
Bytes copied / young generation bytes 0.77 to 0.73 0.97 to 0.46 0.38 to 0.38 0.40 to 0.40
Full collections 6 to 4 6 to 3 0 to 0 5 to 4

Measured

One benchmark run of this branch against two runs of its base (the commit before it, which is now on develop), median iteration time on the benchmark host:

Row Base This change Peak RSS
orjson-roundtrip 2.93 to 3.06 s 1.63 s 5.4 GB to 0.5 GB
pydantic-json 1.55 to 1.61 s 1.21 s 876 MB to 714 MB
pydantic-models 1.25 to 1.34 s 1.16 s unchanged
other seven package rows within 5% within 10%
  • Real packages overall 0.90, C API micro 0.99, pure Python 1.01 (geometric mean of the ratios).
  • orjson-roundtrip no longer alternates: the last 20 iterations are all between 1.57 and 1.95 s. On the base they alternate between about 0.75 s and 3 to 9.6 s. CodSpeed compares the fastest iteration and therefore reports this row as a regression (0.71 s to 1.57 s); the fastest iterations of the base are the ones in which no collection ran.
  • euler31 (2.47 s to 3.62 s) and fasta3 (1.30 to 1.35 s to 1.45 s) are slower in this run. Both are pure Python rows that have changed speed between builds of the same commit before (euler31 measured 2.47 s and 3.92 s on two builds of the base); the only change here on a pure Python path is a check of a flag that is off.

Known limits and risks

  • An item stored with PyList_SET_ITEM shows a reference count one lower than in CPython. GraalPy already behaves this way for PyList_Append and PyDict_SetItem.
  • Each store into a list that C builds is now a call into Java (about 200 k per iteration on pydantic-json, 415 k on orjson-roundtrip), where it was a write to a native array.
  • With the change, the collection policy chose a smaller young generation on orjson-roundtrip in the counting runs, which gave more young collections. The benchmark run shows whether that matters.
  • pandas-str has the same kind of chain through other holders; this change does not reach it.
  • Two tests asserted the old behaviour and were changed: test_PyList_SET_ITEM (reference count across the store) and test_cycle_with_lists (strong handle table entries).

Testing

C API tests on macOS, release and assertions builds: 758 passed, 9 skipped, the same as the base. Elide CI on this branch (Linux x86-64, assertions on) passes, including the tagged standard-library batches.

🤖 Generated with Claude Code

One line on stderr per reference-queue drain that follows a Java collection,
and after each collection that GraalPy forces: handle-table size and its
strong, weak and dead-weak entries, stubs created, strong/weak flips (and the
flips caused by the drain itself), distinct table cards written, references
drained by kind, native storages created, and forced collections by trigger.
Off by default. Adds the option set capi-stats to codspeed-diagnose.txt.
Since lists' stubs mirror ob_size/ob_item (934689b), PyList_GetItem, and the
PyList_GET_ITEM macro that calls it, made the storage of a list with a
managed storage native on the first valid read, so that later reads stay in
C. A native storage holds a reference to every item. Each item's
handle-table entry therefore stays strong until the list has died, a Java
collection has found it dead and the reference queue has released the
storage; the item survives that collection, and nested lists need one more
collection per level.

Java now answers PyList_GetItem for a list whose storage is managed, as it
did before 934689b. The item is borrowed and the list keeps it alive.
Lists whose storage is already native or empty are still read in C, and
GraalPyList_ITEMS (PySequence_Fast_ITEMS, PyList_SET_ITEM) still makes the
storage native. This reverses only part of 934689b; on pydantic-json and
orjson-roundtrip it removes about 6% and 3% of the conversions of list
storages to native, so its effect on the GC is small. The engine option
--python.ListGetItemMaterializes restores the materialising read.
…in Java

A list that C creates with PyList_New(n) has a managed storage of n
placeholders. The first PyList_SET_ITEM made it a native PyObject* array,
and the array then owned a reference to every item. Each item's
handle-table entry stayed strong until the list had died, a Java
collection had found it dead and the reference queue had released the
storage. So every item that C put into a list it built survived at least
one more Java collection, and each level of nested lists added one more;
items promoted meanwhile needed one full collection per level. pydantic-core
(through PyO3) and orjson build every list they return this way: of the
lists made native in pydantic-json and orjson-roundtrip, all but a handful
are such lists.

For a list whose storage is managed (its stub's ob_item is NULL), C now
calls GraalPyPrivate_List_SetItemSteal, which stores the item in the
managed storage and takes over the stolen reference. The list keeps the
item with a Java reference and both die in the same collection. Lists with
a native storage are written in C as before, and PySequence_Fast_ITEMS
still makes the storage native.

Reference counts: the stolen reference moves to Java, so the stored item's
Py_REFCNT drops by one where CPython's would stay (as it already does for
PyList_Append and PyDict_SetItem into managed storages). When
PyList_SET_ITEM overwrites a real item, the caller receives a new native
reference to it, because callers commonly decref the previous item after
SET_ITEM; PyList_SetItem releases the previous item itself and gets none.
test_PyList_SET_ITEM and test_cycle_with_lists asserted the old counts and
strong handle-table entries; they now check the documented behaviour (no
decref of the previous item, the cycle is freed).

The engine option --python.ListSetItemMaterializes restores the old store.
lists-old and lists-old-gc run with --python.ListSetItemMaterializes and
--python.ListGetItemMaterializes, so that one diagnose run of a build
compares the managed list storage (default, capi-stats) with the native one;
lists-getitem-old restores only the materialising PyList_GetItem.
@horakivo Ivo Horák (horakivo) added the perf:bench Runs walltime bench on our infra label Nov 29, 2026
@codspeed

codspeed Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 11.24%

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

⚡ 7 improved benchmarks
❌ 5 regressed benchmarks
✅ 75 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ packages/orjson-loads[2500] 515.8 ms 1,395.9 ms -63.05%
❌ packages/orjson-roundtrip[2500] 640.4 ms 1,626.5 ms -60.63%
❌ packages/orjson-dumps[2500] 130.1 ms 175.2 ms -25.7%
❌ micro-native/c-many-shortlived-objs[100000000] 24.1 s 29.4 s -18.13%
❌ meso/pidigits 6.2 s 7.4 s -15.89%
⚡ micro-native/c-upcall-builtin-function[67108864] 146.5 ms 114 ms +28.5%
⚡ memory/objects[1000000] 272.7 ms 212.7 ms +28.18%
⚡ packages/pydantic-json[8000] 1.4 s 1.2 s +17.31%
⚡ micro-native/c-call-method[5000000] 476.5 ms 412.7 ms +15.46%
⚡ meso/chaos-sized2[500] 934.9 ms 819.7 ms +14.05%
⚡ meso/fasta3[25000000] 1.4 s 1.2 s +12.86%
⚡ meso/binarytrees3[18] 3.1 s 2.8 s +11.85%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing perf/c-built-lists-stay-managed (b88b2c1) with develop (55fc469)

Open in CodSpeed

…in CApiGCStats

With --python.CApiGCStats the generated upcall wrappers count calls per C
API builtin, printed as one [capi-up] line per [capi-gc] line. Native
objects deallocated in a reference-queue drain are deallocated one at a
time so that the strong-to-weak flips each one causes can be attributed to
its type (tp_name); flips caused by releasing a native sequence storage
are counted separately. PyList_Append, PyList_Insert, PyList_Extend and
PyList_SetSlice count the calls that store into a native list storage.
Nothing changes without the option.
…ava takes it

Storing every PyList_SET_ITEM through Java keeps the items of C-built
lists out of the handle table's strong roots, but costs one upcall per
item. Now PyList_New(n) from C gives the list a native array of n NULLs
again, so C fills it with plain stores. The first time Java resolves the
list pointer (as an argument or result of a C API call, or as an item of
a list being adopted) and every slot is filled, the items' references move
to a managed storage and the native array only waits to be freed: the list
holds its items with Java references and they die together, as before, but
without the per-item upcall. Nested lists that C built the same way are
adopted level by level as their pointers are converted.

A list is not adopted while the cycle GC runs, and never after C took its
item array with PySequence_Fast_ITEMS (GraalPyList_ITEMS sets a flag in the
padding of the stub header), since C may keep that pointer. PyList_SET_ITEM
and PyList_SetItem write a native storage directly instead of going through
GraalPyList_ITEMS, so that they do not set that flag.

The internal option --python.AdoptCBuiltLists=false keeps such lists
managed from the start, with the per-item store through Java.
…erence

Adopting a list from PyList_New only when Java resolves its pointer misses
two common patterns: a list that C hands to its parent (PyDict_SetItem)
before filling it, as orjson's deserializer does, and a list that C builds
and drops without Java ever seeing it. The first stayed native, the
second's items were released one collection late.

C now counts the filled slots of such a list in the padding of its stub
header (GRAALPY_STUB_BUILT_BY_C is set by PyList_New, the count is kept by
PyList_SET_ITEM and PyList_SetItem) and calls GraalPyPrivate_List_Adopt when
the last slot is filled: one call per list instead of one per item. A list
is also adopted when C drops its last reference to it (the strong-to-weak
flip of its handle-table entry). In all cases a list is adopted only when
every slot is filled; one that never becomes full keeps its native storage
as before. --python.AdoptCBuiltLists=false still turns all of this off.
lists-old now also turns off --python.AdoptCBuiltLists, so that it restores
the native list storage, and lists-perstore and lists-perstore-gc run the
per-item store through Java that adoption replaces.
With --python.CApiGCStats, the generated upcall wrappers keep a stack of
the C API builtins in progress, and each Java wrapper created for a native
object is counted by its type and the innermost upcall (or none: a result
of a C function, or an item Java reads), printed as [capi-wrap] lines.
This shows how Java comes to hold native containers such as C-built
tuples. Nothing changes without the option.
…lled

The fill counter called GraalPyPrivate_List_Adopt for every list from
PyList_New as soon as its last slot was filled, so lists that Java would
have adopted for free when it first takes them (PyO3 fills its lists before
handing them over) paid one upcall each. Now Java sets
GRAALPY_STUB_ADOPT_ON_FILL in the stub when an adoption attempt finds empty
slots (C handed the list to its parent before filling it, as orjson does),
and only then does C call GraalPyPrivate_List_Adopt when the last slot is
filled. The fill count moves up one bit to make room for the flag.

Adds to test_c_built_lists: a list handed to a dict and released before it
is filled, lists that only C sees, and a NULL stored over an item and
refilled.
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