Repository navigation
Native copies of int, float, complex and str for C extensions - #22
Draft
Ivo Horák (horakivo) wants to merge 7 commits into
Draft
Ivo Horák (horakivo) wants to merge 7 commits into
Ivo Horák (horakivo) wants to merge 7 commits into
Conversation
Merging this PR will regress 5 benchmarks1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing |
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.
Ivo Horák (horakivo)
force-pushed
the
perf/native-value-copies
branch
from
November 28, 2026 02:56
08a8c7d to
a71afd8
Compare
…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.
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. 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)
complexcrosses as a nativePyComplexObjectfrom a size-class allocator. Lists of exact complex values store counted pointers to these structs;PComplexkeeps an unowned pointer and serial so that a value read from such a list stays the same object.intthat does not fit GraalPy's tagged pointer (up to 120 bits) crosses as a nativePyLongObjectwith no Java companion;PyLong_From*/PyLong_As*handle these in C.floatthat cannot be tagged crosses as aPyFloatObjectfrom a 64-byte small-block pool shared byPyObject_Mallocand Java. Instances of static nativefloatsubclasses that are only (type,ob_fval) are held in Java as value copies.PyDict_Next) are still promoted to objects with stable stubs, as before.str (commit 2)
strthat 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/READandPyUnicode_AsUTF8AndSizerun in C; hash, compare and equality have C paths.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_Resizeis implemented.strsubclasses, interned strings and strings that already have a stub keep the existing path.GRAALPY_NATIVE_STR=0turns 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
PyTuple_GetItem,PyList_GetItem,PyDict_GetItem*and theirRefvariants) return stable stubs; generic ones (PyObject_GetItem,PySequence_GetItem,PyIter_Next) return copies.numpy-vectorized2.0 → 3.3 GB,c-arith-binop0.5 → 1.6 GB.complexis larger for all code.PComplexgained three fields, which slows complex-heavy pure Python code such as a Mandelbrot kernel.c-list-iterating-obj,c-magic-iter,c-call-method-oandc-call-method-int-float, in two runs. Not yet explained.malloc/free. That holds in the native standalone; a JVM run with native memory tracking enabled would break it. Onlyunicodeobject.cwas audited for str frees through GraalPy's allocator.__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
test_pyexpat's interning test, which that fix addresses. The run on the current commit is in progress.test_pyexpatpass; the remaining failures are the same as ondevelop.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.
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