diff --git a/ddprof-lib/src/main/cpp/counters.h b/ddprof-lib/src/main/cpp/counters.h index 8bfb0e343a..f28353a814 100644 --- a/ddprof-lib/src/main/cpp/counters.h +++ b/ddprof-lib/src/main/cpp/counters.h @@ -325,6 +325,12 @@ * 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 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") \ 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/javaApi.cpp b/ddprof-lib/src/main/cpp/javaApi.cpp index 5bb651e8ac..779972d42d 100644 --- a/ddprof-lib/src/main/cpp/javaApi.cpp +++ b/ddprof-lib/src/main/cpp/javaApi.cpp @@ -1226,12 +1226,10 @@ 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, + 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) { diff --git a/ddprof-lib/src/main/cpp/livenessTracker.cpp b/ddprof-lib/src/main/cpp/livenessTracker.cpp index 5d6f895832..fe00397c24 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, @@ -994,6 +1009,9 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( _klass_population[slot].ring_head = 0; _klass_population[slot].ring_fill = 0; _klass_population[slot].consecutive_positive = 0; +#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. @@ -1006,6 +1024,16 @@ jweak LivenessTracker::recordKlassPopulationSampleLocked( } KlassPopulationEntry &entry = _klass_population[slot]; +#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; + *out_slot = slot; + *out_created = created; + return evicted_ref; + } +#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 99d21b2cbd..d93d3149fd 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -107,6 +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; +#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 @@ -1430,6 +1435,7 @@ class alignas(alignof(SpinLock)) LivenessTracker { _klass_population_size--; } + // 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, @@ -1446,6 +1452,30 @@ class alignas(alignof(SpinLock)) LivenessTracker { return evicted; } +#ifdef DEBUG + /** + * 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, + int *out_evicted_count = nullptr, int max_evicted = 0) { + 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) { + _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; + } +#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/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index ab226c6c21..37dd9ec963 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; @@ -143,45 +144,64 @@ 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++) { + // Drop dead/ABANDONED entries and compact survivors in admission order before tier selection. + // 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]; 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) || + entry.state == FrontierEntryState::ABANDONED) { + _static_anchor_index_class_tags.erase(tag); + continue; + } + 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.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) || 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]); - if (shape_it != _class_shape_cache.end() && - shape_it->second == (u8)AnchorClassShape::CONTAINER) { - container_picks.push_back(TierPick{i, tag}); - } else { - other_picks.push_back(TierPick{i, tag}); - } + 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 { - other_picks.push_back(TierPick{i, tag}); + other_picks.push_back(TierPick{pos, tag}); } } - // 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. + _static_anchor_index.resize(kept); + idx_size = kept; + // 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()) { 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; } @@ -190,9 +210,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); @@ -201,30 +221,27 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { } pos = (size_t)(it - _static_anchor_index.begin()); } + 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.class_tag; + } 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 - // 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); + 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); @@ -333,16 +350,48 @@ void ReferenceChainTracker::addToStaticAnchorIndex(jlong tag, root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { return; } + indexAnchorForRotation(tag, own_class_tag, false); +} + +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 == static_cast(AnchorClassShape::CONTAINER) || + shape->second == static_cast(AnchorClassShape::UNKNOWN_TRUNCATED)); +} + +void ReferenceChainTracker::indexAnchorForRotation(jlong tag, + jlong own_class_tag, + bool transient_root) { // 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, 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 && 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; } _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) { _static_anchor_fresh_queue.pop_front(); + Counters::increment(REFERENCE_CHAIN_STATIC_FRESH_DROPPED); } } @@ -392,24 +441,24 @@ 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); 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. @@ -437,22 +486,36 @@ bool ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, break; } jclass super = jni->GetSuperclass(cur); - if (!jniExceptionCheck(jni) && super != nullptr) { + if (jniExceptionCheck(jni)) { + incomplete = true; + if (super != nullptr) { + jni->DeleteLocalRef(super); + } + } else if (super != nullptr) { work.push_back(super); - } else { - jni->ExceptionClear(); } 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) { + // A null element hides an unexamined interface, like a lookup error does. + incomplete = true; + } else { + work.push_back(ifaces[i]); + } } } - jvmti->Deallocate((unsigned char *)ifaces); + } 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 // this walk minted (GetSuperclass/ GetImplementedInterfaces locals, deleted immediately after @@ -461,15 +524,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 = incomplete || (!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, @@ -477,7 +545,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 @@ -485,7 +553,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.class_tag; if (class_tag == 0 || seen.count(class_tag) > 0 || _class_shape_cache.count(class_tag) > 0) { continue; @@ -537,9 +606,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 3115479e20..711adf1bb1 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -134,6 +134,25 @@ 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); + } + // 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); + if (shape == ctx->tracker->_class_shape_cache.end() || + 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; } @@ -147,6 +166,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) { + // 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); + } + } +} + void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, bool run_root_enum, int root_enum_budget, @@ -190,11 +222,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; @@ -373,10 +403,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 @@ -387,9 +415,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) { - 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; @@ -1070,6 +1096,9 @@ bool ReferenceChainTracker::runPass(jvmtiEnv *jvmti, JNIEnv *jni, if (manual_first_pass) { _search_started = true; store(_search_start_ns, OS::nanotime()); + // 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); } // 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..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: 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; 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) && @@ -464,8 +463,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)); } @@ -491,13 +490,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.cpp b/ddprof-lib/src/main/cpp/referenceChains.cpp index db9653623a..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, @@ -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 c6a4dd3cd2..f0ae180179 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,10 +489,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. + // 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; @@ -511,22 +510,28 @@ 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 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; - // 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). - 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; + // 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()). @@ -1046,13 +1051,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 @@ -1076,29 +1076,34 @@ 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); - - // 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); + // Shared deduplicated index insertion for durable roots and local holders. + 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); + + // 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). 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. + // 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 @@ -1418,13 +1423,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. @@ -1546,17 +1547,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 a7497a86ed..bf2eab363c 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1094,6 +1094,53 @@ 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( + 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(); + } + + 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) { @@ -1288,6 +1335,327 @@ class LivenessTrackerTestAccessor { } }; +#ifdef DEBUG +TEST_F(SelectLeakCandidatesTest, SeededClassHistorySurvivesRealGcFolds) { + 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)); + for (int epoch = 21; epoch <= 30; epoch++) { + 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)); +} +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) { + 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; + 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); + } +} + +// 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; + 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 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; + 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)); +} + +// 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) { LivenessTracker *tracker = LivenessTracker::instance(); LivenessTrackerTestAccessor::setSessionGatesForTest( diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index d39be8edff..59c324eb22 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -467,6 +467,246 @@ 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)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + 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); +} + +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)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + 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); +} + +// 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(); + int holderC = addNode(); + node_tags[holderA] = 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 = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + // 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(3u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + // 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]); + 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()); +} + +// 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 // intercepts a leak chunk 3 hops below it - the repair for the population the root-attached // collector demonstrably cannot select (the negative control below). @@ -809,3 +1049,393 @@ 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()); +} + +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, 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"; + + 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) { + 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; + 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); + 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, + 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()); + 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)); +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index 576bd4bc9d..964795ae59 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -5,8 +5,11 @@ #include "referenceChainsTestAccessors.h" #include "referenceChainsMockHeap.h" +#include "referenceChainInternal.h" #include "tsc.h" +#include + @@ -20,6 +23,21 @@ protected: void TearDown() override { tearDown(); } }; +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; ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); @@ -539,6 +557,110 @@ 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)); + ReferenceChainsTestAccessor::TrackerStopGuard stop_guard; + LivenessTrackerTestResetGuard liveness_reset_guard; + 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]); + + // 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) { + 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 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]); +} + // 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/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 3e7e7f94f4..7b77f8759b 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" @@ -37,6 +38,17 @@ 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. Owns the teardown instead; stop() is a no-op once already stopped. + class TrackerStopGuard { + public: + TrackerStopGuard() = default; + ~TrackerStopGuard() { ReferenceChainTracker::instance()->stop(); } + TrackerStopGuard(const TrackerStopGuard &) = delete; + TrackerStopGuard &operator=(const TrackerStopGuard &) = delete; + }; + static void reset() { ReferenceChainTracker *t = ReferenceChainTracker::instance(); delete t->_frontier; @@ -94,8 +106,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 +539,24 @@ 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 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) { + ReferenceChainTracker::mergeAtRiskAnchors(selection, drained); } static jlong discoveredTagForTest(int slot, int idx) { @@ -888,8 +915,30 @@ 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); } // At-risk static-anchor FIFO (see _static_anchor_fifo in referenceChains.h). @@ -991,6 +1040,22 @@ 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); + } + + // 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/ExternalProcessReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ExternalProcessReferenceChainTest.java index 25ab1f15cf..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,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 { @@ -89,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 plus grace period (~20s in-process). - 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) @@ -120,13 +110,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 { @@ -176,11 +161,9 @@ 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 + // 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) @@ -210,7 +193,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 63e1c99ba1..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,22 +18,9 @@ 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() {} @@ -77,6 +64,12 @@ private LeakingCacheScenario() {} */ public static final String CHAIN_NOT_PERSISTED_MARKER = "[chain-not-persisted] "; + // 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; + /** * 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 @@ -102,6 +95,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; @@ -153,24 +147,67 @@ 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 < 5; attempt++) { - Thread.sleep(1000); + 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) { + // 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 +257,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 +266,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,16 +356,35 @@ 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). + * 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; 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; 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..1b7fe5c6f2 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,61 @@ 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. 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 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. + +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. 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. + +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.