diff --git a/ddprof-lib/src/main/cpp/counters.h b/ddprof-lib/src/main/cpp/counters.h index f28353a814..0a1c5f2034 100644 --- a/ddprof-lib/src/main/cpp/counters.h +++ b/ddprof-lib/src/main/cpp/counters.h @@ -266,11 +266,9 @@ * signal for spotting a recurrence. */ \ X(METADATA_TREE_NULL_CHILD, "metadata_tree_null_child") \ X(METADATA_TREE_DEPTH_EXCEEDED, "metadata_tree_depth_exceeded") \ - /* A resolved datadog.ReferenceChain could not be cached in \ - * ReferenceChainTracker::_resolved_chains (referenceChains.h): a brand-new \ - * leak-candidate klass arrived with the cache already at \ - * MAX_RESOLVED_CHAINS, so its chain is dropped rather than evicting some \ - * other still-live sample's chain. See that constant's own comment. */ \ + /* A reference-chain event could not be retained for a future dump: a \ + * bounded cache or queue was full, or invalidation overflow cleared the \ + * resolved-chain cache to avoid emitting stale output. */ \ X(REFERENCE_CHAIN_EVENTS_DROPPED, "reference_chain_events_dropped") \ /* ReferenceChainTracker::releaseSearchTags() (referenceChains.cpp) failed \ * to call GetObjectsWithTags() for at least one batch - the search's tag \ diff --git a/ddprof-lib/src/main/cpp/livenessTracker.cpp b/ddprof-lib/src/main/cpp/livenessTracker.cpp index fe00397c24..dd0e35b56a 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.cpp +++ b/ddprof-lib/src/main/cpp/livenessTracker.cpp @@ -843,66 +843,6 @@ int LivenessTracker::tagLeakInstances(jvmtiEnv *jvmti, return tagged; } -void LivenessTracker::insertThreadGen(KlassCountScratch &scratch, - jint tid, u32 age) { - // Find or create the thread entry for this tid - for (int i = 0; i < scratch.thread_count; i++) { - if (scratch.threads[i].tid == tid) { - // Insert age into the thread's sorted distinct-age array - auto &t = scratch.threads[i]; - // Every surviving object counts toward the per-tid retained-count - // bar (TID_RETAINED_COUNT_BAR) BEFORE the age-dedup early return - // below: the count is per-instance, the ages are per-cohort. - t.count++; - for (u32 j = 0; j < t.age_count; j++) { - if (t.ages[j] == age) { - return; // age already counted for this thread - } - } - if (t.age_count < KlassCountScratch::MAX_AGES_PER_THREAD) { - // Insert sorted (small array, linear scan + shift) - u32 pos = t.age_count; - for (u32 j = 0; j < t.age_count; j++) { - if (age < t.ages[j]) { - pos = j; - break; - } - } - for (u32 j = t.age_count; j > pos; j--) { - t.ages[j] = t.ages[j - 1]; - } - t.ages[pos] = age; - t.age_count++; - } - return; - } - } - int idx; - if (scratch.thread_count < KlassCountScratch::MAX_THREADS_PER_KLASS) { - 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, jweak sample_source, jint tid) { @@ -948,6 +888,7 @@ void LivenessTracker::accumulateKlassCount(u32 klass_id, jlong age, slot.ages.push_back((u32)age); slot.oldest_count = 0; slot.thread_count = 0; + slot.challenger_count = 0; insertOldestSample(slot, sample_source, (u32)age, tid); insertThreadGen(slot, tid, (u32)age); } @@ -1380,123 +1321,6 @@ bool LivenessTracker::tidPushQualifies( return hasQualifyingTidGrowth(trend); } -void LivenessTracker::recordTidTrendSamplesLocked( - int slot, const KlassCountScratch &scratch) { - if (slot < 0 || slot >= _klass_population_size) { - return; - } - KlassPopulationEntry &entry = _klass_population[slot]; - // Present tids first: find-or-create their trend and push this epoch's - // distinct-age count. (KlassCountScratch threads always carry >=1 - // surviving instance, so every scratch thread has a real claim on a - // slot; a zero-count tid never reaches this fold.) - for (int ti = 0; ti < scratch.thread_count; ti++) { - jint tid = scratch.threads[ti].tid; - KlassPopulationEntry::TidTrend *trend = nullptr; - for (int i = 0; i < entry.tid_trend_count; i++) { - if (entry.tid_trends[i].tid == tid) { - trend = &entry.tid_trends[i]; - break; - } - } - if (trend != nullptr && trend->synthetic) { - // Seam-owned history: the test maintains this ramp itself - // (seedTidTrendSample0), and a real fold interleaving its own low - // count for the same tid would reset the trend's hysteresis every - // System.gc() the scenario runs between rounds. Production data has - // no synthetic trends, so this exemption is inert there. - continue; - } - if (trend == nullptr) { - if (entry.tid_trend_count < KlassPopulationEntry::MAX_TID_TRENDS) { - trend = &entry.tid_trends[entry.tid_trend_count++]; - } else { - // Full: evict the WEAKEST non-synthetic trend (lowest - // consecutive_positive, then lowest ring_fill) - a genuinely rising - // leak tid accumulates hysteresis fast and resists eviction, while - // machinery tids never build any. Synthetic (test-seeded) trends - // are never evicted by real data. If every slot is synthetic, the - // new tid is simply dropped - production data never marks - // anything synthetic, so this only caps a scenario's own seeding. - int victim = -1; - for (int i = 0; i < entry.tid_trend_count; i++) { - if (entry.tid_trends[i].synthetic) { - continue; - } - if (victim < 0 || - (entry.tid_trends[i].consecutive_positive < - entry.tid_trends[victim].consecutive_positive) || - (entry.tid_trends[i].consecutive_positive == - entry.tid_trends[victim].consecutive_positive && - entry.tid_trends[i].ring_fill < - entry.tid_trends[victim].ring_fill)) { - victim = i; - } - } - if (victim < 0) { - continue; // all slots synthetic - drop this tid's sample - } - trend = &entry.tid_trends[victim]; - } - trend->tid = tid; - trend->ring_head = 0; - trend->ring_fill = 0; - trend->consecutive_positive = 0; - trend->synthetic = false; - } - trend->ring[trend->ring_head] = (u8)scratch.threads[ti].age_count; - trend->count_ring[trend->ring_head] = - (u8)std::min(scratch.threads[ti].count, UINT8_MAX); - trend->ring_head = (u8)((trend->ring_head + 1) % - KlassPopulationEntry::TID_TREND_RING_SIZE); - if (trend->ring_fill < KlassPopulationEntry::TID_TREND_RING_SIZE) { - trend->ring_fill++; - } - if (tidPushQualifies(*trend, scratch.threads[ti].count)) { - if (trend->consecutive_positive < UINT8_MAX) { - trend->consecutive_positive++; - } - } else { - trend->consecutive_positive = 0; - } - } - // Tracked tids ABSENT this epoch: a thread whose instances all died - // must not keep a stale rising ring - push 0 so the next - // hasQualifyingTidGrowth() fails and the trend's hysteresis resets (the - // per-tid analogue of the population simply stopping). Synthetic - // (test-seeded) trends are exempt: scenarios interleave real - // System.gc()-driven folds with their seeded ramps, and without the - // exemption every real fold would wipe the seeded qualification before - // the test could ever use it (see TidTrend::synthetic's own comment). - for (int i = 0; i < entry.tid_trend_count; i++) { - KlassPopulationEntry::TidTrend &trend = entry.tid_trends[i]; - if (trend.synthetic) { - continue; - } - bool present = false; - for (int ti = 0; ti < scratch.thread_count; ti++) { - if (scratch.threads[ti].tid == trend.tid) { - present = true; - break; - } - } - if (present) { - continue; - } - trend.ring[trend.ring_head] = 0; - trend.count_ring[trend.ring_head] = 0; - trend.ring_head = (u8)((trend.ring_head + 1) % - KlassPopulationEntry::TID_TREND_RING_SIZE); - if (trend.ring_fill < KlassPopulationEntry::TID_TREND_RING_SIZE) { - trend.ring_fill++; - } - // A 0-count epoch cannot qualify as a rise - reset now rather than - // deferring to the next push, so a long-absent tid does not keep - // hysteresis from before its population died. - trend.consecutive_positive = 0; - } -} - u64 LivenessTracker::newestHeapFloorSample(u64 *seq_out) const { // Per-slot seqlock read: the slot's seq validates the payload below it // (writer: recordHeapFloorSampleUnchecked()). Bounded retry, never a torn diff --git a/ddprof-lib/src/main/cpp/livenessTracker.h b/ddprof-lib/src/main/cpp/livenessTracker.h index d93d3149fd..e2c99c6a46 100644 --- a/ddprof-lib/src/main/cpp/livenessTracker.h +++ b/ddprof-lib/src/main/cpp/livenessTracker.h @@ -214,6 +214,7 @@ typedef struct KlassCandidate { class alignas(alignof(SpinLock)) LivenessTracker { friend Recording; friend class LivenessTrackerTestAccessor; + friend class LivenessThreadTrendTestAccessor; private: // pre-c++17 we should mark these inline(or out of class) @@ -572,6 +573,7 @@ class alignas(alignof(SpinLock)) LivenessTracker { // generations. Thread ID is stable and naturally separates leak // threads from noise threads. static constexpr int MAX_THREADS_PER_KLASS = 16; + static constexpr int MAX_THREAD_CHALLENGERS_PER_KLASS = 4; static constexpr int MAX_AGES_PER_THREAD = 32; struct ThreadGens { jint tid; @@ -584,7 +586,15 @@ class alignas(alignof(SpinLock)) LivenessTracker { }; ThreadGens threads[MAX_THREADS_PER_KLASS]; int thread_count; + // New tids accrue evidence separately when every incumbent meets the retained-count bar. + // At fold, only a challenger that outranks the weakest incumbent replaces a primary slot. + ThreadGens challengers[MAX_THREAD_CHALLENGERS_PER_KLASS]; + int challenger_count; } KlassCountScratch; + static_assert(sizeof(KlassCountScratch::ThreadGens) * + KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS * + MAX_KLASS_POPULATION_ENTRIES == 143360, + "four-thread challenger scratch must stay within its approved budget"); KlassCountScratch _klass_count_scratch[MAX_KLASS_POPULATION_ENTRIES]; int _klass_count_scratch_size; @@ -761,6 +771,15 @@ class alignas(alignof(SpinLock)) LivenessTracker { void insertOldestSample(KlassCountScratch &scratch, jweak sample_source, u32 age, jint tid); void insertThreadGen(KlassCountScratch &scratch, jint tid, u32 age); + // `displaced` (optional, capacity MAX_THREAD_CHALLENGERS_PER_KLASS) receives the incumbents + // promotion replaced, with their pre-replacement epoch sample. `unpromoted` (same capacity) + // receives the challengers promotion could not place: the fold keeps their live sample for a + // tracked trend, like the displaced incumbents', instead of writing them a zero epoch. + void promoteThreadGenCandidates( + KlassCountScratch &scratch, KlassCountScratch::ThreadGens *displaced = nullptr, + int *displaced_count = nullptr, + KlassCountScratch::ThreadGens *unpromoted = nullptr, + int *unpromoted_count = nullptr); // Pushes `count` into klass_id's ring buffer, creating the entry (evicting // the least-recently-updated entry first if the table is already at @@ -867,7 +886,7 @@ class alignas(alignof(SpinLock)) LivenessTracker { // tracked tid from the scratch and push it a spurious 0 - the same // fixed-capacity best-effort the scratch itself already accepts. // _table_lock held exclusively by the caller (foldKlassCountsLocked()). - void recordTidTrendSamplesLocked(int slot, const KlassCountScratch &scratch); + void recordTidTrendSamplesLocked(int slot, KlassCountScratch &scratch); // The sustained-trend gate (this class's own header comment above, // "Sustained-trend gate") - both-required growth-magnitude and floor-rise diff --git a/ddprof-lib/src/main/cpp/livenessTrackerThreadTrends.cpp b/ddprof-lib/src/main/cpp/livenessTrackerThreadTrends.cpp new file mode 100644 index 0000000000..cbda70ddf3 --- /dev/null +++ b/ddprof-lib/src/main/cpp/livenessTrackerThreadTrends.cpp @@ -0,0 +1,302 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "livenessTracker.h" + +#include +#include + +void LivenessTracker::insertThreadGen(KlassCountScratch &scratch, jint tid, + u32 age) { + auto add_sample = [age](KlassCountScratch::ThreadGens &thread) { + thread.count++; + for (u32 i = 0; i < thread.age_count; i++) { + if (thread.ages[i] == age) { + return; + } + } + if (thread.age_count >= KlassCountScratch::MAX_AGES_PER_THREAD) { + return; + } + u32 pos = thread.age_count; + for (u32 i = 0; i < thread.age_count; i++) { + if (age < thread.ages[i]) { + pos = i; + break; + } + } + for (u32 i = thread.age_count; i > pos; i--) { + thread.ages[i] = thread.ages[i - 1]; + } + thread.ages[pos] = age; + thread.age_count++; + }; + auto initialize = [tid, age](KlassCountScratch::ThreadGens &thread) { + thread.tid = tid; + thread.ages[0] = age; + thread.age_count = 1; + thread.count = 1; + }; + + for (int i = 0; i < scratch.thread_count; i++) { + if (scratch.threads[i].tid == tid) { + add_sample(scratch.threads[i]); + return; + } + } + for (int i = 0; i < scratch.challenger_count; i++) { + if (scratch.challengers[i].tid == tid) { + add_sample(scratch.challengers[i]); + return; + } + } + if (scratch.thread_count < KlassCountScratch::MAX_THREADS_PER_KLASS) { + initialize(scratch.threads[scratch.thread_count++]); + return; + } + + // With the incumbent table full, a newcomer ALWAYS accumulates in the challenger pool - even + // when a sub-bar (count < TID_RETAINED_COUNT_BAR) incumbent sits in the table. Immediate + // sub-bar eviction let two alternating single-sample threads overwrite the same slot every + // epoch (each reset to count 1), so a genuinely-present thread could never reach the bar and + // qualify. Challenger promotion (promoteThreadGenCandidates()) is the only path back into the + // incumbent table, and it requires the challenger to OUTRANK the weakest incumbent - sub-bar + // incumbents therefore survive newcomer churn while real threads keep accumulating samples. + // A newcomer that lands on a full challenger pool recycles only a count-1 (single-sample) + // challenger: bounded pool churn that can never displace an incumbent. + if (scratch.challenger_count < + KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS) { + initialize(scratch.challengers[scratch.challenger_count++]); + return; + } + int weakest = 0; + for (int i = 1; i < scratch.challenger_count; i++) { + const auto &candidate = scratch.challengers[i]; + const auto ¤t = scratch.challengers[weakest]; + if (candidate.count < current.count || + (candidate.count == current.count && + candidate.age_count < current.age_count)) { + weakest = i; + } + } + if (scratch.challengers[weakest].count == 1) { + initialize(scratch.challengers[weakest]); + } +} + +void LivenessTracker::promoteThreadGenCandidates( + KlassCountScratch &scratch, KlassCountScratch::ThreadGens *displaced, + int *displaced_count, KlassCountScratch::ThreadGens *unpromoted, + int *unpromoted_count) { + for (int i = 0; i < scratch.challenger_count; i++) { + const auto &candidate = scratch.challengers[i]; + if (scratch.thread_count < KlassCountScratch::MAX_THREADS_PER_KLASS) { + scratch.threads[scratch.thread_count++] = candidate; + continue; + } + int victim = 0; + for (int j = 1; j < scratch.thread_count; j++) { + const auto ¤t = scratch.threads[victim]; + const auto &next = scratch.threads[j]; + if (next.count < current.count || + (next.count == current.count && next.age_count < current.age_count)) { + victim = j; + } + } + const auto &weakest = scratch.threads[victim]; + // A complete challenger must outrank the weakest incumbent to replace it. + if (candidate.count > weakest.count || + (candidate.count == weakest.count && + candidate.age_count > weakest.age_count)) { + if (displaced != nullptr && displaced_count != nullptr && + *displaced_count < KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS) { + displaced[(*displaced_count)++] = weakest; + } + scratch.threads[victim] = candidate; + } else if (unpromoted != nullptr && unpromoted_count != nullptr && + *unpromoted_count < + KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS) { + unpromoted[(*unpromoted_count)++] = candidate; + } + } + scratch.challenger_count = 0; +} + +void LivenessTracker::recordTidTrendSamplesLocked( + int slot, KlassCountScratch &scratch) { + if (slot < 0 || slot >= _klass_population_size) { + return; + } + KlassCountScratch::ThreadGens displaced + [KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS]; + int displaced_count = 0; + KlassCountScratch::ThreadGens unpromoted + [KlassCountScratch::MAX_THREAD_CHALLENGERS_PER_KLASS]; + int unpromoted_count = 0; + promoteThreadGenCandidates(scratch, displaced, &displaced_count, unpromoted, + &unpromoted_count); + KlassPopulationEntry &entry = _klass_population[slot]; + auto push_trend_sample = + [&](KlassPopulationEntry::TidTrend *trend, + const KlassCountScratch::ThreadGens &gen) { + trend->ring[trend->ring_head] = (u8)gen.age_count; + trend->count_ring[trend->ring_head] = + (u8)std::min(gen.count, UINT8_MAX); + trend->ring_head = + (u8)((trend->ring_head + 1) % + KlassPopulationEntry::TID_TREND_RING_SIZE); + if (trend->ring_fill < KlassPopulationEntry::TID_TREND_RING_SIZE) { + trend->ring_fill++; + } + if (tidPushQualifies(*trend, gen.count)) { + if (trend->consecutive_positive < UINT8_MAX) { + trend->consecutive_positive++; + } + } else { + trend->consecutive_positive = 0; + } + }; + // Present tids first: find-or-create their trend and push this epoch's + // distinct-age count. Every scratch thread has a surviving instance. + for (int ti = 0; ti < scratch.thread_count; ti++) { + jint tid = scratch.threads[ti].tid; + KlassPopulationEntry::TidTrend *trend = nullptr; + for (int i = 0; i < entry.tid_trend_count; i++) { + if (entry.tid_trends[i].tid == tid) { + trend = &entry.tid_trends[i]; + break; + } + } + if (trend != nullptr && trend->synthetic) { + continue; + } + if (trend == nullptr) { + if (entry.tid_trend_count < KlassPopulationEntry::MAX_TID_TRENDS) { + trend = &entry.tid_trends[entry.tid_trend_count++]; + } else { + // A takeover must be earned against the victim's accumulated evidence, not just its + // (possibly just-reset) hysteresis counter: a trend whose consecutive_positive was just + // reset still carries its pre-reset retained counts, and a single-sample newcomer must + // not take that slot unconditionally. A candidate victim is therefore unsustained + // (consecutive_positive == 0) AND dead-enough: either its ring ends in two or more zero + // epochs (the thread is really gone - its history no longer matters) or its newest live + // retained count is below the newcomer's current epoch count. Among the qualifying + // candidates the weakest (lowest consecutive_positive, then ring_fill) loses its slot. + // No qualifying victim: the newcomer is dropped - bounded, it retries on a later epoch + // (no new state; the scan is O(candidates x ring) with both constants bounded: 8 x 16). + const u8 incoming_count = + (u8)std::min(scratch.threads[ti].count, UINT8_MAX); + int victim = -1; + for (int i = 0; i < entry.tid_trend_count; i++) { + KlassPopulationEntry::TidTrend &candidate = entry.tid_trends[i]; + if (candidate.synthetic) { + continue; + } + if (candidate.consecutive_positive != 0) { + continue; // still sustaining its qualification - never a victim + } + u8 trailing_zeros = 0; + u8 last_live_count = 0; + for (int k = 0; k < candidate.ring_fill; k++) { + u8 sample = candidate.count_ring[(candidate.ring_head + + KlassPopulationEntry::TID_TREND_RING_SIZE - 1 - k) % + KlassPopulationEntry::TID_TREND_RING_SIZE]; + if (sample == 0) { + trailing_zeros++; + continue; + } + last_live_count = sample; + break; + } + if (trailing_zeros < 2 && last_live_count >= incoming_count) { + continue; // just reset (one skipped epoch) or present-but-unsustained, and still + // hotter than the newcomer: the accumulated evidence keeps the slot + } + if (victim < 0 || + (candidate.consecutive_positive < + entry.tid_trends[victim].consecutive_positive) || + (candidate.consecutive_positive == + entry.tid_trends[victim].consecutive_positive && + candidate.ring_fill < entry.tid_trends[victim].ring_fill)) { + victim = i; + } + } + if (victim < 0) { + continue; + } + trend = &entry.tid_trends[victim]; + } + trend->tid = tid; + trend->ring_head = 0; + trend->ring_fill = 0; + trend->consecutive_positive = 0; + trend->synthetic = false; + } + push_trend_sample(trend, scratch.threads[ti]); + } + // A promotion that replaced an incumbent discarded the victim's current-epoch sample: the + // absent-tid pass below would write the still-live thread a zero epoch and reset its + // qualification. A displaced incumbent with a tracked (non-synthetic) trend records its live + // sample instead; one without a trend slot has no qualification to lose. An unpromoted + // challenger with a tracked trend gets the same treatment: it met the fold with a live + // sample, and promotion's failure must not read as absence and reset its streak. + for (int d = 0; d < displaced_count; d++) { + KlassPopulationEntry::TidTrend *trend = nullptr; + for (int i = 0; i < entry.tid_trend_count; i++) { + if (entry.tid_trends[i].tid == displaced[d].tid) { + trend = &entry.tid_trends[i]; + break; + } + } + if (trend == nullptr || trend->synthetic) { + continue; + } + push_trend_sample(trend, displaced[d]); + } + for (int u = 0; u < unpromoted_count; u++) { + KlassPopulationEntry::TidTrend *trend = nullptr; + for (int i = 0; i < entry.tid_trend_count; i++) { + if (entry.tid_trends[i].tid == unpromoted[u].tid) { + trend = &entry.tid_trends[i]; + break; + } + } + if (trend == nullptr || trend->synthetic) { + continue; + } + push_trend_sample(trend, unpromoted[u]); + } + // Absent tids receive a zero epoch so stale trends cannot remain qualified. + for (int i = 0; i < entry.tid_trend_count; i++) { + KlassPopulationEntry::TidTrend &trend = entry.tid_trends[i]; + if (trend.synthetic) { + continue; + } + bool present = false; + for (int ti = 0; ti < scratch.thread_count; ti++) { + if (scratch.threads[ti].tid == trend.tid) { + present = true; + break; + } + } + for (int d = 0; !present && d < displaced_count; d++) { + present = displaced[d].tid == trend.tid; + } + for (int u = 0; !present && u < unpromoted_count; u++) { + present = unpromoted[u].tid == trend.tid; + } + if (present) { + continue; + } + trend.ring[trend.ring_head] = 0; + trend.count_ring[trend.ring_head] = 0; + trend.ring_head = (u8)((trend.ring_head + 1) % + KlassPopulationEntry::TID_TREND_RING_SIZE); + if (trend.ring_fill < KlassPopulationEntry::TID_TREND_RING_SIZE) { + trend.ring_fill++; + } + trend.consecutive_positive = 0; + } +} diff --git a/ddprof-lib/src/main/cpp/profiler.cpp b/ddprof-lib/src/main/cpp/profiler.cpp index 55b2b924eb..c0184dbd2a 100644 --- a/ddprof-lib/src/main/cpp/profiler.cpp +++ b/ddprof-lib/src/main/cpp/profiler.cpp @@ -2282,6 +2282,32 @@ Error Profiler::stop() { return Error("signal handlers did not drain; teardown skipped, retry stop()"); } + // Close the reference-chain heap paths BEFORE joining the BFS thread: the flag gates the + // thread-object registry and dump() emission, so flipping it first means nothing past the + // flip stages anchor observations or thread-object registrations for a consumer that is about + // to stop existing. A callback that already read the flag is handled downstream + // (releaseAllThreadObjects() closes the registry; SignalInflight::drain() covers signal-path + // writers). The BFS thread is the only FollowReferences caller, so the join below drains any + // walk that read the flag before the flip. + bool reference_chains_was_active = _reference_chains_active.load( + std::memory_order_acquire); + if (reference_chains_was_active) { + _reference_chains_active.store(false, std::memory_order_release); + } + if (reference_chains_was_active && + !ReferenceChainTracker::instance()->stopThread()) { + // Reopen the gate: teardown was skipped, so the recording stays intact and a retried + // stop() re-enters this path (the join itself is idempotent for that retry). + _reference_chains_active.store(true, std::memory_order_release); + // Threads started while the gate was closed were never registered (onThreadStart gates on + // the flag): re-run the start()-time snapshot over the reopened gate. A thread seen by both + // the snapshot and a later onThreadStart is re-registered under the same tid, which + // registerThreadObject() handles - the same reconciliation start() relies on. + ReferenceChainTracker::instance()->registerExistingThreads(VM::jvmti(), + VM::jni()); + return Error("reference chain BFS thread did not join; teardown skipped, retry stop()"); + } + // Close the registration gate and wait for the calls already past it, so no // thread arms a timer or opens an fd after the engines below stop. // Unregistration stays open (see _thread_tables_stable). The engine stops @@ -2297,16 +2323,12 @@ Error Profiler::stop() { if (_event_mask & EM_ALLOC) _alloc_engine->stop(); - if (_reference_chains_active) { - // Cleared first so new onThreadStart()/onThreadEnd() calls skip the - // thread-object registry; a call that already read the flag is handled - // by releaseAllThreadObjects() closing the registry. - _reference_chains_active = false; - // Join the BFS thread and clear the recording-boundary state before the - // rest of the teardown (stopThread() wakes and joins; stop() resets the - // per-recording caches). Matches the Profiler::stop() order documented - // in referenceChains.cpp's stopThread()/stop() comments. - ReferenceChainTracker::instance()->stopThread(); + if (reference_chains_was_active) { + // The flag was flipped before the BFS join (above): new onThreadStart()/onThreadEnd() calls + // skip the thread-object registry; a call that already read the flag is handled by + // releaseAllThreadObjects() closing the registry. + // The BFS thread was joined at the top of stop(); stop() below resets the + // per-recording caches. // Write the tracker's still-undrained events into the final chunk before stop() clears // the queues - otherwise abandonment events queued since the last dump() are dropped for // good, and the final chunk's live-object/leak-tag events (written by diff --git a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp index 37dd9ec963..2005148439 100644 --- a/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainAnchors.cpp @@ -76,13 +76,54 @@ jlong resolveThreadLocalMapClassTag(jvmtiEnv *jvmti, JNIEnv *jni) { } // namespace -void ReferenceChainTracker::descendFromAnchor( - jvmtiEnv *jvmti, JNIEnv *jni, jobject anchor, jlong anchor_tag, - u32 anchor_depth, jlong anchor_descend_class_tag, int budget, - int *edges_admitted, bool *truncated, bool *frontier_cap_hit, - u64 *safepoint_ns) { +void ReferenceChainTracker::replayAnchorObservations( + const AnchorObservation *records, u32 count, bool static_retry) { + // Strict arrival order, no dedup or coalescing: the helpers apply their own caps, promotion and + // eviction, so the index mutations happen here, after the JVMTI call has returned. + for (u32 i = 0; i < count; i++) { + const AnchorObservation &r = records[i]; + if (r.actions & AnchorObservation::LOCAL) { + noteLocalRootHolder(r.tag, r.own_class_tag); + } + if (r.actions & AnchorObservation::DURABLE_ADD) { + addToStaticAnchorIndex(r.tag, r.own_class_tag, r.durable_root_kind); + } + if (r.actions & AnchorObservation::REENLIST_ELIGIBLE) { + // Eligibility was decided at callback time against the frontier snapshot: root-attached + // durable kind, or a CONTAINER-shaped holder (isSelectableAnchor) - the admission contract + // for a rediscovered evicted anchor, which can carry parent_tag != 0 and a stale transient + // root_kind after reparenting. No recheck here. For a tag still indexed the call is the + // dedup no-op - except that a repeated sighting carrying a resolved class tag upgrades a + // stored 0 own-class tag (the sweep's class object is the only carrier of the resolved tag + // once reparenting has taken the root-attached eligibility away). + // A durable sighting also promotes a locally indexed holder to the durable share: + // release its local slot the way addToStaticAnchorIndex() does (no-op for durable-share + // and evicted tags; LOCAL records never share a record with a durable action). The + // promotion grows the durable share without a new index push (the dedup in + // indexAnchorForRotation() returns early for the still-indexed tag), so the durable cap + // is checked here too, exactly as addToStaticAnchorIndex() does; the just promoted tag + // may itself be among the evicted oldest entries, and its next re-enlist re-indexes it. + _local_anchor_tags.erase(r.tag); + evictOldestDurableAnchors(); + indexAnchorForRotation(r.tag, r.own_class_tag); + } + if (r.actions & AnchorObservation::AT_RISK) { + pushAtRiskStaticAnchor(r.tag, r.at_risk_klass_id); + } + } + if (static_retry) { + _durable_anchor_resweep_gen++; // one retry request for the rejected static-field report(s) + } +} + +jvmtiError ReferenceChainTracker::descendFromAnchor( + jvmtiEnv *jvmti, JNIEnv *jni, ReferenceChainAnchorObservationScope &scope, + jobject anchor, jlong anchor_tag, u32 anchor_depth, + jlong anchor_descend_class_tag, int budget, int *edges_admitted, + bool *truncated, bool *frontier_cap_hit, u64 *safepoint_ns, + bool *anchor_observation_overflow) { jlong resolved_chain_tags[MAX_RESOLVED_CHAINS]; - ReferenceChainPassContext ctx; + ReferenceChainPassContext ctx(scope); ctx.tracker = this; ctx.frontier = _frontier; ctx.resolved_chain_tags = resolved_chain_tags; @@ -107,22 +148,30 @@ void ReferenceChainTracker::descendFromAnchor( memset(&callbacks, 0, sizeof(callbacks)); callbacks.heap_reference_callback = heapReferenceCallback; u64 follow_start_ns = OS::nanotime(); - jvmti->FollowReferences(0, nullptr, anchor, &callbacks, &ctx); + jvmtiError follow_err = + jvmti->FollowReferences(0, nullptr, anchor, &callbacks, &ctx); *safepoint_ns += OS::nanotime() - follow_start_ns; *edges_admitted += ctx.edges_admitted; *truncated = *truncated || ctx.truncated; *frontier_cap_hit = *frontier_cap_hit || ctx.frontier_cap_hit; + // observeReturn() takes the buffer lock, ordering the callbacks' writes before this read. + *anchor_observation_overflow = + scope.observeReturn() || ctx.anchor_observation_overflow; + return follow_err; } std::vector -ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { +ReferenceChainTracker::collectStaticFieldAnchorsForRotation( + int max_count, std::vector *fresh_picked) { + if (fresh_picked != nullptr) { + fresh_picked->clear(); + } std::vector selected; - if (max_count <= 0 || _static_anchor_index.empty()) { + const size_t fresh_queue_len = _static_anchor_fresh_queue.size(); + if (max_count <= 0 || + (_static_anchor_index.empty() && fresh_queue_len == 0)) { return selected; } - // 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; @@ -134,44 +183,45 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { size_t pos; jlong tag; }; + const size_t max_picks = std::min( + std::max(idx_size, fresh_queue_len), static_cast(max_count)); + const size_t fair_pick_limit = std::min(idx_size, max_picks * 2); std::vector leak_picks; std::vector fresh_picks; std::vector container_picks; std::vector other_picks; - leak_picks.reserve(16); - // Fresh picks kept by the queue drain (bounded by max_count) - used to keep the fair-tier - // consumption below from double-selecting them. + // Fresh-pick membership for the fair tiers' dedup: a set, not a vector - the fair tiers probe + // it once per scanned pick on the per-pass hot path. std::unordered_set fresh_kept_tags; - const size_t fresh_queue_len = _static_anchor_fresh_queue.size(); + std::vector fresh_spent_tags; + selected.reserve(max_picks); + leak_picks.reserve(max_picks); + fresh_picks.reserve(std::min(fresh_queue_len, max_picks)); + container_picks.reserve(fair_pick_limit); + other_picks.reserve(fair_pick_limit); + fresh_kept_tags.reserve(std::min(fresh_queue_len, max_picks)); + fresh_spent_tags.reserve(fresh_queue_len + max_picks); + std::unordered_set leak_spent_tags; + // Reserve before the lock like the other scratch vectors: the common pass reclaims nothing, + // and an unreserved push_back would pay its first growth inside the shared-lock lambda. + std::vector dead_tags; + dead_tags.reserve(16); + bool container_before_cursor = false; + bool other_before_cursor = false; _frontier->withSharedLock([&](const FrontierTable *frontier) { - // Drop dead/ABANDONED entries and compact survivors in admission order before tier selection. - // Released tags are re-minted, so a later observation can 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++) { + for (size_t i = 0; i < idx_size; i++) { jlong tag = _static_anchor_index[i]; + jlong own_class_tag = i < _static_anchor_own_class_tags.size() + ? _static_anchor_own_class_tags[i] + : 0; FrontierEntry entry{}; if (!frontier->lookupLocked(tag, &entry) || entry.state == FrontierEntryState::ABANDONED) { - _static_anchor_index_class_tags.erase(tag); + // Dead holder: the scan is the only reclaim below the durable cap - the selection + // skip means the walk's missing-anchor path can never see the tag again. + dead_tags.push_back(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) || @@ -179,92 +229,123 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { continue; } if (entry.leak_tag != 0) { - leak_picks.push_back(TierPick{pos, tag}); - } else if (shape_it != _class_shape_cache.end() && - (shape_it->second == static_cast(AnchorClassShape::CONTAINER) || - shape_it->second == - static_cast(AnchorClassShape::UNKNOWN_TRUNCATED))) { - container_picks.push_back(TierPick{pos, tag}); + if (leak_picks.size() < max_picks) { + leak_picks.push_back(TierPick{i, tag}); + } else { + // Capped out: a leak-tagged anchor never falls to the fair tiers (only this tier and + // the fresh lane can select it, and the fresh lane's filter rejects leak tags), so a + // skipped suffix pick must not keep a fresh-lane turn it can never spend on a walk. + // Spend the first look here - the leak tier's own cap is the only wait, and once the + // head drains the anchor is still leak-tagged and still selectable by this scan. + fresh_spent_tags.push_back(tag); + leak_spent_tags.insert(tag); + } } else { - other_picks.push_back(TierPick{pos, tag}); + bool is_container = false; + if (i < _static_anchor_own_class_tags.size()) { + auto shape_it = + _class_shape_cache.find(_static_anchor_own_class_tags[i]); + is_container = shape_it != _class_shape_cache.end() && + (shape_it->second == (u8)AnchorClassShape::CONTAINER || + shape_it->second == (u8)AnchorClassShape::UNKNOWN_TRUNCATED); + } + if (is_container) { + if (i < _anchor_container_cursor) { + container_before_cursor = true; + } else if (container_picks.size() < fair_pick_limit) { + container_picks.push_back(TierPick{i, tag}); + } + } else if (i < _anchor_other_cursor) { + other_before_cursor = true; + } else if (other_picks.size() < fair_pick_limit) { + other_picks.push_back(TierPick{i, tag}); + } } } - _static_anchor_index.resize(kept); - idx_size = kept; - // Fresh-lane drain. Every queue entry is popped (its ONE first look is spent either way): 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; - } - jlong tag = _static_anchor_fresh_queue.front(); - _static_anchor_fresh_queue.pop_front(); - size_t pos = drain_pos; - drain_pos++; - if (pos >= idx_size || _static_anchor_index[pos] != tag) { - // 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); - if (it == _static_anchor_index.end()) { - continue; + + int fresh_room = + (max_count - (int)leak_picks.size()) - + (max_count - (int)leak_picks.size()) / 2; + if (fresh_room <= 0 && !_static_anchor_fresh_queue.empty()) { + // The leak tier saturated the whole selection budget: the fresh lane got NO budget this + // pass, so queued entries would never pop and never receive fair-tier budget either - + // spend their first look now (the old queue.clear() semantics) so they fall back to the + // fair tiers at their index positions once the leak tier ebbs. With a positive fresh + // budget the queue keeps its entries' turns across passes (FIFO order, nothing jumps the + // queue). An entry no longer in the durable index has no fair-tier fallback, so its turn + // stays queued for the pass the leak tier ebbs instead of being spent here. + std::deque pending; + while (!_static_anchor_fresh_queue.empty()) { + FreshAnchor anchor = _static_anchor_fresh_queue.front(); + _static_anchor_fresh_queue.pop_front(); + if (_static_anchor_index_tags.count(anchor.tag) != 0) { + fresh_spent_tags.push_back(anchor.tag); + } else { + pending.push_back(anchor); } - 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; } + _static_anchor_fresh_queue.swap(pending); + } + while (!_static_anchor_fresh_queue.empty() && fresh_room > 0) { + FreshAnchor anchor = _static_anchor_fresh_queue.front(); + _static_anchor_fresh_queue.pop_front(); + // A queued entry carries the enqueue-time class tag; the index's stored tag is the + // authority - a 0-to-resolved upgrade between enqueue and pop must not make the fresh + // lane reject an eligible container and spend its only queued turn. + auto known = _static_anchor_index_class_tags.find(anchor.tag); + jlong shape_tag = known != _static_anchor_index_class_tags.end() + ? known->second.class_tag + : anchor.own_class_tag; FrontierEntry entry{}; - if (!frontier->lookupLocked(tag, &entry) || - !isSelectableAnchor(entry, own_class_tag) || + if (!frontier->lookupLocked(anchor.tag, &entry) || + !isSelectableAnchor(entry, shape_tag) || (entry.state != FrontierEntryState::FRONTIER && entry.state != FrontierEntryState::EXPANDED) || - isQueuedForRotation(tag) || entry.leak_tag != 0) { - 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) + isQueuedForRotation(anchor.tag) || entry.leak_tag != 0) { + // Dead/ineligible/queued/leak-tier: first look spent, not fresh-kept (the leak tier + // selects it via the scan if it is leak-tagged). + fresh_spent_tags.push_back(anchor.tag); + continue; } - auto shape_it = _class_shape_cache.find(own_class_tag); + auto shape_it = _class_shape_cache.find(shape_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 (durable roots only) + shape_it->second == (u8)AnchorClassShape::CONTAINER || + shape_it->second == (u8)AnchorClassShape::UNKNOWN_TRUNCATED; + if (!keep && known != _static_anchor_index_class_tags.end()) { + // Classified non-container and still indexed: the other tier's scan can select it, + // so the fresh lane spends the turn here. + fresh_spent_tags.push_back(anchor.tag); + continue; + } + // Evicted non-container (no fair-tier fallback) and container/unknown/truncated shapes + // alike: the preserved queued turn is this holder's only rotation walk, so it is spent as + // a fresh pick - spending it without a fallback would strand the holder until + // re-enumeration and no re-enlist could restore the served turn. + fresh_picks.push_back(TierPick{idx_size, anchor.tag}); + fresh_kept_tags.insert(anchor.tag); + if (fresh_picked != nullptr) { + fresh_picked->push_back(anchor); } - fresh_picks.push_back(TierPick{pos, tag}); - fresh_kept_tags.insert(tag); fresh_room--; } }); - // Cursor-fair consumption of one tier: scan picks (sorted by pos by construction) starting at - // entries with pos >= cursor, stop at `want` OR at the lap end (NO within-call wrap: re-walking - // anchors this same call already covered would waste walk budget - the leftover budget flows to - // the next tier instead, and the cursor resets to 0 so the NEXT call starts a fresh lap). auto consume_tier_fair = [&](const std::vector &picks, - size_t &cursor, int want) { + bool has_pick_before_cursor, size_t &cursor, + int want) { int took = 0; - if (want <= 0 || picks.empty()) { + if (want <= 0) { + return took; + } + if (picks.empty()) { + if (has_pick_before_cursor) { + cursor = 0; + } return took; } size_t consumed_pos = 0; for (size_t k = 0; k < picks.size() && took < want; k++) { const TierPick &p = picks[k]; - if (p.pos < cursor) { - continue; - } - if (fresh_kept_tags.count(p.tag) > 0) { + if (fresh_kept_tags.count(p.tag) != 0) { continue; } selected.push_back(p.tag); @@ -273,24 +354,6 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { } if (took > 0) { cursor = consumed_pos + 1 >= idx_size ? 0 : consumed_pos + 1; - } else { - // Took nothing AND no pick sits at or ahead of the cursor: this lap - // already passed every current member of the tier (members selected in - // earlier calls and since demoted out of eligibility). Without a reset - // the cursor never wraps again - every later call skips them all - // (p.pos < cursor) and the tier starves until a NEW anchor is appended - // at a higher pos. Treat the lap as completed-but-unproductive and - // restart it, matching the wrap semantics applied above. - bool any_ahead = false; - for (const TierPick &p : picks) { - if (p.pos >= cursor) { - any_ahead = true; - break; - } - } - if (!any_ahead) { - cursor = 0; - } } return took; }; @@ -302,9 +365,6 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { selected.push_back(p.tag); budget_left--; } - // Fresh lane: queue order (admission order) so a burst larger than the budget spends the oldest - // first looks first and nothing jumps the queue; outranked fresh anchors fall back to the fair - // tiers at their positions (the drain already dropped them from the queue). for (const TierPick &p : fresh_picks) { if (budget_left <= 0) { break; @@ -312,29 +372,63 @@ ReferenceChainTracker::collectStaticFieldAnchorsForRotation(int max_count) { selected.push_back(p.tag); budget_left--; } - budget_left -= consume_tier_fair(container_picks, _anchor_container_cursor, - budget_left); - // The other tier is the last consumer of the budget - its leftover has no further reader, so - // don't accumulate it back into budget_left (a dead store clang scan-build flags). - consume_tier_fair(other_picks, _anchor_other_cursor, budget_left); + budget_left -= consume_tier_fair(container_picks, container_before_cursor, + _anchor_container_cursor, budget_left); + consume_tier_fair(other_picks, other_before_cursor, _anchor_other_cursor, + budget_left); + + if (!selected.empty() || !leak_spent_tags.empty()) { + // Selection alone no longer consumes a fresh anchor's first look: walked anchors are marked + // served after their descent (the caller, post-flush), and unwalked fresh picks are requeued + // to the queue front. Erase the tags whose look IS spent this pass and that must not sit in + // the queue: selected tags (leak- or fair-tier picks - their look happens via the walk, and + // leaving them queued would re-serve them next pass) and the cap-skipped leak suffix (spent + // in the scan above). A fair-tier pick can still hold a queue entry; it goes to fresh_picked + // with the fresh-lane picks so the caller's unwalked requeue restores its queued turn. + std::unordered_set served(selected.begin(), selected.end()); + served.insert(leak_spent_tags.begin(), leak_spent_tags.end()); + for (auto it = _static_anchor_fresh_queue.begin(); + it != _static_anchor_fresh_queue.end();) { + if (served.count(it->tag) != 0) { + if (fresh_picked != nullptr) { + fresh_picked->push_back(*it); + } + it = _static_anchor_fresh_queue.erase(it); + } else { + ++it; + } + } + } + // First looks spent WITHOUT a walk: entries the fresh-lane filters rejected (dead, leak-tier, + // non-container), the leak-tier cap's skipped suffix, and the no-budget overflow drain. These + // never descend this pass, so their look is spent here; walked anchors' looks are spent by the + // caller after the scope flush. + _frontier->markAnchorRotationServed(fresh_spent_tags.data(), + fresh_spent_tags.size()); + if (!dead_tags.empty()) { + // Reclaim after every position this pass recorded was consumed: the erase compacts the + // index, so surviving cursors set above may wait one lap before their tier sees them again. + removeMissingAnchors(dead_tags); + } return selected; } -void ReferenceChainTracker::pushAtRiskStaticAnchor(jlong tag, u32 klass_id) { - if (_static_anchor_fifo_set.contains(tag)) { - return; - } - if (_static_anchor_fifo.size() >= STATIC_ANCHOR_FIFO_CAP) { - // The per-class quota prevents a single class from saturating this queue. - return; +bool ReferenceChainTracker::atRiskAnchorNeedsObservation(jlong tag, + u32 klass_id) const { + if (_static_anchor_fifo_set.contains(tag) || + _static_anchor_fifo.size() >= STATIC_ANCHOR_FIFO_CAP) { + return false; } auto count_it = _static_anchor_fifo_klass_counts.find(klass_id); - if (count_it != _static_anchor_fifo_klass_counts.end() && - count_it->second >= STATIC_ANCHOR_ATRISK_PER_KLASS_CAP) { - // Per-class quota drop: this class already holds its share of the lane, and its oldest entry - // drains within a few passes (STATIC_ANCHOR_FIFO_DRAIN=16/pass). + return count_it == _static_anchor_fifo_klass_counts.end() || + count_it->second < STATIC_ANCHOR_ATRISK_PER_KLASS_CAP; +} + +void ReferenceChainTracker::pushAtRiskStaticAnchor(jlong tag, u32 klass_id) { + if (!atRiskAnchorNeedsObservation(tag, klass_id)) { return; } + auto count_it = _static_anchor_fifo_klass_counts.find(klass_id); if (count_it == _static_anchor_fifo_klass_counts.end()) { count_it = _static_anchor_fifo_klass_counts.emplace(klass_id, 0U).first; } @@ -350,7 +444,328 @@ void ReferenceChainTracker::addToStaticAnchorIndex(jlong tag, root_kind != (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { return; } - indexAnchorForRotation(tag, own_class_tag, false); + // A local holder later attached by a durable root now belongs to the capped durable share; + // release its slot in the local cap (it stays indexed - the dedup below is a no-op for it). + // INVARIANT (_local_anchor_tags ⊆ _static_anchor_index_tags): erasing here keeps the subset + // relation evictOldestDurableAnchors()'s durable-share subtraction relies on - the tag stays + // in _static_anchor_index_tags, so a local-share tag is always an indexed tag, never the + // reverse. + _local_anchor_tags.erase(tag); + // The upgrade grows the durable share without a new index push (the dedup in + // indexAnchorForRotation() returns early), so the durable cap is checked here too. The just + // upgraded tag may itself be among the evicted oldest entries; replay of its next durable-edge + // observation re-indexes it. + evictOldestDurableAnchors(); + indexAnchorForRotation(tag, own_class_tag); +} + +void ReferenceChainTracker::advancePendingLocalAnchorEvictionCursor() { + if (_pending_local_evict_cursor > _pending_local_anchors.size()) { + _pending_local_evict_cursor = 0; + } + while (_pending_local_evict_cursor < _pending_local_anchors.size()) { + auto shape = _class_shape_cache.find( + _pending_local_anchors[_pending_local_evict_cursor].class_tag); + if (shape == _class_shape_cache.end() || + (shape->second != (u8)AnchorClassShape::CONTAINER && + shape->second != (u8)AnchorClassShape::UNKNOWN_TRUNCATED)) { + break; + } + _pending_local_evict_cursor++; + } +} + +void ReferenceChainTracker::preparePendingLocalAnchorEvictionCursor() { + if (_pending_local_anchors.size() >= PENDING_LOCAL_ANCHOR_CAP) { + advancePendingLocalAnchorEvictionCursor(); + } +} + +bool ReferenceChainTracker::localHolderNeedsObservation( + jlong tag, jlong own_class_tag) const { + auto shape = _class_shape_cache.find(own_class_tag); + if (shape != _class_shape_cache.end() && + shape->second != (u8)AnchorClassShape::CONTAINER && + shape->second != (u8)AnchorClassShape::UNKNOWN_TRUNCATED) { + return false; + } + if (_static_anchor_index_tags.count(tag) > 0 || + _pending_local_anchor_tags.count(tag) > 0) { + return false; + } + if (shape == _class_shape_cache.end()) { + return _pending_local_anchors.size() < PENDING_LOCAL_ANCHOR_CAP; + } + if (_local_anchor_tags.size() < LOCAL_ANCHOR_INDEX_CAP || + _pending_local_anchors.size() < PENDING_LOCAL_ANCHOR_CAP) { + return true; + } + return _pending_local_evict_cursor < _pending_local_anchors.size(); +} + +void ReferenceChainTracker::noteLocalRootHolder(jlong tag, + jlong own_class_tag) { + auto shape = _class_shape_cache.find(own_class_tag); + if (shape != _class_shape_cache.end() && + shape->second != (u8)AnchorClassShape::CONTAINER && + shape->second != (u8)AnchorClassShape::UNKNOWN_TRUNCATED) { + return; // classified non-container: never indexed + } + if (_static_anchor_index_tags.count(tag) > 0) { + return; // already indexed (durable root or earlier local report) + } + bool confirmed_container = false; + if (shape != _class_shape_cache.end()) { + if (_local_anchor_tags.size() < LOCAL_ANCHOR_INDEX_CAP) { + // INVARIANT (_local_anchor_tags ⊆ _static_anchor_index_tags): every local-share insert is + // immediately followed by indexAnchorForRotation(), which inserts the same tag into + // _static_anchor_index_tags (dedup no-op if already indexed) - the subset relation + // evictOldestDurableAnchors()'s durable-share subtraction relies on. + _local_anchor_tags.emplace(tag, own_class_tag); + indexAnchorForRotation(tag, own_class_tag); + return; + } + // At the cap: defer to resolvePendingLocalAnchors(), which may compact dead local entries + // on the BFS thread. + confirmed_container = true; + } + if (_pending_local_anchors.size() >= PENDING_LOCAL_ANCHOR_CAP) { + if (!confirmed_container || _pending_local_anchor_tags.count(tag) > 0) { + return; // re-reported by the next root enumeration + } + // A confirmed container is walkable as soon as a local slot frees, so it outranks an entry not + // yet confirmed as a container: evict the oldest such entry (re-reported by the next root + // enumeration). Forward-only cursor: while the buffer is full nothing is appended, the only + // overwrite is at the cursor with a container, and skipped slots are containers, so every slot + // below the cursor stays a confirmed container and the scan totals <= PENDING_LOCAL_ANCHOR_CAP + // per enumeration. + advancePendingLocalAnchorEvictionCursor(); + if (_pending_local_evict_cursor >= _pending_local_anchors.size()) { + return; // only confirmed containers parked: dropped, re-reported by the next enumeration + } + PendingLocalAnchor &victim = _pending_local_anchors[_pending_local_evict_cursor++]; + _pending_local_anchor_tags.erase(victim.tag); + // The count is maintained by the same replay that parks the entries, so it must be positive + // here; the clamp keeps a drifted count from wrapping the size_t in release builds while the + // assert keeps the drift visible in debug. + assert(_pending_local_evictable_count > 0); + _pending_local_evictable_count = + _pending_local_evictable_count > 0 ? _pending_local_evictable_count - 1 : 0; + victim = PendingLocalAnchor{tag, own_class_tag}; + _pending_local_anchor_tags.insert(tag); + return; + } + if (!_pending_local_anchor_tags.insert(tag).second) { + return; + } + if (shape == _class_shape_cache.end()) { + _pending_local_evictable_count++; + } + _pending_local_anchors.push_back(PendingLocalAnchor{tag, own_class_tag}); +} + +void ReferenceChainTracker::resolvePendingLocalAnchors() { + if (_pending_local_anchors.empty()) { + return; + } + bool compacted = false; + for (const PendingLocalAnchor &pending : _pending_local_anchors) { + if (_static_anchor_index_tags.count(pending.tag) > 0) { + continue; + } + auto shape = _class_shape_cache.find(pending.class_tag); + if (shape == _class_shape_cache.end() || + (shape->second != (u8)AnchorClassShape::CONTAINER && + shape->second != (u8)AnchorClassShape::UNKNOWN_TRUNCATED)) { + continue; // non-container, or still unclassified: dropped (see the buffer's comment). + // UNKNOWN_TRUNCATED indexes like a container: the bounded walk could not prove + // a non-match, so the holder keeps its selection eligibility (isSelectableAnchor + // accepts the same shapes). + } + if (_local_anchor_tags.size() >= LOCAL_ANCHOR_INDEX_CAP && !compacted) { + // At most one compaction attempt per call. After a compaction that removed nothing (local + // share full of live containers), skip the next LOCAL_ANCHOR_COMPACT_BACKOFF attempts so a + // saturated-but-live share does not pay the locked O(cap) scan every pass. + compacted = true; + if (_local_compact_backoff > 0) { + _local_compact_backoff--; + } else { + const size_t reclaimed = compactLocalAnchors(); + _local_compact_backoff = + reclaimed < LOCAL_ANCHOR_COMPACT_MIN_RECLAIM + ? LOCAL_ANCHOR_COMPACT_BACKOFF + : 0; + } + } + if (_local_anchor_tags.size() >= LOCAL_ANCHOR_INDEX_CAP) { + continue; // still full (live containers, or compaction backed off): the cap holds + } + _local_anchor_tags.emplace(pending.tag, pending.class_tag); + // INVARIANT (_local_anchor_tags ⊆ _static_anchor_index_tags): same contract as + // noteLocalRootHolder()'s insert - indexAnchorForRotation() below adds the tag to + // _static_anchor_index_tags in the same step. + indexAnchorForRotation(pending.tag, pending.class_tag); + } + // Keep capacity: the buffer refills on every root enumeration. + _pending_local_anchors.clear(); + _pending_local_anchor_tags.clear(); + _pending_local_evict_cursor = 0; + _pending_local_evictable_count = 0; +} + +size_t ReferenceChainTracker::compactLocalAnchors() { + if (_local_anchor_tags.empty()) { + return 0; + } + std::unordered_set removed; + _frontier->withSharedLock([&](const FrontierTable *frontier) { + // Only the local share (O(cap)): the durable share is never compacted here. + for (const auto &local : _local_anchor_tags) { + FrontierEntry entry{}; + // Same eligibility as collectStaticFieldAnchorsForRotation(): a released (ABANDONED) entry + // is a dead object and can never be selected again. + if (!frontier->lookupLocked(local.first, &entry) || + !isSelectableAnchor(entry, local.second) || + (entry.state != FrontierEntryState::FRONTIER && + entry.state != FrontierEntryState::EXPANDED)) { + removed.insert(local.first); + } + } + }); + if (removed.empty()) { + return 0; + } + eraseAnchorEntries(removed); + return removed.size(); +} + +size_t ReferenceChainTracker::evictOldestDurableAnchors() { + // The local share is capped and self-compacting; only entries outside it count against the + // durable cap. + size_t durable = _static_anchor_index_tags.size() - _local_anchor_tags.size(); + if (durable <= DURABLE_ANCHOR_INDEX_CAP) { + return 0; + } + // Evict enough oldest entries to drop the share to cap - DURABLE_ANCHOR_EVICT_BATCH, so one + // O(index) compaction amortizes over ~DURABLE_ANCHOR_EVICT_BATCH admissions instead of being + // paid per admission. to_evict <= durable always (DURABLE_ANCHOR_INDEX_CAP > batch). + size_t to_evict = + durable - DURABLE_ANCHOR_INDEX_CAP + DURABLE_ANCHOR_EVICT_BATCH; + // FIFO by index position (appends are at the back). Local-share entries keep their slots - + // their cap and compaction live in noteLocalRootHolder()/compactLocalAnchors(). + std::unordered_set evicted; + evicted.reserve(to_evict); + for (size_t i = 0; + i < _static_anchor_index.size() && evicted.size() < to_evict; + i++) { + jlong tag = _static_anchor_index[i]; + if (_local_anchor_tags.count(tag) > 0) { + continue; + } + evicted.insert(tag); + } + eraseAnchorEntries(evicted, /*preserve_pending_turns=*/true); + // Record a resweep request unconditionally (see _durable_anchor_resweep_gen): a holder + // displaced while admissions keep the population above the cap must be re-swept even when + // evictions stop. No cursor restart here: with churn above the cap an eviction fires every + // pass, and an unpaced cursor restart on each eviction would reset a mid-lap cursor so laps + // over large class lists never complete (later static fields never visited). The unserved generation alone is the scheduling contract - the lap in flight + // finishes, then the next fresh lap from class 0 serves the request. + _durable_anchor_resweep_gen++; + return evicted.size(); +} + +// See the declaration in referenceChains.h. +void ReferenceChainTracker::removeMissingAnchors( + const std::vector &missing) { + if (missing.empty()) { + return; + } + eraseAnchorEntries( + std::unordered_set(missing.begin(), missing.end())); +} + +// See the declaration in referenceChains.h. +void ReferenceChainTracker::eraseAnchorEntries( + const std::unordered_set &removed, bool preserve_pending_turns) { + if (removed.empty()) { + return; + } + // Stable compaction preserves index order and the parallel class-tag alignment. + // Durable eviction preserves pending first-look turns outside the capped index. + size_t out = 0; + for (size_t i = 0; i < _static_anchor_index.size(); i++) { + jlong tag = _static_anchor_index[i]; + if (removed.count(tag) > 0) { + continue; + } + _static_anchor_index[out] = tag; + if (i < _static_anchor_own_class_tags.size()) { + _static_anchor_own_class_tags[out] = _static_anchor_own_class_tags[i]; + } + out++; + } + _static_anchor_index.resize(out); + if (_static_anchor_own_class_tags.size() > out) { + _static_anchor_own_class_tags.resize(out); + } + if (preserve_pending_turns && !_static_anchor_fresh_queue.empty()) { + // Durable eviction preserves the queued first look but discards the index's class-tag + // metadata: write the resolved tag back into the queued entry here (before the map erase), + // or a re-enlist that re-inserts it (the queued entry is PENDING, so no new push happens) + // followed by another eviction would leave the preserved turn carrying the admission-time 0 + // and spend it on the unresolvable shape fallback. + for (FreshAnchor &anchor : _static_anchor_fresh_queue) { + if (anchor.own_class_tag != 0 || removed.count(anchor.tag) == 0) { + continue; + } + auto known = _static_anchor_index_class_tags.find(anchor.tag); + if (known != _static_anchor_index_class_tags.end() && + known->second.class_tag != 0) { + anchor.own_class_tag = known->second.class_tag; + } + } + } + for (jlong tag : removed) { + _static_anchor_index_tags.erase(tag); + auto known = _static_anchor_index_class_tags.find(tag); + if (known != _static_anchor_index_class_tags.end() && + known->second.class_tag == 0) { + _indexed_zero_class_tag_count--; + } + _static_anchor_index_class_tags.erase(tag); + _local_anchor_tags.erase(tag); + } + // The stable compaction shifted every survivor's position; the tag-keyed view must track it + // or the class-tag upgrade would write into the wrong slot. + for (size_t i = 0; i < _static_anchor_index.size(); i++) { + auto entry = _static_anchor_index_class_tags.find(_static_anchor_index[i]); + if (entry == _static_anchor_index_class_tags.end()) { + // The set and the map are maintained together (every push updates both, every erase + // clears both); a missing entry means a divergence, which must not turn into an + // end()-dereference here. + continue; + } + entry->second.pos = i; + } + if (!preserve_pending_turns) { + std::vector pending_removed; + pending_removed.reserve( + std::min(_static_anchor_fresh_queue.size(), removed.size())); + _static_anchor_fresh_queue.erase( + std::remove_if(_static_anchor_fresh_queue.begin(), + _static_anchor_fresh_queue.end(), + [&](const FreshAnchor &anchor) { + if (removed.count(anchor.tag) == 0) { + return false; + } + pending_removed.push_back(anchor.tag); + return true; + }), + _static_anchor_fresh_queue.end()); + _frontier->clearAnchorRotationPending(pending_removed.data(), + pending_removed.size()); + } } bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, @@ -362,36 +777,58 @@ bool ReferenceChainTracker::isSelectableAnchor(const FrontierEntry &entry, } 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)); + (shape->second == (u8)AnchorClassShape::CONTAINER || + shape->second == (u8)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. - 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; + jlong own_class_tag) { + // Dedup: a push at first admission and another at upgrade would double-add. A repeated sight + // with a resolved class tag upgrades a stored 0 (a root first reported before its class was + // tagged), or the container-shape fallback stays unavailable for this holder after + // reparenting takes away the root-attached eligibility. + auto known = _static_anchor_index_class_tags.find(tag); + if (known != _static_anchor_index_class_tags.end()) { + if (own_class_tag != 0 && known->second.class_tag == 0) { + known->second.class_tag = own_class_tag; + _static_anchor_own_class_tags[known->second.pos] = own_class_tag; + _indexed_zero_class_tag_count--; + // Keep the tag's pending fresh turn in sync: durable eviction preserves the queued turn + // outside the capped index but discards the index's class-tag metadata, so a queue entry + // still carrying the stale 0 would spend the preserved first look on the unresolvable + // shape fallback (reparented holders are selectable only through their class shape). + for (FreshAnchor &anchor : _static_anchor_fresh_queue) { + if (anchor.tag == tag && anchor.own_class_tag == 0) { + anchor.own_class_tag = own_class_tag; + } + } } return; } + if (!_static_anchor_index_tags.insert(tag).second) { + // In the set but not in the class-tag map: unreachable when both are maintained together + // (every push updates both, every erase clears both) - treat as already indexed. + return; + } + // Checked after the insert so the count includes the incoming tag; the batch evicts only the + // oldest positions, never the tag being admitted here. + evictOldestDurableAnchors(); + _static_anchor_index_class_tags.emplace( + tag, StaticAnchorIndexEntry{own_class_tag, _static_anchor_index.size()}); + if (own_class_tag == 0) { + _indexed_zero_class_tag_count++; + } _static_anchor_index.push_back(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); + _static_anchor_own_class_tags.push_back(own_class_tag); + if (_frontier != nullptr) { + if (_static_anchor_fresh_queue.size() < STATIC_ANCHOR_FRESH_CAP && + _frontier->tryMarkAnchorRotationPending(tag)) { + _static_anchor_fresh_queue.push_back(FreshAnchor{tag, own_class_tag}); + } else if (_static_anchor_fresh_queue.size() >= STATIC_ANCHOR_FRESH_CAP) { + // The prioritized first look was lost to the queue cap (the counter's documented + // meaning); the anchor keeps fair-tier coverage via the index. + Counters::increment(REFERENCE_CHAIN_STATIC_FRESH_DROPPED); + } } } @@ -540,31 +977,43 @@ ReferenceChainTracker::classImplementsContainerOrMap(jvmtiEnv *jvmti, : AnchorClassShape::NON_CONTAINER; } -void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, - JNIEnv *jni) { - if (jni == nullptr) { - return; - } - if (_static_anchor_index_class_tags.empty()) { - return; - } - // Collect up to ANCHOR_SHAPE_RECONCILE_BUDGET distinct class tags that appear in the anchor index - // but are not yet classified. +std::vector +ReferenceChainTracker::collectUnclassifiedAnchorClassTags() const { + // Collect up to ANCHOR_SHAPE_RECONCILE_BUDGET distinct class tags that appear in the pending + // local-holder buffer or the anchor index but are not yet classified. Pending holders go first: + // resolvePendingLocalAnchors() drops any still unclassified after this call, while indexed + // durable anchors simply wait for a later pass. std::vector unknown; unknown.reserve(8); std::unordered_set seen; - for (const auto &index_entry : _static_anchor_index_class_tags) { - jlong class_tag = index_entry.second.class_tag; + auto consider = [&](jlong class_tag) { if (class_tag == 0 || seen.count(class_tag) > 0 || _class_shape_cache.count(class_tag) > 0) { - continue; + return true; } seen.insert(class_tag); unknown.push_back(class_tag); - if ((int)unknown.size() >= ANCHOR_SHAPE_RECONCILE_BUDGET) { - break; - } + return (int)unknown.size() < ANCHOR_SHAPE_RECONCILE_BUDGET; + }; + bool room = true; + for (size_t i = 0; room && i < _pending_local_anchors.size(); i++) { + room = consider(_pending_local_anchors[i].class_tag); } + for (size_t i = 0; room && i < _static_anchor_own_class_tags.size(); i++) { + room = consider(_static_anchor_own_class_tags[i]); + } + return unknown; +} + +void ReferenceChainTracker::reconcileAnchorClassShapes(jvmtiEnv *jvmti, + JNIEnv *jni) { + if (jni == nullptr) { + return; + } + if (_static_anchor_own_class_tags.empty() && _pending_local_anchors.empty()) { + return; + } + std::vector unknown = collectUnclassifiedAnchorClassTags(); if (unknown.empty()) { return; } @@ -654,10 +1103,34 @@ void ReferenceChainTracker::requeueStaticAnchorFifoFront( _static_anchor_fifo_set.rebuildFrom(_static_anchor_fifo); } +void ReferenceChainTracker::requeueStaticAnchorFreshFront( + const std::vector &entries) { + if (entries.empty()) { + return; + } + // Reverse order onto the front preserves the tags' relative admission order (push_front of the + // LAST entry first leaves the FIRST entry at the deque's front). + for (size_t i = entries.size(); i-- > 0;) { + if (_static_anchor_fresh_queue.size() >= STATIC_ANCHOR_FRESH_CAP) { + // A flush between this pass's pops and the requeue can refill the freed slots: an + // entry requeued past the cap spends its first look here (fair-tier coverage via the + // index) rather than overfilling the queue or stranding a PENDING flag no later + // re-enlist could clear (tryMarkAnchorRotationPending refuses while PENDING is set). + if (_frontier != nullptr) { + _frontier->markAnchorRotationServed(&entries[i].tag, 1); + } + continue; + } + _static_anchor_fresh_queue.push_front(entries[i]); + } +} + void ReferenceChainTracker::walkStaticFieldAnchors( - jvmtiEnv *jvmti, JNIEnv *jni, const std::vector &anchor_tags, - int budget, int *edges_admitted, bool *truncated, bool *frontier_cap_hit, - u64 *safepoint_ns, std::vector *unwalked) { + jvmtiEnv *jvmti, JNIEnv *jni, ReferenceChainAnchorObservationScope &scope, + const std::vector &anchor_tags, int budget, int *edges_admitted, + bool *truncated, bool *frontier_cap_hit, u64 *safepoint_ns, + bool *anchor_observation_overflow, std::vector *unwalked) { + *anchor_observation_overflow = false; if (anchor_tags.empty()) { return; } @@ -666,10 +1139,33 @@ void ReferenceChainTracker::walkStaticFieldAnchors( jobject *objects = nullptr; jlong *resolved_tags = nullptr; if (jvmti->GetObjectsWithTags((jint)anchor_tags.size(), anchor_tags.data(), - &resolved_count, &objects, - &resolved_tags) != JVMTI_ERROR_NONE) { + &resolved_count, &objects, + &resolved_tags) != JVMTI_ERROR_NONE) { + // No anchor was walked, so none may be reported as walked: the caller marks first looks + // served only for tags outside `unwalked`. Permanently dead tags fail to resolve on the + // retry pass and are reclaimed by the missing-anchor path there. + if (unwalked != nullptr) { + unwalked->insert(unwalked->end(), anchor_tags.begin(), anchor_tags.end()); + } return; } + if ((jint)anchor_tags.size() > resolved_count) { + // Anchors absent from the resolution are collected: they can never be walked again, so their + // index slots are pure capacity waste - and a dead local container's frontier record stays + // selectable (EXPANDED), so compaction alone would keep rejecting replacement live containers + // until a search restart cleared the frontier. Reclaim the slots here; the frontier record + // itself stays - release machinery owns dead-entry cleanup. + std::unordered_set resolved(resolved_tags, + resolved_tags + resolved_count); + std::vector missing; + missing.reserve(anchor_tags.size() - resolved.size()); + for (jlong tag : anchor_tags) { + if (resolved.count(tag) == 0) { + missing.push_back(tag); + } + } + removeMissingAnchors(missing); + } int walked = 0; // First index the walk did NOT consume (breaks before an anchor's walk report i, breaks after // report i+1; a completed loop keeps the resolved_count sentinel). @@ -695,15 +1191,43 @@ void ReferenceChainTracker::walkStaticFieldAnchors( break; } int edges_before = *edges_admitted; - descendFromAnchor(jvmti, jni, objects[i], resolved_tags[i], entry.depth, - /*anchor_descend_class_tag=*/0, remaining, edges_admitted, - truncated, frontier_cap_hit, safepoint_ns); + bool overflow = false; + jvmtiError follow_err = + descendFromAnchor(jvmti, jni, scope, objects[i], resolved_tags[i], + entry.depth, /*anchor_descend_class_tag=*/0, remaining, + edges_admitted, truncated, frontier_cap_hit, safepoint_ns, + &overflow); TEST_LOG("ReferenceChainTracker::walkStaticFieldAnchors anchor walk " "outcome tag=%lld edges=%d truncated=%d cap_hit=%d", (long long)resolved_tags[i], *edges_admitted - edges_before, (int)*truncated, (int)*frontier_cap_hit); - walked++; jni->DeleteLocalRef(objects[i]); + if (follow_err != JVMTI_ERROR_NONE) { + // A failed descent was not walked; this anchor and everything after it keep their + // rotation turn via the unwalked path. The local ref was already deleted above, so the + // object may be collected before the retry pass - the retry's resolution then misses it + // and the missing-anchor path reclaims the slot instead of retrying a dead tag. + first_unwalked = i; + first_undeleted = i + 1; + break; + } + if (overflow) { + // The partially walked anchor stays unwalked (its rejected edge was not applied) so the + // caller restores it with the remaining resolved tags. Edge-accounting contract: + // ctx.edges_admitted counts NEW frontier admissions only (admitObject() counts a fresh + // insert, never an already-admitted tag), and the partial descent's accepted observation + // prefix IS replayed by the caller's scope flush - those admissions stay applied to the + // frontier. Keeping them counted is what keeps the budget exact: the later re-walk re- + // charges only edges that are still unadmitted (dedup by positive tag), so the anchor's + // segment is charged once in total. Rolling the partial edges back would let applied-to- + // frontier work escape the budget; incrementing the walk count would misreport the + // descent as consumed, so only the walk count stays untouched here. + *anchor_observation_overflow = true; + first_unwalked = i; + first_undeleted = i + 1; + break; + } + walked++; if (*truncated && !*frontier_cap_hit) { // Budget/deadline exhausted mid-set - remaining anchors keep their rotation turn via the // cursor next pass (the wrapping cursor already tolerates a short selection). @@ -816,9 +1340,39 @@ void ReferenceChainTracker::walkCandidateThreadLocals( if (anchor_tag != 0) { int remaining = budget - *edges_admitted; if (remaining > 0) { - descendFromAnchor(jvmti, jni, thread_obj, anchor_tag, anchor_depth, - descend_class_tag, remaining, edges_admitted, - truncated, frontier_cap_hit, safepoint_ns); + bool overflow = false; + jvmtiError follow_err = JVMTI_ERROR_NONE; + { + ReferenceChainAnchorObservationScope scope(this); + follow_err = descendFromAnchor( + jvmti, jni, scope, thread_obj, anchor_tag, anchor_depth, + descend_class_tag, remaining, edges_admitted, truncated, + frontier_cap_hit, safepoint_ns, &overflow); + // Flush this descent before the loop advances or retains its cursor. + // Later traversal decisions must see its accepted observations. + scope.flush(); + } + if (overflow || follow_err != JVMTI_ERROR_NONE) { + // The partially walked anchor stays unwalked (its rejected edge was not applied), + // matching walkStaticFieldAnchors(): the descent is not misreported as consumed, so + // the retained cursor re-walks it in full without the walked count charging it. A + // failed FollowReferences is transient, not a missing object - the walked thread is + // a registered JNI global ref and stays reachable for the retry. A persistent + // FollowReferences failure must not re-anchor the + // cursor on the same anchor every pass: after THREAD_WALK_FAILURE_SKIP consecutive + // failures the cursor advances past it and the wrap retries it on a later cycle. + // A journal overflow keeps the plain retain: it clears with the next pass's flush. + if (follow_err != JVMTI_ERROR_NONE) { + _thread_walk_consecutive_failures++; + if (_thread_walk_consecutive_failures >= THREAD_WALK_FAILURE_SKIP) { + _thread_walk_consecutive_failures = 0; + i = (i + 1) % total; + _thread_walk_anchor_cursor = i; + } + } + break; // retain the cursor on this thread: its walk was cut short + } + _thread_walk_consecutive_failures = 0; walked++; } } diff --git a/ddprof-lib/src/main/cpp/referenceChainEvents.cpp b/ddprof-lib/src/main/cpp/referenceChainEvents.cpp index 1a5de250ff..96474eef0f 100644 --- a/ddprof-lib/src/main/cpp/referenceChainEvents.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainEvents.cpp @@ -154,12 +154,13 @@ void ReferenceChainTracker::pollWatchedTargets(jvmtiEnv *jvmti, JNIEnv *jni) { return; } - // Don't rebuild chains against cache entries the heap callback asked to drop. - drainPendingChainInvalidations(); - // Stamp every entry this poll refreshes with the current search generation. const u64 current_search_ns = load(_search_start_ns); + // Don't rebuild chains against cache entries the heap callback asked to drop, and refresh the + // ones whose path changed (the only site that applies REBUILD invalidations). + applyPendingChainInvalidations(jvmti, jni, current_search_ns); + // klass_ids resolved (and therefore already pruned-if-dead) by the candidate loop below, so the // prune pass afterwards skips re-resolving them - it only needs to cover cached klasses that are // no longer flagged. @@ -576,7 +577,7 @@ int ReferenceChainTracker::snapshotResolvedChainTags(jlong *out) { void ReferenceChainTracker::deferResolvedChainInvalidation( jlong source_tag, const jlong *resolved_chain_tags, - int resolved_chain_tag_count) { + int resolved_chain_tag_count, ChainInvalidationKind kind) { bool was_cached = false; for (int i = 0; i < resolved_chain_tag_count; i++) { if (resolved_chain_tags[i] == source_tag) { @@ -587,32 +588,69 @@ void ReferenceChainTracker::deferResolvedChainInvalidation( if (!was_cached) { return; } + // Cache keys are frontier tags (>= 0); a negative key would alias another tag's REBUILD + // encoding, so it is never queued. + assert(source_tag >= 0); + if (source_tag < 0) { + return; + } + const jlong evict = encodePendingChainInvalidation(source_tag, ChainInvalidationKind::EVICT); + const jlong rebuild = encodePendingChainInvalidation(source_tag, ChainInvalidationKind::REBUILD); + // A traversal snapshot and the cache cap bound distinct eligible tags; polling drains pending + // work before inserting chains. The overflow path still fails closed if that contract changes. _pending_chain_invalidations_lock.lock(); - for (jlong tag : _pending_chain_invalidations) { - if (tag == source_tag) { + for (jlong &pending : _pending_chain_invalidations) { + if (pending == evict) { + _pending_chain_invalidations_lock.unlock(); + return; // EVICT already queued - it wins over any REBUILD + } + if (pending == rebuild) { + if (kind == ChainInvalidationKind::EVICT) { + pending = evict; // the source was rejected after its path changed: erase, don't rebuild + } _pending_chain_invalidations_lock.unlock(); return; } } - // Cache insertion is serialized with traversals on the engine thread and dumps can only remove - // keys, so one pre-traversal snapshot bounds distinct eligible tags to the cache cap. - assert((int)_pending_chain_invalidations.size() < - MAX_PENDING_CHAIN_INVALIDATIONS); if ((int)_pending_chain_invalidations.size() < MAX_PENDING_CHAIN_INVALIDATIONS) { - _pending_chain_invalidations.push_back(source_tag); + _pending_chain_invalidations.push_back( + kind == ChainInvalidationKind::REBUILD ? rebuild : evict); + } else { + // No callback may drop an invalidation; the next drain clears every cached chain instead. + _pending_chain_invalidation_overflow = true; } _pending_chain_invalidations_lock.unlock(); } void ReferenceChainTracker::drainPendingChainInvalidations() { // Serialize drainers and scratch-buffer use with the cache. The producer lock is held only for - // the O(1) handoff, never for unordered_map erase or node destruction. + // a bounded (<= MAX_PENDING_CHAIN_INVALIDATIONS) in-place partition - EVICT entries move to the + // reserved scratch buffer, REBUILD entries stay pending for the BFS thread - never for + // unordered_map erase or node destruction. Neither step reallocates. ExclusiveLockGuard guard(&_resolved_chains_lock); _pending_chain_invalidations_lock.lock(); assert(_draining_chain_invalidations.empty()); - _pending_chain_invalidations.swap(_draining_chain_invalidations); + if (_pending_chain_invalidation_overflow) { + _pending_chain_invalidation_overflow = false; + _pending_chain_invalidations.clear(); + _pending_chain_invalidations_lock.unlock(); + Counters::increment(REFERENCE_CHAIN_EVENTS_DROPPED, + static_cast(_resolved_chains.size())); + _resolved_chains.clear(); + return; + } + size_t kept = 0; + for (size_t i = 0; i < _pending_chain_invalidations.size(); i++) { + jlong pending = _pending_chain_invalidations[i]; + if (isPendingChainRebuild(pending)) { + _pending_chain_invalidations[kept++] = pending; + } else { + _draining_chain_invalidations.push_back(pending); + } + } + _pending_chain_invalidations.resize(kept); _pending_chain_invalidations_lock.unlock(); for (jlong tag : _draining_chain_invalidations) { @@ -624,11 +662,97 @@ void ReferenceChainTracker::drainPendingChainInvalidations() { _draining_chain_invalidations.clear(); } +void ReferenceChainTracker::applyPendingChainInvalidations( + jvmtiEnv *jvmti, JNIEnv *jni, u64 current_search_ns) { + // REBUILD tags whose cached chain is current-generation. A chain cached by an earlier search + // under the same numeric tag describes a different object (restartSearch() resets the tag + // namespace), so a path change on the new object says nothing about it: leave it alone. + jlong rebuild_tags[MAX_PENDING_CHAIN_INVALIDATIONS]; + int rebuild_count = 0; + { + ExclusiveLockGuard guard(&_resolved_chains_lock); + _pending_chain_invalidations_lock.lock(); + assert(_draining_chain_invalidations.empty()); + if (_pending_chain_invalidation_overflow) { + _pending_chain_invalidation_overflow = false; + _pending_chain_invalidations.clear(); + _pending_chain_invalidations_lock.unlock(); + Counters::increment(REFERENCE_CHAIN_EVENTS_DROPPED, + static_cast(_resolved_chains.size())); + _resolved_chains.clear(); + return; + } + _pending_chain_invalidations.swap(_draining_chain_invalidations); + _pending_chain_invalidations_lock.unlock(); + + for (jlong pending : _draining_chain_invalidations) { + jlong tag = pendingChainInvalidationTag(pending); + if (!isPendingChainRebuild(pending)) { + if (_resolved_chains.erase(tag) > 0) { + TEST_LOG("ReferenceChainTracker::drainPendingChainInvalidations source_tag=%lld", + (long long)tag); + } + continue; + } + auto it = _resolved_chains.find(tag); + if (it != _resolved_chains.end() && + it->second.source_search_ns == current_search_ns && + rebuild_count < MAX_PENDING_CHAIN_INVALIDATIONS) { + rebuild_tags[rebuild_count++] = tag; + } + } + _draining_chain_invalidations.clear(); + } + +#ifdef DEBUG + if (_between_invalidation_scan_and_writeback_for_test != nullptr) { + _between_invalidation_scan_and_writeback_for_test(); + } +#endif + + for (int i = 0; i < rebuild_count; i++) { + const jlong tag = rebuild_tags[i]; + ReferenceChainEvent event; + // The frontier entry stays intact until restartSearch(), so this does not depend on the + // candidate/discovered slots runPass()'s terminal branch may already have zeroed. + if (!buildChainEvent(jvmti, jni, tag, &event)) { + TEST_LOG("ReferenceChainTracker::applyPendingChainInvalidations rebuild failed, " + "keeping cached chain source_tag=%lld", + (long long)tag); + continue; + } + if (suppressChainEvent(event)) { + // The new path turned the chain into a filtered shape: same outcome as every other build + // site (see buildDiscoveredInstanceChains()). + invalidateResolvedChain(tag); + continue; + } + if (isLeakTag((jlong)event._target_tag) && !chainTargetsCurrentLeakOwner(event)) { + // Dead-owner rebuild: keep the old chain; the next dump evicts it if it is dead too. + continue; + } + event._start_time = TSC::ticks(); + ExclusiveLockGuard guard(&_resolved_chains_lock); + auto it = _resolved_chains.find(tag); + // Replace only: a dump may have evicted the entry (dead owner) since the scan above, and a + // rebuild must never resurrect it. + if (it != _resolved_chains.end() && + it->second.source_search_ns == current_search_ns) { + it->second.event = std::move(event); + it->second.source_tag = tag; + TEST_LOG("ReferenceChainTracker::applyPendingChainInvalidations rebuilt " + "source_tag=%lld depth=%u", + (long long)tag, it->second.event._depth); + } + } +} + void ReferenceChainTracker::clearPendingChainInvalidations() { ExclusiveLockGuard cache_guard(&_resolved_chains_lock); _pending_chain_invalidations_lock.lock(); _pending_chain_invalidations.clear(); _draining_chain_invalidations.clear(); + _pending_chain_invalidation_overflow = false; _pending_chain_invalidations_lock.unlock(); } @@ -763,7 +887,8 @@ void ReferenceChainTracker::recordDiscoveredInstance( _candidate_discovered_tags[s][d] = frontier_tag; if (invalidation_mode == CacheInvalidationMode::DEFERRED) { deferResolvedChainInvalidation(victim, resolved_chain_tags, - resolved_chain_tag_count); + resolved_chain_tag_count, + ChainInvalidationKind::EVICT); } else { invalidateResolvedChain(victim); } diff --git a/ddprof-lib/src/main/cpp/referenceChainFrontier.cpp b/ddprof-lib/src/main/cpp/referenceChainFrontier.cpp index aaaebd5f28..9aee92af7e 100644 --- a/ddprof-lib/src/main/cpp/referenceChainFrontier.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainFrontier.cpp @@ -112,6 +112,10 @@ bool FrontierTable::insert(jlong tag, jlong parent_tag, u32 referrer_klass, _table[idx].depth = depth; _table[idx].state = state; _table[idx].root_kind = root_kind; + _table[idx].root_report_attempt = 0; + _table[idx].root_report_kind_mask = 0; + _table[idx].root_report_sweep_attempt = 0; + _table[idx].anchor_rotation_flags = 0; _table[idx].class_tag = class_tag; _table[idx].leak_tag = 0; _table[idx].leak_tag_incarnation = 0; @@ -218,6 +222,222 @@ void FrontierTable::updateRootKind(jlong tag, u8 root_kind) { } } +void FrontierTable::markRootReportObserved(jlong tag, u8 root_kind, + u32 attempt_id, + bool static_sweep) { + u8 kind_bit = root_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD + ? FrontierRootReport::STATIC_FIELD_MASK + : root_kind == JVMTI_HEAP_REFERENCE_JNI_GLOBAL + ? FrontierRootReport::JNI_GLOBAL_MASK + : 0; + if (kind_bit == 0 || attempt_id == 0 || tag <= 0 || + tag - 1 >= (jlong)INT_MAX || + (static_sweep && root_kind != JVMTI_HEAP_REFERENCE_STATIC_FIELD)) { + return; + } + int idx = (int)(tag - 1); + if (static_sweep) { + // +1 with 0 reserved for never-stamped; two ids 65,535 apart share a bucket (bounded, + // one missed staging), but a fresh entry never false-matches an unstamped slot. + const u16 sweep_seq = (u16)((attempt_id & 0xFFFF) % 65535U + 1U); + { + SharedLockGuard guard(&_table_lock); + if (idx >= _table_size) { + return; + } + const bool chain_attached = _table[idx].parent_tag != 0; + if (chain_attached + ? (u32)_table[idx].referrer_class_tag == attempt_id + : _table[idx].root_report_sweep_attempt == sweep_seq) { + return; + } + } + ExclusiveLockGuard guard(&_table_lock); + if (idx < _table_size) { + // The sweep stamp never touches root_report_attempt: a root-attached write there + // would displace the enumeration stamp and restage the weaker JNI-global report on + // every retry (the starvation the stamp machinery prevents). Chain-attached + // entries keep the referrer_class_tag stamp - reconstructChain never reads that + // field on a parented entry. + if (_table[idx].parent_tag != 0) { + _table[idx].referrer_class_tag = (jlong)attempt_id; + } else { + _table[idx].root_report_sweep_attempt = sweep_seq; + } + } + return; + } + { + SharedLockGuard guard(&_table_lock); + if (idx >= _table_size || + (_table[idx].root_report_attempt == attempt_id && + (_table[idx].root_report_kind_mask & kind_bit) != 0)) { + return; + } + } + ExclusiveLockGuard guard(&_table_lock); + if (idx < _table_size) { + if (_table[idx].root_report_attempt != attempt_id) { + _table[idx].root_report_attempt = attempt_id; + _table[idx].root_report_kind_mask = kind_bit; + } else { + _table[idx].root_report_kind_mask |= kind_bit; + } + } +} + +bool FrontierTable::rootReportCompleted(jlong tag, u8 root_kind, + bool anchor_indexed, u32 attempt_id, + u32 previous_attempt_id, + bool retrying_incomplete, + bool *weaker_root_noop, + bool static_sweep, + u32 retry_base_id) { + if (weaker_root_noop != nullptr) { + *weaker_root_noop = false; + } + if (tag <= 0 || tag - 1 >= (jlong)INT_MAX) { + return false; + } + int idx = (int)(tag - 1); + SharedLockGuard guard(&_table_lock); + if (idx >= _table_size) { + return false; + } + const FrontierEntry &entry = _table[idx]; + // A retry sequence widens the recognized-stamp window to every attempt in it, else alternating + // oversized groups ping-pong (each retry restages the group the one-attempt window dropped). + // The window expires with the sequence; static-sweep stamps (high attempt bit) never fall in it. + const bool retry_sequence_seen = retrying_incomplete && retry_base_id != 0 && + retry_base_id <= attempt_id && + entry.root_report_attempt >= retry_base_id && + entry.root_report_attempt <= attempt_id && + (entry.root_report_attempt & FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT) == 0; + // Static attribution stays authoritative, but an unseen evicted anchor may re-enlist. + // An index hit or accepted retry stamp suppresses restaging of the weaker report. The old + // static-sweep stamp alone must NOT suppress: after a static edge disappears and FIFO eviction + // drops the holder from the durable index, the static sweep can never rediscover the holder + // through that edge again - only the JNI-global report can re-enlist it, so a stale sweep stamp + // would lock it out of indexed rotation forever (the stamp survives eviction because + // root_report_attempt lives on the frontier entry, not in the index). + bool weaker_jni_global = entry.parent_tag == 0 && + entry.root_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD && + root_kind == JVMTI_HEAP_REFERENCE_JNI_GLOBAL; + if (weaker_jni_global) { + bool root_global_seen = + attempt_id != 0 && entry.root_report_attempt == attempt_id && + (entry.root_report_kind_mask & + FrontierRootReport::JNI_GLOBAL_MASK) != 0; + bool previous_global_seen = retrying_incomplete && + previous_attempt_id != 0 && + entry.root_report_attempt == previous_attempt_id && + (entry.root_report_kind_mask & + FrontierRootReport::JNI_GLOBAL_MASK) != 0; + bool sequence_global_seen = retry_sequence_seen && + (entry.root_report_kind_mask & + FrontierRootReport::JNI_GLOBAL_MASK) != 0; + if (anchor_indexed || root_global_seen || previous_global_seen || + sequence_global_seen) { + if (weaker_root_noop != nullptr) { + *weaker_root_noop = true; + } + return true; + } + } + if (entry.parent_tag == 0 && entry.root_kind != root_kind && + !weaker_jni_global) { + return false; + } + if (static_sweep && root_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) { + // Chain-attached entries keep the referrer_class_tag stamp; root-attached entries keep + // the parallel u16 field (see markRootReportObserved). Low-16 comparisons match the stored + // truncation. + if (entry.parent_tag != 0) { + u32 stamped = (u32)entry.referrer_class_tag; + return anchor_indexed || + (attempt_id != 0 && stamped == attempt_id) || + (retrying_incomplete && previous_attempt_id != 0 && + stamped == previous_attempt_id); + } + u16 stamped = entry.root_report_sweep_attempt; + u16 now_seq = (u16)((attempt_id & 0xFFFF) % 65535U + 1U); + u16 prev_seq = (u16)((previous_attempt_id & 0xFFFF) % 65535U + 1U); + return anchor_indexed || + (attempt_id != 0 && stamped == now_seq) || + (retrying_incomplete && previous_attempt_id != 0 && + stamped == prev_seq); + } + u8 kind_bit = root_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD + ? FrontierRootReport::STATIC_FIELD_MASK + : root_kind == JVMTI_HEAP_REFERENCE_JNI_GLOBAL + ? FrontierRootReport::JNI_GLOBAL_MASK + : 0; + bool current_stamp = attempt_id != 0 && + entry.root_report_attempt == attempt_id && + (entry.root_report_kind_mask & kind_bit) != 0; + bool previous_stamp = retrying_incomplete && previous_attempt_id != 0 && + entry.root_report_attempt == previous_attempt_id && + (entry.root_report_kind_mask & kind_bit) != 0; + bool sequence_stamp = retry_sequence_seen && + (entry.root_report_kind_mask & kind_bit) != 0; + return anchor_indexed || current_stamp || previous_stamp || + sequence_stamp; +} + +bool FrontierTable::tryMarkAnchorRotationPending(jlong tag) { + if (tag <= 0 || tag - 1 >= (jlong)INT_MAX) { + return false; + } + int idx = (int)(tag - 1); + ExclusiveLockGuard guard(&_table_lock); + if (idx >= _table_size || + (_table[idx].anchor_rotation_flags & + (FrontierAnchorRotation::FIRST_LOOK_PENDING | + FrontierAnchorRotation::FIRST_LOOK_SERVED)) != 0) { + return false; + } + _table[idx].anchor_rotation_flags |= + FrontierAnchorRotation::FIRST_LOOK_PENDING; + return true; +} + +void FrontierTable::markAnchorRotationServed(const jlong *tags, size_t count) { + if (tags == nullptr || count == 0) { + return; + } + ExclusiveLockGuard guard(&_table_lock); + for (size_t i = 0; i < count; i++) { + jlong tag = tags[i]; + if (tag > 0 && tag - 1 < (jlong)INT_MAX) { + int idx = (int)(tag - 1); + if (idx < _table_size) { + u8 &flags = _table[idx].anchor_rotation_flags; + flags = static_cast( + (flags & ~FrontierAnchorRotation::FIRST_LOOK_PENDING) | + FrontierAnchorRotation::FIRST_LOOK_SERVED); + } + } + } +} + +void FrontierTable::clearAnchorRotationPending(const jlong *tags, + size_t count) { + if (tags == nullptr || count == 0) { + return; + } + ExclusiveLockGuard guard(&_table_lock); + for (size_t i = 0; i < count; i++) { + jlong tag = tags[i]; + if (tag > 0 && tag - 1 < (jlong)INT_MAX) { + int idx = (int)(tag - 1); + if (idx < _table_size) { + _table[idx].anchor_rotation_flags &= + static_cast(~FrontierAnchorRotation::FIRST_LOOK_PENDING); + } + } + } +} + bool FrontierTable::improveChain(jlong tag, jlong parent_tag, u32 referrer_klass, u32 depth, u8 root_kind, jint referrer_field_index, diff --git a/ddprof-lib/src/main/cpp/referenceChainFrontier.h b/ddprof-lib/src/main/cpp/referenceChainFrontier.h index d5b662814e..540d0bdd5b 100644 --- a/ddprof-lib/src/main/cpp/referenceChainFrontier.h +++ b/ddprof-lib/src/main/cpp/referenceChainFrontier.h @@ -27,6 +27,17 @@ constexpr u8 EDGE = 2; constexpr u8 ABANDONED = 3; // tag released; entry kept only to avoid reuse } // namespace FrontierEntryState +namespace FrontierAnchorRotation { +constexpr u8 FIRST_LOOK_PENDING = 1; +constexpr u8 FIRST_LOOK_SERVED = 2; +} // namespace FrontierAnchorRotation + +namespace FrontierRootReport { +constexpr u8 STATIC_FIELD_MASK = 1u << 0; +constexpr u8 JNI_GLOBAL_MASK = 1u << 1; +constexpr u32 STATIC_SWEEP_ATTEMPT_BIT = 1u << 31; +} // namespace FrontierRootReport + // Search outcome; per-pass truncation does not imply abandonment. namespace SearchState { constexpr u8 RUNNING = 0; // at least one more pass may still make progress @@ -61,8 +72,8 @@ typedef struct FrontierEntry { // LivenessTracker::leakTagIncarnation(leak_tag) captured when leak_tag was bound to this entry // (setLeakTag()): the ownership period of the tag this entry's object held. A leak tag is // recycled after its object dies, so (leak_tag, leak_tag_incarnation) - not leak_tag alone - - // identifies the object. 0 while leak_tag == 0. Sits in the padding after `state`, so - // sizeof(FrontierEntry) is unchanged (static_assert below). + // identifies the object. 0 while leak_tag == 0. It uses padding after `state`; report and + // rotation flags use padding after `root_kind` and `edge_kind`, preserving the 64-byte entry. u32 leak_tag_incarnation; // The leak tag assigned by LivenessTracker to this specific tracked object, copied from the JVMTI // tag at admission time. @@ -73,6 +84,13 @@ typedef struct FrontierEntry { // reconstructChain()'s callers want to report (they want to label the chain's root, not every // hop). u8 root_kind; + // Static-sweep retry stamp for ROOT-ATTACHED entries (the chain-attached shape uses + // referrer_class_tag): (low 16 bits of the sweep attempt id) + 1, so 0 means never-stamped and + // the enumeration stamp in root_report_attempt is never displaced. A false suppression needs + // the same tag re-swept exactly 65,536 sweep attempts apart - one missed staging, bounded. + u16 root_report_sweep_attempt; + // Last accepted root-report attempt and its kinds; attempt ids distinguish traversal sources. + u32 root_report_attempt; // Raw JVMTI class tag of THIS entry's own object, from the shared, process-wide allocator // (classTagAllocator.h) - NOT referrer_klass above (a classMap dictionary id, which can differ // for the same class at different times if that dictionary gets compacted/regenerated - see @@ -90,15 +108,16 @@ typedef struct FrontierEntry { // jvmtiHeapReferenceKind of the admitting edge for an INTERIOR hop (an entry with parent_tag != 0 // - "this object was reached from its parent via this kind of edge"). u8 edge_kind; + u8 root_report_kind_mask; // STATIC_FIELD and JNI_GLOBAL reports accepted in the stamped attempt + u8 anchor_rotation_flags; // fresh-queue pending and first-look-served bits - // Referrer's class tag when the referrer is a CLASS OBJECT rather than a frontier entry (a - // root-attached static-field admission - the referrer is the declaring class, parent_tag == 0 so - // there is no parent entry to read a class from). + // Declaring-class tag for root-attached static fields; chain entries reuse it for static retries. + // reconstructChain reads this value only when parent_tag is zero. jlong referrer_class_tag; } FrontierEntry; static_assert(sizeof(FrontierEntry) == 64, - "FrontierEntry::leak_tag_incarnation must stay in the padding after `state`"); + "frontier stamps must stay within existing FrontierEntry padding"); // Per-hop retention-edge identity collected by reconstructChain() alongside the class chain: // everything needed at emission to label HOW chain[i] is retained (the field of chain[i+1] pointing @@ -207,6 +226,23 @@ class alignas(alignof(SpinLock)) FrontierTable { // Updates only the recorded root kind. void updateRootKind(jlong tag, u8 root_kind); + // Records an accepted durable-root report in a root or static-sweep attempt. + void markRootReportObserved(jlong tag, u8 root_kind, u32 attempt_id, + bool static_sweep = false); + // Checks current/prior-incomplete attempt stamps or index membership for a durable-root report. + bool rootReportCompleted(jlong tag, u8 root_kind, bool anchor_indexed, + u32 attempt_id, u32 previous_attempt_id, + bool retrying_incomplete, + bool *weaker_root_noop = nullptr, + bool static_sweep = false, + u32 retry_base_id = 0); + + // Fresh-turn flags share FrontierEntry's existing padding. + // Pending turns survive index eviction; served turns do not regain fresh-lane priority. + bool tryMarkAnchorRotationPending(jlong tag); + void markAnchorRotationServed(const jlong *tags, size_t count); + void clearAnchorRotationPending(const jlong *tags, size_t count); + // Set the leak tag on a frontier entry (the JVMTI tag assigned by LivenessTracker to this // specific tracked leaking object) together with that tag's ownership-period stamp // (LivenessTracker::leakTagIncarnation(leak_tag)) read at the binding site. The stamp is required diff --git a/ddprof-lib/src/main/cpp/referenceChainInternal.h b/ddprof-lib/src/main/cpp/referenceChainInternal.h index 9258562658..fe9acbfe72 100644 --- a/ddprof-lib/src/main/cpp/referenceChainInternal.h +++ b/ddprof-lib/src/main/cpp/referenceChainInternal.h @@ -9,15 +9,280 @@ #include "arch.h" #include "common.h" -#include "referenceChainBatchSet.h" +#include "referenceChains.h" +#include #include +#include class FrontierTable; -class ReferenceChainTracker; ASSERT_ONLY(extern thread_local bool t_inGCCallback;) +// Caller-side owner of one traversal group's journal lease. Callbacks only reserve/commit; the +// caller observes the return and flushes. Destruction flushes any remaining prefix, then releases +// the lease. A flush whose captured epoch is stale discards before any tag lookup. +class ReferenceChainAnchorObservationScope { +public: + explicit ReferenceChainAnchorObservationScope(ReferenceChainTracker *tracker) + : _tracker(tracker), _buffer(&tracker->_anchor_observations), + _lease(_buffer->tryLease()) { + resetStagingBudgets(); + } + ~ReferenceChainAnchorObservationScope() { + flush(); + _buffer->releaseLease(_lease); // no-op for a non-owning or stale scope + } + ReferenceChainAnchorObservationScope(const ReferenceChainAnchorObservationScope &) = delete; + ReferenceChainAnchorObservationScope &operator=(const ReferenceChainAnchorObservationScope &) = delete; + + // Every journal operation goes through the scope's token; a non-owning scope's calls are + // rejected by the buffer and never touch another scope's journal. + AnchorObservationReservation reserve() { return AnchorObservationReservation(*_buffer, _lease); } + bool containsAction(jlong tag, u8 action) { + return _buffer->containsAction(_lease, tag, action); + } + + // Unknown shapes can use only pending slots; confirmed containers can use the local share, + // then a pending slot, then displace a staged unknown. The master budget bounds the scope's + // buffer FOOTPRINT: only growing admissions spend it, so a confirmed container whose record + // displaces a pending unknown stays admissible after the unknowns exhausted the buffer. + bool reserveLocalStaging(jlong tag, jlong class_tag) { + // Branch on the shape first: an exhausted budget must fail without paying + // localHolderNeedsObservation()'s up-to-three hash lookups (this runs per local-root edge + // inside the JVMTI enumeration callback, and the exhausted case is the saturated norm). + auto shape = _tracker->_class_shape_cache.find(class_tag); + const bool unclassified = shape == _tracker->_class_shape_cache.end(); + const bool confirmed_container = + !unclassified && + (shape->second == (u8)ReferenceChainTracker::AnchorClassShape::CONTAINER || + shape->second == + (u8)ReferenceChainTracker::AnchorClassShape::UNKNOWN_TRUNCATED); + if (unclassified) { + if (_local_staging_budget == 0 || _local_pending_budget == 0 || + !_tracker->localHolderNeedsObservation(tag, class_tag)) { + return false; + } + _local_pending_budget--; + _local_staging_budget--; + // The unknown this record parks in the pending buffer is itself displaceable: replay's + // eviction replaces the oldest unknown slot with a later confirmed container, so the + // container's own staging can spend this budget instead of being rejected. + _local_evictable_budget++; + return true; + } + if (!confirmed_container) { + return false; + } + if (_local_index_budget > 0) { + if (!_tracker->localHolderNeedsObservation(tag, class_tag)) { + return false; + } + _local_index_budget--; + _local_staging_budget--; + return true; + } + if (_local_pending_budget > 0) { + if (!_tracker->localHolderNeedsObservation(tag, class_tag)) { + return false; + } + _local_pending_budget--; + _local_staging_budget--; + return true; + } + if (_local_evictable_budget > 0) { + if (!_tracker->localHolderNeedsObservation(tag, class_tag)) { + return false; + } + // Displacement: replay's eviction replaces a pending unknown with this holder, so the + // buffer footprint is unchanged and replay can always absorb the record. + _local_evictable_budget--; + return true; + } + return false; + } + + bool reserveAtRiskStaging(jlong tag, u32 klass_id) { + if (_at_risk_staging_budget == 0 || + !_tracker->atRiskAnchorNeedsObservation(tag, klass_id) || + containsAction(tag, AnchorObservation::AT_RISK)) { + return false; + } + auto live = _tracker->_static_anchor_fifo_klass_counts.find(klass_id); + u32 live_count = live == _tracker->_static_anchor_fifo_klass_counts.end() + ? 0 + : live->second; + // Look the slot up WITHOUT claiming it: a rejection (table full or per-klass cap exceeded) + // must not burn a class-set slot for the rest of the scope - a claimed-but-unused slot + // accumulates across callbacks and can fill the fixed table, silently refusing later + // eligible classes. + bool found = false; + u32 slot = findAtRiskClassSlot(klass_id, found); + u32 staged = found ? _at_risk_class_counts[slot].count : 0; + if (slot == AT_RISK_CLASS_SET_SLOTS || + live_count + staged >= + ReferenceChainTracker::STATIC_ANCHOR_ATRISK_PER_KLASS_CAP) { + return false; + } + if (!found) { + _at_risk_class_used[slot >> 3] |= + static_cast(1u << (slot & 7)); + _at_risk_class_counts[slot] = AtRiskClassCount{klass_id, 0}; + } + _at_risk_class_counts[slot].count++; + _at_risk_staging_budget--; + return true; + } + + void markOverflow(bool static_attachment) { _buffer->markOverflow(_lease, static_attachment); } + bool ownsLease() const { return _lease.id != 0; } + + // Acquires the buffer lock so the caller sees the callbacks' writes; true if the journal overflowed. + bool observeReturn() { return _buffer->observeOverflow(_lease); } + + // Replays the accepted prefix, then resets count/static-retry/overflow while keeping the lease. + void flush() { + const AnchorObservation *records = nullptr; + u32 count = 0; + bool static_retry = false; + if (!_buffer->snapshot(_lease, &records, &count, &static_retry)) { + return; + } + if (count > 0 || static_retry) { + _tracker->replayAnchorObservations(records, count, static_retry); + } + _buffer->clearPrefix(_lease); + resetStagingBudgets(); + } + +private: + static constexpr u32 AT_RISK_CLASS_SET_SLOTS = + ReferenceChainTracker::STATIC_ANCHOR_FIFO_CAP * 2; + static constexpr u32 AT_RISK_CLASS_SET_BITMAP_BYTES = + AT_RISK_CLASS_SET_SLOTS / 8; + struct AtRiskClassCount { + u32 klass_id; + u8 count; + }; + static_assert((AT_RISK_CLASS_SET_SLOTS & (AT_RISK_CLASS_SET_SLOTS - 1)) == 0, + "at-risk staging set must be a power of two"); + // This fixed table accounts staged classes without allocating in heap callbacks. + // Twice the FIFO cap holds one distinct class per staged record at half load. + + u32 findAtRiskClassSlot(u32 klass_id, bool &found) const { + u32 slot = klass_id * 0x9E3779B9U >> 21; + for (u32 probes = 0; probes < AT_RISK_CLASS_SET_SLOTS; probes++) { + bool used = (_at_risk_class_used[slot >> 3] & + static_cast(1u << (slot & 7))) != 0; + if (!used) { + found = false; + return slot; + } + if (_at_risk_class_counts[slot].klass_id == klass_id) { + found = true; + return slot; + } + slot = (slot + 1) & (AT_RISK_CLASS_SET_SLOTS - 1); + } + found = false; + return AT_RISK_CLASS_SET_SLOTS; + } + + void resetStagingBudgets() { + _local_staging_budget = _tracker->localStagingAbsorbable(); + _local_index_budget = ReferenceChainTracker::LOCAL_ANCHOR_INDEX_CAP - + _tracker->_local_anchor_tags.size(); + _local_pending_budget = ReferenceChainTracker::PENDING_LOCAL_ANCHOR_CAP - + _tracker->_pending_local_anchors.size(); + _local_evictable_budget = _tracker->_pending_local_evictable_count; +#ifdef UNIT_TEST + if (_tracker->_local_staging_budget_override_for_test != 0) { + _local_index_budget = _local_staging_budget; + _local_pending_budget = _local_staging_budget; + _local_evictable_budget = _local_staging_budget; + } +#endif + _at_risk_staging_budget = ReferenceChainTracker::STATIC_ANCHOR_FIFO_CAP - + _tracker->_static_anchor_fifo.size(); + memset(_at_risk_class_used, 0, sizeof(_at_risk_class_used)); + } + + ReferenceChainTracker *_tracker; + AnchorObservationBuffer *_buffer; + AnchorObservationLease _lease; + u32 _local_staging_budget = 0; + size_t _local_index_budget = 0; + size_t _local_pending_budget = 0; + size_t _local_evictable_budget = 0; + size_t _at_risk_staging_budget = 0; + AtRiskClassCount _at_risk_class_counts[AT_RISK_CLASS_SET_SLOTS] = {}; + u8 _at_risk_class_used[AT_RISK_CLASS_SET_BITMAP_BYTES] = {}; +}; + +inline bool isDurableAnchorRootKind(u8 root_kind) { + return root_kind == (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD || + root_kind == (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL; +} + +// Callback branches reserve only when they can publish an anchor observation. +// Placement-new avoids moving the non-movable reservation; destruction cancels an unused slot. +class AnchorObservationReservationGuard { +public: + AnchorObservationReservationGuard() = default; + AnchorObservationReservationGuard(const AnchorObservationReservationGuard &) = delete; + AnchorObservationReservationGuard &operator=(const AnchorObservationReservationGuard &) = delete; + ~AnchorObservationReservationGuard() { + if (_live) { + get()->~AnchorObservationReservation(); + } + } + + bool acquire(ReferenceChainAnchorObservationScope &scope) { + new (&_storage) AnchorObservationReservation(scope.reserve()); + _live = true; + return get()->held(); + } + + void commit(const AnchorObservation &record) { + if (_live) { + get()->commit(record); + } + } + +private: + AnchorObservationReservation *get() { + return reinterpret_cast(&_storage); + } + + alignas(AnchorObservationReservation) unsigned char _storage[sizeof(AnchorObservationReservation)]; + bool _live = false; +}; + struct ReferenceChainPassContext { + // Required binding: the owning caller's scope; there is no unscoped immediate-mutation path. + explicit ReferenceChainPassContext(ReferenceChainAnchorObservationScope &scope) + : anchor_scope(scope) {} + + ReferenceChainAnchorObservationScope &anchor_scope; + + // Attempt stamps let each durable-report traversal skip its accepted prefix on retry. + u32 root_report_attempt_id = 0; + u32 root_report_previous_attempt_id = 0; + bool root_report_retrying_incomplete = false; + // The current incomplete retry sequence's first attempt id (0 outside root enumeration): the + // recognized-stamp window in rootReportCompleted() widens to the whole sequence. + u32 root_report_retry_base_id = 0; + + // Set with `truncated` when the journal had no room; distinct from frontier_cap_hit. The rejected + // transition is not performed, so the source traversal obligation stays unserved. + bool anchor_observation_overflow = false; + + // Records the overflow under the buffer lock; static_attachment requests a static-scan retry. + void abortForObservationOverflow(bool static_attachment) { + anchor_scope.markOverflow(static_attachment); + anchor_observation_overflow = true; + truncated = true; + } + ReferenceChainTracker *tracker; FrontierTable *frontier; int hop_cap; diff --git a/ddprof-lib/src/main/cpp/referenceChainObservation.h b/ddprof-lib/src/main/cpp/referenceChainObservation.h new file mode 100644 index 0000000000..055427ca41 --- /dev/null +++ b/ddprof-lib/src/main/cpp/referenceChainObservation.h @@ -0,0 +1,324 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef _REFERENCECHAINOBSERVATION_H +#define _REFERENCECHAINOBSERVATION_H + +#include "arch.h" +#include "spinLock.h" +#include +#include + +// One callback report's anchor effects for one frontier tag. Callbacks only record these; the +// caller replays them in arrival order after the synchronous JVMTI traversal returns. +struct AnchorObservation { + static constexpr u8 LOCAL = 1; // noteLocalRootHolder(tag, own_class_tag) + static constexpr u8 DURABLE_ADD = 2; // addToStaticAnchorIndex(tag, durable_root_kind, own_class_tag) + static constexpr u8 REENLIST_ELIGIBLE = 4; // indexAnchorForRotation() if not indexed + static constexpr u8 AT_RISK = 8; // pushAtRiskStaticAnchor(tag, at_risk_klass_id) + + jlong tag; + jlong own_class_tag; + u32 at_risk_klass_id; + u8 actions; + u8 durable_root_kind; +}; +static_assert(sizeof(AnchorObservation) <= 24, "AnchorObservation payload must stay <= 24 bytes"); + +// Ownership token of one scope: valid only while its id is the buffer's current lease and its +// epoch is unchanged. Default-constructed (id 0) is never valid. +struct AnchorObservationLease { + u64 epoch = 0; + u64 id = 0; +}; + +// Fixed-capacity, tracker-owned journal. The record array uses at most 384 KiB; the two per-scope +// LOCAL/AT_RISK indexes add 136 KiB. Metadata is locked; callbacks write records and the caller +// reads them after traversal returns. The lock is never held across JVMTI, frontier or index work. +class AnchorObservationBuffer { +public: + static constexpr u32 CAPACITY = 16384; + static constexpr u32 ACTION_TAG_SET_SLOTS = CAPACITY * 2; + static constexpr u32 ACTION_TAG_SET_BITMAP_BYTES = ACTION_TAG_SET_SLOTS / 8; + static constexpr u32 ACTION_DEDUP_STORAGE_BYTES = + 2 * (ACTION_TAG_SET_SLOTS * sizeof(u16) + ACTION_TAG_SET_BITMAP_BYTES); + static_assert(ACTION_TAG_SET_SLOTS == 32768 && + ACTION_DEDUP_STORAGE_BYTES == 139264, + "anchor action indexes must stay bounded at 136 KiB"); + + AnchorObservationBuffer() = default; + AnchorObservationBuffer(const AnchorObservationBuffer &) = delete; + AnchorObservationBuffer &operator=(const AnchorObservationBuffer &) = delete; + + // Takes the sole caller lease; an invalid token (id 0) if a scope already holds it. + AnchorObservationLease tryLease() { + ExclusiveLockGuard guard(&_lock); + if (_lease_id != 0) { + return AnchorObservationLease{}; + } + _lease_id = ++_next_lease_id; + return AnchorObservationLease{_epoch, _lease_id}; + } + + // Releases only the lease the token names; a stale or non-owning token changes nothing. + void releaseLease(const AnchorObservationLease &lease) { + ExclusiveLockGuard guard(&_lock); + if (owns(lease)) { + _lease_id = 0; + } + } + + // Checks room for one record without publishing it; at most one reservation is outstanding. + // A non-owning token, a prior overflow or a nested reservation fails without changing state; + // a full journal also latches the overflow flag. + bool reserve(const AnchorObservationLease &lease) { + ExclusiveLockGuard guard(&_lock); + if (!owns(lease) || _overflow || _reserved) { + return false; + } + if (_count >= CAPACITY) { + _overflow = true; + return false; + } + _reserved = true; + return true; + } + + bool containsAction(const AnchorObservationLease &lease, jlong tag, u8 action) { + ExclusiveLockGuard guard(&_lock); + if (!owns(lease)) { + return false; + } + if (action == AnchorObservation::LOCAL) { + return _local_action_tags.contains(tag, _records); + } + if (action == AnchorObservation::AT_RISK) { + return _at_risk_action_tags.contains(tag, _records); + } + return false; + } + + void commit(const AnchorObservationLease &lease, const AnchorObservation &record) { + ExclusiveLockGuard guard(&_lock); + if (!owns(lease) || !_reserved) { + return; + } + AnchorObservation staged = record; + if ((staged.actions & AnchorObservation::LOCAL) != 0 && + _local_action_tags.contains(staged.tag, _records)) { + staged.actions &= static_cast(~AnchorObservation::LOCAL); + } + if ((staged.actions & AnchorObservation::AT_RISK) != 0 && + _at_risk_action_tags.contains(staged.tag, _records)) { + staged.actions &= static_cast(~AnchorObservation::AT_RISK); + } + if (staged.actions == 0) { + _reserved = false; + return; + } + u16 record_index = static_cast(_count + 1); + _records[_count] = staged; + if ((staged.actions & AnchorObservation::LOCAL) != 0) { + _local_action_tags.insert(staged.tag, record_index); + } + if ((staged.actions & AnchorObservation::AT_RISK) != 0) { + _at_risk_action_tags.insert(staged.tag, record_index); + } + _count++; + _reserved = false; + } + + void cancel(const AnchorObservationLease &lease) { + ExclusiveLockGuard guard(&_lock); + if (owns(lease)) { + _reserved = false; + } + } + + // Latches the overflow outcome; static_attachment also requests one static-scan retry. + // A non-owning token is ignored. + void markOverflow(const AnchorObservationLease &lease, bool static_attachment) { + ExclusiveLockGuard guard(&_lock); + if (!owns(lease)) { + return; + } + _overflow = true; + _static_retry = _static_retry || static_attachment; + } + + // Caller-side publication barrier after a synchronous traversal returned. A non-owning token + // has no journal, so it reports overflow and the caller aborts rather than losing observations. + bool observeOverflow(const AnchorObservationLease &lease) { + ExclusiveLockGuard guard(&_lock); + return !owns(lease) || _overflow; + } + + // Snapshots the accepted prefix; the caller retains the lease until its read finishes. + // Returns false and clears the outputs unless the token still owns the journal. + bool snapshot(const AnchorObservationLease &lease, + const AnchorObservation **records, u32 *count, + bool *static_retry) { + ExclusiveLockGuard guard(&_lock); + *records = nullptr; + *count = 0; + *static_retry = false; + if (!owns(lease)) { + return false; + } + *records = _records; + *count = _count; + *static_retry = _static_retry; + return true; + } + + // Clears the whole journal: the only caller (flush()) has just replayed every record the + // snapshot returned. A no-op for a stale or non-owning token. + void clearPrefix(const AnchorObservationLease &lease) { + ExclusiveLockGuard guard(&_lock); + if (!owns(lease)) { + return; + } + // A reservation is RAII-cancelled at callback return, so none can be outstanding here; a + // commit after this clear would be silently dropped by the !_reserved check. Keeping the + // assignment is the defensive fallback if that discipline is ever broken in a release build. + assert(_reserved == false); + _local_action_tags.clear(); + _at_risk_action_tags.clear(); + _count = 0; + _static_retry = false; + _overflow = false; + _reserved = false; + } + + // Lifecycle disposal; callers guarantee no scope is mid-traversal (engine serialization or a + // joined thread). Invalidates every outstanding lease token. + void reset() { + ExclusiveLockGuard guard(&_lock); + _local_action_tags.clear(); + _at_risk_action_tags.clear(); + _count = 0; + _static_retry = false; + _overflow = false; + _reserved = false; + _lease_id = 0; + _epoch++; + } + + u32 count() { + ExclusiveLockGuard guard(&_lock); + return _count; + } + + u64 epoch() { + ExclusiveLockGuard guard(&_lock); + return _epoch; + } + +private: + class ActionTagSet { + public: + bool contains(jlong tag, const AnchorObservation *records) const { + u32 slot = start(tag); + for (u32 probes = 0; probes < ACTION_TAG_SET_SLOTS; probes++) { + if (!isUsed(slot)) { + return false; + } + u16 record_index = _record_indices[slot]; + if (records[record_index - 1].tag == tag) { + return true; + } + slot = (slot + 1) & (ACTION_TAG_SET_SLOTS - 1); + } + return false; + } + + void insert(jlong tag, u16 record_index) { + assert(_size < CAPACITY); + u32 slot = start(tag); + for (u32 probes = 0; probes < ACTION_TAG_SET_SLOTS; probes++) { + if (!isUsed(slot)) { + _record_indices[slot] = record_index; + _used[slot >> 3] |= static_cast(1u << (slot & 7)); + _size++; + return; + } + slot = (slot + 1) & (ACTION_TAG_SET_SLOTS - 1); + } + assert(false && "anchor action index capacity proof violated"); + } + + void clear() { + if (_size == 0) { + return; + } + memset(_used, 0, sizeof(_used)); + _size = 0; + } + + private: + static u32 start(jlong tag) { + return static_cast(static_cast(tag) * + 0x9E3779B97F4A7C15ULL >> 49); + } + + bool isUsed(u32 slot) const { + return (_used[slot >> 3] & static_cast(1u << (slot & 7))) != 0; + } + + u16 _record_indices[ACTION_TAG_SET_SLOTS]; + u8 _used[ACTION_TAG_SET_BITMAP_BYTES] = {}; + u32 _size = 0; + }; + + // Caller holds _lock. A token owns the journal only for its own lease within its own epoch. + bool owns(const AnchorObservationLease &lease) const { + return lease.id != 0 && lease.id == _lease_id && lease.epoch == _epoch; + } + + SpinLock _lock; + u32 _count = 0; + u64 _epoch = 0; + bool _static_retry = false; + bool _overflow = false; + bool _reserved = false; + u64 _lease_id = 0; // 0 = no lease held + u64 _next_lease_id = 0; // never reused, so a stale token cannot match a newer lease + ActionTagSet _local_action_tags; + ActionTagSet _at_risk_action_tags; + AnchorObservation _records[CAPACITY]; +}; +static_assert(sizeof(AnchorObservation) * AnchorObservationBuffer::CAPACITY <= 393216, + "journal storage must stay <= 384 KiB"); + +// RAII token for one outstanding reservation: commit() publishes, destruction without commit +// abandons it. +class AnchorObservationReservation { +public: + AnchorObservationReservation(AnchorObservationBuffer &buffer, const AnchorObservationLease &lease) + : _buffer(buffer), _lease(lease), _held(buffer.reserve(lease)) {} + ~AnchorObservationReservation() { + if (_held) { + _buffer.cancel(_lease); + } + } + AnchorObservationReservation(const AnchorObservationReservation &) = delete; + AnchorObservationReservation &operator=(const AnchorObservationReservation &) = delete; + + bool held() const { return _held; } + + void commit(const AnchorObservation &record) { + if (_held) { + _buffer.commit(_lease, record); + _held = false; + } + } + +private: + AnchorObservationBuffer &_buffer; + AnchorObservationLease _lease; + bool _held; +}; + +#endif // _REFERENCECHAINOBSERVATION_H diff --git a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp index 711adf1bb1..6c1a34e686 100644 --- a/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainTraversal.cpp @@ -23,6 +23,7 @@ #include #include #include +#include // Manual walk driver - IterateOverReachableObjects root/stack-ref enumeration @@ -68,6 +69,53 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( u32 referrer_klass = ctx->tracker->classTags()->resolve(class_tag); u8 translated_root_kind = translateHeapRootKind(root_kind); + // Reserve before a frontier/tag transition that may publish an anchor effect; known local + // no-ops are filtered first. A full journal aborts with nothing changed so root enumeration retries. + const bool durable_root = isDurableAnchorRootKind(translated_root_kind); + const bool local_root = + isTransientRootKind(translated_root_kind) && class_tag != 0; + bool completed_durable_report = false; + bool weaker_root_noop = false; + if (durable_root && *tag_ptr > 0 && !isLeakTag(*tag_ptr)) { + completed_durable_report = ctx->frontier->rootReportCompleted( + *tag_ptr, translated_root_kind, + /*anchor_indexed=*/ctx->tracker->isAnchorIndexed(*tag_ptr), + ctx->root_report_attempt_id, ctx->root_report_previous_attempt_id, + ctx->root_report_retrying_incomplete, &weaker_root_noop, + /*static_sweep=*/false, ctx->root_report_retry_base_id); + } + // Only reserve LOCAL records replay can absorb; repeated refusals would fill the same prefix and + // starve later roots. + bool durable_observation_complete = false; + bool stage_local = false; + // A locally indexed holder sighted by a durable root edge promotes to the durable share, + // escaping both the root-kind upgrade (which refuses reparented holders) and the report + // dedup - otherwise the holder keeps a local slot and durable capacity forever. + bool stage_promotion = durable_root && *tag_ptr > 0 && !isLeakTag(*tag_ptr) && + !ctx->tracker->isLocalShareEmpty() && + ctx->tracker->isLocalShareIndexed(*tag_ptr); + // Same suppression escape for the 0-to-resolved class-tag refresh: the dedup only stands in + // for restaging, not for the tag upgrade replay's dedup path exists to perform. + bool stage_refresh = + durable_root && !stage_promotion && *tag_ptr > 0 && !isLeakTag(*tag_ptr) && + completed_durable_report && + ctx->tracker->indexedAnchorNeedsClassTagRefresh(*tag_ptr, class_tag); + if (local_root && (*tag_ptr >= 0 || isLeakTag(*tag_ptr)) && + !ctx->anchor_scope.containsAction(*tag_ptr, AnchorObservation::LOCAL)) { + jlong observation_tag = isLeakTag(*tag_ptr) ? 0 : *tag_ptr; + stage_local = + ctx->anchor_scope.reserveLocalStaging(observation_tag, class_tag); + } + AnchorObservationReservationGuard reservation; + if (((durable_root && !completed_durable_report) || stage_local || + stage_promotion || stage_refresh) && + !reservation.acquire(ctx->anchor_scope)) { + ctx->abortForObservationOverflow(/*static_attachment=*/false); + return JVMTI_ITERATION_ABORT; + } + u8 actions = 0; + u8 durable_kind = 0; + jlong record_class_tag = class_tag; AdmitResult result = ctx->tracker->admitObject( ctx->frontier, ctx->hop_cap, ctx->budget, &ctx->edges_admitted, tag_ptr, /*parent_tag=*/0, referrer_klass, /*depth=*/0, translated_root_kind, @@ -80,7 +128,17 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( ctx->truncated = true; ctx->frontier_cap_hit = true; return JVMTI_ITERATION_ABORT; - case AdmitResult::ALREADY_ADMITTED: + case AdmitResult::ADMITTED: + // A fresh durable root's first admission must journal its anchor effect like the + // FollowReferences admission branch does: without it the holder waits for a later + // enumeration to re-report it before it enters the rotation index. + if (durable_root) { + actions |= AnchorObservation::DURABLE_ADD; + durable_kind = translated_root_kind; + durable_observation_complete = true; + } + break; + case AdmitResult::ALREADY_ADMITTED: { if (isLeakTag(*tag_ptr)) { // Leak-tagged object met as a DIRECT heap root (JNI global, stack local, ...): convert the // leak tag exactly like heapReferenceCallback()'s interception branch so a chain can be built @@ -97,12 +155,12 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( ctx->edges_admitted++; ctx->tracker->trackLeakAccumulation(ctx->frontier, class_tag, 0, frontier_tag); - // Index maintenance, mirroring the edge path's interception branch: a leak-tagged root - // attached by a durable root edge is the highest-priority anchor tier. - if (translated_root_kind == (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD || - translated_root_kind == (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { - ctx->tracker->addToStaticAnchorIndex(frontier_tag, class_tag, - translated_root_kind); + // A leak-tagged root attached by a durable root edge is the highest-priority anchor tier. + // Recorded as a journal observation; the caller replays it after JVMTI returns. + if (durable_root) { + actions |= AnchorObservation::DURABLE_ADD; + durable_kind = translated_root_kind; + durable_observation_complete = true; } if (ctx->tracker->_candidate_count > 0) { u32 klass_id = ctx->tracker->classTags()->resolve(class_tag); @@ -124,34 +182,64 @@ jvmtiIterationControl JNICALL ReferenceChainTracker::heapRootCallback( } // Prefer the more durable root when an object is rediscovered and invalidate a cached chain so // its root attribution is rebuilt. + jlong upgraded_class_tag = 0; if (ctx->tracker->maybeUpgradeRootAttachedRootKind( - ctx->frontier, *tag_ptr, translated_root_kind)) { + ctx->frontier, *tag_ptr, translated_root_kind, + &upgraded_class_tag)) { + if (durable_root) { + actions |= AnchorObservation::DURABLE_ADD; + durable_kind = translated_root_kind; + record_class_tag = upgraded_class_tag; + durable_observation_complete = true; + } ctx->tracker->deferResolvedChainInvalidation( *tag_ptr, ctx->resolved_chain_tags, - ctx->resolved_chain_tag_count); + ctx->resolved_chain_tag_count, + ReferenceChainTracker::ChainInvalidationKind::REBUILD); + } else if (translated_root_kind == + (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL) { + // Re-enlist evicted anchors unless this report was accepted in this or the preceding retry. + FrontierEntry current{}; + if (completed_durable_report) { + durable_observation_complete = true; + } else if (ctx->frontier->lookup(*tag_ptr, ¤t) && + ctx->tracker->isSelectableAnchor(current, class_tag)) { + actions |= AnchorObservation::REENLIST_ELIGIBLE; + durable_observation_complete = true; + } } break; + } 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); + if (stage_promotion) { + actions |= AnchorObservation::DURABLE_ADD; + durable_kind = translated_root_kind; + durable_observation_complete = true; + if (record_class_tag == 0) { + record_class_tag = class_tag; } + } else if (stage_refresh) { + actions |= AnchorObservation::REENLIST_ELIGIBLE; + durable_observation_complete = true; + } + // Remember eligible local holders before expansion reparents them into deeper chains. + // Stage only reports accepted by the pre-admission gate and this scope's replay budget. + if (stage_local && *tag_ptr > 0 && !isLeakTag(*tag_ptr)) { + actions |= AnchorObservation::LOCAL; + } + if (actions != 0) { + AnchorObservation record{}; + record.tag = *tag_ptr; + record.own_class_tag = record_class_tag; + record.actions = actions; + record.durable_root_kind = durable_kind; + reservation.commit(record); + } + if (durable_observation_complete && !weaker_root_noop) { + ctx->frontier->markRootReportObserved( + *tag_ptr, translated_root_kind, ctx->root_report_attempt_id); } return JVMTI_ITERATION_CONTINUE; } @@ -166,17 +254,15 @@ 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); - } +u32 ReferenceChainTracker::nextRootReportAttemptId(bool static_sweep) { + // Root and static sweeps share the frontier stamp; this bit keeps their retries distinct. + constexpr u32 source_bit = + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT; + if (_root_report_attempt_sequence == source_bit - 1) { + _root_report_attempt_sequence = 0; } + u32 sequence = ++_root_report_attempt_sequence; + return sequence | (static_sweep ? source_bit : 0); } void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, @@ -226,9 +312,17 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, // oop, only a tag_ptr), so even when it runs this pass, expandFrontier() below is still needed // to make progress. if (run_root_enum) { + preparePendingLocalAnchorEvictionCursor(); jlong resolved_chain_tags[MAX_RESOLVED_CHAINS]; - ReferenceChainPassContext ctx; + // Root-enumeration scope: flushed right after the call returns, before any result handling, + // so every exit below (error, truncation, completion) sees the accepted prefix applied. + ReferenceChainAnchorObservationScope root_scope(this); + ReferenceChainPassContext ctx(root_scope); ctx.tracker = this; + ctx.root_report_retrying_incomplete = _root_enum_incomplete; + ctx.root_report_previous_attempt_id = _last_root_enum_attempt_id; + ctx.root_report_retry_base_id = _root_enum_retry_base_attempt_id; + ctx.root_report_attempt_id = nextRootReportAttemptId(false); ctx.resolved_chain_tags = resolved_chain_tags; ctx.resolved_chain_tag_count = snapshotResolvedChainTags(resolved_chain_tags); ctx.frontier = _frontier; @@ -252,6 +346,13 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, &ctx); u64 root_enum_safepoint_ns = OS::nanotime() - root_enum_start_ns; *safepoint_ns += root_enum_safepoint_ns; + if (root_scope.observeReturn()) { + // A full (or non-owned) journal stops the walk without frontier_cap_hit: the rejected root + // is reported again by the next enumeration. + ctx.anchor_observation_overflow = true; + ctx.truncated = true; + } + root_scope.flush(); // expand_budget is spent independently of root_enum_budget below (see // ROOT_ENUM_MIN_INTERVAL_NS's own comment) - ctx.edges_admitted is written straight into @@ -265,6 +366,10 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, _last_root_enum_safepoint_ms = root_enum_safepoint_ns / 1000000; if (root_err != JVMTI_ERROR_NONE) { + if (!_root_enum_incomplete) { + _root_enum_retry_base_attempt_id = ctx.root_report_attempt_id; + } + _last_root_enum_attempt_id = ctx.root_report_attempt_id; // The enumeration attempt errored out - the root picture is incomplete, so record it: // runPass()'s termination ladder must not treat the search as settled. The consecutive-error // count feeds the ladder's ROOT_ENUM_ERROR abandon; any successful attempt resets it. @@ -276,6 +381,10 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, return; } if (ctx.truncated) { + if (!_root_enum_incomplete) { + _root_enum_retry_base_attempt_id = ctx.root_report_attempt_id; + } + _last_root_enum_attempt_id = ctx.root_report_attempt_id; // A truncated attempt ends this pass - an incomplete enumeration leaves the frontier's root // picture inconsistent with the expansion phases below, so the next pass expands on the // roots already admitted. Retry timing is shouldRunRootEnum()'s (ROOT_ENUM_MIN_INTERVAL_NS). @@ -290,8 +399,11 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, return; } // Completed attempt (no error, no truncation): the root picture is now consistent, so the - // ladder may treat the frontier as the only pending work. + // ladder may treat the frontier as the only pending work. The retry sequence's widened stamp + // window expires with it. _root_enum_incomplete = false; + _last_root_enum_attempt_id = 0; + _root_enum_retry_base_attempt_id = 0; _consecutive_enum_errors = 0; } @@ -332,10 +444,12 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, // IterateOverReachableObjects' root/stack-ref callbacks above - see admitStaticFieldRoots()'s own // comment - so this pass would otherwise never discover an object retained only that way. TEST_LOG_SUMMARY("ReferenceChainTracker::runPassManualWalk static_sweep_gate " - "resolved=%d swept=%d cursor=%d", + "resolved=%d swept=%d cursor=%d unserved=%d", _last_resolved_class_count, _last_static_field_class_count, - _static_field_sweep_cursor); - if (_last_resolved_class_count != _last_static_field_class_count) { + _static_field_sweep_cursor, + (int)(_static_field_sweep_served_gen != _durable_anchor_resweep_gen)); + if (_last_resolved_class_count != _last_static_field_class_count || + _static_field_sweep_served_gen != _durable_anchor_resweep_gen) { int static_field_edges_admitted = 0; bool static_field_truncated = false; bool static_field_frontier_cap_hit = false; @@ -362,8 +476,12 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, // The chunk cursor completed a full lap over the loaded-class list with no chunk truncating // along the way (possibly discovering nothing, if every static field seen was already // ALREADY_ADMITTED) - remember the class count it covered so a later pass with no new classes - // can skip re-running the sweep entirely. + // can skip re-running the sweep entirely, and publish that this lap served every resweep + // request recorded before it started (see the lap-start latch in admitStaticFieldRoots()). + // Requests recorded during the lap stay unserved: this lap does not revisit the classes it + // already passed, so the next lap starting from class 0 serves them. _last_static_field_class_count = _last_resolved_class_count; + _static_field_sweep_served_gen = _static_field_sweep_lap_request_gen; } } @@ -411,13 +529,27 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, // collectStaticFieldAnchorsForRotation()/ walkStaticFieldAnchors()'s own comments) - not pushed // onto the priority lane, so they are independent of the queue tiers above. reconcileAnchorClassShapes(jvmti, jni); - std::vector static_anchor_tags = - collectStaticFieldAnchorsForRotation(STATIC_ANCHOR_ROTATION_BUDGET); + resolvePendingLocalAnchors(); + std::vector static_anchor_tags; + std::vector static_anchor_fresh_picked; + static_anchor_tags = collectStaticFieldAnchorsForRotation( + STATIC_ANCHOR_ROTATION_BUDGET, &static_anchor_fresh_picked); std::vector static_anchor_fifo_drained; drainStaticAnchorFifo(STATIC_ANCHOR_FIFO_DRAIN, static_anchor_fifo_drained); - mergeAtRiskAnchors(static_anchor_tags, static_anchor_fifo_drained); + for (const AtRiskAnchor &at_risk : static_anchor_fifo_drained) { + // A reparented collection can also have been selected by the persistent + // container tier. The combined selection is bounded by 48 + 16 entries. + if (std::find(static_anchor_tags.begin(), static_anchor_tags.end(), + at_risk.tag) == static_anchor_tags.end()) { + static_anchor_tags.push_back(at_risk.tag); + } + } if (rotation_tags.empty() && leak_accumulation_tags.empty() && stale_expanded_tags.empty() && static_anchor_tags.empty()) { + // Fresh-lane picks popped but never selected (the selection budget went to the other tiers) + // keep their queued turns: this return bypasses the walk block's requeue below, so restore + // them here - otherwise they are out of the queue and never walked or spent. + requeueStaticAnchorFreshFront(static_anchor_fresh_picked); return; } // rotation_reserved_budget + max(budget - expand_phase_edges_admitted, 0) is exactly @@ -443,40 +575,101 @@ void ReferenceChainTracker::runPassManualWalk(jvmtiEnv *jvmti, JNIEnv *jni, bool static_anchor_truncated = false; bool static_anchor_frontier_cap_hit = false; std::vector static_anchor_unwalked; - walkStaticFieldAnchors(jvmti, jni, static_anchor_tags, rotation_budget, - &static_anchor_edges_admitted, - &static_anchor_truncated, - &static_anchor_frontier_cap_hit, safepoint_ns, - &static_anchor_unwalked); - rotation_edges_admitted += static_anchor_edges_admitted; - rotation_budget -= static_anchor_edges_admitted; - *truncated = *truncated || static_anchor_truncated; - // Requeue: resolved-but-unwalked anchors that came from this pass's FIFO drain go back to - // the FIFO front, order-preserving, so a pass whose budget died mid-batch walks them first next - // pass instead of waiting for the next sweep lap's re-push. - if (!static_anchor_unwalked.empty() && - !static_anchor_fifo_drained.empty()) { - std::vector static_anchor_requeue; - for (jlong tag : static_anchor_unwalked) { - FrontierEntry entry{}; - if (!_frontier->lookup(tag, &entry)) { - continue; - } + bool static_anchor_observation_overflow = false; + bool static_anchor_cap_hit_return = false; + { + // Selected-anchor scope: spans the walk and the at-risk requeue, and flushes before the + // queue-tier expansion below (replayed at-risk pushes land behind the requeued entries). + ReferenceChainAnchorObservationScope anchor_scope(this); + walkStaticFieldAnchors(jvmti, jni, anchor_scope, static_anchor_tags, + rotation_budget, &static_anchor_edges_admitted, + &static_anchor_truncated, + &static_anchor_frontier_cap_hit, safepoint_ns, + &static_anchor_observation_overflow, + &static_anchor_unwalked); + rotation_edges_admitted += static_anchor_edges_admitted; + rotation_budget -= static_anchor_edges_admitted; + *truncated = *truncated || static_anchor_truncated || + static_anchor_observation_overflow; + // Requeue: resolved-but-unwalked anchors that came from this pass's FIFO drain go back to + // the FIFO front, order-preserving, so a pass whose budget died mid-batch walks them first + // next pass instead of waiting for the next sweep lap's re-push. + if (!static_anchor_unwalked.empty() && + !static_anchor_fifo_drained.empty()) { + std::vector static_anchor_requeue; for (const AtRiskAnchor &at_risk : static_anchor_fifo_drained) { - if (tag == at_risk.tag) { + bool unwalked = false; + for (jlong tag : static_anchor_unwalked) { + if (tag == at_risk.tag) { + unwalked = true; + break; + } + } + FrontierEntry entry{}; + if (unwalked && _frontier->lookup(at_risk.tag, &entry)) { static_anchor_requeue.push_back(at_risk); - break; } } + if (!static_anchor_requeue.empty()) { + requeueStaticAnchorFifoFront(static_anchor_requeue); + } + } + anchor_scope.flush(); + // First looks are consumed by the walk, not the selection: mark the anchors that were + // actually walked (post-flush, so the walk's own replay observes them still pending and + // cannot re-enqueue them mid-walk), and give the fresh picks whose walk never happened + // (budget exhausted before the fresh tier, or mid-walk) their turn back at the queue + // front. Entries spent without a walk (filter-rejected, fresh-room overflow) were marked + // served by the selection itself. + if (!static_anchor_fresh_picked.empty()) { + std::vector fresh_requeue; + for (const FreshAnchor &fresh : static_anchor_fresh_picked) { + bool selected_for_walk = false; + for (jlong tag : static_anchor_tags) { + if (tag == fresh.tag) { + selected_for_walk = true; + break; + } + } + if (!selected_for_walk) { + fresh_requeue.push_back(fresh); + continue; + } + for (jlong tag : static_anchor_unwalked) { + if (tag == fresh.tag) { + fresh_requeue.push_back(fresh); + break; + } + } + } + requeueStaticAnchorFreshFront(fresh_requeue); } - if (!static_anchor_requeue.empty()) { - requeueStaticAnchorFifoFront(static_anchor_requeue); + std::vector walked_served; + walked_served.reserve(static_anchor_tags.size()); + for (jlong tag : static_anchor_tags) { + bool unwalked = false; + for (jlong pending : static_anchor_unwalked) { + if (pending == tag) { + unwalked = true; + break; + } + } + if (!unwalked) { + walked_served.push_back(tag); + } } + _frontier->markAnchorRotationServed(walked_served.data(), + walked_served.size()); + static_anchor_cap_hit_return = static_anchor_frontier_cap_hit; } - if (static_anchor_frontier_cap_hit) { + if (static_anchor_cap_hit_return) { *frontier_cap_hit = true; return; } + } else if (!static_anchor_fresh_picked.empty()) { + // No rotation budget for the anchor walks this pass: no descent happened, so no first look + // was consumed - every fresh pick keeps its queued turn, back at the queue front. + requeueStaticAnchorFreshFront(static_anchor_fresh_picked); } // expandFrontier() SETS (does not add into) its edges output - see its entry - so the anchor // walks' edges are kept in a separate counter and summed here. @@ -523,7 +716,10 @@ void ReferenceChainTracker::expandFrontier(jvmtiEnv *jvmti, JNIEnv *jni, "and must not be made from GarbageCollectionStart/Finish"); jlong resolved_chain_tags[MAX_RESOLVED_CHAINS]; - ReferenceChainPassContext ctx; + // One scope for the whole call; each FollowReferences batch is observed and flushed below + // before its completion/pop/requeue handling and before the next batch. + ReferenceChainAnchorObservationScope scope(this); + ReferenceChainPassContext ctx(scope); ctx.tracker = this; ctx.frontier = _frontier; ctx.hop_cap = hop_cap; @@ -698,6 +894,13 @@ void ReferenceChainTracker::expandFrontier(jvmtiEnv *jvmti, JNIEnv *jni, jvmtiError follow_err = jvmti->FollowReferences(0, nullptr, holder, &callbacks, &ctx); *safepoint_ns += OS::nanotime() - follow_start_ns; + if (scope.observeReturn()) { + // Journal overflow: the rejected edge's referrer is not in completed_batch_tags, so + // the truncated-batch handling below keeps it queued. + ctx.anchor_observation_overflow = true; + ctx.truncated = true; + } + scope.flush(); if (follow_err != JVMTI_ERROR_NONE) { ctx.truncated = true; } @@ -864,8 +1067,23 @@ void ReferenceChainTracker::admitStaticFieldRoots(jvmtiEnv *jvmti, JNIEnv *jni, // than reading out of range. _static_field_sweep_cursor = 0; _static_field_sweep_cycle_truncated = false; + _static_field_retry_chunk_start = -1; + _static_field_retry_attempt_id = 0; } jint chunk_start = _static_field_sweep_cursor; + // A lap starting at class 0 re-traverses the whole loaded-class list, so when it completes it + // will have served every resweep request recorded up to now - latch this lap's request + // generation. Latched, not cleared: a lap whose first chunk truncates (or that is overtaken by + // a mid-lap eviction) must leave the request unserved so the gate keeps running the sweep until + // a lap from class 0 actually completes and publishes the generation (see the completion write + // in runPassManualWalk()). + // A retry of the first chunk keeps the ORIGINAL latch: its retry stamps suppress re-reports of + // holders the failed attempt already accepted, so a request raised between the original latch + // and the retry (an at-cap eviction while replaying the accepted prefix, for one) would be + // consumed without its holder ever being re-indexed. The next fresh lap from class 0 serves it. + if (chunk_start == 0 && _static_field_retry_attempt_id == 0) { + _static_field_sweep_lap_request_gen = _durable_anchor_resweep_gen; + } jint chunk_end = std::min(chunk_start + STATIC_FIELD_SWEEP_CHUNK_CLASSES, class_count); jint chunk_count = chunk_end - chunk_start; @@ -927,7 +1145,10 @@ void ReferenceChainTracker::admitStaticFieldRoots(jvmtiEnv *jvmti, JNIEnv *jni, } jlong resolved_chain_tags[MAX_RESOLVED_CHAINS]; - ReferenceChainPassContext ctx; + // Static-sweep scope: flushed right after FollowReferences, before the follow_err early return + // and before the cursor/lap outcome is reported to the caller. + ReferenceChainAnchorObservationScope scope(this); + ReferenceChainPassContext ctx(scope); ctx.tracker = this; ctx.frontier = _frontier; ctx.hop_cap = hop_cap; @@ -946,6 +1167,13 @@ void ReferenceChainTracker::admitStaticFieldRoots(jvmtiEnv *jvmti, JNIEnv *jni, // ReferenceChainPassContext::static_field_seed's own comment) so this sweep actually reaches each // class's static fields instead of stopping at the negative-tagged class object itself. ctx.static_field_seed = true; + bool retrying_static_chunk = + _static_field_retry_chunk_start == chunk_start && + _static_field_retry_attempt_id != 0; + ctx.root_report_retrying_incomplete = retrying_static_chunk; + ctx.root_report_previous_attempt_id = + retrying_static_chunk ? _static_field_retry_attempt_id : 0; + ctx.root_report_attempt_id = nextRootReportAttemptId(true); // Per-class non-STATIC_FIELD admission cap (see ReferenceChainPassContext::_class_other_cap's own // comment). ctx._class_other_cap = STATIC_FIELD_SWEEP_NON_STATIC_CAP_PER_CLASS; @@ -957,8 +1185,17 @@ void ReferenceChainTracker::admitStaticFieldRoots(jvmtiEnv *jvmti, JNIEnv *jni, jvmtiError follow_err = jvmti->FollowReferences(0, nullptr, holder, &callbacks, &ctx); *safepoint_ns += OS::nanotime() - follow_start_ns; + if (scope.observeReturn()) { + // Overflow takes the truncation path below: chunk_start is kept, the lap is marked truncated + // (no cycle completion) and frontier_cap_hit stays false. + ctx.anchor_observation_overflow = true; + ctx.truncated = true; + } + scope.flush(); jni->DeleteLocalRef(holder); if (follow_err != JVMTI_ERROR_NONE) { + _static_field_retry_chunk_start = chunk_start; + _static_field_retry_attempt_id = ctx.root_report_attempt_id; return; } @@ -968,10 +1205,14 @@ void ReferenceChainTracker::admitStaticFieldRoots(jvmtiEnv *jvmti, JNIEnv *jni, if (ctx.truncated) { _static_field_sweep_cycle_truncated = true; + _static_field_retry_chunk_start = chunk_start; + _static_field_retry_attempt_id = ctx.root_report_attempt_id; // Resumable cursor: instead of skipping to chunk_end (losing every class after the interruption // point for the rest of this lap), redo the chunk on the next pass. _static_field_sweep_cursor = chunk_start; } else { + _static_field_retry_chunk_start = -1; + _static_field_retry_attempt_id = 0; // Full advance: every class in the chunk was processed. _static_field_sweep_cursor = chunk_end; } @@ -1096,8 +1337,10 @@ 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. + // Register the candidates that triggered this search before walking. The + // first pass can drain the frontier; without a watched klass it would then + // complete and release its tags before the loop's post-pass poll can + // reconstruct any chain or schedule candidate-scoped walks. pollWatchedTargets(jvmti, jni); } diff --git a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp index 91b7573d51..bda0c2aa91 100644 --- a/ddprof-lib/src/main/cpp/referenceChainWalk.cpp +++ b/ddprof-lib/src/main/cpp/referenceChainWalk.cpp @@ -141,6 +141,22 @@ void ReferenceChainTracker::resolveLoadedClasses(jvmtiEnv *jvmti, jvmti->Deallocate((unsigned char *)classes); } +namespace { + +AnchorObservation makeAnchorObservation(jlong tag, jlong own_class_tag, + u32 at_risk_klass_id, u8 actions, + u8 durable_root_kind) { + AnchorObservation record{}; + record.tag = tag; + record.own_class_tag = own_class_tag; + record.at_risk_klass_id = at_risk_klass_id; + record.actions = actions; + record.durable_root_kind = durable_root_kind; + return record; +} + +} // namespace + jint JNICALL ReferenceChainTracker::heapReferenceCallback( jvmtiHeapReferenceKind reference_kind, const jvmtiHeapReferenceInfo *reference_info, jlong class_tag, @@ -286,10 +302,18 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( return JVMTI_VISIT_ABORT; } jlong leak_tag = *tag_ptr; + u8 root_kind = parent_tag == 0 ? (u8)reference_kind : 0; + // Reserve before the tag install: a full journal aborts with the leak tag still in place. + const bool durable_leak = isDurableAnchorRootKind(root_kind); + AnchorObservationReservationGuard leak_reservation; + if (durable_leak && !leak_reservation.acquire(ctx->anchor_scope)) { + ctx->abortForObservationOverflow(root_kind == + (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD); + return JVMTI_VISIT_ABORT; + } // Allocate a frontier tag for this object jlong frontier_tag = ctx->tracker->nextTag(); u32 referrer_klass = ctx->tracker->classTags()->resolve(class_tag); - u8 root_kind = parent_tag == 0 ? (u8)reference_kind : 0; if (ctx->frontier->insert(frontier_tag, parent_tag, referrer_klass, depth, FrontierEntryState::FRONTIER, root_kind, class_tag, edge_field_index, @@ -315,14 +339,18 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( (long long)parent_tag); ctx->tracker->trackLeakAccumulation(ctx->frontier, class_tag, parent_tag, frontier_tag); - // Index maintenance: a leak-tagged object admitted root-attached by a durable root edge (e.g. - // a static field directly holding a tagged chunk) is the highest-priority anchor tier - // (leak_tag != 0). - if (parent_tag == 0 && - (root_kind == (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD || - root_kind == (u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL)) { - ctx->tracker->addToStaticAnchorIndex(frontier_tag, class_tag, - root_kind); + // A leak-tagged object admitted root-attached by a durable root edge is the highest-priority + // anchor tier (leak_tag != 0). Recorded as a journal observation; the caller replays the + // index update after JVMTI returns. + if (durable_leak) { + leak_reservation.commit(makeAnchorObservation( + frontier_tag, class_tag, 0, AnchorObservation::DURABLE_ADD, + root_kind)); + if (ctx->static_field_seed) { + ctx->frontier->markRootReportObserved( + frontier_tag, root_kind, ctx->root_report_attempt_id, + /*static_sweep=*/true); + } } // Auto-mark: record this as a discovered instance, with eviction rights over uncorrelated // noise slots (see recordDiscoveredInstance). @@ -375,6 +403,13 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // (parent_tag == 0) - see FrontierEntry::root_kind's own comment for why a non-root entry's // edge kind is not recorded. u8 root_kind = parent_tag == 0 ? (u8)reference_kind : 0; + const bool durable_admission = isDurableAnchorRootKind(root_kind); + AnchorObservationReservationGuard admit_reservation; + if (durable_admission && !admit_reservation.acquire(ctx->anchor_scope)) { + ctx->abortForObservationOverflow(root_kind == + (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD); + return JVMTI_VISIT_ABORT; + } ReferenceChainTracker::AdmitResult result = ctx->tracker->admitObject( ctx->frontier, ctx->hop_cap, ctx->budget, &ctx->edges_admitted, tag_ptr, parent_tag, referrer_klass, depth, root_kind, class_tag, @@ -395,11 +430,17 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // nothing further to do. break; } - // Index maintenance: track root-attached durable anchors for O(anchors) collector iteration - // instead of O(frontier_size) table scan. + // Durable admission is recorded as a journal observation; the caller replays the anchor + // index update after JVMTI returns. if (result == ReferenceChainTracker::AdmitResult::ADMITTED && - parent_tag == 0) { - ctx->tracker->addToStaticAnchorIndex(*tag_ptr, class_tag, root_kind); + durable_admission) { + admit_reservation.commit(makeAnchorObservation( + *tag_ptr, class_tag, 0, AnchorObservation::DURABLE_ADD, root_kind)); + if (ctx->static_field_seed) { + ctx->frontier->markRootReportObserved( + *tag_ptr, root_kind, ctx->root_report_attempt_id, + /*static_sweep=*/true); + } } // Auto-mark: if this object's class matches a watched leak class, record its frontier tag so // pollWatchedTargets() can build a chain event for it. @@ -446,27 +487,41 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // This new path is deeper - replace the shallow root-attached entry with the deeper // chain-attached entry. u32 referrer_klass = ctx->tracker->classTags()->resolve(class_tag); - // Pre-read the CURRENT shape: improveChain() can remove this entry's durable-root - // eligibility; the FIFO push below then gives it a first descend walk. + // Pre-read the CURRENT shape: improveChain() can remove this entry's + // durable-root eligibility. A known collection remains in the container + // tier; other holders need the FIFO's first look below. FrontierEntry pre_improve_entry{}; bool was_root_attached_durable = ctx->frontier->lookup(*tag_ptr, &pre_improve_entry) && pre_improve_entry.parent_tag == 0 && rootKindDurability(pre_improve_entry.root_kind) >= 2; + // Reserve before improveChain(): a successful demotion cannot be undone, so a full journal + // must abort while the entry is still root-attached. + AnchorObservationReservationGuard demotion_reservation; + if (was_root_attached_durable && + !demotion_reservation.acquire(ctx->anchor_scope)) { + ctx->abortForObservationOverflow( + pre_improve_entry.root_kind == + (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD); + return JVMTI_VISIT_ABORT; + } if (ctx->frontier->improveChain(*tag_ptr, parent_tag, referrer_klass, depth, 0, edge_field_index, (u8)reference_kind)) { - // Chain was improved — invalidate any cached chain for this tag so pollWatchedTargets - // rebuilds it with the deeper path. + // Chain was improved — queue a REBUILD so pollWatchedTargets replaces any cached chain for + // this tag with the deeper path (never erased: the source is still live). // Deferred: we're inside the FollowReferences pause (see deferResolvedChainInvalidation()). ctx->tracker->deferResolvedChainInvalidation( *tag_ptr, ctx->resolved_chain_tags, - ctx->resolved_chain_tag_count); + ctx->resolved_chain_tag_count, + ReferenceChainTracker::ChainInvalidationKind::REBUILD); if (was_root_attached_durable) { // 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)); + demotion_reservation.commit(makeAnchorObservation( + *tag_ptr, class_tag, + ctx->tracker->classTags()->resolve(class_tag), + AnchorObservation::AT_RISK, 0)); } } else if (ctx->frontier->reparentToDurableRoot( *tag_ptr, parent_tag, referrer_klass, edge_field_index, @@ -476,31 +531,90 @@ jint JNICALL ReferenceChainTracker::heapReferenceCallback( // durable root. ctx->tracker->deferResolvedChainInvalidation( *tag_ptr, ctx->resolved_chain_tags, - ctx->resolved_chain_tag_count); + ctx->resolved_chain_tag_count, + ReferenceChainTracker::ChainInvalidationKind::REBUILD); } } else { // Already-admitted entry reached via a NEW root-like edge (parent_tag == 0): the static-field // sweep's class -> field edge reports the class as the referrer with a negative tag, which // the rtag < 0 branch above treats as root-like (class objects are never frontier entries), // and heap-root references arrive here with referrer_tag_ptr == nullptr. - if (ctx->tracker->maybeUpgradeRootAttachedRootKind(ctx->frontier, - *tag_ptr, - (u8)reference_kind)) { + const bool durable_edge = + isDurableAnchorRootKind((u8)reference_kind); + u8 pending_actions = 0; + u32 pending_at_risk_klass_id = 0; + bool durable_report_complete = false; + AnchorObservationReservationGuard root_reservation; + if (durable_edge) { + FrontierEntry current{}; + bool found = ctx->frontier->lookup(*tag_ptr, ¤t); + bool upgrade_possible = + found && current.parent_tag == 0 && + rootKindDurability((u8)reference_kind) > + rootKindDurability(current.root_kind); + if (ctx->static_field_seed && found && + reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) { + durable_report_complete = ctx->frontier->rootReportCompleted( + *tag_ptr, (u8)reference_kind, /*anchor_indexed=*/false, + ctx->root_report_attempt_id, + ctx->root_report_previous_attempt_id, + ctx->root_report_retrying_incomplete, + /*weaker_root_noop=*/nullptr, /*static_sweep=*/true); + } + if (!durable_report_complete) { + // Recorded for indexed tags too: the replay's dedup turns it into the 0 -> resolved + // own-class-tag upgrade (main's repeated-sighting refresh), and into a plain no-op + // once the stored tag is resolved. + if (found && ctx->tracker->isSelectableAnchor(current, class_tag)) { + pending_actions |= AnchorObservation::REENLIST_ELIGIBLE; + } + if (reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD && found && + current.parent_tag != 0) { + pending_at_risk_klass_id = + ctx->tracker->classTags()->resolve(class_tag); + if (ctx->anchor_scope.reserveAtRiskStaging( + *tag_ptr, pending_at_risk_klass_id)) { + pending_actions |= AnchorObservation::AT_RISK; + } + } + } + if ((upgrade_possible || pending_actions != 0) && + !root_reservation.acquire(ctx->anchor_scope)) { + ctx->abortForObservationOverflow( + reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD); + return JVMTI_VISIT_ABORT; + } + } + jlong upgraded_class_tag = 0; + if (ctx->tracker->maybeUpgradeRootAttachedRootKind( + ctx->frontier, *tag_ptr, (u8)reference_kind, + &upgraded_class_tag)) { + if (durable_edge) { + root_reservation.commit(makeAnchorObservation( + *tag_ptr, upgraded_class_tag, 0, AnchorObservation::DURABLE_ADD, + (u8)reference_kind)); + durable_report_complete = true; + } ctx->tracker->deferResolvedChainInvalidation( *tag_ptr, ctx->resolved_chain_tags, - ctx->resolved_chain_tag_count); - } else if (reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) { - // 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)); - } + ctx->resolved_chain_tag_count, + ReferenceChainTracker::ChainInvalidationKind::REBUILD); + } else if (pending_actions != 0) { + // No upgrade: an unchanged durable root never upgrades, so this edge is a static-only + // holder's only re-indexing path (via the static sweep) and a non-root holder's at-risk witness. + root_reservation.commit(makeAnchorObservation( + *tag_ptr, class_tag, + (pending_actions & AnchorObservation::AT_RISK) + ? pending_at_risk_klass_id + : 0, + pending_actions, 0)); + durable_report_complete = true; + } + if (ctx->static_field_seed && durable_report_complete && + reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) { + ctx->frontier->markRootReportObserved( + *tag_ptr, (u8)reference_kind, ctx->root_report_attempt_id, + /*static_sweep=*/true); } } } @@ -716,7 +830,8 @@ void ReferenceChainTracker::seedLeakAccumulationForNewlyWatchedKlass( } bool ReferenceChainTracker::maybeUpgradeRootAttachedRootKind( - FrontierTable *frontier, jlong tag, u8 new_root_kind) { + FrontierTable *frontier, jlong tag, u8 new_root_kind, + jlong *upgraded_class_tag) { FrontierEntry entry{}; if (!frontier->lookup(tag, &entry)) { return false; @@ -732,7 +847,9 @@ bool ReferenceChainTracker::maybeUpgradeRootAttachedRootKind( return false; } frontier->updateRootKind(tag, new_root_kind); - addToStaticAnchorIndex(tag, entry.class_tag, new_root_kind); + if (upgraded_class_tag != nullptr) { + *upgraded_class_tag = entry.class_tag; + } return true; } diff --git a/ddprof-lib/src/main/cpp/referenceChains.cpp b/ddprof-lib/src/main/cpp/referenceChains.cpp index 0208341393..2d33d8eef3 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.cpp +++ b/ddprof-lib/src/main/cpp/referenceChains.cpp @@ -238,6 +238,12 @@ void ReferenceChainTracker::autoTuneDefaults(Arguments &args) { } Error ReferenceChainTracker::start(Arguments &args) { + // An unjoined BFS thread may still hold an observation scope; resetting under it would replay + // observations against reused tags. + // Gated regardless of the requested option so no start path touches state a live worker owns. + if (!_thread_joined) { + return Error("previous reference chain BFS thread was not joined"); + } storeRelease(_enabled, args._reference_chains); if (!args._reference_chains) { @@ -264,6 +270,8 @@ Error ReferenceChainTracker::start(Arguments &args) { _thread_objects_open = true; } _urgency_budget_boosted = false; + // The BFS thread is joined (checked on entry) and startThread() runs later, so no scope is live. + _anchor_observations.reset(); // Auto-tune defaults that the operator did not set explicitly, based on max heap size and // available processors. @@ -379,6 +387,11 @@ void ReferenceChainTracker::stop() { if (!enabled()) { return; } + if (!_thread_joined) { + // Reset only after a confirmed join; a straggler could still hold a scope. + Log::warn("Reference chain BFS thread not joined; recording-boundary reset skipped"); + return; + } Log::info("Reference chain tracking stopped"); // Recording-boundary search teardown: stopThread() has already joined the BFS thread, so no @@ -441,6 +454,8 @@ void ReferenceChainTracker::stop() { ExclusiveLockGuard guard(&_pending_abandoned_events_lock); _pending_abandoned_events.clear(); } + // The BFS thread is joined (checked on entry), so no scope is live; the epoch bump keeps any stale token from replaying against the reused tags. + _anchor_observations.reset(); // Do not disable GC notifications here - LivenessTracker follows the same rule: the JVMTI env // and its tracker singletons outlive start/stop recording cycles, even though LivenessTracker @@ -451,6 +466,10 @@ void ReferenceChainTracker::startThread() { if (!enabled() || _running.load(std::memory_order_acquire)) { return; } + if (!_thread_joined) { + Log::warn("Previous ReferenceChains BFS thread was not joined; not starting a new one"); + return; + } // Reset from any previous stopThread() call - a dynamic-attach profiler can go through multiple // start()/stop() cycles in one JVM lifetime (this class's own start()/stop() header comments), // and a stale abort request left set from the prior cycle would make heapReferenceCallback() @@ -466,27 +485,35 @@ void ReferenceChainTracker::startThread() { return; } _thread = thread; + _thread_joined = false; } -void ReferenceChainTracker::stopThread() { - if (!_running.load(std::memory_order_acquire)) { - return; +bool ReferenceChainTracker::stopThread() { + if (_thread_joined) { + return true; } + // A retry after a failed join finds _running already false but the thread still unjoined. + bool was_running = _running.load(std::memory_order_acquire); _running.store(false, std::memory_order_release); - // Ask any in-flight JVMTI FollowReferences walk (heapReferenceCallback()) to abort at its next - // callback invocation - set before pthread_kill() below, since that signal alone cannot interrupt - // a call already inside the JVM/JVMTI implementation. - _abort_pass_requested.store(true, std::memory_order_relaxed); - // Same wake-then-join shape as BaseWallClock::stop() (wallClock.cpp:324-333): - // pthread_kill(WAKEUP_SIGNAL) interrupts threadLoop()'s OS::sleep() early (WAKEUP_SIGNAL/SIGIO is - // installed with a no-op handler unconditionally in vmEntry.cpp, so this signal never terminates - // the thread) so it re-checks _running and exits promptly rather than waiting out the rest of the - // current sleep interval. - pthread_kill(_thread, WAKEUP_SIGNAL); - int res = pthread_join(_thread, NULL); + if (was_running) { + // Set before pthread_kill(): the signal alone cannot interrupt a call already inside JVMTI. + _abort_pass_requested.store(true, std::memory_order_relaxed); + // WAKEUP_SIGNAL has a no-op handler (vmEntry.cpp); it cuts threadLoop()'s sleep short. + pthread_kill(_thread, WAKEUP_SIGNAL); + } + int res; +#ifdef DEBUG + res = _join_thread_for_test != nullptr ? _join_thread_for_test(_thread, NULL) + : pthread_join(_thread, NULL); +#else + res = pthread_join(_thread, NULL); +#endif if (res != 0) { Log::warn("Unable to join ReferenceChains BFS thread on stop %d", res); + return false; } + _thread_joined = true; + return true; } // threadLoop()'s per-iteration OOM ramp: pause target, cadence and the urgency budget @@ -1071,6 +1098,8 @@ void ReferenceChainTracker::restartSearch() { _frontier->resetForRestart(); } clearPendingChainInvalidations(); + // Runs under _engine_lock on the BFS thread between passes, so every pass scope has flushed. + _anchor_observations.reset(); _next_tag = 1; // Hop-edge label cache: keyed by raw class tags, which survive a restart (the shared class-tag // allocator is deliberately not reset - see this method's own declaration comment) - but the @@ -1091,7 +1120,19 @@ 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(); + _indexed_zero_class_tag_count = 0; + _local_anchor_tags.clear(); + _pending_local_anchors.clear(); + _pending_local_anchor_tags.clear(); + _local_compact_backoff = 0; + _pending_local_evict_cursor = 0; + _pending_local_evictable_count = 0; + _durable_anchor_resweep_gen = 0; + _static_field_sweep_lap_request_gen = 0; + _static_field_sweep_served_gen = 0; _anchor_container_cursor = 0; _anchor_other_cursor = 0; // Fresh lane: nothing admits before the search does, so nothing can have a pending first look @@ -1110,6 +1151,11 @@ void ReferenceChainTracker::restartSearch() { _leak_tags_assigned = 0; _leak_tags_resolved = 0; _root_enum_incomplete = false; + _last_root_enum_attempt_id = 0; + _root_enum_retry_base_attempt_id = 0; + _root_report_attempt_sequence = 0; + _static_field_retry_chunk_start = -1; + _static_field_retry_attempt_id = 0; _consecutive_enum_errors = 0; store(_last_pass_ns, (u64)0); store(_passes_run, 0); @@ -1131,7 +1177,9 @@ void ReferenceChainTracker::resetSearchStateForTest(jvmtiEnv *jvmti, // flight on that thread can observe this reset only partially, or overwrite it right back (e.g. // finish a pass that was already headed for SearchState::ABANDONED after this method has just // forced SearchState::RUNNING below), a race found in practice, not just in theory. - stopThread(); + if (!stopThread()) { + return; // a live BFS thread may still reach the state below + } // Clear every live tag this search still holds before resetting - the same ordering // restartSearch() itself requires (its own assert), so a stale tag from whatever search a @@ -1163,6 +1211,8 @@ void ReferenceChainTracker::resetSearchStateForTest(jvmtiEnv *jvmti, // resetForRestart() since it never needs to change the cap mid-JVM. _frontier->resetCapacityForTest(_configured_frontier_cap); } + // stopThread() above joined the BFS thread, so no scope holds the journal. + _anchor_observations.reset(); _next_tag = 1; _search_started = false; @@ -1176,7 +1226,19 @@ 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(); + _indexed_zero_class_tag_count = 0; + _local_anchor_tags.clear(); + _pending_local_anchors.clear(); + _pending_local_anchor_tags.clear(); + _local_compact_backoff = 0; + _pending_local_evict_cursor = 0; + _pending_local_evictable_count = 0; + _durable_anchor_resweep_gen = 0; + _static_field_sweep_lap_request_gen = 0; + _static_field_sweep_served_gen = 0; _anchor_container_cursor = 0; _anchor_other_cursor = 0; _static_anchor_fresh_queue.clear(); @@ -1219,6 +1281,11 @@ void ReferenceChainTracker::resetSearchStateForTest(jvmtiEnv *jvmti, _last_root_enum_ns = 0; _last_root_enum_safepoint_ms = 0; _root_enum_incomplete = false; + _last_root_enum_attempt_id = 0; + _root_enum_retry_base_attempt_id = 0; + _root_report_attempt_sequence = 0; + _static_field_retry_chunk_start = -1; + _static_field_retry_attempt_id = 0; _consecutive_enum_errors = 0; _static_field_sweep_cycle_truncated = false; _candidate_count = 0; diff --git a/ddprof-lib/src/main/cpp/referenceChains.h b/ddprof-lib/src/main/cpp/referenceChains.h index f0ae180179..75d02e3a8b 100644 --- a/ddprof-lib/src/main/cpp/referenceChains.h +++ b/ddprof-lib/src/main/cpp/referenceChains.h @@ -30,6 +30,9 @@ #include "referenceChainFrontier.h" #include "referenceChainBatchSet.h" +#include "referenceChainObservation.h" + +class ReferenceChainAnchorObservationScope; // Incremental reference-chain search driven by a dedicated JVMTI agent thread. class ReferenceChainTracker { @@ -38,6 +41,7 @@ class ReferenceChainTracker { // (_search_state/_search_started/etc.) would otherwise leak across separate TEST_F cases in the // same gtest binary. friend class ReferenceChainsTestAccessor; + friend class ReferenceChainAnchorObservationScope; private: // Written by start() on the control thread, read by the GC callbacks and other threads via @@ -92,6 +96,8 @@ class ReferenceChainTracker { // single FollowReferences over every loaded class at once (no cursor) could never finish within // one pass's safepoint deadline on a JVM with tens of thousands of loaded classes. int _static_field_sweep_cursor; + int _static_field_retry_chunk_start = -1; + u32 _static_field_retry_attempt_id = 0; // Set when any chunk within the current lap (the cursor's walk from 0 back to 0) truncates. bool _static_field_sweep_cycle_truncated; @@ -489,8 +495,8 @@ class ReferenceChainTracker { } } _priority_expand_set; - // 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). + // Chain-attached holders without a known collection shape need a first + // descend walk when a static edge or reparenting removes their root eligibility. struct AtRiskAnchor { jlong tag; u32 klass_id; @@ -510,18 +516,104 @@ class ReferenceChainTracker { std::unordered_map _static_anchor_fifo_klass_counts; static constexpr u32 STATIC_ANCHOR_ATRISK_PER_KLASS_CAP = 64; - // Index durable roots and local roots with unknown or container-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. + // Index of durable roots and CONFIRMED-container local holders. Known collections remain + // eligible after reparenting, so replacing their storage is still observed. A stack/JNI-local + // root is indexed only once its class is classified as a collection/map (see + // noteLocalRootHolder()/resolvePendingLocalAnchors()); non-collection local holders are never + // indexed. Both shares are capped: the local share at LOCAL_ANCHOR_INDEX_CAP (compacted by + // compactLocalAnchors()), the durable share at DURABLE_ANCHOR_INDEX_CAP (FIFO-evicted by + // evictOldestDurableAnchors(); a still-live evicted anchor is re-reported and re-admitted by + // the next root enumeration, a dead one never is). The caps bound + // collectStaticFieldAnchorsForRotation()'s per-pass scan, which iterates these anchors rather + // than scanning the full frontier table, to LOCAL_ANCHOR_INDEX_CAP + DURABLE_ANCHOR_INDEX_CAP + // entries under the shared frontier lock. std::vector _static_anchor_index; - // 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. + // Parallel to _static_anchor_index: the runtime class tag of each indexed holder. + std::vector _static_anchor_own_class_tags; + + // O(1) tag-keyed view of the index: the holder's runtime class tag and its position in + // _static_anchor_index. The class tag is authoritative here: a root first reported before its + // class was tagged stores 0, and the STATIC_FIELD edge that later delivers the resolved tag + // upgrades it in place (a stored 0 would leave the reparented holder outside the + // container-shape fallback forever). Positions are rebuilt by eraseAnchorEntries()'s + // stable compaction, which already walks the full index. struct StaticAnchorIndexEntry { jlong class_tag; - bool transient_root; + size_t pos; }; std::unordered_map _static_anchor_index_class_tags; + // How many indexed entries still carry the admission-time class tag 0. The callback's + // 0-to-resolved refresh gate consults this count first, so a fully resolved index costs the + // per-report gate nothing (the enumeration callback is safepoint-bound). + size_t _indexed_zero_class_tag_count = 0; + + // Dedup companion for _static_anchor_index (O(1) membership). + std::unordered_set _static_anchor_index_tags; + + // Subset of _static_anchor_index_tags that were indexed as stack/JNI-local holders (not as + // durable roots). Its size is the local share of the index, capped at LOCAL_ANCHOR_INDEX_CAP so + // per-pass anchor selection stays O(durable anchors + cap) no matter how many locals the + // application holds. A tag later indexed as a durable root leaves this map (uncapped share). + // Maps each local holder tag to its own runtime class tag at admission time, so + // compactLocalAnchors() can evaluate isSelectableAnchor() by iterating only the local share + // (O(cap)) instead of scanning the whole, uncapped index. + std::unordered_map _local_anchor_tags; + static constexpr size_t LOCAL_ANCHOR_INDEX_CAP = 4096; + // Durable-share cap (STATIC_FIELD / JNI_GLOBAL holders). A live evicted anchor is re-enlisted + // when a traversal re-reports its durable edge: the captured REENLIST_ELIGIBLE observation is + // replayed to indexAnchorForRotation() - JNI_GLOBAL + // roots every root enumeration; for static-only holders eviction also invalidates the sweep + // memo so the next pass re-traverses their class -> field edges. A dead evicted anchor is never + // reported again. Index mutation runs in replay after the JVMTI call returns, not in callbacks. + static constexpr size_t DURABLE_ANCHOR_INDEX_CAP = 8192; + // Eviction removes enough oldest entries to drop the share to cap - DURABLE_ANCHOR_EVICT_BATCH, + // so one O(index) compaction is amortized over ~DURABLE_ANCHOR_EVICT_BATCH admissions. + static constexpr size_t DURABLE_ANCHOR_EVICT_BATCH = 1024; + // Resweep requests as a generation counter: every eviction batch bumps + // _durable_anchor_resweep_gen, and a sweep lap serves exactly the generations requested before + // the lap started - a fresh lap (cursor 0) latches _static_field_sweep_lap_request_gen, and its + // completion publishes it as _static_field_sweep_served_gen. The gate runs the sweep while + // served != requested, so a request survives: laps in flight when the eviction lands (which do + // not revisit classes they already passed) and first chunks that truncate both leave the + // generation unserved until a full lap from class 0 completes. Latching at lap start (not + // clearing at start or completion) is what makes a completion serve only the requests that + // predate the lap. Eviction never restarts the cursor: a restart under sustained above-cap + // churn would reset a mid-lap cursor and starve later classes. + u64 _durable_anchor_resweep_gen = 0; + u64 _static_field_sweep_lap_request_gen = 0; + u64 _static_field_sweep_served_gen = 0; + // Small compactions scan both shares to reclaim few slots; skip 8 at-cap attempts after + // reclaiming less than one eighth of the local cap. New holders are re-reported meanwhile. + static constexpr int LOCAL_ANCHOR_COMPACT_BACKOFF = 8; + static constexpr size_t LOCAL_ANCHOR_COMPACT_MIN_RECLAIM = + LOCAL_ANCHOR_INDEX_CAP / LOCAL_ANCHOR_COMPACT_BACKOFF; + // Remaining at-cap attempts to skip after a low-yield compaction. + int _local_compact_backoff = 0; + + // Local-root holders whose class was not yet classified when root enumeration reported them + // (classification needs JNI, which the heap-root callback cannot use). Drained - indexed if + // confirmed containers, dropped otherwise - by resolvePendingLocalAnchors() after every + // reconcileAnchorClassShapes(); an entry whose class is still unclassified is dropped too and + // re-reported by the next root enumeration. Capped so a burst of locals cannot grow it. When the + // buffer is full, a confirmed container met at the local cap evicts the oldest entry not + // confirmed as a container (that entry is re-reported by the next root enumeration); an + // unclassified holder met at a full buffer, or a container met at a buffer holding only + // confirmed containers, is dropped and re-reported. + struct PendingLocalAnchor { + jlong tag; + jlong class_tag; + }; + std::vector _pending_local_anchors; + std::unordered_set _pending_local_anchor_tags; + static constexpr size_t PENDING_LOCAL_ANCHOR_CAP = 1024; + // noteLocalRootHolder() eviction cursor (forward-only): every _pending_local_anchors slot below it + // holds a confirmed container. Reset together with the buffer. + size_t _pending_local_evict_cursor = 0; + // Counts entries not confirmed as containers; each can be displaced by a confirmed container. + // Keep the count in sync with pending-buffer insertions, replacements and clears. + // Scope budgets use it to cap LOCAL records at replayable capacity. + size_t _pending_local_evictable_count = 0; // Shape of a class as an anchor candidate: does the class implement java/util/Collection or // java/util/Map (directly or via superclasses/interfaces)? UNKNOWN_TRUNCATED preserves a bounded @@ -549,13 +641,16 @@ class ReferenceChainTracker { size_t _anchor_container_cursor = 0; size_t _anchor_other_cursor = 0; - // FIFO of newly admitted anchors awaiting their first walk. - std::deque _static_anchor_fresh_queue; + struct FreshAnchor { + jlong tag; + jlong own_class_tag; + }; + // FIFO of anchors awaiting their first rotation turn; durable eviction keeps those turns alive. + // The class tag is the callback-time snapshot used to select each queued turn. + std::deque _static_anchor_fresh_queue; - // Cap for _static_anchor_fresh_queue. The queue normally holds only ~one pass of sweep admits - // (admits happen in passes, the collector drains every pass, and the drain DROPS everything it - // does not keep, so the queue empties each call); the cap only guards a pathological burst (e.g. - // a pass admitting thousands) from growing it unbounded in native memory. + // Overflow drops newest turns, which remain eligible for the fair index tiers. + // A served turn stays served after reindexing, preventing repeated fresh-lane priority. static constexpr size_t STATIC_ANCHOR_FRESH_CAP = 1024; // java/lang/Object jclass cache for expandFrontier()'s and admitStaticFieldRoots()'s holder-array @@ -613,6 +708,12 @@ class ReferenceChainTracker { // walkCandidateThreadLocals()'s THREAD_WALK_MAX_ANCHORS-per-pass cap rotates fairly instead of // always walking the same first candidates' tids. int _thread_walk_anchor_cursor; + // Consecutive FollowReferences failures at the retained cursor. A persistent JVMTI failure + // (wrong phase, sustained OOM) must not re-anchor the cursor on the same anchor every pass: + // after THREAD_WALK_FAILURE_SKIP consecutive failures the cursor advances past it and the + // wrap retries it on a later cycle. + int _thread_walk_consecutive_failures; + static constexpr int THREAD_WALK_FAILURE_SKIP = 3; // Per-pass cap on how many EXPANDED entries collectLeakAccumulationCandidatesForRotation() // re-queues - see that method's own comment. @@ -642,20 +743,30 @@ class ReferenceChainTracker { std::unordered_map _resolved_chains; SpinLock _resolved_chains_lock; - // Chain evictions deferred by heap callbacks. Only tags present in the immutable pre-traversal - // resolved-cache snapshot are eligible, so distinct pending tags are bounded exactly by the - // cache cap. Both buffers are reserved up front: drains swap the active producer buffer into the - // scratch buffer under the pending lock, then erase cache entries after releasing that lock. + // Chain invalidations deferred by heap callbacks. Both buffers are reserved up front; if the + // snapshot bound is violated, the next drain clears the cache rather than retaining stale chains. + // The ChainInvalidationKind is stored in-band (see encodePendingChainInvalidation()): EVICT + // entries hold the source tag, REBUILD entries its bitwise complement. Every read and write of + // both buffers and the overflow flag happens under _pending_chain_invalidations_lock. static constexpr int MAX_PENDING_CHAIN_INVALIDATIONS = MAX_RESOLVED_CHAINS; std::vector _pending_chain_invalidations; std::vector _draining_chain_invalidations; + bool _pending_chain_invalidation_overflow = false; SpinLock _pending_chain_invalidations_lock; +#ifdef DEBUG + // Test hook for evicting a scanned chain before write-back; absent from release builds. + void (*_between_invalidation_scan_and_writeback_for_test)() = nullptr; +#endif // Abandoned-search events awaiting Profiler::dump() (profiler.cpp). static constexpr int MAX_PENDING_ABANDONED_EVENTS = 16; std::vector _pending_abandoned_events; SpinLock _pending_abandoned_events_lock; + // Callback-recorded anchor effects, replayed by the owning traversal caller after the JVMTI call + // returns. Search-owned: reset only at quiescent lifecycle boundaries, never against live scopes. + AnchorObservationBuffer _anchor_observations; + // leaky bucket over the wall-clock cost of past searches, gating how soon a *restarted* search // may take its first pass - see PainBudget's own comment (painBudget.h) and canAffordNewSearch() // below. @@ -770,6 +881,14 @@ class ReferenceChainTracker { // become visible to threadLoop() late, missing the shutdown request on one wakeup and looping an // extra cycle before pthread_join() unblocks it. std::atomic _running; + // False from startThread() until stopThread() has joined the BFS thread; true when no thread + // exists or it was joined. A failed join leaves it false so callers do not tear down state the + // thread may still reach. + bool _thread_joined = true; +#ifdef DEBUG + // Test hook replacing pthread_join() in stopThread() to inject a join failure; absent from release builds. + int (*_join_thread_for_test)(pthread_t, void**) = nullptr; +#endif // Cooperative-cancellation flag for an in-flight JVMTI FollowReferences walk: stopThread() sets // this before pthread_kill()/pthread_join() (that signal alone cannot interrupt a call already @@ -795,6 +914,15 @@ class ReferenceChainTracker { // may still hold reachable chains. Cleared on a completed attempt, by restartSearch(), and by // resetSearchStateForTest(); runPass()'s termination ladder treats it as pending frontier. bool _root_enum_incomplete = false; + // The last incomplete root attempt and the shared source-qualified report-attempt sequence. + u32 _last_root_enum_attempt_id = 0; + u32 _root_report_attempt_sequence = 0; + // The FIRST attempt of the current incomplete root-enumeration retry sequence (0 when no + // sequence is open). An ongoing sequence widens the recognized-stamp window in + // rootReportCompleted() to every attempt of the sequence, so alternating oversized groups + // cannot ping-pong each other out of the durable index; it expires when an attempt completes. + // BFS-thread-only, like the fields above. + u32 _root_enum_retry_base_attempt_id = 0; // Consecutive root-enumeration attempts ended by a JVMTI error; reset by any successful // attempt, restartSearch(), and resetSearchStateForTest(). At MAX_CONSECUTIVE_ENUM_ERRORS the @@ -836,6 +964,7 @@ class ReferenceChainTracker { _root_kind_rotation_cursor(1), _stale_expanded_rotation_cursor(1), _thread_walk_anchor_cursor(0), + _thread_walk_consecutive_failures(0), _safepoint_pain_budget(0.0), _search_pain_ms(0), _cpu_pain_budget(0.0), _thread(), _running(false), _abort_pass_requested(false) { _pending_chain_invalidations.reserve(MAX_PENDING_CHAIN_INVALIDATIONS); @@ -1036,8 +1165,17 @@ class ReferenceChainTracker { void seedLeakAccumulationForNewlyWatchedKlass(u32 klass_id); // Upgrades root_kind when a rediscovered heap root is more durable; testable without a JVMTI mock. + // On success `upgraded_class_tag` (when non-null) receives the entry's class tag; it never + // touches the anchor index. bool maybeUpgradeRootAttachedRootKind(FrontierTable *frontier, jlong tag, - u8 new_root_kind); + u8 new_root_kind, + jlong *upgraded_class_tag = nullptr); + + // Applies the first `count` journal records in arrival order, then adds one static-resweep + // request if `static_retry`. Runs only from ReferenceChainAnchorObservationScope::flush(), never + // from a heap callback. + void replayAnchorObservations(const AnchorObservation *records, u32 count, + bool static_retry); // True if `tag` is already sitting in _priority_expand - either queued earlier this same pass by // the other rotation collector, or left over from a prior pass's truncated batch @@ -1062,11 +1200,16 @@ class ReferenceChainTracker { int max_count); // CANDIDATE-SCOPED REACH: bounded descend walk from an anchor object. - void descendFromAnchor(jvmtiEnv *jvmti, JNIEnv *jni, jobject anchor, - jlong anchor_tag, u32 anchor_depth, - jlong anchor_descend_class_tag, int budget, - int *edges_admitted, bool *truncated, - bool *frontier_cap_hit, u64 *safepoint_ns); + // Borrows `scope` (owned and flushed by the caller); `*anchor_observation_overflow` reports a + // full journal. Returns the FollowReferences() error code: a failed descent must not be + // reported as walked, or the caller marks a first look served without any walk. + jvmtiError descendFromAnchor(jvmtiEnv *jvmti, JNIEnv *jni, + ReferenceChainAnchorObservationScope &scope, + jobject anchor, jlong anchor_tag, u32 anchor_depth, + jlong anchor_descend_class_tag, int budget, + int *edges_admitted, bool *truncated, + bool *frontier_cap_hit, u64 *safepoint_ns, + bool *anchor_observation_overflow); // Candidate-scoped reach for thread-retained leaks (ThreadLocal-held caches and thread-owned // collections): per pass, walk up to THREAD_WALK_MAX_ANCHORS of the current @@ -1078,20 +1221,90 @@ class ReferenceChainTracker { // 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); + // When non-null, `fresh_picked` receives every fresh-lane pick (tag + own_class_tag) this + // call selected - the caller requeues the picks the walk did not consume back to the fresh + // queue's front, since selection no longer marks a picked anchor served. + std::vector collectStaticFieldAnchorsForRotation( + int max_count, std::vector *fresh_picked = nullptr); bool isSelectableAnchor(const FrontierEntry &entry, jlong own_class_tag) const; + // Callback and replay are serialized on the BFS thread, so callback-time reads see prior flushes. + bool isAnchorIndexed(jlong tag) const { + return _static_anchor_index_tags.count(tag) > 0; + } + // True when an indexed anchor still carries the admission-time class tag 0 and this report + // carries its resolved tag: the stamp dedup suppresses the repeated sighting, so the caller + // must journal the re-enlist for replay's 0-to-resolved upgrade to run. The zero-tag count + // gate makes this a no-op for a fully resolved index. + bool indexedAnchorNeedsClassTagRefresh(jlong tag, jlong class_tag) const { + if (class_tag == 0 || _indexed_zero_class_tag_count == 0) { + return false; + } + auto known = _static_anchor_index_class_tags.find(tag); + return known != _static_anchor_index_class_tags.end() && + known->second.class_tag == 0; + } + // True when the tag sits in the capped local share (a subset of the durable index). + bool isLocalShareIndexed(jlong tag) const { + return _local_anchor_tags.count(tag) > 0; + } + // Fast path for the callback's promotion gate: most recordings never index a local holder, + // and the gate runs per durable root edge inside the JVMTI enumeration callback. + bool isLocalShareEmpty() const { return _local_anchor_tags.empty(); } + // Advances past pending entries already confirmed as containers; both callers share this scan. + void advancePendingLocalAnchorEvictionCursor(); + // Normalize the pending eviction cursor once before root callbacks so their gate stays O(1). + void preparePendingLocalAnchorEvictionCursor(); + // Mirrors noteLocalRootHolder()'s current admission limits without changing pending state. + bool localHolderNeedsObservation(jlong tag, jlong own_class_tag) const; + // Mirrors pushAtRiskStaticAnchor() so callbacks do not stage known queue no-ops. + bool atRiskAnchorNeedsObservation(jlong tag, u32 klass_id) const; + // Bounds LOCAL records by free index slots, pending slots, and displaceable pending entries. + // Only replay mutates these counts, after the same-thread traversal completes. + // The test override lets journal-overflow tests deliberately stage a larger prefix. + u32 localStagingAbsorbable() const { +#ifdef UNIT_TEST + if (_local_staging_budget_override_for_test != 0) { + return _local_staging_budget_override_for_test; + } +#endif + size_t index_room = _local_anchor_tags.size() < LOCAL_ANCHOR_INDEX_CAP + ? LOCAL_ANCHOR_INDEX_CAP - _local_anchor_tags.size() + : 0; + size_t buffer_room = PENDING_LOCAL_ANCHOR_CAP - _pending_local_anchors.size(); + return (u32)(index_room + buffer_room + _pending_local_evictable_count); + } // At-risk anchor push: deduped, capped, and quota-limited per klass. void pushAtRiskStaticAnchor(jlong tag, u32 klass_id); // Add `tag` to _static_anchor_index if its root_kind is a durable anchor-tier kind (STATIC_FIELD // or JNI_GLOBAL). void addToStaticAnchorIndex(jlong tag, jlong own_class_tag, u8 root_kind); // Shared deduplicated index insertion for durable roots and local holders. - void indexAnchorForRotation(jlong tag, jlong own_class_tag, - 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); + void indexAnchorForRotation(jlong tag, jlong own_class_tag); + // Replays a stack/JNI-local holder observation: indexes a confirmed container (under + // LOCAL_ANCHOR_INDEX_CAP), ignores a classified non-container, and parks an unclassified holder + // (or one met at the cap) in the capped _pending_local_anchors buffer; at a full buffer a + // confirmed container evicts the oldest not-confirmed entry. Not called from heap callbacks. + void noteLocalRootHolder(jlong tag, jlong own_class_tag); + // BFS thread, after reconcileAnchorClassShapes(): indexes pending holders confirmed as + // containers, drops the rest, and empties the pending buffer. + void resolvePendingLocalAnchors(); + // Removes local-holder index entries that are no longer selectable (dead or demoted). Scans only + // the local share and runs at most once per resolvePendingLocalAnchors() call at the cap. + // Returns the number of removed entries. + size_t compactLocalAnchors(); + // Removes tags absent from walkStaticFieldAnchors()'s GetObjectsWithTags() resolution - a + // collected anchor can never be walked again, so its slot is reclaimed instead of waiting for + // FIFO eviction (and a dead local container would otherwise keep its selectable EXPANDED + // frontier record until a search restart cleared the frontier). + void removeMissingAnchors(const std::vector &missing); + // Stable compaction preserves index order and parallel class-tag alignment. + // Durable eviction keeps pending turns; removal paths clear them. + void eraseAnchorEntries(const std::unordered_set &removed, + bool preserve_pending_turns = false); + // FIFO-evicts the oldest durable entries down to cap - DURABLE_ANCHOR_EVICT_BATCH. + // Pending first-look turns survive eviction; the index remains bounded. + // Local-share entries are never evicted here. Returns the number evicted. + size_t evictOldestDurableAnchors(); // 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. @@ -1105,6 +1318,10 @@ class ReferenceChainTracker { // 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); + // Pure (no JNI) collection step of reconcileAnchorClassShapes(): up to + // ANCHOR_SHAPE_RECONCILE_BUDGET distinct non-zero class tags absent from _class_shape_cache, + // pending local holders first (buffer order), then indexed anchors (index order). Read-only. + std::vector collectUnclassifiedAnchorClassTags() const; // Pops up to max_count AtRiskAnchor entries off _static_anchor_fifo's front into `out` // (appending), decrementing each popped entry's class occupancy in // _static_anchor_fifo_klass_counts (erased at zero, so the map tracks the FIFO's live contents), @@ -1115,14 +1332,24 @@ class ReferenceChainTracker { // re-incrementing each entry's class occupancy, and rebuilds the set - the truncated-walk requeue // path. void requeueStaticAnchorFifoFront(const std::vector &entries); + // Pushes fresh-lane picks whose walk never happened back to _static_anchor_fresh_queue's FRONT + // in reverse order (preserving admission order). Their FIRST_LOOK_PENDING flag is untouched - + // the flag is spent only by the post-descent serving (or by the selection-time spending of the + // fresh-room overflow drain). + void requeueStaticAnchorFreshFront( + const std::vector &entries); // When non-null, receives the tags of RESOLVED-but-unwalked anchors at the truncation break point // - GetObjectsWithTags may return fewer anchors than requested (dead tags drop out) in its own // order, so the caller cannot recover the un-walked set from a consumed index; the walk hands the // exact tags back instead. + // Borrows the caller's `scope`; on journal overflow `unwalked` also receives the partially + // walked anchor and `*anchor_observation_overflow` is set. void walkStaticFieldAnchors(jvmtiEnv *jvmti, JNIEnv *jni, + ReferenceChainAnchorObservationScope &scope, const std::vector &anchor_tags, int budget, int *edges_admitted, bool *truncated, bool *frontier_cap_hit, u64 *safepoint_ns, + bool *anchor_observation_overflow, std::vector *unwalked = nullptr); // jvmtiHeapRootCallback/jvmtiStackReferenceCallback for runPassManualWalk()'s @@ -1143,6 +1370,7 @@ class ReferenceChainTracker { int root_enum_budget, int expand_budget, int *edges_admitted, bool *truncated, bool *frontier_cap_hit, u64 *safepoint_ns); + u32 nextRootReportAttemptId(bool static_sweep); // Inserts (or refreshes) klass_id's resolved chain in _resolved_chains, recording the // source_tag/source_search_ns it was reconstructed from so a later poll can tell a stale entry @@ -1158,16 +1386,46 @@ class ReferenceChainTracker { // Copies the current cache keys into fixed caller-owned storage before a synchronous traversal. int snapshotResolvedChainTags(jlong *out); - // Queues an eviction from a heap callback only when the tag was cached in the immutable + // What a deferred invalidation does to the cached chain. + // EVICT: the source was rejected (noise eviction) - the cached chain is erased, at dump time or + // on the next poll, whichever drains first. + // REBUILD: the source is still live and its frontier entry intact, only its path changed + // (improveChain()/reparentToDurableRoot()/root-kind upgrade). Never erased at dump time: only + // the BFS-thread poll applies it, rebuilding the chain from the frontier and keeping the old one + // if the rebuild fails (restartSearch()'s keep-across-restart contract). EVICT wins over + // REBUILD for the same pending tag. + enum class ChainInvalidationKind : u8 { EVICT, REBUILD }; + + // In-band kind encoding for the pending buffers. Cache keys are frontier tags (>= 0), so the + // complement of a REBUILD tag is always negative and never collides with an EVICT entry. + static jlong encodePendingChainInvalidation(jlong source_tag, + ChainInvalidationKind kind) { + return kind == ChainInvalidationKind::REBUILD ? ~source_tag : source_tag; + } + static bool isPendingChainRebuild(jlong encoded) { return encoded < 0; } + static jlong pendingChainInvalidationTag(jlong encoded) { + return encoded < 0 ? ~encoded : encoded; + } + + // Queues an invalidation from a heap callback only when the tag was cached in the immutable // pre-traversal snapshot. This never takes _resolved_chains_lock or allocates. void deferResolvedChainInvalidation(jlong source_tag, const jlong *resolved_chain_tags, - int resolved_chain_tag_count); + int resolved_chain_tag_count, + ChainInvalidationKind kind); - // Applies queued exact-tag evictions. Called by the engine thread and by dump threads, which may - // overlap a traversal; the resolved-cache/pending locks provide synchronization. + // Dump-path drain: applies only the queued EVICT invalidations and leaves REBUILD entries + // pending for the BFS thread (see ChainInvalidationKind). May overlap a traversal; the + // resolved-cache/pending locks provide synchronization. void drainPendingChainInvalidations(); + // BFS-thread drain (pollWatchedTargets()): applies EVICT entries like the dump path and rebuilds + // each REBUILD entry's current-generation cached chain from the frontier via buildChainEvent(), + // overwriting it on success and keeping it on failure. Independent of candidate/discovered + // slots, so it still works after runPass()'s terminal branch zeroed them. + void applyPendingChainInvalidations(jvmtiEnv *jvmti, JNIEnv *jni, + u64 current_search_ns); + // Clears both pending buffers at cache/tag-generation boundaries without releasing capacity. void clearPendingChainInvalidations(); @@ -1267,6 +1525,7 @@ class ReferenceChainTracker { // Test accessor for _passes_since_last_progress. int passesSinceLastProgressForTest() const { return _passes_since_last_progress; } + // Canary-lane backoff state - see _canary_backoff_mult's own comment. int canaryBackoffMultForTest() const { return _canary_backoff_mult; } u64 canaryPassEmaMsForTest() const { return _canary_pass_ema_ms; } @@ -1277,6 +1536,13 @@ class ReferenceChainTracker { _last_canary_pass_ns = last_pass_ns; } void setOomRampActiveForTest(bool active) { _oom_ramp_active = active; } +#ifdef UNIT_TEST + // Test-only LOCAL staging bound override; absent from profiler builds. + u32 _local_staging_budget_override_for_test = 0; + void setLocalStagingBudgetOverrideForTest(u32 budget) { + _local_staging_budget_override_for_test = budget; + } +#endif int candidateCountForTest() const { return _candidate_count; } void setCandidateCountForTest(int n) { _candidate_count = n; } void setCandidateKlassIdForTest(int idx, u32 klass_id) { @@ -1390,10 +1656,10 @@ class ReferenceChainTracker { // no thread is already running. void startThread(); - // Stops and joins the BFS thread started by startThread(), mirroring BaseWallClock::stop()'s - // pthread_kill(WAKEUP_SIGNAL) + pthread_join() shape (wallClock.cpp) - WAKEUP_SIGNAL is already - // installed unconditionally in vmEntry.cpp, so no extra signal setup is needed here. - void stopThread(); + // Stops and joins the BFS thread via the installed WAKEUP_SIGNAL. + // False means termination was not confirmed; callers must skip teardown and may retry the join. + // True also covers the no-thread case. + bool stopThread(); bool enabled() const { return loadAcquire(_enabled); } diff --git a/ddprof-lib/src/test/cpp/elfparser_ut.cpp b/ddprof-lib/src/test/cpp/elfparser_ut.cpp index ecc3449e46..a8cebfcbb3 100644 --- a/ddprof-lib/src/test/cpp/elfparser_ut.cpp +++ b/ddprof-lib/src/test/cpp/elfparser_ut.cpp @@ -380,6 +380,15 @@ INSTANTIATE_TEST_SUITE_P( #else TEST_P(ElfTestParam, invalidElfSmallMappingAfterUnmap) { +#ifdef TSAN_ENABLED + // TSan aborts the whole binary (halt_on_error) on the uninstrumented-libc + // window this test exists to exercise: dlclose on the unmap thread frees + // loader structures while the main thread's dlinfo/dladdr reads run. The + // race is a TSan-visibility artifact, not a product defect, + // and an abort skips XML writing, so quarantine cannot express it - skip + // at runtime instead. + GTEST_SKIP() << "TSan flags the intentional dlclose-vs-parseLibraries race"; +#endif char path[PATH_MAX]; if (!findTestResource("native-libs/small-lib/libsmall-lib.so", path, sizeof(path))) { GTEST_SKIP() << "Missing test resource native-libs/small-lib/libsmall-lib.so"; diff --git a/ddprof-lib/src/test/cpp/livenessTrackerThreadTrends_ut.cpp b/ddprof-lib/src/test/cpp/livenessTrackerThreadTrends_ut.cpp new file mode 100644 index 0000000000..928001723e --- /dev/null +++ b/ddprof-lib/src/test/cpp/livenessTrackerThreadTrends_ut.cpp @@ -0,0 +1,550 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "livenessTracker.h" + +#include + +class LivenessThreadTrendTestAccessor { +public: + using Scratch = LivenessTracker::KlassCountScratch; + + static void *newScratch() { return new Scratch{}; } + static void deleteScratch(void *scratch) { delete static_cast(scratch); } + + static void add(LivenessTracker *tracker, void *scratch, jint tid, u32 age) { + tracker->insertThreadGen(*static_cast(scratch), tid, age); + } + + static void promote(LivenessTracker *tracker, void *scratch) { + tracker->promoteThreadGenCandidates(*static_cast(scratch)); + } + + static int threadCount(void *scratch) { + return static_cast(scratch)->thread_count; + } + + static int challengerCount(void *scratch) { + return static_cast(scratch)->challenger_count; + } + + static jint threadTid(void *scratch, int index) { + return static_cast(scratch)->threads[index].tid; + } + + static u32 threadAgeCount(void *scratch, int index) { + return static_cast(scratch)->threads[index].age_count; + } + + static u32 threadCount(void *scratch, int index) { + return static_cast(scratch)->threads[index].count; + } + + static jint challengerTid(void *scratch, int index) { + return static_cast(scratch)->challengers[index].tid; + } + + static u32 challengerCount(void *scratch, int index) { + return static_cast(scratch)->challengers[index].count; + } + + static u32 challengerAgeCount(void *scratch, int index) { + return static_cast(scratch)->challengers[index].age_count; + } + + // Folds one epoch: creates/refreshes klass_id's population record, then runs the production + // fold (recordTidTrendSamplesLocked) over the caller's scratch under the table lock. + static void fold(LivenessTracker *tracker, void *scratch, u32 klass_id, + u64 epoch) { + int slot; + bool created; + tracker->klassPopulationRecordForTest(klass_id, /*count=*/1, epoch, + &slot, &created); + foldSlot(tracker, scratch, slot); + } + + // Folds into an arbitrary slot (no record creation) - the direct seam for the slot-bounds + // guard test. + static void foldSlot(LivenessTracker *tracker, void *scratch, int slot) { + tracker->_table_lock.lock(); + tracker->recordTidTrendSamplesLocked( + slot, *static_cast(scratch)); + tracker->_table_lock.unlock(); + } + + static const KlassPopulationEntry::TidTrend *trendFor( + LivenessTracker *tracker, u32 klass_id, jint tid) { + for (int i = 0; i < tracker->_klass_population_size; i++) { + if (tracker->_klass_population[i].klass_id != klass_id) { + continue; + } + const KlassPopulationEntry &entry = tracker->_klass_population[i]; + for (int t = 0; t < entry.tid_trend_count; t++) { + if (entry.tid_trends[t].tid == tid) { + return &entry.tid_trends[t]; + } + } + return nullptr; + } + return nullptr; + } + + static int consecutivePositive(LivenessTracker *tracker, u32 klass_id, + jint tid) { + const auto *trend = trendFor(tracker, klass_id, tid); + return trend != nullptr ? trend->consecutive_positive : -1; + } +}; + +namespace { +struct ScratchGuard { + void *scratch; + ~ScratchGuard() { + LivenessThreadTrendTestAccessor::deleteScratch(scratch); + } + operator void *() const { return scratch; } +}; +} // namespace + +TEST(LivenessThreadTrendTest, SingleNewcomerCannotDisplaceQualifiedIncumbent) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (jint tid = 1; tid <= 16; tid++) { + u32 count = tid == 1 ? 8 : 12; + for (u32 i = 0; i < count; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + } + LivenessThreadTrendTestAccessor::add(tracker, scratch, 99, 1); + ASSERT_EQ(16, LivenessThreadTrendTestAccessor::threadCount(scratch)); + ASSERT_EQ(1, LivenessThreadTrendTestAccessor::challengerCount(scratch)); + EXPECT_EQ(1, LivenessThreadTrendTestAccessor::threadTid(scratch, 0)); + EXPECT_EQ(8u, LivenessThreadTrendTestAccessor::threadCount(scratch, 0)); + EXPECT_EQ(99, LivenessThreadTrendTestAccessor::challengerTid(scratch, 0)); + EXPECT_EQ(1u, LivenessThreadTrendTestAccessor::challengerCount(scratch, 0)); + + LivenessThreadTrendTestAccessor::promote(tracker, scratch); + EXPECT_EQ(1, LivenessThreadTrendTestAccessor::threadTid(scratch, 0)); + EXPECT_EQ(8u, LivenessThreadTrendTestAccessor::threadCount(scratch, 0)); +} + +TEST(LivenessThreadTrendTest, ChallengerPoolKeepsFourSamplesBeforePromotion) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (jint tid = 1; tid <= 16; tid++) { + for (u32 i = 0; i < 8; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + } + for (jint tid = 100; tid < 104; tid++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + LivenessThreadTrendTestAccessor::add(tracker, scratch, 104, 1); + ASSERT_EQ(4, LivenessThreadTrendTestAccessor::challengerCount(scratch)); + EXPECT_EQ(104, LivenessThreadTrendTestAccessor::challengerTid(scratch, 0)); + for (u32 i = 0; i < 11; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, 104, 1); + } + LivenessThreadTrendTestAccessor::promote(tracker, scratch); + bool found = false; + for (int i = 0; i < LivenessThreadTrendTestAccessor::threadCount(scratch); + i++) { + found = found || + LivenessThreadTrendTestAccessor::threadTid(scratch, i) == 104; + } + EXPECT_TRUE(found); +} + +TEST(LivenessThreadTrendTest, LargerLateCohortsPromoteFromChallengerPool) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + constexpr jint kFirstChallenger = 100; + constexpr int kChallengers = 4; + + for (jint tid = 1; tid <= 16; tid++) { + for (u32 i = 0; i < 8; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + } + for (int i = 0; i < kChallengers; i++) { + for (u32 n = 0; n < 12; n++) { + LivenessThreadTrendTestAccessor::add( + tracker, scratch, kFirstChallenger + i, 1); + } + } + ASSERT_EQ(kChallengers, + LivenessThreadTrendTestAccessor::challengerCount(scratch)); + LivenessThreadTrendTestAccessor::promote(tracker, scratch); + + bool found[kChallengers] = {}; + for (int i = 0; i < LivenessThreadTrendTestAccessor::threadCount(scratch); + i++) { + jint tid = LivenessThreadTrendTestAccessor::threadTid(scratch, i); + if (tid >= kFirstChallenger && tid < kFirstChallenger + kChallengers) { + found[tid - kFirstChallenger] = true; + } + } + for (int candidate = 0; candidate < kChallengers; candidate++) { + EXPECT_TRUE(found[candidate]) << (kFirstChallenger + candidate); + } +} +// The per-thread age-capacity guard: a thread sampling more than MAX_AGES_PER_THREAD distinct +// ages keeps its sorted-ages window capped at the maximum while its retained count keeps +// growing. Without the guard, the write past ages[MAX - 1] lands on age_count itself (the next +// member of ThreadGens), corrupting the accumulator. +TEST(LivenessThreadTrendTest, AgeCapacityGuardCapsDistinctAgesWithoutDroppingCount) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (u32 i = 0; i < 40; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, 7, i + 1); + } + ASSERT_EQ(1, LivenessThreadTrendTestAccessor::threadCount(scratch)); + EXPECT_EQ(7, LivenessThreadTrendTestAccessor::threadTid(scratch, 0)) + << "accumulator header must survive the age window's cap"; + EXPECT_EQ(32u, LivenessThreadTrendTestAccessor::threadAgeCount(scratch, 0)) + << "distinct-age window must cap at MAX_AGES_PER_THREAD"; + EXPECT_EQ(40u, LivenessThreadTrendTestAccessor::threadCount(scratch, 0)) + << "the retained count keeps rising past the age cap"; + // The boundary is >= (not >): with the guard loosened to >, the 41st distinct age would be + // admitted and written past ages[MAX - 1], corrupting age_count itself. + LivenessThreadTrendTestAccessor::add(tracker, scratch, 7, 41); + EXPECT_EQ(32u, LivenessThreadTrendTestAccessor::threadAgeCount(scratch, 0)) + << "the guard must hold at the cap boundary (>=, not >)"; + EXPECT_EQ(7, LivenessThreadTrendTestAccessor::threadTid(scratch, 0)); + EXPECT_EQ(41u, LivenessThreadTrendTestAccessor::threadCount(scratch, 0)); +} + +// Promotion must require a challenger to OUTRANK the weakest incumbent (strict >): an equal +// count AND equal distinct-age span must not replace an incumbent, or churn replaces incumbents +// that are accumulating just as much evidence. +TEST(LivenessThreadTrendTest, PromotionRequiresStrictlyBetterChallenger) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (jint tid = 1; tid <= 16; tid++) { + for (u32 i = 0; i < 5; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + } + for (u32 i = 0; i < 5; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, 100, 9); + } + ASSERT_EQ(1, LivenessThreadTrendTestAccessor::challengerCount(scratch)); + // Equal count (5) and equal age span (1): the challenger does not outrank the weakest + // incumbent, so promotion must leave the incumbent table untouched. + LivenessThreadTrendTestAccessor::promote(tracker, scratch); + ASSERT_EQ(16, LivenessThreadTrendTestAccessor::threadCount(scratch)); + for (int i = 0; i < 16; i++) { + EXPECT_NE(100, LivenessThreadTrendTestAccessor::threadTid(scratch, i)) + << "an equal challenger replaced an incumbent (>= comparison)"; + } + + // Promotion cleared the challenger pool, so the challenger re-accumulates from scratch: six + // samples put it strictly over the weakest incumbent's count of 5, and promotion now + // replaces the weakest slot. + for (u32 i = 0; i < 6; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, 100, 9); + } + LivenessThreadTrendTestAccessor::promote(tracker, scratch); + ASSERT_EQ(16, LivenessThreadTrendTestAccessor::threadCount(scratch)); + bool promoted = false; + for (int i = 0; i < 16; i++) { + promoted = promoted || + LivenessThreadTrendTestAccessor::threadTid(scratch, i) == 100; + } + EXPECT_TRUE(promoted) << "a strictly better challenger must promote"; +} + +// The per-tid hysteresis counter resets on the first non-qualifying epoch: a thread over the +// retained-count bar that drops back under it must lose its accumulated consecutive_positive +// (the transient burst is not a sustained trend). +TEST(LivenessThreadTrendTest, ConsecutivePositiveResetsOnNonQualifyingEpoch) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 771; + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + // Two qualifying epochs: the tid's surviving count clears the retained-count bar. + for (u32 i = 0; i < 10; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, 7, 1); + } + LivenessThreadTrendTestAccessor::fold(tracker, scratch, klass_id, 1); + LivenessThreadTrendTestAccessor::fold(tracker, scratch, klass_id, 2); + EXPECT_EQ(2, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 7)); + + // One non-qualifying epoch (count 1, flat history): the counter resets to 0. + ScratchGuard fresh{LivenessThreadTrendTestAccessor::newScratch()}; + for (u32 i = 0; i < 1; i++) { + LivenessThreadTrendTestAccessor::add(tracker, fresh, 7, 1); + } + LivenessThreadTrendTestAccessor::fold(tracker, fresh, klass_id, 3); + EXPECT_EQ(0, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 7)) + << "a non-qualifying epoch must reset the hysteresis counter"; +} + +// Newcomer churn stays bounded: with the incumbent table full, a burst of more than +// MAX_THREAD_CHALLENGERS_PER_KLASS one-shot newcomers recycles only the challenger pool's +// count-1 slots and never displaces an incumbent (not even a sub-bar one). +TEST(LivenessThreadTrendTest, NewcomerChurnBeyondPoolNeverDisplacesIncumbents) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (jint tid = 1; tid <= 16; tid++) { + for (u32 i = 0; i < 5; i++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + } + ASSERT_EQ(16, LivenessThreadTrendTestAccessor::threadCount(scratch)); + + // More than 4 one-shot newcomers (one sample each) churn through the pool. + for (jint tid = 100; tid < 110; tid++) { + LivenessThreadTrendTestAccessor::add(tracker, scratch, tid, 1); + } + ASSERT_EQ(16, LivenessThreadTrendTestAccessor::threadCount(scratch)); + for (jint tid = 1; tid <= 16; tid++) { + bool present = false; + for (int i = 0; i < 16; i++) { + present = present || + LivenessThreadTrendTestAccessor::threadTid(scratch, i) == tid; + } + EXPECT_TRUE(present) << "incumbent tid " << tid + << " displaced by newcomer churn"; + } + EXPECT_EQ(4, LivenessThreadTrendTestAccessor::challengerCount(scratch)); +} + +// A full trend table must not hand a slot to a newcomer that is weaker than the weakest victim's +// accumulated evidence: a trend whose consecutive_positive was just reset by one skipped (or +// non-qualifying) epoch still owns its pre-reset retained counts, and a single-sample newcomer +// must not take that slot unconditionally (F-772fa299c1da). +TEST(LivenessThreadTrendTest, TakeoverEarnsAgainstAccumulatedEvidence) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 772; + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + // Fill all 8 trend slots with qualifying threads (count 12 clears the bar): two full epochs. + for (int epoch = 1; epoch <= 2; epoch++) { + ScratchGuard epoch_scratch{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 8; tid++) { + for (u32 i = 0; i < 12; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch_scratch, + tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch_scratch, klass_id, + epoch); + } + + // Epoch 3: tid 1 drops to a single retained instance (resets its hysteresis, newest live + // count 1); tids 2-8 vanish entirely (one trailing zero epoch each, pre-reset count 12). + ScratchGuard dipped{LivenessThreadTrendTestAccessor::newScratch()}; + for (u32 i = 0; i < 1; i++) { + LivenessThreadTrendTestAccessor::add(tracker, dipped, 1, 1); + } + LivenessThreadTrendTestAccessor::fold(tracker, dipped, klass_id, 3); + EXPECT_EQ(0, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 1)) + << "setup: tid 1's hysteresis must be reset by the weak epoch"; + + // A single-sample newcomer (count 1) is weaker than every victim's evidence: tid 1's newest + // live count matches it and tids 2-8 still own pre-reset counts of 12 - the newcomer is + // dropped and every accumulated trend survives. + ScratchGuard newcomer{LivenessThreadTrendTestAccessor::newScratch()}; + LivenessThreadTrendTestAccessor::add(tracker, newcomer, 99, 1); + LivenessThreadTrendTestAccessor::fold(tracker, newcomer, klass_id, 4); + EXPECT_EQ(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 99)) + << "a weaker newcomer must not take a slot unconditionally"; + for (jint tid = 1; tid <= 8; tid++) { + EXPECT_NE(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, + tid)) + << "accumulated trend for tid " << tid << " must survive"; + } + + // A newcomer that OUTRANKS the weakest victim's evidence earns the slot: count 20 beats + // tid 1's newest live count of 1. + ScratchGuard hot{LivenessThreadTrendTestAccessor::newScratch()}; + for (u32 i = 0; i < 20; i++) { + LivenessThreadTrendTestAccessor::add(tracker, hot, 99, 1); + } + LivenessThreadTrendTestAccessor::fold(tracker, hot, klass_id, 5); + EXPECT_NE(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 99)) + << "a newcomer hotter than the weakest victim's evidence must take a slot"; + EXPECT_EQ(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 1)) + << "the weakest victim's trend is the one replaced"; +} + +// Sustaining trends are never victims: with every slot's consecutive_positive alive, a newcomer +// of any strength is dropped (bounded retry on a later epoch). +TEST(LivenessThreadTrendTest, SustainedTrendsAreNeverTakeoverVictims) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 773; + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + + for (int epoch = 1; epoch <= 2; epoch++) { + ScratchGuard epoch_scratch{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 8; tid++) { + for (u32 i = 0; i < 12; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch_scratch, + tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch_scratch, klass_id, + epoch); + } + // Epoch 3 keeps every thread present at its qualifying count. + ScratchGuard epoch_scratch{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 8; tid++) { + for (u32 i = 0; i < 12; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch_scratch, tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch_scratch, klass_id, 3); + + ScratchGuard hot{LivenessThreadTrendTestAccessor::newScratch()}; + for (u32 i = 0; i < 40; i++) { + LivenessThreadTrendTestAccessor::add(tracker, hot, 99, 1); + } + LivenessThreadTrendTestAccessor::fold(tracker, hot, klass_id, 4); + EXPECT_EQ(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 99)) + << "no sustaining trend may be evicted, whatever the newcomer's strength"; +} + +// A challenger promotion that replaces an incumbent must not discard the victim's live epoch +// sample: the displaced incumbent's tracked trend records its current-epoch count instead of +// the absent-tid pass writing the still-live thread a zero epoch and resetting qualification. +TEST(LivenessThreadTrendTest, PromotionKeepsDisplacedIncumbentQualification) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 774; + // Epochs 1-2: 16 incumbents; tids 1-8 (count 9) win the 8 trend slots, all qualifying. + for (int epoch = 1; epoch <= 2; epoch++) { + ScratchGuard epoch_scratch{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 16; tid++) { + u32 count = tid <= 8 ? 9 : 12; + for (u32 i = 0; i < count; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch_scratch, + tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch_scratch, klass_id, + epoch); + } + ASSERT_EQ(2, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 1)) + << "setup: tid 1's trend must be qualified before the displacement"; + + // Epoch 3: the same cohort plus four stronger challengers; promotion replaces the four + // weakest incumbents - the trend-holding tids 1-4. + ScratchGuard epoch3{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 16; tid++) { + u32 count = tid <= 8 ? 9 : 12; + for (u32 i = 0; i < count; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch3, tid, 1); + } + } + for (jint tid = 100; tid < 104; tid++) { + for (u32 i = 0; i < 20; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch3, tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch3, klass_id, 3); + for (jint tid = 1; tid <= 4; tid++) { + EXPECT_EQ(3, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, tid)) + << "displaced incumbent " << tid + << " keeps its qualification through the live sample"; + } + for (jint tid = 5; tid <= 8; tid++) { + EXPECT_EQ(3, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, tid)); + } +} + +// The slot bounds guard on recordTidTrendSamplesLocked(): out-of-range slots must be a no-op +// (removing the guard would index the population table out of bounds). +TEST(LivenessThreadTrendTest, OutOfRangeFoldSlotIsANoOp) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 774; + ScratchGuard scratch{LivenessThreadTrendTestAccessor::newScratch()}; + LivenessThreadTrendTestAccessor::add(tracker, scratch, 7, 1); + // Seed one real trend through a VALID slot, then prove out-of-range slots are no-ops. + ScratchGuard seed{LivenessThreadTrendTestAccessor::newScratch()}; + LivenessThreadTrendTestAccessor::add(tracker, seed, 7, 1); + int slot = -1; + { + bool created; + tracker->klassPopulationRecordForTest(klass_id, 1, 1, &slot, &created); + } + LivenessThreadTrendTestAccessor::foldSlot(tracker, seed, slot); + ASSERT_NE(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 7)) + << "setup: the valid fold must create the trend"; + LivenessThreadTrendTestAccessor::foldSlot(tracker, scratch, -1); + LivenessThreadTrendTestAccessor::foldSlot(tracker, scratch, slot + 1); + EXPECT_NE(nullptr, + LivenessThreadTrendTestAccessor::trendFor(tracker, klass_id, 7)) + << "out-of-range folds must not create or corrupt trends"; +} + +// An unpromoted challenger with a tracked trend must not read as absent: it met the fold with a +// live sample (it merely failed to outrank the weakest incumbent), and the absent-tid pass +// writing it a zero epoch would reset its qualification streak. +TEST(LivenessThreadTrendTest, UnpromotedChallengerKeepsTrendSample) { + LivenessTracker *tracker = LivenessTracker::instance(); + const u32 klass_id = 775; + // Epochs 1-2: tids 1-8 (count 9) hold the 8 trend slots, all qualified. + for (int epoch = 1; epoch <= 2; epoch++) { + ScratchGuard epoch_scratch{LivenessThreadTrendTestAccessor::newScratch()}; + for (jint tid = 1; tid <= 16; tid++) { + u32 count = tid <= 8 ? 9 : 12; + for (u32 i = 0; i < count; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch_scratch, + tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch_scratch, klass_id, + epoch); + } + ASSERT_EQ(2, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 5)) + << "setup: tid 5's trend must be qualified before the fold"; + + // Epoch 3: sixteen other threads fill the scratch table (all stronger than tid 5's + // challenger), then tid 5 - an existing trend holder - contributes 9 retained objects as a + // challenger. Promotion fails (9 < 12), so without the live-sample preservation the + // absent-tid pass writes tid 5 a zero epoch and resets its streak. + ScratchGuard epoch3{LivenessThreadTrendTestAccessor::newScratch()}; + jint filler = 1; + for (int i = 0; i < 16; i++) { + while (filler == 5) { + filler++; + } + for (u32 j = 0; j < 12; j++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch3, filler, 1); + } + filler++; + } + for (u32 i = 0; i < 9; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch3, 5, 1); + } + // Three more low-count challengers so the pool is full around tid 5. + for (jint tid = 101; tid < 104; tid++) { + for (u32 i = 0; i < 2; i++) { + LivenessThreadTrendTestAccessor::add(tracker, epoch3, tid, 1); + } + } + LivenessThreadTrendTestAccessor::fold(tracker, epoch3, klass_id, 3); + EXPECT_EQ(3, LivenessThreadTrendTestAccessor::consecutivePositive( + tracker, klass_id, 5)) + << "the unpromoted challenger's live sample must keep its streak alive"; +} diff --git a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp index bf2eab363c..62789431b6 100644 --- a/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp +++ b/ddprof-lib/src/test/cpp/livenessTracker_ut.cpp @@ -1123,6 +1123,54 @@ class LivenessTrackerTestAccessor { t->_table_lock.unlock(); } + // Feeds one insertThreadGen() call into a caller-owned scratch, so a test can drive the + // at-capacity eviction scan directly and inspect the resulting per-slot state. The scratch + // type is private to LivenessTracker, so tests hold it through this void* handle pair. + static void *allocScratchForTest() { + return new LivenessTracker::KlassCountScratch{}; + } + + static void freeScratchForTest(void *scratch) { + delete (LivenessTracker::KlassCountScratch *)scratch; + } + + static void insertThreadGenForTest(LivenessTracker *t, void *scratch, + jint tid, u32 age) { + t->insertThreadGen(*(LivenessTracker::KlassCountScratch *)scratch, tid, age); + } + + static int scratchThreadCountForTest(void *scratch) { + return ((LivenessTracker::KlassCountScratch *)scratch)->thread_count; + } + + static jint scratchTidForTest(void *scratch, int idx) { + return ((LivenessTracker::KlassCountScratch *)scratch)->threads[idx].tid; + } + + static u32 scratchRetainedCountForTest(void *scratch, int idx) { + return ((LivenessTracker::KlassCountScratch *)scratch)->threads[idx].count; + } + + static u32 scratchAgeCountForTest(void *scratch, int idx) { + return ((LivenessTracker::KlassCountScratch *)scratch)->threads[idx].age_count; + } + + static int scratchChallengerCountForTest(void *scratch) { + return ((LivenessTracker::KlassCountScratch *)scratch)->challenger_count; + } + + static jint scratchChallengerTidForTest(void *scratch, int idx) { + return ((LivenessTracker::KlassCountScratch *)scratch)->challengers[idx].tid; + } + + static u32 scratchChallengerCountForTest(void *scratch, int idx) { + return ((LivenessTracker::KlassCountScratch *)scratch)->challengers[idx].count; + } + + static void promoteThreadGensForTest(LivenessTracker *t, void *scratch) { + t->promoteThreadGenCandidates(*(LivenessTracker::KlassCountScratch *)scratch); + } + using Scratch = LivenessTracker::KlassCountScratch; static constexpr int KLASS_POPULATION_CAP = LivenessTracker::MAX_KLASS_POPULATION_ENTRIES; @@ -1334,6 +1382,164 @@ class LivenessTrackerTestAccessor { return t->_heap_floor_sample_seq; } }; +// RAII handle for the accessor-owned KlassCountScratch: frees on every exit, an ASSERT_* +// early return included. Converts to the accessor's void* handle implicitly. +struct ScratchGuard { + void *p; + ~ScratchGuard() { LivenessTrackerTestAccessor::freeScratchForTest(p); } + operator void *() const { return p; } +}; + + +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); + } +} + +// Newcomers never immediately evict incumbents - not even sub-bar ones: a newcomer accumulates +// in the challenger pool, and promotion into the incumbent table requires OUTRANKING the weakest +// incumbent (strict >). The weakest-incumbent victim scan's tie-break (earliest slot among equal +// minima, strict <) is exercised through promotion: a promoted challenger replaces the earliest +// minimum slot, never a later equal-count one and never a larger-count one. +TEST_F(SelectLeakCandidatesTest, NewcomerAccumulatesInChallengerPoolAndPromotesOverWeakestIncumbent) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessTrackerTestAccessor::allocScratchForTest()}; + // Slots 0 and 1 tie at the minimum count 1; slots 2-15 hold count 5. All sub-bar. + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 1, 1); + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 2, 1); + for (jint tid = 3; tid <= 16; tid++) { + for (u32 i = 0; i < 5; i++) { + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, tid, 1); + } + } + ASSERT_EQ(16, LivenessTrackerTestAccessor::scratchThreadCountForTest(scratch)); + + // A sub-bar newcomer must not displace anyone: it accumulates in the challenger pool. + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 100, 1); + ASSERT_EQ(16, LivenessTrackerTestAccessor::scratchThreadCountForTest(scratch)); + EXPECT_EQ(1, LivenessTrackerTestAccessor::scratchChallengerCountForTest(scratch)); + EXPECT_EQ(100, LivenessTrackerTestAccessor::scratchChallengerTidForTest(scratch, 0)); + for (int i = 0; i < 16; i++) { + EXPECT_NE(100, LivenessTrackerTestAccessor::scratchTidForTest(scratch, i)) + << "a sub-bar newcomer displaced an incumbent"; + } + + // Once the challenger outranks the weakest incumbent, promotion replaces the earliest + // minimum slot (count 1 at slot 0), never slot 1 (the later equal-count minimum, only + // reachable with a <= scan) and never a count-5 slot (only reachable with an inverted + // comparison). + for (u32 i = 0; i < 2; i++) { + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 100, 1); + } + LivenessTrackerTestAccessor::promoteThreadGensForTest(tracker, scratch); + ASSERT_EQ(16, LivenessTrackerTestAccessor::scratchThreadCountForTest(scratch)); + EXPECT_EQ(100, LivenessTrackerTestAccessor::scratchTidForTest(scratch, 0)); + EXPECT_EQ(3u, LivenessTrackerTestAccessor::scratchRetainedCountForTest(scratch, 0)); + EXPECT_EQ(2, LivenessTrackerTestAccessor::scratchTidForTest(scratch, 1)) + << "the later equal-count minimum slot must survive"; + EXPECT_EQ(1u, LivenessTrackerTestAccessor::scratchRetainedCountForTest(scratch, 1)); + for (int i = 2; i < 16; i++) { + EXPECT_NE(100, LivenessTrackerTestAccessor::scratchTidForTest(scratch, i)) + << "promoted over a non-minimum slot"; + } + EXPECT_EQ(0, LivenessTrackerTestAccessor::scratchChallengerCountForTest(scratch)); +} + +// The promotion-time count-tie scan must break ties toward the FEWER distinct surviving ages +// (replace the tid whose retained set is poorer), not the other way round. +TEST_F(SelectLeakCandidatesTest, PromotionTieReplacesThreadWithFewerDistinctAges) { + LivenessTracker *tracker = LivenessTracker::instance(); + ScratchGuard scratch{LivenessTrackerTestAccessor::allocScratchForTest()}; + // Slot 0: count 5 across two distinct ages. Every other slot: count 5, one age - so the + // first age-poorer slot is the correct promotion victim. + const u32 two_ages[5] = {10, 11, 10, 11, 10}; + for (u32 i = 0; i < 5; i++) { + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 1, two_ages[i]); + } + for (jint tid = 2; tid <= 16; tid++) { + for (u32 i = 0; i < 5; i++) { + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, tid, 10); + } + } + ASSERT_EQ(16, LivenessTrackerTestAccessor::scratchThreadCountForTest(scratch)); + EXPECT_EQ(2u, LivenessTrackerTestAccessor::scratchAgeCountForTest(scratch, 0)); + + // The newcomer accumulates in the challenger pool and reaches count 6 - one over the + // incumbents' count of 5 - before promoting. + for (u32 i = 0; i < 6; i++) { + LivenessTrackerTestAccessor::insertThreadGenForTest(tracker, scratch, 100, 1); + } + LivenessTrackerTestAccessor::promoteThreadGensForTest(tracker, scratch); + ASSERT_EQ(16, LivenessTrackerTestAccessor::scratchThreadCountForTest(scratch)); + EXPECT_EQ(1, LivenessTrackerTestAccessor::scratchTidForTest(scratch, 0)) + << "the tid with more distinct ages must survive"; + EXPECT_EQ(2u, LivenessTrackerTestAccessor::scratchAgeCountForTest(scratch, 0)); + EXPECT_EQ(100, LivenessTrackerTestAccessor::scratchTidForTest(scratch, 1)) + << "promotion victim must be an equal-count, age-poorer slot"; + EXPECT_EQ(1u, LivenessTrackerTestAccessor::scratchAgeCountForTest(scratch, 1)); + EXPECT_EQ(6u, LivenessTrackerTestAccessor::scratchRetainedCountForTest(scratch, 1)) + << "the promoted challenger keeps its own accumulated count"; + for (int i = 2; i < 16; i++) { + EXPECT_NE(100, LivenessTrackerTestAccessor::scratchTidForTest(scratch, i)); + } +} #ifdef DEBUG TEST_F(SelectLeakCandidatesTest, SeededClassHistorySurvivesRealGcFolds) { @@ -1427,215 +1633,6 @@ TEST_F(SelectLeakCandidatesTest, OrdinaryClassHistoryStillDecaysAfterGrowthStops 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{}; diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorJournalTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorJournalTests.inc new file mode 100644 index 0000000000..f47a8a21c3 --- /dev/null +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorJournalTests.inc @@ -0,0 +1,1666 @@ +/* + * Copyright 2026, Datadog, Inc. + * SPDX-License-Identifier: Apache-2.0 + */ + +TEST_F(ReferenceChainsBfsTest, AnchorJournalSnapshotRequiresCurrentLease) { + AnchorObservationBuffer buffer; + AnchorObservationLease lease = buffer.tryLease(); + ASSERT_NE(0u, lease.id); + ASSERT_TRUE(buffer.reserve(lease)); + buffer.commit(lease, AnchorObservation{1, 2, 3, + AnchorObservation::LOCAL, + (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD}); + + const AnchorObservation *records = nullptr; + u32 count = 0; + bool static_retry = false; + ASSERT_TRUE(buffer.snapshot(lease, &records, &count, &static_retry)); + ASSERT_NE(nullptr, records); + ASSERT_EQ(1u, count); + EXPECT_EQ(1, records[0].tag); + EXPECT_FALSE(static_retry); + + buffer.releaseLease(lease); + EXPECT_FALSE(buffer.snapshot(lease, &records, &count, &static_retry)); + EXPECT_EQ(nullptr, records); + EXPECT_EQ(0u, count); + EXPECT_FALSE(static_retry); +} + +// Destroying the scope is itself a flush boundary: the early-return paths of the callers never +// call flush() explicitly. +TEST_F(ReferenceChainsBfsTest, AnchorScopeDestructionFlushesPendingPrefix) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + insertAnchorEntry(frontier, 20001, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, 20001); + ASSERT_EQ(1u, AnchorAcc::journalCountForTest()); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(20001)); + } + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(20001)); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + + tracker->stop(); +} + +// Empty journal: a flush with no accepted report applies nothing and requests no resweep; the +// return observation reports no overflow. +TEST_F(ReferenceChainsBfsTest, AnchorJournalEmptyFlushAppliesNothing) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + AnchorAcc::addToStaticAnchorIndexForTest(30001, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + const u64 gen = AnchorAcc::durableAnchorResweepGenForTest(); + + AnchorScopedPass pass(tracker, frontier); + EXPECT_FALSE(pass.scope.observeReturn()); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(gen, AnchorAcc::durableAnchorResweepGenForTest()); + EXPECT_FALSE(pass.scope.observeReturn()); + + tracker->stop(); +} + +// Duplicates consume staging capacity but never duplicate an indexed tag, and a duplicate of a +// still-indexed holder keeps its original first-look (fresh queue) position. +TEST_F(ReferenceChainsBfsTest, AnchorJournalDuplicatesConsumeCapacityButIndexOnce) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong first = 20001, second = 20002; + insertAnchorEntry(frontier, first, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + insertAnchorEntry(frontier, second, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + { + AnchorScopedPass pass(tracker, frontier); + for (int i = 0; i < 5; i++) { + reportRediscovery(pass, first); + } + EXPECT_EQ(5u, AnchorAcc::journalCountForTest()); // duplicates are not coalesced + pass.scope.flush(); + } + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(1u, AnchorAcc::anchorOwnClassTagsSizeForTest()); + EXPECT_EQ((std::vector{first}), AnchorAcc::freshQueueTagsForTest()); + + // The second tag joins behind it; then both are re-reported, the older one first and last. + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, second); + reportRediscovery(pass, first); + reportRediscovery(pass, second); + reportRediscovery(pass, first); + } + EXPECT_EQ(2u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(first, AnchorAcc::anchorIndexTagForTest(0)); + EXPECT_EQ(second, AnchorAcc::anchorIndexTagForTest(1)); + EXPECT_EQ((std::vector{first, second}), AnchorAcc::freshQueueTagsForTest()); + + // The next enumeration re-reports both tags: both are indexed now, so the indexed-tag gate + // stages nothing - their replay would be a no-op, and the slots stay free for real effects. + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, first); + reportRediscovery(pass, second); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + } + + tracker->stop(); +} + +// Exact capacity, first record over it, and sustained overflow. The accepted prefix is never +// overwritten: the first record (a local holder) survives, the rejected report is not applied, and +// the replay of the whole prefix keeps arrival order through repeated durable evictions. +TEST_F(ReferenceChainsBfsTest, AnchorJournalExactCapacityFirstOverAndSustainedOverflow) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr size_t kCapacity = AnchorObservationBuffer::CAPACITY; + const jlong kContainer = -3101; + AnchorAcc::primeClassShapeForTest(kContainer, true); + const jlong first_tag = 20000; + // kCapacity - 1 durable rediscoveries behind the first (local) record, plus two entries for + // the rejected reports. + insertRootAttachedDurableEntries(frontier, first_tag, kCapacity + 1); + const size_t accepted_durable = kCapacity - 1; + const jlong rejected_tag = first_tag + (jlong)accepted_durable; + const jlong rejected_tag2 = rejected_tag + 1; + + auto overflowed = std::make_unique(tracker, frontier); + AnchorScopedPass &pass = *overflowed; + const jlong local = reportFreshLocal(pass, kContainer); + ASSERT_GT(local, 0); + for (size_t i = 0; i < accepted_durable; i++) { + reportRediscovery(pass, first_tag + (jlong)i); + } + // Exactly at capacity: every report was accepted and nothing overflowed. + ASSERT_EQ(kCapacity, (size_t)AnchorAcc::journalCountForTest()); + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_FALSE(pass.ctx.truncated); + EXPECT_FALSE(pass.scope.observeReturn()); + + // First over: aborts without recording, flags the overflow (not a frontier cap) and leaves the + // reported tag in place. + jlong over = rejected_tag; + EXPECT_EQ(JVMTI_ITERATION_ABORT, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &over)); + EXPECT_EQ(rejected_tag, over); + EXPECT_TRUE(pass.ctx.anchor_observation_overflow); + EXPECT_TRUE(pass.ctx.truncated); + EXPECT_FALSE(pass.ctx.frontier_cap_hit); + EXPECT_TRUE(pass.scope.observeReturn()); + EXPECT_EQ(kCapacity, (size_t)AnchorAcc::journalCountForTest()); + + // Sustained overflow: later reports of every kind abort without admission, upgrade or record. + const size_t frontier_size = frontier->size(); + for (int i = 0; i < 3; i++) { + jlong again = rejected_tag2; + EXPECT_EQ(JVMTI_ITERATION_ABORT, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &again)); + jlong fresh_local = 0; + EXPECT_EQ(JVMTI_ITERATION_ABORT, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &fresh_local)); + EXPECT_EQ(0, fresh_local) << "an overflowed report must not be admitted"; + jlong edge = rejected_tag2; + EXPECT_EQ(JVMTI_VISIT_ABORT, pass.staticEdge(&edge)); + } + EXPECT_EQ(frontier_size, (size_t)frontier->size()); + EXPECT_EQ(kCapacity, (size_t)AnchorAcc::journalCountForTest()); + EXPECT_EQ(0u, AnchorAcc::anchorIndexSizeForTest()); // nothing applied before the flush + + pass.scope.flush(); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + EXPECT_FALSE(pass.scope.observeReturn()); // the flush reset the overflow latch + + // No overwrite: the first record's local holder is still indexed in the local share, the + // rejected tags never were. + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(local)); + EXPECT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(rejected_tag)); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(rejected_tag2)); + // Arrival-order replay through the durable cap: model the helper's insert-then-evict rule. + const size_t cap = AnchorAcc::kDurableAnchorIndexCap; + const size_t batch = AnchorAcc::kDurableAnchorEvictBatch; + size_t survivors = 0; + for (size_t i = 0; i < accepted_durable; i++) { + survivors++; + if (survivors > cap) { + survivors -= survivors - cap + batch; + } + } + EXPECT_EQ(survivors, AnchorAcc::durableAnchorCountForTest()); + for (size_t i = 0; i < accepted_durable; i++) { + EXPECT_EQ(i >= accepted_durable - survivors, + AnchorAcc::anchorIndexContainsForTest(first_tag + (jlong)i)) + << "durable record " << i; + } + + // The next traversal (a fresh context and scope, as in production) accepts the rejected tag. + overflowed.reset(); + AnchorScopedPass retry(tracker, frontier); + reportRediscovery(retry, rejected_tag); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + retry.scope.flush(); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(rejected_tag)); + + tracker->stop(); +} + +namespace { + +// Fills the journal to exactly its capacity with LOCAL records of a class the shape cache does not +// know (replay parks at most the pending-buffer cap and drops the rest: no durable evictions). +void fillJournalWithUnknownLocals(AnchorScopedPass &pass) { + for (size_t i = 0; i < AnchorObservationBuffer::CAPACITY; i++) { + ASSERT_GT(reportFreshLocal(pass, -3999), 0); + } + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, + (size_t)ReferenceChainsTestAccessor::journalCountForTest()); + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0); +} + +// A stable durable population at the journal capacity is re-reported by every enumeration. Before +// the indexed-tag gate its re-enlist records refilled the journal at the same prefix every pass: +// the overflow aborted at the same report, _root_enum_incomplete latched, and no later root was +// ever reached. The gate must keep the repeat reports slot-free so the next enumeration admits +// the late root. +TEST_F(ReferenceChainsBfsTest, AnchorJournalStablePopulationLeavesSlotsForLaterRoots) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr size_t kCapacity = AnchorObservationBuffer::CAPACITY; + const jlong first_tag = 20000; + // The stable population plus one late root reported behind it. + insertRootAttachedDurableEntries(frontier, first_tag, kCapacity + 1); + + // First enumeration: nothing is indexed yet, so every report stages a record and the replay + // indexes the whole population through the durable cap (evicting its oldest share). + { + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < kCapacity; i++) { + reportRediscovery(pass, first_tag + (jlong)i); + } + ASSERT_EQ(kCapacity, (size_t)AnchorAcc::journalCountForTest()); + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + pass.scope.flush(); + } + const size_t indexed = AnchorAcc::anchorIndexSizeForTest(); + EXPECT_GT(indexed, (size_t)0); + EXPECT_LT(indexed, kCapacity); // the durable cap evicted the oldest share + + // Second enumeration: the indexed share stages nothing; only the evicted holders re-enlist. + // The journal must stay below capacity and admit the late root. + AnchorScopedPass retry(tracker, frontier); + for (size_t i = 0; i < kCapacity; i++) { + reportRediscovery(retry, first_tag + (jlong)i); + } + EXPECT_FALSE(retry.ctx.anchor_observation_overflow); + EXPECT_EQ(kCapacity - indexed, (size_t)AnchorAcc::journalCountForTest()); + const jlong late = first_tag + (jlong)kCapacity; + reportRediscovery(retry, late); + EXPECT_FALSE(retry.ctx.anchor_observation_overflow); + retry.scope.flush(); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(late)); + + tracker->stop(); +} + +// Root retries keep accepted durable reports complete when callback order changes. +TEST_F(ReferenceChainsBfsTest, RootEnumerationProgressSurvivesRepeatedAnchorJournalOverflow) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr size_t kJournalCapacity = AnchorObservationBuffer::CAPACITY; + constexpr size_t kRootCount = 2 * kJournalCapacity + 1; + const jlong first_tag = 20000; + const std::vector root_tags = + insertRootAttachedDurableEntries(frontier, first_tag, kRootCount); + std::vector root_nodes; + root_nodes.reserve(kRootCount); + script.reserve(kRootCount); + for (size_t i = 0; i < kRootCount; i++) { + const int node = addNode(); + root_nodes.push_back(node); + node_tags[node] = root_tags[i]; + script.push_back({JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, node, -1}); + } + // Keep the search active after the final complete root enumeration to inspect the retained index. + AnchorAcc::setCandidateCountForTest(1); + AnchorAcc::setCandidateKlassIdForTest(0, 999); + + bool truncated = false; + t8AllowRootEnumeration(); + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_TRUE(truncated); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest( + root_tags[kJournalCapacity - 1])); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest( + root_tags[kJournalCapacity])); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, active_fixture->last_ior_control); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + + // The retry skips completed tag observations and reaches the next journal-sized segment. + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_TRUE(truncated); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest( + root_tags[2 * kJournalCapacity - 1])); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest( + root_tags[2 * kJournalCapacity])); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, active_fixture->last_ior_control); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + + // The final root was rejected; the next retry skips completed tags and indexes it. A pass's + // truncated flag may also come from the unrelated static-field sweep, so membership proves it. + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + const int late_node = root_nodes.back(); + EXPECT_EQ(root_tags.back(), tags_ever_assigned[late_node]); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(root_tags.back())); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, StaticSweepProgressSurvivesIndexEviction) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr size_t capacity = AnchorObservationBuffer::CAPACITY; + constexpr u32 first_attempt = + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 1U; + const jlong first_tag = 22000; + for (size_t i = 0; i < 2 * capacity + 1; i++) { + insertAnchorEntry(frontier, first_tag + (jlong)i, 0, + JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + + { + AnchorScopedPass first(tracker, frontier); + first.ctx.static_field_seed = true; + first.ctx.root_report_attempt_id = first_attempt; + for (size_t i = 0; i < capacity; i++) { + jlong tag = first_tag + (jlong)i; + ASSERT_EQ(JVMTI_VISIT_OBJECTS, first.staticEdge(&tag)); + } + ASSERT_EQ(capacity, AnchorAcc::journalCountForTest()); + jlong rejected = first_tag + (jlong)capacity; + EXPECT_EQ(JVMTI_VISIT_ABORT, first.staticEdge(&rejected)); + first.scope.flush(); + } + EXPECT_LT(AnchorAcc::durableAnchorCountForTest(), capacity); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(first_tag)); + + { + AnchorScopedPass retry(tracker, frontier); + retry.ctx.static_field_seed = true; + retry.ctx.root_report_attempt_id = first_attempt + 1; + retry.ctx.root_report_previous_attempt_id = first_attempt; + retry.ctx.root_report_retrying_incomplete = true; + for (size_t i = 0; i < 2 * capacity; i++) { + jlong tag = first_tag + (jlong)i; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, retry.staticEdge(&tag)); + } + EXPECT_EQ(capacity, AnchorAcc::journalCountForTest()) + << "the accepted first chunk must not be restaged after eviction"; + jlong second_rejected = first_tag + (jlong)(2 * capacity); + EXPECT_EQ(JVMTI_VISIT_ABORT, retry.staticEdge(&second_rejected)); + retry.scope.flush(); + } + + const jlong last = first_tag + (jlong)(2 * capacity); + { + AnchorScopedPass final(tracker, frontier); + final.ctx.static_field_seed = true; + final.ctx.root_report_attempt_id = first_attempt + 2; + final.ctx.root_report_previous_attempt_id = first_attempt + 1; + final.ctx.root_report_retrying_incomplete = true; + for (size_t i = 0; i < 2 * capacity; i++) { + jlong tag = first_tag + (jlong)i; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, final.staticEdge(&tag)); + } + jlong reported = last; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, final.staticEdge(&reported)); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + final.scope.flush(); + } + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(last)); + + tracker->stop(); +} + +// An incomplete retry sequence widens the recognized-stamp window to every attempt of the +// sequence: a report stamped by the sequence's FIRST attempt still suppresses restaging two +// attempts later (alternating oversized groups must not ping-pong each other out of the durable +// index). The window expires with the sequence: a completed sequence, or a range outside it, +// suppresses only on the current attempt's stamp. +TEST_F(ReferenceChainsBfsTest, RetrySequenceWindowRecognizesEverySequenceAttempt) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 21101; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + // Attempt 1 stamps the JNI report, then truncates (the sequence opens with base 1). + frontier->markRootReportObserved(tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 1); + // Attempt 2 (the immediate retry) suppresses via the previous-attempt window... + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 2, 1, true, nullptr, + /*static_sweep=*/false, /*retry_base_id=*/1)); + // ...and attempt 3 must STILL suppress the attempt-1 stamp via the sequence window. + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 3, 2, true, nullptr, + /*static_sweep=*/false, /*retry_base_id=*/1)) + << "a stamp from the sequence's first attempt must suppress within the sequence"; + // Outside the sequence (no open sequence): the old one-attempt window applies. + EXPECT_FALSE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 3, 2, true, nullptr, + /*static_sweep=*/false, /*retry_base_id=*/0)); + // The sequence completed: the suppression expires with it. + EXPECT_FALSE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 3, 2, false, nullptr, + /*static_sweep=*/false, /*retry_base_id=*/1)); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, DurableRootReportProgressStampBoundaries) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 21001; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + frontier->markRootReportObserved( + 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + frontier->markRootReportObserved( + -5, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + frontier->markRootReportObserved( + (jlong)INT_MAX + 1, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + const jlong past_end = (jlong)frontier->size() + 1; + frontier->markRootReportObserved( + past_end, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + frontier->markRootReportObserved(tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 0); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_EQ(0u, entry.root_report_attempt); + EXPECT_FALSE(frontier->lookup(past_end, &entry)); + EXPECT_FALSE(frontier->rootReportCompleted( + past_end, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, true, 7, 6, true)); + EXPECT_FALSE(frontier->rootReportCompleted( + (jlong)INT_MAX + 1, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, true, 7, 6, true)); + + frontier->markRootReportObserved(tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 7, 6, true)); + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 7, true)); + EXPECT_FALSE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 7, false)); + EXPECT_FALSE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 6, true)); + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, true, 0, 0, false)); + EXPECT_FALSE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_LOCAL, true, 7, 6, true)); + + const jlong static_tag = 21008; + insertAnchorEntry(frontier, static_tag, 0, + JVMTI_HEAP_REFERENCE_STATIC_FIELD); + bool weaker_root_noop = false; + EXPECT_FALSE(frontier->rootReportCompleted( + static_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 7, 6, true, + &weaker_root_noop)); + EXPECT_FALSE(weaker_root_noop); + frontier->markRootReportObserved( + static_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 7U, + /*static_sweep=*/true); + EXPECT_TRUE(frontier->rootReportCompleted( + static_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, false, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 8U, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 7U, true, + nullptr, /*static_sweep=*/true)); + weaker_root_noop = false; + // A stale static-sweep stamp alone no longer suppresses the weaker JNI report: after the + // static edge disappears and eviction drops the holder from the durable index, the JNI report + // is the only route back into indexed rotation (see rootReportCompleted()). + EXPECT_FALSE(frontier->rootReportCompleted( + static_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 8, false, + &weaker_root_noop)); + EXPECT_FALSE(weaker_root_noop); + // Index coverage still suppresses: the holder sits in the durable index, so the JNI report + // restages nothing. + EXPECT_TRUE(frontier->rootReportCompleted( + static_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, true, 9, 8, false, + &weaker_root_noop)); + EXPECT_TRUE(weaker_root_noop); + + insertAnchorEntry(frontier, 21007, 21001, JVMTI_HEAP_REFERENCE_STACK_LOCAL); + EXPECT_FALSE(frontier->rootReportCompleted( + 21007, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 0, 0, false)); + frontier->markRootReportObserved( + 21007, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 9); + frontier->markRootReportObserved( + 21007, JVMTI_HEAP_REFERENCE_STATIC_FIELD, 9); + EXPECT_TRUE(frontier->rootReportCompleted( + 21007, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 0, false)); + EXPECT_TRUE(frontier->rootReportCompleted( + 21007, JVMTI_HEAP_REFERENCE_STATIC_FIELD, false, 9, 0, false)); + EXPECT_TRUE(frontier->rootReportCompleted( + 21007, JVMTI_HEAP_REFERENCE_JNI_LOCAL, true, 0, 0, false)); + + const jlong chain_static_tag = 21009; + insertAnchorEntry(frontier, chain_static_tag, 21001, + JVMTI_HEAP_REFERENCE_STACK_LOCAL); + frontier->markRootReportObserved( + chain_static_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 11U, + /*static_sweep=*/true); + frontier->markRootReportObserved( + chain_static_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 12); + EXPECT_TRUE(frontier->rootReportCompleted( + chain_static_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, false, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 12U, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 11U, true, + nullptr, true)); + EXPECT_TRUE(frontier->rootReportCompleted( + chain_static_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 13, 12, + true)); + + tracker->stop(); +} + +// A stale static-sweep stamp alone no longer suppresses the weaker JNI report: after the static +// edge disappears and eviction drops the holder from the durable index, the JNI report is the only +// route back into indexed rotation, so it stages a re-enlistment observation even though the old +// sweep stamp is still on the frontier entry. +TEST_F(ReferenceChainsBfsTest, WeakerJniGlobalReportStagesDespiteStaleSweepStamp) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 21009; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->markRootReportObserved( + tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 1U, + /*static_sweep=*/true); + + AnchorScopedPass pass(tracker, frontier); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY - 1, + AnchorAcc::fillAnchorJournalForTest( + pass.ctx, AnchorObservationBuffer::CAPACITY - 1)); + jlong reported = tag; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, 0, &reported)); + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::journalCountForTest()) + << "the stale sweep stamp must not suppress the JNI re-enlistment observation"; + pass.scope.flush(); + + tracker->stop(); +} + +// A static-sweep stamp must never displace a stored enumeration stamp: both share +// root_report_attempt, and the sweep's high-bit id falls outside root enumeration's retry-sequence +// window, so the overwrite would restage the weaker JNI-global report on every retry - the exact +// starvation the stamp machinery prevents. +TEST_F(ReferenceChainsBfsTest, SweepStampDoesNotDisplaceEnumerationStamp) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + // Root-attached static holder (the shape whose sweep stamp takes the shared field): the + // enumeration accepts its weaker JNI-global report first. + const jlong tag = 21021; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->markRootReportObserved(tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 7); + + // The sweep arrives between enumeration attempts: it must keep the enumeration stamp. + frontier->markRootReportObserved( + tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 40U, + /*static_sweep=*/true); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_EQ(7u, entry.root_report_attempt) + << "a sweep stamp must not clobber the enumeration stamp"; + EXPECT_TRUE(entry.root_report_kind_mask & + FrontierRootReport::JNI_GLOBAL_MASK); + + // The retry sequence still recognizes the stamp: the weaker JNI-global report stays + // suppressed instead of restaging on every attempt. + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 8, 7, true)); + EXPECT_TRUE(frontier->rootReportCompleted( + tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, false, 9, 7, true)); + + // A re-inserted slot starts fresh: insert() clears the sweep stamp with its siblings, or a + // restarted search reusing the slot would inherit the previous search's stamp and + // false-suppress its first sweep. + const jlong reuse_tag = 21023; + insertAnchorEntry(frontier, reuse_tag, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->markRootReportObserved( + reuse_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 61U, + /*static_sweep=*/true); + { + FrontierEntry stamped{}; + ASSERT_TRUE(frontier->lookup(reuse_tag, &stamped)); + EXPECT_NE(0u, stamped.root_report_sweep_attempt); + } + insertAnchorEntry(frontier, reuse_tag, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + { + FrontierEntry recycled{}; + ASSERT_TRUE(frontier->lookup(reuse_tag, &recycled)); + EXPECT_EQ(0u, recycled.root_report_sweep_attempt) + << "insert() must clear the sweep stamp like every other stamp"; + } + + // A root-attached entry with no enumeration stamp keeps its sweep suppression through + // the parallel sweep field (chain-attached entries use referrer_class_tag instead). + const jlong free_tag = 21022; + insertAnchorEntry(frontier, free_tag, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->markRootReportObserved( + free_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 41U, + /*static_sweep=*/true); + EXPECT_TRUE(frontier->rootReportCompleted( + free_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD, false, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 42U, + FrontierRootReport::STATIC_SWEEP_ATTEMPT_BIT | 41U, true, + nullptr, /*static_sweep=*/true)); + + tracker->stop(); +} + +// LOCAL staging cannot exceed replay capacity or refill the same journal prefix on every retry. +// At zero budget, fresh locals stay unstaged while a durable root report in the same scope still +// stages; this keeps refused locals from starving later roots. +TEST_F(ReferenceChainsBfsTest, LocalStagingBoundStopsRecordsReplayWouldRefuse) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong kContainer = -3155; + AnchorAcc::primeClassShapeForTest(kContainer, true); + + // Fill the local index and pending buffer with confirmed containers. With no displaceable + // pending victim, replay cannot absorb further LOCAL reports. + { + AnchorScopedPass pass(tracker, frontier); + const int kSaturate = 4096 + 1024; + for (int i = 0; i < kSaturate; i++) { + jlong reported = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &reported)); + EXPECT_GT(reported, 0); + } + pass.scope.flush(); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + } + + // A fresh scope: the absorbable budget is zero. LOCAL reports of distinct fresh holders stage + // nothing; a durable root report still stages its re-enlist record. + AnchorScopedPass pass(tracker, frontier); + const int kOverflowAttempts = 64; + for (int i = 0; i < kOverflowAttempts; i++) { + jlong reported = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &reported)); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()) + << "a saturated absorbable budget stages no LOCAL records"; + } + insertAnchorEntry(frontier, 4242, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + jlong durable_tag = 4242; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, 0, &durable_tag)); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()) + << "the durable root still stages with the LOCAL budget exhausted"; + pass.scope.flush(); + + tracker->stop(); +} + +// The budget includes all entries the eviction cursor can skip to, without scanning the buffer. +TEST_F(ReferenceChainsBfsTest, LocalStagingBudgetCountsDisplaceablePendingEntries) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong kContainer = -3156; + const jlong kUnclassified = -3157; + const jlong kUnclassifiedTag = 50000; + AnchorAcc::primeClassShapeForTest(kContainer, true); + for (size_t i = 0; i < AnchorAcc::kLocalAnchorIndexCap; i++) { + AnchorAcc::noteLocalRootHolderForTest(10000 + (jlong)i, kContainer); + } + ASSERT_EQ(AnchorAcc::kLocalAnchorIndexCap, AnchorAcc::localAnchorCountForTest()); + AnchorAcc::noteLocalRootHolderForTest(kUnclassifiedTag, kUnclassified); + for (size_t i = 0; i < AnchorAcc::kPendingLocalAnchorCap - 1; i++) { + AnchorAcc::noteLocalRootHolderForTest(60000 + (jlong)i, kContainer); + } + ASSERT_EQ(AnchorAcc::kPendingLocalAnchorCap, + AnchorAcc::pendingLocalAnchorCountForTest()); + AnchorAcc::preparePendingLocalAnchorEvictionCursorForTest(); + EXPECT_EQ(1u, AnchorAcc::localStagingAbsorbableForTest()); + + AnchorScopedPass pass(tracker, frontier); + jlong accepted_tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &accepted_tag)); + ASSERT_GT(accepted_tag, 0); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + + jlong unstaged_tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &unstaged_tag)); + ASSERT_GT(unstaged_tag, 0); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + + pass.scope.flush(); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(kUnclassifiedTag)); + EXPECT_TRUE(AnchorAcc::pendingLocalAnchorContainsForTest(accepted_tag)); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(unstaged_tag)); + EXPECT_EQ(0u, AnchorAcc::localStagingAbsorbableForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, UnclassifiedLocalsCannotSpendContainerIndexBudget) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong unclassified = -3158; + const jlong container = -3159; + AnchorAcc::primeClassShapeForTest(container, true); + AnchorScopedPass pass(tracker, frontier); + const size_t pending_cap = AnchorAcc::kPendingLocalAnchorCap; + const size_t index_cap = AnchorAcc::kLocalAnchorIndexCap; + + for (size_t i = 0; i < pending_cap + index_cap; i++) { + jlong tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, unclassified, &tag)); + } + EXPECT_EQ(pending_cap, AnchorAcc::journalCountForTest()) + << "unclassified holders can consume pending slots only"; + + std::vector confirmed; + confirmed.reserve(index_cap); + for (size_t i = 0; i < index_cap; i++) { + jlong tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, container, &tag)); + confirmed.push_back(tag); + } + EXPECT_EQ(pending_cap + index_cap, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(pending_cap, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_EQ(index_cap, AnchorAcc::localAnchorCountForTest()); + for (jlong tag : confirmed) { + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(tag)); + } + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, LeakTaggedLocalCollectionGetsAnAnchorObservation) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + const jlong container = -3160; + AnchorAcc::primeClassShapeForTest(container, true); + + AnchorScopedPass pass(tracker, tracker->frontierTable()); + jlong leak_tag = AnchorAcc::leakTagForTest(7); + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, container, &leak_tag)); + ASSERT_GT(leak_tag, 0); + EXPECT_NE(AnchorAcc::leakTagForTest(7), leak_tag); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(leak_tag)); + EXPECT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + + tracker->stop(); +} + +// A local holder whose class is already classified non-container replays as a pure no-op +// (noteLocalRootHolder() returns before any state change): the LOCAL gate must not stage it, so +// a stable non-container local population never occupies journal slots. +TEST_F(ReferenceChainsBfsTest, AnchorJournalClassifiedNonContainerLocalStagesNothing) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong kNonContainer = -3102; + AnchorAcc::primeClassShapeForTest(kNonContainer, false); + + const jlong local = [&] { + AnchorScopedPass pass(tracker, frontier); + const jlong local = reportFreshLocal(pass, kNonContainer); + EXPECT_GT(local, 0); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + return local; + }(); + ASSERT_GT(local, 0); + EXPECT_EQ(0u, AnchorAcc::anchorIndexSizeForTest()); + + // Re-report the same admitted tag at a full journal: it must not abort as a no-op. + AnchorScopedPass retry(tracker, frontier); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::fillAnchorJournalForTest( + retry.ctx, AnchorObservationBuffer::CAPACITY)); + jlong tag = local; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + retry.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kNonContainer, &tag)); + EXPECT_EQ(local, tag); + EXPECT_FALSE(retry.ctx.anchor_observation_overflow); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::journalCountForTest()); + retry.scope.flush(); + + tracker->stop(); +} + +// An unclassified local holder parks on its first report (a real effect); the re-report finds it +// already parked and must not stage a second record for it. +TEST_F(ReferenceChainsBfsTest, AnchorJournalParkedLocalRestagesNothing) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong local = [&] { + AnchorScopedPass pass(tracker, frontier); + const jlong local = reportFreshLocal(pass, -3999); + EXPECT_GT(local, 0); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + return local; + }(); + ASSERT_GT(local, 0); + ASSERT_EQ(0u, AnchorAcc::anchorIndexSizeForTest()); + ASSERT_EQ(1u, AnchorAcc::pendingLocalAnchorCountForTest()); + + AnchorScopedPass retry(tracker, frontier); + jlong tag = local; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + retry.root(JVMTI_HEAP_ROOT_STACK_LOCAL, -3999, &tag)); + EXPECT_EQ(local, tag); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + EXPECT_EQ(1u, AnchorAcc::pendingLocalAnchorCountForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AnchorJournalFullPendingBufferSkipsUnknownLocalNoops) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong unknown = -4101; + const size_t cap = AnchorAcc::kPendingLocalAnchorCap; + + for (size_t i = 0; i < cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(50000 + (jlong)i, unknown); + } + ASSERT_EQ(cap, AnchorAcc::pendingLocalAnchorCountForTest()); + + AnchorScopedPass pass(tracker, frontier); + jlong tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, unknown, &tag)); + ASSERT_GT(tag, 0); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(cap, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(tag)); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AnchorJournalFullConfirmedPendingWithNoVictimSkipsLocalNoop) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong container = -4102; + const size_t local_cap = AnchorAcc::kLocalAnchorIndexCap; + const size_t pending_cap = AnchorAcc::kPendingLocalAnchorCap; + AnchorAcc::primeClassShapeForTest(container, true); + + for (size_t i = 0; i < local_cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(60000 + (jlong)i, container); + } + for (size_t i = 0; i < pending_cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(70000 + (jlong)i, container); + } + ASSERT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + ASSERT_EQ(pending_cap, AnchorAcc::pendingLocalAnchorCountForTest()); + + AnchorScopedPass pass(tracker, frontier); + ASSERT_EQ(pending_cap, AnchorAcc::pendingLocalEvictCursorForTest()); + jlong tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, container, &tag)); + ASSERT_GT(tag, 0); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(pending_cap, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(tag)); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AnchorJournalFullPendingWithVictimStagesConfirmedLocal) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong container = -4103, unknown = -4104; + const size_t local_cap = AnchorAcc::kLocalAnchorIndexCap; + const size_t pending_cap = AnchorAcc::kPendingLocalAnchorCap; + AnchorAcc::primeClassShapeForTest(container, true); + + for (size_t i = 0; i < local_cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(80000 + (jlong)i, container); + } + for (size_t i = 0; i < pending_cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(90000 + (jlong)i, unknown); + } + ASSERT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + ASSERT_EQ(pending_cap, AnchorAcc::pendingLocalAnchorCountForTest()); + + AnchorScopedPass pass(tracker, frontier); + ASSERT_EQ(0u, AnchorAcc::pendingLocalEvictCursorForTest()); + jlong tag = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, container, &tag)); + ASSERT_GT(tag, 0); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(tag, AnchorAcc::pendingLocalAnchorTagForTest(0)); + EXPECT_EQ(1u, AnchorAcc::pendingLocalEvictCursorForTest()); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(90000)); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AnchorJournalSkipsAlreadyQueuedAtRiskNoop) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong non_container = -4105; + const jlong holder = 20001; + AnchorAcc::primeClassShapeForTest(-555, false); + insertAnchorEntry(frontier, holder, 20000, JVMTI_HEAP_REFERENCE_STACK_LOCAL, + non_container); + AnchorAcc::pushStaticAnchorFifoForTest(holder, 0); + + AnchorScopedPass pass(tracker, frontier); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::fillAnchorJournalForTest( + pass.ctx, AnchorObservationBuffer::CAPACITY)); + jlong tag = holder; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, pass.staticEdge(&tag)); + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::journalCountForTest()); + EXPECT_TRUE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + pass.scope.flush(); + EXPECT_EQ(1u, AnchorAcc::staticAnchorFifoSizeForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AtRiskObservationGateHonorsQueueAndClassCaps) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + const size_t fifo_cap = AnchorAcc::priorityExpandCap(); + const u32 klass_cap = AnchorAcc::kAtRiskPerKlassCap; + + EXPECT_TRUE(AnchorAcc::atRiskAnchorNeedsObservationForTest(1, 42)); + for (u32 i = 0; i < klass_cap; i++) { + AnchorAcc::pushStaticAnchorFifoForTest(100 + (jlong)i, 42); + } + EXPECT_FALSE(AnchorAcc::atRiskAnchorNeedsObservationForTest(1000, 42)); + EXPECT_TRUE(AnchorAcc::atRiskAnchorNeedsObservationForTest(1000, 43)); + + for (size_t i = 0; i < fifo_cap - klass_cap; i++) { + u32 klass_id = 100 + (u32)(i / klass_cap); + AnchorAcc::pushStaticAnchorFifoForTest(2000 + (jlong)i, klass_id); + } + ASSERT_EQ(fifo_cap, AnchorAcc::staticAnchorFifoSizeForTest()); + EXPECT_FALSE(AnchorAcc::atRiskAnchorNeedsObservationForTest(5000, 999)); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, StagedAtRiskReportsRespectPerClassQuota) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -4200; + constexpr u32 klass_id = 42; + tracker->classTags()->insert(class_tag, klass_id); + const size_t cap = AnchorAcc::kAtRiskPerKlassCap; + for (size_t i = 0; i < cap + 8; i++) { + insertAnchorEntry(frontier, 30000 + (jlong)i, 20000, + JVMTI_HEAP_REFERENCE_STACK_LOCAL, class_tag); + } + + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < cap + 8; i++) { + jlong tag = 30000 + (jlong)i; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, + AnchorAcc::reportStaticFieldEdgeForTest( + -555, &tag, &pass.ctx, class_tag)); + } + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(cap, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(cap, AnchorAcc::staticAnchorFifoSizeForTest()); + + std::vector drained; + EXPECT_EQ(1, AnchorAcc::drainStaticAnchorFifoForTest(1, drained)); + jlong reopened = 30000 + (jlong)(cap + 8); + insertAnchorEntry(frontier, reopened, 20000, JVMTI_HEAP_REFERENCE_STACK_LOCAL, + class_tag); + EXPECT_EQ(JVMTI_VISIT_OBJECTS, + AnchorAcc::reportStaticFieldEdgeForTest( + -555, &reopened, &pass.ctx, class_tag)); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(cap, AnchorAcc::staticAnchorFifoSizeForTest()); + + tracker->stop(); +} + +// Rejected per-klass staging must not consume scope class-set slots: a klass whose scope-local +// staging reached its per-klass cap rejects further records without claiming class-set slots, so +// another class keeps staging into the same scope afterwards (and the fixed table cannot fill up +// with zero-count claims). +TEST_F(ReferenceChainsBfsTest, RejectedAtRiskStagingKeepsClassSetSlotsForOtherClasses) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const size_t cap = AnchorAcc::kAtRiskPerKlassCap; + const jlong class_tag_a = -4200; + const jlong class_tag_b = -4201; + tracker->classTags()->insert(class_tag_a, 42); + tracker->classTags()->insert(class_tag_b, 43); + // Per-klass cap anchors for A, then far more A anchors than the cap: the excess must be + // REJECTED (not staged), and the rejections must not erode the class set. + for (size_t i = 0; i < cap + 200; i++) { + insertAnchorEntry(frontier, 30000 + (jlong)i, 20000, + JVMTI_HEAP_REFERENCE_STACK_LOCAL, class_tag_a); + } + const jlong b_tag = 31000; + insertAnchorEntry(frontier, b_tag, 20000, + JVMTI_HEAP_REFERENCE_STACK_LOCAL, class_tag_b); + + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < cap + 200; i++) { + jlong tag = 30000 + (jlong)i; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, + AnchorAcc::reportStaticFieldEdgeForTest( + -555, &tag, &pass.ctx, class_tag_a)); + } + EXPECT_EQ(cap, AnchorAcc::journalCountForTest()) + << "only the per-klass cap's worth of A records may stage"; + + // A different class stages into the same scope after all those rejections. + jlong b_reported = b_tag; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, + AnchorAcc::reportStaticFieldEdgeForTest( + -555, &b_reported, &pass.ctx, class_tag_b)); + EXPECT_EQ(cap + 1, AnchorAcc::journalCountForTest()) + << "the rejected A records must not have burned class-set slots"; + pass.scope.flush(); + EXPECT_EQ(cap + 1, AnchorAcc::staticAnchorFifoSizeForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, StagedAtRiskReportsRespectGlobalFifoQuota) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const size_t cap = AnchorAcc::priorityExpandCap(); + for (size_t i = 0; i < cap + 1; i++) { + jlong class_tag = -50000 - (jlong)i; + tracker->classTags()->insert(class_tag, (u32)i + 1); + insertAnchorEntry(frontier, 40000 + (jlong)i, 20000, + JVMTI_HEAP_REFERENCE_STACK_LOCAL, class_tag); + } + + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < cap + 1; i++) { + jlong class_tag = -50000 - (jlong)i; + jlong tag = 40000 + (jlong)i; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, + AnchorAcc::reportStaticFieldEdgeForTest( + -555, &tag, &pass.ctx, class_tag)); + } + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(cap, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + EXPECT_EQ(cap, AnchorAcc::staticAnchorFifoSizeForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, AnchorJournalDeduplicatesLocalAndAtRiskWithinScope) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong unknown = -4106; + const jlong non_container = -555; + const jlong holder = 20002; + AnchorAcc::primeClassShapeForTest(non_container, false); + insertAnchorEntry(frontier, holder, 20000, JVMTI_HEAP_REFERENCE_STACK_LOCAL, + non_container); + + AnchorScopedPass pass(tracker, frontier); + jlong local = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, unknown, &local)); + ASSERT_GT(local, 0); + jlong at_risk = holder; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, pass.staticEdge(&at_risk)); + ASSERT_EQ(2u, AnchorAcc::journalCountForTest()); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::fillAnchorJournalForTest( + pass.ctx, AnchorObservationBuffer::CAPACITY)); + for (int i = 0; i < 8; i++) { + jlong repeated = local; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, unknown, &repeated)); + EXPECT_EQ(JVMTI_VISIT_OBJECTS, pass.staticEdge(&at_risk)); + } + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, + AnchorAcc::journalCountForTest()); + EXPECT_FALSE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + pass.scope.flush(); + EXPECT_TRUE(AnchorAcc::pendingLocalAnchorContainsForTest(local)); + EXPECT_TRUE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + + tracker->stop(); +} + +} // namespace + +// A full journal rejecting a STATIC-FIELD report requests exactly one static-scan retry for the +// whole traversal (not one per rejected report), applied after the accepted prefix. +TEST_F(ReferenceChainsBfsTest, AnchorOverflowOnStaticReportRequestsOneStaticRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong static_holder = 60001; + insertAnchorEntry(frontier, static_holder, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + const u64 gen = AnchorAcc::durableAnchorResweepGenForTest(); + + // Unbounded LOCAL staging: this test exercises the journal's own capacity mechanics, while + // production bounds staging to what replay absorbs (localStagingAbsorbable()). + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0xFFFFFFFFu); + AnchorScopedPass pass(tracker, frontier); + fillJournalWithUnknownLocals(pass); + for (int i = 0; i < 2; i++) { + jlong tag = static_holder; + EXPECT_EQ(JVMTI_VISIT_ABORT, pass.staticEdge(&tag)); + } + EXPECT_TRUE(pass.ctx.anchor_observation_overflow); + EXPECT_EQ(gen, AnchorAcc::durableAnchorResweepGenForTest()); // nothing applied before flush + pass.scope.flush(); + EXPECT_EQ(gen + 1, AnchorAcc::durableAnchorResweepGenForTest()); + EXPECT_TRUE(AnchorAcc::durableAnchorResweepUnservedForTest()); + // The accepted prefix was applied: the unknown locals parked in the capped pending buffer. + EXPECT_EQ(AnchorAcc::kPendingLocalAnchorCap, AnchorAcc::pendingLocalAnchorCountForTest()); + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, ReenlistedAnchorsKeepEveryFirstRotationTurn) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr int kHolders = 9000; + std::vector served(kHolders + 1, false); + int served_count = 0; + for (int tag = 1; tag <= kHolders; tag++) { + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + AnchorAcc::addToStaticAnchorIndexForTest( + tag, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + + for (int pass = 0; pass < 1000 && served_count < kHolders; pass++) { + for (int tag = 1; tag <= kHolders; tag++) { + if (!AnchorAcc::anchorIndexContainsForTest(tag)) { + AnchorAcc::addToStaticAnchorIndexForTest( + tag, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + } + std::vector selected = + AnchorAcc::collectStaticFieldAnchorsForRotationForTest(32); + for (jlong tag : selected) { + ASSERT_GT(tag, 0); + ASSERT_LE(tag, kHolders); + if (!served[(size_t)tag]) { + served[(size_t)tag] = true; + served_count++; + } + } + } + EXPECT_EQ(kHolders, served_count) + << "every live durable holder must retain a first-look turn across eviction"; + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, DurableAnchorIndexEvictionKeepsPendingFirstLooks) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const size_t cap = AnchorAcc::kDurableAnchorIndexCap; + const size_t batch = AnchorAcc::kDurableAnchorEvictBatch; + const jlong first = 1001; + + for (size_t i = 0; i <= cap; i++) { + jlong tag = first + (jlong)i; + insertAnchorEntry(frontier, tag, 0, + JVMTI_HEAP_REFERENCE_STATIC_FIELD); + AnchorAcc::addToStaticAnchorIndexForTest( + tag, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + EXPECT_EQ(cap - batch, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(cap - batch, AnchorAcc::anchorOwnClassTagsSizeForTest()); + for (size_t i = 0; i < batch + 1; i++) { + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(first + (jlong)i)); + } + EXPECT_TRUE(AnchorAcc::freshAnchorQueueContainsForTest(first)) + << "the evicted oldest holder keeps its unserved first look"; + EXPECT_FALSE(AnchorAcc::freshAnchorQueueContainsForTest(first + (jlong)cap)) + << "the bounded queue drops newest turns"; + EXPECT_LE(AnchorAcc::freshAnchorQueueSizeForTest(), + AnchorAcc::freshAnchorQueueCapForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, LocalThenDurableReportKeepsFirstLookOrder) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong container = -3101; + AnchorAcc::primeClassShapeForTest(container, true); + const jlong earlier = 30001; + insertAnchorEntry(frontier, earlier, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + AnchorAcc::addToStaticAnchorIndexForTest( + earlier, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + AnchorScopedPass pass(tracker, frontier); + jlong holder = 0; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, container, &holder)); + ASSERT_GT(holder, 0); + jlong again = holder; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, container, &again)); + EXPECT_EQ(2u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + + EXPECT_EQ(2u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ((std::vector{earlier, holder}), + AnchorAcc::freshQueueTagsForTest()); + ASSERT_TRUE(frontier->improveChain(holder, earlier, 0, 1, 0)); + std::vector selected = + AnchorAcc::collectStaticFieldAnchorsForRotationForTest(8); + EXPECT_NE(std::find(selected.begin(), selected.end(), holder), + selected.end()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, ReenlistedPendingTurnKeepsItsQueuePosition) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const size_t cap = AnchorAcc::kDurableAnchorIndexCap; + const size_t batch = AnchorAcc::kDurableAnchorEvictBatch; + const jlong victim = 20001; + const jlong crossing = 20002; + insertAnchorEntry(frontier, victim, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + insertAnchorEntry(frontier, crossing, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + AnchorAcc::addToStaticAnchorIndexForTest( + victim, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + for (size_t i = 0; i < cap - 1; i++) { + AnchorAcc::addToStaticAnchorIndexForTest( + 40000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + + { + AnchorScopedPass pass(tracker, frontier); + ASSERT_TRUE(pass.scope.ownsLease()); + jlong reported = crossing; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, -3001, &reported)) + << "journal=" << AnchorAcc::journalCountForTest() + << " overflow=" << pass.ctx.anchor_observation_overflow; + EXPECT_EQ(crossing, reported); + pass.scope.flush(); + } + EXPECT_EQ(cap - batch, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(victim)); + ASSERT_GE(AnchorAcc::freshAnchorQueueSizeForTest(), 2u); + EXPECT_EQ(victim, AnchorAcc::freshQueueTagsForTest().front()); + + { + AnchorScopedPass retry(tracker, frontier); + ASSERT_TRUE(retry.scope.ownsLease()); + jlong reported = victim; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + retry.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, -3001, &reported)) + << "journal=" << AnchorAcc::journalCountForTest() + << " overflow=" << retry.ctx.anchor_observation_overflow; + EXPECT_EQ(victim, reported); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + retry.scope.flush(); + } + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(victim)); + EXPECT_EQ(victim, AnchorAcc::freshQueueTagsForTest().front()); + EXPECT_EQ(crossing, AnchorAcc::freshQueueTagsForTest()[1]); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, ReplayedDurableWaveKeepsEvictedTurnsPending) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const size_t cap = AnchorAcc::kDurableAnchorIndexCap; + const size_t batch = AnchorAcc::kDurableAnchorEvictBatch; + const jlong first = 20000; + insertRootAttachedDurableEntries(frontier, first, cap + 1); + + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i <= cap; i++) { + reportRediscovery(pass, first + (jlong)i); + } + pass.scope.flush(); + EXPECT_EQ(cap - batch, AnchorAcc::durableAnchorCountForTest()); + bool found_evicted_pending = false; + for (jlong tag : AnchorAcc::freshQueueTagsForTest()) { + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_NE(0, entry.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + if (!AnchorAcc::anchorIndexContainsForTest(tag)) { + found_evicted_pending = true; + } + } + EXPECT_TRUE(found_evicted_pending); + + tracker->stop(); +} + +// The root-enumeration stamp dedup suppresses a repeated durable report on an indexed holder +// (rootReportCompleted()'s anchor_indexed disjunct). When the index still stores the +// admission-time class tag 0 and this report carries the resolved tag, the callback must journal +// the re-enlist so replay's 0-to-resolved upgrade runs - otherwise selection cannot recognize +// the reparented holder's collection shape and persistent revisits stop. +TEST_F(ReferenceChainsBfsTest, SuppressedDurableReportStillRefreshesStoredClassTag) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 21001; + const jlong resolved_class = -3107; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + ASSERT_EQ(0, AnchorAcc::indexedAnchorClassTagForTest(tag)); + + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, tag, resolved_class); + pass.scope.flush(); + } + EXPECT_EQ(resolved_class, AnchorAcc::indexedAnchorClassTagForTest(tag)) + << "the suppressed report must still journal the 0-to-resolved refresh"; + + // A further report on the resolved holder is a plain dedup no-op: the stored tag is already + // resolved, so no refresh is journaled and the index state does not change. + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, tag, resolved_class); + pass.scope.flush(); + } + EXPECT_EQ(resolved_class, AnchorAcc::indexedAnchorClassTagForTest(tag)); + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + + tracker->stop(); +} + +// A locally indexed container sighted by a durable root edge promotes to the durable share: the +// callback journals the durable add even though the report itself is dedup-suppressed, and +// replay releases the local slot. Without it, a reparented holder consumes a local slot forever +// - 4,096 such holders block new local collections despite free durable capacity. +TEST_F(ReferenceChainsBfsTest, DurableSightingPromotesLocallyIndexedHolder) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 22001; + const jlong container_class = -3207; + insertAnchorEntry(frontier, tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class, true); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, container_class); + ASSERT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + ASSERT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, tag, container_class); + pass.scope.flush(); + } + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()) + << "the durable sighting must release the local slot"; + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()) + << "the holder stays indexed, now in the durable share"; + EXPECT_EQ(container_class, AnchorAcc::indexedAnchorClassTagForTest(tag)); + + tracker->stop(); +} + +// The re-enlist replay promotes a locally indexed holder the same way addToStaticAnchorIndex() +// does: the descent's durable-edge reports journal REENLIST_ELIGIBLE for indexed selectable +// holders, and that replay must release the local slot too. +TEST_F(ReferenceChainsBfsTest, ReenlistReplayPromotesLocallyIndexedHolder) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 22051; + const jlong container_class = -3208; + insertAnchorEntry(frontier, tag, 555, JVMTI_HEAP_REFERENCE_STACK_LOCAL); + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class, true); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, container_class); + ASSERT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + + AnchorObservation record{}; + record.tag = tag; + record.own_class_tag = container_class; + record.actions = AnchorObservation::REENLIST_ELIGIBLE; + ReferenceChainsTestAccessor::replayAnchorObservationsForTest({record}); + + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()) + << "the re-enlist replay must release the local slot"; + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + + tracker->stop(); +} + +// The re-enlist replay's promotion must enforce the durable cap the way addToStaticAnchorIndex() +// does: releasing the local slot grows the durable share while the dedup in +// indexAnchorForRotation() returns early for the still-indexed tag, so a promotion at a full +// durable share would exceed DURABLE_ANCHOR_INDEX_CAP until an unrelated admission evicts. +TEST_F(ReferenceChainsBfsTest, ReenlistReplayPromotionAtCapTriggersEviction) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const size_t batch = ReferenceChainsTestAccessor::kDurableAnchorEvictBatch; + for (size_t i = 0; i < cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 4001 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_EQ(cap, AnchorAcc::durableAnchorCountForTest()); + + const jlong promoted = 22051; + const jlong container_class = -3208; + insertAnchorEntry(frontier, promoted, 555, JVMTI_HEAP_REFERENCE_STACK_LOCAL); + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class, true); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(promoted, + container_class); + ASSERT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + ASSERT_EQ(cap, AnchorAcc::durableAnchorCountForTest()) + << "the local holder's index push shifts the share boundary, not the " + "durable share's size"; + + AnchorObservation record{}; + record.tag = promoted; + record.own_class_tag = container_class; + record.actions = AnchorObservation::REENLIST_ELIGIBLE; + ReferenceChainsTestAccessor::replayAnchorObservationsForTest({record}); + + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()) + << "the promotion must release the local slot"; + EXPECT_EQ(cap - batch, AnchorAcc::durableAnchorCountForTest()) + << "the promotion at a full durable share must evict, not exceed the cap"; + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(promoted)) + << "the just promoted tag is the newest entry, never among the evicted " + "oldest"; + + tracker->stop(); +} + +// A confirmed container arriving after the pending buffer filled with unclassified holders in +// the same walk must still stage: every staged unknown is displaceable in replay, so the +// container's record displaces the oldest unknown instead of being rejected while a local slot +// would have been available through that displacement. +TEST_F(ReferenceChainsBfsTest, ConfirmedContainerDisplacesPendingUnknownInSameScope) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong container_class = -3307; + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class, true); + // Fill the local share to its cap with confirmed containers. + for (jlong t = 30001; t < 30001 + (jlong)ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + t++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(t, container_class); + } + ASSERT_EQ((size_t)ReferenceChainsTestAccessor::kLocalAnchorIndexCap, + AnchorAcc::localAnchorCountForTest()); + + { + ReferenceChainAnchorObservationScope scope(tracker); + auto stage_local_record = [&](jlong tag, jlong class_tag) -> bool { + if (!scope.reserveLocalStaging(tag, class_tag)) { + return false; + } + AnchorObservationReservationGuard reservation; + if (!reservation.acquire(scope)) { + return false; + } + AnchorObservation record{}; + record.tag = tag; + record.own_class_tag = class_tag; + record.actions = AnchorObservation::LOCAL; + reservation.commit(record); + return true; + }; + // Unclassified holders fill the pending buffer: each spends one pending slot and, per + // the displacement contract, makes itself evictable by a later confirmed container. + for (int i = 0; i < (int)ReferenceChainsTestAccessor::kPendingLocalAnchorCap; i++) { + ASSERT_TRUE(stage_local_record(40000 + i, -3999 - i)); + } + ASSERT_TRUE(stage_local_record(50001, container_class)) + << "the confirmed container must stage by displacing a staged unknown"; + scope.flush(); + } + EXPECT_TRUE(AnchorAcc::pendingLocalAnchorContainsForTest(50001)); + EXPECT_EQ((size_t)ReferenceChainsTestAccessor::kLocalAnchorIndexCap, + AnchorAcc::localAnchorCountForTest()) + << "the container stays parked in the pending buffer; the local share is unchanged"; + EXPECT_EQ((size_t)ReferenceChainsTestAccessor::kPendingLocalAnchorCap, + AnchorAcc::pendingLocalAnchorCountForTest()); + + // The displacement budget is finite: once every pending unknown is displaced, further + // confirmed containers are rejected. A mutation of the budget check from `> 0` to `>= 0` + // would admit a container with no unknown left to displace. + { + ReferenceChainAnchorObservationScope scope(tracker); + int admitted = 0; + bool rejected = false; + for (jlong t = 60000; t < 60000 + 1100 && !rejected; t++) { + if (scope.reserveLocalStaging(t, container_class)) { + admitted++; + } else { + rejected = true; + } + } + EXPECT_TRUE(rejected) << "the displacement budget must be finite"; + EXPECT_EQ((size_t)ReferenceChainsTestAccessor::kPendingLocalAnchorCap - 1, + (size_t)admitted) + << "exactly the remaining displaced unknowns may be staged"; + } + + tracker->stop(); +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc index 59c324eb22..99907543ea 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsAnchorTests.inc @@ -3,6 +3,78 @@ * SPDX-License-Identifier: Apache-2.0 */ +namespace { + +using AnchorAcc = ReferenceChainsTestAccessor; + +// A pass context bound to a caller-owned journal scope, as every production traversal caller +// builds it. Callbacks only record; the test plays the caller and flushes at the return boundary +// (scope.flush(), or scope destruction). Never replays from inside a callback. +struct AnchorScopedPass { + ReferenceChainAnchorObservationScope scope; + ReferenceChainPassContext ctx; + + AnchorScopedPass(ReferenceChainTracker *tracker, FrontierTable *frontier, + int budget = 100000) + : scope(tracker), ctx(scope) { + AnchorAcc::preparePendingLocalAnchorEvictionCursorForTest(); + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = budget; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + } + + jvmtiIterationControl root(jvmtiHeapRootKind kind, jlong class_tag, jlong *tag) { + return AnchorAcc::reportHeapRootForTest(kind, class_tag, tag, &ctx); + } + + // The static sweep's class -> field edge (negative class-object referrer, class tag 0). + jint staticEdge(jlong *tag) { + return AnchorAcc::reportStaticFieldEdgeForTest(-555, tag, &ctx); + } +}; + +void insertAnchorEntry(FrontierTable *frontier, jlong tag, jlong parent_tag, + u8 root_kind, jlong class_tag = 0) { + ASSERT_TRUE(AnchorAcc::insertFrontierEntry( + frontier, tag, parent_tag, parent_tag == 0 ? 0 : 1, + FrontierEntryState::FRONTIER, root_kind, /*referrer_klass=*/0, class_tag)); +} + +// Reports an already-admitted, root-attached JNI-global entry again: the callback records one +// REENLIST_ELIGIBLE observation for it (no frontier change, nothing indexed until the flush). +void reportRediscovery(AnchorScopedPass &pass, jlong tag, jlong class_tag = -3001) { + jlong reported = tag; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, class_tag, &reported)); + ASSERT_EQ(tag, reported); +} + +// Reports a fresh local root (admits a new frontier tag and records one LOCAL observation). +jlong reportFreshLocal(AnchorScopedPass &pass, jlong class_tag) { + jlong reported = 0; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, class_tag, &reported)); + return reported; +} + +std::vector insertRootAttachedDurableEntries(FrontierTable *frontier, + jlong first_tag, size_t count) { + std::vector tags; + tags.reserve(count); + for (size_t i = 0; i < count; i++) { + insertAnchorEntry(frontier, first_tag + (jlong)i, 0, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + tags.push_back(first_tag + (jlong)i); + } + return tags; +} + +} // namespace + TEST_F(ReferenceChainsBfsTest, StaticAnchorRotationWalksRootAttachedStaticHolders) { Arguments args; ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); @@ -89,7 +161,10 @@ TEST_F(ReferenceChainsBfsTest, ContainerAnchorLeapsQueueAcrossLargeIndex) { ASSERT_FALSE(tracker->start(args)); FrontierTable *frontier = tracker->frontierTable(); - constexpr int kAnchorCount = 28000; + // Large-but-capped index (the durable share caps at 8192): containers only at positions + // 5000..5003 - outside the fresh queue's last-1024-admissions window (tags 6076..7099) and + // buried behind ~6k other-tier anchors under any admission-order cursor. + constexpr int kAnchorCount = 7000; for (int i = 0; i < kAnchorCount; i++) { jlong tag = 100 + i; jlong class_tag = 500000 + i; @@ -98,9 +173,7 @@ TEST_F(ReferenceChainsBfsTest, ContainerAnchorLeapsQueueAcrossLargeIndex) { JVMTI_HEAP_REFERENCE_STATIC_FIELD)); ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); - // Containers only at late positions 24000..24003 - buried behind 24k other-tier anchors - // under any admission-order cursor. - bool container = (i >= 24000 && i <= 24003); + bool container = (i >= 5000 && i <= 5003); ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, container); } @@ -119,12 +192,12 @@ TEST_F(ReferenceChainsBfsTest, ContainerAnchorLeapsQueueAcrossLargeIndex) { ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( 16); ASSERT_EQ(16u, selected.size()) - << "28k+5 eligible anchors at a 16 budget must fill the selection"; + << "7000+1 eligible anchors at a 16 budget must fill the selection"; EXPECT_EQ(leak_anchor, selected[0]) << "the leak-tagged anchor (tier 0) must lead the walk order"; - // The four container anchors are selected in this FIRST call despite positions 24000+ (tags - // 24100-24103). - for (jlong t : {24100, 24101, 24102, 24103}) { + // The four container anchors are selected in this FIRST call despite positions 5000+ (tags + // 5100-5103) - outside the fresh queue's window, so only the container tier can pick them. + for (jlong t : {5100, 5101, 5102, 5103}) { EXPECT_NE(std::find(selected.begin(), selected.end(), t), selected.end()) << "container anchor " << t << " did not leap the other-tier queue"; @@ -157,8 +230,9 @@ TEST_F(ReferenceChainsBfsTest, FreshContainerWalkedBeforeFairBacklog) { tag, 700000 + i, JVMTI_HEAP_REFERENCE_STATIC_FIELD); ReferenceChainsTestAccessor::primeClassShapeForTest(700000 + i, true); } - // First collector call: all 200 anchors are fresh (nothing has had a first look yet), the lane - // keeps 16 and the rest spend their first look (they fall back to the fair container tier). + // First collector call: all 200 anchors are fresh (nothing has had a first look yet); the + // fresh lane serves the oldest 8 and the fair container tier the leftover 8 (the reserved + // split); the remaining 184 stay queued for their FIFO turn. std::vector first = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( 16); @@ -191,42 +265,315 @@ TEST_F(ReferenceChainsBfsTest, FreshContainerWalkedBeforeFairBacklog) { ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( 16); ASSERT_EQ(16u, second.size()); - EXPECT_EQ(wrapper_tag, second[0]) - << "the freshly admitted container must lead the walk order, not " - "wait behind the 184-container fair backlog"; - EXPECT_NE(std::find(second.begin(), second.end(), fresh_unknown_tag), - second.end()) + // FIFO: wave 1's unserved entries kept their queue positions and lead, in admission order. + EXPECT_EQ((jlong)516, second[0]); + EXPECT_EQ((jlong)523, second[7]); + // The fresh lane is the container lane: the classified NON-container was dropped from the + // queue (it keeps the other-tier fallback), the wrapper and the unclassified anchor stay + // queued behind wave 1. + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + wrapper_tag)); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + fresh_unknown_tag)) << "an unclassified fresh anchor must ride the fresh lane (the " "wrapper admits a pass before reconcile classifies its class)"; - EXPECT_EQ(std::find(second.begin(), second.end(), fresh_string_tag), - second.end()) - << "a fresh NON-container stays in the other tier - the fresh lane " - "is the container lane, or fresh Strings would flood it"; - // The fair container lap still gets the leftover budget. Call 1's fresh picks (500-515) spent - // the whole budget, so the fair cursor never advanced - call 2's fair picks start at tag 500 - // again (a benign one-call overlap: walks are idempotent, and it only happens when fresh and - // fair coincide at a lap boundary). - EXPECT_NE(std::find(second.begin(), second.end(), (jlong)500), - second.end()) - << "the fair container lap must still advance with the leftover " - "budget"; - EXPECT_EQ(14, (int)std::count_if(second.begin(), second.end(), - [](jlong t) { - return t >= 500 && t < 500 + kBacklog; - })) - << "16 budget - 2 fresh picks = 14 fair-container picks"; - - // And the dropped fresh entries from call 1 (516-699 spent their first look) are still covered - // by the fair tier: a third call with no new admits must keep advancing the fair container - // cursor from wherever call 2 left it, not re-drain anything. - std::vector third = + + // The wrapper's wait is bounded by the queued backlog (FIFO turn), not by the fair cursor's + // ~100-pass lap over the 1633-entry production backlog: it is served within roughly + // kBacklog / (fresh budget per collect) collects. The classified NON-container is dropped + // from the queue when its turn arrives (its look is spent on the other tier). + int wrapper_turn = -1; + for (int collect = 0; collect < 40 && wrapper_turn < 0; collect++) { + std::vector sel = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + if (std::find(sel.begin(), sel.end(), wrapper_tag) != sel.end()) { + wrapper_turn = collect; + } + } + ASSERT_GE(wrapper_turn, 0) + << "the late container must get its first look within the queue's " + "FIFO horizon"; + EXPECT_LE(wrapper_turn, 26); + for (int collect = 0; + collect < 40 && + ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + fresh_string_tag); + collect++) { ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( 16); - ASSERT_EQ(16u, third.size()); - EXPECT_EQ(std::find(third.begin(), third.end(), wrapper_tag), - third.end()) - << "the wrapper already had its first look - it must not be " - "re-selected while the fair cursor has 184 uncovered peers"; + } + EXPECT_FALSE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + fresh_string_tag)) + << "a fresh NON-container must be dropped from the queue at its FIFO " + "turn - the fresh lane is the container lane, or fresh Strings " + "would flood it"; + + tracker->stop(); +} + +// Overflow must preserve the oldest unserved first looks and drop only newest admissions. +TEST_F(ReferenceChainsBfsTest, FreshQueueCapDropsNewestAnchors) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const size_t cap = ReferenceChainsTestAccessor::freshAnchorQueueCapForTest(); + const jlong first = 2000; + const jlong klass = -799100; + ReferenceChainsTestAccessor::primeClassShapeForTest(klass, true); + long long dropped_before = + Counters::getCounter(REFERENCE_CHAIN_STATIC_FRESH_DROPPED); + for (size_t i = 0; i < cap + 2; i++) { + const jlong tag = first + (jlong)i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, klass, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + + std::vector queued = ReferenceChainsTestAccessor::freshQueueTagsForTest(); + ASSERT_EQ(cap, queued.size()); + EXPECT_EQ(first, queued.front()) << "the oldest unserved first look must stay queued"; + EXPECT_EQ(first + (jlong)cap - 1, queued.back()); + EXPECT_FALSE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + first + (jlong)cap)); + EXPECT_FALSE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + first + (jlong)cap + 1)); + EXPECT_EQ(2, Counters::getCounter(REFERENCE_CHAIN_STATIC_FRESH_DROPPED) - + dropped_before) + << "each cap-rejected admission must count its lost prioritized first look"; + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(1); + ASSERT_EQ(1u, selected.size()); + EXPECT_EQ(first, selected[0]) << "the retained FIFO head must receive the next first look"; + EXPECT_EQ(first + 1, ReferenceChainsTestAccessor::freshQueueTagsForTest().front()); + + tracker->stop(); +} + +// A requeue past the queue cap spends the overflow entries' first looks instead of overfilling +// the deque: flush admissions between this pass's pops and the requeue can refill the freed +// slots, and an unbounded push_front would grow the queue past its fixed cap. +TEST_F(ReferenceChainsBfsTest, FreshRequeuePastCapSpendsOverflowFirstLooks) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const size_t cap = ReferenceChainsTestAccessor::freshAnchorQueueCapForTest(); + const jlong klass = -799200; + ReferenceChainsTestAccessor::primeClassShapeForTest(klass, true); + for (size_t i = 0; i < cap; i++) { + const jlong tag = 3000 + (jlong)i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, klass, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_EQ(cap, ReferenceChainsTestAccessor::freshQueueTagsForTest().size()); + + // Three popped turns (PENDING set, as the production requeue receives them) requeued against + // a full queue: all three overflow. + constexpr jlong overflow_base = 6000; + for (int i = 0; i < 3; i++) { + const jlong tag = overflow_base + i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, klass, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_TRUE(frontier->tryMarkAnchorRotationPending(tag)); + } + ReferenceChainsTestAccessor::requeueStaticAnchorFreshFrontForTest( + std::vector{ + {overflow_base, klass}, + {overflow_base + 1, klass}, + {overflow_base + 2, klass}}); + + EXPECT_EQ(cap, ReferenceChainsTestAccessor::freshQueueTagsForTest().size()) + << "the requeue must not grow the queue past its cap"; + for (int i = 0; i < 3; i++) { + EXPECT_FALSE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + overflow_base + i)); + } + for (int i = 0; i < 3; i++) { + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(overflow_base + i, &entry)); + EXPECT_TRUE(entry.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_SERVED) + << "an overflowed turn is spent, never left PENDING outside the queue"; + EXPECT_FALSE(entry.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + } + + tracker->stop(); +} + +// A queued anchor whose class tag is refreshed while it waits keeps the resolved tag across +// durable eviction: eviction preserves the pending first look but discards the index's class-tag +// metadata, and the fresh lane's fallback to the enqueue-time tag would spend the preserved look +// on a stale 0 - a reparented holder is selectable only through its class shape. +TEST_F(ReferenceChainsBfsTest, EvictedFreshAnchorKeepsRefreshedClassTag) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong kContainer = -505; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + const jlong target = 6101, parent = 6102; + // Reparented (parent != 0): the root-attached eligibility is gone, so the fresh lane's + // selectability check rides entirely on the holder's class tag. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, target, parent, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + // Queued before its class was tagged: the entry carries the admission-time 0. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + // The resolved class tag arrives while the anchor waits: the index entry is upgraded. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, kContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_EQ(kContainer, + ReferenceChainsTestAccessor::indexedAnchorClassTagForTest(target)); + + // Cross the cap: `target` sits at the oldest position and is evicted with its fresh turn + // preserved - but the refreshed index metadata is gone with the eviction. + for (size_t i = 0; i <= cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 8000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 8); + EXPECT_TRUE(std::find(selected.begin(), selected.end(), target) != + selected.end()) + << "the preserved first look must walk the holder, not be spent on " + "the stale 0 class tag"; + + tracker->stop(); +} + +// A tag admitted with class tag 0, evicted, re-enlisted with the resolved tag, and evicted again +// before selection keeps its resolved tag on the preserved queue entry: the eviction writes the +// index's resolved tag back into the queued turn, so the fresh lane never falls back to the +// admission-time 0 and rejects a chain-attached container whose first look it then spends. +TEST_F(ReferenceChainsBfsTest, DoubleEvictionPreservesResolvedFreshClassTag) { + 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 size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong kContainer = -525; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + const jlong target = 6401, parent = 6402; + // Chain-attached: eligibility rides on the holder's class shape, so the queued entry's tag + // must resolve for the fresh lane to keep the turn. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, target, parent, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + // First admission with class tag 0: the queue entry carries the unresolvable 0. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, 0, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + // First eviction: the pending turn survives outside the index with its 0 tag. + for (size_t i = 0; i <= cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 8300 + (jlong)i, -905, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + // Re-enlist with the resolved tag: the PENDING flag suppresses a fresh queue push, and the + // upgrade path's queue refresh never runs (the class-tag map was erased by the eviction). + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, kContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + // Second eviction drops the re-inserted metadata; the write-back keeps the resolved tag on + // the preserved queued entry. The oversized wave leaves no doubt the re-inserted target + // (admitted before the whole wave) falls outside the surviving window. + for (size_t i = 0; i <= 2 * cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 9300 + (jlong)i, -906, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 8); + EXPECT_TRUE(std::find(selected.begin(), selected.end(), target) != + selected.end()) + << "the preserved turn must carry the resolved tag and walk the container"; + + tracker->stop(); +} + +// An evicted non-container holder's preserved fresh turn is its only rotation walk: the fair +// tiers scan only indexed holders, so spending the turn at the shape gate would strand the +// holder until re-enumeration. Root-attached: selectability rides on the root kind, not the +// (non-container) shape, and the shape only decides the lane. +TEST_F(ReferenceChainsBfsTest, EvictedNonContainerWalksPreservedFreshTurn) { + 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 size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong kNonContainer = -511; + ReferenceChainsTestAccessor::primeClassShapeForTest(kNonContainer, false); + const jlong target = 6301; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, target, 0, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, kNonContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + // Cross the cap: `target` is evicted oldest, its fresh turn preserved outside the index. + for (size_t i = 0; i <= cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 8200 + (jlong)i, -901, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 8); + EXPECT_TRUE(std::find(selected.begin(), selected.end(), target) != + selected.end()) + << "the preserved turn must walk the evicted non-container holder - " + "no indexed fallback exists to spend it against"; tracker->stop(); } @@ -467,287 +814,47 @@ TEST_F(ReferenceChainsBfsTest, SweepPushFiresOnStaticEdgeOntoChainAttachedHolder tracker->stop(); } -TEST_F(ReferenceChainsBfsTest, StaticFieldCollectionRemainsIndexedAfterFirstLook) { +// 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). +TEST_F(ReferenceChainsBfsTest, AtRiskAnchorFifoDrainAndWalkIntercept) { 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); + void *holderCls = (void *)0x6001, *chunkCls = (void *)0x6002; + addClass(holderCls, "Lcom/rc/descendwalk/ChainAttachedHolder;"); + int chunk = addClass(chunkCls, "Lcom/rc/descendwalk/ChainChunk;"); - // Mutate after both the FIFO and fresh-lane first looks. No static-field - // edge is delivered again, so discovery requires a persistent revisit. + int parentNode = addNode(); + int holderNode = addNode(); + int tableNode = addNode(); + int entryNode = addNode(); + int leakChunk = addNode(); const jlong leak_tag = ReferenceChainsTestAccessor::leakTagBase(); - node_tags[payload] = leak_tag; + node_tags[leakChunk] = leak_tag; + + // Chain: parent -> holder -> table -> entry -> leak chunk. script = { - {JVMTI_HEAP_REFERENCE_FIELD, holder, table, -1}, - {JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, table, payload, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, holderNode, tableNode, -1}, + {JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, tableNode, entryNode, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, entryNode, leakChunk, chunk}, }; - 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(); + // Seed the holder exactly as the eviction leaves it: chain-attached (parent_tag = 104, depth 1, + // no root_kind). FrontierTable *frontier = tracker->frontierTable(); + node_tags[holderNode] = 105; + // root_kind = 0: the entry is chain-attached, and a non-root entry's edge kind is not recorded + // (FrontierEntry::root_kind's own comment). ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( - frontier, node_tags[parent], 0, 0, FrontierEntryState::EXPANDED, - JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + frontier, 105, 104, 1, FrontierEntryState::FRONTIER, 0)); + // The chain's root: TRANSIENT (stack local), so the collector's durable root-kind filter skips + // it too - the whole table is un-selectable. 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). -TEST_F(ReferenceChainsBfsTest, AtRiskAnchorFifoDrainAndWalkIntercept) { - Arguments args; - ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); - ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); - ASSERT_FALSE(tracker->start(args)); - - void *holderCls = (void *)0x6001, *chunkCls = (void *)0x6002; - addClass(holderCls, "Lcom/rc/descendwalk/ChainAttachedHolder;"); - int chunk = addClass(chunkCls, "Lcom/rc/descendwalk/ChainChunk;"); - - int parentNode = addNode(); - int holderNode = addNode(); - int tableNode = addNode(); - int entryNode = addNode(); - int leakChunk = addNode(); - const jlong leak_tag = ReferenceChainsTestAccessor::leakTagBase(); - node_tags[leakChunk] = leak_tag; - - // Chain: parent -> holder -> table -> entry -> leak chunk. - script = { - {JVMTI_HEAP_REFERENCE_FIELD, holderNode, tableNode, -1}, - {JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, tableNode, entryNode, -1}, - {JVMTI_HEAP_REFERENCE_FIELD, entryNode, leakChunk, chunk}, - }; - - // Seed the holder exactly as the eviction leaves it: chain-attached (parent_tag = 104, depth 1, - // no root_kind). - FrontierTable *frontier = tracker->frontierTable(); - node_tags[holderNode] = 105; - // root_kind = 0: the entry is chain-attached, and a non-root entry's edge kind is not recorded - // (FrontierEntry::root_kind's own comment). - ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( - frontier, 105, 104, 1, FrontierEntryState::FRONTIER, 0)); - // The chain's root: TRANSIENT (stack local), so the collector's durable root-kind filter skips - // it too - the whole table is un-selectable. - ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( - frontier, 104, 0, 0, FrontierEntryState::FRONTIER, - JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + frontier, 104, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); // Negative control: the root-attached collector selects NOTHING from a table holding only a // chain-attached holder and a transient root. @@ -1050,392 +1157,2153 @@ TEST_F(ReferenceChainsBfsTest, AtRiskFifoPerClassQuotaKeepsFloodOut) { // 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) { +// Local-root holders enter the anchor index only once confirmed as containers: a classified +// non-container is ignored outright, and an unclassified holder waits in the pending buffer and is +// dropped by the resolve step if its class is still unknown or turns out to be a non-container. +TEST_F(ReferenceChainsBfsTest, LocalRootAnchorIndexHoldsOnlyConfirmedContainers) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const jlong kNonContainer = -201, kLater = -202, kNever = -203, kContainer = -204; + ReferenceChainsTestAccessor::primeClassShapeForTest(kNonContainer, false); + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + + // Classified non-container: neither indexed nor parked. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(301, kNonContainer); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + // Classified container: indexed directly and counted against the local cap. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(302, kContainer); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + + // Unclassified holders are parked (deduplicated), not indexed. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(303, kLater); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(303, kLater); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(304, kNever); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(2u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + // kLater classifies as a non-container, kNever stays unknown: both are dropped, and the + // pending buffer is emptied every resolve. + ReferenceChainsTestAccessor::primeClassShapeForTest(kLater, false); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + tracker->stop(); +} + +// The local share of the anchor index is capped, and the pending buffer is capped too, so the +// per-pass anchor scan cannot grow with the number of application locals. At the cap, the resolve +// step compacts away local entries whose frontier entry is gone before admitting new ones. +TEST_F(ReferenceChainsBfsTest, LocalRootAnchorIndexIsCappedAndCompactsDeadEntries) { 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++) { + const size_t cap = ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + const size_t pending_cap = ReferenceChainsTestAccessor::kPendingLocalAnchorCap; + const jlong kContainer = -301; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + + // A durable anchor is outside the local share and must survive compaction. + const jlong durable = 50; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, durable, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + durable, -302, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + + // Fill the local share with holders whose frontier entries are then released (dead objects: + // the GC cleanup marks them ABANDONED). + const jlong dead_base = 100; + for (size_t i = 0; i < cap; i++) { + jlong tag = dead_base + (jlong)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); + frontier, tag, 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, kContainer); + frontier->clear(tag); } - 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); + ASSERT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + ASSERT_EQ(cap + 1, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + + // Containers met at the cap are parked, and the pending buffer stops at its own cap. + // Above every inserted tag, so un-inserted parked tags have no frontier entry at all. + const jlong live_base = dead_base + (jlong)cap + 1000; + for (size_t i = 0; i < pending_cap + 10; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(live_base + (jlong)i, + kContainer); + } + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + // Only one parked holder is live; the resolve step compacts the dead local entries and + // admits it. Dead parked holders are indexed too (liveness is checked at selection), but + // all of them fit once the dead share is gone. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, live_base, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(pending_cap + 1, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + // A productive compaction leaves the compaction backoff disarmed. + EXPECT_EQ(0, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_LE(ReferenceChainsTestAccessor::freshAnchorQueueSizeForTest(), + ReferenceChainsTestAccessor::anchorIndexSizeForTest()); 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()); + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_NE(std::find(selected.begin(), selected.end(), durable), selected.end()) + << "durable anchor lost by local-share compaction"; + EXPECT_NE(std::find(selected.begin(), selected.end(), live_base), selected.end()) + << "live local container not admitted after compaction"; + + tracker->stop(); } -// 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) { +// When every local entry is live the cap holds: no compaction can free a slot, new holders are +// not indexed, and the pending buffer is still emptied. +TEST_F(ReferenceChainsBfsTest, LocalRootAnchorCapHoldsWhenAllEntriesLive) { 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++) { + const size_t cap = ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + const jlong kContainer = -401; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + for (size_t i = 0; i < cap; i++) { + jlong tag = 1000 + (jlong)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); + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, kContainer); } - 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"; + const jlong extra = 1000 + (jlong)cap; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, extra, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(extra, kContainer); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + tracker->stop(); } -// 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) { +// A local holder later attached by a durable root moves to the uncapped durable share, freeing its +// local-cap slot without duplicating the index entry. +TEST_F(ReferenceChainsBfsTest, DurableRootUpgradeReleasesLocalAnchorSlot) { 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)); + const jlong kContainer = -501; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(777, kContainer); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 777, kContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + + // restartSearch() resets the local share and the pending buffer with the rest of the index. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(778, -502); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + ReferenceChainsTestAccessor::restartSearchForTest(); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexIsEmptyForTest()); + + tracker->stop(); +} + +// FIFO eviction walks index positions but never takes a local-share slot: the local cap and its +// compaction are owned by noteLocalRootHolder()/compactLocalAnchors(), so a local holder sitting at +// the oldest positions survives a durable-share eviction untouched. +TEST_F(ReferenceChainsBfsTest, DurableAnchorEvictionSparesLocalShare) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong kContainer = -501; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + const size_t kLocals = 4; + // Admitted first, so they occupy the oldest index positions. + for (size_t i = 0; i < kLocals; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(500 + (jlong)i, + kContainer); + } + ASSERT_EQ(kLocals, + ReferenceChainsTestAccessor::localAnchorCountForTest()); + const jlong first_durable = 2001; + for (size_t i = 0; i <= cap; i++) { ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( - 1100 + i, 930000 + i, JVMTI_HEAP_REFERENCE_STATIC_FIELD); - ReferenceChainsTestAccessor::primeClassShapeForTest(930000 + i, false); + first_durable + (jlong)i, -900, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL); } - 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); + EXPECT_EQ(kLocals, + ReferenceChainsTestAccessor::localAnchorCountForTest()); + for (size_t i = 0; i < kLocals; i++) { + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest( + 500 + (jlong)i)) + << "local holder " << i << " must survive durable eviction"; } - 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()); + // The durable share alone sits at cap - batch after the eviction. + EXPECT_EQ(cap - ReferenceChainsTestAccessor::kDurableAnchorEvictBatch, + ReferenceChainsTestAccessor::durableAnchorCountForTest()); - 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"; + tracker->stop(); } -// 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) { +// An evicted anchor that is still root-attached is re-reported by the next root enumeration and +// re-admitted (fresh lane); the readmission lands at the back of the index. +TEST_F(ReferenceChainsBfsTest, EvictedDurableAnchorIsReadmittedByRootEnumeration) { Arguments args; - ASSERT_FALSE(args.parse("referencechains=true:budget=1000")); + ASSERT_FALSE(args.parse("referencechains=true:hops=64: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"; + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const size_t batch = ReferenceChainsTestAccessor::kDurableAnchorEvictBatch; + const jlong first_tag = 3001; + for (size_t i = 0; i <= cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + first_tag + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + const jlong evicted = first_tag; // oldest position, evicted by the crossing admission + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(evicted)); + const size_t size_before = ReferenceChainsTestAccessor::anchorIndexSizeForTest(); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + evicted, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(evicted)); + EXPECT_EQ(size_before + 1, + ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(evicted, + ReferenceChainsTestAccessor::anchorIndexTagForTest( + size_before)); // readmitted at the back - for (int epoch = 1; epoch <= 20; epoch++) { - int slot; - bool created; - liveness->klassPopulationRecordForTest(1, epoch, epoch, &slot, &created); - liveness->tidTrendRecordForTest(1, 4242, epoch, epoch); + tracker->stop(); +} + +// A local-to-durable upgrade grows the durable share without an index push (the dedup in +// indexAnchorForRotation() returns early), so only addToStaticAnchorIndex()'s own eviction call +// can reclaim the share when the upgrade itself crosses the cap. +TEST_F(ReferenceChainsBfsTest, DurableUpgradeAtCapTriggersEviction) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const size_t batch = ReferenceChainsTestAccessor::kDurableAnchorEvictBatch; + const jlong first_tag = 4001; + for (size_t i = 0; i < cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + first_tag + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); } - liveness->klassPopulationSetStableClassTagForTest(1, -41); + ASSERT_EQ(cap, + ReferenceChainsTestAccessor::durableAnchorCountForTest()); + // Admit a local holder (newest index position), then upgrade it: the upgrade alone pushes the + // durable share to cap + 1. + const jlong kContainer = -501; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + const jlong upgraded = first_tag + (jlong)cap; + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(upgraded, kContainer); + ASSERT_EQ(1u, + ReferenceChainsTestAccessor::localAnchorCountForTest()); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + upgraded, kContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_EQ(0u, + ReferenceChainsTestAccessor::localAnchorCountForTest()); + // The upgrade's eviction reclaimed the share to cap - batch, and the upgraded tag - the + // newest entry, never among the FIFO-evicted oldest - is still indexed. + EXPECT_EQ(cap - batch, + ReferenceChainsTestAccessor::durableAnchorCountForTest()); + EXPECT_TRUE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(upgraded)); - 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()); + tracker->stop(); } -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))); +// A live evicted anchor has no fresh-admission path (its frontier entry is already ADMITTED) and +// no upgrade path (an unchanged durable root kind never upgrades), so the traversal callbacks' +// re-enlistment staging is its only route back into the rotation index. Non-root-attached entries +// and unchanged transient root kinds are not staged. +TEST_F(ReferenceChainsBfsTest, EvictedDurableAnchorIsReenlistedByTraversalReport) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong kClass = -601; + AnchorAcc::primeClassShapeForTest(kClass, false); + const jlong target = 7001; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, target, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + target, kClass, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + // Cross the cap: `target` sits at the oldest position and is evicted. + for (size_t i = 0; i <= cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 8000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); } - 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; + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + + // The next traversal report of the holder's durable edge stages a re-enlist; the flush + // indexes it. + { + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, target); + ASSERT_EQ(1u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + } + EXPECT_TRUE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(target)); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + target)); + + // Negative controls: a non-root-attached entry is not staged for re-enlist (the static edge + // stages an at-risk push instead), and an unchanged transient root kind of a classified + // non-container stages nothing at all. + const jlong child = 7100, transient = 7101; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, child, 42, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, transient, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + { + AnchorScopedPass pass(tracker, frontier); + jlong child_tag = child; + jint child_ctl = pass.staticEdge(&child_tag); + EXPECT_EQ(0, child_ctl & JVMTI_VISIT_ABORT); + jlong transient_tag = transient; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kClass, + &transient_tag)); + pass.scope.flush(); } + EXPECT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(child)); + EXPECT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(transient)); - const u8 shape = ReferenceChainsTestAccessor::classifyAnchorClassForTest( - &mock_jvmti, &mock_jni, reinterpret_cast(classes[0]), - kCollectionTag, kMapTag); - EXPECT_TRUE(ReferenceChainsTestAccessor::isUnknownTruncatedClassShapeForTest( - shape)); + tracker->stop(); } -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; +// Eviction requests a full static sweep lap: static-only holders are invisible to root +// enumeration, and the sweep is otherwise skipped while the loaded-class count is unchanged - an +// evicted static-only anchor would never be re-reported. Every eviction bumps the request +// generation, and the request survives a lap-completion overwrite - a lap in flight when the +// eviction lands does not revisit the classes it already passed, so only a later lap starting +// from class 0 serves the request. Eviction never touches the sweep cursor: a restart under +// sustained above-cap churn would reset a mid-lap cursor every few runs and starve later classes. +TEST_F(ReferenceChainsBfsTest, EvictionForcesStaticFieldSweepRerun) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); - 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"; -} + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + for (size_t i = 0; i < cap; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 9000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_EQ(cap, + ReferenceChainsTestAccessor::durableAnchorCountForTest()); + // Simulate a mid-lap state: the sweep memo latched and the cursor part-way into a lap. + ReferenceChainsTestAccessor::setStaticFieldSweepMemoForTest(12345); + ReferenceChainsTestAccessor::setStaticFieldSweepCursorForTest(456); + // The cap-crossing admission evicts - and must record the resweep request WITHOUT resetting + // the in-flight cursor: a restart here would make laps over large class lists never complete + // under sustained churn. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 9000 + (jlong)cap, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_TRUE( + ReferenceChainsTestAccessor::durableAnchorResweepUnservedForTest()); + EXPECT_EQ(456, + ReferenceChainsTestAccessor::staticFieldSweepCursorForTest()); + // The lap in flight completing (memo overwritten) must NOT consume the request: this lap's + // behind-cursor classes were traversed before the eviction. + ReferenceChainsTestAccessor::setStaticFieldSweepMemoForTest(12345); + EXPECT_TRUE( + ReferenceChainsTestAccessor::durableAnchorResweepUnservedForTest()); + + // A second eviction under the same conditions still records the request and still preserves + // the cursor. Refill the durable share first: eviction drains it to + // cap - DURABLE_ANCHOR_EVICT_BATCH, so without the refill the next admission would not cross + // the cap and this phase would assert on a no-op. + const u64 gen_after_first = + ReferenceChainsTestAccessor::durableAnchorResweepGenForTest(); + ASSERT_LT(ReferenceChainsTestAccessor::durableAnchorCountForTest(), cap); + for (size_t i = 0; + ReferenceChainsTestAccessor::durableAnchorCountForTest() < cap; + i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 20000 + (jlong)i, -901, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_EQ(cap, + ReferenceChainsTestAccessor::durableAnchorCountForTest()); + ReferenceChainsTestAccessor::setStaticFieldSweepCursorForTest(789); + // A tag outside the refill range (20000..21023) - a colliding tag would dedup to a no-op + // instead of crossing the cap. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 30000, -901, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_GT(ReferenceChainsTestAccessor::durableAnchorResweepGenForTest(), + gen_after_first); + EXPECT_TRUE( + ReferenceChainsTestAccessor::durableAnchorResweepUnservedForTest()); + EXPECT_EQ(789, + ReferenceChainsTestAccessor::staticFieldSweepCursorForTest()); -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, {}, {}}; + tracker->stop(); +} - 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"; +// End-to-end wiring: the heap-root callback's re-enlist branch. An evicted JNI_GLOBAL root is +// re-reported every root enumeration; the already-admitted rediscovery takes the upgrade-refused +// path (an unchanged durable root kind never upgrades) and must restore the victim's index entry. +TEST_F(ReferenceChainsBfsTest, HeapRootCallbackReenlistsEvictedDurableAnchor) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); - 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(); + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong victim = 15001; + // The eviction removes only the index entry; the victim's frontier entry survives. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, victim, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + victim, -700, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + for (size_t i = 0; i < cap - 1; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 16000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + const jlong filler = 16000 + (jlong)cap; + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + filler, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); // crosses the cap + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + + // The next root enumeration re-reports the victim: already admitted, unchanged durable kind, + // so the upgrade refuses and the re-enlist branch fires. + AnchorScopedPass pass(tracker, frontier, 1000); + jlong reported = victim; + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, -700, &reported); + // The callback only records the rediscovery; the caller's flush applies it. + EXPECT_FALSE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::journalCountForTest()); + pass.scope.flush(); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + victim)); - 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(); + tracker->stop(); +} - 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"; +// A reparented confirmed container stays rotation-eligible after eviction: reparentToDurableRoot() +// re-parents it under a durable root (parent_tag != 0) while leaving its stale transient root_kind, +// so the pre-fix gate (parent_tag != 0) and the root-kind filter in addToStaticAnchorIndex() both +// rejected every re-enlistment attempt - and a JNI-global-only holder has no static-edge FIFO +// fallback, so its rotation eligibility was lost for good. isSelectableAnchor() is the admission +// contract (root-attached durable kind OR CONTAINER shape) and must gate the re-index. +TEST_F(ReferenceChainsBfsTest, ReparentedContainerReenlistsAfterEviction) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); - 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"; + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong victim = 17001; + // Reparented holder: parent_tag points at a root-attached durable root, root_kind is the + // stale transient kind reparenting leaves behind. Shape reconciliation classifies it as a + // container (that is what made it an anchor in the first place). + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, victim, 17999, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::primeClassShapeForTest(-800, true); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + victim, -800, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + for (size_t i = 0; i < cap - 1; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 18000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + const jlong filler = 18000 + (jlong)cap; + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + filler, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); // crosses the cap + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + + // The next traversal report re-discovers the victim through the heap-root callback; the + // re-enlist branch must restore it despite parent_tag != 0 and the stale root kind. + AnchorScopedPass pass(tracker, frontier, 1000); + jlong reported = victim; + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, -800, &reported); + // The callback only records the rediscovery; the caller's flush applies it. + EXPECT_FALSE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::journalCountForTest()); + pass.scope.flush(); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + victim)); - 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"; + tracker->stop(); } -TEST_F(ReferenceChainsBfsTest, TransientNonContainerAnchorsArePruned) { +// End-to-end wiring: heapReferenceCallback's already-admitted root-edge branch. The static sweep's +// class -> field edge is the only traversal that re-reports a static-only holder, whose re-enlist +// must not depend on the root enumeration (which never reports static-field holders). +TEST_F(ReferenceChainsBfsTest, HeapReferenceCallbackReenlistsEvictedDurableAnchor) { 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; + const size_t cap = ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const jlong victim = 17001; 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)); + frontier, victim, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + victim, -700, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + for (size_t i = 0; i < cap - 1; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 18000 + (jlong)i, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + const jlong filler = 18000 + (jlong)cap; + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + filler, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); // crosses the cap + ASSERT_FALSE( + ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + + // The sweep re-reports the victim's class -> field edge: root-like negative class referrer, + // unchanged durable kind - upgrade refused, re-enlist fires. + AnchorScopedPass pass(tracker, frontier, 1000); + jlong reported = victim; + pass.staticEdge(&reported); + EXPECT_FALSE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::journalCountForTest()); + pass.scope.flush(); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(victim)); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest( + victim)); - 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)); + tracker->stop(); +} - // 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) { +// No-progress and low-yield compactions arm a backoff; reclaiming at least the threshold leaves it +// disarmed. Under the cap the backoff is neither consulted nor changed. +TEST_F(ReferenceChainsBfsTest, LocalRootAnchorCompactBackoffSkipsLowYieldCompactions) { 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++) { + EXPECT_EQ(0, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + + const size_t cap = ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + const int backoff = ReferenceChainsTestAccessor::kLocalCompactBackoff; + ASSERT_GT(backoff, 1); + const jlong kContainer = -451, kLater = -452; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + + const jlong local_base = 1000; + for (size_t i = 0; i < cap; i++) { + jlong tag = local_base + (jlong)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()); - } + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, kContainer); + } + ASSERT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + + // Parked containers carry no frontier entry: they are only checked for admission. + jlong next_parked = local_base + (jlong)cap + 10000; + + // No-progress compaction arms the backoff; the cap holds. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(next_parked++, kContainer); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(backoff, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + + // A skipped at-cap attempt decrements once per resolve, however many containers were parked. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(next_parked++, kContainer); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(next_parked++, kContainer); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(backoff - 1, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + + // Under the cap the backoff is untouched: free one local slot via a durable-root upgrade, then + // admit a holder that becomes a confirmed container while parked. + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + local_base, kContainer, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_EQ(cap - 1, ReferenceChainsTestAccessor::localAnchorCountForTest()); + const jlong later = next_parked++; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, later, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(later, kLater); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + ReferenceChainsTestAccessor::primeClassShapeForTest(kLater, true); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + const size_t index_size = cap + 1; // the upgraded durable entry stays indexed + EXPECT_EQ(index_size, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(backoff - 1, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + + // A low-yield compaction must re-arm the backoff after reclaiming fewer than the threshold. + const size_t dead = ReferenceChainsTestAccessor::kLocalCompactMinReclaim - 1; + ASSERT_GT(dead, 0u); + for (size_t i = 1; i <= dead; i++) { + frontier->clear(local_base + (jlong)i); + } + for (int k = backoff - 1; k > 0; k--) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(next_parked++, kContainer); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(index_size, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(k - 1, ReferenceChainsTestAccessor::localCompactBackoffForTest()); } - 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)); + // Backoff exhausted: the next at-cap resolve reclaims the small dead share and admits the + // parked container, then re-arms the backoff for that low-yield batch. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(next_parked++, kContainer); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(cap - dead + 1, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ(index_size - dead + 1, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(backoff, ReferenceChainsTestAccessor::localCompactBackoffForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + tracker->stop(); +} + +// A full pending buffer gives confirmed containers (met at the local cap) priority over entries not +// yet confirmed as containers: the oldest such entry is evicted through a forward-only cursor, dedup +// stays exact, and once only confirmed containers are parked a further container is dropped (to be +// re-reported by the next root enumeration). +TEST_F(ReferenceChainsBfsTest, LocalRootAnchorPendingBufferEvictsForConfirmedContainer) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const size_t cap = ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + const size_t pending_cap = ReferenceChainsTestAccessor::kPendingLocalAnchorCap; + ASSERT_GT(pending_cap, 8u); + const jlong kContainer = -601, kUnknown = -602; + ReferenceChainsTestAccessor::primeClassShapeForTest(kContainer, true); + + // Fill the local cap so confirmed containers park instead of being indexed directly. + for (size_t i = 0; i < cap; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(10000 + (jlong)i, kContainer); + } + ASSERT_EQ(cap, ReferenceChainsTestAccessor::localAnchorCountForTest()); + + // Fill the pending buffer with unclassified holders. + const jlong unk_base = 20000; + for (size_t i = 0; i < pending_cap; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(unk_base + (jlong)i, kUnknown); + } + ASSERT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + ASSERT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + // The first container evicts the oldest unclassified entry, in place. + const jlong c_base = 30000; + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(c_base, kContainer); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_TRUE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(c_base)); + EXPECT_EQ(c_base, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(0)); + EXPECT_FALSE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(unk_base)); + EXPECT_TRUE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(unk_base + 1)); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + // The second evicts the next-oldest; the parked container below the cursor is kept. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(c_base + 1, kContainer); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(c_base, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(0)); + EXPECT_EQ(c_base + 1, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(1)); + EXPECT_FALSE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(unk_base + 1)); + EXPECT_EQ(2u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + // Dedup: re-reporting a parked container or a parked unclassified holder changes nothing. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(c_base, kContainer); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(unk_base + 5, kUnknown); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(c_base, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(0)); + EXPECT_EQ(c_base + 1, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(1)); + EXPECT_EQ(unk_base + 2, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(2)); + EXPECT_TRUE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(unk_base + 2)); + EXPECT_EQ(2u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + // A new unclassified holder at a full buffer is dropped (no eviction). + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(40000, kUnknown); + EXPECT_FALSE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(40000)); + EXPECT_EQ(2u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + // Evict every remaining unclassified entry. + for (size_t i = 2; i < pending_cap; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(c_base + (jlong)i, kContainer); + } + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + for (size_t i = 0; i < pending_cap; i++) { + EXPECT_EQ(c_base + (jlong)i, ReferenceChainsTestAccessor::pendingLocalAnchorTagForTest(i)); + EXPECT_FALSE( + ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(unk_base + (jlong)i)); + } + + // Only confirmed containers are parked: a further container is dropped. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(50000, kContainer); + EXPECT_FALSE(ReferenceChainsTestAccessor::pendingLocalAnchorContainsForTest(50000)); + EXPECT_EQ(pending_cap, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + // Resolve empties the buffer and rewinds the cursor. + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalEvictCursorForTest()); + + tracker->stop(); +} + +// The per-pass classification request (the pure first step of reconcileAnchorClassShapes()) holds +// exactly ANCHOR_SHAPE_RECONCILE_BUDGET distinct class tags, in pending-buffer order; holders whose +// classes did not make the batch stay unclassified and are dropped by the resolve step. +TEST_F(ReferenceChainsBfsTest, AnchorShapeReconcileBudgetCapsRequestedClasses) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const int budget = ReferenceChainsTestAccessor::kAnchorShapeReconcileBudget; + const int extra = 10; + ASSERT_GT(ReferenceChainsTestAccessor::kPendingLocalAnchorCap, (size_t)(budget + extra + 1)); + ASSERT_GT(ReferenceChainsTestAccessor::kLocalAnchorIndexCap, (size_t)(budget + 1)); + + // Holder 61000 shares the first holder's class: the request must list it once. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(60000, -7000); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(61000, -7000); + for (int i = 1; i < budget + extra; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(60000 + i, -(jlong)(7000 + i)); + } + ASSERT_EQ((size_t)(budget + extra + 1), + ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + std::vector req = ReferenceChainsTestAccessor::unclassifiedAnchorClassTagsForTest(); + ASSERT_EQ((size_t)budget, req.size()); + for (int i = 0; i < budget; i++) { + EXPECT_EQ(-(jlong)(7000 + i), req[i]); + } + + // Classify the requested batch as containers; the remainder stays unclassified and is dropped. + for (jlong class_tag : req) { + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + } + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ((size_t)(budget + 1), ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_EQ((size_t)(budget + 1), ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_TRUE(ReferenceChainsTestAccessor::unclassifiedAnchorClassTagsForTest().empty()); + + tracker->stop(); +} + +// Pending holders' classes are requested before indexed anchors' classes (the pending ones are +// dropped if left unclassified; indexed anchors just wait), and the index scan stops once the +// budget is exhausted. +TEST_F(ReferenceChainsBfsTest, AnchorShapeReconcilePrefersPendingHolders) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const int budget = ReferenceChainsTestAccessor::kAnchorShapeReconcileBudget; + const int fresh_pending = 4; + ASSERT_GT(ReferenceChainsTestAccessor::kPendingLocalAnchorCap, (size_t)(budget + fresh_pending)); + ASSERT_GT(ReferenceChainsTestAccessor::kLocalAnchorIndexCap, (size_t)(budget + 1)); + // Class-tag ranges below must stay disjoint. + ASSERT_LT(budget + 20, 500); + + // Phase 1: durable anchors with unclassified classes, then a full budget of pending classes. + const int durable_first = 20; + for (int i = 0; i < durable_first; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 80000 + i, -(jlong)(9000 + i), JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + for (int i = 0; i < budget; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(81000 + i, -(jlong)(9500 + i)); + } + std::vector req = ReferenceChainsTestAccessor::unclassifiedAnchorClassTagsForTest(); + ASSERT_EQ((size_t)budget, req.size()); + for (int i = 0; i < budget; i++) { + EXPECT_EQ(-(jlong)(9500 + i), req[i]); + } + for (int i = 0; i < durable_first; i++) { + EXPECT_EQ(std::find(req.begin(), req.end(), -(jlong)(9000 + i)), req.end()) + << "durable class requested ahead of pending classes"; + } + + // Phase 2: nothing classified, so the resolve drops every pending holder. A few new pending + // classes come first, then durable classes fill the rest of the budget in index order. + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + ASSERT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + for (int i = 0; i < fresh_pending; i++) { + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(82000 + i, -(jlong)(9800 + i)); + } + for (int i = durable_first; i < budget + durable_first; i++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 80000 + i, -(jlong)(9000 + i), JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + req = ReferenceChainsTestAccessor::unclassifiedAnchorClassTagsForTest(); + ASSERT_EQ((size_t)budget, req.size()); + for (int i = 0; i < fresh_pending; i++) { + EXPECT_EQ(-(jlong)(9800 + i), req[i]); + } + for (int j = 0; j < budget - fresh_pending; j++) { + EXPECT_EQ(-(jlong)(9000 + j), req[fresh_pending + j]); + } + + tracker->stop(); +} + +// Under a stable anchor population above the durable cap, every pass re-enlists a wave of evicted +// anchors far larger than one collect's budget. The fresh queue is the fairness mechanism: it is a +// cross-pass FIFO (unserved entries keep their position), so the oldest re-enlisted anchors are +// served first and coverage rotates through the population. A force-drained window instead +// re-selected the same wave tail every pass and starved every other holder (8968 of 9000 got zero +// selections in 20 passes). +TEST_F(ReferenceChainsBfsTest, ReenlistedAnchorsGetFifoRotationTurns) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const int kHolders = 9000; + for (int t = 1; t <= kHolders; t++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, t, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + } + for (int t = 1; t <= kHolders; t++) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + t, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + // FIFO service: the first collect serves the queue's oldest 32 entries, and a second collect + // with no enumeration in between serves the NEXT 32 - unserved entries keep their position. + std::vector queue = + ReferenceChainsTestAccessor::freshQueueTagsForTest(); + ASSERT_GE(queue.size(), 64u); + // The reserved split serves 16 fresh (the queue's oldest) + 16 fair-tier per collect. + std::vector s1 = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(32); + ASSERT_EQ(32u, s1.size()); + for (size_t i = 0; i < 16; i++) { + EXPECT_EQ(queue[i], s1[i]); + } + std::vector s2 = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(32); + ASSERT_EQ(32u, s2.size()); + for (size_t i = 0; i < 16; i++) { + EXPECT_EQ(queue[16 + i], s2[i]); + } + + // Churn coverage: repeated enumerate+collect passes must spread selections across the + // population instead of re-selecting one region (the pre-fix behavior selected the same 32 + // holders in every pass - 8968 of 9000 got zero selections). The 32-per-collect budget bounds + // coverage at 32 holders per pass, so full population coverage needs ~282 passes under this + // churn; 60 passes serve ~1984 selections and must reach well past the single fixed region. + std::unordered_set distinct(s1.begin(), s1.end()); + distinct.insert(s2.begin(), s2.end()); + for (int pass = 0; pass < 60; pass++) { + for (int t = 1; t <= kHolders; t++) { + if (!ReferenceChainsTestAccessor::anchorIndexContainsForTest(t)) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + t, -900, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + } + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(32); + distinct.insert(selected.begin(), selected.end()); + } + EXPECT_GT(distinct.size(), 400u); + + tracker->stop(); +} + +// A collected local container must free its anchor slot at the next walk: its frontier record +// stays selectable (EXPANDED - GC callbacks do not clear it), so compaction alone keeps the slot +// occupied and rejects replacement live containers until a search restart clears the frontier. +// The walk's GetObjectsWithTags() resolution is the liveness signal: absent tags are reclaimed +// immediately, and the freed slots admit new containers without any search reset. +TEST_F(ReferenceChainsBfsTest, WalkReclaimsCollectedLocalAnchors) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + ReferenceChainsTestAccessor::primeClassShapeForTest(-700, true); + const size_t cap = ReferenceChainsTestAccessor::kLocalAnchorIndexCap; + for (size_t i = 0; i < cap; i++) { + jlong tag = 100 + (jlong)i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + tracker->frontierTable(), tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, -700); + } + ASSERT_EQ(cap, + ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + + // The first collect selects the fresh queue's head (the earliest-noted containers); mark them + // collected and walk them - the mock GetObjectsWithTags skips dead tags. + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(32); + ASSERT_EQ(32u, selected.size()); + for (jlong tag : selected) { + dead_tags.insert(tag); + } + int edges = 0; + ReferenceChainsTestAccessor::walkStaticFieldAnchorsForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges); + for (jlong tag : selected) { + EXPECT_FALSE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(tag)); + } + + // The reclaimed slots admit a replacement live container directly - no frontier->clear(), no + // search restart, no pending-buffer detour. + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(5000, -700); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(5000)); + + tracker->stop(); +} + +// --------------------------------------------------------------------------------------------- +// Anchor observation journal: callbacks record, the traversal caller replays at its return +// boundary. The tests below play the caller (a bound scope + flush) around the real callbacks. +// --------------------------------------------------------------------------------------------- + +// Every effect kind a callback can produce stays out of the anchor index, FIFO and share maps until +// the caller flushes; the frontier-side transition (admission, root upgrade) still happens in the +// callback. +TEST_F(ReferenceChainsBfsTest, AnchorCallbacksDeferIndexMutationToCaller) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong kContainer = -3101; + AnchorAcc::primeClassShapeForTest(kContainer, true); + // The static edge driver reports class tag 0, so the chain-attached holder's rediscovery + // eligibility rides on class 0's shape. + AnchorAcc::primeClassShapeForTest(0, true); + const jlong rediscovered = 20001; // root-attached JNI global, unindexed: REENLIST_ELIGIBLE + const jlong upgraded = 20002; // root-attached stack local, upgraded: DURABLE_ADD + const jlong holder = 20003; // chain-attached container, static edge: REENLIST + AT_RISK + insertAnchorEntry(frontier, rediscovered, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, kContainer); + insertAnchorEntry(frontier, upgraded, 0, JVMTI_HEAP_REFERENCE_STACK_LOCAL, kContainer); + insertAnchorEntry(frontier, holder, rediscovered, 0, kContainer); + + AnchorScopedPass pass(tracker, frontier); + jlong t_rediscovered = rediscovered, t_upgraded = upgraded, t_holder = holder; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &t_rediscovered)); + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &t_upgraded)); + EXPECT_EQ(JVMTI_VISIT_OBJECTS, pass.staticEdge(&t_holder)); + const jlong local = reportFreshLocal(pass, kContainer); + ASSERT_GT(local, 0); + + // One record per reporting callback; none of the index state moved yet. + EXPECT_EQ(4u, AnchorAcc::journalCountForTest()); + EXPECT_EQ(0u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, AnchorAcc::anchorOwnClassTagsSizeForTest()); + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ(0u, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_EQ(0u, AnchorAcc::freshAnchorQueueSizeForTest()); + EXPECT_EQ(0u, AnchorAcc::staticAnchorFifoSizeForTest()); + EXPECT_FALSE(AnchorAcc::durableAnchorResweepUnservedForTest()); + // The frontier transitions are not deferred: the root upgrade and the local admission landed. + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(upgraded, &entry)); + EXPECT_EQ((u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL, entry.root_kind); + ASSERT_TRUE(frontier->lookup(local, &entry)); + EXPECT_EQ((u8)JVMTI_HEAP_REFERENCE_STACK_LOCAL, entry.root_kind); + + pass.scope.flush(); + EXPECT_EQ(0u, AnchorAcc::journalCountForTest()); + for (jlong tag : {rediscovered, upgraded, holder, local}) { + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(tag)) << tag; + } + EXPECT_EQ(4u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ(3u, AnchorAcc::durableAnchorCountForTest()); + EXPECT_TRUE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + EXPECT_EQ(1u, AnchorAcc::staticAnchorFifoSizeForTest()); + + // A second flush of the now-empty prefix changes nothing. + pass.scope.flush(); + EXPECT_EQ(4u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(1u, AnchorAcc::staticAnchorFifoSizeForTest()); + EXPECT_EQ(4u, AnchorAcc::freshAnchorQueueSizeForTest()); + + tracker->stop(); +} + +#include "referenceChainsAnchorJournalTests.inc" + +// A rejected non-static report (local root) leaves the static scan alone: no retry request. +TEST_F(ReferenceChainsBfsTest, AnchorOverflowOnLocalReportRequestsNoStaticRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const u64 gen = AnchorAcc::durableAnchorResweepGenForTest(); + + // Unbounded LOCAL staging: this test exercises the journal's own capacity mechanics, while + // production bounds staging to what replay absorbs (localStagingAbsorbable()). + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0xFFFFFFFFu); + AnchorScopedPass pass(tracker, frontier); + fillJournalWithUnknownLocals(pass); + jlong rejected = 0; + EXPECT_EQ(JVMTI_ITERATION_ABORT, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, -3999, &rejected)); + EXPECT_EQ(0, rejected); + EXPECT_TRUE(pass.ctx.anchor_observation_overflow); + pass.scope.flush(); + EXPECT_EQ(gen, AnchorAcc::durableAnchorResweepGenForTest()); + EXPECT_FALSE(AnchorAcc::durableAnchorResweepUnservedForTest()); + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0); + + tracker->stop(); +} + +// A report that reserves a slot but produces no effect cancels the reservation: no slot is +// consumed (however many such reports arrive), and the slot stays usable by the next real record, +// including the very last one of the journal. +TEST_F(ReferenceChainsBfsTest, AnchorJournalCancelledReservationConsumesNoSlot) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + constexpr size_t kCapacity = AnchorObservationBuffer::CAPACITY; + const jlong kNonContainer = -3102; + AnchorAcc::primeClassShapeForTest(kNonContainer, false); + // Chain-attached non-container: a JNI-global rediscovery reserves, finds no eligible effect + // (non-container, not root-attached) and cancels. + const jlong parent = 20001, ineligible = 20002; + insertAnchorEntry(frontier, parent, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + insertAnchorEntry(frontier, ineligible, parent, 0, kNonContainer); + const jlong eligible_first = 30000; + insertRootAttachedDurableEntries(frontier, eligible_first, kCapacity); + + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < kCapacity - 1; i++) { + reportRediscovery(pass, eligible_first + (jlong)i); + } + ASSERT_EQ(kCapacity - 1, (size_t)AnchorAcc::journalCountForTest()); + // More cancelled reservations than the journal has slots left: still no overflow. + for (size_t i = 0; i < 8; i++) { + jlong tag = ineligible; + EXPECT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kNonContainer, &tag)); + } + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + EXPECT_FALSE(pass.scope.observeReturn()); + EXPECT_EQ(kCapacity - 1, (size_t)AnchorAcc::journalCountForTest()); + // The last slot is still free for a real record. + reportRediscovery(pass, eligible_first + (jlong)(kCapacity - 1)); + EXPECT_EQ(kCapacity, (size_t)AnchorAcc::journalCountForTest()); + EXPECT_FALSE(pass.ctx.anchor_observation_overflow); + pass.scope.flush(); + // The negative control: the non-container was never recorded, so it is never indexed. + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(ineligible)); + + tracker->stop(); +} + +// One callback can produce two effects (re-enlist of a reparented container plus an at-risk +// witness) in a single record: one slot, both effects applied. +TEST_F(ReferenceChainsBfsTest, AnchorJournalRecordCarriesReenlistAndAtRiskTogether) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + // The static edge driver reports class tag 0: the reparented holder is eligible through it. + AnchorAcc::primeClassShapeForTest(0, true); + const jlong parent = 20001, holder = 20002; + insertAnchorEntry(frontier, parent, 0, JVMTI_HEAP_REFERENCE_STACK_LOCAL); + insertAnchorEntry(frontier, holder, parent, 0); + + AnchorScopedPass pass(tracker, frontier); + jlong tag = holder; + EXPECT_EQ(JVMTI_VISIT_OBJECTS, pass.staticEdge(&tag)); + EXPECT_EQ(1u, AnchorAcc::journalCountForTest()); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(holder)); + EXPECT_FALSE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + pass.scope.flush(); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(holder)); + EXPECT_TRUE(AnchorAcc::freshAnchorQueueContainsForTest(holder)); + EXPECT_TRUE(AnchorAcc::staticAnchorFifoContainsForTest(holder)); + // The holder stays chain-attached: recording never re-attributes the entry. + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(holder, &entry)); + EXPECT_EQ(parent, entry.parent_tag); + + tracker->stop(); +} + +// Durable, then local, report of the same holder: the tag stays in the durable share (the local +// replay sees it already indexed) and is indexed once. +TEST_F(ReferenceChainsBfsTest, AnchorDurableThenLocalReportKeepsDurableShare) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kContainer = -3101; + AnchorAcc::primeClassShapeForTest(kContainer, true); + const jlong holder = 20001; + insertAnchorEntry(frontier, holder, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL, kContainer); + + AnchorScopedPass pass(tracker, frontier); + reportRediscovery(pass, holder, kContainer); + jlong again = holder; + // A stack-local report of an already-durable holder: no upgrade, a LOCAL record. + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_STACK_LOCAL, kContainer, &again)); + EXPECT_EQ(2u, AnchorAcc::journalCountForTest()); + pass.scope.flush(); + + EXPECT_EQ(1u, AnchorAcc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ(1u, AnchorAcc::durableAnchorCountForTest()); + EXPECT_EQ(1u, AnchorAcc::freshAnchorQueueSizeForTest()); + + tracker->stop(); +} + +// A deferred durable upgrade of a local holder frees its local slot at replay: the local share, +// full before, accepts the next local holder. +TEST_F(ReferenceChainsBfsTest, AnchorPromotionAtReplayFreesLocalSlot) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kContainer = -3101; + AnchorAcc::primeClassShapeForTest(kContainer, true); + const size_t local_cap = AnchorAcc::kLocalAnchorIndexCap; + const jlong promoted = 20001; + insertAnchorEntry(frontier, promoted, 0, JVMTI_HEAP_REFERENCE_STACK_LOCAL, kContainer); + AnchorAcc::noteLocalRootHolderForTest(promoted, kContainer); + for (size_t i = 1; i < local_cap; i++) { + AnchorAcc::noteLocalRootHolderForTest(30000 + (jlong)i, kContainer); + } + ASSERT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + + AnchorScopedPass pass(tracker, frontier); + jlong tag = promoted; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &tag)); + EXPECT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); // deferred: slot still held + pass.scope.flush(); + EXPECT_EQ(local_cap - 1, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ(1u, AnchorAcc::durableAnchorCountForTest()); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(promoted)); + + // The freed slot admits a new local holder. + const jlong fresh = reportFreshLocal(pass, kContainer); + pass.scope.flush(); + EXPECT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(fresh)); + + tracker->stop(); +} + +// The recorded observation is a callback-time snapshot: later evidence changes before the flush +// (a demotion under a chain, a reparent under a durable root) neither undo the anchor effect nor +// make it re-validate against the final frontier state. +TEST_F(ReferenceChainsBfsTest, AnchorObservationIsCallbackTimeSnapshotAcrossDemotion) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kContainer = -3101; + AnchorAcc::primeClassShapeForTest(kContainer, true); + const jlong durable = 20001, parent = 20002, local_parent = 20003; + insertAnchorEntry(frontier, durable, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + insertAnchorEntry(frontier, parent, 0, JVMTI_HEAP_REFERENCE_STACK_LOCAL); + insertAnchorEntry(frontier, local_parent, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + + AnchorScopedPass pass(tracker, frontier); + // (1) A durable report of a holder whose class is not a container: eligible at callback time + // only because it is root-attached. + reportRediscovery(pass, durable, /*class_tag=*/-3102); + // (2) A local report whose holder is later reparented under a durable root. + const jlong local = reportFreshLocal(pass, kContainer); + ASSERT_GT(local, 0); + // Later callbacks of the same traversal: the durable holder is demoted under a chain, the local + // holder is moved under a durable root. + ASSERT_TRUE(frontier->improveChain(durable, parent, 0, 1, 0)); + ASSERT_TRUE(frontier->improveChain(local, local_parent, 0, 1, 0)); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(durable, &entry)); + ASSERT_EQ(parent, entry.parent_tag); + + pass.scope.flush(); + // Both anchors are indexed from their callback-time evidence although the final frontier shape + // no longer qualifies the durable holder (non-container, chain-attached). + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(durable)); + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(local)); + EXPECT_EQ(1u, AnchorAcc::localAnchorCountForTest()); + ASSERT_TRUE(frontier->lookup(durable, &entry)); + EXPECT_EQ(parent, entry.parent_tag); // the demotion itself is not undone + + tracker->stop(); +} + +// Class-tag snapshot: a re-enlist is indexed under the CALLBACK's class tag (it decided +// eligibility), while a deferred root upgrade is indexed under the entry's stored class tag. +// Selectability of a chain-attached holder rides on that indexed class, so selection reads it back. +TEST_F(ReferenceChainsBfsTest, AnchorObservationClassTagFollowsCallbackSnapshot) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kContainer = -3101, kOther = -3102, kUnclassified = -3103; + AnchorAcc::primeClassShapeForTest(kContainer, true); + AnchorAcc::primeClassShapeForTest(kOther, false); + const jlong root = 20001; + insertAnchorEntry(frontier, root, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + // Re-enlist: stored class is non-container, the callback reports the container class. + const jlong reenlisted = 20002; + insertAnchorEntry(frontier, reenlisted, root, 0, kOther); + // Upgrade: stored class is the container, the callback reports an unclassified class. + const jlong upgraded = 20003; + insertAnchorEntry(frontier, upgraded, 0, JVMTI_HEAP_REFERENCE_STACK_LOCAL, kContainer); + + AnchorScopedPass pass(tracker, frontier); + jlong t1 = reenlisted, t2 = upgraded; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kContainer, &t1)); + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + pass.root(JVMTI_HEAP_ROOT_JNI_GLOBAL, kUnclassified, &t2)); + ASSERT_EQ(2u, AnchorAcc::journalCountForTest()); + // Before the flush the upgraded holder is demoted under the root: it is then selectable only + // through the class it was indexed under. + ASSERT_TRUE(frontier->improveChain(upgraded, root, 0, 1, 0)); + pass.scope.flush(); + ASSERT_TRUE(AnchorAcc::anchorIndexContainsForTest(reenlisted)); + ASSERT_TRUE(AnchorAcc::anchorIndexContainsForTest(upgraded)); + + std::vector selected = AnchorAcc::collectStaticFieldAnchorsForRotationForTest(8); + EXPECT_NE(std::find(selected.begin(), selected.end(), reenlisted), selected.end()) + << "re-enlist must be indexed under the callback's class tag"; + EXPECT_NE(std::find(selected.begin(), selected.end(), upgraded), selected.end()) + << "upgrade must be indexed under the entry's stored class tag"; + + tracker->stop(); +} + +// Replayed local reports honor the classification and capacity contracts end to end: a full local +// share parks further confirmed containers in the pending buffer, where they displace the oldest +// unclassified entry; unclassified reports beyond the pending cap are dropped. +TEST_F(ReferenceChainsBfsTest, AnchorReplayedLocalsHonorPendingCapAndConfirmedPriority) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kContainer = -3101, kUnknown = -3104; + AnchorAcc::primeClassShapeForTest(kContainer, true); + const size_t local_cap = AnchorAcc::kLocalAnchorIndexCap; + const size_t pending_cap = AnchorAcc::kPendingLocalAnchorCap; + + // This test exercises replay's pending-cap and displacement mechanics, so staging is unbounded. + // Set the override before constructing the scope, which snapshots the production budget. + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0xFFFFFFFFu); + AnchorScopedPass pass(tracker, frontier); + for (size_t i = 0; i < local_cap; i++) { + ASSERT_GT(reportFreshLocal(pass, kContainer), 0); + } + std::vector unknown; + for (size_t i = 0; i < pending_cap; i++) { + unknown.push_back(reportFreshLocal(pass, kUnknown)); + ASSERT_GT(unknown.back(), 0); + } + const jlong confirmed = reportFreshLocal(pass, kContainer); + const jlong dropped = reportFreshLocal(pass, kUnknown); + ASSERT_GT(confirmed, 0); + ASSERT_GT(dropped, 0); + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(0); + EXPECT_EQ(0u, AnchorAcc::localAnchorCountForTest()); // nothing applied before the flush + pass.scope.flush(); + + EXPECT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + EXPECT_EQ(pending_cap, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_TRUE(AnchorAcc::pendingLocalAnchorContainsForTest(confirmed)) + << "a confirmed container outranks an unclassified pending entry"; + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(unknown.front())); + EXPECT_TRUE(AnchorAcc::pendingLocalAnchorContainsForTest(unknown[1])); + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(dropped)) + << "an unclassified report past the pending cap is dropped"; + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(confirmed)); // no free local slot yet + + // Classification happens outside the callbacks: the unclassified entries are dropped, and the + // parked container waits for a slot (live local share, compaction backs off). + AnchorAcc::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(0u, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_EQ(local_cap, AnchorAcc::localAnchorCountForTest()); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(confirmed)); + + tracker->stop(); +} + +// Locals of a class classified only after the report wait in the pending buffer and are indexed by +// the later resolution; locals of a classified non-container are never indexed or parked. +TEST_F(ReferenceChainsBfsTest, AnchorReplayedLocalsClassifiedLaterOrRejectedAsNonContainer) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong kLater = -3105, kNonContainer = -3102; + AnchorAcc::primeClassShapeForTest(kNonContainer, false); + + AnchorScopedPass pass(tracker, frontier); + std::vector later; + for (int i = 0; i < 3; i++) { + later.push_back(reportFreshLocal(pass, kLater)); + } + std::vector rejected; + for (int i = 0; i < 2; i++) { + rejected.push_back(reportFreshLocal(pass, kNonContainer)); + } + EXPECT_EQ(3u, AnchorAcc::journalCountForTest()); // unclassified holders stage; classified + // non-containers replay as a no-op and are + // skipped at staging time + pass.scope.flush(); + EXPECT_EQ(3u, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_EQ(0u, AnchorAcc::anchorIndexSizeForTest()); + for (jlong tag : rejected) { + EXPECT_FALSE(AnchorAcc::pendingLocalAnchorContainsForTest(tag)); + EXPECT_FALSE(AnchorAcc::anchorIndexContainsForTest(tag)); + } + + AnchorAcc::primeClassShapeForTest(kLater, true); // reconcile classified it meanwhile + AnchorAcc::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(0u, AnchorAcc::pendingLocalAnchorCountForTest()); + EXPECT_EQ(3u, AnchorAcc::localAnchorCountForTest()); + for (jlong tag : later) { + EXPECT_TRUE(AnchorAcc::anchorIndexContainsForTest(tag)); + } + + tracker->stop(); +} + +// === Tests integrated from the earlier reference-chain rework, adapted to this branch's +// journal and pending-buffer design === + +// Dead entries inside the fresh-queue window (the ABANDONED shape the production death path +// leaves): the selection must skip them, spend their first look, and drain the queue in +// admission order. The selection also reclaims the dead entries it skipped - the walk's +// missing-anchor path can never see them again - so the index sheds them in the same pass. +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 selection lap, and the dead entries the scan reclaims compact +// the index after the pass consumed its positions: the stale cursor clamps to 0 on the next lap, +// so survivors the dead entries shadowed are served immediately - none lost. +TEST_F(ReferenceChainsBfsTest, FairCursorAfterPruneServesSkippedSurvivorsNextLap) { + 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, so this lap continues at 954-957; the dead 950/951 are + // reclaimed when the pass ends, compacting the survivors and resetting the stale cursor. + EXPECT_EQ((std::vector{954, 955, 956, 957}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)); + EXPECT_EQ((std::vector{952, 953, 954, 955}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)); + EXPECT_EQ((std::vector{956, 957, 958, 959}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)) + << "the lap wrapped: every survivor keeps its fair turn, none lost"; +} + +// Dead durable entries the selection cannot pick (missing frontier lookup or the ABANDONED state +// the release machinery leaves) are reclaimed by the selection scan itself: below the durable cap +// nothing else reclaims them - the walk's missing-anchor path only sees tags the scan picked. +TEST_F(ReferenceChainsBfsTest, RotationScanReclaimsDeadEntriesBelowCap) { + 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(); + int holderA = addNode(); + int holderC = addNode(); + node_tags[holderA] = tracker->nextTag(); + // Beyond any slot the inserted holders can grow the table to: the released-tag shape. + const jlong missing_tag = 5000; + node_tags[holderC] = tracker->nextTag(); + const jlong unknown_class_tag = -106; + // Durable admissions index every tag directly (root-attached JNI_GLOBAL holders stay + // selectable without a classified shape); holderA and holderC get real frontier slots. + for (jlong tag : + {node_tags[holderA], missing_tag, node_tags[holderC]}) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, unknown_class_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderA], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderC], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + // holderC's object died: its frontier record moves to ABANDONED (the entry itself is kept + // to block tag reuse). + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderC], 0, 0, FrontierEntryState::ABANDONED, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_EQ(3u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + const u64 resweep_before = + ReferenceChainsTestAccessor::durableAnchorResweepGenForTest(); + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_EQ((std::vector{node_tags[holderA]}), selected) + << "only the live holder is picked; dead entries are skipped, not selected"; + EXPECT_EQ((std::vector{node_tags[holderA]}), + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()) + << "the scan reclaims both dead shapes below the durable cap"; + EXPECT_EQ(resweep_before, + ReferenceChainsTestAccessor::durableAnchorResweepGenForTest()) + << "a dead-entry reclaim displaces nothing live, so no resweep is requested"; + // The compaction must leave the scan usable: the live holder is picked again. + EXPECT_EQ((std::vector{node_tags[holderA]}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4)); +} + +// A dead entry's queued fresh turn is dropped with its index entry: the tag can never be picked +// again, so retaining the turn would only spend a later pass on it. The no-budget drain pops +// still-indexed turns (spent via the served mark), so the turn must sit beyond the fresh-room +// cutoff when the reclaim runs to exercise the reclaim's own queue drop. +TEST_F(ReferenceChainsBfsTest, RotationScanPruneDropsDeadQueuedTurn) { + 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(); + + // One leak-tagged anchor: it takes the whole 2-budget's leak half, leaving fresh_room 1. + const jlong leak_anchor = 870; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, leak_anchor, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + frontier->setLeakTag(leak_anchor, 777, /*leak_tag_incarnation=*/0); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + leak_anchor, 599999, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest(599999, false); + // Three regular anchors, admitted in order - their fresh turns queue FIFO. + for (jlong tag : {880, 881, 882}) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, 610000 + (tag - 880), JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest( + 610000 + (tag - 880), true); + } + ASSERT_EQ(4u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); + // 881 dies while its turn is still queued: the frontier record goes away (the missing-lookup + // dead shape), but the index and the queued turn keep it for now. + frontier->clear(881); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(2); + EXPECT_EQ((std::vector{leak_anchor, 880}), selected) + << "the leak tier leads; 880's queued turn becomes the one fresh pick"; + // fresh_room 1 popped 880's turn (fresh-kept); 881 (dead) and 882 sit beyond the cutoff - + // the reclaim drops 881's queued turn with its index entry, keeping 882's. + EXPECT_EQ(1u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); + EXPECT_EQ((std::vector{leak_anchor, 880, 882}), + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()); + // The live queued turn is still spendable: the next pass pops it as a fresh pick. + selected = ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(2); + EXPECT_EQ((std::vector{leak_anchor, 882}), selected); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::staticAnchorFreshQueueSizeForTest()); +} + +// Alive-but-ineligible entries (a reparented holder with a classified non-container shape) are +// skipped by the selection without being reclaimed: the class-tag refresh or shape +// reconciliation can make them selectable again, so only provably dead entries leave the index. +TEST_F(ReferenceChainsBfsTest, RotationScanPruneKeepsLiveIneligibleEntries) { + 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 (jlong tag : {890, 891}) { + // parent_tag != 0: not root-attached, so eligibility falls to the classified shape - + // NON_CONTAINER here, which isSelectableAnchor() refuses. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 999, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, 620000 + (tag - 890), JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::primeClassShapeForTest( + 620000 + (tag - 890), false); + } + ASSERT_EQ(2u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_TRUE(selected.empty()); + EXPECT_EQ((std::vector{890, 891}), + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()) + << "live-but-ineligible entries stay indexed; only dead entries are reclaimed"; + EXPECT_FALSE( + ReferenceChainsTestAccessor::durableAnchorResweepUnservedForTest()); +} + +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"; +} + +// 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()); +} + +// 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"; + for (const auto &at_risk : drained) { + if (std::find(selection.begin(), selection.end(), at_risk.tag) == + selection.end()) { + selection.push_back(at_risk.tag); + } + } + 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; + for (const auto &at_risk : next) { + if (std::find(full.begin(), full.end(), at_risk.tag) == full.end()) { + full.push_back(at_risk.tag); + } + } + EXPECT_EQ(selection, full) << "a drained duplicate of a persistent pick is not repeated"; +} + +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)); + ReferenceChainAnchorObservationScope scope(tracker); + ReferenceChainPassContext ctx{scope}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + 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); + } + scope.flush(); + 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: before classification the + // witness only reached the at-risk FIFO (drained above), never the index. + ReferenceChainsTestAccessor::primeClassShapeForTest(holder_class_tag, false); + EXPECT_TRUE(ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4).empty()); + ReferenceChainsTestAccessor::primeClassShapeForTest(holder_class_tag, true); + // The sweep repeats every pass: once the shape is confirmed, the same static edge onto the + // chain-attached holder journals a re-enlist, and the flush applies it (the holder stays + // indexed after its first look from here on). + ReferenceChainsTestAccessor::reportHeapReferenceForTest( + JVMTI_HEAP_REFERENCE_STATIC_FIELD, holder_class_tag, + &node_tags[holder], &owner_class_tag, &ctx); + scope.flush(); + 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); + ReferenceChainAnchorObservationScope scope(tracker); + ReferenceChainPassContext ctx{scope}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + 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); + } + } + // The durable-root reports journal their index effect; the flush after the callback calls + // applies it (the callbacks only record). + scope.flush(); + 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); +} + +// Indexed holders whose objects die stop resolving in GetObjectsWithTags(); the anchor walk +// drops them from the rotation index (removeMissingAnchors()) instead of accumulating them for +// the tracker's lifetime (released tags get re-minted, so the same holder would otherwise +// re-index under its fresh tag every pass). Adapted from the earlier rework's walk-path test: the +// prune covers tags the scan picked; the selection scan reclaims the tags it must skip +// (RotationScanReclaimsDeadEntriesBelowCap). +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; + FrontierTable *frontier = tracker->frontierTable(); + int holderA = addNode(); + int holderC = addNode(); + node_tags[holderA] = tracker->nextTag(); + // Beyond any slot the inserted holder can grow the table to: the released-tag shape. + const jlong holderB_tag = 5000; + node_tags[holderC] = tracker->nextTag(); + const jlong unknown_class_tag = -106; + // Durable admissions index every tag directly (root-attached JNI_GLOBAL holders stay + // selectable without a classified shape); holderA and holderC get real frontier slots. + for (jlong tag : {node_tags[holderA], holderB_tag, node_tags[holderC]}) { + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, unknown_class_tag, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + } + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderA], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, node_tags[holderC], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_EQ(3u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + + // HolderA's object died (the walk's tag resolution no longer reports it), holderB's tag was + // never backed by a live object; holderC stays live. Both dead shapes must leave the index. + dead_tags.insert(node_tags[holderA]); + dead_tags.insert(holderB_tag); + int edges = 0; + ReferenceChainsTestAccessor::walkStaticAnchorFifoForTest( + &mock_jvmti, &mock_jni, + {node_tags[holderA], holderB_tag, node_tags[holderC]}, 1000, &edges, + nullptr); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().size()); + EXPECT_EQ(node_tags[holderC], + ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest()[0]); + + dead_tags.insert(node_tags[holderC]); + ReferenceChainsTestAccessor::walkStaticAnchorFifoForTest( + &mock_jvmti, &mock_jni, {node_tags[holderC]}, 1000, &edges, nullptr); + ASSERT_TRUE(ReferenceChainsTestAccessor::staticAnchorIndexTagsForTest().empty()); +} + +// 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; + ReferenceChainAnchorObservationScope scope(tracker); + ReferenceChainPassContext ctx{scope}; + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 1000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + jlong zero_class_tag = 0; + ASSERT_EQ(JVMTI_ITERATION_CONTINUE, + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_JNI_GLOBAL, zero_class_tag, &node_tags[holder], &ctx)); + scope.flush(); + 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)); + scope.flush(); + ReferenceChainsTestAccessor::clearPriorityExpand(); + auto selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + ASSERT_EQ(std::vector{node_tags[holder]}, selected); +} + + +// A pending local holder whose bounded hierarchy walk ended truncated is indexed like a +// confirmed container: the walk could not prove a non-match, so the holder keeps its +// selection eligibility (isSelectableAnchor() accepts the same shapes). +TEST_F(ReferenceChainsBfsTest, TruncatedLocalShapeStaysSelectable) { + 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 holder = addNode(); + const jlong tag = tracker->nextTag(); + node_tags[holder] = (int)tag; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + const jlong truncated_class_tag = -701; + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(tag, truncated_class_tag); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + ReferenceChainsTestAccessor::primeTruncatedClassShapeForTest(truncated_class_tag); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest(tag)); + auto selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest(4); + EXPECT_NE(std::find(selected.begin(), selected.end(), tag), selected.end()) + << "a truncated classification must not cache a permanent non-match"; +} + +// A failed GetObjectsWithTags() walks nothing, so every selected anchor must come back unwalked: +// the caller requeues them instead of marking their first looks served without a walk. Without +// this, an evicted holder whose only queued visit was the failed selection loses it for good. +TEST_F(ReferenceChainsBfsTest, GetObjectsWithTagsFailureKeepsSelectedAnchorsUnwalked) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + void *holderCls = (void *)0x4101; + addClass(holderCls, "Lcom/rc/walkfail/Holder;"); + int nodeA = addNode(); + int nodeB = addNode(); + node_tags[nodeA] = 4101; + node_tags[nodeB] = 4102; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 4101, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 4102, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 4101, 9101, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 4102, 9102, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + std::vector selected = {4101, 4102}; + + fail_get_objects_with_tags = true; + std::vector unwalked; + int edges = 0; + ReferenceChainsTestAccessor::walkStaticAnchorFifoForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges, &unwalked); + fail_get_objects_with_tags = false; + EXPECT_EQ(0, edges) << "no anchor was descended"; + EXPECT_EQ(selected, unwalked) + << "every selected anchor must be reported unwalked on resolution failure"; + + tracker->stop(); +} + +// A failed FollowReferences() descent was not walked: this anchor and everything after it stay +// unwalked, keeping their first-look turns for the retry pass. The resolved local ref pins the +// object, so a failure here is transient rather than a missing object. +TEST_F(ReferenceChainsBfsTest, FollowReferencesFailureKeepsAnchorsUnwalked) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + void *holderCls = (void *)0x4201; + addClass(holderCls, "Lcom/rc/walkfail/FollowFail;"); + int nodeA = addNode(); + int nodeB = addNode(); + node_tags[nodeA] = 4201; + node_tags[nodeB] = 4202; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 4201, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 4202, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 4201, 9201, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + 4202, 9202, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + std::vector selected = {4201, 4202}; + + follow_references_error = JVMTI_ERROR_OUT_OF_MEMORY; + std::vector unwalked; + int edges = 0; + ReferenceChainsTestAccessor::walkStaticAnchorFifoForTest( + &mock_jvmti, &mock_jni, selected, 1000, &edges, &unwalked); + follow_references_error = JVMTI_ERROR_NONE; + EXPECT_EQ(0, edges) << "no anchor was descended"; + EXPECT_EQ(selected, unwalked) + << "the failed descent and its successors must stay unwalked"; + + tracker->stop(); } diff --git a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc index 964795ae59..aae1748d57 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsBfsTests.inc @@ -596,6 +596,10 @@ TEST_F(ReferenceChainsBfsTest, FirstPassWatchesQualifiedLeakBeforeCompleting) { tracker->finishLoopIterationSerialized(&mock_jvmti, &mock_jni); EXPECT_EQ(SearchState::RUNNING, tracker->searchState()); EXPECT_EQ(1, ReferenceChainsTestAccessor::candidateCountForTest()); + + liveness->klassPopulationResetForTest(); + liveness->setGcGenerationsForTest(false); + tracker->stop(); } TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMutation) { @@ -617,21 +621,39 @@ TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMu 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); + { + // The caller-side scope owns the journal lease: the callbacks only record, and the flush + // after the direct callback calls is the boundary that applies them. It must be gone before + // the walk facade below binds its own scope. + ReferenceChainAnchorObservationScope scope(tracker); + ReferenceChainPassContext ctx(scope); + ctx.tracker = tracker; + ctx.frontier = tracker->frontierTable(); + ctx.hop_cap = 64; + ctx.budget = 1000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + 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); + } + scope.flush(); } // 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()); + // Neither holder is indexed yet: the unclassified one waits in the pending buffer, the + // classified non-container is never indexed. + EXPECT_EQ(0u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + // Stand-in for reconcileAnchorClassShapes() + the resolve step that follows it in a pass. + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class_tag, true); + ReferenceChainsTestAccessor::resolvePendingLocalAnchorsForTest(); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); 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. @@ -659,6 +681,7 @@ TEST_F(ReferenceChainsBfsTest, RootContainerRemainsWalkableAfterReparentingAndMu EXPECT_GT(tags_ever_assigned[table], 0); EXPECT_GT(tags_ever_assigned[payload], 0); EXPECT_NE(leak_tag, node_tags[payload]); + tracker->stop(); } // Regression test for the resolveLoadedClasses() scan-skip guard: it must compare `class_count != @@ -1797,3 +1820,314 @@ TEST_F(ReferenceChainsBfsTest, ResolveOrDropPrunesDeadFrontierEntries) { // harness (design node: design-pod-in-a-jar-harness; meta-whackamole-analysis): the REAL tracker // loop (shouldRunPass -> runPass -> pollWatchedTargets, the exact threadLoop body) driven over the // scripted mock heap, asserting SYSTEM INVARIANTS instead of unit symptoms. + +// An improveChain() deeper-path invalidation must REPLACE a resolved leak chain, never +// erase it. Sequence from the late-TL RCA: a leak-correlated chain is cached, a later pass re-reaches +// its source through a strictly deeper path (improveChain() queues a deferred invalidation), the +// search then terminates (candidate/discovered slots zeroed, so no poll path can rebuild from +// them), and the next dump drains the pending invalidations. The source is still live, so the dump +// must keep re-emitting its chain, and the BFS-thread poll rebuilds it from the intact frontier. +TEST_F(ReferenceChainsBfsTest, ImprovedPathInvalidationKeepsLeakChainAcrossTerminalReset) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const u64 kSearchNs = 4242; + ReferenceChainsTestAccessor::setSearchStartNsForTest(kSearchNs); + const jlong kLeakTag = ReferenceChainsTestAccessor::leakTagBase() + 7; + const u32 kStamp = LivenessTracker::instance()->leakTagIncarnation(kLeakTag); + + int parentNode = addNode(); + int leakNode = addNode(); + script = {{JVMTI_HEAP_REFERENCE_FIELD, parentNode, leakNode, -1}}; + node_tags[leakNode] = 105; + node_tags[parentNode] = 104; + // Leak-correlated source 105, first resolved root-attached (depth 0, static field). Parent 104 + // is a durable root whose expansion delivers the deeper (depth 1) path to 105. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 105, 0, 0, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 104, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + frontier->setLeakTag(105, kLeakTag, kStamp); + + ReferenceChainEvent resolved; + ASSERT_TRUE(tracker->buildChainEvent(&mock_jvmti, &mock_jni, 105, &resolved)); + ASSERT_EQ((u64)kLeakTag, resolved._target_tag); + ASSERT_EQ(0u, resolved._depth); + ASSERT_TRUE(ReferenceChainsTestAccessor::cacheChain(105, std::move(resolved), 105, + kSearchNs)); + + // Real improveChain() path: heapReferenceCallback() sees the already-tagged 105 via 104. + ReferenceChainsTestAccessor::pushPendingExpandForTest(104); + int edges = 0; + ReferenceChainsTestAccessor::expandFrontierForTest(&mock_jvmti, &mock_jni, &edges); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(105, &entry)); + ASSERT_EQ(104, entry.parent_tag); + ASSERT_EQ(1u, entry.depth); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + + // Terminal reset (runPass()'s canary early-termination branch). + ReferenceChainsTestAccessor::setCandidateCountForTest(0); + ReferenceChainsTestAccessor::setCandidateFoundBitsForTest(0); + + // Dump: the still-live leak chain must survive the drain. + std::vector dump; + ReferenceChainsTestAccessor::drain(&dump); + ASSERT_EQ(1u, dump.size()) << "improveChain invalidation erased a live leak chain"; + EXPECT_EQ((u64)kLeakTag, dump[0]._target_tag); + EXPECT_EQ(kStamp, dump[0]._leak_tag_incarnation); + + // BFS-thread poll: rebuilds the chain from the intact frontier with the deeper path. + LivenessTracker::instance()->klassPopulationResetForTest(); + LivenessTracker::instance()->setGcGenerationsForTest(true); + tracker->pollWatchedTargets(&mock_jvmti, &mock_jni); + LivenessTracker::instance()->setGcGenerationsForTest(false); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + dump.clear(); + ReferenceChainsTestAccessor::drain(&dump); + ASSERT_EQ(1u, dump.size()); + EXPECT_EQ((u64)kLeakTag, dump[0]._target_tag); + EXPECT_EQ(1u, dump[0]._depth) << "rebuild must pick up the improved (deeper) path"; + + tracker->stop(); +} + +// Split semantics: the dump path applies only EVICT (noise eviction still erases at +// dump time, exactly as before), EVICT wins over a REBUILD queued for the same tag, and REBUILD is +// left for the BFS-thread poll, which keeps the old chain when the frontier cannot rebuild it. +TEST_F(ReferenceChainsBfsTest, DumpDrainAppliesEvictAndLeavesRebuildToPoll) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + const u64 kSearchNs = 777; + ReferenceChainsTestAccessor::setSearchStartNsForTest(kSearchNs); + for (jlong tag = 1; tag <= 3; tag++) { + ReferenceChainEvent event; + event._target_tag = (u64)tag; + ASSERT_TRUE(ReferenceChainsTestAccessor::cacheChain(tag, std::move(event), tag, + kSearchNs)); + } + std::vector snapshot = ReferenceChainsTestAccessor::snapshotResolvedChainTags(); + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(1, snapshot); // noise eviction + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(2, snapshot, true); + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(3, snapshot, true); + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(3, snapshot); // EVICT wins + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(2, snapshot, true); // deduped + EXPECT_EQ(3u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + + std::vector dump; + ReferenceChainsTestAccessor::drain(&dump); + EXPECT_FALSE(ReferenceChainsTestAccessor::hasResolvedChainForTag(1)) + << "noise-evicted chain must still be erased at dump time"; + EXPECT_FALSE(ReferenceChainsTestAccessor::hasResolvedChainForTag(3)) + << "EVICT queued after REBUILD must erase, not keep, the chain"; + EXPECT_TRUE(ReferenceChainsTestAccessor::hasResolvedChainForTag(2)); + ASSERT_EQ(1u, dump.size()); + EXPECT_EQ(2u, dump[0]._target_tag); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()) + << "REBUILD stays pending for the BFS thread"; + EXPECT_EQ(0u, ReferenceChainsTestAccessor::drainingChainInvalidationCount()); + + // No frontier entry for tag 2: the poll's rebuild fails and the old chain is kept. + LivenessTracker::instance()->klassPopulationResetForTest(); + LivenessTracker::instance()->setGcGenerationsForTest(true); + tracker->pollWatchedTargets(&mock_jvmti, &mock_jni); + LivenessTracker::instance()->setGcGenerationsForTest(false); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + EXPECT_TRUE(ReferenceChainsTestAccessor::hasResolvedChainForTag(2)); + EXPECT_FALSE(ReferenceChainsTestAccessor::hasResolvedChainForTag(1)); + EXPECT_FALSE(ReferenceChainsTestAccessor::hasResolvedChainForTag(3)); + + tracker->stop(); +} + +// The pending-invalidation buffers encode the kind in-band: a REBUILD tag is stored complemented +// (negative), an EVICT tag as itself. A NEGATIVE source tag's EVICT encoding therefore lands in +// the REBUILD band and decodes to a different tag - the reason deferResolvedChainInvalidation() +// refuses negative source tags (assert in debug builds, guard in release). +TEST_F(ReferenceChainsBfsTest, PendingInvalidationEncodingAliasesNegativeSourceTags) { + EXPECT_EQ(42, ReferenceChainsTestAccessor::pendingChainInvalidationTag( + ReferenceChainsTestAccessor::encodePendingChainInvalidationForTest( + 42, /*rebuild=*/false))); + EXPECT_FALSE(ReferenceChainsTestAccessor::isPendingChainRebuild( + ReferenceChainsTestAccessor::encodePendingChainInvalidationForTest( + 42, /*rebuild=*/false))); + jlong rebuild = ReferenceChainsTestAccessor::encodePendingChainInvalidationForTest( + 42, /*rebuild=*/true); + EXPECT_TRUE(ReferenceChainsTestAccessor::isPendingChainRebuild(rebuild)); + EXPECT_EQ(42, ReferenceChainsTestAccessor::pendingChainInvalidationTag(rebuild)); + + jlong negative = ReferenceChainsTestAccessor::encodePendingChainInvalidationForTest( + -1, /*rebuild=*/false); + EXPECT_TRUE(ReferenceChainsTestAccessor::isPendingChainRebuild(negative)) + << "a negative source tag's EVICT encoding collides with the REBUILD band"; + EXPECT_NE(-1, ReferenceChainsTestAccessor::pendingChainInvalidationTag(negative)); +} + +// A REBUILD queued for a chain cached by an EARLIER search generation must not be rebuilt: +// restartSearch() reassigns tag numbers, so a same-numbered chain from a previous search +// describes a different object, and a path change on the new object says nothing about it. The +// stale chain must survive the poll intact - and must not be erased by a suppressed-shape rebuild +// the scan was never supposed to run. +TEST_F(ReferenceChainsBfsTest, RebuildScanLeavesStaleGenerationChainAlone) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const u64 kOldNs = 1000, kNewNs = 2000; + ReferenceChainsTestAccessor::setSearchStartNsForTest(kOldNs); + ReferenceChainEvent stale; + stale._target_tag = (u64)2; + stale._depth = 3; + stale._root_kind = (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD; + ASSERT_TRUE(ReferenceChainsTestAccessor::cacheChain(2, std::move(stale), 2, kOldNs)); + + // The new generation's frontier holds a deeper STACK_LOCAL-rooted path under the same numeric + // tag: rebuilding it would produce a depth-1 transient-root event - a shape the discovered- + // chain gate suppresses, i.e. a rebuild here would ERASE the stale chain instead of replacing + // it. The scan's generation condition is what keeps that rebuild from running at all. + // (The rebuilt event's root kind is the chain's TERMINAL entry's, so the transient kind goes + // on the root entry 1.) + ReferenceChainsTestAccessor::setSearchStartNsForTest(kNewNs); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 1, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 2, 1, 1, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + + std::vector snapshot = ReferenceChainsTestAccessor::snapshotResolvedChainTags(); + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(2, snapshot, /*rebuild=*/true); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + + LivenessTracker::instance()->klassPopulationResetForTest(); + LivenessTracker::instance()->setGcGenerationsForTest(true); + tracker->pollWatchedTargets(&mock_jvmti, &mock_jni); + LivenessTracker::instance()->setGcGenerationsForTest(false); + + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()) + << "stale-generation REBUILD must be dropped, not left pending"; + EXPECT_TRUE(ReferenceChainsTestAccessor::hasResolvedChainForTag(2)) + << "stale-generation chain must not be erased by a suppressed-shape rebuild"; + std::vector dump; + ReferenceChainsTestAccessor::drain(&dump); + ASSERT_EQ(1u, dump.size()); + EXPECT_EQ((u64)2, dump[0]._target_tag); + EXPECT_EQ(3u, dump[0]._depth) << "stale chain must be emitted unchanged"; + + tracker->stop(); +} + +#ifdef DEBUG +// The debug hook evicts a cached entry after the REBUILD scan but before write-back. This verifies +// that the replacement does not resurrect an entry removed in that window. +TEST_F(ReferenceChainsBfsTest, RebuildWritebackNeverResurrectsDumpEvictedEntry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + const u64 kSearchNs = 555; + ReferenceChainsTestAccessor::setSearchStartNsForTest(kSearchNs); + ReferenceChainEvent cached; + cached._target_tag = (u64)7; + cached._depth = 4; + cached._root_kind = (u8)JVMTI_HEAP_REFERENCE_STATIC_FIELD; + ASSERT_TRUE(ReferenceChainsTestAccessor::cacheChain(7, std::move(cached), 7, kSearchNs)); + // Frontier entry intact and deep enough that the rebuilt event is not a suppressed shape - + // the write-back recheck, not suppression, is what must keep the evicted entry dead. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, 7, 0, 4, FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + + std::vector snapshot = ReferenceChainsTestAccessor::snapshotResolvedChainTags(); + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(7, snapshot, /*rebuild=*/true); + ASSERT_EQ(1u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + + ReferenceChainsTestAccessor::setBetweenInvalidationScanAndWritebackForTest([] { + ReferenceChainsTestAccessor::invalidateResolvedChainForTest(7); + }); + LivenessTracker::instance()->klassPopulationResetForTest(); + LivenessTracker::instance()->setGcGenerationsForTest(true); + tracker->pollWatchedTargets(&mock_jvmti, &mock_jni); + LivenessTracker::instance()->setGcGenerationsForTest(false); + ReferenceChainsTestAccessor::setBetweenInvalidationScanAndWritebackForTest(nullptr); + + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + EXPECT_FALSE(ReferenceChainsTestAccessor::hasResolvedChainForTag(7)) + << "a rebuild must never resurrect an entry evicted after the scan"; + std::vector dump; + ReferenceChainsTestAccessor::drain(&dump); + EXPECT_EQ(0u, dump.size()); + + tracker->stop(); +} +#endif + +// heapRootCallback()'s local-holder guard: only a positive tag with a class tag may reach +// noteLocalRootHolder(). A non-positive tag identifies no allocatable object; a leak tag can never +// reach the guard at all (a successful frontier conversion rewrites *tag_ptr to the fresh frontier +// tag, a failed one aborts the walk first), so the guard's leak-tag check is defense in depth. +TEST_F(ReferenceChainsBfsTest, LocalRootHolderGuardRejectsLeakAndNonPositiveTags) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const jlong kClassTag = -301; + ReferenceChainAnchorObservationScope scope(tracker); + ReferenceChainPassContext ctx(scope); + ctx.tracker = tracker; + ctx.frontier = tracker->frontierTable(); + ctx.hop_cap = 64; + ctx.budget = 1000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + + // Non-positive tags: admitObject() treats any non-zero tag as already admitted, so these + // reach the guard with their original value. + jlong negative_tag = -5; + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, kClassTag, &negative_tag, &ctx); + // No class tag: nothing to classify, so no holder to remember. + jlong classless_tag = tracker->nextTag(); + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, 0, &classless_tag, &ctx); + scope.flush(); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + + // Leak tag whose frontier conversion fails (frontier table disabled): the conversion-failure + // branch aborts the walk before the local-holder guard, so *tag_ptr keeps the leak tag and + // nothing is parked under it. + tracker->frontierTable()->resetCapacityForTest(0); + const jlong kLeakTag = ReferenceChainsTestAccessor::leakTagBase() + 3; + jlong leak_tag = kLeakTag; + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, kClassTag, &leak_tag, &ctx); + EXPECT_EQ(kLeakTag, leak_tag) << "conversion must fail on a disabled frontier table"; + EXPECT_EQ(0u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::anchorIndexSizeForTest()); + + // Control: a positive, non-leak tag with a class tag is parked for classification. Fresh + // context: the aborted report above set ctx.truncated, which would abort every later report. + ctx.truncated = false; + tracker->frontierTable()->resetCapacityForTest(1024); + jlong plain_tag = tracker->nextTag(); + ReferenceChainsTestAccessor::reportHeapRootForTest( + JVMTI_HEAP_ROOT_STACK_LOCAL, kClassTag, &plain_tag, &ctx); + scope.flush(); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::pendingLocalAnchorCountForTest()); + + tracker->stop(); +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsLifecycleTests.inc b/ddprof-lib/src/test/cpp/referenceChainsLifecycleTests.inc index b5b96bd525..695ed2a832 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsLifecycleTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsLifecycleTests.inc @@ -510,3 +510,437 @@ TEST_F(ReferenceChainsRecordingBoundaryTest, NoStaleFrontierIdsAfterRecordingBou tracker->stop(); } + +// --------------------------------------------------------------------------------------------- +// Anchor-observation journal lifecycle: lease ownership, epoch invalidation and the join gate. +// A scope is kept alive only around the traversal group it owns; scopes that outlive a lifecycle +// boundary below are deliberate stand-ins for a straggler holding a stale token. +// --------------------------------------------------------------------------------------------- + +namespace { + +using T9LAcc = ReferenceChainsTestAccessor; + +// Restores the shared singleton/mock state on every exit, including a failed ASSERT. +struct T9LTestGuard { + ReferenceChainsMockHeap &fixture; + explicit T9LTestGuard(ReferenceChainsMockHeap &f) : fixture(f) {} + ~T9LTestGuard() { + T9LAcc::setAbortPassRequestedForTest(false); +#ifdef DEBUG + T9LAcc::clearJoinResultForTest(); +#endif + fixture.jvmti_tbl.IterateOverReachableObjects = + &ReferenceChainsMockHeap::mock_IterateOverReachableObjects; + fixture.fail_get_objects_with_tags = false; + ReferenceChainTracker::instance()->stop(); + } +}; + +// A pass context bound to a caller-owned scope, as every production traversal caller builds it. +struct T9LScopedPass { + ReferenceChainAnchorObservationScope scope; + ReferenceChainPassContext ctx; + + T9LScopedPass(ReferenceChainTracker *tracker, FrontierTable *frontier) : scope(tracker), ctx(scope) { + ctx.tracker = tracker; + ctx.frontier = frontier; + ctx.hop_cap = 64; + ctx.budget = 100000; + ctx.edges_admitted = 0; + ctx.truncated = false; + ctx.frontier_cap_hit = false; + } +}; + +constexpr jlong kT9LClassTag = -3501; + +void t9lInsertRootAttachedDurable(FrontierTable *frontier, jlong tag) { + ASSERT_TRUE(T9LAcc::insertFrontierEntry(frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL, 0, kT9LClassTag)); +} + +AnchorObservation t9lAtRiskRecord(jlong tag, u32 klass_id) { + AnchorObservation record{}; + record.tag = tag; + record.at_risk_klass_id = klass_id; + record.actions = AnchorObservation::AT_RISK; + return record; +} + +AnchorObservation t9lReenlistRecord(jlong tag) { + AnchorObservation record{}; + record.tag = tag; + record.own_class_tag = kT9LClassTag; + record.actions = AnchorObservation::REENLIST_ELIGIBLE; + return record; +} + +// Root enumeration whose first report is accepted, after which the stop request arrives (what +// stopThread()'s abort flag does to an in-flight pass) and the second report is refused. +struct T9LCooperativeStop { + static inline jlong first_tag = 0; + static inline jlong second_tag = 0; + static inline int first_control = -1; + static inline int second_control = -1; + static inline jlong first_tag_after = 0; + static inline jlong second_tag_after = 0; +}; + +jvmtiError JNICALL t9lCooperativeStopIterate(jvmtiEnv *, jvmtiHeapRootCallback root_cb, + jvmtiStackReferenceCallback, jvmtiObjectReferenceCallback, + const void *user_data) { + void *ctx = const_cast(user_data); + jlong first = T9LCooperativeStop::first_tag; + T9LCooperativeStop::first_control = root_cb(JVMTI_HEAP_ROOT_JNI_GLOBAL, 0, 0, &first, ctx); + T9LCooperativeStop::first_tag_after = first; + T9LAcc::setAbortPassRequestedForTest(true); + jlong second = T9LCooperativeStop::second_tag; + T9LCooperativeStop::second_control = root_cb(JVMTI_HEAP_ROOT_JNI_GLOBAL, 0, 0, &second, ctx); + T9LCooperativeStop::second_tag_after = second; + return JVMTI_ERROR_NONE; +} + +} // namespace + +// Scopes overlapping the owner's group are non-owning: they cannot reserve, cannot latch overflow +// or a static retry on the owner's journal, cannot flush its records, and their destruction does +// not release the owner's lease. +TEST_F(ReferenceChainsBfsTest, OverlappingAnchorScopeCannotReserveOverflowFlushOrReleaseOwner) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + + const u64 gen = T9LAcc::durableAnchorResweepGenForTest(); + { + ReferenceChainAnchorObservationScope owner(tracker); + ASSERT_TRUE(owner.ownsLease()); + { + ReferenceChainAnchorObservationScope other(tracker); + EXPECT_FALSE(other.ownsLease()); + { + AnchorObservationReservation reservation = other.reserve(); + EXPECT_FALSE(reservation.held()); + reservation.commit(t9lAtRiskRecord(901, 7)); // a refused reservation records nothing + } + other.markOverflow(/*static_attachment=*/true); + EXPECT_TRUE(other.observeReturn()) << "a non-owning scope has no journal: abort, don't lose"; + other.flush(); + } + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + EXPECT_FALSE(owner.observeReturn()) << "the overlapping scope latched overflow on the owner"; + + { + AnchorObservationReservation reservation = owner.reserve(); + ASSERT_TRUE(reservation.held()); + reservation.commit(t9lAtRiskRecord(901, 7)); + } + ASSERT_EQ(1u, T9LAcc::journalCountForTest()); + { + // The owner's destructor-free lease is still the only one: a later overlapping scope + // (after the earlier one was destroyed) is non-owning too, and flushing it replays nothing. + ReferenceChainAnchorObservationScope later(tracker); + EXPECT_FALSE(later.ownsLease()) << "destroying a non-owning scope released the owner's lease"; + later.flush(); + } + EXPECT_EQ(1u, T9LAcc::journalCountForTest()) << "a non-owning flush consumed the owner's record"; + EXPECT_FALSE(T9LAcc::staticAnchorFifoContainsForTest(901)); + + owner.flush(); + EXPECT_TRUE(T9LAcc::staticAnchorFifoContainsForTest(901)); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + } + EXPECT_EQ(gen, T9LAcc::durableAnchorResweepGenForTest()) + << "a non-owning markOverflow(static) must not request a resweep"; + ReferenceChainAnchorObservationScope next(tracker); + EXPECT_TRUE(next.ownsLease()) << "the owner's destruction must release its lease"; +} + +// A stop()/start() cycle reusing numeric tag 1 invalidates every outstanding token: the stale +// scope's flush is discarded before any tag lookup (its positive, non-empty payload would index +// the NEW recording's tag 1), cannot touch the new owner's journal, and its destruction cannot +// release the new lease. +TEST_F(ReferenceChainsBfsTest, StaleAnchorScopeAfterStopStartCannotReplayOrReleaseNewLease) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + + t9lInsertRootAttachedDurable(tracker->frontierTable(), 1); + auto stale = std::make_unique(tracker); + ASSERT_TRUE(stale->ownsLease()); + { + AnchorObservationReservation r1 = stale->reserve(); + ASSERT_TRUE(r1.held()); + r1.commit(t9lReenlistRecord(1)); + } + { + AnchorObservationReservation r2 = stale->reserve(); + ASSERT_TRUE(r2.held()); + r2.commit(t9lAtRiskRecord(902, 3)); + } + ASSERT_EQ(2u, T9LAcc::journalCountForTest()); + const u64 epoch_before = T9LAcc::journalEpochForTest(); + + tracker->stop(); + ASSERT_GT(T9LAcc::journalEpochForTest(), epoch_before); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + ASSERT_FALSE(tracker->start(args)); + // The new recording reuses numeric tag 1 for a different object. + t9lInsertRootAttachedDurable(tracker->frontierTable(), 1); + EXPECT_FALSE(T9LAcc::anchorIndexContainsForTest(1)); + + auto fresh = std::make_unique(tracker); + ASSERT_TRUE(fresh->ownsLease()) << "the epoch bump must clear the stale lease"; + { + AnchorObservationReservation reservation = fresh->reserve(); + ASSERT_TRUE(reservation.held()); + reservation.commit(t9lAtRiskRecord(903, 4)); + } + ASSERT_EQ(1u, T9LAcc::journalCountForTest()); + + { + AnchorObservationReservation reservation = stale->reserve(); + EXPECT_FALSE(reservation.held()); + } + stale->markOverflow(/*static_attachment=*/true); + stale->flush(); + EXPECT_FALSE(T9LAcc::anchorIndexContainsForTest(1)) << "a stale payload was replayed"; + EXPECT_FALSE(T9LAcc::staticAnchorFifoContainsForTest(902)); + EXPECT_EQ(1u, T9LAcc::journalCountForTest()) << "the stale scope touched the new journal"; + EXPECT_FALSE(fresh->observeReturn()); + stale.reset(); // must not release the new owner's lease + { + ReferenceChainAnchorObservationScope overlapping(tracker); + EXPECT_FALSE(overlapping.ownsLease()) << "a stale token released the new lease"; + } + + fresh->flush(); + EXPECT_TRUE(T9LAcc::staticAnchorFifoContainsForTest(903)); + EXPECT_FALSE(T9LAcc::staticAnchorFifoContainsForTest(902)); + EXPECT_FALSE(T9LAcc::anchorIndexContainsForTest(1)); +} + +// The accepted prefix is applied when a cooperative stop aborts the walk, and the refused report +// leaves its object untouched. +TEST_F(ReferenceChainsBfsTest, CooperativeStopAppliesAcceptedPrefixBeforePassReturns) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + + const jlong leak_base = T9LAcc::leakTagBase(); + T9LCooperativeStop::first_tag = leak_base; + T9LCooperativeStop::second_tag = leak_base + 1; + jvmti_tbl.IterateOverReachableObjects = &t9lCooperativeStopIterate; + T9LAcc::setRootEnumRawStateForTest(0, 0); + + bool truncated = false; + tracker->runPass(&mock_jvmti, &mock_jni, &truncated); + EXPECT_EQ((int)JVMTI_ITERATION_CONTINUE, T9LCooperativeStop::first_control); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, T9LCooperativeStop::second_control); + const jlong admitted = T9LCooperativeStop::first_tag_after; + ASSERT_GT(admitted, 0); + EXPECT_NE(leak_base, admitted) << "the accepted report must have converted its leak tag"; + EXPECT_EQ(leak_base + 1, T9LCooperativeStop::second_tag_after) << "the refused report was applied"; + EXPECT_TRUE(T9LAcc::anchorIndexContainsForTest(admitted)) + << "the accepted prefix was not flushed on the stop path"; + EXPECT_EQ(1u, T9LAcc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); +} + +// JVMTI heap callbacks run on a thread other than the caller's (the VM thread). They only begin +// and commit records under the journal lock; the caller, blocked in the synchronous traversal, +// observes the return and drains. +TEST_F(ReferenceChainsBfsTest, AnchorCallbacksOnWorkerThreadOnlyRecordAndCallerFlushes) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + FrontierTable *frontier = tracker->frontierTable(); + + const jlong tags[] = {11, 12, 13}; + for (jlong tag : tags) { + t9lInsertRootAttachedDurable(frontier, tag); + } + { + T9LScopedPass pass(tracker, frontier); + int controls[3] = {-1, -1, -1}; + std::thread worker([&]() { + for (int i = 0; i < 3; i++) { + jlong tag = tags[i]; + controls[i] = T9LAcc::reportHeapRootForTest(JVMTI_HEAP_ROOT_JNI_GLOBAL, + kT9LClassTag, &tag, &pass.ctx); + } + }); + worker.join(); // the synchronous traversal returned + for (int i = 0; i < 3; i++) { + EXPECT_EQ((int)JVMTI_ITERATION_CONTINUE, controls[i]); + } + EXPECT_FALSE(pass.scope.observeReturn()); + EXPECT_EQ(3u, T9LAcc::journalCountForTest()); + EXPECT_EQ(0u, T9LAcc::anchorIndexSizeForTest()) << "a callback mutated the anchor index"; + pass.scope.flush(); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + for (jlong tag : tags) { + EXPECT_TRUE(T9LAcc::anchorIndexContainsForTest(tag)); + } + } + + // A callback worker that outruns the capacity aborts at the first record that does not fit; + // the caller sees the overflow after the join and the flush keeps the accepted prefix. The + // reports are distinct unindexed roots: a re-report of the already-indexed tags above would + // stage nothing (its replay would be a no-op) and never fill the journal. + std::vector fill_tags; + for (u32 i = 0; i <= AnchorObservationBuffer::CAPACITY; i++) { + fill_tags.push_back(100 + (jlong)i); + t9lInsertRootAttachedDurable(frontier, fill_tags.back()); + } + T9LScopedPass full(tracker, frontier); + u32 accepted = 0; + int last_control = -1; + std::thread worker([&]() { + for (u32 i = 0; i <= AnchorObservationBuffer::CAPACITY; i++) { + jlong tag = fill_tags[i]; + last_control = T9LAcc::reportHeapRootForTest(JVMTI_HEAP_ROOT_JNI_GLOBAL, kT9LClassTag, + &tag, &full.ctx); + if (last_control != JVMTI_ITERATION_CONTINUE) { + break; + } + accepted++; + } + }); + worker.join(); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, accepted); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, last_control); + EXPECT_TRUE(full.scope.observeReturn()); + EXPECT_TRUE(full.ctx.anchor_observation_overflow); + EXPECT_EQ(AnchorObservationBuffer::CAPACITY, T9LAcc::journalCountForTest()); + full.scope.flush(); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + EXPECT_FALSE(full.scope.observeReturn()); +} + +#ifdef DEBUG +// A failed pthread_join leaves the worker unjoined: start, recording-boundary teardown and the +// test reset all refuse to touch the journal a straggler could still hold, and a retry that +// succeeds lets them proceed. +TEST_F(ReferenceChainsBfsTest, StopThreadJoinFailureKeepsJournalAndRetrySucceeds) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + + auto holder = std::make_unique(tracker); + ASSERT_TRUE(holder->ownsLease()); + { + AnchorObservationReservation reservation = holder->reserve(); + ASSERT_TRUE(reservation.held()); + reservation.commit(t9lAtRiskRecord(904, 5)); + } + const u64 epoch = T9LAcc::journalEpochForTest(); + + T9LAcc::setThreadUnjoinedForTest(); + T9LAcc::setJoinResultForTest(EBUSY); + EXPECT_FALSE(tracker->stopThread()); + EXPECT_FALSE(T9LAcc::threadJoinedForTest()); + EXPECT_EQ(1, T9LAcc::joinCallCountForTest()); + + EXPECT_TRUE((bool)tracker->start(args)) << "start() must refuse while a worker is unjoined"; + tracker->stop(); + tracker->resetSearchStateForTest(&mock_jvmti, &mock_jni); + EXPECT_EQ(2, T9LAcc::joinCallCountForTest()) << "the reset retried the join once and gave up"; + EXPECT_EQ(epoch, T9LAcc::journalEpochForTest()); + EXPECT_EQ(1u, T9LAcc::journalCountForTest()) << "teardown cleared a journal the worker could hold"; + EXPECT_FALSE(T9LAcc::threadJoinedForTest()); + + T9LAcc::setJoinResultForTest(0); + EXPECT_TRUE(tracker->stopThread()); + EXPECT_TRUE(T9LAcc::threadJoinedForTest()); + EXPECT_EQ(1, T9LAcc::joinCallCountForTest()); + EXPECT_TRUE(tracker->stopThread()) << "an already joined worker needs no second join"; + EXPECT_EQ(1, T9LAcc::joinCallCountForTest()); + + tracker->stop(); + EXPECT_GT(T9LAcc::journalEpochForTest(), epoch); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + holder->flush(); // stale token: discarded + EXPECT_FALSE(T9LAcc::staticAnchorFifoContainsForTest(904)); + holder.reset(); + EXPECT_FALSE((bool)tracker->start(args)); +} +#endif + +// While a failed tag release keeps the abandoned search's tags live, nothing resets the journal; +// the restart that follows the confirmed release does, so no earlier scope can replay against the +// reused tags. +TEST_F(ReferenceChainsRecordingBoundaryTest, + TagReleaseRetryKeepsJournalUntilRestartThenInvalidatesStaleScope) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000:framecap=1:ttl=0")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9LTestGuard guard(*this); + + int nodeA = addNode(); + script = { + {JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, nodeA, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, nodeA, nodeA, -1}, + }; + fail_get_objects_with_tags = true; + bool truncated = false; + for (int i = 0; i < ReferenceChainTracker::NO_PROGRESS_PASS_LIMIT + 2; i++) { + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + } + ASSERT_EQ(SearchState::ABANDONED, tracker->searchState()); + ASSERT_FALSE(T9LAcc::tagsReleased()); + const u64 epoch = T9LAcc::journalEpochForTest(); + + auto straggler = std::make_unique(tracker); + ASSERT_TRUE(straggler->ownsLease()); + { + AnchorObservationReservation reservation = straggler->reserve(); + ASSERT_TRUE(reservation.held()); + reservation.commit(t9lReenlistRecord(1)); + } + // Failed release retries: no restart, so no journal reset. + EXPECT_TRUE(T9LAcc::shouldRunPass(1)); + EXPECT_EQ(epoch, T9LAcc::journalEpochForTest()); + EXPECT_EQ(1u, T9LAcc::journalCountForTest()); + EXPECT_EQ(SearchState::ABANDONED, tracker->searchState()); + + // Release succeeds; the restart gate then resets the search and with it the journal epoch. + fail_get_objects_with_tags = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_TRUE(T9LAcc::tagsReleased()); + // The restart gate also needs a leak-signal source and a growing candidate (this fixture's + // TearDown restores the no-signal state). + LivenessTracker::instance()->setGcGenerationsForTest(true); + int fake_object_storage = 0; + for (u16 i = 1; i <= 20; i++) { + int slot; + bool created; + LivenessTracker::instance()->klassPopulationRecordForTest(/*klass_id=*/1, i, i, &slot, &created); + LivenessTracker::instance()->tidTrendRecordForTest(/*klass_id=*/1, /*tid=*/4242, (u32)i, (u64)i); + } + LivenessTracker::instance()->klassPopulationSetRepresentativeForTest( + nullptr, /*klass_id=*/1, (jweak)&fake_object_storage); + EXPECT_TRUE(T9LAcc::shouldRunPass(OS::nanotime() + 3600ULL * 1000000000ULL)); + ASSERT_EQ(SearchState::RUNNING, tracker->searchState()) << "the restart gate did not fire"; + EXPECT_GT(T9LAcc::journalEpochForTest(), epoch); + EXPECT_EQ(0u, T9LAcc::journalCountForTest()); + + // The reused numeric tag 1 now names a new entry; the straggler's stale record must not index it. + t9lInsertRootAttachedDurable(tracker->frontierTable(), 1); + straggler->flush(); + EXPECT_FALSE(T9LAcc::anchorIndexContainsForTest(1)); + straggler.reset(); + ReferenceChainAnchorObservationScope next(tracker); + EXPECT_TRUE(next.ownsLease()); +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h b/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h index e7872219b3..22d65f6a25 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h +++ b/ddprof-lib/src/test/cpp/referenceChainsMockHeap.h @@ -128,6 +128,27 @@ class ReferenceChainsMockHeap { // the script - drives runPassManualWalk()'s root_err != JVMTI_ERROR_NONE path. jvmtiError ior_error = JVMTI_ERROR_NONE; + // When set, mock_IterateOverReachableObjects() delivers up to ior_prefix_count root callbacks + // and then returns this error (also when the script has fewer roots). A callback abort ends the + // walk first with JVMTI_ERROR_NONE, as a real abort does. + jvmtiError ior_error_after_prefix = JVMTI_ERROR_NONE; + int ior_prefix_count = 0; + + // Same prefix-then-error contract for mock_FollowReferences(); the prefix counts every + // heap_reference_callback invocation of one call (holder-walk and script edges alike). + jvmtiError follow_error_after_prefix = JVMTI_ERROR_NONE; + int follow_prefix_count = 0; + + // Last control value each mock walk saw returned by the production callback (the root + // callback's jvmtiIterationControl, the reference callback's jint visit flags); -1 = none yet. + int last_ior_control = -1; + int last_follow_control = -1; + + // When non-empty, mock_GetObjectsWithTags() reports its resolved objects in this order of + // positions within the request-ordered resolved list (out-of-range entries are skipped, + // positions not named are dropped) instead of request order. + std::vector gotw_resolution_order; + // Synthetic frontier-holder arrays for expandFrontier()'s array-holder walk: // mock_NewObjectArray() hands back an opaque handle, mock_SetObjectArrayElement() records its // elements here, and mock_FollowReferences() treats every recorded element as an expansion seed @@ -570,10 +591,15 @@ class ReferenceChainsMockHeap { if (active_fixture->ior_error != JVMTI_ERROR_NONE) { return active_fixture->ior_error; } + int ior_delivered = 0; for (auto &e : active_fixture->script) { if (e.referrer_idx != -1) { continue; } + if (active_fixture->ior_error_after_prefix != JVMTI_ERROR_NONE && + ior_delivered >= active_fixture->ior_prefix_count) { + return active_fixture->ior_error_after_prefix; + } jlong class_tag = 0; if (e.class_idx >= 0) { class_tag = active_fixture->tags[active_fixture->classes[e.class_idx].klass]; @@ -585,11 +611,13 @@ class ReferenceChainsMockHeap { if (*tag_ptr != 0) { active_fixture->tags_ever_assigned[e.referee_idx] = *tag_ptr; } + active_fixture->last_ior_control = (int)ctl; + ior_delivered++; if (ctl == JVMTI_ITERATION_ABORT) { - break; + return JVMTI_ERROR_NONE; } } - return JVMTI_ERROR_NONE; + return active_fixture->ior_error_after_prefix; } // Resolves each requested tag to its node's synthetic identity (&node_tags[idx]) by scanning @@ -638,9 +666,19 @@ class ReferenceChainsMockHeap { } } } - if (active_fixture->reverse_gotw_results) { - // objs and found are index-paired; reverse both together so each - // tag still resolves to its own object. + if (!active_fixture->gotw_resolution_order.empty()) { + std::vector ordered_objs; + std::vector ordered_found; + for (size_t pos : active_fixture->gotw_resolution_order) { + if (pos < objs.size()) { + ordered_objs.push_back(objs[pos]); + ordered_found.push_back(found[pos]); + } + } + objs.swap(ordered_objs); + found.swap(ordered_found); + } else if (active_fixture->reverse_gotw_results) { + // objs and found are index-paired; reverse both together so each tag still resolves. std::reverse(objs.begin(), objs.end()); std::reverse(found.begin(), found.end()); } @@ -678,6 +716,7 @@ class ReferenceChainsMockHeap { // they build), so every holder->element ARRAY_ELEMENT edge below is replayed with a // referrer tag of 0. static jlong holder_tag = 0; + int follow_delivered = 0; if (initial_object != nullptr) { auto holder_it = active_fixture->holders.find(initial_object); if (holder_it != active_fixture->holders.end()) { @@ -694,6 +733,10 @@ class ReferenceChainsMockHeap { if (idx < 0) { continue; } + if (active_fixture->follow_error_after_prefix != JVMTI_ERROR_NONE && + follow_delivered >= active_fixture->follow_prefix_count) { + return active_fixture->follow_error_after_prefix; + } jlong *tag_ptr = &active_fixture->node_tags[idx]; jint ctl; { @@ -704,6 +747,8 @@ class ReferenceChainsMockHeap { /*size=*/0, tag_ptr, &holder_tag, /*length=*/-1, const_cast(user_data)); } + active_fixture->last_follow_control = (int)ctl; + follow_delivered++; if (*tag_ptr != 0) { active_fixture->tags_ever_assigned[idx] = *tag_ptr; } @@ -725,7 +770,11 @@ class ReferenceChainsMockHeap { auto it = expandable.find(e.referrer_idx); if (it == expandable.end() || !it->second) { continue; } - } jlong class_tag = 0; + } if (active_fixture->follow_error_after_prefix != JVMTI_ERROR_NONE && + follow_delivered >= active_fixture->follow_prefix_count) { + return active_fixture->follow_error_after_prefix; + } + jlong class_tag = 0; if (e.class_idx >= 0) { class_tag = active_fixture->tags[active_fixture->classes[e.class_idx].klass]; } @@ -740,6 +789,8 @@ class ReferenceChainsMockHeap { /*size=*/0, tag_ptr, referrer_tag_ptr, /*length=*/-1, const_cast(user_data)); } + active_fixture->last_follow_control = (int)ctl; + follow_delivered++; if (*tag_ptr != 0) { active_fixture->tags_ever_assigned[e.referee_idx] = *tag_ptr; } @@ -748,7 +799,7 @@ class ReferenceChainsMockHeap { } expandable[e.referee_idx] = (ctl & JVMTI_VISIT_OBJECTS) != 0; } - return JVMTI_ERROR_NONE; + return active_fixture->follow_error_after_prefix; } }; diff --git a/ddprof-lib/src/test/cpp/referenceChainsRotationTests.inc b/ddprof-lib/src/test/cpp/referenceChainsRotationTests.inc index c429505e32..baee0c4a26 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsRotationTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsRotationTests.inc @@ -987,3 +987,796 @@ TEST_F(ReferenceChainsBfsTest, SeedLeakAccumulationComposesWithOngoingIncrementa // Smoke test simulating the hotdog pod conditions that starved BFS: + +// --------------------------------------------------------------------------------------------- +// At-risk FIFO requeue under journal overflow. A selected-anchor walk that meets a full journal +// restores its resolved-but-unwalked drained entries to the FIFO front BEFORE the scope replays +// the accepted prefix's deferred at-risk pushes, so the older entries keep their turn and the +// deferred pushes can neither overshoot the FIFO cap nor a class quota. +// --------------------------------------------------------------------------------------------- + +namespace { + +using T9RAcc = ReferenceChainsTestAccessor; +using T9RAtRisk = ReferenceChainsTestAccessor::AtRiskAnchor; + +// ReferenceChainTracker::STATIC_ANCHOR_FIFO_DRAIN / STATIC_ANCHOR_FIFO_CAP are private. +constexpr int kT9RDrain = 16; +constexpr size_t kT9RFifoCap = 1024; +// Anchors walked normally before the journal fills at the next walk. +constexpr int kT9RWalked = 2; + +// Fills the live scope's journal from inside a FollowReferences call (the walk of the anchor that +// follows the kT9RWalked accepted ones) and records which object each call was seeded from. +struct T9RJournalFill { + static inline int fill_on_follow_call = -1; // 0-based call to fill before + static inline int follow_calls = 0; + static inline jlong holder_tag = 0; + static inline jlong holder_class_tag = -9201; + static inline u32 count_after_fill = 0; + static inline std::vector follow_seeds; + + static void reset(ReferenceChainTracker *tracker = nullptr) { + fill_on_follow_call = -1; + follow_calls = 0; + holder_tag = 0; + count_after_fill = 0; + follow_seeds.clear(); + if (tracker != nullptr) { + T9RAcc::setLocalStagingBudgetOverrideForTest(0); + } + } + + // Keep the fixture entry used by count assertions; LOCAL fill reports are intentionally + // unbounded so tests can exercise the journal's overflow behavior. + static void seedHolder(ReferenceChainTracker *tracker) { + T9RAcc::setLocalStagingBudgetOverrideForTest(0xFFFFFFFFu); + holder_tag = tracker->nextTag(); + T9RAcc::primeClassShapeForTest(holder_class_tag, false); + ASSERT_TRUE(T9RAcc::insertFrontierEntry( + tracker->frontierTable(), holder_tag, /*parent_tag=*/1, /*depth=*/1, + FrontierEntryState::FRONTIER, JVMTI_HEAP_REFERENCE_STACK_LOCAL, 0, + holder_class_tag)); + } + + static void fill(const void *user_data) { + auto *ctx = const_cast( + static_cast(user_data)); + count_after_fill = static_cast(T9RAcc::fillAnchorJournalForTest( + *ctx, AnchorObservationBuffer::CAPACITY)); + } +}; + +jvmtiError JNICALL t9RFollow(jvmtiEnv *env, jint heap_filter, jclass klass, + jobject initial_object, const jvmtiHeapCallbacks *callbacks, + const void *user_data) { + T9RJournalFill::follow_seeds.push_back(initial_object); + if (T9RJournalFill::follow_calls++ == T9RJournalFill::fill_on_follow_call) { + T9RJournalFill::fill(user_data); + } + return ReferenceChainsMockHeap::mock_FollowReferences(env, heap_filter, klass, initial_object, + callbacks, user_data); +} + +// Restores the shared mock/tracker state on every exit, including a failed ASSERT. +struct T9RTestGuard { + ReferenceChainsMockHeap &fixture; + explicit T9RTestGuard(ReferenceChainsMockHeap &f) : fixture(f) {} + ~T9RTestGuard() { + fixture.jvmti_tbl.FollowReferences = &ReferenceChainsMockHeap::mock_FollowReferences; + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + T9RJournalFill::reset(tracker); + tracker->releaseAllThreadObjects(&fixture.mock_jni); + tracker->stop(); + } +}; + +// kT9RDrain chain-attached anchors, each with two durable-rooted holders it would demote (one +// FIELD edge per holder). The anchors are the oldest at-risk FIFO entries (class 0 = the class the +// walk's own pushes use for these classless edges). +struct T9RAtRiskScenario { + jlong anchor[kT9RDrain]; + jlong holder[kT9RDrain][2]; +}; + +void t9RBuildAtRiskScenario(ReferenceChainsMockHeap &f, ReferenceChainTracker *tracker, + T9RAtRiskScenario *s) { + FrontierTable *frontier = tracker->frontierTable(); + ASSERT_EQ(0u, tracker->classTags()->resolve(0)) << "classless edges must push class 0"; + const jlong root_tag = 1000; + ASSERT_TRUE(T9RAcc::insertFrontierEntry(frontier, root_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + std::vector anchor_node; + std::vector holder_node; + for (int i = 0; i < kT9RDrain; i++) { + anchor_node.push_back(f.addNode()); + holder_node.push_back(f.addNode()); + holder_node.push_back(f.addNode()); + } + for (int i = 0; i < kT9RDrain; i++) { + s->anchor[i] = 1001 + i; + f.node_tags[anchor_node[i]] = s->anchor[i]; + ASSERT_TRUE(T9RAcc::insertFrontierEntry(frontier, s->anchor[i], root_tag, 1, + FrontierEntryState::FRONTIER, 0)); + for (int j = 0; j < 2; j++) { + s->holder[i][j] = 2000 + 2 * i + j; + f.node_tags[holder_node[2 * i + j]] = s->holder[i][j]; + ASSERT_TRUE(T9RAcc::insertFrontierEntry( + frontier, s->holder[i][j], 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + f.script.push_back( + {JVMTI_HEAP_REFERENCE_FIELD, anchor_node[i], holder_node[2 * i + j], -1}); + } + T9RAcc::pushStaticAnchorFifoForTest(s->anchor[i], 0); + } +} + +// Runs one pass whose selected-anchor walk meets a full journal at its kT9RWalked-th anchor. +void t9RRunOverflowPass(ReferenceChainsMockHeap &f, ReferenceChainTracker *tracker) { + T9RJournalFill::reset(tracker); + T9RJournalFill::seedHolder(tracker); + ASSERT_FALSE(::testing::Test::HasFatalFailure()); + T9RJournalFill::fill_on_follow_call = kT9RWalked; + f.jvmti_tbl.FollowReferences = &t9RFollow; + T9RAcc::setRootEnumRawStateForTest(0, 0); + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&f.mock_jvmti, &f.mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T9RJournalFill::count_after_fill) + << "the anchor walk must have been the one that met the full journal"; + EXPECT_TRUE(truncated); + EXPECT_EQ(0u, T9RAcc::journalCountForTest()); +} + +// Drains the whole FIFO and checks: unwalked anchors (original drained order, whatever order the +// resolution used) first, then the older entries behind them, then only as many of the walked +// anchors' deferred pushes as the cap/quota leave room for; no total or class overshoot. Restores +// the FIFO so the caller can run a retry pass. +void t9RCheckRequeueBeforePushes(const T9RAtRiskScenario &s, const std::vector &walked_order, + const std::vector &older, size_t free_slots) { + std::vector walked(kT9RDrain, false); + for (int w = 0; w < kT9RWalked; w++) { + walked[walked_order[w]] = true; + } + std::vector expected; + for (int i = 0; i < kT9RDrain; i++) { + if (!walked[i]) { + expected.push_back(s.anchor[i]); + } + } + for (const T9RAtRisk &entry : older) { + expected.push_back(entry.tag); + } + std::vector pushes; + for (int w = 0; w < kT9RWalked; w++) { + pushes.push_back(s.holder[walked_order[w]][0]); + pushes.push_back(s.holder[walked_order[w]][1]); + } + ASSERT_GT(pushes.size(), free_slots) << "the scenario must offer more pushes than room"; + for (size_t i = 0; i < free_slots; i++) { + expected.push_back(pushes[i]); + } + + std::vector actual; + T9RAcc::drainStaticAnchorFifoForTest(2 * (int)kT9RFifoCap, actual); + EXPECT_LE(actual.size(), kT9RFifoCap) << "the FIFO cap was overshot"; + std::map per_class; + for (const T9RAtRisk &entry : actual) { + per_class[entry.klass_id]++; + } + for (const auto &kv : per_class) { + EXPECT_LE(kv.second, T9RAcc::kAtRiskPerKlassCap) << "class " << kv.first << " overshot"; + } + ASSERT_EQ(expected.size(), actual.size()); + for (size_t i = 0; i < expected.size(); i++) { + EXPECT_EQ(expected[i], actual[i].tag) << "FIFO position " << i; + } + T9RAcc::requeueStaticAnchorFifoFrontForTest(actual); +} + +// After the overflow pass the rejected demotions were not performed; the retry pass walks the +// requeued anchors first and delivers them. +void t9RCheckRejectedDemotionsDeliveredOnRetry(ReferenceChainsMockHeap &f, + ReferenceChainTracker *tracker, + const T9RAtRiskScenario &s, + const std::vector &walked_order) { + FrontierTable *frontier = tracker->frontierTable(); + std::vector walked(kT9RDrain, false); + for (int w = 0; w < kT9RWalked; w++) { + walked[walked_order[w]] = true; + } + FrontierEntry entry{}; + for (int i = 0; i < kT9RDrain; i++) { + for (int j = 0; j < 2; j++) { + ASSERT_TRUE(frontier->lookup(s.holder[i][j], &entry)); + EXPECT_EQ(walked[i] ? s.anchor[i] : 0, entry.parent_tag) + << "anchor " << i << " holder " << j + << (walked[i] ? ": accepted demotion applied" : ": rejected demotion performed"); + } + } + T9RJournalFill::reset(tracker); + f.jvmti_tbl.FollowReferences = &ReferenceChainsMockHeap::mock_FollowReferences; + f.gotw_resolution_order.clear(); + T9RAcc::setRootEnumRawStateForTest(0, 0); + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&f.mock_jvmti, &f.mock_jni, &truncated)); + for (int i = 0; i < kT9RDrain; i++) { + for (int j = 0; j < 2; j++) { + ASSERT_TRUE(frontier->lookup(s.holder[i][j], &entry)); + EXPECT_EQ(s.anchor[i], entry.parent_tag) + << "anchor " << i << " holder " << j << " not delivered by the retry"; + } + } +} + +std::vector t9RPushOlderEntries(const std::vector> &class_counts) { + std::vector older; + jlong tag = 5000; + for (const auto &cc : class_counts) { + for (u32 i = 0; i < cc.second; i++) { + T9RAcc::pushStaticAnchorFifoForTest(tag, cc.first); + older.push_back(T9RAtRisk{tag, cc.first}); + tag++; + } + } + return older; +} + +std::vector t9RIdentityOrder() { + std::vector order; + for (int i = 0; i < kT9RDrain; i++) { + order.push_back((size_t)i); + } + return order; +} + +} // namespace + +// FIFO at its 1024 cap; the walk overflows after two anchors. The 14 unwalked anchors return to the +// front (freeing exactly the slots the drain took), so the walked anchors' four deferred pushes +// find room for only two; had they been replayed first, the requeue would overshoot the cap. +TEST_F(ReferenceChainsBfsTest, AtRiskFullFifoPartialOverflowRequeuesBeforeDeferredPushes) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9RTestGuard guard(*this); + + T9RAtRiskScenario s; + t9RBuildAtRiskScenario(*this, tracker, &s); + ASSERT_FALSE(HasFatalFailure()); + // 15 classes at their quota plus a 16th at 48 fill the cap exactly behind the 16 anchors. + std::vector> classes; + for (u32 klass = 1; klass <= 15; klass++) { + classes.push_back({klass, T9RAcc::kAtRiskPerKlassCap}); + } + classes.push_back({16, 48}); + std::vector older = t9RPushOlderEntries(classes); + ASSERT_EQ(kT9RFifoCap, T9RAcc::staticAnchorFifoSizeForTest()); + + t9RRunOverflowPass(*this, tracker); + ASSERT_FALSE(HasFatalFailure()); + t9RCheckRequeueBeforePushes(s, t9RIdentityOrder(), older, /*free_slots=*/2); + ASSERT_FALSE(HasFatalFailure()); + t9RCheckRejectedDemotionsDeliveredOnRetry(*this, tracker, s, t9RIdentityOrder()); +} + +// Class 0 (the class of the walk's own pushes) sits at its quota behind the anchors. The requeue +// restores the unwalked anchors' occupancy first, leaving two quota slots for four deferred pushes. +TEST_F(ReferenceChainsBfsTest, AtRiskPerClassSaturationRequeuesBeforeDeferredPushes) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9RTestGuard guard(*this); + + T9RAtRiskScenario s; + t9RBuildAtRiskScenario(*this, tracker, &s); + ASSERT_FALSE(HasFatalFailure()); + std::vector older = t9RPushOlderEntries({{0, T9RAcc::kAtRiskPerKlassCap - kT9RDrain}}); + ASSERT_EQ((size_t)T9RAcc::kAtRiskPerKlassCap, T9RAcc::staticAnchorFifoSizeForTest()); + + t9RRunOverflowPass(*this, tracker); + ASSERT_FALSE(HasFatalFailure()); + // Quota 64 - (14 requeued + 48 older) = 2 free slots, FIFO cap far from binding. + t9RCheckRequeueBeforePushes(s, t9RIdentityOrder(), older, /*free_slots=*/2); +} + +// GetObjectsWithTags reports the anchors in an order unrelated to the drain: the walk's cut-off +// point follows the resolution order, but the requeue must keep the drained order. +TEST_F(ReferenceChainsBfsTest, AtRiskRequeueKeepsDrainedOrderUnderShuffledResolution) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9RTestGuard guard(*this); + + T9RAtRiskScenario s; + t9RBuildAtRiskScenario(*this, tracker, &s); + ASSERT_FALSE(HasFatalFailure()); + std::vector> classes; + for (u32 klass = 1; klass <= 15; klass++) { + classes.push_back({klass, T9RAcc::kAtRiskPerKlassCap}); + } + classes.push_back({16, 48}); + std::vector older = t9RPushOlderEntries(classes); + + const std::vector shuffled = {9, 4, 14, 1, 12, 6, 0, 15, 3, 10, 7, 13, 2, 8, 5, 11}; + ASSERT_EQ((size_t)kT9RDrain, shuffled.size()); + gotw_resolution_order = shuffled; + + t9RRunOverflowPass(*this, tracker); + ASSERT_FALSE(HasFatalFailure()); + // Walked anchors are the first two RESOLVED (9 and 4), not the first two drained. + t9RCheckRequeueBeforePushes(s, shuffled, older, /*free_slots=*/2); + ASSERT_FALSE(HasFatalFailure()); + t9RCheckRejectedDemotionsDeliveredOnRetry(*this, tracker, s, shuffled); +} + +// Candidate-thread descent meeting a full journal on its second thread keeps the cursor on that +// thread: the retry starts there, not at the thread after it. +TEST_F(ReferenceChainsBfsTest, CandidateThreadWalkOverflowRetainsCursorOnCutShortThread) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + T9RTestGuard guard(*this); + FrontierTable *frontier = tracker->frontierTable(); + + void *threadCls = (void *)0x3201, *tlmapCls = (void *)0x3202, *loaderCls = (void *)0x3203; + int tlmapIdx = registerClassForFindClass( + tlmapCls, "java/lang/ThreadLocal$ThreadLocalMap", "Ljava/lang/ThreadLocal$ThreadLocalMap;"); + registerClassForFindClass(loaderCls, "java/lang/ClassLoader", "Ljava/lang/ClassLoader;"); + registerClassForFindClass(threadCls, "java/lang/Thread", "Ljava/lang/Thread;"); + thread_class = threadCls; + T9RAcc::resolveLoadedClasses(&mock_jvmti, &mock_jni); + + int thread0 = addNode(); + int thread1 = addNode(); + int thread2 = addNode(); + int tlmap = addNode(); + int holder = addNode(); + node_tags[holder] = 107; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, thread1, tlmap, tlmapIdx}, + {JVMTI_HEAP_REFERENCE_FIELD, tlmap, holder, -1}, + }; + // Thread 1 is admitted root-attached; threads 0 and 2 are minted on their walks. The durable + // holder under thread 1's ThreadLocalMap is what its walk demotes. + jlong anchor_tag = tracker->tagObject( + &mock_jvmti, reinterpret_cast(&node_tags[thread1])); + ASSERT_GT(anchor_tag, 0); + node_tags[thread1] = anchor_tag; + ASSERT_TRUE(T9RAcc::insertFrontierEntry(frontier, anchor_tag, 0, 0, FrontierEntryState::FRONTIER, + (u8)JVMTI_HEAP_REFERENCE_THREAD)); + ASSERT_TRUE(T9RAcc::insertFrontierEntry(frontier, 107, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + jint tids[] = {777, 778, 779}; + T9RAcc::seedCandidateSlotForTest(0, 6, tids, 3); + jobject objs[] = {reinterpret_cast(&node_tags[thread0]), + reinterpret_cast(&node_tags[thread1]), + reinterpret_cast(&node_tags[thread2])}; + for (int i = 0; i < 3; i++) { + tracker->registerThreadObject(&mock_jni, tids[i], reinterpret_cast(objs[i])); + } + + // The walk starts at thread 0 (accepted), and the journal fills before thread 1's walk. + T9RJournalFill::reset(tracker); + T9RJournalFill::seedHolder(tracker); + ASSERT_FALSE(HasFatalFailure()); + T9RJournalFill::fill_on_follow_call = 1; + jvmti_tbl.FollowReferences = &t9RFollow; + int edges = 0; + T9RAcc::walkCandidateThreadLocalsForTest(&mock_jvmti, &mock_jni, 1000, &edges); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T9RJournalFill::count_after_fill); + ASSERT_EQ(2u, T9RJournalFill::follow_seeds.size()) << "the group must stop at the cut-short thread"; + EXPECT_EQ(objs[0], T9RJournalFill::follow_seeds[0]); + EXPECT_EQ(objs[1], T9RJournalFill::follow_seeds[1]); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(0, entry.parent_tag) << "the rejected demotion must not be performed"; + EXPECT_EQ(0, T9RAcc::getTagForTest(&mock_jvmti, objs[2])); + + // The retry resumes at thread 1 (a cursor advanced past it would start at thread 2). + jvmti_tbl.FollowReferences = &t9RFollow; + T9RJournalFill::reset(tracker); + edges = 0; + T9RAcc::walkCandidateThreadLocalsForTest(&mock_jvmti, &mock_jni, 1000, &edges); + ASSERT_GE(T9RJournalFill::follow_seeds.size(), 2u); + EXPECT_EQ(objs[1], T9RJournalFill::follow_seeds[0]) << "cursor must stay on the cut-short thread"; + EXPECT_EQ(objs[2], T9RJournalFill::follow_seeds[1]); + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(tags_ever_assigned[tlmap], entry.parent_tag) + << "the retried descent delivers the rejected demotion"; +} + +TEST_F(ReferenceChainsBfsTest, LocalAnchorTagsStayIndexedAcrossDurableEviction) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong local_class = -3101; + const jlong local_tag = 20001; + ReferenceChainsTestAccessor::primeClassShapeForTest(local_class, true); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, local_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::noteLocalRootHolderForTest(local_tag, + local_class); + ASSERT_TRUE(ReferenceChainsTestAccessor::localAnchorTagsAreIndexedForTest()); + + const size_t durable_cap = + ReferenceChainsTestAccessor::kDurableAnchorIndexCap; + const size_t evict_batch = + ReferenceChainsTestAccessor::kDurableAnchorEvictBatch; + for (size_t i = 0; i < durable_cap + evict_batch + 1; i++) { + jlong tag = 30000 + (jlong)i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, -3200, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest( + local_tag)); + EXPECT_EQ(1u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_TRUE(ReferenceChainsTestAccessor::localAnchorTagsAreIndexedForTest()); + + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + local_tag, local_class, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::localAnchorCountForTest()); + EXPECT_TRUE(ReferenceChainsTestAccessor::anchorIndexContainsForTest( + local_tag)); + EXPECT_TRUE(ReferenceChainsTestAccessor::localAnchorTagsAreIndexedForTest()); + + tracker->stop(); +} + +TEST_F(ReferenceChainsBfsTest, StaticAnchorRotationUsesIndexCapacityAfterFreshQueueDrains) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -3301; + constexpr int anchor_count = 20; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + for (int i = 0; i < anchor_count; i++) { + jlong tag = 40000 + i; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + + for (int i = 0; i < anchor_count - 1; i++) { + std::vector first_look = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 1); + ASSERT_EQ(1u, first_look.size()); + } + ASSERT_EQ(1u, + ReferenceChainsTestAccessor::freshAnchorQueueSizeForTest()); + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + EXPECT_EQ(16u, selected.size()); + + tracker->stop(); +} + +// The fresh lane is capped at half the post-leak budget; with a positive budget the queue keeps +// its entries' FIFO turns across passes (nothing jumps the queue). +TEST_F(ReferenceChainsBfsTest, FreshBudgetExhaustionKeepsNextTurnForLater) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -3302; + const jlong first = 41001; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + for (jlong tag = first; tag < first + 3; tag++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + + EXPECT_EQ((std::vector{first}), + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 1)); + EXPECT_EQ((std::vector{first + 1, first + 2}), + ReferenceChainsTestAccessor::freshQueueTagsForTest()); + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 2); + ASSERT_EQ(2u, selected.size()); + EXPECT_NE(std::find(selected.begin(), selected.end(), first + 1), + selected.end()); + EXPECT_NE(std::find(selected.begin(), selected.end(), first), + selected.end()); + EXPECT_EQ((std::vector{first + 2}), + ReferenceChainsTestAccessor::freshQueueTagsForTest()); + + FrontierEntry picked{}; + ASSERT_TRUE(frontier->lookup(first + 1, &picked)); + // Selection no longer spends a picked anchor's first look: the walk does (post-descent). + // first+1 was picked here but never walked (this test drives the collector alone), so its + // pending turn is intact. + EXPECT_NE(0, picked.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + EXPECT_EQ(0, picked.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_SERVED); + + tracker->stop(); +} + +// When the leak tier saturates the whole selection budget, the fresh lane gets no budget: queued +// entries would never pop and never receive fair-tier budget, so they spend their first looks at +// that point (old queue.clear() semantics) and fall back to the fair tiers once the leak tier +// ebbs. +TEST_F(ReferenceChainsBfsTest, LeakSaturatedBudgetSpendsQueuedFirstLooks) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -3304; + const jlong first = 43001; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + // The fresh lane's queued containers. + for (jlong tag = first; tag < first + 3; tag++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + // Leak-tagged anchors saturating the selection budget. + for (jlong tag = first + 100; tag < first + 120; tag++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->setLeakTag(tag, 777, /*leak_tag_incarnation=*/0); + } + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + ASSERT_EQ(16u, selected.size()); + for (jlong tag : selected) { + EXPECT_GE(tag, first + 100) << "only leak-tier picks fit the saturated budget"; + } + // The queued containers spent their first looks at the saturated pass and left the queue. + EXPECT_TRUE(ReferenceChainsTestAccessor::freshQueueTagsForTest().empty()); + for (jlong tag = first; tag < first + 3; tag++) { + FrontierEntry spent{}; + ASSERT_TRUE(frontier->lookup(tag, &spent)); + EXPECT_EQ(0, spent.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + EXPECT_NE(0, spent.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_SERVED); + } + + // Once the leak tier ebbs, the spent entries are selected through the fair tiers. + for (jlong tag = first + 100; tag < first + 120; tag++) { + frontier->setLeakTag(tag, 0, /*leak_tag_incarnation=*/0); + } + std::vector after = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + for (jlong tag = first; tag < first + 3; tag++) { + EXPECT_NE(std::find(after.begin(), after.end(), tag), after.end()) + << "the spent first look must fall back to the fair tiers"; + } + + tracker->stop(); +} + +// An entry evicted from the durable index has no fair-tier fallback: the saturated pass must keep +// its queued turn instead of spending it, so the fresh lane can still walk it once the leak tier +// ebbs. +TEST_F(ReferenceChainsBfsTest, LeakSaturatedBudgetKeepsEvictedQueuedTurns) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -3305; + const jlong evicted = 43101; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, evicted, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + evicted, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ReferenceChainsTestAccessor::evictStaticAnchorIndexEntryForTest(evicted); + ASSERT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest(evicted)); + + // Leak-tagged anchors saturate the selection budget. + for (jlong tag = evicted + 100; tag < evicted + 120; tag++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->setLeakTag(tag, 777, /*leak_tag_incarnation=*/0); + } + + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + ASSERT_EQ(16u, selected.size()); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshAnchorQueueContainsForTest(evicted)) + << "the evicted entry keeps its queued turn through the saturated pass"; + + // Once the leak tier ebbs, the fresh lane walks the evicted holder's queued turn. + for (jlong tag = evicted + 100; tag < evicted + 120; tag++) { + frontier->setLeakTag(tag, 0, /*leak_tag_incarnation=*/0); + } + std::vector after = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 16); + EXPECT_NE(std::find(after.begin(), after.end(), evicted), after.end()) + << "the kept turn is spent by the fresh lane, not lost"; + EXPECT_TRUE(ReferenceChainsTestAccessor::freshQueueTagsForTest().empty()); + + tracker->stop(); +} + +// A fair-tier pick whose holder still sits in the fresh queue must not strand the queued first +// look: the selection hands the queue entry to the caller's requeue path alongside the +// fresh-lane picks. +TEST_F(ReferenceChainsBfsTest, FairTierPickRestoresItsQueuedFirstLook) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong leak_class_tag = -3306; + const jlong container_class_tag = -3307; + const jlong fresh_pick = 43201; + const jlong deep = 43202; + ReferenceChainsTestAccessor::primeClassShapeForTest(leak_class_tag, true); + ReferenceChainsTestAccessor::primeClassShapeForTest(container_class_tag, true); + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, fresh_pick, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + fresh_pick, container_class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + // Deeper in the fresh queue, selected by the container tier before the fresh lane reaches it. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, deep, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + deep, container_class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + const jlong leak_anchor = 43301; + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, leak_anchor, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + leak_anchor, leak_class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + frontier->setLeakTag(leak_anchor, 778, /*leak_tag_incarnation=*/0); + + std::vector fresh_picked; + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 3, &fresh_picked); + ASSERT_EQ(3u, selected.size()); + // The fresh lane spent its whole room on the queue's head entry; the deep entry's selection + // came from the container tier while it was still queued. Every selected tag's queue entry + // is handed to the caller's requeue path - the leak pick's too - so an unwalked selection + // keeps its queued turn for the next pass. + ASSERT_EQ(3u, fresh_picked.size()); + EXPECT_EQ(fresh_pick, fresh_picked[0].tag); + EXPECT_EQ(deep, fresh_picked[1].tag); + EXPECT_EQ(container_class_tag, fresh_picked[1].own_class_tag); + EXPECT_EQ(leak_anchor, fresh_picked[2].tag); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshQueueTagsForTest().empty()); + + tracker->stop(); +} + +// A fresh pick's first look is consumed by the WALK, not the selection: a pick the caller never +// walked (budget exhausted before its descent, or unwalked mid-batch) is requeued to the fresh +// queue's front with its pending turn intact. +TEST_F(ReferenceChainsBfsTest, UnwalkedFreshPicksKeepTheirQueuedTurn) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=64")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong class_tag = -3303; + const jlong first = 42001; + ReferenceChainsTestAccessor::primeClassShapeForTest(class_tag, true); + for (jlong tag = first; tag < first + 6; tag++) { + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, class_tag, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + + std::vector fresh_picked; + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 4, &fresh_picked); + // 2 fresh-lane picks (half the post-leak budget); the fair container tier fills the rest of + // the selection from the index (it may pick a still-queued entry - the fresh queue is not + // exclusive). The fair picks' queue entries are handed to the caller's requeue path with the + // lane picks, so an unwalked fair pick keeps its queued turn. + ASSERT_EQ(4u, selected.size()); + ASSERT_EQ(4u, fresh_picked.size()); + EXPECT_EQ(first, fresh_picked[0].tag); + EXPECT_EQ(class_tag, fresh_picked[0].own_class_tag); + EXPECT_EQ(first + 2, fresh_picked[2].tag); + EXPECT_EQ(first + 3, fresh_picked[3].tag); + // Selection alone must not spend the picks' first look. + for (jlong tag : selected) { + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_NE(0, entry.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + EXPECT_EQ(0, entry.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_SERVED); + } + // The fresh lane had budget, so the entries beyond the picks and the fair tier's share KEEP + // their queued turns (no spending without a walk when the lane is not starved). + EXPECT_EQ((std::vector{first + 4, first + 5}), + ReferenceChainsTestAccessor::freshQueueTagsForTest()); + FrontierEntry queued{}; + ASSERT_TRUE(frontier->lookup(first + 4, &queued)); + EXPECT_NE(0, queued.anchor_rotation_flags & + FrontierAnchorRotation::FIRST_LOOK_PENDING); + + // The caller requeues the pick whose walk never happened; the queue keeps its turn at the + // front, ahead of the not-yet-popped entries, with its pending flag intact. + ReferenceChainsTestAccessor::requeueStaticAnchorFreshFrontForTest( + std::vector{fresh_picked[1]}); + EXPECT_EQ((std::vector{fresh_picked[1].tag, first + 4, first + 5}), + ReferenceChainsTestAccessor::freshQueueTagsForTest()); + + tracker->stop(); +} + +// A queued first look carries the enqueue-time class tag; the index's stored tag is the +// authority at pop time. A holder indexed before its class resolved (stored 0, later upgraded) +// must not be rejected by the stale carried tag: after reparenting, isSelectableAnchor() judged +// on the stale tag spends the holder's only queued turn on an otherwise eligible container. +TEST_F(ReferenceChainsBfsTest, FreshLanePopUsesIndexClassTagForQueuedEntries) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + const jlong tag = 43501; + const jlong resolved_class = -3310; + // Reparented holder: parent_tag != 0, so isSelectableAnchor() needs the class shape. + ASSERT_TRUE(ReferenceChainsTestAccessor::insertFrontierEntry( + frontier, tag, 999, 1, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ReferenceChainsTestAccessor::primeClassShapeForTest(resolved_class, true); + ReferenceChainsTestAccessor::addToStaticAnchorIndexForTest( + tag, 0, JVMTI_HEAP_REFERENCE_JNI_GLOBAL); + ReferenceChainsTestAccessor::indexAnchorForRotationForTest(tag, resolved_class); + ASSERT_EQ(resolved_class, ReferenceChainsTestAccessor::indexedAnchorClassTagForTest(tag)); + // The first index admission queued the holder with the admission-time tag 0; the stored + // index tag has since been upgraded to the resolved class. + + std::vector fresh_picked; + std::vector selected = + ReferenceChainsTestAccessor::collectStaticFieldAnchorsForRotationForTest( + 1, &fresh_picked); + ASSERT_EQ(1u, selected.size()); + EXPECT_EQ(tag, selected[0]); + ASSERT_EQ(1u, fresh_picked.size()); + EXPECT_EQ(tag, fresh_picked[0].tag); + EXPECT_TRUE(ReferenceChainsTestAccessor::freshQueueTagsForTest().empty()); + + tracker->stop(); +} diff --git a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h index 7b77f8759b..636591807e 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h +++ b/ddprof-lib/src/test/cpp/referenceChainsTestAccessors.h @@ -12,13 +12,14 @@ #ifndef REFERENCE_CHAINS_TEST_ACCESSORS_H #define REFERENCE_CHAINS_TEST_ACCESSORS_H +#include #include #include #include #include #include "classTagAllocator.h" -#include "livenessTracker.h" +#include "referenceChainInternal.h" #include "referenceChains.h" #include "vmEntry.h" @@ -67,6 +68,10 @@ class ReferenceChainsTestAccessor { t->_search_started = false; t->_tags_released = true; t->_root_enum_incomplete = false; + t->_last_root_enum_attempt_id = 0; + t->_root_report_attempt_sequence = 0; + t->_static_field_retry_chunk_start = -1; + t->_static_field_retry_attempt_id = 0; t->_consecutive_enum_errors = 0; t->_search_state = SearchState::RUNNING; t->_abandon_reason = SearchAbandonReason::NONE; @@ -106,7 +111,21 @@ 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->_local_anchor_tags.clear(); + t->_pending_local_anchors.clear(); + t->_pending_local_anchor_tags.clear(); + t->_local_compact_backoff = 0; + t->_durable_anchor_resweep_gen = 0; + t->_static_field_sweep_lap_request_gen = 0; + t->_static_field_sweep_served_gen = 0; + t->_pending_local_evict_cursor = 0; + t->_pending_local_evictable_count = 0; +#ifdef UNIT_TEST + t->_local_staging_budget_override_for_test = 0; +#endif t->_anchor_container_cursor = 0; t->_anchor_other_cursor = 0; t->_class_shape_cache.clear(); @@ -127,6 +146,39 @@ class ReferenceChainsTestAccessor { t->_gotw_batch_size = 0; t->_pass_deadline_ns = 0; t->_expand_lane_prefer_priority = true; +#ifdef DEBUG + t->_between_invalidation_scan_and_writeback_for_test = nullptr; + t->_join_thread_for_test = nullptr; +#endif + // A failed-join test leaves the worker marked unjoined; no thread exists at fixture setup. + t->_thread_joined = true; + t->_anchor_observations.reset(); + } + + // Anchor-observation journal: accepted-record count and the lifecycle epoch reset() advances. + static u32 journalCountForTest() { + return ReferenceChainTracker::instance()->_anchor_observations.count(); + } + // Pre-fills the active scope to a total record count without replay effects. + static size_t fillAnchorJournalForTest(ReferenceChainPassContext &ctx, + size_t target_count) { + size_t filled = journalCountForTest(); + for (; filled < target_count; filled++) { + AnchorObservationReservation reservation = ctx.anchor_scope.reserve(); + if (!reservation.held()) { + break; + } + AnchorObservation record{}; + record.actions = AnchorObservation::DURABLE_ADD; + reservation.commit(record); + } + return filled; + } + static u64 journalEpochForTest() { + return ReferenceChainTracker::instance()->_anchor_observations.epoch(); + } + static bool threadJoinedForTest() { + return ReferenceChainTracker::instance()->_thread_joined; } static bool canAffordNewSearch(u64 now_ns) { @@ -159,6 +211,15 @@ class ReferenceChainsTestAccessor { ReferenceChainTracker::instance()->setCandidateCountForTest(n); } +#ifdef UNIT_TEST + static void setLocalStagingBudgetOverrideForTest(u32 budget) { + ReferenceChainTracker::instance()->setLocalStagingBudgetOverrideForTest(budget); + } +#endif + static jlong leakTagForTest(u32 index) { + return ReferenceChainTracker::LEAK_TAG_BASE + index; + } + // Canary-lane backoff state wrappers - see _canary_backoff_mult's own comment // (referenceChains.h). static int canaryBackoffMult() { @@ -313,10 +374,14 @@ class ReferenceChainsTestAccessor { return std::vector(tags, tags + count); } + // Defaults to EVICT (noise-eviction semantics); pass rebuild=true for the improveChain/ + // reparent/root-kind-upgrade REBUILD kind. static void deferResolvedChainInvalidation( - jlong tag, const std::vector &snapshot) { + jlong tag, const std::vector &snapshot, bool rebuild = false) { ReferenceChainTracker::instance()->deferResolvedChainInvalidation( - tag, snapshot.data(), (int)snapshot.size()); + tag, snapshot.data(), (int)snapshot.size(), + rebuild ? ReferenceChainTracker::ChainInvalidationKind::REBUILD + : ReferenceChainTracker::ChainInvalidationKind::EVICT); } static size_t pendingChainInvalidationCount() { @@ -343,6 +408,69 @@ class ReferenceChainsTestAccessor { ReferenceChainTracker::instance()->drainPendingChainInvalidations(); } + static void applyPendingChainInvalidationsForTest(u64 search_ns) { + ReferenceChainTracker::instance()->applyPendingChainInvalidations(nullptr, nullptr, + search_ns); + } + + static void invalidateResolvedChainForTest(jlong tag) { + ReferenceChainTracker::instance()->invalidateResolvedChain(tag); + } + + // Raw pending-buffer encoding probes: lets a test pin the in-band kind encoding's negative-tag + // hazard (the reason deferResolvedChainInvalidation() refuses negative source tags). + static jlong encodePendingChainInvalidationForTest(jlong tag, bool rebuild) { + return ReferenceChainTracker::encodePendingChainInvalidation( + tag, rebuild ? ReferenceChainTracker::ChainInvalidationKind::REBUILD + : ReferenceChainTracker::ChainInvalidationKind::EVICT); + } + + static bool isPendingChainRebuild(jlong encoded) { + return ReferenceChainTracker::isPendingChainRebuild(encoded); + } + + static jlong pendingChainInvalidationTag(jlong encoded) { + return ReferenceChainTracker::pendingChainInvalidationTag(encoded); + } + +#ifdef DEBUG + // Sets/clears the debug-only write-back recheck hook. + static void setBetweenInvalidationScanAndWritebackForTest(void (*hook)()) { + ReferenceChainTracker::instance()->_between_invalidation_scan_and_writeback_for_test = + hook; + } +#endif + +#ifdef DEBUG + // Join-result injection: stopThread()'s pthread_join() is replaced by a stub that returns the + // configured result (0 = success) without joining a real thread, and counts its calls. + static inline int s_join_result = 0; + static inline int s_join_calls = 0; + static int injectedJoinForTest(pthread_t, void **) { + s_join_calls++; + return s_join_result; + } + static void setJoinResultForTest(int result) { + s_join_result = result; + s_join_calls = 0; + ReferenceChainTracker::instance()->_join_thread_for_test = &injectedJoinForTest; + } + static void clearJoinResultForTest() { + ReferenceChainTracker::instance()->_join_thread_for_test = nullptr; + } + static int joinCallCountForTest() { return s_join_calls; } + // Installs a caller-owned join stub (same signature as the injected one) so a test can + // observe Profiler state at join time - e.g. that stop() closes the reference-chain gate + // before it joins the BFS worker. + static void setJoinHookForTest(int (*hook)(pthread_t, void **)) { + ReferenceChainTracker::instance()->_join_thread_for_test = hook; + } + // Marks a worker as started-but-unjoined, the state a failed join leaves. + static void setThreadUnjoinedForTest() { + ReferenceChainTracker::instance()->_thread_joined = false; + } +#endif + static bool hasResolvedChainForTag(jlong tag) { ReferenceChainTracker *t = ReferenceChainTracker::instance(); return t->_resolved_chains.find(tag) != t->_resolved_chains.end(); @@ -539,24 +667,187 @@ class ReferenceChainsTestAccessor { static bool anchorIndexIsEmptyForTest() { ReferenceChainTracker *t = ReferenceChainTracker::instance(); return t->_static_anchor_index.empty() && - t->_static_anchor_index_class_tags.empty(); + t->_static_anchor_own_class_tags.empty() && + t->_static_anchor_index_tags.empty() && + t->_local_anchor_tags.empty() && + t->_pending_local_anchors.empty() && + t->_pending_local_anchor_tags.empty() && + t->_static_anchor_fresh_queue.empty() && + t->_local_compact_backoff == 0 && + t->_durable_anchor_resweep_gen == t->_static_field_sweep_served_gen && + t->_pending_local_evict_cursor == 0 && + t->_pending_local_evictable_count == 0 +#ifdef UNIT_TEST + && t->_local_staging_budget_override_for_test == 0 +#endif + ; + } + + // Local-root anchor seams (see noteLocalRootHolder()/resolvePendingLocalAnchors()). + static void noteLocalRootHolderForTest(jlong tag, jlong class_tag) { + ReferenceChainTracker::instance()->noteLocalRootHolder(tag, class_tag); + } + static void resolvePendingLocalAnchorsForTest() { + ReferenceChainTracker::instance()->resolvePendingLocalAnchors(); + } + static size_t anchorIndexSizeForTest() { + return ReferenceChainTracker::instance()->_static_anchor_index.size(); + } + static size_t localAnchorCountForTest() { + return ReferenceChainTracker::instance()->_local_anchor_tags.size(); + } + // Durable share: indexed tags minus the capped local share. + static size_t durableAnchorCountForTest() { + ReferenceChainTracker *t = ReferenceChainTracker::instance(); + return t->_static_anchor_index_tags.size() - t->_local_anchor_tags.size(); } - - // Copy of the indexed holder tags, so a test can observe pruning and - // admission of the persistent rotation index without reaching into it. + static bool localAnchorTagsAreIndexedForTest() { + ReferenceChainTracker *t = ReferenceChainTracker::instance(); + for (const auto &local : t->_local_anchor_tags) { + if (t->_static_anchor_index_tags.count(local.first) == 0) { + return false; + } + } + return true; + } + static bool anchorIndexContainsForTest(jlong tag) { + return ReferenceChainTracker::instance()->_static_anchor_index_tags.count(tag) > 0; + } + // Caller keeps idx < anchorIndexSizeForTest(). + static jlong anchorIndexTagForTest(size_t idx) { + return ReferenceChainTracker::instance()->_static_anchor_index[idx]; + } + // 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) { + // Drops one tag from the durable index the way eviction does: the tag leaves the index and + // its parallel views while any queued first look stays alive. + static void evictStaticAnchorIndexEntryForTest(jlong tag) { + ReferenceChainTracker *t = ReferenceChainTracker::instance(); + auto pos_it = t->_static_anchor_index_class_tags.find(tag); + if (pos_it == t->_static_anchor_index_class_tags.end()) { + return; + } + size_t pos = pos_it->second.pos; + t->_static_anchor_index_class_tags.erase(pos_it); + t->_static_anchor_index_tags.erase(tag); + t->_static_anchor_index.erase(t->_static_anchor_index.begin() + pos); + t->_static_anchor_own_class_tags.erase( + t->_static_anchor_own_class_tags.begin() + pos); + for (auto &entry : t->_static_anchor_index_class_tags) { + if (entry.second.pos > pos) { + entry.second.pos--; + } + } + } + static size_t anchorOwnClassTagsSizeForTest() { + return ReferenceChainTracker::instance()->_static_anchor_own_class_tags.size(); + } + // The durable index's stored class tag for `tag` (0 when unindexed or un-upgraded). + static jlong indexedAnchorClassTagForTest(jlong tag) { + const auto &tags = + ReferenceChainTracker::instance()->_static_anchor_index_class_tags; + auto it = tags.find(tag); + return it == tags.end() ? 0 : it->second.class_tag; + } + static void indexAnchorForRotationForTest(jlong tag, jlong class_tag) { + ReferenceChainTracker::instance()->indexAnchorForRotation(tag, class_tag); + } + static void replayAnchorObservationsForTest( + const std::vector &records) { + ReferenceChainTracker::instance()->replayAnchorObservations( + records.data(), (u32)records.size(), false); + } + static size_t pendingLocalAnchorCountForTest() { + return ReferenceChainTracker::instance()->_pending_local_anchors.size(); + } + static size_t freshAnchorQueueSizeForTest() { + return ReferenceChainTracker::instance()->_static_anchor_fresh_queue.size(); + } + static size_t freshAnchorQueueCapForTest() { + return ReferenceChainTracker::STATIC_ANCHOR_FRESH_CAP; + } + static bool freshAnchorQueueContainsForTest(jlong tag) { + const auto &queue = + ReferenceChainTracker::instance()->_static_anchor_fresh_queue; + return std::find_if(queue.begin(), queue.end(), + [tag](const auto &entry) { + return entry.tag == tag; + }) != queue.end(); + } + // Snapshot of the fresh queue in FIFO order (front first) - pins the cross-pass service order. + static std::vector freshQueueTagsForTest() { + const auto &queue = + ReferenceChainTracker::instance()->_static_anchor_fresh_queue; + std::vector tags; + tags.reserve(queue.size()); + for (const auto &entry : queue) { + tags.push_back(entry.tag); + } + return tags; + } + // The static sweep resweep request (set by durable-share eviction, served and cleared by a + // full sweep lap): runPassManualWalk() runs admitStaticFieldRoots() while this is pending or + // the class-count memo is stale. + // The static sweep resweep-request state (see _durable_anchor_resweep_gen): runPassManualWalk() + // runs admitStaticFieldRoots() while a generation is unserved or the class-count memo is stale. + static bool durableAnchorResweepUnservedForTest() { + ReferenceChainTracker *t = ReferenceChainTracker::instance(); + return t->_static_field_sweep_served_gen != t->_durable_anchor_resweep_gen; + } + static u64 durableAnchorResweepGenForTest() { + return ReferenceChainTracker::instance()->_durable_anchor_resweep_gen; + } + static void setStaticFieldSweepMemoForTest(int count) { + ReferenceChainTracker::instance()->_last_static_field_class_count = count; + } + static void setStaticFieldSweepCursorForTest(int cursor) { + ReferenceChainTracker::instance()->_static_field_sweep_cursor = cursor; + } + static int staticFieldSweepCursorForTest() { + return ReferenceChainTracker::instance()->_static_field_sweep_cursor; + } + static constexpr size_t kLocalAnchorIndexCap = + ReferenceChainTracker::LOCAL_ANCHOR_INDEX_CAP; + static constexpr size_t kDurableAnchorIndexCap = + ReferenceChainTracker::DURABLE_ANCHOR_INDEX_CAP; + static constexpr size_t kDurableAnchorEvictBatch = + ReferenceChainTracker::DURABLE_ANCHOR_EVICT_BATCH; + static constexpr size_t kPendingLocalAnchorCap = + ReferenceChainTracker::PENDING_LOCAL_ANCHOR_CAP; + static constexpr int kLocalCompactBackoff = + ReferenceChainTracker::LOCAL_ANCHOR_COMPACT_BACKOFF; + static constexpr size_t kLocalCompactMinReclaim = + ReferenceChainTracker::LOCAL_ANCHOR_COMPACT_MIN_RECLAIM; + static int localCompactBackoffForTest() { + return ReferenceChainTracker::instance()->_local_compact_backoff; + } + static size_t pendingLocalEvictCursorForTest() { + return ReferenceChainTracker::instance()->_pending_local_evict_cursor; + } + static u32 localStagingAbsorbableForTest() { + return ReferenceChainTracker::instance()->localStagingAbsorbable(); + } + static void preparePendingLocalAnchorEvictionCursorForTest() { + ReferenceChainTracker::instance()->preparePendingLocalAnchorEvictionCursor(); + } + // Caller keeps idx < pendingLocalAnchorCountForTest(). + static jlong pendingLocalAnchorTagForTest(size_t idx) { + return ReferenceChainTracker::instance()->_pending_local_anchors[idx].tag; + } + static bool pendingLocalAnchorContainsForTest(jlong tag) { return ReferenceChainTracker::instance() - ->_static_anchor_index_class_tags.count(tag) > 0; + ->_pending_local_anchor_tags.count(tag) > 0; } - static void mergeAtRiskAnchorsForTest( - std::vector &selection, - const std::vector &drained) { - ReferenceChainTracker::mergeAtRiskAnchors(selection, drained); + // Reconcile collection step (see collectUnclassifiedAnchorClassTags()). + static constexpr int kAnchorShapeReconcileBudget = + ReferenceChainTracker::ANCHOR_SHAPE_RECONCILE_BUDGET; + static std::vector unclassifiedAnchorClassTagsForTest() { + return ReferenceChainTracker::instance() + ->collectUnclassifiedAnchorClassTags(); } static jlong discoveredTagForTest(int slot, int idx) { @@ -899,9 +1190,12 @@ class ReferenceChainsTestAccessor { } static std::vector - collectStaticFieldAnchorsForRotationForTest(int max_count) { + collectStaticFieldAnchorsForRotationForTest( + int max_count, + std::vector *fresh_picked = + nullptr) { return ReferenceChainTracker::instance() - ->collectStaticFieldAnchorsForRotation(max_count); + ->collectStaticFieldAnchorsForRotation(max_count, fresh_picked); } static void addToStaticAnchorIndexForTest(jlong tag, jlong own_class_tag, @@ -964,6 +1258,14 @@ class ReferenceChainsTestAccessor { entries); } + using FreshAnchor = ReferenceChainTracker::FreshAnchor; + + static void requeueStaticAnchorFreshFrontForTest( + const std::vector &entries) { + ReferenceChainTracker::instance()->requeueStaticAnchorFreshFront( + entries); + } + static size_t staticAnchorFifoSizeForTest() { return ReferenceChainTracker::instance()->_static_anchor_fifo.size(); } @@ -972,18 +1274,48 @@ class ReferenceChainsTestAccessor { return ReferenceChainTracker::instance() ->_static_anchor_fifo_set.contains(tag); } + static bool atRiskAnchorNeedsObservationForTest(jlong tag, u32 klass_id) { + return ReferenceChainTracker::instance()->atRiskAnchorNeedsObservation( + tag, klass_id); + } static void walkStaticAnchorFifoForTest(jvmtiEnv *jvmti, JNIEnv *jni, const std::vector &tags, int budget, int *edges_admitted, - std::vector *unwalked) { + std::vector *unwalked, + bool *anchor_observation_overflow = nullptr) { + walkStaticFieldAnchorsWithPrefillForTest(jvmti, jni, 0, tags, budget, + edges_admitted, unwalked, + anchor_observation_overflow); + } + + // Direct walkStaticFieldAnchors() drive with the walk's own scope pre-filled to + // `journal_prefill` records, so a test can force a mid-descent journal overflow after a + // controlled number of admitted edges. + static void walkStaticFieldAnchorsWithPrefillForTest( + jvmtiEnv *jvmti, JNIEnv *jni, size_t journal_prefill, + const std::vector &tags, int budget, int *edges_admitted, + std::vector *unwalked, + bool *anchor_observation_overflow = nullptr) { ReferenceChainTracker *t = ReferenceChainTracker::instance(); bool truncated = false; bool cap_hit = false; u64 safepoint_ns = 0; - t->walkStaticFieldAnchors(jvmti, jni, tags, budget, edges_admitted, - &truncated, &cap_hit, &safepoint_ns, + bool overflow = false; + // The scope is the caller-side owner: its destructor replays the accepted prefix. + ReferenceChainAnchorObservationScope scope(t); + if (journal_prefill > 0) { + ReferenceChainPassContext fill_ctx(scope); + fill_ctx.tracker = t; + fill_ctx.frontier = t->frontierTable(); + fillAnchorJournalForTest(fill_ctx, journal_prefill); + } + t->walkStaticFieldAnchors(jvmti, jni, scope, tags, budget, edges_admitted, + &truncated, &cap_hit, &safepoint_ns, &overflow, unwalked); + if (anchor_observation_overflow != nullptr) { + *anchor_observation_overflow = overflow; + } } // Direct candidate-slot seeding (the production path fills these via pollWatchedTargets()'s @@ -1048,12 +1380,26 @@ class ReferenceChainsTestAccessor { context); } + // Direct heapReferenceCallback driver for the static sweep's class -> field rediscovery of an + // already-admitted holder: negative class-object referrer (treated as root-like), holder as + // tag_ptr. + static jint reportStaticFieldEdgeForTest( + jlong referrer_class_tag, jlong *tag, void *context, + jlong class_tag = 0) { + jlong rtag = referrer_class_tag; + return ReferenceChainTracker::heapReferenceCallback( + JVMTI_HEAP_REFERENCE_STATIC_FIELD, /*reference_info=*/nullptr, + class_tag, /*referrer_class_tag=*/0, /*size=*/0, tag, &rtag, + /*length=*/0, 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); + kind, /*reference_info=*/nullptr, class_tag, 0, 0, tag, + referrer_tag, -1, context); } // Simulates a tag left in _priority_expand by a prior pass's truncated expandFrontier() diff --git a/ddprof-lib/src/test/cpp/referenceChainsTrackerTests.inc b/ddprof-lib/src/test/cpp/referenceChainsTrackerTests.inc index b43e48d6c9..20a542422d 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTrackerTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsTrackerTests.inc @@ -639,6 +639,46 @@ TEST_F(ResolvedChainCacheTest, DeferredInvalidationIsBoundedByCacheAndKeepsCapac (size_t)cap); } +TEST_F(ResolvedChainCacheTest, DeferredInvalidationOverflowClearsCacheOnNextDrain) { + const int cap = ReferenceChainsTestAccessor::maxResolvedChains(); + const long long dropped_before = + Counters::getCounter(REFERENCE_CHAIN_EVENTS_DROPPED); + auto stageOverflow = [&]() { + for (int i = 1; i <= cap; i++) { + ReferenceChainsTestAccessor::cacheChain(i, makeEvent(i), i, 0); + } + std::vector snapshot = + ReferenceChainsTestAccessor::snapshotResolvedChainTags(); + if (snapshot.size() != static_cast(cap)) { + return ReferenceChainsTestAccessor::pendingChainInvalidationCount(); + } + snapshot.pop_back(); // Leave one cached chain outside the invalidation set. + snapshot.push_back(cap + 1); + snapshot.push_back(cap + 2); // Simulate a broken snapshot bound. + for (jlong tag : snapshot) { + ReferenceChainsTestAccessor::deferResolvedChainInvalidation(tag, + snapshot); + } + return ReferenceChainsTestAccessor::pendingChainInvalidationCount(); + }; + + ASSERT_EQ(static_cast(cap), stageOverflow()); + ReferenceChainsTestAccessor::drainPendingChainInvalidations(); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::resolvedChainCount()); + EXPECT_EQ(0u, + ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + EXPECT_EQ(dropped_before + cap, + Counters::getCounter(REFERENCE_CHAIN_EVENTS_DROPPED)); + + ASSERT_EQ(static_cast(cap), stageOverflow()); + ReferenceChainsTestAccessor::applyPendingChainInvalidationsForTest(0); + EXPECT_EQ(0u, ReferenceChainsTestAccessor::resolvedChainCount()); + EXPECT_EQ(0u, + ReferenceChainsTestAccessor::pendingChainInvalidationCount()); + EXPECT_EQ(dropped_before + 2 * cap, + Counters::getCounter(REFERENCE_CHAIN_EVENTS_DROPPED)); +} + TEST_F(ResolvedChainCacheTest, RestartDropsPendingTagsBeforeNumericTagReuse) { ReferenceChainsTestAccessor::cacheChain(1, makeEvent(1), 1, 0); std::vector snapshot = diff --git a/ddprof-lib/src/test/cpp/referenceChainsTraversalTests.inc b/ddprof-lib/src/test/cpp/referenceChainsTraversalTests.inc index 984b1cec89..97d368ad6d 100644 --- a/ddprof-lib/src/test/cpp/referenceChainsTraversalTests.inc +++ b/ddprof-lib/src/test/cpp/referenceChainsTraversalTests.inc @@ -52,7 +52,7 @@ TEST_F(ReferenceChainsBfsTest, RollingResumePopsProcessedEntriesOnTruncatedBatch bool truncated = true; jlong listTag = 0; for (int i = 0; i < 200 && listTag == 0; i++) { - ASSERT_EQ(SearchState::RUNNING, tracker->searchState()); + ASSERT_EQ((u8)SearchState::RUNNING, tracker->searchState()); ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); listTag = tags_ever_assigned[listNode]; } @@ -60,7 +60,7 @@ TEST_F(ReferenceChainsBfsTest, RollingResumePopsProcessedEntriesOnTruncatedBatch // Phase 2: run passes until listNode is expanded (rolling resume pops it). for (int i = 0; i < 200; i++) { - ASSERT_EQ(SearchState::RUNNING, tracker->searchState()); + ASSERT_EQ((u8)SearchState::RUNNING, tracker->searchState()); ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); FrontierEntry entry{}; if (frontier->lookup(listTag, &entry) && @@ -83,7 +83,7 @@ TEST_F(ReferenceChainsBfsTest, RollingResumePopsProcessedEntriesOnTruncatedBatch // Phase 3: run more passes until all chain children are admitted. for (int i = 0; i < 500 && admittedChildren < kChainLen; i++) { - ASSERT_EQ(SearchState::RUNNING, tracker->searchState()); + ASSERT_EQ((u8)SearchState::RUNNING, tracker->searchState()); ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); admittedChildren = 0; for (int j = 0; j < kChainLen; j++) { @@ -798,6 +798,21 @@ public: static void setCpuEngine(Profiler *p, Engine *e) { p->_cpu_engine = e; } static void setWallEngine(Profiler *p, Engine *e) { p->_wall_engine = e; } static void setReferenceChainsActive(Profiler *p, bool v) { p->_reference_chains_active = v; } + static Engine *cpuEngine(Profiler *p) { return p->_cpu_engine; } + static Engine *wallEngine(Profiler *p) { return p->_wall_engine; } + static void setEngines(Profiler *p, Engine *cpu, Engine *wall) { + p->_cpu_engine = cpu; + p->_wall_engine = wall; + } + static State state(Profiler *p) { return p->_state.load(std::memory_order_acquire); } + static void setState(Profiler *p, State s) { p->_state.store(s, std::memory_order_release); } + static int eventMask(Profiler *p) { return p->_event_mask; } + static void setEventMask(Profiler *p, int mask) { p->_event_mask = mask; } + static bool referenceChainsActive(Profiler *p) { + return p->_reference_chains_active.load(std::memory_order_acquire); + } + static jvmtiEventMode threadEventsState(Profiler *p) { return p->_thread_events_state; } + static void setThreadEventsState(Profiler *p, jvmtiEventMode m) { p->_thread_events_state = m; } static void onThreadStart(Profiler *p, jvmtiEnv *jvmti, JNIEnv *jni, jthread thread) { p->onThreadStart(jvmti, jni, thread); } @@ -877,3 +892,1090 @@ TEST_F(ReferenceChainsBfsTest, ProfilerThreadLifecycleRegistersLateThreadObject) // with a wrapping cursor, and the walk reaches a leak held 3-4 hops inside a static collection in // one bounded call - the shape the one-hop Tier-2 rotation demonstrably cannot reach from an // un-expanded FRONTIER holder on a rising heap (pod rounds 5-6). + +// --------------------------------------------------------------------------------------------- +// Production-caller-path tests for the anchor-observation journal. Each drives a real traversal +// caller (runPass(), expandFrontier(), walkCandidateThreadLocals()); the scope those callers own +// applies the callbacks' records at the return boundary, and a full journal aborts the report +// before its destructive transition so the same object is reported again by a later traversal. +// --------------------------------------------------------------------------------------------- + +namespace { + +using T8Acc = ReferenceChainsTestAccessor; + +// Fills the live caller scope at a JVMTI return boundary so the next real callback reaches overflow. +struct T8JournalFill { + static inline bool fill_on_ior = false; + static inline int fill_on_follow_call = -1; // 0-based FollowReferences call to fill before + static inline int follow_calls = 0; + static inline jlong holder_tag = 0; + static inline jlong holder_class_tag = -9101; + static inline u32 count_after_fill = 0; + + // The fill saturates the journal by staging LOCAL reports production would bound to what + // replay can absorb; the unbounded override is active from seedHolder() until reset(). + static void reset(ReferenceChainTracker *tracker = nullptr) { + fill_on_ior = false; + fill_on_follow_call = -1; + follow_calls = 0; + holder_tag = 0; + count_after_fill = 0; + if (tracker != nullptr) { + T8Acc::setLocalStagingBudgetOverrideForTest(0); + } + } + + // Keeps one fixture frontier entry for tests that assert the count after a rejected report. + static void seedHolder(ReferenceChainTracker *tracker) { + T8Acc::setLocalStagingBudgetOverrideForTest(0xFFFFFFFFu); + holder_tag = tracker->nextTag(); + T8Acc::primeClassShapeForTest(holder_class_tag, false); + ASSERT_TRUE(T8Acc::insertFrontierEntry( + tracker->frontierTable(), holder_tag, /*parent_tag=*/1, /*depth=*/1, + FrontierEntryState::FRONTIER, JVMTI_HEAP_REFERENCE_STACK_LOCAL, 0, + holder_class_tag)); + } + + static void fill(const void *user_data) { + auto *ctx = const_cast( + static_cast(user_data)); + count_after_fill = static_cast(T8Acc::fillAnchorJournalForTest( + *ctx, AnchorObservationBuffer::CAPACITY)); + } +}; + +jvmtiError JNICALL t8FillingIterate(jvmtiEnv *env, jvmtiHeapRootCallback root_cb, + jvmtiStackReferenceCallback stack_cb, + jvmtiObjectReferenceCallback object_cb, + const void *user_data) { + if (T8JournalFill::fill_on_ior) { + T8JournalFill::fill(user_data); + } + return ReferenceChainsMockHeap::mock_IterateOverReachableObjects( + env, root_cb, stack_cb, object_cb, user_data); +} + +jvmtiError JNICALL t8FillingFollow(jvmtiEnv *env, jint heap_filter, jclass klass, + jobject initial_object, + const jvmtiHeapCallbacks *callbacks, const void *user_data) { + if (T8JournalFill::follow_calls++ == T8JournalFill::fill_on_follow_call) { + T8JournalFill::fill(user_data); + } + return ReferenceChainsMockHeap::mock_FollowReferences( + env, heap_filter, klass, initial_object, callbacks, user_data); +} + +// A scripted-root pass must enumerate roots, whatever an earlier pass of the singleton left. +void t8AllowRootEnumeration() { + T8Acc::setRootEnumRawStateForTest(0, 0); +} + +} // namespace + +// Root enumeration: the prefix accepted before a JVMTI error is applied before the error handling +// returns, and the enumeration the error cut short is retried by the next pass. +TEST_F(ReferenceChainsBfsTest, RootEnumerationAppliesAcceptedPrefixBeforeJvmtiError) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + const jlong leak_base = T8Acc::leakTagBase(); + int n[3] = {addNode(), addNode(), addNode()}; + for (int i = 0; i < 3; i++) { + node_tags[n[i]] = leak_base + i; + script.push_back({JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, n[i], -1}); + } + active_fixture->ior_error_after_prefix = JVMTI_ERROR_OUT_OF_MEMORY; + active_fixture->ior_prefix_count = 2; + t8AllowRootEnumeration(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_TRUE(truncated); + // Two reports crossed the callback; the error then cut the walk before the third. + EXPECT_EQ((int)JVMTI_ITERATION_CONTINUE, active_fixture->last_ior_control); + jlong f0 = tags_ever_assigned[n[0]]; + jlong f1 = tags_ever_assigned[n[1]]; + ASSERT_NE(leak_base + 0, f0); + ASSERT_GT(f0, 0); + ASSERT_GT(f1, 0); + EXPECT_EQ(0, tags_ever_assigned[n[2]]) << "the third root was never reported"; + EXPECT_EQ(leak_base + 2, node_tags[n[2]]); + // The accepted prefix was flushed before the error return: both durable roots are indexed and + // nothing is left in the journal. + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(f0)); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(f1)); + EXPECT_EQ(2u, T8Acc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + + // Retry: the third root is reported and indexed by the next enumeration. + active_fixture->ior_error_after_prefix = JVMTI_ERROR_NONE; + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + jlong f2 = tags_ever_assigned[n[2]]; + ASSERT_GT(f2, 0); + EXPECT_NE(leak_base + 2, f2); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(f2)); + EXPECT_EQ(3u, T8Acc::anchorIndexSizeForTest()); + + tracker->stop(); +} + +// Root enumeration with a full journal: the rejected leak conversion is not performed (the object +// keeps its leak tag, no frontier entry appears), the accepted prefix is still applied, and the +// retry converts it. +TEST_F(ReferenceChainsBfsTest, RootEnumerationOverflowLeavesLeakTagForRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + int leak_node = addNode(); + const jlong leak_tag = T8Acc::leakTagBase() + 7; + node_tags[leak_node] = leak_tag; + script = {{JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, leak_node, -1}}; + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_ior = true; + jvmti_tbl.IterateOverReachableObjects = &t8FillingIterate; + t8AllowRootEnumeration(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill) + << "the journal must be full when the rejected report arrives"; + EXPECT_TRUE(truncated); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, active_fixture->last_ior_control); + EXPECT_EQ(leak_tag, node_tags[leak_node]) << "overflow must leave the leak tag installed"; + EXPECT_EQ(1u, tracker->frontierTable()->size()) + << "no frontier entry may exist for the rejected conversion (only the fill holder)"; + EXPECT_EQ(0u, T8Acc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, T8Acc::journalCountForTest()) << "the full prefix is replayed and cleared"; + + jvmti_tbl.IterateOverReachableObjects = &mock_IterateOverReachableObjects; + T8JournalFill::reset(tracker); + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + jlong converted = tags_ever_assigned[leak_node]; + ASSERT_GT(converted, 0) << "the retry never converted the leak-tagged root"; + EXPECT_NE(leak_tag, converted); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(converted)); + + tracker->stop(); +} + +// Root upgrade of an already-admitted transient root to a durable one is a destructive transition: +// with a full journal the entry stays as it was and the next enumeration upgrades it. +TEST_F(ReferenceChainsBfsTest, RootEnumerationOverflowLeavesRootKindUnchangedForRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int node = addNode(); + jlong tag = tracker->nextTag(); + node_tags[node] = tag; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + script = {{JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, node, -1}}; + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_ior = true; + jvmti_tbl.IterateOverReachableObjects = &t8FillingIterate; + t8AllowRootEnumeration(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill); + EXPECT_TRUE(truncated); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_EQ((u8)JVMTI_HEAP_REFERENCE_STACK_LOCAL, entry.root_kind) + << "the rejected upgrade must not be performed"; + EXPECT_EQ(0, entry.parent_tag); + EXPECT_EQ(tag, node_tags[node]); + EXPECT_FALSE(T8Acc::anchorIndexContainsForTest(tag)); + + jvmti_tbl.IterateOverReachableObjects = &mock_IterateOverReachableObjects; + T8JournalFill::reset(tracker); + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_TRUE(frontier->lookup(tag, &entry)); + EXPECT_EQ((u8)JVMTI_HEAP_REFERENCE_JNI_GLOBAL, entry.root_kind); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(tag)); + + tracker->stop(); +} + +namespace { + +// Seeds the demotion shape: `parent` is a queued, root-attached stack-local entry whose expansion +// delivers an edge onto `holder`, a root-attached STATIC_FIELD entry (deeper path => demotion). +struct T8DemotionSeed { + static constexpr jlong kParentTag = 104; + static constexpr jlong kHolderTag = 105; +}; + +} // namespace + +// Expansion with a full journal: the demotion that would drop a durable root is not performed +// (entry stays root-attached, no at-risk push), the batch stays queued, and the retry demotes it. +TEST_F(ReferenceChainsBfsTest, ExpansionOverflowKeepsDemotionAndBatchForRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int parent = addNode(); + int holder = addNode(); + script = {{JVMTI_HEAP_REFERENCE_FIELD, parent, holder, -1}}; + node_tags[parent] = T8DemotionSeed::kParentTag; + node_tags[holder] = T8DemotionSeed::kHolderTag; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, T8DemotionSeed::kHolderTag, 0, 0, + FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, T8DemotionSeed::kParentTag, 0, 0, + FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + T8Acc::pushPendingExpandForTest(T8DemotionSeed::kParentTag); + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_follow_call = 0; + jvmti_tbl.FollowReferences = &t8FillingFollow; + + int edges = 0; + bool truncated = false; + // The test-only journal fill has no FIFO effect; the rejected demotion must not push one. + const size_t fifo_before = T8Acc::staticAnchorFifoSizeForTest(); + T8Acc::expandFrontierWithBudgetForTest(&mock_jvmti, &mock_jni, 1000, &edges, &truncated); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill); + EXPECT_TRUE(truncated); + EXPECT_EQ((int)JVMTI_VISIT_ABORT, active_fixture->last_follow_control); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(T8DemotionSeed::kHolderTag, &entry)); + EXPECT_EQ(0, entry.parent_tag) << "the rejected demotion must not be performed"; + EXPECT_EQ(0u, entry.depth); + EXPECT_EQ(fifo_before, T8Acc::staticAnchorFifoSizeForTest()); + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + // Incomplete batch: the source obligation stays queued and un-expanded. + EXPECT_EQ(std::vector{T8DemotionSeed::kParentTag}, T8Acc::pendingExpandContents()); + FrontierEntry parent_entry{}; + ASSERT_TRUE(frontier->lookup(T8DemotionSeed::kParentTag, &parent_entry)); + EXPECT_EQ(FrontierEntryState::FRONTIER, parent_entry.state); + + jvmti_tbl.FollowReferences = &mock_FollowReferences; + T8JournalFill::reset(tracker); + edges = 0; + T8Acc::expandFrontierWithBudgetForTest(&mock_jvmti, &mock_jni, 1000, &edges, &truncated); + EXPECT_FALSE(truncated); + ASSERT_TRUE(frontier->lookup(T8DemotionSeed::kHolderTag, &entry)); + EXPECT_EQ(T8DemotionSeed::kParentTag, entry.parent_tag); + EXPECT_EQ(1u, entry.depth); + EXPECT_TRUE(T8Acc::staticAnchorFifoContainsForTest(T8DemotionSeed::kHolderTag)); + EXPECT_EQ(0u, T8Acc::pendingExpandSize()); + ASSERT_TRUE(frontier->lookup(T8DemotionSeed::kParentTag, &parent_entry)); + EXPECT_EQ(FrontierEntryState::EXPANDED, parent_entry.state); + + tracker->stop(); +} + +// Expansion: records accepted before a JVMTI error are flushed before the error handling, and the +// batch (no entry known complete) stays queued. +TEST_F(ReferenceChainsBfsTest, ExpansionAppliesAcceptedPrefixBeforeJvmtiError) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int first = addNode(); + int second = addNode(); + int holder = addNode(); + int child = addNode(); + node_tags[first] = 104; + node_tags[second] = 106; + node_tags[holder] = 105; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, first, holder, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, second, child, -1}, + }; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 105, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + for (jlong tag : {104, 106}) { + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + T8Acc::pushPendingExpandForTest(tag); + } + // Two holder->element reports, then the first->holder demotion edge, then the error. + active_fixture->follow_error_after_prefix = JVMTI_ERROR_OUT_OF_MEMORY; + active_fixture->follow_prefix_count = 3; + + int edges = 0; + bool truncated = false; + T8Acc::expandFrontierWithBudgetForTest(&mock_jvmti, &mock_jni, 1000, &edges, &truncated); + EXPECT_TRUE(truncated); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(105, &entry)); + EXPECT_EQ(104, entry.parent_tag) << "the demotion delivered before the error was kept"; + EXPECT_TRUE(T8Acc::staticAnchorFifoContainsForTest(105)) + << "its at-risk record was flushed before the error return"; + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + EXPECT_EQ(0, tags_ever_assigned[child]) << "the error cut the walk before the second edge"; + EXPECT_EQ((std::vector{104, 106}), T8Acc::pendingExpandContents()); + + tracker->stop(); +} + +// Expansion: budget exhaustion keeps the accepted prefix, which includes the demotion delivered +// before the budget ran out. +TEST_F(ReferenceChainsBfsTest, ExpansionBudgetExhaustionKeepsAcceptedPrefix) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int parent = addNode(); + int holder = addNode(); + int admitted = addNode(); + int refused = addNode(); + node_tags[parent] = 104; + node_tags[holder] = 105; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, parent, holder, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, parent, admitted, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, parent, refused, -1}, + }; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 105, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 104, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + T8Acc::pushPendingExpandForTest(104); + + int edges = 0; + bool truncated = false; + T8Acc::expandFrontierWithBudgetForTest(&mock_jvmti, &mock_jni, 1, &edges, &truncated); + EXPECT_TRUE(truncated); + EXPECT_EQ(1, edges); + EXPECT_GT(tags_ever_assigned[admitted], 0); + EXPECT_EQ(0, tags_ever_assigned[refused]); + EXPECT_EQ((int)JVMTI_VISIT_ABORT, active_fixture->last_follow_control); + EXPECT_TRUE(T8Acc::staticAnchorFifoContainsForTest(105)) + << "the demotion recorded before the budget abort must be applied"; + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + + tracker->stop(); +} + +// Root enumeration cut short by a full frontier: the rediscovery accepted before the cap-hitting +// root is flushed (indexed) on the abandoning exit, with nothing left in the journal. +TEST_F(ReferenceChainsBfsTest, RootEnumerationFrontierCapExitFlushesAcceptedAnchor) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000:framecap=1")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int known = addNode(); + int fresh = addNode(); + const jlong known_tag = tracker->nextTag(); + node_tags[known] = known_tag; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, known_tag, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_JNI_GLOBAL)); + ASSERT_EQ(1u, frontier->size()); + ASSERT_FALSE(T8Acc::anchorIndexContainsForTest(known_tag)); + script = { + {JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, known, -1}, + {JVMTI_HEAP_REFERENCE_JNI_GLOBAL, -1, fresh, -1}, + }; + t8AllowRootEnumeration(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_TRUE(truncated); + EXPECT_EQ((int)JVMTI_ITERATION_ABORT, active_fixture->last_ior_control); + EXPECT_EQ(0, tags_ever_assigned[fresh]) << "the second root must not be admitted"; + EXPECT_EQ(1u, frontier->size()) << "the cap must have been what refused the second root"; + EXPECT_EQ(SearchState::ABANDONED, tracker->searchState()); + EXPECT_EQ((u8)SearchAbandonReason::FRONTIER_CAP, T8Acc::searchAbandonReasonForTest()); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(known_tag)) + << "the rediscovery accepted before the cap exit must be flushed"; + EXPECT_EQ(1u, T8Acc::anchorIndexSizeForTest()); + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + + tracker->stop(); +} + +// Static sweep with a full journal: the rejected static attachment is not admitted, the lap is not +// reported complete (the next pass sweeps again), exactly one resweep retry is requested, and the +// retry admits and indexes the holder. +TEST_F(ReferenceChainsBfsTest, StaticSweepOverflowRetriesChunkWithoutServing) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + int class_node = addNode(); + int holder = addNode(); + addClass((void *)&node_tags[class_node], "Lcom/rc/statics/OverflowHolder;"); + script = {{JVMTI_HEAP_REFERENCE_STATIC_FIELD, class_node, holder, -1}}; + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_follow_call = 0; // no candidates: the sweep is the first Follow call + jvmti_tbl.FollowReferences = &t8FillingFollow; + t8AllowRootEnumeration(); + const u64 gen_before = T8Acc::durableAnchorResweepGenForTest(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill) + << "the sweep's walk must be the one that met the full journal"; + EXPECT_TRUE(truncated); + EXPECT_EQ(0, tags_ever_assigned[holder]) << "the rejected admission must not be performed"; + EXPECT_EQ(0, node_tags[holder]); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_EQ(gen_before + 1, T8Acc::durableAnchorResweepGenForTest()) + << "a rejected static attachment requests exactly one resweep"; + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + + jvmti_tbl.FollowReferences = &mock_FollowReferences; + T8JournalFill::reset(tracker); + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + jlong admitted_tag = tags_ever_assigned[holder]; + ASSERT_GT(admitted_tag, 0) << "overflow was reported as a served chunk: no second sweep ran"; + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(admitted_tag)); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()); + + tracker->stop(); +} + +namespace { + +// kLapClasses loaded mock classes (> one 512-class sweep chunk), each a class object with one +// static field holding its own distinct holder. All nodes are created before any class captures a +// node address (addNode() may reallocate node_tags). +constexpr int kLapClasses = 600; +// Mirrors ReferenceChainTracker::STATIC_FIELD_SWEEP_CHUNK_CLASSES (private; the cursor assertions +// fail if the production value differs). +constexpr int kLapChunk = 512; + +struct T8LapWorld { + std::vector class_nodes; + std::vector holders; + std::vector chunk0; // class indices in the first sweep chunk (ascending class tag) + std::vector chunk1; +}; + +void t8BuildLapWorld(ReferenceChainsMockHeap &heap, T8LapWorld *w) { + static char sigs[kLapClasses][40]; + for (int i = 0; i < kLapClasses; i++) { + w->class_nodes.push_back(heap.addNode()); + w->holders.push_back(heap.addNode()); + } + for (int i = 0; i < kLapClasses; i++) { + snprintf(sigs[i], sizeof(sigs[i]), "Lcom/rc/lap/C%d;", i); + heap.addClass((void *)&heap.node_tags[w->class_nodes[i]], sigs[i]); + heap.script.push_back( + {JVMTI_HEAP_REFERENCE_STATIC_FIELD, w->class_nodes[i], w->holders[i], -1}); + } +} + +// The sweep orders classes by their (negative) class tag, minted by resolveLoadedClasses() in the +// first pass; reads that order back so assertions name the real chunk membership. +void t8PartitionChunks(const ReferenceChainsMockHeap &heap, T8LapWorld *w) { + std::vector order(kLapClasses); + for (int i = 0; i < kLapClasses; i++) { + order[i] = i; + } + std::sort(order.begin(), order.end(), [&](int a, int b) { + return heap.node_tags[w->class_nodes[a]] < heap.node_tags[w->class_nodes[b]]; + }); + w->chunk0.assign(order.begin(), order.begin() + kLapChunk); + w->chunk1.assign(order.begin() + kLapChunk, order.end()); +} + +size_t t8AdmittedHolders(const ReferenceChainsMockHeap &heap, const T8LapWorld &w, + const std::vector &classes) { + size_t n = 0; + for (int c : classes) { + n += heap.tags_ever_assigned[w.holders[c]] != 0; + } + return n; +} + +// Fills the durable share to exactly the cap (distinct indexed anchors with EXPANDED frontier +// entries, so no pass re-expands them), without crossing it. Tags stay below the frontier cap. +void t8FillDurableShareToCap(ReferenceChainTracker *tracker, jlong first_tag) { + const size_t cap = T8Acc::kDurableAnchorIndexCap; + for (jlong tag = first_tag; T8Acc::durableAnchorCountForTest() < cap; tag++) { + ASSERT_TRUE(T8Acc::insertFrontierEntry(tracker->frontierTable(), tag, 0, 0, + FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + T8Acc::addToStaticAnchorIndexForTest(tag, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + } + ASSERT_EQ(cap, T8Acc::durableAnchorCountForTest()); +} + +// Crosses the cap exactly once: one more distinct anchor evicts, requesting one resweep. +void t8CrossDurableCapOnce(ReferenceChainTracker *tracker, jlong tag) { + const u64 gen = T8Acc::durableAnchorResweepGenForTest(); + ASSERT_TRUE(T8Acc::insertFrontierEntry(tracker->frontierTable(), tag, 0, 0, + FrontierEntryState::EXPANDED, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + T8Acc::addToStaticAnchorIndexForTest(tag, -900, JVMTI_HEAP_REFERENCE_STATIC_FIELD); + ASSERT_EQ(gen + 1, T8Acc::durableAnchorResweepGenForTest()) + << "the cap crossing must request exactly one resweep"; + ASSERT_GT(T8Acc::durableAnchorCountForTest(), 0u); +} + +// Keeps the search RUNNING across passes that discover nothing new (a watched klass defers the +// natural-completion branch, which would release every tag and ignore later passes). +void t8KeepSearchRunning() { + T8Acc::setWatchedLeakKlassIdsForTest({1}); +} + +} // namespace + +// Real multi-chunk static sweep over > 512 loaded classes: chunk 0 completes and leaves the cursor +// at the chunk size; a cap crossing between passes requests a resweep WITHOUT resetting the +// cursor; the second chunk completes the lap latched at class 0 (old generation) and leaves the +// new generation unserved; the next full lap from class 0 serves it only after its final chunk. +TEST_F(ReferenceChainsBfsTest, StaticSweepMultiChunkLapServesOnlyItsStartLatchedGeneration) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=5000:firstpassbudget=5000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + t8KeepSearchRunning(); + + T8LapWorld w; + t8BuildLapWorld(*this, &w); + ASSERT_EQ(kLapClasses, (int)classes.size()); + ASSERT_GT(kLapClasses, kLapChunk); + + // Lap 1, chunk 0 (class-zero start latches the current, already-served generation). + bool truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(truncated); + ASSERT_EQ((u8)SearchState::RUNNING, tracker->searchState()); + t8PartitionChunks(*this, &w); + EXPECT_EQ(kLapChunk, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_EQ((size_t)kLapChunk, t8AdmittedHolders(*this, w, w.chunk0)); + EXPECT_EQ(0u, t8AdmittedHolders(*this, w, w.chunk1)) << "chunk 1 must not be swept yet"; + EXPECT_FALSE(T8Acc::durableAnchorResweepUnservedForTest()); + + // Cross the durable cap once while the lap is in flight. + t8FillDurableShareToCap(tracker, 10000); + t8CrossDurableCapOnce(tracker, 40000); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + EXPECT_EQ(kLapChunk, T8Acc::staticFieldSweepCursorForTest()) + << "the resweep request must not reset the in-flight cursor"; + + // Chunk 1 completes the OLD lap: the cursor wraps, but the new generation stays unserved. + truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(truncated); + EXPECT_EQ((size_t)kLapClasses - kLapChunk, t8AdmittedHolders(*this, w, w.chunk1)); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()) << "the lap must have completed"; + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()) + << "the lap latched before the eviction must not serve the later request"; + + // The next lap starts at class 0, latches the new generation, and serves it only at its end. + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_EQ(kLapChunk, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()) + << "a lap's first chunk must not serve its generation"; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_FALSE(T8Acc::durableAnchorResweepUnservedForTest()) + << "the lap's final chunk must serve the generation it latched at class 0"; + + tracker->stop(); +} + +// A truncated (journal-overflow) second chunk is not served: the cursor retries the chunk start, +// the lap is not reported complete, and the retry later completes the lap without serving the +// resweep the overflow requested. +TEST_F(ReferenceChainsBfsTest, StaticSweepMultiChunkTruncatedChunkRetriesWithoutServingLap) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=5000:firstpassbudget=5000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + t8KeepSearchRunning(); + + T8LapWorld w; + t8BuildLapWorld(*this, &w); + + bool truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_FALSE(truncated); + ASSERT_EQ(kLapChunk, T8Acc::staticFieldSweepCursorForTest()); + t8PartitionChunks(*this, &w); + ASSERT_EQ((size_t)kLapChunk, t8AdmittedHolders(*this, w, w.chunk0)); + const int saved_cursor = T8Acc::staticFieldSweepCursorForTest(); + + // Chunk 1 with a full journal: its new static attachments are rejected. + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_follow_call = 0; // the sweep is the first Follow call of the pass + jvmti_tbl.FollowReferences = &t8FillingFollow; + const u64 gen_before = T8Acc::durableAnchorResweepGenForTest(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill) + << "the chunk-1 sweep must be the walk that met the full journal"; + EXPECT_TRUE(truncated); + EXPECT_EQ(saved_cursor, T8Acc::staticFieldSweepCursorForTest()) + << "a truncated chunk must retry its own start, not advance or wrap"; + EXPECT_EQ(0u, t8AdmittedHolders(*this, w, w.chunk1)) << "rejected attachments must not be admitted"; + EXPECT_EQ(gen_before + 1, T8Acc::durableAnchorResweepGenForTest()); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + + // Retry: the chunk completes the lap; the overflow-requested generation stays unserved. + jvmti_tbl.FollowReferences = &mock_FollowReferences; + T8JournalFill::reset(tracker); + truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(truncated); + EXPECT_EQ((size_t)kLapClasses - kLapChunk, t8AdmittedHolders(*this, w, w.chunk1)); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()) + << "a lap whose chunk was truncated must not serve the request that truncation raised"; + + // A full fresh lap from class 0 then serves it. + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(T8Acc::durableAnchorResweepUnservedForTest()); + + tracker->stop(); +} + +// A FollowReferences error after a prefix of the FIRST chunk keeps the lap's original latch across +// the chunk retry: a resweep request raised between the latch and the retry (stood in for here by +// an at-cap eviction after the failed attempt) stays unserved until a fresh lap from class 0 +// completes. The retry stamps suppress re-reports of holders the failed attempt already accepted, +// so a retry that re-latched the newer generation would publish it as served while the evicted +// holder's class sits behind the retry stamps - leaving the holder out of the index with no +// pending request. The fresh lap's unsuppressed re-report must be what re-indexes it. +TEST_F(ReferenceChainsBfsTest, StaticSweepFirstChunkErrorRetryKeepsOriginalLatch) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=5000:firstpassbudget=5000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + t8KeepSearchRunning(); + + T8LapWorld w; + t8BuildLapWorld(*this, &w); + ASSERT_EQ(kLapClasses, (int)classes.size()); + ASSERT_GT(kLapClasses, kLapChunk); + t8PartitionChunks(*this, &w); + + // Lap 1, chunk 0: a four-edge prefix of the chunk's static fields is accepted (stamped by + // the failed attempt), then FollowReferences errors. The latch fired at the chunk-0 start; + // the retry flags are set and the cursor stays at the chunk start. The mock delivers all 512 + // class seeds before the script's static-field edges, so the prefix budget covers both. + active_fixture->follow_error_after_prefix = JVMTI_ERROR_OUT_OF_MEMORY; + active_fixture->follow_prefix_count = kLapChunk + 4; + bool truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + active_fixture->follow_error_after_prefix = JVMTI_ERROR_NONE; + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()) + << "the errored first chunk must retry its own start"; + std::vector stamped_tags; + for (int c : w.chunk0) { + if (tags_ever_assigned[w.holders[c]] != 0) { + stamped_tags.push_back(tags_ever_assigned[w.holders[c]]); + } + } + ASSERT_EQ(4u, stamped_tags.size()) + << "only the static-field edges delivered before the error may be admitted"; + const jlong stamped_tag = stamped_tags[0]; + EXPECT_FALSE(T8Acc::durableAnchorResweepUnservedForTest()); + + // One at-cap eviction raises a resweep request while the retry is pending. + t8FillDurableShareToCap(tracker, 10000); + t8CrossDurableCapOnce(tracker, 40000); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + + // The retry re-sweeps chunk 0: the stamped prefix is suppressed, the rest is admitted. + truncated = true; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(truncated); + EXPECT_EQ((size_t)kLapChunk, T8Acc::staticFieldSweepCursorForTest()); + + // Chunk 1 completes the lap: it publishes the ORIGINAL latch, so the eviction's request + // stays unserved - a re-latch at the retry's chunk-0 start would serve it here. + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_EQ(0, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()) + << "the retry lap must not serve the request raised after its lap latched"; + + // The fresh lap from class 0 re-reports the suppressed prefix without retry stamps, + // re-indexing the evicted holder, and its completion serves the request. + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_EQ((size_t)kLapChunk, T8Acc::staticFieldSweepCursorForTest()); + EXPECT_TRUE(T8Acc::durableAnchorResweepUnservedForTest()); + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + EXPECT_FALSE(T8Acc::durableAnchorResweepUnservedForTest()); + EXPECT_TRUE(T8Acc::anchorIndexContainsForTest(stamped_tag)) + << "the fresh lap's unsuppressed re-report must re-index the evicted holder"; + + tracker->stop(); +} + +// Selected-anchor walk with a full journal: the rejected demotion below the anchor's walk is not +// performed, the anchor returns to the front of the at-risk FIFO, and the next pass walks it again. +TEST_F(ReferenceChainsBfsTest, SelectedAnchorWalkOverflowRequeuesAnchorForRetry) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int root = addNode(); + int anchor = addNode(); + int holder = addNode(); + node_tags[root] = 104; + node_tags[anchor] = 105; + node_tags[holder] = 107; + script = {{JVMTI_HEAP_REFERENCE_FIELD, anchor, holder, -1}}; + // The anchor is chain-attached (the at-risk shape); the holder below it is a durable root that + // the walk's edge would demote. + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 104, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 105, 104, 1, FrontierEntryState::FRONTIER, 0)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 107, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + T8Acc::pushStaticAnchorFifoForTest(105, 28366); + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_follow_call = 0; // the anchor walk is the pass's only Follow call + jvmti_tbl.FollowReferences = &t8FillingFollow; + t8AllowRootEnumeration(); + + bool truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill); + EXPECT_TRUE(truncated); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(0, entry.parent_tag) << "the rejected demotion must not be performed"; + EXPECT_FALSE(T8Acc::staticAnchorFifoContainsForTest(107)); + EXPECT_TRUE(T8Acc::staticAnchorFifoContainsForTest(105)) + << "the partially walked anchor must be restored to the FIFO"; + EXPECT_EQ(0u, T8Acc::journalCountForTest()); + + jvmti_tbl.FollowReferences = &mock_FollowReferences; + T8JournalFill::reset(tracker); + t8AllowRootEnumeration(); + truncated = false; + ASSERT_TRUE(tracker->runPass(&mock_jvmti, &mock_jni, &truncated)); + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(105, entry.parent_tag); + EXPECT_TRUE(T8Acc::staticAnchorFifoContainsForTest(107)) + << "the retried walk's demotion is applied before the pass returns"; + EXPECT_FALSE(T8Acc::staticAnchorFifoContainsForTest(105)); + + tracker->stop(); +} + +// Journal overflow mid-descent: the partially walked anchor stays unwalked and is re-walked +// later, but its partial descent's edges STAY counted - ctx.edges_admitted counts NEW frontier +// admissions, the accepted prefix stays applied (the scope flush replays it), and the re-walk +// re-charges only still-unadmitted edges (dedup by positive tag), so the segment is charged +// exactly once. Rolling the partial edges back out of the budget would let applied-to-frontier +// work escape the budget (fails-before: the pushed rollback under-counted by the partial edges). +TEST_F(ReferenceChainsBfsTest, AnchorWalkOverflowKeepsPartialEdgesCounted) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + int anchor = addNode(); + int child = addNode(); + int holder = addNode(); + node_tags[anchor] = 105; + node_tags[holder] = 107; + // The journal is filled to capacity before the walk: the plain child edge is admitted first + // (edge admissions need no journal slot); the holder edge (a durable demotion, which needs + // journal room) is where the descent overflows. + script = { + {JVMTI_HEAP_REFERENCE_FIELD, anchor, child, -1}, + {JVMTI_HEAP_REFERENCE_FIELD, anchor, holder, -1}, + }; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 104, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STACK_LOCAL)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 105, 104, 1, FrontierEntryState::FRONTIER, 0)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 107, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + T8Acc::pushStaticAnchorFifoForTest(105, 28366); + + std::vector drained; + ASSERT_EQ(1, T8Acc::drainStaticAnchorFifoForTest(16, drained)); + std::vector drained_tags; + for (const auto &at_risk : drained) { + drained_tags.push_back(at_risk.tag); + } + + int edges = 0; + std::vector unwalked; + bool overflow = false; + T8Acc::walkStaticFieldAnchorsWithPrefillForTest( + &mock_jvmti, &mock_jni, AnchorObservationBuffer::CAPACITY, + drained_tags, 1000, &edges, &unwalked, &overflow); + EXPECT_TRUE(overflow); + ASSERT_EQ(1u, unwalked.size()); + EXPECT_EQ(105, unwalked[0]); + EXPECT_GT(tags_ever_assigned[child], 0) + << "the plain child edge never ran - the overflow came too early to exercise the contract"; + EXPECT_EQ(1, edges) + << "the partial descent's admitted edge must stay counted: it is applied to the frontier " + "and the re-walk will not re-charge it"; + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(0, entry.parent_tag) << "the rejected demotion must not be performed"; + + // A retry on an empty journal walks the anchor fully: the demotion lands and the child is + // re-admitted against a fresh budget. + jvmti_tbl.FollowReferences = &mock_FollowReferences; + edges = 0; + unwalked.clear(); + overflow = false; + T8Acc::walkStaticFieldAnchorsWithPrefillForTest( + &mock_jvmti, &mock_jni, 0, drained_tags, 1000, &edges, &unwalked, + &overflow); + EXPECT_FALSE(overflow); + EXPECT_TRUE(unwalked.empty()); + // The retry legitimately charges no NEW edges: the partial walk's child admission survived + // (frontier dedup) and was already counted above, so only the rejected demotion is left to + // apply - total charge for the anchor's segment stays exact. + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(105, entry.parent_tag) << "the retried descent demotes the holder"; + + tracker->stop(); +} + +// Candidate-thread descent with a full journal: the first thread's rejected demotion stops the +// group before the second thread is walked; the accepted prefix is flushed on the way out, and the +// retry walks both threads. +TEST_F(ReferenceChainsBfsTest, CandidateThreadWalkOverflowStopsGroupAndFlushesPrefix) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + FrontierTable *frontier = tracker->frontierTable(); + + void *threadCls = (void *)0x3101, *tlmapCls = (void *)0x3102, *loaderCls = (void *)0x3103; + int tlmapIdx = registerClassForFindClass( + tlmapCls, "java/lang/ThreadLocal$ThreadLocalMap", "Ljava/lang/ThreadLocal$ThreadLocalMap;"); + registerClassForFindClass(loaderCls, "java/lang/ClassLoader", "Ljava/lang/ClassLoader;"); + registerClassForFindClass(threadCls, "java/lang/Thread", "Ljava/lang/Thread;"); + thread_class = threadCls; + T8Acc::resolveLoadedClasses(&mock_jvmti, &mock_jni); + + int thread1 = addNode(); + int thread2 = addNode(); + int tlmap = addNode(); + int holder = addNode(); + node_tags[holder] = 107; + script = { + {JVMTI_HEAP_REFERENCE_FIELD, thread1, tlmap, tlmapIdx}, + {JVMTI_HEAP_REFERENCE_FIELD, tlmap, holder, -1}, + }; + // The first thread is already admitted root-attached (reuse path); the second is minted on + // its first walk. The durable holder under the ThreadLocalMap is what the walk demotes. + jlong anchor_tag = tracker->tagObject( + &mock_jvmti, reinterpret_cast(&node_tags[thread1])); + ASSERT_GT(anchor_tag, 0); + node_tags[thread1] = anchor_tag; + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, anchor_tag, 0, 0, FrontierEntryState::FRONTIER, + (u8)JVMTI_HEAP_REFERENCE_THREAD)); + ASSERT_TRUE(T8Acc::insertFrontierEntry(frontier, 107, 0, 0, FrontierEntryState::FRONTIER, + JVMTI_HEAP_REFERENCE_STATIC_FIELD)); + jint tids0[] = {777}; + jint tids1[] = {778}; + T8Acc::seedCandidateSlotForTest(0, 6, tids0, 1); + T8Acc::seedCandidateSlotForTest(1, 6, tids1, 1); + tracker->registerThreadObject(&mock_jni, 777, reinterpret_cast(&node_tags[thread1])); + tracker->registerThreadObject(&mock_jni, 778, reinterpret_cast(&node_tags[thread2])); + + T8JournalFill::reset(tracker); + T8JournalFill::seedHolder(tracker); + T8JournalFill::fill_on_follow_call = 0; + jvmti_tbl.FollowReferences = &t8FillingFollow; + + int edges = 0; + T8Acc::walkCandidateThreadLocalsForTest(&mock_jvmti, &mock_jni, 1000, &edges); + ASSERT_EQ(AnchorObservationBuffer::CAPACITY, T8JournalFill::count_after_fill); + FrontierEntry entry{}; + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(0, entry.parent_tag) << "the rejected demotion must not be performed"; + EXPECT_EQ(0, T8Acc::getTagForTest(&mock_jvmti, reinterpret_cast(&node_tags[thread2]))) + << "an overflowed descent must end the group before the next thread"; + EXPECT_EQ(0u, T8Acc::journalCountForTest()) << "the group's scope flushed on exit"; + + jvmti_tbl.FollowReferences = &mock_FollowReferences; + T8JournalFill::reset(tracker); + edges = 0; + T8Acc::walkCandidateThreadLocalsForTest(&mock_jvmti, &mock_jni, 1000, &edges); + ASSERT_TRUE(frontier->lookup(107, &entry)); + EXPECT_EQ(tags_ever_assigned[tlmap], entry.parent_tag) + << "the retried descent demotes the holder under the ThreadLocalMap"; + EXPECT_GT(T8Acc::getTagForTest(&mock_jvmti, reinterpret_cast(&node_tags[thread2])), 0) + << "the retry continues to the second thread"; + + tracker->stop(); +} + +// --------------------------------------------------------------------------------------------- +// Profiler::stop() and the BFS worker join (ProfilerTestAccessor, defined above). +// --------------------------------------------------------------------------------------------- + +namespace { + +// Counts the teardown calls stop() makes on an engine. +class T8CountingEngine : public Engine { +public: + int stops = 0; + int enable_calls = 0; + void stop() override { stops++; } + void enableEvents(bool) override { enable_calls++; } +}; + +// Puts the Profiler singleton back exactly as found, whatever the test asserted or returned from. +class T8ProfilerStateGuard { +public: + T8ProfilerStateGuard() + : _profiler(Profiler::instance()), + _state(ProfilerTestAccessor::state(_profiler)), + _cpu(ProfilerTestAccessor::cpuEngine(_profiler)), + _wall(ProfilerTestAccessor::wallEngine(_profiler)), + _mask(ProfilerTestAccessor::eventMask(_profiler)), + _active(ProfilerTestAccessor::referenceChainsActive(_profiler)), + _thread_events(ProfilerTestAccessor::threadEventsState(_profiler)), + _vm(VMTestAccessor::getVm()) {} + ~T8ProfilerStateGuard() { + ProfilerTestAccessor::setState(_profiler, _state); + ProfilerTestAccessor::setEngines(_profiler, _cpu, _wall); + ProfilerTestAccessor::setEventMask(_profiler, _mask); + ProfilerTestAccessor::setReferenceChainsActive(_profiler, _active); + ProfilerTestAccessor::setThreadEventsState(_profiler, _thread_events); + VMTestAccessor::setVm(_vm); + } + +private: + Profiler *_profiler; + State _state; + Engine *_cpu; + Engine *_wall; + int _mask; + bool _active; + jvmtiEventMode _thread_events; + JavaVM *_vm; +}; + +jint JNICALL t8MockGetEnv(JavaVM *, void **penv, jint) { + *penv = &ReferenceChainsMockHeap::active_fixture->mock_jni; + return JNI_OK; +} + +jvmtiError JNICALL t8MockGetAllThreads(jvmtiEnv *, jint *count, jthread **threads) { + *count = 0; + *threads = nullptr; + return JVMTI_ERROR_NONE; +} + +} // namespace + +#ifdef DEBUG +// A failed BFS-worker join must stop Profiler::stop() before any teardown the worker can still +// reach: the call returns an Error, the state stays RUNNING with the tracker active, no engine is +// stopped and the tracker's journal epoch is unchanged. Once the join succeeds, a retried stop() +// runs the whole teardown. +TEST_F(ReferenceChainsBfsTest, ProfilerStopFailedJoinSkipsTeardownAndRetrySucceeds) { + Arguments args; + ASSERT_FALSE(args.parse("referencechains=true:hops=64:budget=1000")); + ReferenceChainTracker *tracker = ReferenceChainTracker::instance(); + ASSERT_FALSE(tracker->start(args)); + + T8ProfilerStateGuard restore; + Profiler *profiler = Profiler::instance(); + T8CountingEngine cpu_engine; + T8CountingEngine wall_engine; + JNIInvokeInterface_ invoke_tbl{}; + invoke_tbl.GetEnv = &t8MockGetEnv; + JavaVM_ mock_vm{}; + mock_vm.functions = &invoke_tbl; + // stop()'s teardown tail talks to the JVM through these. + jvmti_tbl.GetAllThreads = &t8MockGetAllThreads; + VMTestAccessor::setVm(&mock_vm); + ProfilerTestAccessor::setEngines(profiler, &cpu_engine, &wall_engine); + ProfilerTestAccessor::setEventMask(profiler, EM_CPU | EM_WALL); + ProfilerTestAccessor::setThreadEventsState(profiler, JVMTI_DISABLE); + ProfilerTestAccessor::setReferenceChainsActive(profiler, true); + ProfilerTestAccessor::setState(profiler, RUNNING); + + // A started-but-unjoined worker whose join the stub refuses. The stub records the + // reference-chain gate state AT JOIN TIME: stop() must close the gate (heap callbacks and + // thread-object registrations) before it joins, so nothing past the flip can enqueue for the + // dying consumer. + T8Acc::setThreadUnjoinedForTest(); + static int s_join_calls_observed = 0; + static bool s_join_gate_open = false; + s_join_calls_observed = 0; + s_join_gate_open = false; + T8Acc::setJoinHookForTest([](pthread_t, void **) { + s_join_calls_observed++; + s_join_gate_open = ProfilerTestAccessor::referenceChainsActive( + Profiler::instance()); + return EBUSY; + }); + const u64 epoch_before = T8Acc::journalEpochForTest(); + + Error failed = profiler->stop(); + EXPECT_TRUE(failed) << "a failed join must make stop() report an error"; + EXPECT_EQ(1, s_join_calls_observed); + EXPECT_FALSE(s_join_gate_open) + << "the registration gate must be closed before the BFS join"; + EXPECT_FALSE(T8Acc::threadJoinedForTest()); + EXPECT_EQ(RUNNING, ProfilerTestAccessor::state(profiler)); + EXPECT_TRUE(ProfilerTestAccessor::referenceChainsActive(profiler)) + << "the failed join must reopen the gate: teardown was skipped"; + EXPECT_EQ(0, cpu_engine.stops); + EXPECT_EQ(0, wall_engine.stops); + EXPECT_EQ(epoch_before, T8Acc::journalEpochForTest()) << "tracker teardown must not have run"; + EXPECT_TRUE(tracker->enabled()); + + // Retry with a successful join: the join is attempted again and the teardown completes. + T8Acc::clearJoinResultForTest(); + T8Acc::setJoinResultForTest(0); + Error retried = profiler->stop(); + EXPECT_FALSE(retried) << (retried.message() != nullptr ? retried.message() : ""); + EXPECT_EQ(1, T8Acc::joinCallCountForTest()); + EXPECT_TRUE(T8Acc::threadJoinedForTest()); + EXPECT_EQ(IDLE, ProfilerTestAccessor::state(profiler)); + EXPECT_FALSE(ProfilerTestAccessor::referenceChainsActive(profiler)); + EXPECT_EQ(1, cpu_engine.stops); + EXPECT_EQ(1, wall_engine.stops); + EXPECT_GT(T8Acc::journalEpochForTest(), epoch_before) + << "the tracker's recording-boundary reset ran after the join"; + + T8Acc::clearJoinResultForTest(); +} +#endif diff --git a/ddprof-test/quarantine.txt b/ddprof-test/quarantine.txt index 11e1232880..f21dd7da68 100644 --- a/ddprof-test/quarantine.txt +++ b/ddprof-test/quarantine.txt @@ -91,16 +91,8 @@ com.datadoghq.profiler.nativesocket.NativeSocketSendRecvSeparateTest.* | PROF-16 com.datadoghq.profiler.nativesocket.NativeSocketStackTraceTest.* | PROF-16014 | 2026-09-21 | 2026-12-20 | el7-8-release-amd64 | @TestTemplate invocations (cstack=vm/vmx/dwarf/fp) have no method name in the XML; same root cause as the rest of the package com.datadoghq.profiler.cpu.TlsPrimingTest.* | PROF-16281 | 2026-10-20 | 2027-01-18 | el7-8-release-amd64 | samples_dropped_thread_local exceeds this test's sample count across all RetryingTest attempts (79/195, 50/645, 272/137); counter is shared with every SIGNAL_HANDLER_GUARD_OR_DROP path, so co-located runner load can trip the max(10, samples/20) bound -# PROF-16305 -- the reference-chain slow e2e family is intermittently red in -# the nightly sanitized run 39893765385. The dominant failure never observes a -# CachedPayload chain[0] (only HashMap$Node grace chains): 20 of ~32 eligible -# HotSpot 11+ debug/asan slow jobs. Three sibling tests fail the same run -- -# the two loose child-JVM variants report an out-of-pool correlation tag, and -# the gc-root variant never observes a ChainLink chain[0] on musl-aarch64 -# JDK 11. Scoped to *-slow so a failure in the regular suite still gates. -# These lines go away with the PROF-16305 fix PR (PR #800) once the tests -# are made reliable again. -com.datadoghq.profiler.referencechains.ReferenceChainTrackingTest.shouldReconstructReferrerChainThroughUnboundedCacheLeak | PROF-16305 | 2026-10-23 | 2027-01-21 | *-slow | Never observes a CachedPayload chain[0] (only HashMap$Node chains); failed 20 of ~32 eligible HotSpot 11+ debug/asan slow jobs in nightly run 39893765385 -com.datadoghq.profiler.referencechains.ReferenceChainTrackingTest.shouldReconstructReferrerChainToGcRoot | PROF-16305 | 2026-10-23 | 2027-01-21 | *-slow | Never observes a ChainLink chain[0]; 1 failing job (musl-11-debug-aarch64-slow) in nightly run 39893765385 -com.datadoghq.profiler.referencechains.ThreadLocalLeakReferenceChainTest.shouldCorrelateThreadLocalHeldLeakChain | PROF-16305 | 2026-10-23 | 2027-01-21 | *-slow | Child reports [tl-correlation-tag-out-of-pool]; 3 failing jobs in nightly run 39893765385 -com.datadoghq.profiler.referencechains.LeakTagCorrelationReferenceChainTest.shouldCorrelateLeakChainTargetTagWithLiveObjectLeakTag | PROF-16305 | 2026-10-23 | 2027-01-21 | *-slow | Child reports [correlation-tag-out-of-pool]; 1 failing job in nightly run 39893765385 +# PROF-16632 was handled in the test itself: elfparser_ut's +# invalidElfSmallMappingAfterUnmap skips at runtime under TSan because the +# intentional dlclose-vs-parseLibraries race aborts the whole binary +# (halt_on_error) before any XML is written, which quarantine cannot express. +# See the GTEST_SKIP in ddprof-lib/src/test/cpp/elfparser_ut.cpp. diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakTagCorrelationScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakTagCorrelationScenario.java index 4fe6125b2f..c0c560adba 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakTagCorrelationScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/LeakTagCorrelationScenario.java @@ -89,6 +89,32 @@ private LeakTagCorrelationScenario() {} private static final int SEED_CHUNKS = 10; + /** + * Growth schedule of run()'s 25-round loop (load-bearing, see the loop's own comment): the leak + * grows by {@link #CHUNKS_PER_GROWTH_ROUND} chunks in each of rounds 1..GROWTH_ROUNDS, and only + * by one chunk every {@link #QUIET_TOP_UP_EVERY}th round after that. Invariants: + * + *
    + *
  • Total leak = SEED_CHUNKS + GROWTH_ROUNDS * CHUNKS_PER_GROWTH_ROUND + (25 - GROWTH_ROUNDS) + * / QUIET_TOP_UP_EVERY = 10 + 20 + 3 = 33 chunks, below the 35 of the earlier + * one-chunk-every-round schedule - a smaller working set, never a larger one. + *
  • Every {@link #LEAK_SINK} backing-array replacement (capacity 10 -> 15 -> 22 -> 33 at + * sizes 11/16/23) happens inside the growth rounds, i.e. after the first-pass wait (so the + * resize case LEAK_SINK exists for is still exercised) and before the tail; the tail + * top-ups fill size 31..33 within the final capacity 33, so the tail never replaces + * elementData again. + *
  • The growth rounds alone span 10 GC epochs (one System.gc() per round), i.e. + * KLASS_POPULATION_MIN_FILL_FOR_TREND ring samples of real growth; the tail top-ups keep a + * fresh surviving-age cohort arriving so the real fold's trend does not go flat, and debug + * builds additionally push one seeded rising epoch every round. + *
+ */ + private static final int GROWTH_ROUNDS = 10; + + private static final int CHUNKS_PER_GROWTH_ROUND = 2; + + private static final int QUIET_TOP_UP_EVERY = 5; + /** * Per-round trend-maintenance epoch counter (debug builds only), same pattern as * StaticFieldGrowingCollectionScenario: a one-shot seeded ramp ages out of LivenessTracker's @@ -315,11 +341,24 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD // every scanned dump are accumulated into the kept result. ScanResult best = null; int totalRounds = 25; - // Slow growth per round is deliberate: each chunk clears the allocation sampler's floor on - // its own (see CHUNK_BYTES), so every allocation is sampled, tracked, and taggable - the - // per-round population growth is only the trend signal, not a sampling-volume requirement. + // Front-loaded growth, quiet tail (see GROWTH_ROUNDS): rounds 1..GROWTH_ROUNDS grow the leak, + // every later round is a quiet poll with only the sparse QUIET_TOP_UP_EVERY top-up. Pass 1 + // (the first pass that can intercept a leak tag) is gated by repaying pass 0's CPU + // pain-budget debt, which on a slow cell lands anywhere in the tail or grace period; with + // the growth already done by then, every chunk is tracked, leak-tagged, and sitting in the + // final elementData whenever that pass lands. Each chunk still clears the allocation + // sampler's floor on its own (see CHUNK_BYTES), so every allocation is sampled, tracked, and + // taggable - the per-round growth is only the trend signal, not a sampling-volume + // requirement, and in debug builds the per-round seeded ramp below keeps both trends + // qualifying through the quiet tail. for (int round = 1; round <= totalRounds; round++) { - addChunk(); + int newChunks = + round <= GROWTH_ROUNDS + ? CHUNKS_PER_GROWTH_ROUND + : (round % QUIET_TOP_UP_EVERY == 0 ? 1 : 0); + for (int c = 0; c < newChunks; c++) { + addChunk(); + } if (debugBuild) { hysteresisEpoch++; ReferenceChainTestHooks.seedKlassPopulationSample0( diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ReferenceChainTrackingTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ReferenceChainTrackingTest.java index 9c817debb6..c284aca70e 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ReferenceChainTrackingTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ReferenceChainTrackingTest.java @@ -390,7 +390,9 @@ public void shouldReconstructReferrerChainToGcRoot() throws Exception { ReferenceChainAssertions.JfrChainMatch match = null; boolean seededTestKlassTrend = false; int totalRounds = 16; + int roundsRun = 0; for (int round = 1; round <= totalRounds && match == null; round++) { + roundsRun = round; int newInstances = Math.min(round, 10) * 600; List newLinks = new ArrayList<>(newInstances); currentBatch = newLinks; // published before the request - see the allocator's loop @@ -522,8 +524,9 @@ public void shouldReconstructReferrerChainToGcRoot() throws Exception { + gcRootHolder.size() + " retained ChainLink instances across up to " + totalRounds - + " population-growth rounds plus a grace period" - + failureDiagnostics); + + " allocator rounds plus a grace period" + + failureDiagnostics + + (match == null ? referenceChainDiagnostics(gcRootHolder.get(0), roundsRun) : "")); // chain[0] is the *target* object's own class, not its holder's: reconstructChain() appends // each visited FrontierEntry's referrer_klass leaf-to-root, and referrer_klass is populated // from the *discovered object's own* GetClassSignature at insertion time. The target here is @@ -589,15 +592,27 @@ public void shouldReconstructReferrerChainThroughUnboundedCacheLeak() throws Exc Files.deleteIfExists(scratchDumpPath); Thread allocator = null; try { - // Same round-growth/retry shape as shouldReconstructReferrerChainToGcRoot() - see that - // method's own comment for why the loop self-adjusts rather than committing to a fixed - // round count, why per-round scale is sized against ObjectSampler's real 256KiB sampling - // floor rather than this test's own "memory=64" request, why totalRounds is capped at - // 16 rather than a larger margin above the 10-round minimum (shared-fork heap headroom), - // and why per-round growth itself is clamped to round 10 (Math.min(round, 10) below). + // Same retry shape as shouldReconstructReferrerChainToGcRoot() - see that method's own + // comment for why the loop self-adjusts rather than committing to a fixed round count, why + // per-round scale is sized against ObjectSampler's real 256KiB sampling floor rather than + // this test's own "memory=64" request, and why totalRounds is capped at 16 rather than a + // larger margin above the 10-round minimum (shared-fork heap headroom). + // + // Growth schedule, unlike the gc-root test: the round*600 growth completes at round + // growthRounds (10) - the population trend is already eligible by then. Rounds 11-16 are + // quiet poll/maintenance rounds adding only quietTopUpEntries each: enough to keep + // CachedPayload's population ring advancing (a stalled ring lets the candidate lapse out of + // selectLeakCandidates()), small enough that the BFS gets those rounds plus the grace + // period to drain its frontier backlog and reach a leak-tagged CachedPayload inside the + // HashMap's Node[] - a map that kept growing through all 16 rounds kept that backlog ahead + // of the walk until the retry budget ran out. Static bound: 10*11/2*600 + 6*600 + 1 seed + // = 36,601 entries, within the previous all-growth schedule's 69,001. ReferenceChainAssertions.JfrChainMatch match = null; boolean seededTestKlassTrend = false; int totalRounds = 16; + int growthRounds = 10; + int quietTopUpEntries = 600; + int roundsRun = 0; // Pre-generate every key up front rather than concatenating a fresh String on every put(). // The key String (plus its backing byte[]) is the same kind of same-instant, @@ -607,7 +622,7 @@ public void shouldReconstructReferrerChainThroughUnboundedCacheLeak() throws Exc // the sampler has nothing else in flight to compete with once round 1 begins. int maxEntries = 0; for (int round = 1; round <= totalRounds; round++) { - maxEntries += Math.min(round, 10) * 600; + maxEntries += round <= growthRounds ? Math.min(round, 10) * 600 : quietTopUpEntries; } String[] keys = new String[maxEntries]; for (int i = 0; i < keys.length; i++) { @@ -650,11 +665,13 @@ public void shouldReconstructReferrerChainThroughUnboundedCacheLeak() throws Exc awaitAllocatorTid(allocator, allocatorTid, allocatorFailure); for (int round = 1; round <= totalRounds && match == null; round++) { + roundsRun = round; // Same *600 growth rate as the gc-root test (not *300, this method's previous value): // CachedPayload and ChainLink are near-identical in size, so halving the growth rate here // bought no headroom and just let CachedPayload's population ring stall short of - // KLASS_POPULATION_MIN_FILL_FOR_TREND within the same totalRounds budget. - int newEntries = Math.min(round, 10) * 600; + // KLASS_POPULATION_MIN_FILL_FOR_TREND within the growth rounds. Past growthRounds only the + // quiet top-up - see the schedule comment above. + int newEntries = round <= growthRounds ? Math.min(round, 10) * 600 : quietTopUpEntries; if (!allocRequests.offer(newEntries)) { throw new IllegalStateException("allocRequests queue rejected entry count " + newEntries); } @@ -768,8 +785,9 @@ public void shouldReconstructReferrerChainThroughUnboundedCacheLeak() throws Exc + cache.size() + " cached entries across up to " + totalRounds - + " population-growth rounds plus a grace period" - + failureDiagnostics); + + " allocator rounds plus a grace period" + + failureDiagnostics + + (match == null ? referenceChainDiagnostics(cache.get(keys[0]), roundsRun) : "")); assertEquals(CachedPayload.class.getName(), match.chain.get(0)); assertTrue(match.targetTag > 0, "targetTag should be a valid, non-zero JVMTI tag"); assertTrue(match.depth >= 0, "depth should be a non-negative hop count"); @@ -993,6 +1011,21 @@ private static void awaitAllocatorTid( } } + /** + * Adds the resolved target tag and round count to the shared failure fingerprint after a miss. + * Release builds have no test seams, so this returns {@code ""} there. + */ + private static String referenceChainDiagnostics(Object representative, int roundsRun) { + if (!ReferenceChainAssertions.isDebugInstrumentedBuild()) { + return ""; + } + return " [additional diagnostics: repResolvedTargetTag=" + + ReferenceChainTestHooks.getReferenceChainResolvedTargetTagForTest0(representative) + + " roundsRun=" + + roundsRun + + "]"; + } + /** * Runs up to {@code maxPasses} bounded reference-chain search passes synchronously via the * debug-only {@link ReferenceChainTestHooks#runReferenceChainPass0()} seam, each followed by the diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/StaticFieldGrowingCollectionScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/StaticFieldGrowingCollectionScenario.java index 3b8c57082c..7d8f9c89e0 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/StaticFieldGrowingCollectionScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/StaticFieldGrowingCollectionScenario.java @@ -275,6 +275,7 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD // however many rounds a wipe costs, the trend simply resumes accumulating from the next // round's seed call. ReferenceChainAssertions.ChainMatch match = null; + int manualPassAttempts = 0; for (int round = 1; round <= TOTAL_ROUNDS && match == null; round++) { // Mirrors the real leak's continuous growth; lateChunk stays the watched target. LEAK_BUFFER.add(new byte[CHUNK_BYTES]); @@ -303,6 +304,14 @@ public static void run(JavaProfiler profiler, String startCommand, Path scratchD ReferenceChainTestHooks.setKlassPopulationRepresentativeForTest0( LEAK_BUFFER_TEST_KLASS_ID, LEAK_BUFFER.get(LATE_CHUNK_INDEX)); ReferenceChainTestHooks.pollReferenceChainTargets0(); + // Bound debug-only seam attempts; this assertion tests re-expansion, not pass cadence. + if (manualPassAttempts < 8) { + if (!ReferenceChainTestHooks.runReferenceChainPass0()) { + throw new IllegalStateException("reference-chain pass seam did not run"); + } + manualPassAttempts++; + ReferenceChainTestHooks.pollReferenceChainTargets0(); + } // Only TRUST a match once passesRun() has genuinely changed since the snapshot taken right // before lateChunk was created - either advanced (the same, never-restarted search ran a diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakReferenceChainTest.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakReferenceChainTest.java index a7d483a8cc..32b3cc2d91 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakReferenceChainTest.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakReferenceChainTest.java @@ -50,8 +50,11 @@ void shouldCorrelateThreadLocalHeldLeakChain() throws Exception { Deque testLogTail = new ArrayDeque<>(); try { // Same raised budget/ratio rationale as - // LeakTagCorrelationReferenceChainTest (cold external JVM, ~100k filler, - // memory=64:l:1.0 keeping every chunk allocation tracked). + // LeakTagCorrelationReferenceChainTest (cold external JVM, + // memory=64:l:1.0 keeping every chunk allocation tracked). This + // scenario's filler is ~24k nodes, not ~100k (ThreadLocalLeakScenario.FILLER's + // own comment: it bounds the first pass's CPU pain-budget debt), so the + // budget still leaves that first pass untruncated with headroom. String startCommand = "start,memory=64:l:1.0,generations=true," + "referencechains=true:hops=64:budget=200000:ttl=120000:framecap=2000000:" diff --git a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakScenario.java b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakScenario.java index 2746bbd4f1..26f0de554f 100644 --- a/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakScenario.java +++ b/ddprof-test/src/test/java/com/datadoghq/profiler/referencechains/ThreadLocalLeakScenario.java @@ -47,6 +47,18 @@ * patterns as {@code LeakTagCorrelationScenario}'s own class comment (the one-shot root-seeded walk * is a per-process resource, and a one-shot seeded ramp ages out of LivenessTracker's hysteresis * once real fold samples interleave). + * + *

Schedule shape (see {@link #FILLER}): every round appends one chunk to the leak thread's + * ThreadLocal sink — the chunk supply must span the whole window because the correlation needs the + * walk to intercept a leak-tagged chunk inside the thread's ThreadLocalMap, and starving the tail + * rounds starves that interception surface (observed as {@code tl-correlation-not-found} on JDK 11 + * for the late-thread variant). The scale filler, in contrast, is kept small: the first + * (root-enumeration) pass charges its whole non-safepoint walk time to the tracker's CPU pain + * budget, and no further pass runs until that debt is repaid; until then the only {@code byte[]} + * chains are that first pass's out-of-pool discovered instances. A smaller walked heap shortens the + * debt so the second pass - the one that builds the in-pool chain - lands well inside the 25-round + * + 5-grace window on slow CI cells (an ~8.5 s debt at 96,000 nodes was repaid only at about dump + * 25 of 30 locally). */ public final class ThreadLocalLeakScenario { private ThreadLocalLeakScenario() {} @@ -58,8 +70,16 @@ private ThreadLocalLeakScenario() {} private static final ThreadLocal> SINK = ThreadLocal.withInitial(() -> new ArrayList<>()); - /** Scale ingredient - same rationale as LeakTagCorrelationScenario.FILLER. */ - static final Object[][] FILLER = new Object[1500][]; + /** + * Scale ingredient - same rationale as LeakTagCorrelationScenario.FILLER, but a quarter of its + * size (375 x 64 = 24,000 nodes, not 96,000). Invariant: the filler is the bulk of the heap the + * first pass walks (the byte[] chunks are reference-free leaves), and that pass's non-safepoint + * time is the CPU pain-budget debt the second pass waits out - the one that builds the in-pool + * chain. The filler must stay small enough that the debt is repaid well inside the 25-round + + * 5-grace window on slow CI cells (an ~8.5 s debt at 96,000 nodes repaid only at about dump 25 of + * 30 locally); it still gives the frontier and the tag map real depth. + */ + static final Object[][] FILLER = new Object[375][]; // Distinct from the other scenarios' ids (987301-987304) - each scenario // runs in its own child JVM, but a distinct id keeps logs unambiguous. @@ -170,7 +190,8 @@ public static void run( // One round = the main thread offers a token; the leak thread takes it and // appends one chunk to ITS OWN ThreadLocal sink (same persistent-allocator // shape as ReferenceChainTrackingTest's togcroot fixture, so the chunks are - // always allocated on the same qualifying tid). + // always allocated on the same qualifying tid). Every round of the window + // offers a token - see the class comment's schedule-shape paragraph. BlockingQueue rounds = new ArrayBlockingQueue<>(32); Thread leakThread = new Thread( @@ -252,6 +273,8 @@ public static void run( ScanResult best = null; int totalRounds = 25; for (int round = 1; round <= totalRounds; round++) { + // Every round appends one chunk - the interception-surface invariant in the + // class comment; do not front-load this growth away. if (!rounds.offer(round)) { throw new IllegalStateException("rounds queue rejected round " + round); } @@ -286,9 +309,8 @@ public static void run( ReferenceChainTestHooks.seedTidTrendSample0( LEAK_KLASS_ID, leakTid, hysteresisEpoch * 3, hysteresisEpoch); } - if (!rounds.offer(attempt)) { - throw new IllegalStateException("rounds queue rejected attempt " + attempt); - } + // No chunk is appended in the grace attempts; the trend maintenance + // above is what keeps the candidate alive. Thread.sleep(1000); System.gc(); profiler.dump(scratchDumpPath); diff --git a/doc/README.md b/doc/README.md index 3051b34c39..f09e2b487e 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 reference-chain implementation, including root-anchor indexing and rotation, and deferred updates after JVMTI traversal - [MallocArenaWarning](architecture/MallocArenaWarning.md) - glibc malloc arena detector: arena walk, rule, and JFR events - [NativeMemoryProfiling](architecture/NativeMemoryProfiling.md) - malloc interception, startup admission, per-recording restoration 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 9178f6e2d9..30101e041a 100644 --- a/doc/ReferenceChainsCollectionSummary.md +++ b/doc/ReferenceChainsCollectionSummary.md @@ -105,30 +105,25 @@ 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 and stale expanded entries. -It also revisits transient roots and anchor holders. +A one-time breadth-first walk cannot observe references that appear after the first expansion of an object. This matters for a long-lived collection that receives new elements. -These bounded walks improve mutation coverage. They do not guarantee every changed reference -is observed. +The tracker addresses this case with bounded rotation: -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. +- Leak-accumulation rotation selects parent objects that receive instances of watched classes. +- Stale-entry rotation revisits older expanded entries. +- Root-kind rotation revisits entries with transient root attribution. +- Anchor rotation descends from selected objects held by static fields or JNI globals, and from a capped set of confirmed collection/map holders first seen as stack or JNI locals. -An indexed `CONTAINER` holder can remain eligible after reparenting. -Unknown or `NON_CONTAINER` local-root entries are not persistently selected while they -remain transient. +Heap callbacks record anchor-index effects in a bounded journal. The traversal caller replays accepted observations after the JVMTI call returns. Rotation improves coverage, but it does not guarantee that the tracker observes every mutation. 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. +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 and fresh +picks to the front of their queues when their frontier entries still exist. ## Cost controls diff --git a/doc/architecture/LiveHeapReferenceChainsImplementation.md b/doc/architecture/LiveHeapReferenceChainsImplementation.md index 1b7fe5c6f2..fb47ac7891 100644 --- a/doc/architecture/LiveHeapReferenceChainsImplementation.md +++ b/doc/architecture/LiveHeapReferenceChainsImplementation.md @@ -16,9 +16,9 @@ Related documents: ## Main components -`LivenessTracker` detects growth in the number of distinct GC ages among surviving tracked -samples of a class. Candidate selection also requires qualifying allocating-thread evidence. -It assigns leak tags to instances in those class/thread groups. +`LivenessTracker` uses distinct GC ages and allocating-thread evidence to select candidates. Each +class keeps 16 retained thread cohorts and four challenger slots; these add 143,360 bytes across +256 classes. When all incumbents meet the count bar, a challenger must outscore the weakest. `ReferenceChainTracker` maintains a root-based frontier and searches for those instances. It runs on one agent-owned background thread. `_engine_lock` serializes engine state across lifecycle and test paths. @@ -108,14 +108,21 @@ can expand already-admitted roots while waiting for the next enumeration attempt Root enumeration uses `firstpassbudget`, including attempts after the first pass. -This phase does not use the callback deadline or keep an enumeration cursor. Repeated -attempts can examine already-admitted roots without charging admission budget. Direct-root -leak-tag conversion also bypasses the ordinary admission-budget check; elapsed time is not bounded. +Root enumeration has no JVMTI cursor. It skips compatible indexed anchors and stamps accepted +durable reports by tag, source, kind, and attempt. A retry suppresses only reports accepted by its +preceding incomplete attempt; static-field chunks keep separate stamps across index eviction. + +A weaker `JNI_GLOBAL` report does not replace `STATIC_FIELD` attribution but can re-enlist an evicted +anchor when no index or accepted report covers it. Suppression of the weaker report is bound to the +live index or an accepted retry stamp only: a stale static-sweep stamp alone never suppresses, so a +holder whose static edge disappeared but which a JNI global still retains can always re-enlist after +eviction. Stronger upgrades and rejected transitions remain eligible; chain-attached entries cannot +be upgraded by roots. -For this release, a root-enumeration pause is acceptable if it is shorter than three -seconds. This threshold is not the desired latency and is not a hard real-time -guarantee. [PROF-16284](https://datadoghq.atlassian.net/browse/PROF-16284) -tracks separate measurement and a progress-preserving mitigation. +Repeated attempts can examine already-admitted roots without charging admission budget. Direct-root +leak-tag conversion also bypasses the ordinary admission-budget check; elapsed time is not bounded. +For this release, a root-enumeration pause is acceptable when it stays under three seconds; separate +work tracks the measurement and a progress-preserving mitigation. ### Static fields @@ -197,67 +204,134 @@ 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. | -| 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. - -When a class first becomes watched, the tracker scans existing expanded entries for matching stable class tags. This scan supplies data that admission-time tracking could not collect before the class became watched. - -Rotation improves coverage but remains bounded and best effort. +| Anchors | 32 selected, plus 16 FIFO entries | Descend from indexed anchors: objects held by static fields or JNI globals, and confirmed collection/map holders first seen as stack or JNI locals. See [Anchor index](#anchor-index). | + +### Anchor index + +`collectStaticFieldAnchorsForRotation()` selects descend-walk anchors from an index +(`_static_anchor_index`), not from the full frontier table. The index has two shares: + +- **Durable share.** Root-attached `STATIC_FIELD` and `JNI_GLOBAL` entries, added by + `addToStaticAnchorIndex()`. Such an entry is selectable while it stays root-attached with a + durable root kind. Once it is classified as a collection or map, it stays selectable after + reparenting. A reparented holder of any other class gets one walk from the at-risk FIFO + (`pushAtRiskStaticAnchor()`). +- **Local share.** Holders that root enumeration reports as `STACK_LOCAL` or `JNI_LOCAL` roots. + `heapRootCallback()` passes them to `noteLocalRootHolder()`. A holder is indexed only after + `reconcileAnchorClassShapes()` classifies its class as implementing `java.util.Collection` or + `java.util.Map` (or leaves a bounded hierarchy walk truncated - see below). A confirmed collection remains selectable after expansion reparents it into a + deeper chain, so the tracker still observes replacement backing storage such as a resized + `HashMap.table`. Local holders of any other class are never indexed. + +Classification needs JNI, which the heap-root callback cannot use. A holder whose class is not +yet classified waits in `_pending_local_anchors`, capped at 1024 entries. +`resolvePendingLocalAnchors()` runs after each `reconcileAnchorClassShapes()`. It indexes the +confirmed collections and holders whose walk ended truncated, and drops everything else, +including holders whose class is still unclassified. The next root enumeration reports a dropped holder again. Reconciliation +classifies pending holder classes before unclassified durable-anchor classes, within the +128-classes-per-pass budget. When the pending buffer is full, a holder already confirmed as a +collection (met while the local share is at its cap) evicts the oldest entry not confirmed as a +collection. An unclassified holder that meets a full buffer is dropped, and so is a confirmed +collection when the buffer holds only confirmed collections. Either way the next root enumeration +reports it again. + +The index carries a tag-keyed view (`_static_anchor_index_class_tags`) with each holder's runtime +class tag and index position. A root first reported before its class was tagged stores 0 there; +the later edge that delivers the resolved tag upgrades it in place, or a reparented holder could +never re-enter the container-shape fallback. + +`classImplementsContainerOrMap()` walks at most 64 worklist entries per class (duplicate +interfaces consume entries). A walk that ends without proving a non-match - missing metadata, a +failed hierarchy lookup, or pending entries at the 64-pop limit - caches `UNKNOWN_TRUNCATED`, +which keeps the holder selectable; only a complete no-match walk caches `NON_CONTAINER`. The +shape cache uses process-lifetime class tags and survives search restarts. + +Anchor selection skips entries whose frontier lookup fails or whose state is `ABANDONED`; the +index itself is compacted only by local-share compaction and durable-cap eviction, not per +selection. + +The local share is capped at 4096 entries (`LOCAL_ANCHOR_INDEX_CAP`), bounding its scan contribution. +At the cap, `compactLocalAnchors()` scans only the local share but its erasure runs +`eraseAnchorEntries()`'s stable compaction of the full index, O(durable share + local cap) - so an +at-cap compaction touches up to 12288 entries. Yields of 512 or more can run each pass; smaller +yields skip 8 attempts, and a compaction that reclaims less than `LOCAL_ANCHOR_COMPACT_MIN_RECLAIM` +backs the next attempts off entirely, so a pinned-at-cap index pays the full-index compaction at +most once per pass and never on every low-yield pass. When no slot is available, new local holders +are re-reported by the next root enumeration. A low-yield compaction can leave newly dead entries +holding slots during its 8 skipped at-cap attempts. + +The durable share (static fields and JNI globals) is capped at 8192 entries +(`DURABLE_ANCHOR_INDEX_CAP`). The admission that pushes it past the cap FIFO-evicts the oldest +1024 durable entries (`DURABLE_ANCHOR_EVICT_BATCH`) from the index and dedup set, so the per-pass +selection scan stays bounded by the sum of the two caps. Eviction also invalidates the static sweep +memo, forcing one sweep lap, because a re-discovered durable edge is +the only path that re-enlists an evicted anchor: an unchanged durable root kind never upgrades, +an already-admitted entry takes no fresh admission path, and static-only holders never appear in +root enumeration at all. A live evicted anchor can be re-enlisted when its durable edge is traversed; a dead one is never +reported again. +Rotation eligibility is the shared admission contract +(`isSelectableAnchor()`): root-attached durable kinds, or CONTAINER-shaped holders - reparented +containers keep parent_tag set and a stale transient root_kind, so the re-enlist bypasses the +root-kind filter and re-indexes directly. Eviction bumps a resweep-request generation +unconditionally and never touches the sweep cursor; a sweep lap serves exactly the generations +requested before it started — it latches the generation at its start from class 0 and publishes +it only on completing, so a lap in flight when the eviction lands, or a truncated first chunk, +leave the generation unserved until a full lap actually re-traverses the whole class list. A +cursor restart on eviction would reset mid-lap progress under sustained above-cap churn and +starve later classes, so there is none. The forced-lap rate is self-limiting: one eviction batch +requests one generation, laps never run concurrently, and an eviction fires only after 1024 further +admissions past the cap - so forced laps are bounded by the above-cap admission rate, never by the +pass rate. + +Pending first-look turns remain in a capped FIFO after index eviction. Queue items carry the +callback-time class-tag snapshot, so selection does not search the index per queued tag. Overflow +drops newest turns, which can rejoin when a later report finds a slot; served turns use fair rotation. + +Eviction and re-enlistment run only in the replay step described in +[Deferred anchor-index updates](#deferred-anchor-index-updates), never in a JVMTI callback. +A local holder that a durable root later attaches moves to the durable share and stops +counting against the local cap. `restartSearch()` clears both shares and the pending buffer. + +### Deferred anchor-index updates + +Only the targeted anchor-index mutations are deferred: the local-holder note, the durable add, +the re-enlist and the at-risk push. A heap callback does not call them. It reserves one record in +a fixed journal (`AnchorObservationBuffer`) and commits the record when the report is admitted. +The traversal caller replays the records in arrival order after the synchronous JVMTI call +returns. Callbacks skip known no-op LOCAL and AT_RISK actions before reserving a record; the +scope-local indexes suppress duplicate actions across records in the same prefix. + +Each scope reserves LOCAL capacity by shape: unclassified holders use pending slots only; confirmed +containers use index slots, then pending slots or displaceable entries. It reserves AT_RISK records +against remaining global FIFO room and per-class quotas. Excess local holders are re-reported by +root enumeration. + +The journal holds 16,384 records of at most 24 bytes each, so the record array uses at most +384 KiB. Two scope-local indexes suppress duplicate LOCAL and AT_RISK actions. Each index has +32,768 16-bit slots and a 4 KiB occupancy bitmap; together they add 136 KiB. The record and index +arrays use 520 KiB per tracker, before other metadata. Per-scope quota accounting uses a fixed +16,640-byte stack table and allocates nothing in callbacks. A reservation fails when the journal is +full. The callback then aborts the traversal before the +frontier or tag transition that the report would cause. The caller flushes the accepted prefix. +The source traversal obligation stays unserved, so a later pass retries it: + +- **Root enumeration.** The scope flushes right after `IterateOverReachableObjects()` returns. + The rejected root is reported again by the next enumeration. +- **Expansion batch.** `expandFrontier()` flushes after each `FollowReferences()` batch. The + referrer of the rejected edge stays queued. +- **Static-field chunk.** The sweep flushes right after its `FollowReferences()` call. The chunk + cursor stays, the lap is marked truncated, and the replay adds one static-resweep request. +- **Descent group.** The selected-anchor walk flushes after the walk and the at-risk requeue. The + candidate-thread walk flushes when its scope ends. Each group can hold several descents, and + all of them share the journal capacity. The partially walked anchor stays unwalked, and the + thread cursor stays on the thread whose descent overflowed. + +Other allocations in the callbacks remain. This design makes no universal claim about coverage, +overhead or pause time. Resweep pacing is unchanged. It awaits a separate measurement. + +`Profiler::stop()` joins the reference-chain thread before the rest of the teardown. If the join +fails, `stop()` returns an error and the state stays RUNNING, so a later `stop()` retries the join. +`disableEngines()` has already disabled sampling by then. ## Search termination @@ -385,7 +459,9 @@ length. Edge labels are emitted only when all emitted hops have labels. Callbacks queue bounded, exact-source-tag invalidations under a pending spin lock, not a lock-free protocol. Candidate polling and dump snapshots drain them; a dump can drain -while traversal is active. Callbacks do not acquire the resolved-cache lock. +while traversal is active. On overflow, the next drain clears the whole cache and increments +`REFERENCE_CHAIN_EVENTS_DROPPED` for each removed chain, including unaffected cached chains. +Callbacks do not acquire the resolved-cache lock. Dump and stop write `datadog.ReferenceChain` events; the traversal thread does not write JFR events directly. Stop joins that thread and emits pending output before clearing