Skip to content

C API fast paths that keep the object representation - #21

Merged
Ivo Horák (horakivo) merged 18 commits into
developfrom
perf/capi-fast-paths
Nov 29, 2026
Merged

Ivo Horák (horakivo) merged 18 commits into
developfrom
perf/capi-fast-paths

Conversation

@horakivo

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

Copy link
Copy Markdown
Member

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

Commit Change
Build C extensions with -O3 Extensions were compiled without optimisation. Also keeps JIT-compiled code near libpythonvm on macOS/aarch64, where calls across a large distance are slow; that part does nothing on Linux.
Allocate zeroed native memory lazily calloc-style allocation instead of allocate-then-clear, large zeroed blocks mapped directly, and the native-memory collection trigger looks at the resident footprint.
Mirror dict entry tables in C PyDict_Next reads 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.
Compiled roots for C calls of builtins and simple slots One compiled entry point per wrapped builtin method and per slot kind, with cached argument conversion. Also fixes C calls of ml_meth for builtins with keyword-only arguments such as sorted, min and max.
Answer frequent C API queries without entering Java Py_TYPE, Py_REFCNT, type checks and the thread identifier for common cases.
Keep list size and items readable from C PyList_GET_SIZE, PyList_GET_ITEM and the list length slots read native data for lists that C has seen.
Iterate big ranges with Java longs A range whose values fit 64 bits no longer produces big integers.

Known limits

  • -O3 can expose undefined behaviour in extensions that -O0 hid.
  • On Linux the footprint check reads /proc/self/statm, which counts file-backed pages, unlike the macOS figure.
  • The inline Py_TYPE/Py_REFCNT paths 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 develop on the benchmark host, median iteration time, geometric mean of the ratios (below 1 is faster):

Suite Rows This change / develop
Real packages 10 0.82
C API micro 23 0.52
Pure Python 33 1.00
  • numpy-vectorized 0.69 s to 0.25 s, pandas-groupby-merge 1.90 s to 0.83 s; the other eight package rows are within a few percent.
  • c-upcall-builtin-function 5.4 s to 0.13 s, c-dict-iterating 8.6 s to 0.39 s, c-instantiate-large 6.2 s to 0.92 s, c-upcall 4.2 s to 0.65 s.
  • Slower in both runs than in every develop run: c-magic-bool, 1.07 s to 1.12 s. No pure Python row is.
  • Peak RSS: numpy-vectorized 734 MB to 940 MB; no other row grows by more than 10%.
  • CodSpeed compares the fastest iteration of single runs and flagged binarytrees3; over four develop runs 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_Next mirror, epoch bumps only while holding the GIL, Py_NO_INLINE instead of a GCC attribute, an index check before PyList_GetItem converts a list's storage, PyType_IsSubtype answered 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 on numpy-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

…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.
@datadog-official

datadog-official Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Pipelines

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: bda697c | Docs | Give us feedback!

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.
@codspeed

codspeed Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

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

⚡ 16 improved benchmarks
❌ 1 regressed benchmark
✅ 49 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ meso/binarytrees3[18] 3.1 s 3.5 s -11.94%
⚡ micro-native/c-upcall-builtin-function[67108864] 5,399.4 ms 131.2 ms ×41
⚡ micro-native/c-dict-iterating[50000000] 8,578.4 ms 387.7 ms ×22
⚡ micro-native/c-upcall-slot[1048576] 28.1 ms 1.8 ms ×16
⚡ micro-native/c-instantiate-large[1000] 6,144.1 ms 908.7 ms ×6.8
⚡ micro-native/c-upcall[268435456] 4,165.9 ms 651.3 ms ×6.4
⚡ packages/numpy-vectorized[4000000] 673.6 ms 240.1 ms ×2.8
⚡ micro-native/c-call-method-o[5000000] 110.4 ms 70.2 ms +57.34%
⚡ micro-native/c-call-method-noargs[5000000] 101.9 ms 66.7 ms +52.74%
⚡ micro-native/c-call-method-fastcall[5000000] 139.5 ms 95.5 ms +46.05%
⚡ micro-native/c-call-method[5000000] 505.4 ms 407.7 ms +23.97%
⚡ micro-native/c-call-method-varargs[5000000] 352.3 ms 292.5 ms +20.43%
⚡ micro-native/c-many-shortlived-objs[100000000] 29.8 s 26 s +14.6%
⚡ packages/pandas-groupby-merge[150000] 867.7 ms 765.1 ms +13.4%
⚡ micro-native/c-call-method-obj-args[5000000] 58.7 ms 52.2 ms +12.48%
⚡ micro-native/c-call-method-int-float[5000000] 98.2 ms 87.4 ms +12.44%
⚡ micro-native/c-call-classmethod[50000000] 2.7 s 2.5 s +11.06%

Tip

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


Comparing perf/capi-fast-paths (bda697c) with develop (2fd8b45)

Open in CodSpeed

…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.
@horakivo
Ivo Horák (horakivo) marked this pull request as ready for review November 29, 2026 00:55
@horakivo
Ivo Horák (horakivo) merged commit 65cb049 into develop Nov 29, 2026
38 of 39 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