From f52404afdadc511e9532785c6d5c96fb038369bf Mon Sep 17 00:00:00 2001 From: Paul Fournillon Date: Fri, 23 Oct 2026 14:23:18 +0200 Subject: [PATCH 01/20] Fix reference-chain revisits and leak candidate admission --- ddprof-lib/src/main/cpp/livenessTracker.cpp | 31 ++++-- .../src/main/cpp/referenceChainAnchors.cpp | 31 ++++-- .../src/main/cpp/referenceChainTraversal.cpp | 24 ++++- .../src/main/cpp/referenceChainWalk.cpp | 10 +- ddprof-lib/src/main/cpp/referenceChains.h | 24 +++-- .../src/test/cpp/livenessTracker_ut.cpp | 78 ++++++++++++++ .../src/test/cpp/referenceChainsBfsTests.inc | 100 ++++++++++++++++++ .../test/cpp/referenceChainsTestAccessors.h | 8 ++ 8 files changed, 274 insertions(+), 32 deletions(-) diff --git a/ddprof-lib/src/main/cpp/livenessTracker.cpp b/ddprof-lib/src/main/cpp/livenessTracker.cpp index 5d6f895832..b35d758c62 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.cpp +++ b/ddprof-lib/src/main/cpp/livenessTracker.cpp @@ -877,15 +877,30 @@ void LivenessTracker::insertThreadGen(KlassCountScratch &scratch, return; } } + int idx; if (scratch.thread_count < KlassCountScratch::MAX_THREADS_PER_KLASS) { - int idx = scratch.thread_count++; - scratch.threads[idx].tid = tid; - scratch.threads[idx].ages[0] = age; - scratch.threads[idx].age_count = 1; - scratch.threads[idx].count = 1; // this object is the tid's first this epoch - } - // else: thread table full — additional threads are not tracked, but - // the oldest[] array still captures instances from all threads. + idx = scratch.thread_count++; + } else { + // Keeping only the first tids hides later, larger one-shot cohorts behind + // early small allocations. Replace the smallest observed retained set; + // ties prefer keeping the tid with more distinct surviving ages. + idx = 0; + for (int i = 1; i < scratch.thread_count; i++) { + const auto &candidate = scratch.threads[i]; + const auto &victim = scratch.threads[idx]; + if (candidate.count < victim.count || + (candidate.count == victim.count && candidate.age_count < victim.age_count)) { + idx = i; + } + } + } + // Count only objects observed since this tid entered the scratch. Inherit + // neither the evicted tid's count nor its ages: both feed qualification. + // Reappearing tids can be undercounted at capacity, never overcounted. + scratch.threads[idx].tid = tid; + scratch.threads[idx].ages[0] = age; + scratch.threads[idx].age_count = 1; + scratch.threads[idx].count = 1; } void LivenessTracker::accumulateKlassCount(u32 klass_id, jlong age, diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index ab226c6c21..e59f640680 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -148,11 +148,11 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { // fair pick vector here and is skipped at consumption time via fresh_kept_tags). for (size_t i = 0; i < idx_size; i++) { jlong tag = _static_anchor_index[i]; + jlong own_class_tag = i < _static_anchor_own_class_tags.size() + ? _static_anchor_own_class_tags[i] : 0; FrontierEntry entry{}; if (!frontier->lookupLocked(tag, &entry) || - entry.parent_tag != 0 || - (entry.root_kind != (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD && - entry.root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) || + !isSelectableAnchor(entry, own_class_tag) || (entry.state != FrontierEntryState::FRONTIER && entry.state != FrontierEntryState::EXPANDED) || isQueuedForRotation(tag)) { @@ -201,15 +201,15 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { } pos = (size_t)(it - _static_anchor_index.begin()); } + jlong own_class_tag = pos < _static_anchor_own_class_tags.size() + ? _static_anchor_own_class_tags[pos] : 0; FrontierEntry entry{}; if (!frontier->lookupLocked(tag, &entry) || - entry.parent_tag != 0 || - (entry.root_kind != (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD && - entry.root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) || + !isSelectableAnchor(entry, own_class_tag) || (entry.state != FrontierEntryState::FRONTIER && entry.state != FrontierEntryState::EXPANDED) || isQueuedForRotation(tag) || entry.leak_tag != 0) { - continue; // dead/demoted/queued/leak-tier: first look spent, not + continue; // dead/ineligible/queued/leak-tier: first look spent, not // fresh-kept (the leak tier selects it via the scan if it is leak-tagged) } bool keep = false; // container or not-yet-classified rides the @@ -333,6 +333,23 @@ void ReferenceChainTracker::addToStaticAnchorIndex(jlong tag, root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { return; } + indexAnchorForRotation(tag, own_class_tag); +} + +bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, + jlong own_class_tag) const { + if (entry.parent_tag == 0 && + (entry.root_kind == (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD || + entry.root_kind == (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL)) { + return true; + } + auto shape = _class_shape_cache.find(own_class_tag); + return shape != _class_shape_cache.end() && + shape->second == (u8)AnchorClassShape::CONTAINER; +} + +void ReferenceChainTracker::indexAnchorForRotation(jlong tag, + jlong own_class_tag) { // Dedup: a push at first admission and another at upgrade would double-add. if (!_static_anchor_index_tags.insert(tag).second) { return; diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 3115479e20..78a9066338 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -134,6 +134,18 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( default: break; } + // Remember local holders before expansion can reparent them into a deeper + // chain. Known collections still need bounded descend walks after that change + // to observe replacement backing storage. Classification runs outside this + // callback; unknown types are indexed but do not qualify for a walk yet. + if (isTransientRootKind(translated_root_kind) && class_tag != 0 && + *tag_ptr > 0 && !isLeakTag(*tag_ptr)) { + auto shape = ctx->tracker->_class_shape_cache.find(class_tag); + if (shape == ctx->tracker->_class_shape_cache.end() || + shape->second == (u8)AnchorClassShape::CONTAINER) { + ctx->tracker->indexAnchorForRotation(*tag_ptr, class_tag); + } + } return JVMTI_ITERATION_CONTINUE; } @@ -388,7 +400,12 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, std::vector static_anchor_fifo_drained; drainStaticAnchorFifo(STATIC_ANCHOR_FIFO_DRAIN, static_anchor_fifo_drained); for (const AtRiskAnchor &at_risk : static_anchor_fifo_drained) { - static_anchor_tags.push_back(at_risk.tag); + // A reparented collection can also have been selected by the persistent + // container tier. The combined selection is bounded by 48 + 16 entries. + if (std::find(static_anchor_tags.begin(), static_anchor_tags.end(), + at_risk.tag) == static_anchor_tags.end()) { + static_anchor_tags.push_back(at_risk.tag); + } } if (rotation_tags.empty() && leak_accumulation_tags.empty() && stale_expanded_tags.empty() && static_anchor_tags.empty()) { @@ -1070,6 +1087,11 @@ bool ReferenceChainTracker::runPass(jvmtiEnv *jvmti, JNIEnv *jni, if (manual_first_pass) { _search_started = true; store(_search_start_ns, OS::nanotime()); + // Register the candidates that triggered this search before walking. The + // first pass can drain the frontier; without a watched klass it would then + // complete and release its tags before the loop's post-pass poll can + // reconstruct any chain or schedule candidate-scoped walks. + pollWatchedTargets(jvmti, jni); } // Root/stack-ref enumeration alone never discovers a root's transitive children diff --git a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp index 0d2fd3d585..f521e186b6 100644 --- a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp @@ -446,9 +446,9 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // This new path is deeper - replace the shallow root-attached entry with the deeper // chain-attached entry. u32 referrer_klass = ctx->tracker->classTags()->resolve(class_tag); - // Pre-read the CURRENT shape: if improveChain() below succeeds, this root-attached durable - // entry is about to be replaced with a deeper chain-attached one - i.e. it is leaving the - // population collectStaticFieldAnchorsForRotation() can select, at exactly this moment. + // Pre-read the CURRENT shape: improveChain() can remove this entry's + // durable-root eligibility. A known collection remains in the container + // tier; other holders need the FIFO's first look below. FrontierEntry pre_improve_entry{}; bool was_root_attached_durable = ctx->frontier->lookup(*tag_ptr, &pre_improve_entry) && @@ -464,8 +464,8 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( *tag_ptr, ctx->resolved_chain_tags, ctx->resolved_chain_tag_count); if (was_root_attached_durable) { - // Demotion push: the replaced entry's static/JNI-global attribution was its only - // anchor-tier eligibility, and it is gone now. + // Ensure a first look even when class-shape reconciliation has not + // yet classified this reparented holder as a collection. ctx->tracker->pushAtRiskStaticAnchor( *tag_ptr, ctx->tracker->classTags()->resolve(class_tag)); } diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index c6a4dd3cd2..6682725d35 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -488,10 +488,8 @@ class ReferenceChainTracker { } } _priority_expand_set; - // A static holder richly referenced from the running graph is EXCLUDED from the static-anchor tier forever once its - // frontier entry is chain-attached (first admitted via a non-root path, or demoted by - // improveChain) - maybeUpgradeRootAttachedRootKind() refuses entries with parent_tag != 0 by - // design, so collectStaticFieldAnchorsForRotation() (parent_tag == 0 filter) can never select it. + // Chain-attached holders without a known collection shape need a first + // descend walk when a static edge or reparenting removes their root eligibility. struct AtRiskAnchor { jlong tag; u32 klass_id; @@ -511,13 +509,14 @@ class ReferenceChainTracker { std::unordered_map _static_anchor_fifo_klass_counts; static constexpr u32 STATIC_ANCHOR_ATRISK_PER_KLASS_CAP = 64; - // Index of root-attached STATIC_FIELD/JNI_GLOBAL frontier entries, so - // collectStaticFieldAnchorsForRotation() iterates O(anchors) instead of scanning the full - // frontier table O(frontier_size). + // Index of durable roots and observed local holders. Known collections remain + // eligible after reparenting, so replacing their storage is still observed. + // Non-collection local holders are excluded after classification. + // collectStaticFieldAnchorsForRotation() iterates these anchors rather than + // scanning the full frontier table. std::vector _static_anchor_index; - // Parallel to _static_anchor_index: the OWN class tag of each anchor object (the class of the - // static field's VALUE, not the holder class). + // Parallel to _static_anchor_index: the runtime class tag of each indexed holder. std::vector _static_anchor_own_class_tags; // Dedup companion for _static_anchor_index (O(1) membership; the population is ~28k on a real JVM @@ -1076,14 +1075,17 @@ class ReferenceChainTracker { int *edges_admitted, bool *truncated, bool *frontier_cap_hit, u64 *safepoint_ns); - // Selects root-attached durable entries with a tiered cursor: leak-tagged, fresh, container-shaped, - // then everything else fairly. + // Selects durable roots and indexed collections (including reparented ones) + // with a tiered cursor: leak-tagged, fresh, containers, then other roots fairly. std::vector collectStaticFieldAnchorsForRotation(int max_count); + bool isSelectableAnchor(const FrontierEntry &entry, jlong own_class_tag) const; // At-risk anchor push: deduped, capped, and quota-limited per klass. void pushAtRiskStaticAnchor(jlong tag, u32 klass_id); // Add `tag` to _static_anchor_index if its root_kind is a durable anchor-tier kind (STATIC_FIELD // or JNI_GLOBAL). void addToStaticAnchorIndex(jlong tag, jlong own_class_tag, u8 root_kind); + // Shared deduplicated index insertion for durable roots and local holders. + void indexAnchorForRotation(jlong tag, jlong own_class_tag); // True iff `klass` implements java/util/Collection or java/util/Map, directly or transitively // (superclass chain + interfaces of every visited class, depth-bounded, visited set to survive diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index a7497a86ed..197f1a150e 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1094,6 +1094,22 @@ TEST_F(SelectLeakCandidatesTest, TopKlassesByGenerationCountEmptyTableReturnsZer // Reaches the private state onGC()'s container-usage gate depends on. class LivenessTrackerTestAccessor { public: + // Exercise the production per-thread accumulator and fold without synthetic + // tid histories. Each pair describes a one-cohort allocating thread. + static void recordThreadCohorts( + LivenessTracker *t, int slot, + const std::vector> &cohorts) { + LivenessTracker::KlassCountScratch scratch{}; + for (const auto &cohort : cohorts) { + for (u32 i = 0; i < cohort.second; i++) { + t->insertThreadGen(scratch, cohort.first, /*age=*/1); + } + } + t->_table_lock.lock(); + t->recordTidTrendSamplesLocked(slot, scratch); + t->_table_lock.unlock(); + } + // Runs one onGC() with the given _container_limit_resolved value and returns the // container usage it recorded. Restores the touched fields afterwards. static u64 containerUsageRecordedByOnGC(LivenessTracker *t, bool limit_resolved) { @@ -1288,6 +1304,68 @@ class LivenessTrackerTestAccessor { } }; +TEST_F(SelectLeakCandidatesTest, LateAllocatingThreadCanQualifyAfterScratchFills) { + LivenessTracker *tracker = LivenessTracker::instance(); + std::vector> cohorts; + for (int tid = 1; tid <= 16; tid++) { + cohorts.emplace_back(tid, 1); + } + // The larger, later worker must not be permanently hidden behind the first + // 16 workers. All its objects share one GC age, as in the external cache test. + cohorts.emplace_back(99, 12); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + LivenessTrackerTestAccessor::recordThreadCohorts(tracker, slot, cohorts); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + ASSERT_EQ(1, out[0].qualifying_tid_count); + EXPECT_EQ(99, out[0].qualifying_tids[0]); +} + +TEST_F(SelectLeakCandidatesTest, ScratchOverflowDoesNotInventRetainedInstances) { + LivenessTracker *tracker = LivenessTracker::instance(); + std::vector> cohorts; + for (int tid = 1; tid <= 40; tid++) { + // Below the retained-count bar, with a flat one-age history: replacing + // another tid must never transfer its counts to the incoming worker. + cohorts.emplace_back(tid, 7); + } + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + LivenessTrackerTestAccessor::recordThreadCohorts(tracker, slot, cohorts); + } + KlassCandidate out[5]; + EXPECT_EQ(0, tracker->selectLeakCandidates(out, 5)); +} + +TEST_F(SelectLeakCandidatesTest, ScratchOverflowPreservesStrongEarlyThreads) { + LivenessTracker *tracker = LivenessTracker::instance(); + std::vector> cohorts; + for (int tid = 1; tid <= 16; tid++) { + cohorts.emplace_back(tid, 12); + } + for (int tid = 17; tid <= 40; tid++) { + cohorts.emplace_back(tid, 1); + } + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + LivenessTrackerTestAccessor::recordThreadCohorts(tracker, slot, cohorts); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + ASSERT_GT(out[0].qualifying_tid_count, 0); + for (int i = 0; i < out[0].qualifying_tid_count; i++) { + EXPECT_LE(out[0].qualifying_tids[i], 16); + } +} + TEST(LivenessTrackerSessionTest, ResetSessionClearsOnlyRecordingGates) { LivenessTracker *tracker = LivenessTracker::instance(); LivenessTrackerTestAccessor::setSessionGatesForTest( diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index 576bd4bc9d..ab85beabff 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -5,6 +5,7 @@ #include "referenceChainsTestAccessors.h" #include "referenceChainsMockHeap.h" +#include "referenceChainInternal.h" #include "tsc.h" @@ -539,6 +540,105 @@ TEST_F(ReferenceChainsBfsTest, DiscoversObjectRetainedOnlyByStaticField) { tracker->stop(); } +// A qualifying population must be watched before the first walk can decide the +// search is complete. Polling only afterwards loses the frontier and tags. +TEST_F(ReferenceChainsBfsTest, FirstPassWatchesQualifiedLeakBeforeCompleting) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + LivenessTracker *liveness = LivenessTracker::instance(); + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(true); + liveness->classMapGenerationSetForTest( + Profiler::instance()->classMap()->generation()); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + liveness->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + liveness->tidTrendRecordForTest(1, 4242, epoch, epoch); + } + // Production mints this from the sampled class; the gtest population seam + // has no live JVM from which to resolve it. + liveness->klassPopulationSetStableClassTagForTest(1, -41); + int root = addNode(); + script = {{JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, root, -1}}; + + // Do not explicitly poll: this is the ordering exercised by the production + // first pass, including a walk that drains its entire ordinary queue. + EXPECT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni)); + EXPECT_EQ(SearchState::RUNNING, tracker->searchState()); + EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); + EXPECT_NE(0, node_tags[root]); + + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(false); + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMutation) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + int holder = addNode(); + int parent = addNode(); + int table = addNode(); + int payload = addNode(); + node_tags[holder] = tracker->nextTag(); + node_tags[parent] = tracker->nextTag(); + const jlong container_class_tag = -101; + ReferenceChainsTestAccessor::primeClassShapeForTest(-102, false); + for (int node : {holder, parent}) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + tracker->frontierTable(), node_tags[node], 0, 0, + FrontierEntryState::EXPANDED, JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + } + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = tracker->frontierTable(); + ctx.hop_cap = 64; + ctx.budget = 1000; + for (int repeat = 0; repeat < 2; repeat++) { + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, container_class_tag, + &node_tags[holder], &ctx); + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, -102, &node_tags[parent], &ctx); + } + // Classification runs outside the heap callback. Unknown transient roots + // must not get a descend walk before being confirmed as containers. + EXPECT_TRUE(ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class_tag, true); + // A deeper retaining path replaces the initial local-root attribution. + // The container still needs repeated walks when its backing storage changes. + ASSERT_TRUE(tracker->frontierTable()->improveChain( + node_tags[holder], node_tags[parent], 0, 1, 0)); + ReferenceChainsTestAccessor::clearPriorityExpand(); + auto selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_EQ(std::vector{node_tags[holder]}, selected); + int edges = 0; + ReferenceChainsTestAccessor::walkStaticFieldAnchorsForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges); + + // Mutate AFTER that first walk. No second root callback re-admits the + // holder, and the fresh-anchor lane has already consumed its first look. + const jlong leak_tag = ReferenceChainsTestAccessor::leakTagBase(); + node_tags[payload] = leak_tag; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, holder, table, -1}, + {JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, table, payload, -1}, + }; + selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_EQ(std::vector{node_tags[holder]}, selected); + ReferenceChainsTestAccessor::walkStaticFieldAnchorsForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges); + EXPECT_GT(tags_ever_assigned[table], 0); + EXPECT_GT(tags_ever_assigned[payload], 0); + EXPECT_NE(leak_tag, node_tags[payload]); + tracker->stop(); +} + // Regression test for the resolveLoadedClasses() scan-skip guard: it must compare `class_count != // _last_resolved_class_count`, not `class_count > _last_resolved_class_count`. TEST_F(ReferenceChainsBfsTest, ResolveLoadedClassesRescansAfterClassCountShrinksAndPartiallyRegrows) { diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index 3e7e7f94f4..fc4ac51f34 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -991,6 +991,14 @@ class ReferenceChainsTestAccessor { t->_priority_expand.end()); } + // Report a root without running a whole pass, so its scheduling effect can + // be checked independently of the ordinary rotation collectors. + static jvmtiIterationControl reportHeapRootForTest( + jvmtiHeapRootKind kind, jlong class_tag, jlong *tag, void *context) { + return ReferenceChainTracker::heapRootCallback(kind, class_tag, 0, tag, + context); + } + // Simulates a tag left in _priority_expand by a prior pass's truncated expandFrontier() // batch without a full expandFrontier()/JVMTI round-trip. static void pushPriorityExpand(jlong tag) { From 7bb0c889400f797b6e2e2f9b0dca69f2f99f0a44 Mon Sep 17 00:00:00 2001 From: Paul Fournillon Date: Fri, 23 Oct 2026 15:57:02 +0200 Subject: [PATCH 02/20] Index durable holders and stabilize reference-chain test prerequisites --- ddprof-lib/src/main/cpp/javaApi.cpp | 3 +- ddprof-lib/src/main/cpp/livenessTracker.cpp | 13 +- ddprof-lib/src/main/cpp/livenessTracker.h | 15 ++- .../src/main/cpp/referenceChainTraversal.cpp | 6 + .../src/main/cpp/referenceChainWalk.cpp | 9 +- ddprof-lib/src/main/cpp/referenceChains.h | 2 +- .../src/test/cpp/livenessTracker_ut.cpp | 47 +++++++ .../test/cpp/referenceChainsAnchorTests.inc | 115 ++++++++++++++++++ .../test/cpp/referenceChainsTestAccessors.h | 8 ++ .../referencechains/LeakingCacheScenario.java | 18 ++- 10 files changed, 221 insertions(+), 15 deletions(-) diff --git a/ddprof-lib/src/main/cpp/javaApi.cpp b/ddprof-lib/src/main/cpp/javaApi.cpp index 5bb651e8ac..c3082ada8a 100644 --- a/ddprof-lib/src/main/cpp/javaApi.cpp +++ b/ddprof-lib/src/main/cpp/javaApi.cpp @@ -1232,7 +1232,8 @@ Java_com_datadoghq_profiler_JavaProfiler_seedKlassPopulationSample0( int evicted_count = 0; LivenessTracker::instance()->klassPopulationRecordForTest( (u32)klassId, (u32)count, (u64)epoch, &slot, &created, evicted, - &evicted_count, KlassPopulationEntry::MAX_REPRESENTATIVES_PER_KLASS); + &evicted_count, KlassPopulationEntry::MAX_REPRESENTATIVES_PER_KLASS, + /*synthetic_sample=*/true); for (int i = 0; i < evicted_count; i++) { if (evicted[i] != nullptr) { env->DeleteWeakGlobalRef(evicted[i]); diff --git a/ddprof-lib/src/main/cpp/livenessTracker.cpp b/ddprof-lib/src/main/cpp/livenessTracker.cpp index b35d758c62..3ddfa47a9a 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.cpp +++ b/ddprof-lib/src/main/cpp/livenessTracker.cpp @@ -960,7 +960,8 @@ void LivenessTracker::accumulateKlassCount(u32 klass_id, jlong age, jweak LivenessTracker::recordKlassPopulationSampleLocked( u32 klass_id, u32 count, u64 epoch, int *out_slot, bool *out_created, - jweak *out_evicted, int *out_evicted_count, int max_evicted) { + jweak *out_evicted, int *out_evicted_count, int max_evicted, + bool synthetic_sample) { // Linear scan is fine: MAX_KLASS_POPULATION_ENTRIES is small enough that a // full scan is cheap, the same shape NativeSocketSampler's fd LRU // (NativeSocketSampler's fd cache) and this class's own cleanup_table() @@ -1009,6 +1010,7 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( _klass_population[slot].ring_head = 0; _klass_population[slot].ring_fill = 0; _klass_population[slot].consecutive_positive = 0; + _klass_population[slot].synthetic = false; _klass_population[slot].cached_slope = 0.0; // A reused (evicted) slot's previous class's per-tid trends must not // leak onto the new one, same as the fields above. @@ -1021,6 +1023,15 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( } KlassPopulationEntry &entry = _klass_population[slot]; + if (entry.synthetic && !synthetic_sample) { + // Real GC folds must not replace a JNI test fixture's seeded ramp with + // the sampled cohort's generation count. Keep its LRU epoch current. + entry.last_updated_epoch = epoch; + *out_slot = slot; + *out_created = created; + return evicted_ref; + } + entry.synthetic = entry.synthetic || synthetic_sample; entry.count_ring[entry.ring_head] = count; entry.ring_head = (u8)((entry.ring_head + 1) % KLASS_POPULATION_RING_SIZE); if (entry.ring_fill < KLASS_POPULATION_RING_SIZE) { diff --git a/ddprof-lib/src/main/cpp/livenessTracker.h b/ddprof-lib/src/main/cpp/livenessTracker.h index 99d21b2cbd..40e738a38d 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -107,6 +107,9 @@ typedef struct KlassPopulationEntry { // without this counter it gets reported as a leak candidate almost as // often as a real leak does. u8 consecutive_positive; + // Explicit JNI test seeds own their class trend, as synthetic TidTrend + // histories do. Ordinary allocation-derived histories leave this false. + bool synthetic; // Slope (regression value at the ring's newest sample minus the value at // its oldest sample - see ringWindowStats, livenessTracker.cpp) as of the // last push, computed and cached by hasQualifyingGrowth() alongside @@ -780,7 +783,8 @@ class alignas(alignof(SpinLock)) LivenessTracker { int *out_slot, bool *out_created, jweak *out_evicted = nullptr, int *out_evicted_count = nullptr, - int max_evicted = 0); + int max_evicted = 0, + bool synthetic_sample = false); // Drains _klass_count_scratch into _klass_population for the epoch that // just finished, minting a fresh representative jweak (from each entry's @@ -1430,18 +1434,23 @@ class alignas(alignof(SpinLock)) LivenessTracker { _klass_population_size--; } + // Only explicit JNI fixture seeds set synthetic_sample: real GC folds + // preserve their ramp. The default keeps ordinary algorithm-test histories + // subject to production updates and decay. jweak klassPopulationRecordForTest(u32 klass_id, u32 count, u64 epoch, int *out_slot, bool *out_created, jweak *out_evicted = nullptr, int *out_evicted_count = nullptr, - int max_evicted = 0) { + int max_evicted = 0, + bool synthetic_sample = false) { _table_lock.lock(); klass_id = resolveTestKlassAliasLocked(klass_id); jweak evicted = recordKlassPopulationSampleLocked(klass_id, count, epoch, out_slot, out_created, out_evicted, out_evicted_count, - max_evicted); + max_evicted, + synthetic_sample); _table_lock.unlock(); return evicted; } diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 78a9066338..28fb258dae 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -134,6 +134,12 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( default: break; } + // Record durable roots even when the holder already had a frontier entry: + // neither first admission nor a retained chain path may skip the index. + if (*tag_ptr > 0 && !isLeakTag(*tag_ptr)) { + ctx->tracker->addToStaticAnchorIndex(*tag_ptr, class_tag, + translated_root_kind); + } // Remember local holders before expansion can reparent them into a deeper // chain. Known collections still need bounded descend walks after that change // to observe replacement backing storage. Classification runs outside this diff --git a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp index f521e186b6..2e4d0aab8a 100644 --- a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp @@ -491,13 +491,14 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( *tag_ptr, ctx->resolved_chain_tags, ctx->resolved_chain_tag_count); } else if (reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) { - // The upgrade refused (maybeUpgradeRootAttachedRootKind returns false for parent_tag != 0 - // by design), so this STATIC_FIELD edge just proved an at-risk static attachment the anchor - // tier's parent_tag == 0 filter can never see: a holder already admitted as a non-root - // child (find-anchor-holder-eviction). + // The sweep reached a holder first admitted through another object. + // Keep its static attachment indexed: confirmed collections must remain + // eligible after the FIFO's one-time descend walk has been consumed. FrontierEntry entry{}; if (ctx->frontier->lookup(*tag_ptr, &entry) && entry.parent_tag != 0) { + ctx->tracker->addToStaticAnchorIndex( + *tag_ptr, class_tag, (u8)reference_kind); ctx->tracker->pushAtRiskStaticAnchor( *tag_ptr, ctx->tracker->classTags()->resolve(class_tag)); } diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index 6682725d35..def995d21c 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -509,7 +509,7 @@ class ReferenceChainTracker { std::unordered_map _static_anchor_fifo_klass_counts; static constexpr u32 STATIC_ANCHOR_ATRISK_PER_KLASS_CAP = 64; - // Index of durable roots and observed local holders. Known collections remain + // Index of holders observed at durable root edges or local roots. Known collections remain // eligible after reparenting, so replacing their storage is still observed. // Non-collection local holders are excluded after classification. // collectStaticFieldAnchorsForRotation() iterates these anchors rather than diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index 197f1a150e..82f31e5b14 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1094,6 +1094,19 @@ TEST_F(SelectLeakCandidatesTest, TopKlassesByGenerationCountEmptyTableReturnsZer // Reaches the private state onGC()'s container-usage gate depends on. class LivenessTrackerTestAccessor { public: + // Fold one surviving cohort through the same path as a real GC, excluding + // representative resolution because these tests have no live JVM. + static void foldClassCohort(LivenessTracker *t, u32 klass_id, jint tid, + u64 epoch) { + t->_table_lock.lock(); + t->_klass_count_scratch_size = 0; + for (int i = 0; i < 12; i++) { + t->accumulateKlassCount(klass_id, epoch, nullptr, tid); + } + t->foldKlassCountsLocked(nullptr, epoch, false); + t->_table_lock.unlock(); + } + // Exercise the production per-thread accumulator and fold without synthetic // tid histories. Each pair describes a one-cohort allocating thread. static void recordThreadCohorts( @@ -1304,6 +1317,40 @@ class LivenessTrackerTestAccessor { } }; +TEST_F(SelectLeakCandidatesTest, SyntheticClassHistorySurvivesRealGcFolds) { + LivenessTracker *tracker = LivenessTracker::instance(); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest( + 1, epoch * 10, epoch, &slot, &created, nullptr, nullptr, 0, + /*synthetic_sample=*/true); + tracker->tidTrendRecordForTest(1, 7, epoch * 3, epoch); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + for (int epoch = 21; epoch <= 30; epoch++) { + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, epoch); + } + EXPECT_EQ(1, tracker->selectLeakCandidates(out, 5)); +} + +TEST_F(SelectLeakCandidatesTest, OrdinaryClassHistoryStillDecaysAfterGrowthStops) { + LivenessTracker *tracker = LivenessTracker::instance(); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch * 10, epoch, &slot, &created); + tracker->tidTrendRecordForTest(1, 7, epoch * 3, epoch); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + for (int epoch = 21; epoch <= 30; epoch++) { + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, epoch); + } + EXPECT_EQ(0, tracker->selectLeakCandidates(out, 5)); +} + TEST_F(SelectLeakCandidatesTest, LateAllocatingThreadCanQualifyAfterScratchFills) { LivenessTracker *tracker = LivenessTracker::instance(); std::vector> cohorts; diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index d39be8edff..d2494b57bd 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -467,6 +467,121 @@ TEST_F(ReferenceChainsBfsTest, SweepPushFiresOnStaticEdgeOntoChainAttachedHolder tracker->stop(); } +TEST_F(ReferenceChainsBfsTest, StaticFieldCollectionRemainsIndexedAfterFirstLook) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + int parent = addNode(); + int holder = addNode(); + int table = addNode(); + int payload = addNode(); + node_tags[parent] = tracker->nextTag(); + node_tags[holder] = tracker->nextTag(); + FrontierTable *frontier = tracker->frontierTable(); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[parent], 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + // The holder was first discovered through another object, before the + // one-time static-field sweep reaches it. It has never been a root. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holder], node_tags[parent], 1, + FrontierEntryState::EXPANDED, 0)); + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + const jlong holder_class_tag = -101; + jlong owner_class_tag = -102; + for (int repeat = 0; repeat < 2; repeat++) { + ReferenceChainsTestAccessor::reportHeapReferenceForTest( + JVMTI_HEAP_REFERENCE_STATIC_FIELD, holder_class_tag, + &node_tags[holder], &owner_class_tag, &ctx); + } + EXPECT_TRUE(ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + std::vector drained; + ASSERT_EQ(1, ReferenceChainsTestAccessor::drainStaticAnchorFifoForTest(16, drained)); + int edges = 0; + ReferenceChainsTestAccessor::walkStaticAnchorFifoForTest( + &mock_jvmti, &mock_jni, {drained[0].tag}, 1000, &edges, nullptr); + ASSERT_EQ(0u, ReferenceChainsTestAccessor::staticAnchorFifoSizeForTest()); + + // Classification is outside heap callbacks. Neither an unknown shape nor + // a known non-collection may enter the persistent container tier. + ReferenceChainsTestAccessor::primeClassShapeForTest(holder_class_tag, false); + EXPECT_TRUE(ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + ReferenceChainsTestAccessor::primeClassShapeForTest(holder_class_tag, true); + auto selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + ASSERT_EQ(std::vector{node_tags[holder]}, selected); + ReferenceChainsTestAccessor::walkStaticFieldAnchorsForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges); + + // Mutate after both the FIFO and fresh-lane first looks. No static-field + // edge is delivered again, so discovery requires a persistent revisit. + const jlong leak_tag = ReferenceChainsTestAccessor::leakTagBase(); + node_tags[payload] = leak_tag; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, holder, table, -1}, + {JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, table, payload, -1}, + }; + selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + ASSERT_EQ(std::vector{node_tags[holder]}, selected); + ReferenceChainsTestAccessor::walkStaticFieldAnchorsForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges); + ASSERT_GT(tags_ever_assigned[payload], 0); + EXPECT_NE(leak_tag, node_tags[payload]); + EXPECT_EQ(leak_tag, ReferenceChainsTestAccessor::frontierLeakTag(node_tags[payload])); + FrontierEntry holder_entry{}; + ASSERT_TRUE(frontier->lookup(node_tags[holder], &holder_entry)); + EXPECT_EQ(node_tags[parent], holder_entry.parent_tag); + EXPECT_EQ(1u, holder_entry.depth); + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, GlobalRootsIndexNewAndPreviouslyDiscoveredCollections) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + int parent = addNode(); + int new_holder = addNode(); + int old_holder = addNode(); + node_tags[parent] = tracker->nextTag(); + node_tags[old_holder] = tracker->nextTag(); + FrontierTable *frontier = tracker->frontierTable(); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[parent], 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[old_holder], node_tags[parent], 1, + FrontierEntryState::EXPANDED, 0)); + const jlong class_tag = -101; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + for (int repeat = 0; repeat < 2; repeat++) { + for (int holder : {new_holder, old_holder}) { + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_JNI_GLOBAL, class_tag, &node_tags[holder], &ctx); + } + } + auto selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + ASSERT_EQ(2u, selected.size()); + EXPECT_NE(selected.end(), std::find(selected.begin(), selected.end(), node_tags[new_holder])); + EXPECT_NE(selected.end(), std::find(selected.begin(), selected.end(), node_tags[old_holder])); + // Both the new root and the chain-attached collection must remain indexed + // after their fresh-lane turn, without changing the old holder's parent. + EXPECT_EQ(2u, ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).size()); + FrontierEntry old_entry{}; + ASSERT_TRUE(frontier->lookup(node_tags[old_holder], &old_entry)); + EXPECT_EQ(node_tags[parent], old_entry.parent_tag); + tracker->stop(); +} + // At-risk FIFO mechanics: a chain-attached holder drained from the at-risk FIFO is descend-walked and // intercepts a leak chunk 3 hops below it - the repair for the population the root-attached // collector demonstrably cannot select (the negative control below). diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index fc4ac51f34..f48a60f5fa 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -999,6 +999,14 @@ class ReferenceChainsTestAccessor { context); } + // Deliver an observed edge through the production heap callback. + static jint reportHeapReferenceForTest(jvmtiHeapReferenceKind kind, + jlong class_tag, jlong *tag, + jlong *referrer_tag, void *context) { + return ReferenceChainTracker::heapReferenceCallback( + kind, nullptr, class_tag, 0, 0, tag, referrer_tag, -1, context); + } + // Simulates a tag left in _priority_expand by a prior pass's truncated expandFrontier() // batch without a full expandFrontier()/JVMTI round-trip. static void pushPriorityExpand(jlong tag) { diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index 63e1c99ba1..168805d1e6 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -303,16 +303,24 @@ private static ReferenceChainAssertions.ChainMatch findMatch(Path scratchDumpPat } /** - * Realistic-leak fixture - identical shape to {@code ReferenceChainTrackingTest.CachedPayload}. - * The 32 {@code long} fields exist purely so a given number of megabytes needs far fewer entries - * to reach {@code ObjectSampler}'s real 256KiB sampling floor - deliberately plain fields, not a - * nested array (a same-instance companion array would be a second, separate heap allocation the - * size-weighted sampler would compete for, taking attention away from CachedPayload). + * Inline padding supplies sampled instances for the detector's eight-survivor per-thread + * threshold while preserving the one-shot allocator threads and number of retained objects. + * With only 32 longs, a failing release run retained at most six sampled instances per worker: + * its one-age cohorts could never qualify, regardless of traversal time. About 1KiB per payload + * provides more sampling opportunities within the same rounds at the 256KiB sampling interval. + * Plain fields keep that allocation volume on CachedPayload itself; a companion array would + * compete for samples without contributing any CachedPayload survivors. */ static final class CachedPayload { final String key; long p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15; long p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31; + long p32, p33, p34, p35, p36, p37, p38, p39, p40, p41, p42, p43, p44, p45, p46, p47; + long p48, p49, p50, p51, p52, p53, p54, p55, p56, p57, p58, p59, p60, p61, p62, p63; + long p64, p65, p66, p67, p68, p69, p70, p71, p72, p73, p74, p75, p76, p77, p78, p79; + long p80, p81, p82, p83, p84, p85, p86, p87, p88, p89, p90, p91, p92, p93, p94, p95; + long p96, p97, p98, p99, p100, p101, p102, p103, p104, p105, p106, p107, p108, p109, p110, p111; + long p112, p113, p114, p115, p116, p117, p118, p119, p120, p121, p122, p123, p124, p125, p126, p127; CachedPayload(String key) { this.key = key; From 5196c0e37378b7b41cbf28261374793c69185f9c Mon Sep 17 00:00:00 2001 From: Paul Fournillon Date: Fri, 23 Oct 2026 21:31:33 +0200 Subject: [PATCH 03/20] Isolate seeded class histories to debug test hooks --- ddprof-lib/src/main/cpp/javaApi.cpp | 9 ++-- ddprof-lib/src/main/cpp/livenessTracker.cpp | 12 +++-- ddprof-lib/src/main/cpp/livenessTracker.h | 47 ++++++++++++++----- .../src/test/cpp/livenessTracker_ut.cpp | 34 +++++++++++--- 4 files changed, 73 insertions(+), 29 deletions(-) diff --git a/ddprof-lib/src/main/cpp/javaApi.cpp b/ddprof-lib/src/main/cpp/javaApi.cpp index c3082ada8a..779972d42d 100644 --- a/ddprof-lib/src/main/cpp/javaApi.cpp +++ b/ddprof-lib/src/main/cpp/javaApi.cpp @@ -1226,14 +1226,11 @@ extern "C" DLLEXPORT void JNICALL Java_com_datadoghq_profiler_JavaProfiler_seedKlassPopulationSample0( JNIEnv *env, jclass unused, jint klassId, jint count, jlong epoch) { ProfiledThread::initCurrentThreadSignalSafe(); - int slot; - bool created; jweak evicted[KlassPopulationEntry::MAX_REPRESENTATIVES_PER_KLASS]; int evicted_count = 0; - LivenessTracker::instance()->klassPopulationRecordForTest( - (u32)klassId, (u32)count, (u64)epoch, &slot, &created, evicted, - &evicted_count, KlassPopulationEntry::MAX_REPRESENTATIVES_PER_KLASS, - /*synthetic_sample=*/true); + LivenessTracker::instance()->seedKlassPopulationSampleForTest( + (u32)klassId, (u32)count, (u64)epoch, evicted, + &evicted_count, KlassPopulationEntry::MAX_REPRESENTATIVES_PER_KLASS); for (int i = 0; i < evicted_count; i++) { if (evicted[i] != nullptr) { env->DeleteWeakGlobalRef(evicted[i]); diff --git a/ddprof-lib/src/main/cpp/livenessTracker.cpp b/ddprof-lib/src/main/cpp/livenessTracker.cpp index 3ddfa47a9a..fe00397c24 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.cpp +++ b/ddprof-lib/src/main/cpp/livenessTracker.cpp @@ -960,8 +960,7 @@ void LivenessTracker::accumulateKlassCount(u32 klass_id, jlong age, jweak LivenessTracker::recordKlassPopulationSampleLocked( u32 klass_id, u32 count, u64 epoch, int *out_slot, bool *out_created, - jweak *out_evicted, int *out_evicted_count, int max_evicted, - bool synthetic_sample) { + jweak *out_evicted, int *out_evicted_count, int max_evicted) { // Linear scan is fine: MAX_KLASS_POPULATION_ENTRIES is small enough that a // full scan is cheap, the same shape NativeSocketSampler's fd LRU // (NativeSocketSampler's fd cache) and this class's own cleanup_table() @@ -1010,7 +1009,9 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( _klass_population[slot].ring_head = 0; _klass_population[slot].ring_fill = 0; _klass_population[slot].consecutive_positive = 0; - _klass_population[slot].synthetic = false; +#ifdef DEBUG + _klass_population[slot].test_seeded_history = false; +#endif _klass_population[slot].cached_slope = 0.0; // A reused (evicted) slot's previous class's per-tid trends must not // leak onto the new one, same as the fields above. @@ -1023,7 +1024,8 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( } KlassPopulationEntry &entry = _klass_population[slot]; - if (entry.synthetic && !synthetic_sample) { +#ifdef DEBUG + if (entry.test_seeded_history) { // Real GC folds must not replace a JNI test fixture's seeded ramp with // the sampled cohort's generation count. Keep its LRU epoch current. entry.last_updated_epoch = epoch; @@ -1031,7 +1033,7 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( *out_created = created; return evicted_ref; } - entry.synthetic = entry.synthetic || synthetic_sample; +#endif entry.count_ring[entry.ring_head] = count; entry.ring_head = (u8)((entry.ring_head + 1) % KLASS_POPULATION_RING_SIZE); if (entry.ring_fill < KLASS_POPULATION_RING_SIZE) { diff --git a/ddprof-lib/src/main/cpp/livenessTracker.h b/ddprof-lib/src/main/cpp/livenessTracker.h index 40e738a38d..d01042ca5a 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -107,9 +107,11 @@ typedef struct KlassPopulationEntry { // without this counter it gets reported as a leak candidate almost as // often as a real leak does. u8 consecutive_positive; - // Explicit JNI test seeds own their class trend, as synthetic TidTrend - // histories do. Ordinary allocation-derived histories leave this false. - bool synthetic; +#ifdef DEBUG + // Explicit JNI test seeds own their class trend. Real GC folds preserve it + // until the test resets the population table or the entry is evicted. + bool test_seeded_history; +#endif // Slope (regression value at the ring's newest sample minus the value at // its oldest sample - see ringWindowStats, livenessTracker.cpp) as of the // last push, computed and cached by hasQualifyingGrowth() alongside @@ -783,8 +785,7 @@ class alignas(alignof(SpinLock)) LivenessTracker { int *out_slot, bool *out_created, jweak *out_evicted = nullptr, int *out_evicted_count = nullptr, - int max_evicted = 0, - bool synthetic_sample = false); + int max_evicted = 0); // Drains _klass_count_scratch into _klass_population for the epoch that // just finished, minting a fresh representative jweak (from each entry's @@ -1434,27 +1435,49 @@ class alignas(alignof(SpinLock)) LivenessTracker { _klass_population_size--; } - // Only explicit JNI fixture seeds set synthetic_sample: real GC folds - // preserve their ramp. The default keeps ordinary algorithm-test histories - // subject to production updates and decay. + // Ordinary algorithm-test histories remain subject to GC updates and decay. jweak klassPopulationRecordForTest(u32 klass_id, u32 count, u64 epoch, int *out_slot, bool *out_created, jweak *out_evicted = nullptr, int *out_evicted_count = nullptr, - int max_evicted = 0, - bool synthetic_sample = false) { + int max_evicted = 0) { _table_lock.lock(); klass_id = resolveTestKlassAliasLocked(klass_id); jweak evicted = recordKlassPopulationSampleLocked(klass_id, count, epoch, out_slot, out_created, out_evicted, out_evicted_count, - max_evicted, - synthetic_sample); + max_evicted); _table_lock.unlock(); return evicted; } +#ifdef DEBUG + /** + * Seeds the JNI traversal fixture's class history and protects it from real + * GC updates. Clear protection while recording another explicit seed so it + * updates the same ring and qualification counters as ordinary samples. + */ + void seedKlassPopulationSampleForTest( + u32 klass_id, u32 count, u64 epoch, jweak *out_evicted = nullptr, + int *out_evicted_count = nullptr, int max_evicted = 0) { + _table_lock.lock(); + klass_id = resolveTestKlassAliasLocked(klass_id); + for (int i = 0; i < _klass_population_size; i++) { + if (_klass_population[i].klass_id == klass_id) { + _klass_population[i].test_seeded_history = false; + break; + } + } + int slot; + bool created; + recordKlassPopulationSampleLocked(klass_id, count, epoch, &slot, &created, + out_evicted, out_evicted_count, max_evicted); + _klass_population[slot].test_seeded_history = true; + _table_lock.unlock(); + } +#endif + // Seeds one per-tid trend sample for tests/scenarios: pushes `count` as // tid's epoch sample on klass_id's KlassPopulationEntry, marking the // trend SYNTHETIC (exempt from the real fold's absent-tid decay and slot diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index 82f31e5b14..d3910d63c3 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1317,14 +1317,11 @@ class LivenessTrackerTestAccessor { } }; -TEST_F(SelectLeakCandidatesTest, SyntheticClassHistorySurvivesRealGcFolds) { +#ifdef DEBUG +TEST_F(SelectLeakCandidatesTest, SeededClassHistorySurvivesRealGcFolds) { LivenessTracker *tracker = LivenessTracker::instance(); for (int epoch = 1; epoch <= 20; epoch++) { - int slot; - bool created; - tracker->klassPopulationRecordForTest( - 1, epoch * 10, epoch, &slot, &created, nullptr, nullptr, 0, - /*synthetic_sample=*/true); + tracker->seedKlassPopulationSampleForTest(1, epoch * 10, epoch); tracker->tidTrendRecordForTest(1, 7, epoch * 3, epoch); } KlassCandidate out[5]; @@ -1333,8 +1330,33 @@ TEST_F(SelectLeakCandidatesTest, SyntheticClassHistorySurvivesRealGcFolds) { LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, epoch); } EXPECT_EQ(1, tracker->selectLeakCandidates(out, 5)); + // A fold containing only another class must also preserve the seed when + // the zero-sample pass visits classes absent from the GC scratch table. + LivenessTrackerTestAccessor::foldClassCohort(tracker, 2, 8, 31); + EXPECT_EQ(1, tracker->selectLeakCandidates(out, 5)); + KlassPopulationEntry entry; + ASSERT_TRUE(tracker->klassPopulationLookupForTest(1, &entry)); + EXPECT_EQ(31u, entry.last_updated_epoch); } +TEST_F(SelectLeakCandidatesTest, SeededClassHistoryAcceptsExplicitUpdatesAfterGc) { + LivenessTracker *tracker = LivenessTracker::instance(); + for (int epoch = 1; epoch <= 20; epoch++) { + tracker->seedKlassPopulationSampleForTest(1, epoch * 10, epoch); + tracker->tidTrendRecordForTest(1, 7, epoch * 3, epoch); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, 21); + // Protection excludes GC updates, but must not freeze subsequent explicit + // fixture input or bypass the normal qualification calculation. + for (int epoch = 22; epoch <= 51; epoch++) { + tracker->seedKlassPopulationSampleForTest(1, 0, epoch); + } + EXPECT_EQ(0, tracker->selectLeakCandidates(out, 5)); +} +#endif + TEST_F(SelectLeakCandidatesTest, OrdinaryClassHistoryStillDecaysAfterGrowthStops) { LivenessTracker *tracker = LivenessTracker::instance(); for (int epoch = 1; epoch <= 20; epoch++) { From 6c08cec85a2f3dad3ebe9aa5fa404348d5be938d Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Fri, 13 Nov 2026 15:06:47 +0100 Subject: [PATCH 04/20] referencechains: refresh indexed class tags, prune dead anchors, guard test lifecycles --- .../src/main/cpp/referenceChainAnchors.cpp | 78 ++++++++----- .../src/main/cpp/referenceChainTraversal.cpp | 22 ++-- ddprof-lib/src/main/cpp/referenceChains.cpp | 6 +- ddprof-lib/src/main/cpp/referenceChains.h | 23 ++-- .../test/cpp/referenceChainsAnchorTests.inc | 108 +++++++++++++++++- .../src/test/cpp/referenceChainsBfsTests.inc | 13 ++- .../test/cpp/referenceChainsTestAccessors.h | 42 ++++++- 7 files changed, 230 insertions(+), 62 deletions(-) diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index e59f640680..875cca2dc7 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -143,36 +143,47 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { std::unordered_set fresh_kept_tags; const size_t fresh_queue_len = _static_anchor_fresh_queue.size(); _frontier->withSharedLock([&](const FrontierTable *frontier) { - // Index scan: partition every eligible anchor into the leak tier or one of the two fair tiers - // (the fresh lane is decided by the queue drain below - a fresh-kept anchor also lands in a - // fair pick vector here and is skipped at consumption time via fresh_kept_tags). - for (size_t i = 0; i < idx_size; i++) { + // Fused prune-and-partition pass: an indexed holder whose frontier entry died is dropped from + // the index here - dead entries would otherwise accumulate for the tracker's lifetime (the + // only other removals are the stop/reset clears), and released tags get re-minted, so the + // same holder re-indexes under its fresh tag. Survivors compact down, keeping admission + // order; the tier positions below are the compacted ones the cursors consume. + size_t kept = 0; + for (size_t i = 0; i < _static_anchor_index.size(); i++) { jlong tag = _static_anchor_index[i]; - jlong own_class_tag = i < _static_anchor_own_class_tags.size() - ? _static_anchor_own_class_tags[i] : 0; FrontierEntry entry{}; - if (!frontier->lookupLocked(tag, &entry) || - !isSelectableAnchor(entry, own_class_tag) || + if (!frontier->lookupLocked(tag, &entry)) { + _static_anchor_index_class_tags.erase(tag); + continue; + } + _static_anchor_index[kept] = tag; + size_t pos = kept; + kept++; + jlong own_class_tag = 0; + auto class_it = _static_anchor_index_class_tags.find(tag); + if (class_it != _static_anchor_index_class_tags.end()) { + own_class_tag = class_it->second; + } + if (!isSelectableAnchor(entry, own_class_tag) || (entry.state != FrontierEntryState::FRONTIER && entry.state != FrontierEntryState::EXPANDED) || isQueuedForRotation(tag)) { continue; } if (entry.leak_tag != 0) { - leak_picks.push_back(TierPick{i, tag}); - } else if (i < _static_anchor_own_class_tags.size()) { - auto shape_it = - _class_shape_cache.find(_static_anchor_own_class_tags[i]); + leak_picks.push_back(TierPick{pos, tag}); + } else { + auto shape_it = _class_shape_cache.find(own_class_tag); if (shape_it != _class_shape_cache.end() && shape_it->second == (u8)AnchorClassShape::CONTAINER) { - container_picks.push_back(TierPick{i, tag}); + container_picks.push_back(TierPick{pos, tag}); } else { - other_picks.push_back(TierPick{i, tag}); + other_picks.push_back(TierPick{pos, tag}); } - } else { - other_picks.push_back(TierPick{i, tag}); } } + _static_anchor_index.resize(kept); + idx_size = kept; // Fresh-lane drain. Every queue entry is popped (its ONE first look is spent either way): kept // if eligible AND (container-shaped OR not-yet-classified) AND room remains in the budget; // dropped otherwise. @@ -201,8 +212,11 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { } pos = (size_t)(it - _static_anchor_index.begin()); } - jlong own_class_tag = pos < _static_anchor_own_class_tags.size() - ? _static_anchor_own_class_tags[pos] : 0; + jlong own_class_tag = 0; + auto class_it = _static_anchor_index_class_tags.find(tag); + if (class_it != _static_anchor_index_class_tags.end()) { + own_class_tag = class_it->second; + } FrontierEntry entry{}; if (!frontier->lookupLocked(tag, &entry) || !isSelectableAnchor(entry, own_class_tag) || @@ -215,14 +229,9 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { bool keep = false; // container or not-yet-classified rides the // lane; the wrapper admits one pass before reconcile can classify its // class - if (pos < _static_anchor_own_class_tags.size()) { - auto shape_it = - _class_shape_cache.find(_static_anchor_own_class_tags[pos]); - keep = shape_it == _class_shape_cache.end() || - shape_it->second == (u8)AnchorClassShape::CONTAINER; - } else { - keep = true; // no own-class tag recorded - treat as unknown - } + auto shape_it = _class_shape_cache.find(own_class_tag); + keep = shape_it == _class_shape_cache.end() || + shape_it->second == (u8)AnchorClassShape::CONTAINER; if (!keep) { continue; // classified non-container: the other tier owns it } @@ -351,11 +360,19 @@ bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, void ReferenceChainTracker::indexAnchorForRotation(jlong tag, jlong own_class_tag) { // Dedup: a push at first admission and another at upgrade would double-add. - if (!_static_anchor_index_tags.insert(tag).second) { + auto inserted = + _static_anchor_index_class_tags.try_emplace(tag, own_class_tag); + if (!inserted.second) { + // First sight may have seen the holder before its class was tagged + // (JVMTI reports class_tag == 0 for such roots); the callback that + // delivers the resolved tag must upgrade the stored value, or the + // container-shape fallback in isSelectableAnchor() stays dead forever. + if (own_class_tag != 0 && inserted.first->second == 0) { + inserted.first->second = own_class_tag; + } return; } _static_anchor_index.push_back(tag); - _static_anchor_own_class_tags.push_back(own_class_tag); // Walk newly admitted anchors before the fair cursors. _static_anchor_fresh_queue.push_back(tag); if (_static_anchor_fresh_queue.size() > STATIC_ANCHOR_FRESH_CAP) { @@ -494,7 +511,7 @@ void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, if (jni == nullptr) { return; } - if (_static_anchor_own_class_tags.empty()) { + if (_static_anchor_index_class_tags.empty()) { return; } // Collect up to ANCHOR_SHAPE_RECONCILE_BUDGET distinct class tags that appear in the anchor index @@ -502,7 +519,8 @@ void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, std::vector unknown; unknown.reserve(8); std::unordered_set seen; - for (jlong class_tag : _static_anchor_own_class_tags) { + for (const auto &index_entry : _static_anchor_index_class_tags) { + jlong class_tag = index_entry.second; if (class_tag == 0 || seen.count(class_tag) > 0 || _class_shape_cache.count(class_tag) > 0) { continue; diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 28fb258dae..819a93d434 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -165,6 +165,19 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::stackRefCallback( return heapRootCallback(root_kind, class_tag, size, tag_ptr, user_data); } +void ReferenceChainTracker::mergeAtRiskAnchors( + std::vector &selection, + const std::vector &drained) { + for (const AtRiskAnchor &at_risk : drained) { + // A reparented collection can also have been selected by the persistent + // container tier. The combined selection is bounded by 48 + 16 entries. + if (std::find(selection.begin(), selection.end(), at_risk.tag) == + selection.end()) { + selection.push_back(at_risk.tag); + } + } +} + void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, bool run_root_enum, int root_enum_budget, @@ -405,14 +418,7 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, collectStaticFieldAnchorsForRotation(STATIC_ANCHOR_ROTATION_BUDGET); std::vector static_anchor_fifo_drained; drainStaticAnchorFifo(STATIC_ANCHOR_FIFO_DRAIN, static_anchor_fifo_drained); - for (const AtRiskAnchor &at_risk : static_anchor_fifo_drained) { - // A reparented collection can also have been selected by the persistent - // container tier. The combined selection is bounded by 48 + 16 entries. - if (std::find(static_anchor_tags.begin(), static_anchor_tags.end(), - at_risk.tag) == static_anchor_tags.end()) { - static_anchor_tags.push_back(at_risk.tag); - } - } + mergeAtRiskAnchors(static_anchor_tags, static_anchor_fifo_drained); if (rotation_tags.empty() && leak_accumulation_tags.empty() && stale_expanded_tags.empty() && static_anchor_tags.empty()) { return; diff --git a/ddprof-lib/src/main/cpp/referenceChains.cpp b/ddprof-lib/src/main/cpp/referenceChains.cpp index db9653623a..94a71e9333 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.cpp +++ b/ddprof-lib/src/main/cpp/referenceChains.cpp @@ -1091,8 +1091,7 @@ void ReferenceChainTracker::restartSearch() { _static_anchor_fifo_set.clear(); _static_anchor_fifo_klass_counts.clear(); _static_anchor_index.clear(); - _static_anchor_own_class_tags.clear(); - _static_anchor_index_tags.clear(); + _static_anchor_index_class_tags.clear(); _anchor_container_cursor = 0; _anchor_other_cursor = 0; // Fresh lane: nothing admits before the search does, so nothing can have a pending first look @@ -1177,8 +1176,7 @@ void ReferenceChainTracker::resetSearchStateForTest(jvmtiEnv *jvmti, _static_anchor_fifo_set.clear(); _static_anchor_fifo_klass_counts.clear(); _static_anchor_index.clear(); - _static_anchor_own_class_tags.clear(); - _static_anchor_index_tags.clear(); + _static_anchor_index_class_tags.clear(); _anchor_container_cursor = 0; _anchor_other_cursor = 0; _static_anchor_fresh_queue.clear(); diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index def995d21c..692c13207e 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -516,12 +516,11 @@ class ReferenceChainTracker { // scanning the full frontier table. std::vector _static_anchor_index; - // Parallel to _static_anchor_index: the runtime class tag of each indexed holder. - std::vector _static_anchor_own_class_tags; - - // Dedup companion for _static_anchor_index (O(1) membership; the population is ~28k on a real JVM - // - see addToStaticAnchorIndex()'s own comment). - std::unordered_set _static_anchor_index_tags; + // Own class tag per indexed holder (the runtime class tag of the holder), keyed by the holder's + // frontier tag. A holder first seen before its class was tagged is stored with 0 and refreshed + // by the next callback reporting the resolved class tag - the value is the sole input of the + // container-shape fallback in isSelectableAnchor() for reparented holders. + std::unordered_map _static_anchor_index_class_tags; // Shape of a class as an anchor candidate: does the class implement java/util/Collection or // java/util/Map (directly or via superclasses/ interfaces)? @@ -1086,6 +1085,10 @@ class ReferenceChainTracker { void addToStaticAnchorIndex(jlong tag, jlong own_class_tag, u8 root_kind); // Shared deduplicated index insertion for durable roots and local holders. void indexAnchorForRotation(jlong tag, jlong own_class_tag); + // Appends the drained at-risk anchors to the combined static-anchor selection, skipping tags the + // persistent tiers already selected. Static: no member state, exposed for the dedup test. + static void mergeAtRiskAnchors(std::vector &selection, + const std::vector &drained); // True iff `klass` implements java/util/Collection or java/util/Map, directly or transitively // (superclass chain + interfaces of every visited class, depth-bounded, visited set to survive @@ -1097,10 +1100,10 @@ class ReferenceChainTracker { // cannot be resolved yet (leaves them at -1 so the next call retries). bool resolveContainerInterfaceTags(jvmtiEnv *jvmti, JNIEnv *jni); - // Lazy shape reconciliation for the anchor index: scans _static_anchor_own_class_tags for class - // tags not yet in _class_shape_cache, resolves up to ANCHOR_SHAPE_RECONCILE_BUDGET of them per - // pass via one GetObjectsWithTags call (class objects are tagged with their class tags) and - // classifies each. + // Lazy shape reconciliation for the anchor index: scans the anchor index's class tags + // (_static_anchor_index_class_tags) for class tags not yet in _class_shape_cache, resolves up to + // ANCHOR_SHAPE_RECONCILE_BUDGET of them per pass via one GetObjectsWithTags call (class objects + // are tagged with their class tags) and classifies each. void reconcileAnchorClassShapes(jvmtiEnv *jvmti, JNIEnv *jni); // Pops up to max_count AtRiskAnchor entries off _static_anchor_fifo's front into `out` // (appending), decrementing each popped entry's class occupancy in diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index d2494b57bd..75b5ff86b0 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -472,6 +472,7 @@ TEST_F(ReferenceChainsBfsTest, StaticFieldCollectionRemainsIndexedAfterFirstLook ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; int parent = addNode(); int holder = addNode(); int table = addNode(); @@ -536,7 +537,6 @@ TEST_F(ReferenceChainsBfsTest, StaticFieldCollectionRemainsIndexedAfterFirstLook ASSERT_TRUE(frontier->lookup(node_tags[holder], &holder_entry)); EXPECT_EQ(node_tags[parent], holder_entry.parent_tag); EXPECT_EQ(1u, holder_entry.depth); - tracker->stop(); } TEST_F(ReferenceChainsBfsTest, GlobalRootsIndexNewAndPreviouslyDiscoveredCollections) { @@ -544,6 +544,7 @@ TEST_F(ReferenceChainsBfsTest, GlobalRootsIndexNewAndPreviouslyDiscoveredCollect ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; int parent = addNode(); int new_holder = addNode(); int old_holder = addNode(); @@ -579,7 +580,110 @@ TEST_F(ReferenceChainsBfsTest, GlobalRootsIndexNewAndPreviouslyDiscoveredCollect FrontierEntry old_entry{}; ASSERT_TRUE(frontier->lookup(node_tags[old_holder], &old_entry)); EXPECT_EQ(node_tags[parent], old_entry.parent_tag); - tracker->stop(); +} + +// A durable root first reported before its class was tagged (class_tag == 0) stays indexed with a +// 0 own-class tag; the STATIC_FIELD edge that later delivers the resolved tag must upgrade the +// stored value, or the container-shape fallback can never select the reparented holder. +TEST_F(ReferenceChainsBfsTest, StaticEdgeRefreshesUnknownClassOfIndexedHolder) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + int parent = addNode(); + int holder = addNode(); + node_tags[parent] = tracker->nextTag(); + FrontierTable *frontier = tracker->frontierTable(); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[parent], 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + // The holder starts ROOT-attached (transient attribution) and arrives as a JNI_GLOBAL root + // with class_tag 0: the durable-root indexing path stores the untagged 0 own-class value. + const jlong holder_tag = tracker->nextTag(); + node_tags[holder] = (int)holder_tag; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, holder_tag, 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + const jlong resolved_class_tag = -103; + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + jlong zero_class_tag = 0; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_JNI_GLOBAL, zero_class_tag, &node_tags[holder], &ctx)); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + // Reparented - the durable-root tier's parent_tag == 0 branch can never select it again. + ASSERT_TRUE(tracker->frontierTable()->improveChain( + holder_tag, node_tags[parent], 0, 1, 0)); + + // Classification is outside heap callbacks: prime the resolved class as a container, then + // deliver the STATIC_FIELD edge the static-field sweep reports (the class object as referrer + // with its negative tag - a root-like edge). The index must upgrade 0 -> resolved tag. + ReferenceChainsTestAccessor::primeClassShapeForTest(resolved_class_tag, true); + jlong class_object_referrer = resolved_class_tag; + ASSERT_EQ(JVMTI_VISIT_OBJECTS, + ReferenceChainsTestAccessor::reportHeapReferenceForTest( + JVMTI_HEAP_REFERENCE_STATIC_FIELD, resolved_class_tag, + &node_tags[holder], &class_object_referrer, &ctx)); + ReferenceChainsTestAccessor::clearPriorityExpand(); + auto selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + ASSERT_EQ(std::vector{node_tags[holder]}, selected); +} + +// Indexed holders whose frontier entries died are pruned from the rotation index by the next +// collection, instead of accumulating for the tracker's lifetime (released tags get re-minted, +// so the same holder would otherwise re-index under its fresh tag every pass). +TEST_F(ReferenceChainsBfsTest, DeadAnchorIndexEntriesArePruned) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + int holderA = addNode(); + int holderB = addNode(); + node_tags[holderA] = tracker->nextTag(); + node_tags[holderB] = tracker->nextTag(); + const jlong unknown_class_tag = -106; + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = tracker->frontierTable(); + ctx.hop_cap = 64; + ctx.budget = 1000; + for (int holder : {holderA, holderB}) { + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, unknown_class_tag, + &node_tags[holder], &ctx)); + } + ASSERT_EQ(2u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + // Every frontier entry dies (frontier tags are released and re-minted between passes). + tracker->frontierTable()->clear(node_tags[holderA]); + tracker->frontierTable()->clear(node_tags[holderB]); + ASSERT_TRUE( + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + ASSERT_TRUE(ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().empty()); +} + +// The combined rotation selection keeps each drained at-risk anchor once: flipping the dedup +// comparison would drop every drained anchor, removing the dedup would walk reparented +// collections twice in one pass. +TEST(ReferenceChainsMergeAtRiskTest, MergedAnchorsAppearOnce) { + std::vector selection = {101, 102}; + std::vector drained = { + {102, 7U}, {103, 7U}, {101, 7U}}; + ReferenceChainsTestAccessor::mergeAtRiskAnchorsForTest(selection, drained); + ASSERT_EQ((std::vector{101, 102, 103}), selection); + + std::vector empty_selection; + ReferenceChainsTestAccessor::mergeAtRiskAnchorsForTest(empty_selection, drained); + ASSERT_EQ((std::vector{102, 103, 101}), empty_selection); } // At-risk FIFO mechanics: a chain-attached holder drained from the at-risk FIFO is descend-walked and diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index ab85beabff..58712c0482 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -547,6 +547,8 @@ TEST_F(ReferenceChainsBfsTest, FirstPassWatchesQualifiedLeakBeforeCompleting) { ASSERT_FALSE(args.parse("referencechains=true:budget=1000")); ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard( + /*reset_liveness=*/true); LivenessTracker *liveness = LivenessTracker::instance(); liveness->klassPopulationResetForTest(); liveness->setGcGenerationsForTest(true); @@ -571,9 +573,12 @@ TEST_F(ReferenceChainsBfsTest, FirstPassWatchesQualifiedLeakBeforeCompleting) { EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); EXPECT_NE(0, node_tags[root]); - liveness->klassPopulationResetForTest(); - liveness->setGcGenerationsForTest(false); - tracker->stop(); + // The production loop polls again after the pass (finishLoopIterationSerialized). The second + // poll of the same qualifying klass must not double-register the candidate - the pre-walk + // poll and the post-pass poll are idempotent for candidate admission. + tracker->finishLoopIterationSerialized(&mock_jvmti, &mock_jni); + EXPECT_EQ(SearchState::RUNNING, tracker->searchState()); + EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); } TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMutation) { @@ -581,6 +586,7 @@ TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMu ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; int holder = addNode(); int parent = addNode(); int table = addNode(); @@ -636,7 +642,6 @@ TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMu EXPECT_GT(tags_ever_assigned[table], 0); EXPECT_GT(tags_ever_assigned[payload], 0); EXPECT_NE(leak_tag, node_tags[payload]); - tracker->stop(); } // Regression test for the resolveLoadedClasses() scan-skip guard: it must compare `class_count != diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index f48a60f5fa..0e9b2e9781 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -37,6 +37,30 @@ class VMTestAccessor { class ReferenceChainsTestAccessor { public: + // Failure-safe teardown for tests that start the tracker: a gtest ASSERT_* failure returns from + // the test body immediately and skips a trailing stop(), leaving the singleton started with a + // populated frontier/index and (optionally) LivenessTracker's GC-generation machinery enabled - + // exactly the cross-test state this suite's negative controls depend on being empty. Owns the + // teardown instead of the trailing lines; its stop() is a no-op once already stopped. + class TrackerStopGuard { + public: + explicit TrackerStopGuard(bool reset_liveness = false) + : _reset_liveness(reset_liveness) {} + ~TrackerStopGuard() { + if (_reset_liveness) { + LivenessTracker *liveness = LivenessTracker::instance(); + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(false); + } + ReferenceChainTracker::instance()->stop(); + } + TrackerStopGuard(const TrackerStopGuard &) = delete; + TrackerStopGuard &operator=(const TrackerStopGuard &) = delete; + + private: + bool _reset_liveness; + }; + static void reset() { ReferenceChainTracker *t = ReferenceChainTracker::instance(); delete t->_frontier; @@ -94,8 +118,7 @@ class ReferenceChainsTestAccessor { t->_root_kind_rotation_cursor = 1; t->_stale_expanded_rotation_cursor = 1; t->_static_anchor_index.clear(); - t->_static_anchor_own_class_tags.clear(); - t->_static_anchor_index_tags.clear(); + t->_static_anchor_index_class_tags.clear(); t->_anchor_container_cursor = 0; t->_anchor_other_cursor = 0; t->_class_shape_cache.clear(); @@ -528,8 +551,19 @@ class ReferenceChainsTestAccessor { static bool anchorIndexIsEmptyForTest() { ReferenceChainTracker *t = ReferenceChainTracker::instance(); return t->_static_anchor_index.empty() && - t->_static_anchor_own_class_tags.empty() && - t->_static_anchor_index_tags.empty(); + t->_static_anchor_index_class_tags.empty(); + } + + // Copy of the indexed holder tags, so a test can observe pruning and + // admission of the persistent rotation index without reaching into it. + static std::vector staticAnchorIndexTagsForTest() { + return ReferenceChainTracker::instance()->_static_anchor_index; + } + + static void mergeAtRiskAnchorsForTest( + std::vector &selection, + const std::vector &drained) { + ReferenceChainTracker::mergeAtRiskAnchors(selection, drained); } static jlong discoveredTagForTest(int slot, int idx) { From f0e9900709323497e0bb8264f6a1dcf99773c9b7 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Fri, 13 Nov 2026 15:06:53 +0100 Subject: [PATCH 05/20] liveness: pin scratch-overflow victim selection among equal retained sets --- .../src/test/cpp/livenessTracker_ut.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index d3910d63c3..79dab1a63b 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1435,6 +1435,75 @@ TEST_F(SelectLeakCandidatesTest, ScratchOverflowPreservesStrongEarlyThreads) { } } +// Victim selection among equal retained sets must keep the FIRST minimal slot (strictly-less +// comparison): flipping it to <= evicts the last minimal thread instead. Thread 2 is the first +// minimal slot and thread 1 ties with it at the same count - thread 2 must lose its history +// (absent from the fold every epoch) while thread 1's survives. +TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsFirstMinimalSlot) { + LivenessTracker *tracker = LivenessTracker::instance(); + std::vector> cohorts; + cohorts.emplace_back(1, 12); + cohorts.emplace_back(2, 12); + for (int tid = 3; tid <= 16; tid++) { + cohorts.emplace_back(tid, 13); + } + cohorts.emplace_back(17, 1); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + LivenessTrackerTestAccessor::recordThreadCohorts(tracker, slot, cohorts); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + auto contains_tid = [&out](jint tid) { + for (int i = 0; i < out[0].qualifying_tid_count; i++) { + if (out[0].qualifying_tids[i] == tid) { + return true; + } + } + return false; + }; + // Thread 1 ties with thread 2 at the global minimum count: the scan keeps the first minimal + // slot, so thread 1 is evicted by the overflow thread every epoch and never reaches the fold, + // while thread 2's history qualifies. + EXPECT_TRUE(contains_tid(2)); + EXPECT_FALSE(contains_tid(1)); +} + +// The victim scan must consider slot 0 a candidate: the global minimum (thread 1, the only count +// that clears the bar here) sits at slot 0, and the scan evicts it on every overflow arrival, so +// its history never reaches the fold. (Pins the scan's min-selection; comparing slot 0 with +// itself at a loop start of 0 is a no-op, so no mutation of the start index is observable.) +TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsTheGlobalMinimumThread) { + LivenessTracker *tracker = LivenessTracker::instance(); + std::vector> cohorts; + cohorts.emplace_back(1, 8); + for (int tid = 2; tid <= 16; tid++) { + cohorts.emplace_back(tid, 9); + } + cohorts.emplace_back(17, 1); + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + LivenessTrackerTestAccessor::recordThreadCohorts(tracker, slot, cohorts); + } + KlassCandidate out[5]; + ASSERT_EQ(1, tracker->selectLeakCandidates(out, 5)); + auto contains_tid = [&out](jint tid) { + for (int i = 0; i < out[0].qualifying_tid_count; i++) { + if (out[0].qualifying_tids[i] == tid) { + return true; + } + } + return false; + }; + EXPECT_FALSE(contains_tid(1)); + // Thread 1's history is evicted on every overflow arrival and never reaches the fold; the + // qualifying threads are the 9-count threads the scan never minimizes onto. +} + TEST(LivenessTrackerSessionTest, ResetSessionClearsOnlyRecordingGates) { LivenessTracker *tracker = LivenessTracker::instance(); LivenessTrackerTestAccessor::setSessionGatesForTest( From ce33cd8f47a0b3385dec4471e152305a09f4178f Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Fri, 13 Nov 2026 15:07:10 +0100 Subject: [PATCH 06/20] leaking-cache: fix spotless formatting of the padded fixture --- .../referencechains/LeakingCacheScenario.java | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index 168805d1e6..43c9777b1c 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -304,9 +304,9 @@ private static ReferenceChainAssertions.ChainMatch findMatch(Path scratchDumpPat /** * Inline padding supplies sampled instances for the detector's eight-survivor per-thread - * threshold while preserving the one-shot allocator threads and number of retained objects. - * With only 32 longs, a failing release run retained at most six sampled instances per worker: - * its one-age cohorts could never qualify, regardless of traversal time. About 1KiB per payload + * threshold while preserving the one-shot allocator threads and number of retained objects. With + * only 32 longs, a failing release run retained at most six sampled instances per worker: its + * one-age cohorts could never qualify, regardless of traversal time. About 1KiB per payload * provides more sampling opportunities within the same rounds at the 256KiB sampling interval. * Plain fields keep that allocation volume on CachedPayload itself; a companion array would * compete for samples without contributing any CachedPayload survivors. @@ -320,7 +320,22 @@ static final class CachedPayload { long p64, p65, p66, p67, p68, p69, p70, p71, p72, p73, p74, p75, p76, p77, p78, p79; long p80, p81, p82, p83, p84, p85, p86, p87, p88, p89, p90, p91, p92, p93, p94, p95; long p96, p97, p98, p99, p100, p101, p102, p103, p104, p105, p106, p107, p108, p109, p110, p111; - long p112, p113, p114, p115, p116, p117, p118, p119, p120, p121, p122, p123, p124, p125, p126, p127; + long p112, + p113, + p114, + p115, + p116, + p117, + p118, + p119, + p120, + p121, + p122, + p123, + p124, + p125, + p126, + p127; CachedPayload(String key) { this.key = key; From 26943f7d073d82d240e474c79eba09321c3887ea Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Fri, 13 Nov 2026 17:41:56 +0100 Subject: [PATCH 07/20] test-accessors: include livenessTracker.h for the fuzz target's TrackerStopGuard --- ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h | 1 + 1 file changed, 1 insertion(+) diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index 0e9b2e9781..e79cb7778a 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -18,6 +18,7 @@ #include #include "classTagAllocator.h" +#include "livenessTracker.h" #include "referenceChains.h" #include "vmEntry.h" From 82113af5d65760bbe76e7072a449189d2e231af5 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Fri, 13 Nov 2026 17:57:33 +0100 Subject: [PATCH 08/20] referencechains: prune ABANDONED frontier slots from the anchor index --- .../src/main/cpp/referenceChainAnchors.cpp | 3 +- .../test/cpp/referenceChainsAnchorTests.inc | 33 +++++++++++++++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 875cca2dc7..753043c391 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -152,7 +152,8 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { for (size_t i = 0; i < _static_anchor_index.size(); i++) { jlong tag = _static_anchor_index[i]; FrontierEntry entry{}; - if (!frontier->lookupLocked(tag, &entry)) { + if (!frontier->lookupLocked(tag, &entry) || + entry.state == FrontierEntryState::ABANDONED) { _static_anchor_index_class_tags.erase(tag); continue; } diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 75b5ff86b0..71dde9a925 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -647,25 +647,46 @@ TEST_F(ReferenceChainsBfsTest, DeadAnchorIndexEntriesArePruned) { ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; int holderA = addNode(); int holderB = addNode(); + int holderC = addNode(); node_tags[holderA] = tracker->nextTag(); - node_tags[holderB] = tracker->nextTag(); + // Beyond any slot the two inserted holders can grow the table to: the released-tag shape. + node_tags[holderB] = 5000; + node_tags[holderC] = tracker->nextTag(); + FrontierTable *frontier = tracker->frontierTable(); const jlong unknown_class_tag = -106; ReferenceChainPassContext ctx{}; ctx.tracker = tracker; - ctx.frontier = tracker->frontierTable(); + ctx.frontier = frontier; ctx.hop_cap = 64; ctx.budget = 1000; - for (int holder : {holderA, holderB}) { + // HolderA gets a real frontier slot, so clearing it produces the production ABANDONED state + // that lookupLocked() still finds; holderC stays live; holderB's tag is never allocated in + // the table. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderA], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderC], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + for (int holder : {holderA, holderB, holderC}) { ASSERT_EQ(JVMTI_ITERATION_CONTINUE, ReferenceChainsTestAccessor::reportHeapRootForTest( JVMTI_HEAP_ROOT_STACK_LOCAL, unknown_class_tag, &node_tags[holder], &ctx)); } - ASSERT_EQ(2u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + ASSERT_EQ(3u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); - // Every frontier entry dies (frontier tags are released and re-minted between passes). + // HolderA's slot is cleared to ABANDONED (the production death path - lookupLocked still + // finds it), holderB's slot is beyond the table, holderC stays live. Both dead shapes must + // leave the index. tracker->frontierTable()->clear(node_tags[holderA]); - tracker->frontierTable()->clear(node_tags[holderB]); + ASSERT_TRUE( + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + EXPECT_EQ(node_tags[holderC], + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()[0]); + + tracker->frontierTable()->clear(node_tags[holderC]); ASSERT_TRUE( ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); ASSERT_TRUE(ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().empty()); From 07a4e1b674df04053379e3b780497a9adbcb0388 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Mon, 16 Nov 2026 10:35:43 +0100 Subject: [PATCH 09/20] test-accessors: keep fuzz-compatible tracker teardown --- .../src/test/cpp/referenceChainsBfsTests.inc | 13 +++++++++++-- .../test/cpp/referenceChainsTestAccessors.h | 19 +++---------------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index 58712c0482..c1e94f3c3b 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -21,6 +21,15 @@ protected: void TearDown() override { tearDown(); } }; +class LivenessTrackerTestResetGuard { +public: + ~LivenessTrackerTestResetGuard() { + LivenessTracker *liveness = LivenessTracker::instance(); + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(false); + } +}; + TEST_F(ReferenceChainsBfsTest, ReconstructsChainForSyntheticGraph) { Arguments args; ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); @@ -547,8 +556,8 @@ TEST_F(ReferenceChainsBfsTest, FirstPassWatchesQualifiedLeakBeforeCompleting) { ASSERT_FALSE(args.parse("referencechains=true:budget=1000")); ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); ASSERT_FALSE(tracker->start(args)); - ReferenceChainsTestAccessor::TrackerStopGuard stop_guard( - /*reset_liveness=*/true); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + LivenessTrackerTestResetGuard liveness_reset_guard; LivenessTracker *liveness = LivenessTracker::instance(); liveness->klassPopulationResetForTest(); liveness->setGcGenerationsForTest(true); diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index e79cb7778a..44cf21c2df 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -40,26 +40,13 @@ class ReferenceChainsTestAccessor { public: // Failure-safe teardown for tests that start the tracker: a gtest ASSERT_* failure returns from // the test body immediately and skips a trailing stop(), leaving the singleton started with a - // populated frontier/index and (optionally) LivenessTracker's GC-generation machinery enabled - - // exactly the cross-test state this suite's negative controls depend on being empty. Owns the - // teardown instead of the trailing lines; its stop() is a no-op once already stopped. + // populated frontier/index. Owns the teardown instead; stop() is a no-op once already stopped. class TrackerStopGuard { public: - explicit TrackerStopGuard(bool reset_liveness = false) - : _reset_liveness(reset_liveness) {} - ~TrackerStopGuard() { - if (_reset_liveness) { - LivenessTracker *liveness = LivenessTracker::instance(); - liveness->klassPopulationResetForTest(); - liveness->setGcGenerationsForTest(false); - } - ReferenceChainTracker::instance()->stop(); - } + TrackerStopGuard() = default; + ~TrackerStopGuard() { ReferenceChainTracker::instance()->stop(); } TrackerStopGuard(const TrackerStopGuard &) = delete; TrackerStopGuard &operator=(const TrackerStopGuard &) = delete; - - private: - bool _reset_liveness; }; static void reset() { From 19759fac7fe4e74244019837b54138f684619fdb Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 13:43:07 +0100 Subject: [PATCH 10/20] referencechains: harden anchor and liveness tracking --- ddprof-lib/src/main/cpp/livenessTracker.h | 3 +- .../src/main/cpp/referenceChainAnchors.cpp | 11 +- .../src/main/cpp/referenceChainTraversal.cpp | 18 +- .../src/main/cpp/referenceChainWalk.cpp | 5 +- ddprof-lib/src/main/cpp/referenceChains.cpp | 8 +- ddprof-lib/src/main/cpp/referenceChains.h | 37 ++-- .../src/test/cpp/livenessTracker_ut.cpp | 166 ++++++++++++++++- .../test/cpp/referenceChainsAnchorTests.inc | 174 ++++++++++++++++++ .../src/test/cpp/referenceChainsBfsTests.inc | 8 + doc/README.md | 2 +- doc/ReferenceChainsCollectionSummary.md | 27 ++- .../LiveHeapReferenceChainsImplementation.md | 56 +++++- 12 files changed, 454 insertions(+), 61 deletions(-) diff --git a/ddprof-lib/src/main/cpp/livenessTracker.h b/ddprof-lib/src/main/cpp/livenessTracker.h index d01042ca5a..7d912c6002 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -1461,7 +1461,7 @@ class alignas(alignof(SpinLock)) LivenessTracker { void seedKlassPopulationSampleForTest( u32 klass_id, u32 count, u64 epoch, jweak *out_evicted = nullptr, int *out_evicted_count = nullptr, int max_evicted = 0) { - _table_lock.lock(); + ExclusiveLockGuard guard(&_table_lock); klass_id = resolveTestKlassAliasLocked(klass_id); for (int i = 0; i < _klass_population_size; i++) { if (_klass_population[i].klass_id == klass_id) { @@ -1474,7 +1474,6 @@ class alignas(alignof(SpinLock)) LivenessTracker { recordKlassPopulationSampleLocked(klass_id, count, epoch, &slot, &created, out_evicted, out_evicted_count, max_evicted); _klass_population[slot].test_seeded_history = true; - _table_lock.unlock(); } #endif diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 753043c391..56690f585d 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -120,8 +120,9 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { if (max_count <= 0 || _static_anchor_index.empty()) { return selected; } - // Tiered selection over _static_anchor_index (O(anchors) per pass, under ONE shared lock - the - // lookups below are lookupLocked()). + // Tiered selection over _static_anchor_index (O(anchors) per pass). The tracker thread, holding + // _engine_lock, is the only production index writer and runs this prune; the frontier shared lock + // covers frontier lookups, not index members, so production writers must stay serialized. size_t idx_size = _static_anchor_index.size(); if (_anchor_container_cursor >= idx_size) { _anchor_container_cursor = 0; @@ -202,9 +203,9 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { size_t pos = drain_pos; drain_pos++; if (pos >= idx_size || _static_anchor_index[pos] != tag) { - // The suffix-window invariant broke (cannot happen today; defensive): fall back to a search - // rather than mis-shape the entry - the queue is small, this is not a hot path once - // healthy. + // Reachable: the prune above dropped a queued tag, shifting the suffix window for entries + // queued before it. Search the whole index for the tag; a pruned tag is absent, so it is + // skipped. Cost: one index scan per mismatched entry, at most STATIC_ANCHOR_FRESH_CAP. auto it = std::find(_static_anchor_index.begin(), _static_anchor_index.end(), tag); diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 819a93d434..4f9a3e0546 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -169,8 +169,8 @@ void ReferenceChainTracker::mergeAtRiskAnchors( std::vector &selection, const std::vector &drained) { for (const AtRiskAnchor &at_risk : drained) { - // A reparented collection can also have been selected by the persistent - // container tier. The combined selection is bounded by 48 + 16 entries. + // The persistent tiers may already have selected this tag. The combined selection holds at most + // STATIC_ANCHOR_ROTATION_BUDGET persistent plus STATIC_ANCHOR_FIFO_DRAIN drained entries. if (std::find(selection.begin(), selection.end(), at_risk.tag) == selection.end()) { selection.push_back(at_risk.tag); @@ -221,11 +221,9 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, STALE_EXPANDED_ROTATION_BUDGET); int budget = expand_budget - rotation_reserved_budget; - // Root/stack-ref enumeration alone (unlike a root-seeded FollowReferences call on the fallback - // path) never discovers a root's own transitive children - IterateOverReachableObjects's - // root/stack-ref callbacks are given no oop, only a tag_ptr (see heapRootCallback()'s own - // comment) - so even when it runs this pass, the expandFrontier() call below is still needed to - // make any further progress. + // Root/stack-ref enumeration never discovers a root's transitive children (its callbacks get no + // oop, only a tag_ptr), so even when it runs this pass, expandFrontier() below is still needed + // to make progress. if (run_root_enum) { jlong resolved_chain_tags[MAX_RESOLVED_CHAINS]; ReferenceChainPassContext ctx; @@ -1099,10 +1097,8 @@ bool ReferenceChainTracker::runPass(jvmtiEnv *jvmti, JNIEnv *jni, if (manual_first_pass) { _search_started = true; store(_search_start_ns, OS::nanotime()); - // Register the candidates that triggered this search before walking. The - // first pass can drain the frontier; without a watched klass it would then - // complete and release its tags before the loop's post-pass poll can - // reconstruct any chain or schedule candidate-scoped walks. + // Poll before the first walk: with no watched klass, a pass that drains the frontier completes + // and releases its tags before the loop's post-pass poll can register candidates or build chains. pollWatchedTargets(jvmti, jni); } diff --git a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp index 2e4d0aab8a..91b7573d51 100644 --- a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp @@ -446,9 +446,8 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // This new path is deeper - replace the shallow root-attached entry with the deeper // chain-attached entry. u32 referrer_klass = ctx->tracker->classTags()->resolve(class_tag); - // Pre-read the CURRENT shape: improveChain() can remove this entry's - // durable-root eligibility. A known collection remains in the container - // tier; other holders need the FIFO's first look below. + // Pre-read the CURRENT shape: improveChain() can remove this entry's durable-root + // eligibility; the FIFO push below then gives it a first descend walk. FrontierEntry pre_improve_entry{}; bool was_root_attached_durable = ctx->frontier->lookup(*tag_ptr, &pre_improve_entry) && diff --git a/ddprof-lib/src/main/cpp/referenceChains.cpp b/ddprof-lib/src/main/cpp/referenceChains.cpp index 94a71e9333..0208341393 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.cpp +++ b/ddprof-lib/src/main/cpp/referenceChains.cpp @@ -186,8 +186,8 @@ void ReferenceChainTracker::autoTuneDefaults(Arguments &args) { std::min(scaled, MAX_REFERENCE_CHAINS_BUDGET)); } - // --- First-pass budget --- The root enumeration pass is one-shot per search and can afford a - // much larger budget. + // --- First-pass budget --- Root enumeration passes (first pass and interval-gated repeats) spend + // a much larger budget than expansion passes. if (!(tuned & REF_CHAINS_TUNED_FIRST_PASS_BUDGET)) { int fpb = args._reference_chains_budget * 10; args._reference_chains_first_pass_budget = std::min(fpb, @@ -291,8 +291,8 @@ Error ReferenceChainTracker::start(Arguments &args) { _hop_cap = args._reference_chains_hop_cap; _budget = args._reference_chains_budget; // 0 (unset) auto-scales from _budget instead of falling back to it plainly - see this field's own - // comment (referenceChains.h) for why a steady-state per-pass budget is the wrong size for the - // first pass. + // comment (referenceChains.h) for why a steady-state per-pass budget is the wrong size for root + // enumeration passes. _first_pass_budget = args._reference_chains_first_pass_budget > 0 ? args._reference_chains_first_pass_budget : std::min(_budget * AUTO_FIRST_PASS_BUDGET_MULTIPLIER, diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index 692c13207e..7677f3b2e6 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -114,7 +114,9 @@ class ReferenceChainTracker { int _hop_cap; int _budget; - // Larger one-shot edge budget for the search's root-seeded first pass. + // Edge budget for each root/stack-ref enumeration (first pass and every interval-gated repeat), + // much larger than _budget: an exhausted budget truncates the enumeration. Expansion passes + // spend _effective_budget instead. int _first_pass_budget; // Wall-clock TTL for one search; <= 0 disables the cutoff. @@ -334,9 +336,8 @@ class ReferenceChainTracker { "batch descriptor capacity must track the batch upper bound"); ReferenceChainBatchSet _batch_set; - // Search lifecycle state. _search_started distinguishes a search's first pass (seed - // FollowReferences from the heap roots) from a resumed pass (expand the persisted frontier, see - // expandFrontier()) - runPass() below. + // Search lifecycle state. _search_started marks a search's first pass, which always enumerates + // roots; later passes enumerate only once the interval elapses (see runPass()). bool _search_started; volatile u8 _search_state; @@ -488,8 +489,8 @@ class ReferenceChainTracker { } } _priority_expand_set; - // Chain-attached holders without a known collection shape need a first - // descend walk when a static edge or reparenting removes their root eligibility. + // Holders reparented under a chain, or reached by a static edge while chain-attached, are queued + // for one first descend walk whatever their class shape (bounded by the FIFO and per-class caps). struct AtRiskAnchor { jlong tag; u32 klass_id; @@ -1423,13 +1424,9 @@ class ReferenceChainTracker { // frontierTable()'s existing rationale. ClassTagTable *classTags() { return &_class_tags; } - // Runs exactly one bounded BFS pass and returns. The first call for a search seeds - // FollowReferences from the heap roots (heap_filter=0, klass=NULL, initial_object=NULL - see this - // method's own comment in referenceChains.cpp for why FollowReferences rather than - // IterateThroughHeap); every later call resumes from the persisted frontier via expandFrontier() - // instead of re-walking from the roots (see expandFrontier()'s comment for why - re-walking from - // the roots each call would re-traverse the entire already-discovered subgraph every pass, - // defeating the point of a per-pass budget). + // Runs exactly one bounded BFS pass and returns. Root/stack-ref enumeration is mandatory on a + // search's first pass and repeats once rootEnumIntervalFloorNs() has elapsed; every pass then + // expands the persisted frontier via expandFrontier() rather than re-walking the whole graph. bool runPass(jvmtiEnv *jvmti, JNIEnv *jni, bool *out_truncated = nullptr); // Serialized entry points used by threadLoop(), the BFS thread. @@ -1551,17 +1548,9 @@ class ReferenceChainTracker { // (livenessTracker.h). jlong tagAsRootForTest(jvmtiEnv *jvmti, JNIEnv *jni, jobject obj); - // Test seam - not part of the production API. Since ReferenceChainTracker is a process-wide - // singleton (ExternalProcessReferenceChainTest's own class javadoc explains why that matters: - // only the *first* test to ever call runPass() in a shared JVM gets a real root-seeded walk, - // since runPass() only re-walks from the roots once per search's whole lifetime), an in-process - // test that needs its own genuine first-ever root walk calls this at the start of its test body - // to force exactly that - releasing any tags a previous test's search still held, then resetting - // search/frontier state to the same "brand-new tracker" state restartSearch() - // (referenceChains.cpp) produces, plus the target- dedup/pending-event state restartSearch() - // itself intentionally leaves for pollWatchedTargets()/drainPendingChainEvents() to self-clear - // (this is an immediate, out-of-band reset - there is no next real pass here to observe the - // change and clear them the ordinary way). + // Shared-JVM tests must reset this singleton before a fresh search or inherit earlier search state. + // This seam releases old tags and clears frontier, candidate, cache, and pending-event state. + // Call only between tests; it stops and restarts the BFS thread around the reset. void resetSearchStateForTest(jvmtiEnv *jvmti, JNIEnv *jni); // Test seam - not part of the production API. Diagnostic-only: reports how far a given diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index 79dab1a63b..be479eee4b 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1123,6 +1123,24 @@ class LivenessTrackerTestAccessor { t->_table_lock.unlock(); } + using Scratch = LivenessTracker::KlassCountScratch; + static constexpr int KLASS_POPULATION_CAP = LivenessTracker::MAX_KLASS_POPULATION_ENTRIES; + + static void addObjects(LivenessTracker *t, Scratch &s, jint tid, u32 age, int n = 1) { + for (int i = 0; i < n; i++) { + t->insertThreadGen(s, tid, age); + } + } + + static const Scratch::ThreadGens *findThread(const Scratch &s, jint tid) { + for (int i = 0; i < s.thread_count; i++) { + if (s.threads[i].tid == tid) { + return &s.threads[i]; + } + } + return nullptr; + } + // Runs one onGC() with the given _container_limit_resolved value and returns the // container usage it recorded. Restores the touched fields afterwards. static u64 containerUsageRecordedByOnGC(LivenessTracker *t, bool limit_resolved) { @@ -1355,6 +1373,42 @@ TEST_F(SelectLeakCandidatesTest, SeededClassHistoryAcceptsExplicitUpdatesAfterGc } EXPECT_EQ(0, tracker->selectLeakCandidates(out, 5)); } +TEST_F(SelectLeakCandidatesTest, SeededClassHistoryLosesProtectionAfterReset) { + LivenessTracker *tracker = LivenessTracker::instance(); + tracker->seedKlassPopulationSampleForTest(1, 10, 1); + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, 2); + KlassPopulationEntry entry; + ASSERT_TRUE(tracker->klassPopulationLookupForTest(1, &entry)); + ASSERT_EQ(1, entry.ring_fill); // protection reached: the fold added no sample + tracker->klassPopulationResetForTest(); + ASSERT_FALSE(tracker->klassPopulationLookupForTest(1, &entry)); + int slot; + bool created; + tracker->klassPopulationRecordForTest(1, 10, 3, &slot, &created); + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1, 7, 4); + ASSERT_TRUE(tracker->klassPopulationLookupForTest(1, &entry)); + EXPECT_EQ(2, entry.ring_fill); + EXPECT_EQ(1u, entry.count_ring[1]); // the fold's one distinct age +} + +TEST_F(SelectLeakCandidatesTest, SeededClassHistoryProtectionDoesNotSurviveSlotReuse) { + LivenessTracker *tracker = LivenessTracker::instance(); + constexpr int cap = LivenessTrackerTestAccessor::KLASS_POPULATION_CAP; + tracker->seedKlassPopulationSampleForTest(1, 10, 1); // oldest epoch: the LRU victim + int slot; + bool created; + for (int id = 2; id <= cap; id++) { + tracker->klassPopulationRecordForTest(id, 1, 2, &slot, &created); + } + tracker->klassPopulationRecordForTest(1, 0, 1, &slot, &created); + ASSERT_FALSE(created); // table is full and class 1 sits in the slot to be evicted + LivenessTrackerTestAccessor::foldClassCohort(tracker, 1000, 7, 3); + KlassPopulationEntry entry; + ASSERT_FALSE(tracker->klassPopulationLookupForTest(1, &entry)); + ASSERT_TRUE(tracker->klassPopulationLookupForTest(1000, &entry)); + EXPECT_EQ(1, entry.ring_fill); // a leaked seed flag would have skipped the fold's sample + EXPECT_EQ(1u, entry.count_ring[0]); +} #endif TEST_F(SelectLeakCandidatesTest, OrdinaryClassHistoryStillDecaysAfterGrowthStops) { @@ -1435,10 +1489,9 @@ TEST_F(SelectLeakCandidatesTest, ScratchOverflowPreservesStrongEarlyThreads) { } } -// Victim selection among equal retained sets must keep the FIRST minimal slot (strictly-less -// comparison): flipping it to <= evicts the last minimal thread instead. Thread 2 is the first -// minimal slot and thread 1 ties with it at the same count - thread 2 must lose its history -// (absent from the fold every epoch) while thread 1's survives. +// Victim selection among equal retained sets keeps the FIRST minimal slot (strict <): flipping +// it to <= evicts the last minimal thread. Threads 1 and 2 tie at the minimum count; thread 1 +// (slot 0) is evicted every epoch, so its history never reaches the fold while thread 2's does. TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsFirstMinimalSlot) { LivenessTracker *tracker = LivenessTracker::instance(); std::vector> cohorts; @@ -1500,8 +1553,109 @@ TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsTheGlobalMinimumThread) { return false; }; EXPECT_FALSE(contains_tid(1)); - // Thread 1's history is evicted on every overflow arrival and never reaches the fold; the - // qualifying threads are the 9-count threads the scan never minimizes onto. +} + +// Direct accumulator tests: the scratch holds MAX_THREADS_PER_KLASS (16) tids; each helper +// fills it, then one extra tid forces the victim scan. +static void fillScratchWithTids(LivenessTracker *t, LivenessTrackerTestAccessor::Scratch &s, + int count_per_tid) { + for (jint tid = 1; tid <= 16; tid++) { + LivenessTrackerTestAccessor::addObjects(t, s, tid, 1, count_per_tid); + } + ASSERT_EQ(16, s.thread_count); +} + +TEST(LivenessTrackerScratchTest, IncomingAndReappearingTidsStartFromTheirOwnObject) { + LivenessTracker *t = LivenessTracker::instance(); + LivenessTrackerTestAccessor::Scratch s{}; + // tid 1 is the unique minimum (count 3, three ages); the rest hold count 5. + for (u32 age = 1; age <= 3; age++) { + LivenessTrackerTestAccessor::addObjects(t, s, 1, age); + } + for (jint tid = 2; tid <= 16; tid++) { + LivenessTrackerTestAccessor::addObjects(t, s, tid, 1, 5); + } + ASSERT_EQ(16, s.thread_count); + LivenessTrackerTestAccessor::addObjects(t, s, 99, 9); + EXPECT_EQ(16, s.thread_count); + ASSERT_EQ(nullptr, LivenessTrackerTestAccessor::findThread(s, 1)); + auto *in = LivenessTrackerTestAccessor::findThread(s, 99); + ASSERT_NE(nullptr, in); + EXPECT_EQ(1u, in->count); + EXPECT_EQ(1u, in->age_count); + EXPECT_EQ(9u, in->ages[0]); + LivenessTrackerTestAccessor::addObjects(t, s, 99, 9); + EXPECT_EQ(2u, LivenessTrackerTestAccessor::findThread(s, 99)->count); + // The evicted tid reappears: it replaces the now-minimal tid 99 and starts at one object, + // not at its earlier count of 3 or its earlier ages. + LivenessTrackerTestAccessor::addObjects(t, s, 1, 4); + EXPECT_EQ(nullptr, LivenessTrackerTestAccessor::findThread(s, 99)); + auto *back = LivenessTrackerTestAccessor::findThread(s, 1); + ASSERT_NE(nullptr, back); + EXPECT_EQ(1u, back->count); + EXPECT_EQ(1u, back->age_count); + EXPECT_EQ(4u, back->ages[0]); +} + +TEST(LivenessTrackerScratchTest, LowestCountIsEvictedEvenWithMoreAges) { + LivenessTracker *t = LivenessTracker::instance(); + LivenessTrackerTestAccessor::Scratch s{}; + LivenessTrackerTestAccessor::addObjects(t, s, 1, 1); + LivenessTrackerTestAccessor::addObjects(t, s, 1, 2); + for (jint tid = 2; tid <= 16; tid++) { + LivenessTrackerTestAccessor::addObjects(t, s, tid, 1, 3); + } + LivenessTrackerTestAccessor::addObjects(t, s, 99, 1); + EXPECT_EQ(nullptr, LivenessTrackerTestAccessor::findThread(s, 1)); + EXPECT_NE(nullptr, LivenessTrackerTestAccessor::findThread(s, 2)); +} + +TEST(LivenessTrackerScratchTest, FewerAgesLoseAtEqualCount) { + LivenessTracker *t = LivenessTracker::instance(); + LivenessTrackerTestAccessor::Scratch s{}; + for (u32 age = 1; age <= 4; age++) { + LivenessTrackerTestAccessor::addObjects(t, s, 1, age); + } + LivenessTrackerTestAccessor::addObjects(t, s, 2, 1, 4); + for (jint tid = 3; tid <= 16; tid++) { + LivenessTrackerTestAccessor::addObjects(t, s, tid, 1, 6); + } + LivenessTrackerTestAccessor::addObjects(t, s, 99, 1); + // tid 1 (slot 0) ties tid 2 on count but has more ages, so tid 2 is the victim. + EXPECT_EQ(nullptr, LivenessTrackerTestAccessor::findThread(s, 2)); + auto *kept = LivenessTrackerTestAccessor::findThread(s, 1); + ASSERT_NE(nullptr, kept); + EXPECT_EQ(4u, kept->age_count); +} + +TEST(LivenessTrackerScratchTest, CompleteTieEvictsFirstSlot) { + LivenessTracker *t = LivenessTracker::instance(); + LivenessTrackerTestAccessor::Scratch s{}; + fillScratchWithTids(t, s, 4); + LivenessTrackerTestAccessor::addObjects(t, s, 99, 1); + EXPECT_EQ(99, s.threads[0].tid); + EXPECT_EQ(nullptr, LivenessTrackerTestAccessor::findThread(s, 1)); + EXPECT_NE(nullptr, LivenessTrackerTestAccessor::findThread(s, 16)); +} + +TEST(LivenessTrackerScratchTest, DistinctAgesAreBoundedSortedAndCountedPerObject) { + LivenessTracker *t = LivenessTracker::instance(); + LivenessTrackerTestAccessor::Scratch s{}; + constexpr u32 limit = LivenessTrackerTestAccessor::Scratch::MAX_AGES_PER_THREAD; + // Descending arrival exercises the sorted-insert shift; the first `limit` distinct ages stay. + for (u32 age = limit + 8; age >= 1; age--) { + LivenessTrackerTestAccessor::addObjects(t, s, 5, age); + } + LivenessTrackerTestAccessor::addObjects(t, s, 5, limit + 8); // duplicate age + auto *th = LivenessTrackerTestAccessor::findThread(s, 5); + ASSERT_NE(nullptr, th); + EXPECT_EQ(limit, th->age_count); + EXPECT_EQ(limit + 8 + 1, th->count); + EXPECT_EQ(9u, th->ages[0]); + EXPECT_EQ(limit + 8, th->ages[limit - 1]); + for (u32 i = 1; i < th->age_count; i++) { + EXPECT_LT(th->ages[i - 1], th->ages[i]); + } } TEST(LivenessTrackerSessionTest, ResetSessionClearsOnlyRecordingGates) { diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 71dde9a925..7f9af7f514 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -1049,3 +1049,177 @@ TEST_F(ReferenceChainsBfsTest, AtRiskFifoPerClassQuotaKeepsFloodOut) { // offset, the superclass-chain order, the interface-referrer branch - and degrade to the edge KIND // on any undecodable hop, never a fabricated name (the fail-safe contract: a wrong numbering on an // unverified JVM degrades, it does not lie). + +// A prune inside the fresh-queue window misaligns the estimated queue positions; the fallback +// search must still shape every surviving fresh anchor in admission order and drop the dead ones. +TEST_F(ReferenceChainsBfsTest, InWindowPruneKeepsFreshQueueSelections) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + FrontierTable *frontier = tracker->frontierTable(); + + constexpr int kFresh = 6; + for (int i = 0; i < kFresh; i++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 900 + i, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 900 + i, 910000 + i, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest(910000 + i, true); + } + ASSERT_EQ((size_t)kFresh, + ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); + // Two dead entries inside the queue window (the ABANDONED shape the production death path + // leaves): every later queue position now differs from its estimate. + frontier->clear(901); + frontier->clear(903); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(16); + EXPECT_EQ((std::vector{900, 902, 904, 905}), selected); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); + EXPECT_EQ((std::vector{900, 902, 904, 905}), + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()); +} + +// Cursors are clamped before the prune compacts the index: entries pruned below the cursor shift +// unvisited survivors under it. They wait for the next lap - delayed once, never repeated or lost. +TEST_F(ReferenceChainsBfsTest, FairCursorAfterPruneDelaysSkippedSurvivorsOneLap) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + FrontierTable *frontier = tracker->frontierTable(); + + for (int i = 0; i < 10; i++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 950 + i, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 950 + i, 920000 + i, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest(920000 + i, false); + } + ASSERT_EQ((std::vector{950, 951, 952, 953}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)); + frontier->clear(950); + frontier->clear(951); + // The cursor sat at position 4; survivors 952..959 now sit at 0..7, so 954 and 955 (not yet + // visited) fall below it. + EXPECT_EQ((std::vector{956, 957, 958, 959}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)); + EXPECT_EQ((std::vector{952, 953, 954, 955}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)) + << "the lap wrapped: the skipped survivors are served next, none lost"; +} + +// The rotation selection is 32 persistent anchors plus at most 16 drained at-risk anchors; the +// drain stops at its per-pass cap and a drained duplicate of a persistent pick is not repeated. +TEST_F(ReferenceChainsBfsTest, RotationSelectionBoundaryIsPersistentPlusDrained) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + FrontierTable *frontier = tracker->frontierTable(); + + for (int i = 0; i < 40; i++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 1100 + i, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 1100 + i, 930000 + i, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest(930000 + i, false); + } + std::vector selection = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(32); + ASSERT_EQ(32u, selection.size()); + // 17 at-risk entries: 16 distinct from the persistent picks, plus one repeating selection[0]. + for (int i = 0; i < 16; i++) { + ReferenceChainsTestAccessor::pushStaticAnchorFifoForTest(2100 + i, 77); + } + ReferenceChainsTestAccessor::pushStaticAnchorFifoForTest(selection[0], 77); + std::vector drained; + ASSERT_EQ(16, ReferenceChainsTestAccessor::drainStaticAnchorFifoForTest(16, drained)); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::staticAnchorFifoSizeForTest()) + << "the 17th at-risk entry waits for the next pass"; + ReferenceChainsTestAccessor::mergeAtRiskAnchorsForTest(selection, drained); + EXPECT_EQ(48u, selection.size()); + EXPECT_EQ(2100, selection[32]); + EXPECT_EQ(2115, selection.back()); + + std::vector next; + ASSERT_EQ(1, ReferenceChainsTestAccessor::drainStaticAnchorFifoForTest(16, next)); + std::vector full = selection; + ReferenceChainsTestAccessor::mergeAtRiskAnchorsForTest(full, next); + EXPECT_EQ(selection, full) << "a drained duplicate of a persistent pick is not repeated"; +} + +// A pass that found no candidate leaves the loop-tail poll as the only registration path: a leak +// qualifying after the pass must be admitted by finishLoopIterationSerialized, once. +TEST_F(ReferenceChainsBfsTest, IdleLoopTailPollRegistersLaterCandidateOnce) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + LivenessTrackerTestResetGuard liveness_reset_guard; + LivenessTracker *liveness = LivenessTracker::instance(); + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(true); + liveness->classMapGenerationSetForTest(Profiler::instance()->classMap()->generation()); + int root = addNode(); + script = {{JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, root, -1}}; + + EXPECT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni)); + tracker->finishLoopIterationSerialized(&mock_jvmti, &mock_jni); + ASSERT_EQ(0, ReferenceChainsTestAccessor::candidateCountForTest()) + << "the idle iteration must not have a candidate"; + + for (int epoch = 1; epoch <= 20; epoch++) { + int slot; + bool created; + liveness->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); + liveness->tidTrendRecordForTest(1, 4242, epoch, epoch); + } + liveness->klassPopulationSetStableClassTagForTest(1, -41); + + tracker->finishLoopIterationSerialized(&mock_jvmti, &mock_jni); + EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::candidateKlassIdForTest(0)); + tracker->finishLoopIterationSerialized(&mock_jvmti, &mock_jni); + EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); +} + +// Admission appends to a bounded fresh queue; the 1025th eligible anchor evicts the oldest entry. +TEST_F(ReferenceChainsBfsTest, FreshAnchorQueueDropsOldestPastCap) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + FrontierTable *frontier = tracker->frontierTable(); + constexpr int kCap = 1024; + constexpr jlong kFirstTag = 5000, kClassTag = 940000; + ReferenceChainsTestAccessor::primeClassShapeForTest(kClassTag, true); + for (int i = 0; i <= kCap; i++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, kFirstTag + i, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + kFirstTag + i, kClassTag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + if (i == kCap - 1) { + ASSERT_EQ(1024u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); + } + } + EXPECT_EQ(1024u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()) + << "the 1025th admission must evict, not grow the queue"; + ASSERT_EQ(1025u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + std::vector first = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(1); + ASSERT_EQ(1u, first.size()); + EXPECT_EQ(kFirstTag + 1, first[0]) << "the evicted oldest anchor must not ride the fresh lane"; +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index c1e94f3c3b..964795ae59 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -8,6 +8,8 @@ #include "referenceChainInternal.h" #include "tsc.h" +#include + @@ -23,12 +25,18 @@ protected: class LivenessTrackerTestResetGuard { public: + LivenessTrackerTestResetGuard() = default; + LivenessTrackerTestResetGuard(const LivenessTrackerTestResetGuard &) = delete; + LivenessTrackerTestResetGuard &operator=(const LivenessTrackerTestResetGuard &) = delete; ~LivenessTrackerTestResetGuard() { LivenessTracker *liveness = LivenessTracker::instance(); liveness->klassPopulationResetForTest(); liveness->setGcGenerationsForTest(false); } }; +static_assert(!std::is_copy_constructible::value && + !std::is_copy_assignable::value, + "the reset guard owns a cleanup and must not be copied"); TEST_F(ReferenceChainsBfsTest, ReconstructsChainForSyntheticGraph) { Arguments args; diff --git a/doc/README.md b/doc/README.md index a94b86ed7b..af2e10e552 100644 --- a/doc/README.md +++ b/doc/README.md @@ -21,7 +21,7 @@ All documentation files use **PascalCase** naming (e.g., `BuildSystemGuide.md`). - [CallTraceStorage](architecture/CallTraceStorage.md) - Triple-buffer architecture for call traces; recording-scoped (release/acquire) - [DemoJavaLeakApp](architecture/DemoJavaLeakApp.md) - Self-contained leak-demo app (`demo-java-leak`): unbounded strong-ref cache, self-traffic, watermark flush, no profiler dependency - [JfrIntegration](architecture/JfrIntegration.md) - Native JFR writer: recordings, buffers, metadata, constant pools -- [LiveHeapReferenceChainsImplementation](architecture/LiveHeapReferenceChainsImplementation.md) - Current reference-chain implementation +- [LiveHeapReferenceChainsImplementation](architecture/LiveHeapReferenceChainsImplementation.md) - Current implementation, including root-anchor indexing and rotation - [MallocArenaWarning](architecture/MallocArenaWarning.md) - glibc malloc arena detector: arena walk, rule, and JFR events - [NativeMemoryProfiling](architecture/NativeMemoryProfiling.md) - malloc interception (hooks installed per recording, restored on stop) and allocation sampling - [ProfilingEngines](architecture/ProfilingEngines.md) - CPU, wall-clock, allocation, native-memory and liveness engines; gated thread registration; recording-scoped liveness; allocation/liveness stack capture, JVMTI retry, depth-limit truncation and verification scratch (`allocstack`) diff --git a/doc/ReferenceChainsCollectionSummary.md b/doc/ReferenceChainsCollectionSummary.md index e61178a8a3..9178f6e2d9 100644 --- a/doc/ReferenceChainsCollectionSummary.md +++ b/doc/ReferenceChainsCollectionSummary.md @@ -105,9 +105,30 @@ the tracking table. The expensive class-history fold is kept off that callback p ## Mutable-container coverage -A long-lived collection can receive references after its first expansion. Bounded rotation -revisits leak-accumulating parents, stale expanded entries, transient-root entries, and static -anchors. This adds opportunities to discover changed references, not complete mutation coverage. +A long-lived collection can receive references after its first expansion. +Bounded rotation revisits leak-accumulating parents and stale expanded entries. +It also revisits transient roots and anchor holders. + +These bounded walks improve mutation coverage. They do not guarantee every changed reference +is observed. + +The index stores holders seen through static-field/JNI-global edges. +It also indexes tagged stack/JNI-local roots whose shape is unknown or container-like. + +An indexed `CONTAINER` holder can remain eligible after reparenting. +Unknown or `NON_CONTAINER` local-root entries are not persistently selected while they +remain transient. + +When rotation reaches anchor selection, it takes up to 32 indexed anchors and drains up to +16 at-risk FIFO entries, skipping duplicates. The FIFO offers a best-effort first look to +reparented durable holders and chain-attached holders seen through static-field edges. + +Admission is globally and per-class capped. +Drained entries can be lost if rotation has no budget, object resolution fails, or a +frontier lookup fails during the walk or requeue. + +Budget, deadline, and frontier-cap stops return resolved-but-unwalked FIFO entries to the +front when their frontier entries still exist. These walks share rotation's edge budget. ## Cost controls diff --git a/doc/architecture/LiveHeapReferenceChainsImplementation.md b/doc/architecture/LiveHeapReferenceChainsImplementation.md index aebe2c7c45..a351ccdfe1 100644 --- a/doc/architecture/LiveHeapReferenceChainsImplementation.md +++ b/doc/architecture/LiveHeapReferenceChainsImplementation.md @@ -57,7 +57,7 @@ cleared safepoint-cost debt, the root-enumeration interval, and a current leak c 2. Candidate thread-object traversal. 3. Static-field scanning. 4. Ordinary frontier expansion. -5. Rotation and static-anchor traversal. +5. Rotation and anchor walks. Candidate thread traversal, ordinary frontier expansion, and rotation each receive a fresh callback deadline. Static-field scanning does not receive a fresh deadline. It shares the @@ -197,7 +197,59 @@ An object can change after its first expansion. For example, a long-lived collec | Leak accumulation | 16 | Select parents that accumulate instances of watched classes. | | Stale expanded entries | 256 | Provide eventual low-priority rechecks across the frontier table. | | Transient root kinds | 16 | Improve root attribution when later observations provide a more durable root kind. | -| Static anchors | 32 selected, plus 16 FIFO entries | Descend from selected objects held by static fields. | +| Anchor walks | Up to 32 indexed tags, plus up to 16 FIFO tags | Best-effort revisits of durable roots and container-classified local roots; an at-risk FIFO covers reparenting. | + +### Anchor index and selection + +`_static_anchor_index` stores frontier tags in index-insertion order. The tag-keyed +`_static_anchor_index_class_tags` map stores each holder's class tag. `_class_shape_cache` +stores the result of a bounded check for `Collection` or `Map`. + +Static-field and JNI-global edges add holders to the index. Root callbacks also index +positive frontier tags for stack/JNI-local holders when their class tag is known and shape +is unknown or `CONTAINER`; raw leak tags are excluded. + +`reconcileAnchorClassShapes()` can classify up to 128 distinct unknown anchor classes +in a pass that reaches rotation. It checks their class hierarchy and interfaces for +`Collection` or `Map` with a bounded walk. + +The shape cache uses process-lifetime class tags and survives search restarts. +The index and side map are per-search. + +If either interface tag is unavailable, unclassified shapes remain unknown. +A per-class walk can cache `NON_CONTAINER` when a failed lookup or bound leaves no match. +That label is the walk's result, not proof the class lacks either interface. + +An indexed root-attached `STATIC_FIELD` or `JNI_GLOBAL` entry can be selected regardless of +shape when its state is `FRONTIER` or `EXPANDED` and it is not queued. + +An indexed local-root holder with unknown shape waits for classification. A local holder +classified `NON_CONTAINER` is not persistently selected. + +An indexed holder classified `CONTAINER` can remain eligible after reparenting because its +cached shape still matches when its frontier entry has a parent tag. + +Anchor selection removes entries whose frontier lookup fails or whose state is +`ABANDONED`. It compacts survivors in admission order and removes pruned class-tag entries. + +When rotation reaches anchor selection, the selector takes up to 32 entries. +Its order is leak-tagged, fresh, known containers, then other eligible anchors. + +Separate position cursors scan container and other tiers. +Pruning can shift their positions relative to surviving tags. + +An at-risk FIFO offers a best-effort first look after reparenting or a static-field edge. +Admission is capped globally and per class; excess pushes are dropped. +Rotation drains up to 16 tags and skips tags already selected by the index. + +Drained entries can be lost if no rotation budget remains, object resolution fails, or a +frontier lookup fails during the walk or requeue. + +Budget, deadline, and frontier-cap stops return resolved-but-unwalked entries to the FIFO +front when their frontier entries still exist. + +The index and FIFO share the rotation budget. The 32 plus 16 limit counts tags, not edges +or elapsed time. Leak accumulation has two levels. The first groups admissions by leaf class and parent class. The second ranks parent object tags within the selected group. From 571e44998f2d4d7d4b2abff5ed07e8229eb7f593 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 13:43:14 +0100 Subject: [PATCH 11/20] tests: flush cached reference chains before failing --- .../ExternalProcessReferenceChainTest.java | 28 ++------- .../referencechains/LeakingCacheScenario.java | 60 +++++++++++-------- 2 files changed, 40 insertions(+), 48 deletions(-) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java index 25ab1f15cf..a3cb8916ce 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java @@ -22,19 +22,8 @@ import org.junit.jupiter.api.Test; /** - * Separate-process end-to-end coverage for the reference-chains target-selection mechanism, - * complementing {@link ReferenceChainTrackingTest}'s in-process coverage: runs a "leaking Java app" - * (see {@link LeakingCacheScenario}) in a child JVM and asserts on the child's reported result. - * - *

Why a separate process, not another {@code @Test} in {@code - * ReferenceChainTrackingTest}: {@code runPass()} (referenceChains.cpp) performs exactly one - * root-seeded {@code FollowReferences} walk per search's *entire lifetime* ({@code - * _search_started}); every later pass only expands frontier entries that walk already discovered - * ({@code expandFrontier()}) - it never re-examines GC roots or revisits an already-{@code - * EXPANDED} entry for newly-added children. Since {@code ReferenceChainTracker} is a process-wide - * singleton, only the *first* test to call {@code runPass()} in a given JVM gets a root-seeded - * walk; later tests' independently-rooted locals are invisible to it. A child JVM per scenario gets - * its own fresh singleton and therefore its own first root walk. + * Runs the leak fixture in a child JVM to test reference-chain selection with a fresh tracker. + * Root enumeration repeats only after the adaptive interval, so a fresh process isolates each scenario. */ @Tag("slow") public class ExternalProcessReferenceChainTest extends AbstractProcessProfilerTest { @@ -90,7 +79,7 @@ void shouldReconstructReferrerChainInSeparateProcess() throws Exception { packedCommand, Collections.emptyMap(), // Generous: a separate JVM's startup/classloading cost on top of the up-to-25-round - // growth loop plus grace period (~20s in-process). + // growth loop, up to 20 one-second tail waits plus their dumps, and one final flush. childTimeoutSeconds(90), line -> { if (line.startsWith(LeakingCacheScenario.FOUND_MARKER) @@ -120,13 +109,8 @@ void shouldReconstructReferrerChainInSeparateProcess() throws Exception { } /** - * Mirrors {@link #shouldReconstructReferrerChainInSeparateProcess()}, but against {@link - * StaticFieldGrowingCollectionScenario} instead of {@link LeakingCacheScenario}: a {@code static - * final List} field appended to (never reassigned) after its owning class has already - * been swept once by {@code admitStaticFieldRoots()} (referenceChains.cpp), as opposed to {@code - * LeakingCacheScenario}'s local-variable (stack-root) cache. Checks that {@code - * collectStaleExpandedEntriesForRotation()} re-expands an already-{@code EXPANDED} - * static-field-rooted collection to pick up elements added after its one-time sweep. + * Verifies that a growing static-field collection exposes elements appended after root admission. + * A child JVM keeps the scenario's tracker state isolated from other tests. */ @Test void shouldReconstructReferrerChainForGrowingStaticFieldCollection() throws Exception { @@ -210,7 +194,7 @@ void shouldReconstructReferrerChainForGrowingStaticFieldCollection() throws Exce StaticFieldGrowingCollectionScenario.FOUND_MARKER + "byte[]", resultLine.get(), "Expected a successfully reconstructed chain to a byte[] chunk appended to the static " - + "field's list after its one-time admitStaticFieldRoots() sweep - got: " + + "field's list after its class was admitted as a static-field root - got: " + resultLine.get()); } finally { Files.deleteIfExists(scratchDumpPath); diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index 43c9777b1c..2019d66eea 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -18,22 +18,8 @@ import org.openjdk.jmc.flightrecorder.JfrLoaderToolkit; /** - * The actual "leaking Java app" body run inside a separate child JVM by {@code ExternalLauncher}'s - * {@code leak-cache} mode, driven by {@code ExternalProcessReferenceChainTest}. Deliberately not a - * JUnit test itself - no shared-JVM {@code ReferenceChainTracker} singleton with any other test; - * the whole point is to run alone in its own process so the one-shot root-seeded BFS walk always - * belongs to this scenario (see {@code ExternalProcessReferenceChainTest}'s comment for why an - * earlier in-process attempt failed). - * - *

Why {@code cache} is seeded and populated before the profiler is even started: - * {@code threadLoop()} sleeps one initial cadence *before* its very first {@code shouldRunPass()} - * check, and that first check always returns {@code true} ({@code !_search_started}) - so the - * process's one-and-only root-seeded walk fires roughly one second after {@code startThread()}, or - * earlier if woken by a GC-finish signal (which can race the thread's own startup). An initial - * in-process attempt created {@code cache} only *after* starting the profiler; against a cold JVM - * that lost the race essentially every time - the one-shot walk caught {@code cache} still empty, - * and a frontier entry once marked {@code EXPANDED} is never revisited for new children. Seeding - * before {@code profiler.execute()} removes the race entirely. + * Child-JVM fixture for {@link ExternalProcessReferenceChainTest}; a fresh process isolates tracker state. + * Seed {@code cache} before {@code profiler.execute()} so the first root walk cannot see it empty. */ public final class LeakingCacheScenario { private LeakingCacheScenario() {} @@ -48,6 +34,10 @@ private LeakingCacheScenario() {} // margin. generations=true needs that gate cleared to authorize the BFS thread's first pass. private static final int SEED_EPOCHS_FOR_HYSTERESIS = 15; + // The tracker can cache a chain after the final growth-round dump. + private static final int TAIL_POLL_ATTEMPTS = 20; + private static final long TAIL_POLL_INTERVAL_MILLIS = 1000; + /** * Durable holder for the cache fixture. The discovered-chain gate suppresses chains shallower * than the first real holder hop that are rooted at a TRANSIENT root (stack/JNI local) - a @@ -159,18 +149,24 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD } } - for (int attempt = 0; match == null && attempt < 5; attempt++) { - Thread.sleep(1000); + for (int attempt = 0; match == null && attempt < TAIL_POLL_ATTEMPTS; attempt++) { + Thread.sleep(TAIL_POLL_INTERVAL_MILLIS); profiler.dump(scratchDumpPath); match = findMatch(scratchDumpPath); } + if (match == null) { + // The tracker may cache a live chain after the last tail dump; serialize it before failing. + profiler.dump(scratchDumpPath); + match = findMatch(scratchDumpPath); + } if (match == null) { debugDumpAllChainLeaves(scratchDumpPath); debugDumpCounters(profiler); System.out.println(NOT_FOUND_MARKER); return; } + requireDetectorActivation(profiler, debugBuild); boolean sawHashMapInternals = false; for (IMCType type : match.chain) { if (type.getFullName().startsWith("java.util.HashMap")) { @@ -220,7 +216,7 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD /** * Populates {@code cache} with {@code count} entries under a key namespace ("seed-") disjoint * from the round loop's own ("leak-") - before the profiler (and its BFS thread) even starts, so - * the one-shot root-seeded walk can never catch {@code cache} empty. + * the first root-seeded walk can never catch {@code cache} empty. */ private static void seedInitialBatch(Map cache, int count) { for (int i = 0; i < count; i++) { @@ -229,6 +225,22 @@ private static void seedInitialBatch(Map cache, int count } } + /** Require a candidate when release counters exist; debug logs and no-counter builds skip. */ + private static void requireDetectorActivation(JavaProfiler profiler, boolean debugBuild) { + Long admitted = profiler.getDebugCounters().get("reference_chain_candidate_count"); + System.out.println( + "[debug] detector-activation: reference_chain_candidate_count=" + + admitted + + " debugBuild=" + + debugBuild); + if (!debugBuild && admitted != null && admitted < 1) { + throw new IllegalStateException( + "chain found but the detector never admitted a leak candidate (candidate_count=" + + admitted + + ")"); + } + } + /** Temporary diagnostic: print all native debug counters. */ private static void debugDumpCounters(JavaProfiler profiler) { try { @@ -303,13 +315,9 @@ private static ReferenceChainAssertions.ChainMatch findMatch(Path scratchDumpPat } /** - * Inline padding supplies sampled instances for the detector's eight-survivor per-thread - * threshold while preserving the one-shot allocator threads and number of retained objects. With - * only 32 longs, a failing release run retained at most six sampled instances per worker: its - * one-age cohorts could never qualify, regardless of traversal time. About 1KiB per payload - * provides more sampling opportunities within the same rounds at the 256KiB sampling interval. - * Plain fields keep that allocation volume on CachedPayload itself; a companion array would - * compete for samples without contributing any CachedPayload survivors. + * 128 inline longs (~1KiB per payload) add sampling weight against the 256KiB interval floor in + * {@code ObjectSampler::check}; the allocator threads stay one-shot. Padding only raises sampling + * odds - {@code requireDetectorActivation} proves the detector qualified the class. */ static final class CachedPayload { final String key; From fc4756bc63040ccfbd1c477059ee599d47c414d9 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 13:45:43 +0100 Subject: [PATCH 12/20] referencechains: tighten tracker comments --- ddprof-lib/src/main/cpp/livenessTracker.h | 5 ++-- .../src/main/cpp/referenceChainAnchors.cpp | 14 ++++----- .../src/main/cpp/referenceChainTraversal.cpp | 13 ++++----- ddprof-lib/src/main/cpp/referenceChains.h | 29 ++++++------------- .../src/test/cpp/livenessTracker_ut.cpp | 6 ++-- 5 files changed, 23 insertions(+), 44 deletions(-) diff --git a/ddprof-lib/src/main/cpp/livenessTracker.h b/ddprof-lib/src/main/cpp/livenessTracker.h index 7d912c6002..d93d3149fd 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -1454,9 +1454,8 @@ class alignas(alignof(SpinLock)) LivenessTracker { #ifdef DEBUG /** - * Seeds the JNI traversal fixture's class history and protects it from real - * GC updates. Clear protection while recording another explicit seed so it - * updates the same ring and qualification counters as ordinary samples. + * Protects explicit fixture class history from real GC updates. + * Later explicit seeds update the same ring and qualification counters. */ void seedKlassPopulationSampleForTest( u32 klass_id, u32 count, u64 epoch, jweak *out_evicted = nullptr, diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 56690f585d..18189ca69f 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -144,11 +144,9 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { std::unordered_set fresh_kept_tags; const size_t fresh_queue_len = _static_anchor_fresh_queue.size(); _frontier->withSharedLock([&](const FrontierTable *frontier) { - // Fused prune-and-partition pass: an indexed holder whose frontier entry died is dropped from - // the index here - dead entries would otherwise accumulate for the tracker's lifetime (the - // only other removals are the stop/reset clears), and released tags get re-minted, so the - // same holder re-indexes under its fresh tag. Survivors compact down, keeping admission - // order; the tier positions below are the compacted ones the cursors consume. + // Drop dead/ABANDONED entries and compact survivors in admission order before tier selection. + // Released tags are re-minted, so a later observation can index the holder under its fresh tag. + // The cursors below use the compacted positions. size_t kept = 0; for (size_t i = 0; i < _static_anchor_index.size(); i++) { jlong tag = _static_anchor_index[i]; @@ -365,10 +363,8 @@ void ReferenceChainTracker::indexAnchorForRotation(jlong tag, auto inserted = _static_anchor_index_class_tags.try_emplace(tag, own_class_tag); if (!inserted.second) { - // First sight may have seen the holder before its class was tagged - // (JVMTI reports class_tag == 0 for such roots); the callback that - // delivers the resolved tag must upgrade the stored value, or the - // container-shape fallback in isSelectableAnchor() stays dead forever. + // First sight may report class_tag == 0; a later resolved-tag callback must upgrade it + // or the container-shape fallback stays unavailable for this holder. if (own_class_tag != 0 && inserted.first->second == 0) { inserted.first->second = own_class_tag; } diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 4f9a3e0546..ce0780f8c6 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -140,10 +140,9 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( ctx->tracker->addToStaticAnchorIndex(*tag_ptr, class_tag, translated_root_kind); } - // Remember local holders before expansion can reparent them into a deeper - // chain. Known collections still need bounded descend walks after that change - // to observe replacement backing storage. Classification runs outside this - // callback; unknown types are indexed but do not qualify for a walk yet. + // Record local holders before expansion can reparent them into a deeper chain. + // Known collections need bounded revisits after reparenting to observe replaced storage. + // Classification runs later; unknown types are indexed but cannot be walked yet. if (isTransientRootKind(translated_root_kind) && class_tag != 0 && *tag_ptr > 0 && !isLeakTag(*tag_ptr)) { auto shape = ctx->tracker->_class_shape_cache.find(class_tag); @@ -402,10 +401,8 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, std::vector leak_accumulation_tags = collectLeakAccumulationCandidatesForRotation( LEAK_ACCUMULATION_ROTATION_BUDGET); - // Also re-walk a bounded, rotating subset of EXPANDED entries regardless of root attribution: a - // mutable field reassigned since an object's one-time expansion - e.g. HashMap.table on resize - - // is otherwise never observed again, silently orphaning everything only reachable through the - // field's current value. + // Revisit a bounded, rotating subset of EXPANDED entries: their one-time expansion cannot observe + // later mutable-field replacements (e.g. HashMap.table resize) without this rotation. std::vector stale_expanded_tags = collectStaleExpandedEntriesForRotation(STALE_EXPANDED_ROTATION_BUDGET); // Candidate-scoped reach, prong 2: root-attached static holders are descend-walked directly (see diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index 7677f3b2e6..717a84c3d9 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -510,17 +510,13 @@ class ReferenceChainTracker { std::unordered_map _static_anchor_fifo_klass_counts; static constexpr u32 STATIC_ANCHOR_ATRISK_PER_KLASS_CAP = 64; - // Index of holders observed at durable root edges or local roots. Known collections remain - // eligible after reparenting, so replacing their storage is still observed. - // Non-collection local holders are excluded after classification. - // collectStaticFieldAnchorsForRotation() iterates these anchors rather than - // scanning the full frontier table. + // Index durable roots and local roots with unknown or CONTAINER shape. + // Collections remain eligible after reparenting; classified non-collection locals are excluded. + // Rotation walks this index instead of scanning the full frontier table. std::vector _static_anchor_index; - // Own class tag per indexed holder (the runtime class tag of the holder), keyed by the holder's - // frontier tag. A holder first seen before its class was tagged is stored with 0 and refreshed - // by the next callback reporting the resolved class tag - the value is the sole input of the - // container-shape fallback in isSelectableAnchor() for reparented holders. + // Runtime class tag per indexed holder, keyed by frontier tag; 0 means the class is not resolved. + // A later callback upgrades 0 so isSelectableAnchor() can retain reparented containers. std::unordered_map _static_anchor_index_class_tags; // Shape of a class as an anchor candidate: does the class implement java/util/Collection or @@ -1045,13 +1041,8 @@ class ReferenceChainTracker { // attribution. std::vector collectStaleRootKindEntriesForRotation(int max_count); - // Bounded rotating re-expansion for stale mutable fields: expandFrontier() observes an object's - // outgoing references exactly once (on the FollowReferences call that marks it EXPANDED) and - // never revisits it, so a field that is later reassigned to point at a different object - e.g. - // HashMap.table on resize - has its new value permanently unobserved once the map itself is - // EXPANDED; the old table array's own frontier entry eventually resolves to a dead object via - // GetObjectsWithTags and gets silently cleared with zero children, orphaning everything only - // reachable through the *current* table. + // Bounded rotating re-expansion for stale mutable fields. expandFrontier() marks each entry + // EXPANDED once, so this rotation is needed to observe replacements such as HashMap.table resize. std::vector collectStaleExpandedEntriesForRotation(int max_count); // Bounded rotating re-expansion targeting the accumulation point of a klass LivenessTracker has @@ -1101,10 +1092,8 @@ class ReferenceChainTracker { // cannot be resolved yet (leaves them at -1 so the next call retries). bool resolveContainerInterfaceTags(jvmtiEnv *jvmti, JNIEnv *jni); - // Lazy shape reconciliation for the anchor index: scans the anchor index's class tags - // (_static_anchor_index_class_tags) for class tags not yet in _class_shape_cache, resolves up to - // ANCHOR_SHAPE_RECONCILE_BUDGET of them per pass via one GetObjectsWithTags call (class objects - // are tagged with their class tags) and classifies each. + // Reconcile up to ANCHOR_SHAPE_RECONCILE_BUDGET unknown anchor classes per pass. + // One GetObjectsWithTags call resolves their class objects before classification. void reconcileAnchorClassShapes(jvmtiEnv *jvmti, JNIEnv *jni); // Pops up to max_count AtRiskAnchor entries off _static_anchor_fifo's front into `out` // (appending), decrementing each popped entry's class occupancy in diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index be479eee4b..bf2eab363c 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1524,10 +1524,8 @@ TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsFirstMinimalSlot) { EXPECT_FALSE(contains_tid(1)); } -// The victim scan must consider slot 0 a candidate: the global minimum (thread 1, the only count -// that clears the bar here) sits at slot 0, and the scan evicts it on every overflow arrival, so -// its history never reaches the fold. (Pins the scan's min-selection; comparing slot 0 with -// itself at a loop start of 0 is a no-op, so no mutation of the start index is observable.) +// The unique minimum sits in slot 0 and is evicted on every overflow arrival, so its qualifying +// history never reaches the fold. This pins slot-0 eligibility in the victim scan. TEST_F(SelectLeakCandidatesTest, ScratchOverflowEvictsTheGlobalMinimumThread) { LivenessTracker *tracker = LivenessTracker::instance(); std::vector> cohorts; From 94ffce252cb737a706d34e7a368028c96f7e16e3 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 15:07:40 +0100 Subject: [PATCH 13/20] referencechains: preserve bounded anchor classification --- .../src/main/cpp/referenceChainAnchors.cpp | 101 +++++++------ .../src/main/cpp/referenceChainTraversal.cpp | 6 +- ddprof-lib/src/main/cpp/referenceChains.h | 36 +++-- .../test/cpp/referenceChainsAnchorTests.inc | 138 ++++++++++++++++++ .../test/cpp/referenceChainsTestAccessors.h | 36 ++++- .../LiveHeapReferenceChainsImplementation.md | 18 ++- 6 files changed, 267 insertions(+), 68 deletions(-) diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 18189ca69f..12775e17b3 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -156,14 +156,22 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { _static_anchor_index_class_tags.erase(tag); continue; } - _static_anchor_index[kept] = tag; - size_t pos = kept; - kept++; jlong own_class_tag = 0; + bool transient_root = false; auto class_it = _static_anchor_index_class_tags.find(tag); if (class_it != _static_anchor_index_class_tags.end()) { - own_class_tag = class_it->second; + own_class_tag = class_it->second.class_tag; + transient_root = class_it->second.transient_root; + } + auto shape_it = _class_shape_cache.find(own_class_tag); + if (transient_root && shape_it != _class_shape_cache.end() && + shape_it->second == static_cast(AnchorClassShape::NON_CONTAINER)) { + _static_anchor_index_class_tags.erase(tag); + continue; } + _static_anchor_index[kept] = tag; + size_t pos = kept; + kept++; if (!isSelectableAnchor(entry, own_class_tag) || (entry.state != FrontierEntryState::FRONTIER && entry.state != FrontierEntryState::EXPANDED) || @@ -172,21 +180,20 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { } if (entry.leak_tag != 0) { leak_picks.push_back(TierPick{pos, tag}); + } else if (shape_it != _class_shape_cache.end() && + (shape_it->second == static_cast(AnchorClassShape::CONTAINER) || + shape_it->second == + static_cast(AnchorClassShape::UNKNOWN_TRUNCATED))) { + container_picks.push_back(TierPick{pos, tag}); } else { - auto shape_it = _class_shape_cache.find(own_class_tag); - if (shape_it != _class_shape_cache.end() && - shape_it->second == (u8)AnchorClassShape::CONTAINER) { - container_picks.push_back(TierPick{pos, tag}); - } else { - other_picks.push_back(TierPick{pos, tag}); - } + other_picks.push_back(TierPick{pos, tag}); } } _static_anchor_index.resize(kept); idx_size = kept; - // Fresh-lane drain. Every queue entry is popped (its ONE first look is spent either way): kept - // if eligible AND (container-shaped OR not-yet-classified) AND room remains in the budget; - // dropped otherwise. + // Fresh-lane drain. Every queue entry is popped (its ONE first look is spent either way): keep + // selectable anchors (durable root-attached, container-shaped, or truncated) if room remains; + // unknown transient anchors wait for class-shape reconciliation before selection. int fresh_room = max_count - (int)leak_picks.size(); size_t drain_pos = fresh_queue_len <= idx_size ? idx_size - fresh_queue_len : 0; while (!_static_anchor_fresh_queue.empty()) { @@ -215,7 +222,7 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { jlong own_class_tag = 0; auto class_it = _static_anchor_index_class_tags.find(tag); if (class_it != _static_anchor_index_class_tags.end()) { - own_class_tag = class_it->second; + own_class_tag = class_it->second.class_tag; } FrontierEntry entry{}; if (!frontier->lookupLocked(tag, &entry) || @@ -226,14 +233,13 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { continue; // dead/ineligible/queued/leak-tier: first look spent, not // fresh-kept (the leak tier selects it via the scan if it is leak-tagged) } - bool keep = false; // container or not-yet-classified rides the - // lane; the wrapper admits one pass before reconcile can classify its - // class auto shape_it = _class_shape_cache.find(own_class_tag); - keep = shape_it == _class_shape_cache.end() || - shape_it->second == (u8)AnchorClassShape::CONTAINER; + bool keep = shape_it == _class_shape_cache.end() || + shape_it->second == static_cast(AnchorClassShape::CONTAINER) || + shape_it->second == + static_cast(AnchorClassShape::UNKNOWN_TRUNCATED); if (!keep) { - continue; // classified non-container: the other tier owns it + continue; // classified non-container: the other tier owns it (durable roots only) } fresh_picks.push_back(TierPick{pos, tag}); fresh_kept_tags.insert(tag); @@ -342,7 +348,7 @@ void ReferenceChainTracker::addToStaticAnchorIndex(jlong tag, root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { return; } - indexAnchorForRotation(tag, own_class_tag); + indexAnchorForRotation(tag, own_class_tag, false); } bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, @@ -354,19 +360,27 @@ bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, } auto shape = _class_shape_cache.find(own_class_tag); return shape != _class_shape_cache.end() && - shape->second == (u8)AnchorClassShape::CONTAINER; + (shape->second == static_cast(AnchorClassShape::CONTAINER) || + shape->second == static_cast(AnchorClassShape::UNKNOWN_TRUNCATED)); } void ReferenceChainTracker::indexAnchorForRotation(jlong tag, - jlong own_class_tag) { + jlong own_class_tag, + bool transient_root) { // Dedup: a push at first admission and another at upgrade would double-add. - auto inserted = - _static_anchor_index_class_tags.try_emplace(tag, own_class_tag); + auto inserted = _static_anchor_index_class_tags.try_emplace( + tag, StaticAnchorIndexEntry{own_class_tag, transient_root}); if (!inserted.second) { + StaticAnchorIndexEntry &entry = inserted.first->second; // First sight may report class_tag == 0; a later resolved-tag callback must upgrade it // or the container-shape fallback stays unavailable for this holder. - if (own_class_tag != 0 && inserted.first->second == 0) { - inserted.first->second = own_class_tag; + if (own_class_tag != 0 && entry.class_tag == 0) { + entry.class_tag = own_class_tag; + } + // A durable observation keeps the anchor eligible even if a later callback also reports a + // transient root for the same holder. + if (!transient_root) { + entry.transient_root = false; } return; } @@ -424,14 +438,12 @@ bool ReferenceChainTracker::resolveContainerInterfaceTags( return _collection_iface_class_tag != 0 && _map_iface_class_tag != 0; } -bool ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, - JNIEnv *jni, - jclass klass) { - // LIFO (depth-first) walk over the superclass chain + every visited class's interfaces, not BFS: - // interfaces are pushed after the superclass, so under LIFO every interface subtree is explored - // before the superclass chain - the only path to an inherited Collection/Map. The 64-pop budget - // counts duplicate pops too (already-visited classes burn hops). GetTag() is compared against the - // two cached interface class tags. +ReferenceChainTracker::AnchorClassShape +ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, + JNIEnv *jni, + jclass klass) { + // LIFO (depth-first) walk over superclasses and interfaces; the 64-pop budget includes duplicate + // tagged classes so hierarchy diamonds cannot expand this per-class walk without a bound. std::vector work; std::unordered_set visited; work.push_back(klass); @@ -484,7 +496,7 @@ bool ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, work.push_back(ifaces[i]); } } - jvmti->Deallocate((unsigned char *)ifaces); + jvmti->Deallocate(reinterpret_cast(ifaces)); } // `cur` is either the caller-provided klass (caller-managed ref - NOT deleted here) or a ref // this walk minted (GetSuperclass/ GetImplementedInterfaces locals, deleted immediately after @@ -493,15 +505,20 @@ bool ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, jni->DeleteLocalRef(cur); } } - // Single exit: every remaining ref minted into `work` (early hop-bound exit or the found-break) + // Single exit: every remaining ref minted into `work` (budget exhaustion or the found-break) // is deleted here rather than leaking locals for the process lifetime (the engine thread never // detaches). + bool truncated = !found && !work.empty(); for (jclass r : work) { if (r != nullptr && r != klass) { jni->DeleteLocalRef(r); } } - return found; + if (found) { + return AnchorClassShape::CONTAINER; + } + return truncated ? AnchorClassShape::UNKNOWN_TRUNCATED + : AnchorClassShape::NON_CONTAINER; } void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, @@ -518,7 +535,7 @@ void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, unknown.reserve(8); std::unordered_set seen; for (const auto &index_entry : _static_anchor_index_class_tags) { - jlong class_tag = index_entry.second; + jlong class_tag = index_entry.second.class_tag; if (class_tag == 0 || seen.count(class_tag) > 0 || _class_shape_cache.count(class_tag) > 0) { continue; @@ -570,9 +587,7 @@ void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, } continue; } - AnchorClassShape shape = classImplementsContainerOrMap(jvmti, jni, klass) - ? AnchorClassShape::CONTAINER - : AnchorClassShape::NON_CONTAINER; + AnchorClassShape shape = classImplementsContainerOrMap(jvmti, jni, klass); _class_shape_cache[class_tag] = (u8)shape; // GetObjectsWithTags() returned a local ref for every resolved class - this runs on the // long-lived BFS thread, where undeleted locals accumulate until detach and pin their classes diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index ce0780f8c6..711adf1bb1 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -147,8 +147,10 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( *tag_ptr > 0 && !isLeakTag(*tag_ptr)) { auto shape = ctx->tracker->_class_shape_cache.find(class_tag); if (shape == ctx->tracker->_class_shape_cache.end() || - shape->second == (u8)AnchorClassShape::CONTAINER) { - ctx->tracker->indexAnchorForRotation(*tag_ptr, class_tag); + shape->second == static_cast(AnchorClassShape::CONTAINER) || + shape->second == static_cast( + ReferenceChainTracker::AnchorClassShape::UNKNOWN_TRUNCATED)) { + ctx->tracker->indexAnchorForRotation(*tag_ptr, class_tag, true); } } return JVMTI_ITERATION_CONTINUE; diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index 717a84c3d9..f0ae180179 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -510,18 +510,28 @@ class ReferenceChainTracker { std::unordered_map _static_anchor_fifo_klass_counts; static constexpr u32 STATIC_ANCHOR_ATRISK_PER_KLASS_CAP = 64; - // Index durable roots and local roots with unknown or CONTAINER shape. - // Collections remain eligible after reparenting; classified non-collection locals are excluded. + // Index durable roots and local roots with unknown or container-shaped classes. Transient-only + // entries classified NON_CONTAINER are pruned during anchor compaction; durable roots are retained. // Rotation walks this index instead of scanning the full frontier table. std::vector _static_anchor_index; - // Runtime class tag per indexed holder, keyed by frontier tag; 0 means the class is not resolved. - // A later callback upgrades 0 so isSelectableAnchor() can retain reparented containers. - std::unordered_map _static_anchor_index_class_tags; + // Runtime class tag and root durability per indexed holder, keyed by frontier tag. A later + // callback upgrades an unresolved class tag, while durable observations supersede transient ones. + struct StaticAnchorIndexEntry { + jlong class_tag; + bool transient_root; + }; + std::unordered_map _static_anchor_index_class_tags; // Shape of a class as an anchor candidate: does the class implement java/util/Collection or - // java/util/Map (directly or via superclasses/ interfaces)? - enum class AnchorClassShape : u8 { UNKNOWN = 0, CONTAINER = 1, NON_CONTAINER = 2 }; + // java/util/Map (directly or via superclasses/interfaces)? UNKNOWN_TRUNCATED preserves a bounded + // hierarchy walk that ended before all distinct classes could be examined. + enum class AnchorClassShape : u8 { + UNKNOWN = 0, + CONTAINER = 1, + NON_CONTAINER = 2, + UNKNOWN_TRUNCATED = 3 + }; // class tag -> AnchorClassShape, process-lifetime (class tags are never reused - the shared // class-tag allocator is deliberately not reset by restartSearch()). @@ -1076,17 +1086,17 @@ class ReferenceChainTracker { // or JNI_GLOBAL). void addToStaticAnchorIndex(jlong tag, jlong own_class_tag, u8 root_kind); // Shared deduplicated index insertion for durable roots and local holders. - void indexAnchorForRotation(jlong tag, jlong own_class_tag); + void indexAnchorForRotation(jlong tag, jlong own_class_tag, + bool transient_root); // Appends the drained at-risk anchors to the combined static-anchor selection, skipping tags the // persistent tiers already selected. Static: no member state, exposed for the dedup test. static void mergeAtRiskAnchors(std::vector &selection, const std::vector &drained); - // True iff `klass` implements java/util/Collection or java/util/Map, directly or transitively - // (superclass chain + interfaces of every visited class, depth-bounded, visited set to survive - // interface diamonds). - bool classImplementsContainerOrMap(jvmtiEnv *jvmti, JNIEnv *jni, - jclass klass); + // Classifies whether `klass` implements java/util/Collection or java/util/Map. The bounded walk + // returns UNKNOWN_TRUNCATED rather than treating unvisited hierarchy nodes as a completed miss. + AnchorClassShape classImplementsContainerOrMap(jvmtiEnv *jvmti, JNIEnv *jni, + jclass klass); // Resolve _collection_iface_class_tag/_map_iface_class_tag once; returns false if the interfaces // cannot be resolved yet (leaves them at -1 so the next call retries). diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 7f9af7f514..32ad79b336 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -1193,6 +1193,144 @@ TEST_F(ReferenceChainsBfsTest, IdleLoopTailPollRegistersLaterCandidateOnce) { EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); } +TEST_F(ReferenceChainsBfsTest, ClassShapeWalkMarksBudgetExhaustionUnknown) { + constexpr int kClassCount = 65; + constexpr jlong kCollectionTag = -9000; + constexpr jlong kMapTag = -9001; + std::vector classes; + classes.reserve(kClassCount); + for (int i = 0; i < kClassCount; i++) { + classes.push_back(reinterpret_cast(0xA000 + (i * 16))); + } + for (int i = 0; i < kClassCount; i++) { + void *super = i + 1 < kClassCount ? classes[i + 1] : nullptr; + field_decode_hierarchy[classes[i]] = {false, super, {}, {}}; + tags[classes[i]] = -1000 - i; + } + + const u8 shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(classes[0]), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)); +} + +TEST_F(ReferenceChainsBfsTest, DuplicateHierarchyVisitsExhaustBudgetWithoutFalseNegative) { + constexpr jlong kCollectionTag = -9100; + constexpr jlong kMapTag = -9101; + void *root = reinterpret_cast(0xB000); + void *target = reinterpret_cast(0xB010); + void *repeated = reinterpret_cast(0xB020); + std::vector interfaces = {target}; + interfaces.insert(interfaces.end(), 70, repeated); + field_decode_hierarchy[root] = {false, nullptr, interfaces, {}}; + field_decode_hierarchy[target] = {true, nullptr, {}, {}}; + field_decode_hierarchy[repeated] = {true, nullptr, {}, {}}; + tags[root] = -1100; + tags[target] = kCollectionTag; + tags[repeated] = -1101; + + const u8 shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest(shape)) + << "duplicate worklist entries consume the bound but cannot cache a false miss"; +} + +TEST_F(ReferenceChainsBfsTest, TransientNonContainerAnchorsArePruned) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + FrontierTable *frontier = tracker->frontierTable(); + const int transient_noncontainer = addNode(); + const int durable_noncontainer = addNode(); + const int unknown_transient = addNode(); + const int truncated_transient = addNode(); + const jlong transient_tag = tracker->nextTag(); + const jlong durable_tag = tracker->nextTag(); + const jlong unknown_tag = tracker->nextTag(); + const jlong truncated_tag = tracker->nextTag(); + node_tags[transient_noncontainer] = transient_tag; + node_tags[durable_noncontainer] = durable_tag; + node_tags[unknown_transient] = unknown_tag; + node_tags[truncated_transient] = truncated_tag; + constexpr jlong transient_class_tag = -501; + constexpr jlong durable_class_tag = -502; + constexpr jlong unknown_class_tag = -503; + constexpr jlong truncated_class_tag = -504; + + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, transient_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, durable_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, unknown_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, truncated_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + + ReferenceChainPassContext ctx{}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, transient_class_tag, + &node_tags[transient_noncontainer], &ctx)); + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_JNI_GLOBAL, durable_class_tag, + &node_tags[durable_noncontainer], &ctx)); + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, unknown_class_tag, + &node_tags[unknown_transient], &ctx)); + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, truncated_class_tag, + &node_tags[truncated_transient], &ctx)); + + // Classification follows indexing: the first root callback admits these as unknown. + ReferenceChainsTestAccessor::primeClassShapeForTest(transient_class_tag, false); + ReferenceChainsTestAccessor::primeClassShapeForTest(durable_class_tag, false); + ReferenceChainsTestAccessor::primeTruncatedClassShapeForTest(truncated_class_tag); + auto selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(8); + auto has_tag = [&](jlong tag) { + return std::find(selected.begin(), selected.end(), tag) != selected.end(); + }; + EXPECT_FALSE(has_tag(transient_tag)); + EXPECT_TRUE(has_tag(durable_tag)); + EXPECT_FALSE(has_tag(unknown_tag)); + EXPECT_TRUE(has_tag(truncated_tag)); + + // Unknown transient anchors remain indexed for reconciliation but are not walked until a + // bounded hierarchy check confirms a container or reports truncation. + ReferenceChainsTestAccessor::primeClassShapeForTest(unknown_class_tag, true); + selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(8); + EXPECT_NE(selected.end(), std::find(selected.begin(), selected.end(), unknown_tag)); + + const auto indexed = ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest(); + EXPECT_EQ(indexed.end(), std::find(indexed.begin(), indexed.end(), transient_tag)); + EXPECT_NE(indexed.end(), std::find(indexed.begin(), indexed.end(), durable_tag)); + EXPECT_NE(indexed.end(), std::find(indexed.begin(), indexed.end(), unknown_tag)); + EXPECT_NE(indexed.end(), std::find(indexed.begin(), indexed.end(), truncated_tag)); + EXPECT_FALSE(ReferenceChainsTestAccessor::staticAnchorClassTagMapContainsForTest( + transient_tag)); + EXPECT_TRUE(ReferenceChainsTestAccessor::staticAnchorClassTagMapContainsForTest( + durable_tag)); + EXPECT_TRUE(ReferenceChainsTestAccessor::staticAnchorClassTagMapContainsForTest( + unknown_tag)); + EXPECT_TRUE(ReferenceChainsTestAccessor::staticAnchorClassTagMapContainsForTest( + truncated_tag)); +} + // Admission appends to a bounded fresh queue; the 1025th eligible anchor evicts the oldest entry. TEST_F(ReferenceChainsBfsTest, FreshAnchorQueueDropsOldestPastCap) { Arguments args; diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index 44cf21c2df..49433c838b 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -548,6 +548,11 @@ class ReferenceChainsTestAccessor { return ReferenceChainTracker::instance()->_static_anchor_index; } + static bool staticAnchorClassTagMapContainsForTest(jlong tag) { + return ReferenceChainTracker::instance() + ->_static_anchor_index_class_tags.count(tag) > 0; + } + static void mergeAtRiskAnchorsForTest( std::vector &selection, const std::vector &drained) { @@ -910,8 +915,35 @@ class ReferenceChainsTestAccessor { static void primeClassShapeForTest(jlong class_tag, bool container) { ReferenceChainTracker::instance()->_class_shape_cache[class_tag] = container - ? (u8)ReferenceChainTracker::AnchorClassShape::CONTAINER - : (u8)ReferenceChainTracker::AnchorClassShape::NON_CONTAINER; + ? static_cast(ReferenceChainTracker::AnchorClassShape::CONTAINER) + : static_cast(ReferenceChainTracker::AnchorClassShape::NON_CONTAINER); + } + + static void primeTruncatedClassShapeForTest(jlong class_tag) { + ReferenceChainTracker::instance()->_class_shape_cache[class_tag] = + static_cast( + ReferenceChainTracker::AnchorClassShape::UNKNOWN_TRUNCATED); + } + + static u8 classifyAnchorClassForTest(jvmtiEnv *jvmti, JNIEnv *jni, + jclass klass, + jlong collection_class_tag, + jlong map_class_tag) { + ReferenceChainTracker *t = ReferenceChainTracker::instance(); + t->_collection_iface_class_tag = collection_class_tag; + t->_map_iface_class_tag = map_class_tag; + return static_cast( + t->classImplementsContainerOrMap(jvmti, jni, klass)); + } + + static bool isUnknownTruncatedClassShapeForTest(u8 shape) { + return shape == static_cast( + ReferenceChainTracker::AnchorClassShape::UNKNOWN_TRUNCATED); + } + + static bool isContainerClassShapeForTest(u8 shape) { + return shape == static_cast( + ReferenceChainTracker::AnchorClassShape::CONTAINER); } // At-risk static-anchor FIFO (see _static_anchor_fifo in referenceChains.h). diff --git a/doc/architecture/LiveHeapReferenceChainsImplementation.md b/doc/architecture/LiveHeapReferenceChainsImplementation.md index a351ccdfe1..cd8edc81b4 100644 --- a/doc/architecture/LiveHeapReferenceChainsImplementation.md +++ b/doc/architecture/LiveHeapReferenceChainsImplementation.md @@ -210,24 +210,26 @@ positive frontier tags for stack/JNI-local holders when their class tag is known is unknown or `CONTAINER`; raw leak tags are excluded. `reconcileAnchorClassShapes()` can classify up to 128 distinct unknown anchor classes -in a pass that reaches rotation. It checks their class hierarchy and interfaces for -`Collection` or `Map` with a bounded walk. +in a pass that reaches rotation. Each class walk checks at most 64 worklist entries for +`Collection` or `Map`; duplicate interfaces consume entries in this bound. The shape cache uses process-lifetime class tags and survives search restarts. The index and side map are per-search. -If either interface tag is unavailable, unclassified shapes remain unknown. -A per-class walk can cache `NON_CONTAINER` when a failed lookup or bound leaves no match. -That label is the walk's result, not proof the class lacks either interface. +If interface tags are unavailable, shapes remain unknown. A walk with pending hierarchy entries at +the 64-pop limit caches `UNKNOWN_TRUNCATED`, which remains selectable; only a completed no-match +walk caches `NON_CONTAINER`. An indexed root-attached `STATIC_FIELD` or `JNI_GLOBAL` entry can be selected regardless of shape when its state is `FRONTIER` or `EXPANDED` and it is not queued. -An indexed local-root holder with unknown shape waits for classification. A local holder -classified `NON_CONTAINER` is not persistently selected. +Unknown local-root holders remain indexed but are not selected until classified `CONTAINER` or +`UNKNOWN_TRUNCATED`. A definitive `NON_CONTAINER` removes transient-only entries from both index and +side map; durable static/JNI-global roots remain indexed and root-attached entries stay selectable. An indexed holder classified `CONTAINER` can remain eligible after reparenting because its -cached shape still matches when its frontier entry has a parent tag. +cached shape still matches when its frontier entry has a parent tag. A truncated classification +also remains eligible rather than being mistaken for a completed non-match. Anchor selection removes entries whose frontier lookup fails or whose state is `ABANDONED`. It compacts survivors in admission order and removes pruned class-tag entries. From 681359f0970a39ae73dbea3737807fcf015ebc34 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 17:00:28 +0100 Subject: [PATCH 14/20] referencechains: keep incomplete shape lookups unclassified --- .../src/main/cpp/referenceChainAnchors.cpp | 34 ++++++++--- .../test/cpp/referenceChainsAnchorTests.inc | 61 +++++++++++++++++++ .../src/test/cpp/referenceChainsMockHeap.h | 16 +++++ .../test/cpp/referenceChainsTestAccessors.h | 5 -- .../LiveHeapReferenceChainsImplementation.md | 6 +- 5 files changed, 104 insertions(+), 18 deletions(-) diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 12775e17b3..9e159594c3 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -448,12 +448,14 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, std::unordered_set visited; work.push_back(klass); bool found = false; + bool incomplete = false; int hops = 0; while (!found && !work.empty() && hops++ < 64) { jclass cur = work.back(); work.pop_back(); jlong cur_tag = 0; if (jvmti->GetTag(cur, &cur_tag) != JVMTI_ERROR_NONE || cur_tag == 0) { + incomplete = true; // Early exit: the popped ref is this walk's own (GetSuperclass/ GetImplementedInterfaces // local, or the caller's klass) - delete it like the loop bottom does, or the long-lived // engine thread leaks a JNI local ref per untagged hop. @@ -481,21 +483,33 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, break; } jclass super = jni->GetSuperclass(cur); - if (!jniExceptionCheck(jni) && super != nullptr) { - work.push_back(super); - } else { + if (jniExceptionCheck(jni)) { + incomplete = true; jni->ExceptionClear(); + if (super != nullptr) { + jni->DeleteLocalRef(super); + } + } else if (super != nullptr) { + work.push_back(super); } jint iface_count = 0; jclass *ifaces = nullptr; - if (jvmti->GetImplementedInterfaces(cur, &iface_count, &ifaces) == - JVMTI_ERROR_NONE && - ifaces != nullptr) { - for (jint i = 0; i < iface_count; i++) { - if (ifaces[i] != nullptr) { - work.push_back(ifaces[i]); + jvmtiError interfaces_error = + jvmti->GetImplementedInterfaces(cur, &iface_count, &ifaces); + if (interfaces_error == JVMTI_ERROR_NONE) { + if (iface_count > 0 && ifaces == nullptr) { + incomplete = true; + } else if (ifaces != nullptr) { + for (jint i = 0; i < iface_count; i++) { + if (ifaces[i] != nullptr) { + work.push_back(ifaces[i]); + } } } + } else { + incomplete = true; + } + if (ifaces != nullptr) { jvmti->Deallocate(reinterpret_cast(ifaces)); } // `cur` is either the caller-provided klass (caller-managed ref - NOT deleted here) or a ref @@ -508,7 +522,7 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, // Single exit: every remaining ref minted into `work` (budget exhaustion or the found-break) // is deleted here rather than leaking locals for the process lifetime (the engine thread never // detaches). - bool truncated = !found && !work.empty(); + bool truncated = incomplete || (!found && !work.empty()); for (jclass r : work) { if (r != nullptr && r != klass) { jni->DeleteLocalRef(r); diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 32ad79b336..d34778531a 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -1237,6 +1237,67 @@ TEST_F(ReferenceChainsBfsTest, DuplicateHierarchyVisitsExhaustBudgetWithoutFalse << "duplicate worklist entries consume the bound but cannot cache a false miss"; } +TEST_F(ReferenceChainsBfsTest, ClassShapeWalkKeepsLookupFailuresUnknown) { + constexpr jlong kCollectionTag = -9200; + constexpr jlong kMapTag = -9201; + void *missing_tag_root = reinterpret_cast(0xC000); + void *untagged_interface = reinterpret_cast(0xC010); + void *collection_interface = reinterpret_cast(0xC020); + tags[missing_tag_root] = -1200; + tags[collection_interface] = kCollectionTag; + field_decode_hierarchy[missing_tag_root] = + {false, nullptr, {untagged_interface}, {}}; + field_decode_hierarchy[untagged_interface] = + {true, nullptr, {collection_interface}, {}}; + field_decode_hierarchy[collection_interface] = {true, nullptr, {}, {}}; + + u8 shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(missing_tag_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "an untagged hierarchy node hides an unexamined interface"; + + void *tag_error_root = reinterpret_cast(0xC030); + tags[tag_error_root] = -1201; + fail_get_tag.insert(tag_error_root); + shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(tag_error_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "a failed GetTag cannot prove a completed non-match"; + fail_get_tag.clear(); + + void *super_error_root = reinterpret_cast(0xC040); + tags[super_error_root] = -1202; + field_decode_hierarchy[super_error_root] = {false, nullptr, {}, {}}; + fail_get_superclass.insert(super_error_root); + shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(super_error_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "a superclass exception cannot prove a completed non-match"; + EXPECT_FALSE(pending_exception); + fail_get_superclass.clear(); + + void *interface_error_root = reinterpret_cast(0xC050); + tags[interface_error_root] = -1203; + shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(interface_error_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "a JVMTI interface lookup error cannot prove a completed non-match"; + + void *malformed_root = reinterpret_cast(0xC060); + tags[malformed_root] = -1204; + field_decode_hierarchy[malformed_root] = {false, nullptr, {}, {}}; + malformed_interfaces.insert(malformed_root); + shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(malformed_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "a missing interface array cannot prove a completed non-match"; +} + TEST_F(ReferenceChainsBfsTest, TransientNonContainerAnchorsArePruned) { Arguments args; ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); diff --git a/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h b/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h index 542c6deae3..e7872219b3 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h +++ b/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h @@ -78,6 +78,9 @@ class ReferenceChainsMockHeap { JNIEnv_ mock_jni{}; std::unordered_map tags; + std::unordered_set fail_get_tag; + std::unordered_set fail_get_superclass; + std::unordered_set malformed_interfaces; std::vector classes; std::vector script; std::vector node_tags; @@ -319,6 +322,10 @@ class ReferenceChainsMockHeap { static jvmtiError JNICALL mock_GetTag(jvmtiEnv *, jobject object, jlong *tag_ptr) { MockAllocPause alloc_pause; + if (active_fixture->fail_get_tag.count(object) > 0) { + *tag_ptr = 0; + return JVMTI_ERROR_INTERNAL; + } int idx = active_fixture->indexOfNode(object); if (idx >= 0) { *tag_ptr = active_fixture->node_tags[idx]; @@ -401,6 +408,10 @@ class ReferenceChainsMockHeap { return JVMTI_ERROR_NONE; } static jclass JNICALL mock_JniGetSuperclass(JNIEnv *, jclass cls) { + if (active_fixture->fail_get_superclass.count(cls) > 0) { + active_fixture->pending_exception = true; + return nullptr; + } auto it = active_fixture->field_decode_hierarchy.find(cls); return it == active_fixture->field_decode_hierarchy.end() ? nullptr @@ -412,6 +423,11 @@ class ReferenceChainsMockHeap { if (it == active_fixture->field_decode_hierarchy.end()) { return JVMTI_ERROR_INVALID_CLASS; } + if (active_fixture->malformed_interfaces.count(cls) > 0) { + *count_ptr = 1; + *ifaces_ptr = nullptr; + return JVMTI_ERROR_NONE; + } const std::vector &ifaces = it->second.interfaces; *count_ptr = (jint)ifaces.size(); *ifaces_ptr = ifaces.empty() diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index 49433c838b..7b77f8759b 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -941,11 +941,6 @@ class ReferenceChainsTestAccessor { ReferenceChainTracker::AnchorClassShape::UNKNOWN_TRUNCATED); } - static bool isContainerClassShapeForTest(u8 shape) { - return shape == static_cast( - ReferenceChainTracker::AnchorClassShape::CONTAINER); - } - // At-risk static-anchor FIFO (see _static_anchor_fifo in referenceChains.h). using AtRiskAnchor = ReferenceChainTracker::AtRiskAnchor; static constexpr u32 kAtRiskPerKlassCap = diff --git a/doc/architecture/LiveHeapReferenceChainsImplementation.md b/doc/architecture/LiveHeapReferenceChainsImplementation.md index cd8edc81b4..1b7fe5c6f2 100644 --- a/doc/architecture/LiveHeapReferenceChainsImplementation.md +++ b/doc/architecture/LiveHeapReferenceChainsImplementation.md @@ -216,9 +216,9 @@ in a pass that reaches rotation. Each class walk checks at most 64 worklist entr The shape cache uses process-lifetime class tags and survives search restarts. The index and side map are per-search. -If interface tags are unavailable, shapes remain unknown. A walk with pending hierarchy entries at -the 64-pop limit caches `UNKNOWN_TRUNCATED`, which remains selectable; only a completed no-match -walk caches `NON_CONTAINER`. +If interface tags are unavailable, shapes remain unknown. A walk with missing class metadata, +failed hierarchy lookup, or pending entries at the 64-pop limit caches `UNKNOWN_TRUNCATED`; only a +complete no-match walk caches `NON_CONTAINER`. An indexed root-attached `STATIC_FIELD` or `JNI_GLOBAL` entry can be selected regardless of shape when its state is `FRONTIER` or `EXPANDED` and it is not queued. From 9ff697b3fcbb908d13d9629978f682f6426243ec Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 17:08:49 +0100 Subject: [PATCH 15/20] referencechains: treat null interface entries as incomplete --- ddprof-lib/src/main/cpp/referenceChainAnchors.cpp | 6 ++++-- ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 9e159594c3..f6a4e58e0c 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -485,7 +485,6 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, jclass super = jni->GetSuperclass(cur); if (jniExceptionCheck(jni)) { incomplete = true; - jni->ExceptionClear(); if (super != nullptr) { jni->DeleteLocalRef(super); } @@ -501,7 +500,10 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, incomplete = true; } else if (ifaces != nullptr) { for (jint i = 0; i < iface_count; i++) { - if (ifaces[i] != nullptr) { + if (ifaces[i] == nullptr) { + // A null element hides an unexamined interface, like a lookup error does. + incomplete = true; + } else { work.push_back(ifaces[i]); } } diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index d34778531a..47927b0a0d 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -1296,6 +1296,15 @@ TEST_F(ReferenceChainsBfsTest, ClassShapeWalkKeepsLookupFailuresUnknown) { kCollectionTag, kMapTag); EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( shape)) << "a missing interface array cannot prove a completed non-match"; + + void *null_iface_root = reinterpret_cast(0xC070); + tags[null_iface_root] = -1205; + field_decode_hierarchy[null_iface_root] = {false, nullptr, {nullptr}, {}}; + shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( + &mock_jvmti, &mock_jni, reinterpret_cast(null_iface_root), + kCollectionTag, kMapTag); + EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( + shape)) << "a null interface element hides an unexamined interface"; } TEST_F(ReferenceChainsBfsTest, TransientNonContainerAnchorsArePruned) { From 803e7bf0d66ca875ec27ea681d9fe08731273f6d Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 15:11:36 +0100 Subject: [PATCH 16/20] refchain test: widen external-process leak-cache tail window (stacked on #889) (#1022) --- .../ExternalProcessReferenceChainTest.java | 16 +++--- .../referencechains/LeakingCacheScenario.java | 57 ++++++++++++++++--- 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java index a3cb8916ce..95a3c3cbeb 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java @@ -78,9 +78,10 @@ void shouldReconstructReferrerChainInSeparateProcess() throws Exception { jvmArgs, packedCommand, Collections.emptyMap(), - // Generous: a separate JVM's startup/classloading cost on top of the up-to-25-round - // growth loop, up to 20 one-second tail waits plus their dumps, and one final flush. - childTimeoutSeconds(90), + // Generous: cold-JVM startup + the 25-round growth loop + the scenario's 60s tail + // budget plus per-attempt dumps and one final flush; the sibling static-field test + // uses the same 150s. + childTimeoutSeconds(150), line -> { if (line.startsWith(LeakingCacheScenario.FOUND_MARKER) || line.equals(LeakingCacheScenario.NOT_FOUND_MARKER) @@ -160,11 +161,10 @@ void shouldReconstructReferrerChainForGrowingStaticFieldCollection() throws Exce jvmArgs, packedCommand, Collections.emptyMap(), - // Wider than shouldReconstructReferrerChainInSeparateProcess()'s 90s: this scenario's - // own tail wait (StaticFieldGrowingCollectionScenario.run()) needs up to ~60s on top - // of - // the round loop for a cold JVM's first full pass to actually complete - see that - // method's own comment. + // Same 150s as shouldReconstructReferrerChainInSeparateProcess(): this scenario's + // own tail wait (StaticFieldGrowingCollectionScenario.run()) needs up to ~60s on + // top of the round loop for a cold JVM's first full pass to actually complete - + // see that method's own comment. childTimeoutSeconds(150), line -> { if (line.startsWith(StaticFieldGrowingCollectionScenario.FOUND_MARKER) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index 2019d66eea..e4a2eb1696 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -34,10 +34,6 @@ private LeakingCacheScenario() {} // margin. generations=true needs that gate cleared to authorize the BFS thread's first pass. private static final int SEED_EPOCHS_FOR_HYSTERESIS = 15; - // The tracker can cache a chain after the final growth-round dump. - private static final int TAIL_POLL_ATTEMPTS = 20; - private static final long TAIL_POLL_INTERVAL_MILLIS = 1000; - /** * Durable holder for the cache fixture. The discovered-chain gate suppresses chains shallower * than the first real holder hop that are rooted at a TRANSIENT root (stack/JNI local) - a @@ -67,6 +63,15 @@ private LeakingCacheScenario() {} */ public static final String CHAIN_NOT_PERSISTED_MARKER = "[chain-not-persisted] "; + // The chain event lands only after the search's first BFS pass completes - chain + // building polls are serialized behind the in-flight pass - so the tail must cover + // the whole pass plus one poll. No tighter upper bound is known: from round-loop + // start, admission comes at t≈6-8s and the event at t≈15-17s (measured across three + // aarch64/glibc release runs), hence 60s, inside the parent's 150s child timeout + // (round loop ≈9s measured + 60s tail + startup + post-tail diagnostics). + private static final long TAIL_BUDGET_MILLIS = 60_000; + private static final long TAIL_POLL_INTERVAL_MILLIS = 1000; + /** * Seeds {@code cache} with an initial batch, *then* starts the profiler (order is load-bearing, * see the class comment), then runs the same population-growth loop {@code @@ -92,6 +97,7 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD boolean seededTestKlassTrend = false; ReferenceChainAssertions.ChainMatch match = null; int totalRounds = 25; + long roundLoopStartNanos = System.nanoTime(); for (int round = 1; round <= totalRounds && match == null; round++) { int newEntries = round * 300; int roundNumber = round; @@ -143,16 +149,53 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD profiler.dump(scratchDumpPath); match = findMatch(scratchDumpPath); } + // per-round wall-clock and reference_chain_* counter snapshot: a failing run then shows + // when the frontier stops growing (single-pass duration) and whether a candidate was + // admitted, without touching the native engine. Cost is one scan over the counter table. + StringBuilder diag = new StringBuilder("[debug] round=").append(round); + diag.append(" t=") + .append((System.nanoTime() - roundLoopStartNanos) / 1_000_000_000L) + .append("s"); + diag.append(" cache.size()=").append(cache.size()); + try { + profiler + .getDebugCounters() + .forEach( + (k, v) -> { + if (k.startsWith("reference_chain_")) { + diag.append(' ').append(k).append('=').append(v); + } + }); + } catch (Exception e) { + diag.append(" counters-error=").append(e); + } + System.out.println(diag); if (round == 1 || round == 5 || round == 10 || round == 25) { - System.out.println("[debug] round=" + round + " cache.size()=" + cache.size()); debugDumpAllChainLeaves(scratchDumpPath); } } - for (int attempt = 0; match == null && attempt < TAIL_POLL_ATTEMPTS; attempt++) { - Thread.sleep(TAIL_POLL_INTERVAL_MILLIS); + long tailDeadlineNanos = System.nanoTime() + TAIL_BUDGET_MILLIS * 1_000_000L; + for (int attempt = 0; match == null; attempt++) { + long nowNanos = System.nanoTime(); + if (nowNanos >= tailDeadlineNanos) { + break; + } + // Cap the final sleep so the attempt's dump starts within the budget; the dump + // and JFR parse themselves still run past it on the last attempt. + long sleepMillis = + Math.min(TAIL_POLL_INTERVAL_MILLIS, (tailDeadlineNanos - nowNanos) / 1_000_000L); + Thread.sleep(sleepMillis); profiler.dump(scratchDumpPath); match = findMatch(scratchDumpPath); + System.out.println( + "[debug] tail attempt=" + + attempt + + " t=" + + (System.nanoTime() - roundLoopStartNanos) / 1_000_000_000L + + "s" + + " matchFound=" + + (match != null)); } if (match == null) { From 5dfc814e78d94c7a578cf465b48a872be9f440f8 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 17:38:42 +0100 Subject: [PATCH 17/20] refchain test: trim tail comments to budget --- .../ExternalProcessReferenceChainTest.java | 5 ++--- .../profiler/referencechains/LeakingCacheScenario.java | 9 +++------ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java index 95a3c3cbeb..86eab1ae77 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java @@ -162,9 +162,8 @@ void shouldReconstructReferrerChainForGrowingStaticFieldCollection() throws Exce packedCommand, Collections.emptyMap(), // Same 150s as shouldReconstructReferrerChainInSeparateProcess(): this scenario's - // own tail wait (StaticFieldGrowingCollectionScenario.run()) needs up to ~60s on - // top of the round loop for a cold JVM's first full pass to actually complete - - // see that method's own comment. + // tail wait (StaticFieldGrowingCollectionScenario.run()) needs up to ~60s for a + // cold JVM's first full pass; see that method's own comment. childTimeoutSeconds(150), line -> { if (line.startsWith(StaticFieldGrowingCollectionScenario.FOUND_MARKER) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index e4a2eb1696..77239f8438 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -63,12 +63,9 @@ private LeakingCacheScenario() {} */ public static final String CHAIN_NOT_PERSISTED_MARKER = "[chain-not-persisted] "; - // The chain event lands only after the search's first BFS pass completes - chain - // building polls are serialized behind the in-flight pass - so the tail must cover - // the whole pass plus one poll. No tighter upper bound is known: from round-loop - // start, admission comes at t≈6-8s and the event at t≈15-17s (measured across three - // aarch64/glibc release runs), hence 60s, inside the parent's 150s child timeout - // (round loop ≈9s measured + 60s tail + startup + post-tail diagnostics). + // The chain event lands only after the first BFS pass completes - polls serialize + // behind the in-flight pass - so the tail must cover the whole pass plus one poll: + // admission t≈6-8s, event t≈15-17s on aarch64/glibc release builds; hence 60s. private static final long TAIL_BUDGET_MILLIS = 60_000; private static final long TAIL_POLL_INTERVAL_MILLIS = 1000; From 5c4467b781d62cdc0590cbc15efc00b24b805aa8 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 18:12:51 +0100 Subject: [PATCH 18/20] referencechains: count static fresh-queue overflow drops --- ddprof-lib/src/main/cpp/counters.h | 5 +++++ ddprof-lib/src/main/cpp/referenceChainAnchors.cpp | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/ddprof-lib/src/main/cpp/counters.h b/ddprof-lib/src/main/cpp/counters.h index 8bfb0e343a..97b163fe71 100644 --- a/ddprof-lib/src/main/cpp/counters.h +++ b/ddprof-lib/src/main/cpp/counters.h @@ -325,6 +325,11 @@ * almost all classes" — if this tracks the total class count per lap, \ * the cap is too low; if it stays near zero, the cap is fine. */ \ X(REFERENCE_CHAIN_STATIC_SWEEP_CLASSES_CAPPED, "reference_chain_static_sweep_classes_capped") \ + /* indexAnchorForRotation() fresh-queue overflow: a newly indexed anchor's \ + * prioritized first look was lost to a STATIC_ANCHOR_FRESH_CAP eviction - \ + * the anchor keeps fair-tier coverage via _static_anchor_index, so this \ + * gauges how often anchor bursts outpace the rotation drain. */ \ + X(REFERENCE_CHAIN_STATIC_FRESH_DROPPED, "reference_chain_static_fresh_dropped") \ DD_COUNTER_TABLE_FAULT_INJECTION(X) \ DD_COUNTER_TABLE_FI_DEBUG(X) \ DD_COUNTER_TABLE_SAMPLER_PERF(X) \ diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index f6a4e58e0c..bbd39cb68c 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -145,8 +145,8 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { const size_t fresh_queue_len = _static_anchor_fresh_queue.size(); _frontier->withSharedLock([&](const FrontierTable *frontier) { // Drop dead/ABANDONED entries and compact survivors in admission order before tier selection. - // Released tags are re-minted, so a later observation can index the holder under its fresh tag. - // The cursors below use the compacted positions. + // Released tags are re-minted, so a later observation can re-index the holder under its fresh + // tag. Cursors are not shifted on compaction: survivors left of a cursor may wait one lap. size_t kept = 0; for (size_t i = 0; i < _static_anchor_index.size(); i++) { jlong tag = _static_anchor_index[i]; @@ -389,6 +389,7 @@ void ReferenceChainTracker::indexAnchorForRotation(jlong tag, _static_anchor_fresh_queue.push_back(tag); if (_static_anchor_fresh_queue.size() > STATIC_ANCHOR_FRESH_CAP) { _static_anchor_fresh_queue.pop_front(); + Counters::increment(REFERENCE_CHAIN_STATIC_FRESH_DROPPED); } } From ecb53217ed1066315b2b6f87beca6493e7e5fee5 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 18:12:51 +0100 Subject: [PATCH 19/20] refchain test: rewrap javadoc for spotless --- .../referencechains/ExternalProcessReferenceChainTest.java | 4 ++-- .../profiler/referencechains/LeakingCacheScenario.java | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java index 86eab1ae77..ad7476b066 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java @@ -22,8 +22,8 @@ import org.junit.jupiter.api.Test; /** - * Runs the leak fixture in a child JVM to test reference-chain selection with a fresh tracker. - * Root enumeration repeats only after the adaptive interval, so a fresh process isolates each scenario. + * Runs the leak fixture in a child JVM to test reference-chain selection with a fresh tracker. Root + * enumeration repeats only after the adaptive interval, so a fresh process isolates each scenario. */ @Tag("slow") public class ExternalProcessReferenceChainTest extends AbstractProcessProfilerTest { diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java index 77239f8438..c1da11f152 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakingCacheScenario.java @@ -18,8 +18,9 @@ import org.openjdk.jmc.flightrecorder.JfrLoaderToolkit; /** - * Child-JVM fixture for {@link ExternalProcessReferenceChainTest}; a fresh process isolates tracker state. - * Seed {@code cache} before {@code profiler.execute()} so the first root walk cannot see it empty. + * Child-JVM fixture for {@link ExternalProcessReferenceChainTest}; a fresh process isolates tracker + * state. Seed {@code cache} before {@code profiler.execute()} so the first root walk cannot see it + * empty. */ public final class LeakingCacheScenario { private LeakingCacheScenario() {} From a55a95dd7a9d91490230eaf655ea9aadafe8af15 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 19 Nov 2026 18:33:59 +0100 Subject: [PATCH 20/20] referencechains: count budget-exhausted fresh-lane drops too --- ddprof-lib/src/main/cpp/counters.h | 3 ++- ddprof-lib/src/main/cpp/referenceChainAnchors.cpp | 2 ++ ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/ddprof-lib/src/main/cpp/counters.h b/ddprof-lib/src/main/cpp/counters.h index 97b163fe71..f28353a814 100644 --- a/ddprof-lib/src/main/cpp/counters.h +++ b/ddprof-lib/src/main/cpp/counters.h @@ -326,7 +326,8 @@ * the cap is too low; if it stays near zero, the cap is fine. */ \ X(REFERENCE_CHAIN_STATIC_SWEEP_CLASSES_CAPPED, "reference_chain_static_sweep_classes_capped") \ /* indexAnchorForRotation() fresh-queue overflow: a newly indexed anchor's \ - * prioritized first look was lost to a STATIC_ANCHOR_FRESH_CAP eviction - \ + * prioritized first look was lost, to a STATIC_ANCHOR_FRESH_CAP eviction or \ + * to a rotation drain that exhausted its budget before the queue emptied - \ * the anchor keeps fair-tier coverage via _static_anchor_index, so this \ * gauges how often anchor bursts outpace the rotation drain. */ \ X(REFERENCE_CHAIN_STATIC_FRESH_DROPPED, "reference_chain_static_fresh_dropped") \ diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index bbd39cb68c..37dd9ec963 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -200,6 +200,8 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { if (fresh_room <= 0) { // Budget exhausted before the queue drained: everything remaining spends its first look now // and falls back to the fair tiers at its index position (covered, not urgent). + Counters::increment(REFERENCE_CHAIN_STATIC_FRESH_DROPPED, + (long long)_static_anchor_fresh_queue.size()); _static_anchor_fresh_queue.clear(); break; } diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 47927b0a0d..59c324eb22 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -1412,6 +1412,7 @@ TEST_F(ReferenceChainsBfsTest, FreshAnchorQueueDropsOldestPastCap) { constexpr int kCap = 1024; constexpr jlong kFirstTag = 5000, kClassTag = 940000; ReferenceChainsTestAccessor::primeClassShapeForTest(kClassTag, true); + long long droppedBefore = Counters::getCounter(REFERENCE_CHAIN_STATIC_FRESH_DROPPED); for (int i = 0; i <= kCap; i++) { ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( frontier, kFirstTag + i, 0, 0, FrontierEntryState::FRONTIER, @@ -1425,9 +1426,16 @@ TEST_F(ReferenceChainsBfsTest, FreshAnchorQueueDropsOldestPastCap) { EXPECT_EQ(1024u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()) << "the 1025th admission must evict, not grow the queue"; ASSERT_EQ(1025u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + EXPECT_EQ(droppedBefore + 1, + Counters::getCounter(REFERENCE_CHAIN_STATIC_FRESH_DROPPED)) + << "the cap eviction must count the anchor that lost its fresh-lane first look"; std::vector first = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(1); ASSERT_EQ(1u, first.size()); EXPECT_EQ(kFirstTag + 1, first[0]) << "the evicted oldest anchor must not ride the fresh lane"; + // max_count=1 spends the one fresh look on the queue head; the remaining kCap-1 entries lose + // their prioritized first look to the budget-exhausted drain clear and fall back to the tiers. + EXPECT_EQ(droppedBefore + kCap, + Counters::getCounter(REFERENCE_CHAIN_STATIC_FRESH_DROPPED)); }