Skip to content

Native copies of int, float, complex and str for C extensions - #22

Draft
Ivo Horák (horakivo) wants to merge 7 commits into
perf/capi-fast-pathsfrom
perf/native-value-copies
Draft

Ivo Horák (horakivo) wants to merge 7 commits into
perf/capi-fast-pathsfrom
perf/native-value-copies

Conversation

@horakivo

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

Copy link
Copy Markdown
Member

Draft, do not merge. Stacked on #21 (the C API fast paths that do not change object representation); review that one first. This PR only adds the two commits on top.

What this changes

Today every Python value that crosses into C gets a Java wrapper plus a native stub (and a handle-table entry), and C reads most of its fields through upcalls into Java. This branch copies simple value types into native CPython-layout structs when C needs them, so C reads them directly, and does not create stubs for them.

Complex, int and float (commit 1)

  • Shared native state. One native block holds allocators that C and Java both use without upcalls, a borrowed-reference stack and a downcall depth counter. Generated downcall invokers (and vectorcall slot calls) enter and leave the depth; when the outermost downcall returns, the counts on the borrowed stack are dropped.
  • complex. An exact complex crosses as a native PyComplexObject from a size-class allocator. Lists of exact complex values store counted pointers to these structs; PComplex keeps an unowned pointer and serial so that a value read from such a list stays the same object.
  • int. An exact int that does not fit GraalPy's tagged pointer (up to 120 bits) crosses as a native PyLongObject with no Java companion; PyLong_From*/PyLong_As* handle these in C.
  • float. An exact float that cannot be tagged crosses as a PyFloatObject from a 64-byte small-block pool shared by PyObject_Malloc and Java. Instances of static native float subclasses that are only (type, ob_fval) are held in Java as value copies.
  • Items that a container holds (dict and list items, PyDict_Next) are still promoted to objects with stable stubs, as before.

str (commit 2)

  • An exact str that is a bare Java string crosses as a CPython 3.13 compact unicode object in malloc'd memory (no wrapper, no stub, no handle). PyUnicode_GET_LENGTH/KIND/DATA/READ and PyUnicode_AsUTF8AndSize run in C; hash, compare and equality have C paths.
  • Strings created by C (PyUnicode_New, PyUnicode_FromStringAndSize, the UTF-8 decoders for valid input, ...) are born in that layout and become Java strings only when Java reads them. PyUnicode_Resize is implemented.
  • Java reads every native str struct as one str object, remembered in a small ring (the 4096 most recently converted strings), so a str that C creates and stores into a container keeps its identity. A bare str passed to C and handed straight back is an equal new object.
  • str subclasses, interned strings and strings that already have a stub keep the existing path. GRAALPY_NATIVE_STR=0 turns the scheme off.

Lifetime rule (both commits)

C's reference count owns a copy. A copy passed as an argument or returned as a new reference also holds one count until the outermost C call returns; C that increfs it keeps it.

