Repository navigation
Keep lists that C fills in managed storage - #25
Draft
Ivo Horák (horakivo) wants to merge 10 commits into
Draft
Ivo Horák (horakivo) wants to merge 10 commits into
Ivo Horák (horakivo) wants to merge 10 commits into
Conversation
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.
Merging this PR will degrade performance by 11.24%1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing |
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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-jsonand 0.86 to 1.02 onorjson-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 firstPyList_SET_ITEMreplaces its storage with a native array that holds a native reference to every item.pydantic-core (through PyO3) and orjson build their results this way: 305,688 of 305,713 native list storages on
pydantic-jsonand 533,769 of 533,770 onorjson-roundtripwere lists that C was filling.The change
594dca64:PyList_SET_ITEMandPyList_SetIteminto a managed list are stored by Java, which takes over the stolen reference, so the items die with the list.--python.ListSetItemMaterializes=truerestores the old behaviour.e6226106:PyList_GetItemleaves a managed list managed.--python.ListGetItemMaterializes=truerestores 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)
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:orjson-roundtrippydantic-jsonpydantic-modelsorjson-roundtripno 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) andfasta3(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 (euler31measured 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
PyList_SET_ITEMshows a reference count one lower than in CPython. GraalPy already behaves this way forPyList_AppendandPyDict_SetItem.pydantic-json, 415 k onorjson-roundtrip), where it was a write to a native array.orjson-roundtripin the counting runs, which gave more young collections. The benchmark run shows whether that matters.pandas-strhas the same kind of chain through other holders; this change does not reach it.test_PyList_SET_ITEM(reference count across the store) andtest_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