From 2b9454bc19d62cec6e0a750febbaa7198df409ac Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sun, 29 Nov 2026 00:18:37 +0100 Subject: [PATCH 01/10] Add counters of the C API object tracking behind --python.CApiGCStats One line on stderr per reference-queue drain that follows a Java collection, and after each collection that GraalPy forces: handle-table size and its strong, weak and dead-weak entries, stubs created, strong/weak flips (and the flips caused by the drain itself), distinct table cards written, references drained by kind, native storages created, and forced collections by trigger. Off by default. Adds the option set capi-stats to codspeed-diagnose.txt. --- .github/elide/codspeed-diagnose.txt | 5 + .../builtins/modules/GcModuleBuiltins.java | 5 + .../modules/cext/PythonCextBuiltins.java | 6 + .../modules/cext/PythonCextListBuiltins.java | 2 + .../modules/cext/PythonCextSlotBuiltins.java | 3 + .../objects/cext/capi/CApiContext.java | 6 + .../cext/capi/transitions/CApiGCStats.java | 305 ++++++++++++++++++ .../capi/transitions/CApiTransitions.java | 32 ++ .../objects/common/SequenceStorageNodes.java | 3 + .../graal/python/runtime/PythonOptions.java | 3 + 10 files changed, 370 insertions(+) create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiGCStats.java diff --git a/.github/elide/codspeed-diagnose.txt b/.github/elide/codspeed-diagnose.txt index b90f5e40d9..ece389b823 100644 --- a/.github/elide/codspeed-diagnose.txt +++ b/.github/elide/codspeed-diagnose.txt @@ -18,3 +18,8 @@ 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 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..db285d7821 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) { 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..866f2e1f12 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; @@ -413,6 +414,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..2bbfdb0c07 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,7 @@ public CApiContext(PythonContext context, NativeLibrary library, NativeLibraryLo Arrays.fill(singletonNativePtrs, UNINITIALIZED); this.gcTask = new BackgroundGCTask(context); + CApiGCStats.setEnabled(context.getOption(PythonOptions.CApiGCStats)); this.referenceQueueWatcherTask = new ReferenceQueueWatcherTask(context); } @@ -789,6 +791,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..ec28f5f4e8 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiGCStats.java @@ -0,0 +1,305 @@ +/* + * 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.BitSet; +import java.util.List; + +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; + + // 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; + } + + 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); + System.err.println(sb); + 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..8f323d1e4f 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 @@ -576,6 +576,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 +593,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 +626,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)); @@ -679,6 +697,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 { @@ -779,6 +800,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)); } @@ -1307,6 +1331,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 +1347,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 +1367,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 +1657,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 @@ -2978,10 +3006,12 @@ 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); } @@ -3016,7 +3046,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 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..de92102aae 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 = "