Known problems

  • Copies live only until the outermost C call returns. A borrowed or new-reference copy (str, int above the tagged range, float, complex) is released when the outermost C call returns. C code that keeps such a pointer without its own reference reads freed memory. CPython allows that while another holder keeps the object alive. Container getters (PyTuple_GetItem, PyList_GetItem, PyDict_GetItem* and their Ref variants) return stable stubs; generic ones (PyObject_GetItem, PySequence_GetItem, PyIter_Next) return copies.
  • Address reuse is a real hazard of this scheme. Copies are freed and reallocated constantly, so any cache keyed by a struct address must be invalidated when the struct is freed. One such cache (the "same str passed twice" shortcut) handed out the wrong string after an address was reused; that is fixed. The other address-keyed state (the identity ring, the float struct hint, complex structs, the dict mirror) was reviewed but not stress-tested.
  • Memory grows inside long C calls. Every copy made during one outermost C call is released only when it returns. A C loop that converts many values grows; a C call that never returns (an event loop in C) never releases them. Peak memory in CI against the build without native copies: numpy-vectorized 2.0 → 3.3 GB, c-arith-binop 0.5 → 1.6 GB.
  • Identity. A str that crosses from C is one str object per native struct while the struct is among the 4096 most recently converted strings, and a str stored into a container keeps its identity. A str that C keeps and returns much later can come back as an equal but different object. The same str passed in two calls arrives in C as two pointers, so C that compares pointers against a cached string must fall back to comparing contents.
  • complex is larger for all code. PComplex gained three fields, which slows complex-heavy pure Python code such as a Mandelbrot kernel.
  • Slower C API micro benchmarks. 12–22% slower with native copies than without on c-list-iterating-obj, c-magic-iter, c-call-method-o and c-call-method-int-float, in two runs. Not yet explained.
  • Strings created in C cost an object again. Each one that Java reads gets a str object, and a stub if C reads it back. This came with the identity fix and may give back part of the gain for string-heavy C code; the benchmark run of that commit is the measurement.
  • Allocator agreement. C and Java both use libc malloc/free. That holds in the native standalone; a JVM run with native memory tracking enabled would break it. Only unicodeobject.c was audited for str frees through GraalPy's allocator.
  • Global, single-threaded state. The borrowed stack, the identity ring and the str caches are global and rely on the GIL; not tested with threads.
  • Inactive experimental code. An opt-in representation of __slots__ classes as native structs (__native_layout__ = True) is included. Nothing sets it, and it is guarded by an assumption. Two parts run for every program: a bytecode fast path for __slots__ attribute stores, and a type check on slot reads and writes.

Testing

  • Linux x86-64 in CI, assertions enabled: native build, ABI check, GraalPy's tests including the C API tests, the multi-context tests and seven of eight standard library batches passed on the commit before the identity fix; the eighth failed on test_pyexpat's interning test, which that fix addresses. The run on the current commit is in progress.
  • macOS/aarch64 locally, assertions enabled: the C API tests (758 passed, 9 skipped, 0 failed) and test_pyexpat pass; the remaining failures are the same as on develop.

Measured on the benchmark runner

Median per iteration, one run per build, against #21 (the fast paths without native copies). Two runs of this branch agreed within 10% on every benchmark.

Benchmark #21 this branch
orjson-roundtrip 3.10 s 1.19 s
pandas-str 0.96 s 0.53 s
pandas-apply 1.15 s 0.93 s
pandas-csv 1.63 s 1.36 s
numpy-vectorized 0.25 s 0.17 s
pydantic-json 1.67 s 1.66 s

Geometric mean of the ratio: real packages 0.79, C API micro benchmarks 0.79, pure Python 1.01. These numbers predate the identity fix.

Not in this pull request

Ordinary objects (instances, dicts, lists) still cross into C through wrappers and stubs. A prototype that gives them native handles which the garbage collector reads exists, but it needs a change in GraalVM's serial collector and is not part of this branch.

🤖 Generated with Claude Code

@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: dc7a331 | Docs | Give us feedback!

@codspeed

codspeed Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 5 benchmarks

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

⚡ 9 improved benchmarks
❌ 5 regressed benchmarks
✅ 52 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ micro-native/c-call-method-o[5000000] 68.3 ms 80.2 ms -14.92%
❌ meso/pidigits 6.3 s 7.4 s -14.86%
❌ micro-native/c-magic-iter[50000000] 2.8 s 3.3 s -13.4%
❌ micro-native/c-issubtype-polymorphic[50000000] 2.7 s 3.1 s -13.12%
❌ meso/parrot-b2[200] 1.2 s 1.3 s -10.04%
⚡ micro-native/c-arith-binop2[100] 3,112.3 ms 195.9 ms ×16
⚡ micro-native/c-many-shortlived-objs[100000000] 27.8 s 2 s ×14
⚡ micro-native/c-arith-binop[1000] 4.7 s 1.3 s ×3.6
⚡ packages/pandas-str[20000] 834.5 ms 534.7 ms +56.06%
⚡ packages/pandas-csv[50000] 1.6 s 1.3 s +29.77%
⚡ packages/orjson-roundtrip[2500] 649.6 ms 514.3 ms +26.29%
⚡ micro-native/c-upcall-slot[1048576] 1.5 ms 1.3 ms +19.87%
⚡ packages/pandas-apply[20000] 1,090.3 ms 923.4 ms +18.07%
⚡ packages/lxml-xpath[2500] 1.9 s 1.6 s +15.46%

