Repository navigation
C API fast paths that keep the object representation - #21
Merged
Merged
Conversation
…OS/aarch64 GraalPy's sysconfig set OPT to "-DNDEBUG" only, so C extensions built through it were compiled without optimisation (CPython uses "-DNDEBUG -g -O3 -Wall"). Use "-DNDEBUG -O3" on all platforms except Windows. On darwin-aarch64, build libpythonvm with -H:-RandomizeRuntimeCodeCache. macOS ignores address hints for MAP_JIT mappings, so with the randomisation every runtime-compiled method lands far (hundreds of GB) away from libpythonvm and the C extensions, and Apple cores predict indirect calls across that distance poorly. Without a hint the code cache is mapped next to the (ASLR-slid) libraries. The trade-off is that the code cache loses its own address randomisation on this platform; the flag is not added if the user sets either form of it.
…rint - _PyType_AllocNoTrack allocates with PyObject_Calloc instead of malloc plus memset, and _GraalPyMem_RawCalloc uses calloc for the whole block, so pages of a large object that are never written stay non-resident. - On macOS and Linux, zeroed blocks of 256 KB or more are mapped with mmap and unmapped on free: the system allocator keeps freed large blocks in a cache, and calloc of a reused block zeroes (and so touches) all of it. - The native-memory barrier counts requested bytes. Before forcing a full Java collection, check the resident footprint of the process: if it grew by less than half a barrier since the last collection, allow another barrier's worth of requests (up to the configured maximum). - After a forced collection, wait for the reference handler in short steps (100 us, draining the reference queue) instead of collecting again after fixed delays.
PyDict_Next was an upcall per step. C now keeps a mirror of a dict's entry table: borrowed (key, value) pointers indexed by the storage's iteration position, the same position space as _PyDict_Next. The mirror is built on the second step of a pass and lives in a small direct-mapped cache keyed by the dict pointer. Validity rests on a "Java ran" epoch (CApiEpoch): one native word that Java bumps on entry of every downcall, on exit of every upcall (generated C API wrappers and the closures that go through GilNode.UncachedAcquire) and whenever a thread acquires the GIL. A dict can only change while Java runs, so an unchanged epoch means an unchanged dict. A mirror is refused if the epoch moved while it was filled, and a stale mirror falls back to _PyDict_Next. Entries are promoted before a mirror is built, so the borrowed pointers live as long as the dict holds the entries. GRAALPY_DICT_MIRROR=0 disables the mirror, GRAALPY_DICT_MIRROR=2 checks every mirror hit against _PyDict_Next and reports counts at exit.
C code that calls the ml_meth of a GraalPy builtin (PyCFunctionWrapper) and the lenfunc/hashfunc/inquiry slot wrappers ran uncached nodes on every call. Each wrapper now forwards to one root node of its own (cached argument conversion, argument creation with the builtin's positional and keyword-only defaults, direct call, exception transfer, epoch bump), which the JIT compiles per wrapper so the target is a constant. This also fixes calls through ml_meth of builtins that have keyword-only defaults (e.g. sorted, min, max), which raised "missing keyword-only argument".
- Py_TYPE and Py_REFCNT are inline: a native object or a stub is read directly, tagged ints and floats have fixed types and are immortal. The exported functions stay for the ABI. PyFloat_AS_DOUBLE reads a native float object directly. - PyType_IsSubtype answers PyFloat_Check, and subtype tests against a type whose instance layout differs from its base's, from the tp_base chain instead of the MRO tuple; the MRO walk is kept out of line. - PyThread_get_thread_ident reads the thread id from the thread's native PyThreadState. - Reading the current exception after a downcall does not store anything when C set no exception (the common case). - _PyObject_GetDictPtr is not called for a native object whose type has neither a managed dict nor a tp_dictoffset.
A list's native stub is now a GraalPyVarObject like a tuple's. Its ob_size and ob_item are valid while the list's storage is empty or is native storage attached to that list; otherwise ob_size is -1 and C asks Java. Java keeps the fields current in two places only: PTupleListBase's storage replacement (out of line, only for lists that have a stub) and the length and pointer setters of the attached native storage. With that, PyList_GetItem, PyList_Size, Py_SIZE of a list and PyList_Type's sq_length/mp_length are answered in C, and list.clear's ml_meth is a C function that returns at once for an empty list and calls PyList_Clear otherwise. Every stub now has at least the GraalPyVarObject fields, zeroed. Compiled list append of a list without a stub keeps the code path without the stub sync, so pure-Python appends compile as before.
A range whose bounds are outside the int range but whose values all fit a Java long (e.g. range(2**32, 2**32 + n)) is iterated with longs instead of BigInteger values wrapped in PInt, in the iterator builtins and in the bytecode interpreter's for-loop iteration.
graalpy_list_stub took every pointer with the handle bit as a stub and read its type from the stub memory. Tagged ints and floats also have the handle bit set but are immediates, so PyList_Size(23) or PyList_GetItem(42, 1) dereferenced an invalid address and crashed (test_capi.test_list) instead of raising SystemError. Only pointers whose top three bits are 0b100 are stubs; the other inline list paths (sq_length, mp_length, list.clear) already checked that.
The lenfunc/hashfunc/inquiry slot wrappers each created their own upcall
root node, bound to the language of the context that created the
wrapper. Wrappers of builtin slots hang off static slot objects and are
shared by all contexts, so a context with a different sharing layer
executed a node of another layer ("Invalid sharing of AST nodes
detected", multi-context tests, cpyext test_nb_bool).
The roots are now created once per language and kind
(PythonLanguage.getSlotUpcallCallTarget) and the wrapper is passed as an
argument. The PyCFunctionWrapper roots stay per wrapper: those wrappers
are cached per context (CApiContext) and only that context calls them.
Merging this PR will regress 1 benchmark1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance ChangesTip Investigate this regression by commenting Comparing |
…bject.c The C API library is also built with MSVC, which does not accept __attribute__((noinline)). Py_NO_INLINE (pyport.h) expands to the right form for each compiler.
The fill upcall writes into the slot's entry buffer. Java code run by that upcall can run native code (destructors of released objects) or hand the GIL to another thread; a PyDict_Next there on a dict that maps to the same slot built its own mirror, which could realloc the buffer the outer fill was still writing through, and could leave the slot stamped for the wrong dict. A build now refuses while a fill is in progress and that PyDict_Next takes the Java path. The second fill after growing the buffer and the candidate tracking run inside the same guard.
The epoch bump is a plain read and write. Generated upcall wrappers bump in a finally block that runs after the GIL was released when the builtin runs without the GIL or releases it (e.g. PyEval_SaveThread), and UncachedAcquire.close bumped even when the thread did not own the GIL. Such a delayed store could move the epoch back to a value a mirror was stamped with after the dict changed. Bumps without the GIL are now skipped: no Python object can change without the GIL, and acquiring the GIL bumps.
PyList_GetItem on a list whose stub had no valid ob_size first turned the whole storage into a native PyObject* array and only then checked the index, so an invalid index converted every element (and could fail with MemoryError for a huge list) before raising IndexError. It now asks for the size first and lets the Java path raise IndexError for an invalid index; a valid index still makes the storage native so that further reads stay in C. Adds a cpyext test.
Every native stub was allocated with at least the GraalPyVarObject size (40 bytes) so that PyList_Type's sq_length/mp_length and list.clear could read ob_size without testing the type. That grew the stubs of all other objects: GraalPyObject 24 -> 40 bytes and GraalPyFloatObject 32 -> 40, i.e. one 16-byte allocation class more each (32 -> 48, or 48 -> 64 with the GC header). Stubs have their own size again, and those three C paths test the stub's type (graalpy_list_stub) before reading ob_size.
Two shortcuts answered from the tp_base chain instead of the MRO: one for float (PyFloat_Check) and one for any type whose instance layout differs from its base's. A metaclass mro() may leave out a declared base; CPython then answers false, the chain answered true (e.g. PyFloat_Check on an instance of class F(float, metaclass=M) with M.mro() returning [F, object]). Both shortcuts are removed, so float subclasses and solid bases are looked up in the MRO as before; the MRO walk stays out of line. Adds a cpyext test.
PyMem_RawRealloc of a block that PyMem_RawCalloc had mapped directly allocated a new block of the full new size, copied, and freed the old one. While both existed, the full new size was charged on top of the old block, so even a shrink could trigger collections or hit MaxNativeMemory, and the copy touched every page. A shrink now unmaps the whole pages past the new end in place and uncharges the difference; a growth charges only the growth before moving to a new mapping.
When the requested bytes crossed the barrier and the process footprint had grown by less than half a barrier since the last collection, another barrier's worth of requests was allowed, again at every later crossing up to MaxNativeMemory. The footprint cannot tell resident garbage from freed blocks that the system allocator keeps for reuse: new requests served from that cache leave it flat while the uncollected garbage grows, and the footprint taken after the next collection includes the cache, so each collection raised the baseline (seen on a numpy workload that allocates many large arrays: several deferrals per collection with a flat footprint and a steadily rising baseline). Allow one deferral per collection, so the requested bytes that are not collected yet stay below twice the barrier, and log deferrals at CONFIG level like collections.
A shrinking realloc of a mapped block unmaps the pages past the new end. If that fails, the header and the accounting must keep the old size, or the later free would leave the tail mapped.
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.
C API fast paths that do not change how Python objects are represented. They are the base for #22, which adds native copies of value types; keeping them separate lets the benchmarks show each part on its own.
What this changes
libpythonvmon macOS/aarch64, where calls across a large distance are slow; that part does nothing on Linux.calloc-style allocation instead of allocate-then-clear, large zeroed blocks mapped directly, and the native-memory collection trigger looks at the resident footprint.PyDict_Nextreads a native copy of the entry table instead of calling into Java for every entry. The copy is checked against a counter that changes whenever Java code ran.ml_methfor builtins with keyword-only arguments such assorted,minandmax.Py_TYPE,Py_REFCNT, type checks and the thread identifier for common cases.PyList_GET_SIZE,PyList_GET_ITEMand the list length slots read native data for lists that C has seen.rangewhose values fit 64 bits no longer produces big integers.Known limits
-O3can expose undefined behaviour in extensions that-O0hid./proc/self/statm, which counts file-backed pages, unlike the macOS figure.Py_TYPE/Py_REFCNTpaths assume that native pointers have the top bit clear.Testing
Elide CI on the final commit (Linux x86-64, assertions on): all jobs pass, including the tagged standard-library batches, the C API tests and the multi-context gate. On macOS/aarch64 with assertions: 758 C API tests pass, 9 skipped.
Measured
Two benchmark runs of the final commit against three runs of
developon the benchmark host, median iteration time, geometric mean of the ratios (below 1 is faster):developnumpy-vectorized0.69 s to 0.25 s,pandas-groupby-merge1.90 s to 0.83 s; the other eight package rows are within a few percent.c-upcall-builtin-function5.4 s to 0.13 s,c-dict-iterating8.6 s to 0.39 s,c-instantiate-large6.2 s to 0.92 s,c-upcall4.2 s to 0.65 s.developrun:c-magic-bool, 1.07 s to 1.12 s. No pure Python row is.numpy-vectorized734 MB to 940 MB; no other row grows by more than 10%.binarytrees3; over fourdevelopruns and five runs of this branch its medians overlap (3.23 to 3.67 s against 3.42 to 3.65 s).Review
Eight follow-up commits address an independent review of all nine original commits: a guard against nested builds of the
PyDict_Nextmirror, epoch bumps only while holding the GIL,Py_NO_INLINEinstead of a GCC attribute, an index check beforePyList_GetItemconverts a list's storage,PyType_IsSubtypeanswered from the MRO again, mapped blocks resized without charging the whole new size, at most one deferred native-memory collection per collection (this is the fix for the higher peak memory onnumpy-vectorized; the benchmark run on this commit has to confirm it), and the larger stub layout only for lists and tuples (every other stub had grown by 16 bytes).Known follow-ups, not fixed here: the mirror buffers are not released at shutdown (up to 160 MiB, only with dicts of about a million entries iterated from C); the per-language slot call target cache reads its array without acquire semantics, like the two caches next to it.
Reviewed with sol-loop: 3 rounds with gpt-6.2-sol. Sol verdict: approved
🤖 Generated with Claude Code