diff --git a/.github/elide/codspeed-diagnose.txt b/.github/elide/codspeed-diagnose.txt index b90f5e40d9..f70f2f7bd7 100644 --- a/.github/elide/codspeed-diagnose.txt +++ b/.github/elide/codspeed-diagnose.txt @@ -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 diff --git a/graalpython/com.oracle.graal.python.cext/src/capi.h b/graalpython/com.oracle.graal.python.cext/src/capi.h index d46c8aa191..ca5c7a712c 100644 --- a/graalpython/com.oracle.graal.python.cext/src/capi.h +++ b/graalpython/com.oracle.graal.python.cext/src/capi.h @@ -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; @@ -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, ...) diff --git a/graalpython/com.oracle.graal.python.cext/src/listobject.c b/graalpython/com.oracle.graal.python.cext/src/listobject.c index 89bae483c8..266f18a084 100644 --- a/graalpython/com.oracle.graal.python.cext/src/listobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/listobject.c @@ -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; } @@ -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; @@ -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; } @@ -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. */ diff --git a/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java b/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java index 21184c4244..7cbbf3a09d 100644 --- a/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java +++ b/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java @@ -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) @@ -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 "; @@ -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(" }"); diff --git a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py index aa565e13e5..dc40a6dffa 100644 --- a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py +++ b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_gc.py @@ -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 @@ -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() diff --git a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_list.py b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_list.py index 3aed563b2a..cb015539a6 100644 --- a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_list.py +++ b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_list.py @@ -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 + + 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: ( @@ -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; } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GcModuleBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GcModuleBuiltins.java index cf994eb8b2..87fac524aa 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GcModuleBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GcModuleBuiltins.java @@ -45,6 +45,7 @@ import com.oracle.graal.python.builtins.objects.cext.capi.ExternalFunctionNodes.CheckPrimitiveFunctionResultNode; import com.oracle.graal.python.builtins.objects.cext.capi.NativeCAPISymbol; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions; import com.oracle.graal.python.builtins.objects.cext.structs.CFields; import com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess; @@ -201,6 +202,10 @@ static long javaCollect(Node inliningTarget, GilNode gil) { long freeMemory = runtime.freeMemory(); try { PythonUtils.forceFullGC(); + if (CApiGCStats.isEnabled()) { + CApiGCStats.forcedPython(); + CApiGCStats.report(PythonContext.get(inliningTarget).handleContext, "gc.collect"); + } try { Thread.sleep(15); } catch (InterruptedException e) { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextBuiltins.java index c915dc2c8a..892a92f7c3 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextBuiltins.java @@ -110,6 +110,7 @@ import com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.FromCharPointerNode; import com.oracle.graal.python.builtins.objects.cext.capi.PThreadState; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.CharPtrToPythonNode; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.GcNativePtrToPythonNode; @@ -1064,11 +1065,16 @@ static void GraalPyPrivate_TriggerGC(long delay) { * references cleared by the previous collection and release their native objects now. */ java.util.concurrent.locks.LockSupport.parkNanos(100_000L); + CApiGCStats.forcedNativeMemory(true); CApiTransitions.drainReferenceQueueNow(PythonContext.get(null)); return; } LOGGER.fine("full GC due to native memory"); PythonUtils.forceFullGC(); + if (CApiGCStats.isEnabled()) { + CApiGCStats.forcedNativeMemory(false); + CApiGCStats.report(PythonContext.get(null).handleContext, "nativeMem"); + } try { Thread.sleep(delay); } catch (InterruptedException x) { @@ -1359,6 +1365,10 @@ static int GraalPyPrivate_DisableReferenceQueuePolling() { private static final int GRAALPY_POISON_NATIVE_MEMORY_ON_FREE = 0x100; @CApiConstant // private static final int GRAALPY_SAMPLE_NATIVE_MEMORY_ALLOC_SITES = 0x200; + @CApiConstant // + private static final int GRAALPY_LIST_GETITEM_MATERIALIZES = 0x400; + @CApiConstant // + private static final int GRAALPY_LIST_SETITEM_MATERIALIZES = 0x800; /* * These should be kept so they can be shared across multiple contexts in the same engine, if @@ -1401,6 +1411,12 @@ static int GraalPyPrivate_Native_Options() { if (language.getEngineOption(PythonOptions.SampleNativeMemoryAllocSites)) { options |= GRAALPY_SAMPLE_NATIVE_MEMORY_ALLOC_SITES; } + if (language.getEngineOption(PythonOptions.ListGetItemMaterializes)) { + options |= GRAALPY_LIST_GETITEM_MATERIALIZES; + } + if (language.getEngineOption(PythonOptions.ListSetItemMaterializes)) { + options |= GRAALPY_LIST_SETITEM_MATERIALIZES; + } return options; } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java index b0cc771c10..84ff8ad8e7 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java @@ -68,6 +68,7 @@ import com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode; import com.oracle.graal.python.builtins.objects.cext.capi.ExternalFunctionNodes.ToNativeBorrowedNode; import com.oracle.graal.python.builtins.objects.cext.capi.PySequenceArrayWrapper; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonInternalNode; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonNode; @@ -101,6 +102,18 @@ public final class PythonCextListBuiltins { + /** See {@code --python.AdoptCBuiltLists}. */ + @com.oracle.truffle.api.CompilerDirectives.CompilationFinal private static boolean adoptCBuiltLists = true; + + public static void setAdoptCBuiltLists(boolean value) { + com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate(); + adoptCBuiltLists = value; + } + + public static boolean adoptCBuiltLists() { + return adoptCBuiltLists; + } + private static final CApiTiming TIMING_PYLIST_NEW = CApiTiming.create(false, "PyList_New"); @CApiBuiltin(ret = PyObject, args = {Py_ssize_t}, call = Direct, acquireGil = false, retConversion = PythonToNativeNewRefNode.class, argConversions = {long.class}) @@ -119,9 +132,24 @@ static long PyList_New(long size) { if (!PInt.fitsInInt(size)) { throw PRaiseNode.raiseStatic(null, MemoryError); } - Object[] a = new Object[(int) size]; - Arrays.fill(a, PNone.NO_VALUE); - result = PFactory.createList(language, a); + if (adoptCBuiltLists) { + /* + * C fills the list with PyList_SET_ITEM: give it a native array, so that the + * stores stay in C, and move the items to a managed storage when Java takes the + * list (CApiTransitions.adoptCBuiltList). + */ + NativeObjectSequenceStorage storage = NativeObjectSequenceStorage.create(com.oracle.graal.python.runtime.nativeaccess.NativeMemory.callocPtrArray(size + 1), (int) size, + (int) size, true); + storage.setBuiltByC(true); + result = PFactory.createList(language, storage); + long pointer = PythonToNativeInternalNode.executeNewRefUncached(result); + com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.markCBuiltListStub(pointer); + return pointer; + } else { + Object[] a = new Object[(int) size]; + Arrays.fill(a, PNone.NO_VALUE); + result = PFactory.createList(language, a); + } } return PythonToNativeInternalNode.executeNewRefUncached(result); } finally { @@ -202,6 +230,7 @@ static int PyList_Append(long opPtr, long itemPtr) { Object op = NativeToPythonInternalNode.executeUncached(opPtr, false); Object item = NativeToPythonInternalNode.executeUncached(itemPtr, false); if (op instanceof PList list && item != PNone.NO_VALUE) { + CApiGCStats.listStore(list); PListAppendNode.executeUncached(list, item); return 0; } @@ -252,6 +281,7 @@ static int getSlice(PList list, Object iLow, Object iHigh, Object s, @Bind Node inliningTarget, @Cached ListBuiltins.SetSubscriptNode setItemNode, @Cached PySliceNew sliceNode) { + CApiGCStats.listStore(list); setItemNode.executeVoid(null, list, sliceNode.execute(inliningTarget, iLow, iHigh, PNone.NONE), s); return 0; } @@ -268,6 +298,7 @@ abstract static class PyList_Extend extends CApiBinaryBuiltinNode { @Specialization static int extend(PList list, Object iterable, @Cached ListExtendNode extendNode) { + CApiGCStats.listStore(list); extendNode.execute(null, list, iterable); return 0; } @@ -285,6 +316,7 @@ abstract static class _PyList_Extend extends CApiBinaryBuiltinNode { @Specialization Object extend(PList list, Object iterable, @Cached ListExtendNode extendNode) { + CApiGCStats.listStore(list); extendNode.execute(null, list, iterable); return PNone.NONE; } @@ -338,6 +370,7 @@ abstract static class PyList_Insert extends CApiTernaryBuiltinNode { @Specialization static int insert(PList list, Object i, Object item, @Cached ListInsertNode insertNode) { + CApiGCStats.listStore(list); insertNode.execute(null, list, i, item); return 0; } @@ -380,6 +413,58 @@ static int error(@SuppressWarnings("unused") Object self, } } + /** + * {@code PyList_SET_ITEM} and {@code PyList_SetItem} of a list whose storage is managed: stores + * the item in the managed storage and takes over the reference that C passes (both functions + * steal it). The storage stays managed, so the list holds the item with a Java reference and the + * item dies together with the list. Making the storage native instead would give the native array + * a reference to every item, and each item would stay strongly referenced from the handle table + * until the list has died and a Java collection has released the storage. + * + * A previous item was held by the managed storage with a Java reference, not a native one. In + * CPython, PyList_SET_ITEM leaves the list's reference to the previous item with the caller, + * which commonly decrefs it ({@code old = PyList_GET_ITEM(l, i); PyList_SET_ITEM(l, i, v); + * Py_DECREF(old)}), so for {@code giveOldToCaller != 0} the caller receives a new native + * reference to the previous item. PyList_SetItem releases the previous item itself and passes 0. + */ + @CApiBuiltin(ret = Int, args = {PyObject, Py_ssize_t, PyObject, Int}, call = Ignored, retConversion = int.class, argConversions = {long.class, long.class, long.class, int.class}) + @com.oracle.truffle.api.CompilerDirectives.TruffleBoundary + static int GraalPyPrivate_List_SetItemSteal(long opPtr, long index, long itemPtr, int giveOldToCaller) { + Object item = NativeToPythonInternalNode.executeUncached(itemPtr, true); + Object op = NativeToPythonInternalNode.executeUncached(opPtr, false); + if (!(op instanceof PList list)) { + throw PythonCextBuiltins.badInternalCall("PyList_SetItem", "op"); + } + SequenceStorage storage = list.getSequenceStorage(); + if (index < 0 || index >= storage.length()) { + throw PRaiseNode.raiseStatic(null, IndexError, ErrorMessages.LIST_ASSIGMENT_INDEX_OUT_OF_RANGE); + } + if (giveOldToCaller != 0) { + Object old = com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes.GetItemScalarNode.executeUncached(storage, (int) index); + if (old != PNone.NO_VALUE && old != null) { + PythonToNativeInternalNode.executeNewRefUncached(old); + } + } + SequenceStorage generalized = ListGeneralizationNode.executeUncached(storage, item); + if (generalized != storage) { + list.setSequenceStorage(generalized); + } + SetItemScalarNode.executeUncached(generalized, (int) index, item); + return 0; + } + + /** + * C filled every slot of a list from {@code PyList_New} (counted in the stub, see + * {@code graalpy_list_count_fill} in listobject.c). Resolving the list adopts its items + * ({@code CApiTransitions.adoptCBuiltList}). + */ + @CApiBuiltin(ret = Int, args = {PyObject}, call = Ignored, retConversion = int.class, argConversions = {long.class}) + @com.oracle.truffle.api.CompilerDirectives.TruffleBoundary + static int GraalPyPrivate_List_Adopt(long opPtr) { + NativeToPythonInternalNode.executeUncached(opPtr, false); + return 0; + } + /** C registers its list.clear ml_meth once at C API initialization. */ @CApiBuiltin(ret = Int, args = {Pointer}, call = Ignored, retConversion = int.class, argConversions = {long.class}) @com.oracle.truffle.api.CompilerDirectives.TruffleBoundary @@ -413,6 +498,7 @@ static long doGeneric(PList self, long outItems, @Cached PySequenceArrayWrapper.ToNativeStorageNode toNativeStorageNode) { SequenceStorage sequenceStorage = self.getSequenceStorage(); if (sequenceStorage instanceof ObjectSequenceStorage objectStorage) { + CApiGCStats.listTraverseConversion(); sequenceStorage = toNativeStorageNode.execute(inliningTarget, objectStorage, false); self.setSequenceStorage(sequenceStorage); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java index b8f2505f69..46a9cf82a0 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java @@ -118,6 +118,7 @@ import com.oracle.graal.python.runtime.PythonContext; import com.oracle.graal.python.runtime.sequence.storage.NativeByteSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.NativeObjectSequenceStorage; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.Cached; @@ -133,6 +134,7 @@ public final class PythonCextSlotBuiltins { public static long GraalPyPrivate_Get_PyListObject_ob_item(long ptr) { PList object = (PList) NativeToPythonInternalNode.executeUncached(ptr, false); assert !(object.getSequenceStorage() instanceof NativeByteSequenceStorage); + CApiGCStats.sequenceItemsRequested(false, object.getSequenceStorage()); return PySequenceArrayWrapper.ensureNativeSequence(object); } @@ -140,6 +142,7 @@ public static long GraalPyPrivate_Get_PyListObject_ob_item(long ptr) { public static long GraalPyPrivate_Get_PyTupleObject_ob_item(long ptr) { PTuple object = (PTuple) NativeToPythonInternalNode.executeUncached(ptr, false); assert !(object.getSequenceStorage() instanceof NativeByteSequenceStorage); + CApiGCStats.sequenceItemsRequested(true, object.getSequenceStorage()); return PySequenceArrayWrapper.ensureNativeSequence(object); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java index 308f53421d..72fe280969 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java @@ -92,6 +92,7 @@ import com.oracle.graal.python.builtins.objects.capsule.PyCapsule; import com.oracle.graal.python.builtins.objects.cext.capi.ExternalFunctionNodesFactory.PyObjectCheckFunctionResultNodeGen; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.FirstToNativeNode; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.HandleContext; @@ -391,6 +392,8 @@ public CApiContext(PythonContext context, NativeLibrary library, NativeLibraryLo Arrays.fill(singletonNativePtrs, UNINITIALIZED); this.gcTask = new BackgroundGCTask(context); + CApiGCStats.setEnabled(context.getOption(PythonOptions.CApiGCStats)); + com.oracle.graal.python.builtins.modules.cext.PythonCextListBuiltins.setAdoptCBuiltLists(context.getOption(PythonOptions.AdoptCBuiltLists)); this.referenceQueueWatcherTask = new ReferenceQueueWatcherTask(context); } @@ -789,6 +792,10 @@ private void perform() { long start = System.nanoTime(); PythonUtils.forceFullGC(); long gcTime = (System.nanoTime() - start) / 1000000; + if (CApiGCStats.isEnabled()) { + CApiGCStats.forcedBackground(); + CApiGCStats.report(context.handleContext, "background"); + } if (LOGGER.isLoggable(Level.FINER)) { LOGGER.info(PythonUtils.formatJString("Background GC Task -- GC [%d ms] RSS [%d MB]->[%d MB](%.1f%%)", diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiGCStats.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiGCStats.java new file mode 100644 index 0000000000..3b8db89446 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiGCStats.java @@ -0,0 +1,447 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or + * data (collectively the "Software"), free of charge and under any and all + * copyright rights in the Software, and any and all patent rights owned or + * freely licensable by each licensor hereunder covering either (i) the + * unmodified Software as contributed to or provided by such licensor, or (ii) + * the Larger Works (as defined below), to deal in both + * + * (a) the Software, and + * + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * + * The above copyright notice and either this complete permission notice or at a + * minimum a reference to the UPL must be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.oracle.graal.python.builtins.objects.cext.capi.transitions; + +import java.lang.management.GarbageCollectorMXBean; +import java.lang.management.ManagementFactory; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.CApiNativeStub; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.HandleContext; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.PythonObjectReference; +import com.oracle.graal.python.builtins.objects.object.PythonObject; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * Counters of how the C API tracks managed objects, for diagnosing Java GC cost + * ({@code --python.CApiGCStats}). Off by default; when off, every hook is a constant-false branch + * in compiled code. Counts are deterministic for a given program and do not depend on time. + * + * One line is printed to stderr for each reference-queue drain that follows at least one Java + * collection, and after each collection that GraalPy forces itself. Counters marked "delta" are + * reset after each line. + */ +public final class CApiGCStats { + + /** Entries of the handle table covered by one card, assuming 4-byte references. */ + private static final int CARD_SHIFT = 7; + + @CompilationFinal static boolean enabled; + /** Read by the generated upcall wrappers, which are not partially evaluated. */ + public static boolean countUpcalls; + private static long[] upcallCounts = new long[0]; + private static String[] upcallNames = new String[0]; + /** Per releasing holder (native type name or storage kind): {releases, strong-to-weak flips}. */ + private static final HashMap holders = new HashMap<>(); + private static final HashMap typeNames = new HashMap<>(); + static long nativeListStores; + static long listsAdopted; + static long itemsAdopted; + + // deltas + static long stubsStrong; + static long stubsWeak; + static long strongToWeak; + static long strongToWeakInDrain; + static long weakToStrong; + static long weakToStrongInDrain; + static long releasedDirect; + static long tableWrites; + static final BitSet dirtyCards = new BitSet(); + static long drainedPOR; + static long drainedNOR; + static long drainedNSR; + static long drainedOther; + static long stubsFreed; + static long storagesToNative; + static long storagesToNativeEmpty; + static long storageItems; + static long tuplesToNative; + static long listsToNative; + static long listTraverseConversions; + static long nativeDeallocs; + // totals + static long forcedNativeMemory; + static long nativeMemoryDrainOnly; + static long forcedBackground; + static long forcedPython; + static int drainDepth; + private static long lastGcCount = -1; + private static long lines; + + private CApiGCStats() { + } + + public static void setEnabled(boolean value) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + enabled = value; + countUpcalls = value; + } + + private static final String[] upcallStack = new String[64]; + private static int upcallDepth; + /** Wrappers created for native objects, by "type <- upcall in progress": {count}. */ + private static final HashMap wrapperOrigins = new HashMap<>(); + + @TruffleBoundary + public static void upcallExit() { + if (upcallDepth > 0) { + upcallDepth--; + } + } + + /** A Java wrapper is created for the native object at {@code pointer}. */ + @TruffleBoundary + static void wrapperCreated(long pointer) { + String upcall = upcallDepth == 0 ? "" : upcallDepth > upcallStack.length ? "" : upcallStack[upcallDepth - 1]; + wrapperOrigins.computeIfAbsent(typeName(pointer) + "<-" + upcall, k -> new long[1])[0]++; + } + + @TruffleBoundary + public static void upcall(int id, String name) { + if (upcallDepth < upcallStack.length) { + upcallStack[upcallDepth] = name; + } + upcallDepth++; + if (id >= upcallCounts.length) { + int n = Math.max(id + 1, upcallCounts.length * 2); + upcallCounts = java.util.Arrays.copyOf(upcallCounts, n); + upcallNames = java.util.Arrays.copyOf(upcallNames, n); + } + upcallCounts[id]++; + upcallNames[id] = name; + } + + static void listAdopted(int n) { + if (enabled) { + listsAdopted++; + itemsAdopted += n; + } + } + + /** A C API call stored into a list whose storage is native (the store takes a native reference). */ + public static void listStore(Object list) { + if (enabled) { + listStoreBoundary(list); + } + } + + @TruffleBoundary + private static void listStoreBoundary(Object list) { + if (list instanceof com.oracle.graal.python.builtins.objects.list.PList l && + l.getSequenceStorage() instanceof com.oracle.graal.python.runtime.sequence.storage.NativeSequenceStorage) { + nativeListStores++; + } + } + + /** Name of the type of a native object (tp_name), cached per type pointer. */ + @TruffleBoundary + static String typeName(long obj) { + long type = com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess.readPtrField(obj, com.oracle.graal.python.builtins.objects.cext.structs.CFields.PyObject__ob_type); + String name = typeNames.get(type); + if (name == null) { + long tpName = type == 0 ? 0 : com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess.readPtrField(type, com.oracle.graal.python.builtins.objects.cext.structs.CFields.PyTypeObject__tp_name); + StringBuilder sb = new StringBuilder(); + for (int i = 0; tpName != 0 && i < 80; i++) { + byte b = com.oracle.graal.python.runtime.nativeaccess.NativeMemory.readByte(tpName + i); + if (b == 0) { + break; + } + sb.append((char) b); + } + name = sb.length() == 0 ? "?" : sb.toString(); + typeNames.put(type, name); + } + return name; + } + + /** {@code holder} was released in a reference-queue drain and caused {@code flips} strong-to-weak flips. */ + @TruffleBoundary + static void holderReleased(String holder, long flips) { + long[] c = holders.computeIfAbsent(holder, k -> new long[2]); + c[0]++; + c[1] += flips; + } + + static long flipsInDrain() { + return strongToWeakInDrain; + } + + public static boolean isEnabled() { + return enabled; + } + + static void tableWrite(int idx) { + if (enabled) { + tableWriteBoundary(idx); + } + } + + @TruffleBoundary + private static void tableWriteBoundary(int idx) { + tableWrites++; + dirtyCards.set(idx >>> CARD_SHIFT); + } + + static void stubCreated(boolean strong) { + if (enabled) { + if (strong) { + stubsStrong++; + } else { + stubsWeak++; + } + } + } + + static void strongToWeak() { + if (enabled) { + if (drainDepth > 0) { + strongToWeakInDrain++; + } else { + strongToWeak++; + } + } + } + + static void weakToStrong() { + if (enabled) { + if (drainDepth > 0) { + weakToStrongInDrain++; + } else { + weakToStrong++; + } + } + } + + static void releasedDirect() { + if (enabled) { + releasedDirect++; + } + } + + /** + * A managed object storage was copied to native memory. "Empty" means it had no item other + * than null or the NO_VALUE placeholders of PyList_New (a list that C created and fills + * itself, e.g. with PyList_SET_ITEM); otherwise C reads or writes a filled sequence. + */ + @TruffleBoundary + public static void storageToNative(Object[] items, int length) { + storagesToNative++; + int nonNull = 0; + for (int i = 0; i < length; i++) { + // PyList_New(n) fills a new list with NO_VALUE until C stores the items + if (items[i] != null && items[i] != com.oracle.graal.python.builtins.objects.PNone.NO_VALUE) { + nonNull++; + } + } + if (nonNull == 0) { + storagesToNativeEmpty++; + } + storageItems += nonNull; + } + + /** C asked for the item array of a tuple or list; counts those whose storage is not native yet. */ + public static void sequenceItemsRequested(boolean tuple, Object storage) { + if (enabled && !(storage instanceof com.oracle.graal.python.runtime.sequence.storage.NativeSequenceStorage)) { + if (tuple) { + tuplesToNative++; + } else { + listsToNative++; + } + } + } + + /** list_traverse (tp_traverse) converted a managed list storage to native. */ + public static void listTraverseConversion() { + if (enabled) { + listTraverseConversions++; + } + } + + public static void forcedNativeMemory(boolean drainOnly) { + if (enabled) { + if (drainOnly) { + nativeMemoryDrainOnly++; + } else { + forcedNativeMemory++; + } + } + } + + public static void forcedBackground() { + if (enabled) { + forcedBackground++; + } + } + + public static void forcedPython() { + if (enabled) { + forcedPython++; + } + } + + /** + * Prints a line if at least one Java collection happened since the last line (or always, if + * {@code reason} is not {@code null}). + */ + @TruffleBoundary + public static void report(HandleContext handleContext, String reason) { + if (!enabled) { + return; + } + long young = 0; + long full = 0; + List beans = ManagementFactory.getGarbageCollectorMXBeans(); + for (int i = 0; i < beans.size(); i++) { + GarbageCollectorMXBean bean = beans.get(i); + String name = bean.getName(); + long c = bean.getCollectionCount(); + if (name.contains("omplete") || name.contains("ld") || name.contains("ull")) { + full += c; + } else { + young += c; + } + } + long gcCount = young + full; + if (reason == null && gcCount == lastGcCount) { + return; + } + long dGc = lastGcCount < 0 ? gcCount : gcCount - lastGcCount; + lastGcCount = gcCount; + + CApiNativeStub[] table = handleContext.nativeStubLookup; + long nonNull = 0; + long strongDirect = 0; + long strongRef = 0; + long weakRef = 0; + long weakDead = 0; + for (int i = 0; i < table.length; i++) { + Object e = table[i]; + if (e == null) { + continue; + } + nonNull++; + if (e instanceof PythonObjectReference ref) { + if (ref.isStrongReference()) { + strongRef++; + } else if (ref.get() == null) { + weakDead++; + } else { + weakRef++; + } + } else if (e instanceof PythonObject) { + strongDirect++; + } + } + StringBuilder sb = new StringBuilder(400); + sb.append("[capi-gc] line=").append(lines++); + sb.append(" reason=").append(reason == null ? "drain" : reason); + sb.append(" gc=").append(young).append('/').append(full).append(" dgc=").append(dGc); + sb.append(" table: len=").append(table.length).append(" used=").append(nonNull); + sb.append(" strong=").append(strongDirect).append(" strongref=").append(strongRef); + sb.append(" weak=").append(weakRef).append(" weakdead=").append(weakDead); + sb.append(" nativeLookup=").append(handleContext.nativeLookup.size()); + sb.append(" nativeStorageRefs=").append(handleContext.nativeStorageReferences.size()); + sb.append(" | delta: stubs=").append(stubsStrong).append('/').append(stubsWeak); + sb.append(" s2w=").append(strongToWeak).append(" s2wDrain=").append(strongToWeakInDrain); + sb.append(" w2s=").append(weakToStrong).append(" w2sDrain=").append(weakToStrongInDrain); + sb.append(" released=").append(releasedDirect); + sb.append(" writes=").append(tableWrites).append(" cards=").append(dirtyCards.cardinality()); + sb.append(" drained=").append(drainedPOR).append('/').append(drainedNOR).append('/').append(drainedNSR).append('/').append(drainedOther); + sb.append(" stubsFreed=").append(stubsFreed).append(" nativeDeallocs=").append(nativeDeallocs); + sb.append(" tuples/lists=").append(tuplesToNative).append('/').append(listsToNative); + sb.append(" traverseToNative=").append(listTraverseConversions); + sb.append(" toNative=").append(storagesToNative).append('/').append(storagesToNativeEmpty).append('/').append(storageItems); + sb.append(" | forced: nativeMem=").append(forcedNativeMemory).append(" nativeMemDrain=").append(nativeMemoryDrainOnly); + sb.append(" background=").append(forcedBackground).append(" python=").append(forcedPython); + sb.append(" nativeListStores=").append(nativeListStores); + sb.append(" adopted=").append(listsAdopted).append('/').append(itemsAdopted); + if (!holders.isEmpty()) { + ArrayList> hs = new ArrayList<>(holders.entrySet()); + hs.sort((a, b) -> Long.compare(b.getValue()[1] * 1000000L + b.getValue()[0], a.getValue()[1] * 1000000L + a.getValue()[0])); + sb.append(" | holders:"); + for (int i = 0; i < Math.min(8, hs.size()); i++) { + sb.append(' ').append(hs.get(i).getKey().replace(' ', '_')).append('=').append(hs.get(i).getValue()[0]).append('/').append(hs.get(i).getValue()[1]); + } + } + System.err.println(sb); + StringBuilder up = new StringBuilder("[capi-up] line=").append(lines - 1); + long total = 0; + ArrayList ids = new ArrayList<>(); + for (int i = 0; i < upcallCounts.length; i++) { + if (upcallCounts[i] != 0) { + total += upcallCounts[i]; + ids.add(i); + } + } + ids.sort((a, b) -> Long.compare(upcallCounts[b], upcallCounts[a])); + up.append(" total=").append(total); + for (int i = 0; i < Math.min(30, ids.size()); i++) { + up.append(' ').append(upcallNames[ids.get(i)]).append('=').append(upcallCounts[ids.get(i)]); + } + System.err.println(up); + if (!wrapperOrigins.isEmpty()) { + ArrayList> ws = new ArrayList<>(wrapperOrigins.entrySet()); + ws.sort((a, b) -> Long.compare(b.getValue()[0], a.getValue()[0])); + StringBuilder w = new StringBuilder("[capi-wrap] line=").append(lines - 1); + for (int i = 0; i < Math.min(12, ws.size()); i++) { + w.append(' ').append(ws.get(i).getKey().replace(' ', '_')).append('=').append(ws.get(i).getValue()[0]); + } + System.err.println(w); + wrapperOrigins.clear(); + } + java.util.Arrays.fill(upcallCounts, 0); + holders.clear(); + nativeListStores = 0; + listsAdopted = itemsAdopted = 0; + stubsStrong = stubsWeak = strongToWeak = strongToWeakInDrain = weakToStrong = weakToStrongInDrain = 0; + releasedDirect = tableWrites = 0; + dirtyCards.clear(); + drainedPOR = drainedNOR = drainedNSR = drainedOther = stubsFreed = nativeDeallocs = 0; + storagesToNative = storagesToNativeEmpty = storageItems = tuplesToNative = listsToNative = listTraverseConversions = 0; + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java index d6d8950f64..35332621d9 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java @@ -132,6 +132,7 @@ import com.oracle.graal.python.runtime.PythonContext.PythonThreadState; import com.oracle.graal.python.runtime.PythonOptions; import com.oracle.graal.python.runtime.nativeaccess.NativeMemory; +import com.oracle.graal.python.runtime.sequence.storage.NativeObjectSequenceStorage; import com.oracle.graal.python.runtime.object.PFactory; import com.oracle.graal.python.runtime.sequence.storage.NativeSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage; @@ -576,6 +577,10 @@ private static int pollReferenceQueue(PythonContext context, Reference handof } if (count == 0) { assert handleContext.referenceQueuePollingState == RQ_READY; + if (CApiGCStats.enabled) { + CApiGCStats.report(handleContext, null); + CApiGCStats.drainDepth++; + } handleContext.referenceQueuePollingState = RQ_POLLING; polling = true; start = System.nanoTime(); @@ -589,6 +594,17 @@ private static int pollReferenceQueue(PythonContext context, Reference handof LOGGER.fine(PythonUtils.formatJString("releasing %s, no remaining managed references", currentEntry)); } boolean isLoggableFiner = LOGGER.isLoggable(Level.FINER); + if (CApiGCStats.enabled) { + if (currentEntry instanceof PythonObjectReference) { + CApiGCStats.drainedPOR++; + } else if (currentEntry instanceof NativeObjectReference) { + CApiGCStats.drainedNOR++; + } else if (currentEntry instanceof NativeStorageReference) { + CApiGCStats.drainedNSR++; + } else { + CApiGCStats.drainedOther++; + } + } if (currentEntry instanceof PythonObjectReference reference) { if (HandlePointerConverter.pointsToPyHandleSpace(reference.pointer)) { assert !HandlePointerConverter.pointsToPyIntHandle(reference.pointer); @@ -611,6 +627,9 @@ private static int pollReferenceQueue(PythonContext context, Reference handof LOGGER.finer(PythonUtils.formatJString("No more references for %s (refcount->0): freeing native stub", reference)); } freeNativeStub(reference); + if (CApiGCStats.enabled) { + CApiGCStats.stubsFreed++; + } } else { if (isLoggableFiner) { LOGGER.finer(PythonUtils.formatJString("Some native references to %s remain (refcount=%d): not freeing native stub yet", reference, newRefCount)); @@ -669,7 +688,11 @@ private static int pollReferenceQueue(PythonContext context, Reference handof } } else if (currentEntry instanceof NativeStorageReference reference) { handleContext.nativeStorageReferences.remove(reference); + long before = CApiGCStats.flipsInDrain(); processNativeStorageReference(reference); + if (CApiGCStats.enabled) { + CApiGCStats.holderReleased("", CApiGCStats.flipsInDrain() - before); + } } else if (currentEntry instanceof PyCapsuleReference reference) { handleContext.pyCapsuleReferences.remove(reference); processPyCapsuleReference(reference); @@ -679,6 +702,9 @@ private static int pollReferenceQueue(PythonContext context, Reference handof if (polling && handleContext.referenceQueuePollingState == RQ_POLLING) { handleContext.referenceQueuePollingState = RQ_READY; } + if (polling && CApiGCStats.enabled) { + CApiGCStats.drainDepth--; + } } } } finally { @@ -688,6 +714,79 @@ private static int pollReferenceQueue(PythonContext context, Reference handof } } + /** + * Java takes a list that C created with {@code PyList_New} and filled with + * {@code PyList_SET_ITEM}: its native array owns a reference to every item, which would keep each + * item strongly referenced from the handle table until the list has died, a Java collection has + * found that and the reference queue has released the array (one more collection per nesting + * level). When every slot is filled, and unless C took the array itself + * ({@code PySequence_Fast_ITEMS}) or the cycle GC is running, the items' references move to a + * managed storage, so that the list holds its items with Java references. This is tried when + * Java resolves the list pointer, when C drops its last reference to the list, and, if one of + * those found empty slots, when C fills the last slot (C counts the filled slots in the stub and + * calls {@code GraalPyPrivate_List_Adopt}). Nested lists that C built the same way are adopted as + * their pointers are converted. A list that never becomes full keeps its native storage. + */ + /** + * C dropped its last reference to {@code object}: if it is a list that C built and Java never + * took, adopt its items now, so that they die together with the list. + */ + static void adoptIfCBuiltList(PythonObject object) { + if (object instanceof PList list && list.getSequenceStorage() instanceof NativeObjectSequenceStorage ns && ns.isBuiltByC()) { + adoptCBuiltList(PythonContext.get(null), list, ns); + } + } + + /** Offset of {@code GraalPyObject.graalpy_flags} (capi.h), in the padding after the handle-table index. */ + static long stubFlagsAddress(long stub) { + return CStructAccess.getFieldPtr(stub, CFields.GraalPyObject__handle_table_index) + Integer.BYTES; + } + + /** {@code GRAALPY_STUB_BUILT_BY_C} in capi.h. */ + static final int STUB_BUILT_BY_C = 2; + /** {@code GRAALPY_STUB_ADOPT_ON_FILL} in capi.h. */ + static final int STUB_ADOPT_ON_FILL = 4; + + /** Marks the stub of a list from {@code PyList_New}, so that C counts the slots it fills. */ + public static void markCBuiltListStub(long taggedPointer) { + long flags = stubFlagsAddress(HandlePointerConverter.pointerToStub(taggedPointer)); + NativeMemory.writeInt(flags, NativeMemory.readInt(flags) | STUB_BUILT_BY_C); + } + + @TruffleBoundary + static void adoptCBuiltList(PythonContext context, PList list, NativeObjectSequenceStorage storage) { + long stub = HandlePointerConverter.pointerToStub(list.getNativePointer()); + long flagsAddress = stubFlagsAddress(stub); + int flags = NativeMemory.readInt(flagsAddress); + if ((flags & 1) != 0 || !storage.hasReference()) { + // C holds the array (GRAALPY_STUB_ITEMS_EXPOSED in capi.h) + storage.setBuiltByC(false); + return; + } + if (CStructAccess.readIntField(context.getCApiContext().getGCState(), CFields.GCState__collecting) != 0) { + return; + } + int n = storage.length(); + long ptr = storage.getPtr(); + for (int i = 0; i < n; i++) { + if (NativeMemory.readLongArrayElement(ptr, i) == NULLPTR) { + // still being filled: let C call GraalPyPrivate_List_Adopt when the last slot is filled + NativeMemory.writeInt(flagsAddress, flags | STUB_ADOPT_ON_FILL); + return; + } + } + storage.setBuiltByC(false); + // C stops counting filled slots (the stub no longer mirrors a native array anyway) + NativeMemory.writeInt(flagsAddress, flags & ~STUB_BUILT_BY_C); + Object[] items = new Object[n]; + for (int i = 0; i < n; i++) { + items[i] = NativeToPythonInternalNode.executeUncached(NativeMemory.readLongArrayElement(ptr, i), true); + } + storage.giveUpItemReferences(); + list.setSequenceStorage(new com.oracle.graal.python.runtime.sequence.storage.ObjectSequenceStorage(items)); + CApiGCStats.listAdopted(n); + } + private static void logReferenceQueueDrain(HandleContext handleContext, boolean watcherHandoff, int count, long start) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(PythonUtils.formatJString( @@ -779,6 +878,9 @@ private static void releaseNativeObjects(PythonContext context, ArrayList Object savedException = CExtCommonNodes.ReadAndClearNativeException.executeUncached(threadState); try { int size = referencesToBeFreed.size(); + if (CApiGCStats.enabled) { + CApiGCStats.nativeDeallocs += size; + } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(PythonUtils.formatJString("releasing %d NativeObjectReference instances", size)); } @@ -787,8 +889,20 @@ private static void releaseNativeObjects(PythonContext context, ArrayList NativeMemory.writeLongArrayElement(pointer, i, referencesToBeFreed.get(i)); } try { - ExternalFunctionInvoker.invokeBULK_DEALLOC( - CApiContext.getNativeSymbol(null, NativeCAPISymbol.FUN_BULK_DEALLOC).getAddress(), pointer, size); + if (CApiGCStats.enabled) { + // one at a time, so that the flips each deallocation causes can be attributed + for (int i = 0; i < size; i++) { + long obj = referencesToBeFreed.get(i); + String holder = CApiGCStats.typeName(obj); + long before = CApiGCStats.flipsInDrain(); + ExternalFunctionInvoker.invokeBULK_DEALLOC( + CApiContext.getNativeSymbol(null, NativeCAPISymbol.FUN_BULK_DEALLOC).getAddress(), pointer + 8L * i, 1); + CApiGCStats.holderReleased(holder, CApiGCStats.flipsInDrain() - before); + } + } else { + ExternalFunctionInvoker.invokeBULK_DEALLOC( + CApiContext.getNativeSymbol(null, NativeCAPISymbol.FUN_BULK_DEALLOC).getAddress(), pointer, size); + } } catch (Throwable t) { throw CompilerDirectives.shouldNotReachHere(t); } @@ -1307,6 +1421,7 @@ private static int nativeStubLookupPut(HandleContext context, int idx, CApiNativ assert value instanceof PythonObject || value instanceof PythonObjectReference || CApiContext.isSpecialSingleton(value); assert context.nativeStubLookup[idx] == null || context.nativeStubLookup[idx] == value; context.nativeStubLookup[idx] = value; + CApiGCStats.tableWrite(idx); if (PythonContext.DEBUG_CAPI) { CApiNativeStub prev = HandleContext.putShadowTable(context.nativeStubLookupShadowTable, pointer, value); if (prev != null && prev != value) { @@ -1322,6 +1437,7 @@ private static int nativeStubLookupReplaceByWeak(HandleContext context, int idx, assert HandlePointerConverter.pointsToPyHandleSpace(pointer); assert context.nativeStubLookup[idx] == value.get(); context.nativeStubLookup[idx] = value; + CApiGCStats.tableWrite(idx); if (PythonContext.DEBUG_CAPI) { CApiNativeStub prev = HandleContext.putShadowTable(context.nativeStubLookupShadowTable, pointer, value); if (prev != value.get()) { @@ -1341,6 +1457,7 @@ public static CApiNativeStub nativeStubLookupRemove(HandleContext context, int i CApiNativeStub result = context.nativeStubLookup[idx]; assert result instanceof PythonObjectReference || result instanceof PythonObject || CApiContext.isSpecialSingleton(result); context.nativeStubLookup[idx] = null; + CApiGCStats.tableWrite(idx); context.nativeStubLookupFreeStack.push(idx); if (PythonContext.DEBUG_CAPI && HandleContext.removeShadowTable(context.nativeStubLookupShadowTable, result) != result) { throw CompilerDirectives.shouldNotReachHere(); @@ -1630,6 +1747,7 @@ static long doGeneric(Node inliningTarget, PythonAbstractObject object, Object t ref = PythonObjectReference.createStub(handleContext, (PythonObject) object, false, taggedPointer, idx, gc); } nativeStubLookupPut(handleContext, idx, ref, taggedPointer); + CApiGCStats.stubCreated(initialRefCount > MANAGED_REFCNT); } catch (OverflowException e) { /* * The OverflowException may be thrown by 'nativeStubLookupReserve' and indicates @@ -2278,6 +2396,9 @@ static Object doGeneric(Node inliningTarget, long pointer, boolean needsTransfer CompilerDirectives.transferToInterpreterAndInvalidate(); throw CompilerDirectives.shouldNotReachHere("reference was collected: " + Long.toHexString(pointer)); } + if (result instanceof PList list && list.getSequenceStorage() instanceof NativeObjectSequenceStorage ns && ns.isBuiltByC()) { + adoptCBuiltList(pythonContext, list, ns); + } } else { IdReference lookup = nativeLookupGet(handleContext, pointer); PythonThreadState threadState = pythonContext.getThreadState(pythonContext.getLanguage()); @@ -2755,6 +2876,9 @@ public static void writeNativeRefCount(long pointer, long newValue) { } private static PythonAbstractNativeObject createAbstractNativeObject(PythonContext pythonContext, PythonThreadState threadState, HandleContext handleContext, boolean transfer, long pointer) { + if (CApiGCStats.enabled) { + CApiGCStats.wrapperCreated(pointer); + } pollReferenceQueueIfPending(pythonContext); PythonAbstractNativeObject result = new PythonAbstractNativeObject(pointer); long refCntDelta = MANAGED_REFCNT - (transfer ? 1 : 0); @@ -2978,17 +3102,21 @@ static void handlePythonObjectReference(Node inliningTarget, PythonObjectReferen logWeakToStrong(taggedPointer, handleTableIndex, pythonObject); } pythonObjectReference.setStrongReference(pythonObject); + CApiGCStats.weakToStrong(); if (pythonObjectReference.gc) { gcTrackNode.executeOp(inliningTarget, taggedPointer); } } else if (!setStrong && pythonObjectReference.isStrongReference()) { + CApiGCStats.strongToWeak(); if (isLoggable) { logStrongToWeak(taggedPointer, handleTableIndex, pythonObjectReference.strongReference); } if (!keepInGcList && pythonObjectReference.gc) { gcListRemoveNode.executeOp(inliningTarget, taggedPointer); } + PythonObject referent = pythonObjectReference.strongReference; pythonObjectReference.setStrongReference(null); + adoptIfCBuiltList(referent); } } @@ -3016,7 +3144,9 @@ static void makeDirectReferenceWeak(Node inliningTarget, HandleContext handleCon */ assert gc || pythonObject.getRefCount() == MANAGED_REFCNT; + CApiGCStats.strongToWeak(); if (release) { + CApiGCStats.releasedDirect(); if (pythonObject instanceof PString stringObject && !stringObject.isMaterialized()) { /* * The native companion is about to be released, so materialization must not @@ -3047,6 +3177,7 @@ static void makeDirectReferenceWeak(Node inliningTarget, HandleContext handleCon if (!keepInGcList && gc) { gcListRemoveNode.executeOp(inliningTarget, pythonObject.getNativePointer()); } + adoptIfCBuiltList(pythonObject); } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java index e5f6c45b92..c0d3d481f0 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java @@ -1916,6 +1916,9 @@ static NativeSequenceStorage doObject(Object[] arr, int length, boolean createRe @Cached(inline = false) CStructAccess.WriteObjectNewRefNode write) { long memPtr = callocPtrArray(arr.length + 1L); write.writeArray(memPtr, arr, length, 0, 0); + if (com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.isEnabled()) { + com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiGCStats.storageToNative(arr, length); + } return NativeObjectSequenceStorage.create(memPtr, length, arr.length, createRef); } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonOptions.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonOptions.java index f748426cca..aa652e2450 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonOptions.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonOptions.java @@ -384,6 +384,9 @@ private PythonOptions() { @Option(category = OptionCategory.INTERNAL, usageSyntax = "true|false", help = "Whether the background GC task should be enabled (default) or not.") // public static final OptionKey BackgroundGCTask = new OptionKey<>(true); + @Option(category = OptionCategory.INTERNAL, usageSyntax = "true|false", help = "Print counters of the C API object tracking (handle table, strong/weak transitions, reference-queue drains, forced collections) after each Java collection, to stderr. For diagnosing GC cost.") // + public static final OptionKey CApiGCStats = new OptionKey<>(false); + @Option(category = OptionCategory.INTERNAL, usageSyntax = "