Tip

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


Comparing perf/native-value-copies (dc7a331) with perf/capi-fast-paths (4523f4a)

Open in CodSpeed

Values that cross into C no longer always get a Java wrapper plus a native
stub.

Shared native state (NativeComplex): one native block holds the
allocators that C and Java share without upcalls, the borrowed-reference
stack and the downcall depth. Generated downcall invokers (and vectorcall
slot calls) enter and leave the depth; when the outermost downcall
returns, the counts on the borrowed stack are dropped.

- complex: an exact complex is passed to C as a native PyComplexObject
  from a size-class allocator. A list of exact complex values stores
  counted pointers to such structs (ComplexPtrSequenceStorage); PComplex
  keeps an unowned pointer and serial so a value read from such a list is
  the same object when stored or passed again. PyComplex_FromDoubles and
  exact complex allocation/deallocation in C use the same allocator.
- int: an exact int that does not fit the tagged pointer (up to 120 bits)
  is passed as a native PyLongObject with no Java companion; the Java
  value stays a long. PyLong_From*/PyLong_As* handle these in C.
- float: an exact float that cannot be tagged is passed as a native
  PyFloatObject from a 64-byte small-block pool that PyObject_Malloc and
  Java share. An instance of a static native float subclass that is only
  (type, ob_fval) is held in Java as a value copy (PNativeFloat) instead of
  a native object with a weak reference and lookup entry.

Lifetime: a copy passed as an argument or borrowed result holds a count on
the borrowed stack until the outermost C call returns; C that increfs it
keeps it. Items that a container holds (dict and list items, PyDict_Next)
are still promoted to objects with stable stubs, as before. A copy that C
keeps without its own reference past the outermost call is freed under it.

Also included, experimental and opt-in: classes with __slots__ that set
__native_layout__ = True (and derive directly from object) get instances
whose slots live in native reference-counted structs, with a
pointer-aware list storage for them and pins on dict, cell, global and
attribute stores. No class in the standard library or the tests sets it.
The pins, the list storage and the struct paths are guarded by an
assumption that holds until such a class is created. What runs for every
program: a bytecode fast path for stores to __slots__ attributes (shape-
cached, like the existing load fast path), and a profiled
"native instance" type check on slot reads and writes.

