Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/elide/codspeed-diagnose.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,20 @@ native-8g --experimental-options --python.BackgroundGCTask=false --python
# The serial GC's default policy (Adaptive2) only takes a maximum young generation size; the policy
# BySpaceAndTime keeps the young generation at that size. Changes the policy and the size together.
young-1g --experimental-options --python.BackgroundGCTask=false --vm.XX:InitialCollectionPolicy=BySpaceAndTime --vm.Xmn1g --vm.XX:+PrintGC --log.python.capi.PythonCextBuiltins.level=CONFIG
# Per-collection pause phases (-XX:+VerboseGC -XX:+PrintGCTimes) plus GraalPy's C API tracking counters: one
# "[capi-gc]" line on stderr per reference-queue drain after a collection (handle-table size, strong and weak
# entries, stubs created, strong/weak flips and the flips caused by the drain itself, distinct table cards
# written, references drained by kind, collections GraalPy forced). Needs --python.CApiGCStats.
capi-stats --vm.XX:+PrintGC --vm.XX:+VerboseGC --vm.XX:+PrintGCTimes --experimental-options --python.CApiGCStats=true --log.python.capi.PythonCextBuiltins.level=CONFIG
# A/B of the list-storage changes in one build. "default" and "capi-stats" run the new behaviour: a list that
# C creates with PyList_New is filled natively and its items move to a managed storage when it is full, when
# Java takes it or when C drops it (--python.AdoptCBuiltLists), and PyList_GetItem/PyList_SET_ITEM on a list
# with a managed storage are answered by Java. lists-old restores the old behaviour (the list's storage stays a
# native array owning a reference to every item); lists-perstore keeps C-built lists managed from the start
# and stores every item through Java (the state before adoption); lists-getitem-old restores only the
# materialising PyList_GetItem. The -gc sets add the per-phase GC log and the counters of "capi-stats".
lists-old --experimental-options --python.ListSetItemMaterializes=true --python.ListGetItemMaterializes=true --python.AdoptCBuiltLists=false
lists-old-gc --vm.XX:+PrintGC --vm.XX:+VerboseGC --vm.XX:+PrintGCTimes --experimental-options --python.ListSetItemMaterializes=true --python.ListGetItemMaterializes=true --python.AdoptCBuiltLists=false --python.CApiGCStats=true --log.python.capi.PythonCextBuiltins.level=CONFIG
lists-perstore --experimental-options --python.AdoptCBuiltLists=false
lists-perstore-gc --vm.XX:+PrintGC --vm.XX:+VerboseGC --vm.XX:+PrintGCTimes --experimental-options --python.AdoptCBuiltLists=false --python.CApiGCStats=true --log.python.capi.PythonCextBuiltins.level=CONFIG
lists-getitem-old --experimental-options --python.ListGetItemMaterializes=true
19 changes: 19 additions & 0 deletions graalpython/com.oracle.graal.python.cext/src/capi.h
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,21 @@ Py_LOCAL_SYMBOL void GraalPyPrivate_DebugTrace(void);
typedef struct {
PyObject_HEAD
int32_t handle_table_index;
/* In the padding after handle_table_index, so the layout does not change. Zero when the stub
is allocated. GRAALPY_STUB_ITEMS_EXPOSED: C took the item array of this list (PySequence_Fast_ITEMS),
so its native storage must stay where it is. */
int32_t graalpy_flags;
} GraalPyObject;

#define GRAALPY_STUB_ITEMS_EXPOSED 1
/* The list comes from PyList_New and its native array is filled by C; the bits from
GRAALPY_STUB_FILL_SHIFT count the filled slots (see listobject.c: graalpy_list_count_fill). */
#define GRAALPY_STUB_BUILT_BY_C 2
/* Java found the list not yet full when it tried to adopt it: adopt it when the last slot is filled. */
#define GRAALPY_STUB_ADOPT_ON_FILL 4
#define GRAALPY_STUB_FILL_SHIFT 3
#define GRAALPY_STUB_FILL_UNIT (1 << GRAALPY_STUB_FILL_SHIFT)

