Skip to content

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

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

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

Conversation

@horakivo

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.
  • A small ring maps a struct back to its Java string, so f(s) is s holds and a struct handed back is not copied again.
  • 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 die when the outermost C call returns. C code that keeps a pointer to a str (or large int, float, complex) without its own reference, which CPython allows while another holder keeps the object alive, reads freed memory afterwards. Reproduced with a 20-line extension; correct with GRAALPY_NATIVE_STR=0. Container getters (PyTuple_GetItem, PyList_GetItem, PyDict_GetItem*, ...) return stable stubs, but generic ones (PyObject_GetItem, PySequence_GetItem, PyIter_Next) return copies.
  • Memory growth 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, and a C call that never returns (an event loop in C) never releases them.
  • complex is larger for all code. PComplex gained three fields (pointer, serial, exact flag), which slows complex-heavy pure Python code (e.g. a Mandelbrot kernel). Some large numpy workloads also use more peak memory.
  • Identity across calls. The same Java string passed in two calls gets two structs; C that compares pointers against a cached string falls back to comparing contents.
  • Allocator agreement between C and Java (both use libc malloc/free) holds in the native standalone; a JVM run with native memory tracking enabled would break it. Only unicodeobject.c was audited for frees of str objects through GraalPy's allocator.
  • Global, single-threaded state. The borrowed stack and the ring are global and rely on the GIL; not tested with threads.
  • Inactive experimental code. Commit 1 also contains an opt-in representation of __slots__ classes as native reference-counted structs (classes that set __native_layout__ = True), with a pointer-aware list storage and pins on stores. Nothing sets it. Its pins, list storage and struct paths are guarded by an assumption that holds until such a class exists; two parts run for every program: a bytecode fast path for stores to __slots__ attributes, and a profiled "native instance" type check on slot reads and writes. It is intertwined with the complex list storage and was left in rather than removed.
  • Only built and tested on macOS/aarch64 (cpyext suite: see below). The CI run of this pull request is the first build on Linux x86-64. The local build used an older GraalVM revision than the one this repository pins.

Testing

  • cpyext suite on a native standalone (macOS/aarch64): 765 run, 756 passed, 9 skipped (ABI3T opt-in and Java interop tests that do not apply to this run), 0 failures.
  • The ten package benchmarks (graalpython/com.oracle.graal.python.benchmarks/python/packages, which check their own results) and a few C API micro benchmarks run for correctness only. No performance numbers here; measurements will follow separately.

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

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

datadog-official Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Pipelines

⚠️ Warnings

Your PR has warnings. Please review the issues below.

🚦 2 Pipeline jobs failed

Elide CI | python tests on the native standalone

View more details · View in GitHub Actions

Error during pip installation. AssertionError raised when setting up virtual environment and ensuring pip is available.

Elide CI | tests / tier2 (python-tagged-unittest-gate-batch2-linux-amd64-jdk-latest, 7.88.0, ubuntu-24.04, 1, 3.12.8...

View more details · View in GitHub Actions

Assertion error in graalpython/lib-python/3/test/test_genericalias.py:22 leading to Java AssertionError during unittest execution.

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 08a8c7d | Docs | View more details | Give us feedback!

…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.
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