__graalpython__ gains measurement helpers: complex_counters,
native_long_live, slots_counters (counters need -Dgraalpy.complexCounters
or -Dgraalpy.slotsCounters) and native_quiesce.
An exact str that is a bare Java string (TruffleString) and that C gets as
an argument or as a new reference is now a CPython 3.13 compact unicode
object in malloc'd memory (PyASCIIObject or PyCompactUnicodeObject with
the characters inline, kind chosen from the string's code range), with no
PString wrapper, no stub and no handle. C reads it with CPython's own
layout, so PyUnicode_GET_LENGTH, KIND, DATA, READ and
PyUnicode_AsUTF8AndSize run without entering Java. PyObject_Hash (same
value as Java's hash), PyUnicode_Compare, PyUnicode_CompareWithASCIIString
and PyUnicode_EqualToUTF8AndSize have C paths for these objects, and
PyUnicode_InternInPlace answers from a C cache of interned stubs.

Strings created by C (PyUnicode_New, PyUnicode_FromStringAndSize,
PyUnicode_FromString, PyUnicode_DecodeUTF8[Stateful] for valid input,
PyUnicode_FromKindAndData) are born in that layout and become Java strings
only when Java reads them. PyUnicode_Resize is implemented (it was not)
and resizes an unshared native string in place.

Identity: the struct's padding word holds a mark bit and an index into a
4096-entry ring that maps it to the Java string it was made from, so
f(s) is s holds and a struct handed back to Java is not copied again. The
same string passed twice in one call gets one struct.

Lifetime: C's reference count owns the struct (unicode_dealloc frees it,
or Java when it drops the last count). A borrowed or new-reference copy
also holds one count on the borrowed stack until the outermost C call
returns. Borrowed and new references to items a container holds
(PyTuple_GetItem, PyList_GetItem, PyDict_GetItem*, ...Ref variants,
PyCell_Get, items written into native storage, raw invoker calls) keep a
stable PString stub as before. str subclasses and strings that are
already PString objects take the existing path.

GRAALPY_NATIVE_STR=0 turns the scheme off at C API initialization.
__graalpython__.native_str_stats() reports live stubs and str counters.
…ith memcpy

GCC rejects the previous cast of the value field's address to a block pointer under -Werror=strict-aliasing. Clang accepted it. The stored bytes are the same.
ReleaseNativeArgsTupleNode asserted (with detailed assertions) that every
element of the args tuple is still the pointer that converting the managed
argument again yields. That holds for stubs, handles and tagged values,
but not for arguments that cross as native value copies (str, int, float,
complex): each conversion makes a new struct, so the check failed for
correct tuples (e.g. a str class name passed to a native metaclass
tp_init during "import ctypes"), and the conversion done by the check
itself allocated a further copy.

For an element that is a value copy, compare the struct's type and value
with the managed argument (code points for str, value for int, raw bits
for float and complex, type and bits for value-type float subclasses) and
require that it is still alive; other elements keep the pointer check.
A str passed twice in one call reuses the struct made for its previous
borrowed conversion while that struct is still on the borrowed stack,
checked by comparing the stack entry at the remembered index with the
remembered pointer. After the outermost C call returned, the struct was
freed, but the cache kept its address. In a later call a new struct for a
different string could be allocated at the same address and pushed at the
same index; the check then passed and the new string's struct was handed
out for the old string. test_capi.test_unicode test_fromobject showed it:
PyUnicode_FromObject(Str('abc')) returned the class name 'Str'.

Clear the cache whenever the stack is released below its index.
PyUnicode_FromObject of a str subclass instance returned the bare Java
string that str() of the instance yields. That string can be the very
object another str holds, and a bare string now keeps its identity when it
crosses to C and back, so the result was identical to the original str
(test_capi.test_unicode test_fromobject: assertIsNot(s2, s)). As in
CPython, wrap it in a new exact str object.
…identity

Java read a native str struct as a bare Java string. When C created a str
and stored it into a dict, the dict held that bare string; the first time C
borrowed it from the dict (PyDict_GetItemRef and friends promote bare
strings to an object with a stable stub, and write it back), the dict's
value became a new object. Python code that had already received the
first one saw a different object afterwards. pyexpat's element name
interning showed it (test_pyexpat InterningTest: the first handler call
got another object than the later ones).

Java now reads every native str struct as an exact str object, made once
per struct and remembered in the identity ring, for structs created by C
and for copies of Java strings alike. The same struct read again (key and
value of one PyDict_SetItem, then an argument tuple element) gives the same
object while its ring entry lives, so a str that C stores into a container
is the object the container keeps, and C reading it back gets its stub.

This gives up "f(s) is s" for a bare Java string passed through C: the
result is an equal, new object, as for every str that crosses through a
stub. Adds a cpyext test for the interning-dict pattern.
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