typedef struct {
GraalPyObject ob_base;
Py_ssize_t ob_size;
Expand Down Expand Up @@ -275,6 +288,12 @@ static MUST_INLINE int GraalPyPrivate_PoisonNativeMemoryOnFree() {
static MUST_INLINE int GraalPyPrivate_SampleNativeMemoryAllocSites() {
return Py_Truffle_Options & GRAALPY_SAMPLE_NATIVE_MEMORY_ALLOC_SITES;
}
static MUST_INLINE int GraalPyPrivate_ListGetItemMaterializes() {
return Py_Truffle_Options & GRAALPY_LIST_GETITEM_MATERIALIZES;
}
static MUST_INLINE int GraalPyPrivate_ListSetItemMaterializes() {
return Py_Truffle_Options & GRAALPY_LIST_SETITEM_MATERIALIZES;
}

static inline void
GraalPyPrivate_Log(int level, const char *format, ...)
Expand Down
65 changes: 65 additions & 0 deletions graalpython/com.oracle.graal.python.cext/src/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,48 @@ PyTypeObject PyList_Type = {
.tp_vectorcall = 0, // GraalPy change: nulled
};

static inline GraalPyVarObject *graalpy_list_stub(PyObject *op);

/* A store into the native array of a list from PyList_New: count the filled slots. If Java already tried
to adopt the list while it had empty slots (GRAALPY_STUB_ADOPT_ON_FILL), let it adopt the items into a
managed storage in one call when the last slot is filled (CApiTransitions.adoptCBuiltList); otherwise
that happens when Java takes the list or C releases it, without an extra call. */
static inline void
graalpy_list_count_fill(PyObject *op, GraalPyVarObject *s, PyObject *old, PyObject *value)
{
int32_t f = s->ob_base.graalpy_flags;
if ((f & (GRAALPY_STUB_BUILT_BY_C | GRAALPY_STUB_ITEMS_EXPOSED)) != GRAALPY_STUB_BUILT_BY_C || (old == NULL) == (value == NULL)) {
return;
}
f += value != NULL ? GRAALPY_STUB_FILL_UNIT : -GRAALPY_STUB_FILL_UNIT;
s->ob_base.graalpy_flags = f;
if (value != NULL && (f & GRAALPY_STUB_ADOPT_ON_FILL) && (Py_ssize_t) (f >> GRAALPY_STUB_FILL_SHIFT) == s->ob_size) {
GraalPyPrivate_List_Adopt(op);
}
}

/* A list stub with ob_item == NULL has a managed (or empty) storage. Java stores into it and takes over
the stolen reference, so that the storage stays managed (see GraalPyPrivate_List_SetItemSteal). */
static inline int
graalpy_list_store_in_java(PyObject *op)
{
GraalPyVarObject *s = graalpy_list_stub(op);
return s != NULL && s->ob_item == NULL && !GraalPyPrivate_ListSetItemMaterializes();
}

void GraalPyList_SET_ITEM(PyObject* op, Py_ssize_t index, PyObject* value) {
GraalPyVarObject *s = graalpy_list_stub(op);
if (s != NULL && s->ob_item != NULL) {
/* native storage, e.g. of a list that C created with PyList_New and fills */
PyObject *old = s->ob_item[index];
s->ob_item[index] = value;
graalpy_list_count_fill(op, s, old, value);
return;
}
if (graalpy_list_store_in_java(op)) {
GraalPyPrivate_List_SetItemSteal(op, index, value, 1);
return;
}
GraalPyList_ITEMS(op)[index] = value;
}

Expand Down Expand Up @@ -170,6 +211,18 @@ PyList_SetItem(PyObject *op, Py_ssize_t i,
return -1;
}
// GraalPy change: avoid direct struct access
GraalPyVarObject *s = graalpy_list_stub(op);
if (s != NULL && s->ob_item != NULL) {
p = s->ob_item + i;
PyObject *old = *p;
*p = newitem;
graalpy_list_count_fill(op, s, old, newitem);
Py_XDECREF(old);
return 0;
}
if (graalpy_list_store_in_java(op)) {
return GraalPyPrivate_List_SetItemSteal(op, i, newitem, 0);
}
p = GraalPyList_ITEMS(op) + i;
Py_XSETREF(*p, newitem);
return 0;
Expand Down Expand Up @@ -201,6 +254,10 @@ PyObject **
GraalPyList_ITEMS(PyObject *op)
{
GraalPyVarObject *s = graalpy_list_stub(op);
if (s != NULL) {
/* C may keep this pointer: Java must not move the storage away (see AdoptCBuiltLists) */
s->ob_base.graalpy_flags |= GRAALPY_STUB_ITEMS_EXPOSED;
}
if (s != NULL && s->ob_item != NULL) {
return s->ob_item;
}
Expand All @@ -223,6 +280,14 @@ PyList_GetItem(PyObject *op, Py_ssize_t i)
GraalPyVarObject *s = graalpy_list_stub(op);
if (s != NULL) {
if (s->ob_size < 0) {
/* The storage is managed. Java answers the read and the storage stays managed: a native
storage would hold a reference to every item, so each item would stay strongly referenced
from the handle table until the list has died and a Java collection has released the
storage, one more collection per nesting level (--python.ListGetItemMaterializes). The
item returned is borrowed; the list keeps it alive. */
if (!GraalPyPrivate_ListGetItemMaterializes()) {
return GraalPyPrivate_List_GetItem(op, i);
}
/* Bounds first: an invalid index raises IndexError (Java path) without touching the storage.
A valid one makes the list's storage a native PyObject* array (as ob_item access does), so
further reads stay in C. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,9 @@ private PythonCextBuiltinRegistry() {
lines.add(" @SuppressWarnings(\"try\")");
}
lines.add(" public static " + capiTypeToJavaPrimitiveType(builtin.returnType) + " upcall_" + builtin.name + "(" + argString + ") {");
lines.add(" if (com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.countUpcalls) {");
lines.add(" com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.upcall(" + builtin.id + ", \"" + builtin.name + "\");");
lines.add(" }");
String paramString = IntStream.range(0, builtin.arguments.length).mapToObj(i -> argName(i)).collect(Collectors.joining(", "));
boolean isVoidReturn = isVoid(builtin.returnType);
// Every upcall bumps the "Java ran" epoch on exit (see CApiEpoch)
Expand All @@ -1097,6 +1100,9 @@ private PythonCextBuiltinRegistry() {
lines.add(" " + retString + builtin.name + ".getCallTarget().call(" + paramString + ");");
lines.add(" } finally {");
lines.add(" " + epochBump);
lines.add(" if (com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.countUpcalls) {");
lines.add(" com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.upcallExit();");
lines.add(" }");
lines.add(" }");
} else {
String retString = isVoidReturn ? "" : "return ";
Expand All @@ -1115,6 +1121,9 @@ private PythonCextBuiltinRegistry() {
}
lines.add(" } finally {");
lines.add(" " + epochBump);
lines.add(" if (com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.countUpcalls) {");
lines.add(" com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.upcallExit();");
lines.add(" }");
lines.add(" }");
}
lines.add(" }");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -782,8 +782,8 @@ def assert_is_freed(id): pass

assert_is_alive(0)
assert_is_alive(1)
assert_is_strong(htid_l0)
assert_is_strong(htid_l1)
# The lists are filled with PyList_SET_ITEM while their storage is managed, so they hold
# their items with Java references and their handle-table entries need not be strong.
assert l0[0] is l1
assert l1[0] is l0
assert ml0[0] is ml1
Expand All @@ -793,8 +793,6 @@ def assert_is_freed(id): pass
self._trigger_gc()
assert_is_freed(0)
assert_is_freed(1)
assert_is_strong(htid_l0)
assert_is_strong(htid_l1)

def test_module_globals(self):
self._trigger_gc()
Expand Down
156 changes: 149 additions & 7 deletions graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,146 @@ def test_clear_native_storage_gc(self):
for _ in range(5):
gc.collect()

def test_c_built_lists(self):
# Lists that C creates with PyList_New and fills with PyList_SET_ITEM: filled natively,
# handed to Java, nested, exposed through PySequence_Fast_ITEMS, and modified afterwards.
module = compile_module_from_string(
"""
#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject* nested(PyObject* self, PyObject* arg) {
Py_ssize_t n = PyLong_AsSsize_t(arg);
PyObject* outer = PyList_New(n);
for (Py_ssize_t i = 0; i < n; i++) {
PyObject* inner = PyList_New(2);
PyList_SET_ITEM(inner, 0, PyUnicode_FromFormat("s%zd", i));
PyList_SET_ITEM(inner, 1, PyLong_FromSsize_t(i * 1000003));
PyList_SET_ITEM(outer, i, inner);
}
return outer;
}

static PyObject* exposed(PyObject* self, PyObject* unused) {
PyObject* l = PyList_New(2);
PyObject** items = PySequence_Fast_ITEMS(l);
PyList_SET_ITEM(l, 0, PyUnicode_FromString("e0"));
PyList_SET_ITEM(l, 1, PyUnicode_FromString("e1"));
PyObject* r = PyObject_Repr(l);
Py_XDECREF(r);
PyObject* old = items[1];
items[1] = PyUnicode_FromString("e1-replaced");
Py_DECREF(old);
return l;
}

static PyObject* handed_then_replaced(PyObject* self, PyObject* d) {
PyObject* l = PyList_New(3);
for (int i = 0; i < 3; i++) {
PyList_SET_ITEM(l, i, PyUnicode_FromFormat("a%d", i));
}
if (PyDict_SetItemString(d, "l", l) < 0) {
return NULL;
}
PyObject* old = PyList_GET_ITEM(l, 0);
PyList_SET_ITEM(l, 0, PyUnicode_FromString("a0-replaced"));
Py_DECREF(old);
if (PyList_SetItem(l, 2, PyUnicode_FromString("a2-set")) < 0) {
return NULL;
}
PyObject* one = PyList_GET_ITEM(l, 1);
Py_INCREF(one);
Py_DECREF(l);
return one;
}

static PyObject* append_then_fill(PyObject* self, PyObject* unused) {
PyObject* l = PyList_New(2);
PyObject* x = PyUnicode_FromString("appended");
if (PyList_Append(l, x) < 0) {
return NULL;
}
Py_DECREF(x);
PyList_SET_ITEM(l, 0, PyUnicode_FromString("f0"));
PyList_SET_ITEM(l, 1, PyUnicode_FromString("f1"));
return l;
}

static PyObject* hand_empty_then_fill(PyObject* self, PyObject* d) {
// orjson's pattern: the parent gets the list before it is filled
PyObject* l = PyList_New(2);
if (PyDict_SetItemString(d, "x", l) < 0) {
return NULL;
}
Py_DECREF(l);
PyList_SET_ITEM(l, 0, PyUnicode_FromString("h0"));
PyList_SET_ITEM(l, 1, PyUnicode_FromString("h1"));
Py_RETURN_NONE;
}

static PyObject* build_and_drop(PyObject* self, PyObject* arg) {
// a list that only C ever sees
Py_ssize_t n = PyLong_AsSsize_t(arg);
Py_ssize_t total = 0;
for (Py_ssize_t k = 0; k < n; k++) {
PyObject* l = PyList_New(3);
for (int i = 0; i < 3; i++) {
PyList_SET_ITEM(l, i, PyUnicode_FromFormat("d%zd-%d", k, i));
}
total += PyList_GET_SIZE(l);
Py_DECREF(l);
}
return PyLong_FromSsize_t(total);
}

static PyObject* null_over_item(PyObject* self, PyObject* unused) {
PyObject* l = PyList_New(2);
PyList_SET_ITEM(l, 0, PyUnicode_FromString("n0"));
PyList_SET_ITEM(l, 1, PyUnicode_FromString("n1"));
PyObject* old = PyList_GET_ITEM(l, 1);
PyList_SET_ITEM(l, 1, NULL);
Py_DECREF(old);
PyList_SET_ITEM(l, 1, PyUnicode_FromString("n1-again"));
return l;
}

static PyMethodDef methods[] = {
{"hand_empty_then_fill", (PyCFunction) hand_empty_then_fill, METH_O, NULL},
{"build_and_drop", (PyCFunction) build_and_drop, METH_O, NULL},
{"null_over_item", (PyCFunction) null_over_item, METH_NOARGS, NULL},
{"nested", (PyCFunction) nested, METH_O, NULL},
{"exposed", (PyCFunction) exposed, METH_NOARGS, NULL},
{"handed_then_replaced", (PyCFunction) handed_then_replaced, METH_O, NULL},
{"append_then_fill", (PyCFunction) append_then_fill, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT, "test_c_built_lists", NULL, -1, methods
};

PyMODINIT_FUNC PyInit_test_c_built_lists(void) {
return PyModule_Create(&module);
}
""",
"test_c_built_lists",
)
for round in range(3):
n = module.nested(50)
assert n == [["s%d" % i, i * 1000003] for i in range(50)], n
assert module.exposed() == ["e0", "e1-replaced"]
d = {}
assert module.handed_then_replaced(d) == "a1"
assert d["l"] == ["a0-replaced", "a1", "a2-set"], d["l"]
assert module.append_then_fill() == ["f0", "f1", "appended"]
d = {}
module.hand_empty_then_fill(d)
assert d["x"] == ["h0", "h1"], d["x"]
assert module.build_and_drop(1000) == 3000
assert module.null_over_item() == ["n0", "n1-again"]
del n, d
gc.collect()

test_PyList_New = CPyExtFunction(
_reference_new_list,
lambda: (
Expand Down Expand Up @@ -315,16 +455,18 @@ def test_clear_native_storage_gc(self):
Py_INCREF(newitem);
PyList_SET_ITEM(op, idx, newitem);
int refcnt1 = Py_REFCNT(newitem);
Py_INCREF(Py_None);
PyList_SET_ITEM(op, idx, Py_None);
int refcnt2 = Py_REFCNT(newitem);
// Important! PyList_SET_ITEM does not decref the element that
// was previously at idx, but PyList_SetItem does. Let's make
// sure that semantic difference is observed. (GraalPy moves a
// reference stored into a managed list storage to Java and
// hands it back to the caller when SET_ITEM overwrites it, so
// the count may also go up.)
PyList_SET_ITEM(op, idx, newitem);
int refcnt3 = Py_REFCNT(newitem);
// Important! PyList_SET_ITEM does not change the refcnts,
// but PyList_SetItem decrefs the element that was
// previously at idx. Let's make sure that semantic
// difference is observed
if (refcnt1 != refcnt2 || refcnt2 != refcnt3) {
return Py_BuildValue("iii", refcnt1, refcnt2, refcnt3);
if (refcnt2 < refcnt1) {
return Py_BuildValue("ii", refcnt1, refcnt2);
} else {
return op;
}
Expand Down
Loading
Loading