From 37ca1ad3fcc1afd9df425dde153b62205817faf5 Mon Sep 17 00:00:00 2001 From: agent-job dot-1jbih-a3 Date: Thu, 19 Nov 2026 08:37:43 +0000 Subject: [PATCH] fix(gc): amortize observed-ledger validation across sweep slices Every incremental sweep slice that cleared an observed mark advanced the shared observation epoch, and the barrier-window republish then made ObservedEnvelope::refresh_reclaimed revalidate (and rebuild) the whole ledger. A sweep cost O(slices * ledger) and wedged a long-lived session's main thread at 100% CPU inside incremental_sweep_slice. Count cleared marks in a monotonic RECLAIMED_OBSERVATIONS counter and prune only once the debt since the last validation reaches 1/4 of the ledger. Retained dead identities only widen the gate; already_published and the publication path check exact metadata so a reused address is re-marked. --- .../src/tagged/collection_reads.rs | 11 +- .../collection_reads/observed_envelope.rs | 90 ++++++--- .../tests/observed_sweep_amortization_test.rs | 179 ++++++++++++++++++ crates/neovm-value/src/tagged/gc.rs | 2 +- .../src/tagged/gc/collection_observed.rs | 41 +++- 5 files changed, 282 insertions(+), 41 deletions(-) create mode 100644 crates/neovm-value/src/tagged/collection_reads/tests/observed_sweep_amortization_test.rs diff --git a/crates/neovm-value/src/tagged/collection_reads.rs b/crates/neovm-value/src/tagged/collection_reads.rs index 36422764c0..24ae782e55 100644 --- a/crates/neovm-value/src/tagged/collection_reads.rs +++ b/crates/neovm-value/src/tagged/collection_reads.rs @@ -1142,13 +1142,14 @@ fn publish_observed_owner_in_state(state: &mut State, bits: usize) -> bool { let native_geometry = promoted_geometry.unwrap_or_else(|| native_window_collection_owner(bits)); let changed = state.observed.insert(bits, native_geometry); - let newly = if changed { + // Between prunes the ledger can retain a dead lifetime's identity at + // this reused address; its cleared mark must be published again. + let newly = if changed || !super::gc::collection_observed_metadata(bits) { #[cfg(any(test, feature = "test-support"))] OBSERVED_OWNER_PUBLICATIONS.with(|count| count.set(count.get() + 1)); super::gc::mark_collection_observed(bits) } else { - // Epoch refresh retained this identity only after its exact metadata - // mark was found. Its live publication needs no second radix query. + // The retained identity's exact metadata mark was found above. false }; if refreshed || changed { @@ -1276,6 +1277,10 @@ mod observed_collisions_tests; #[path = "collection_reads/tests/observed_reused_subtype_test.rs"] mod observed_reused_subtype_tests; +#[cfg(all(test, feature = "jit"))] +#[path = "collection_reads/tests/observed_sweep_amortization_test.rs"] +mod observed_sweep_amortization_tests; + /// Carrier park: clear this thread's read-observation scope and recent-read /// cache. `STATE` is World-carried by the swap protocol and is not touched. #[doc(hidden)] diff --git a/crates/neovm-value/src/tagged/collection_reads/observed_envelope.rs b/crates/neovm-value/src/tagged/collection_reads/observed_envelope.rs index 9d868f88af..948d40a3d2 100644 --- a/crates/neovm-value/src/tagged/collection_reads/observed_envelope.rs +++ b/crates/neovm-value/src/tagged/collection_reads/observed_envelope.rs @@ -7,7 +7,7 @@ use super::super::gc::{ BarrierWindow, CompiledObservationGate, collection_observation_epoch, - collection_observed_metadata, + collection_observed_metadata, reclaimed_collection_observation_count, }; use super::super::header::ConsCell; use super::super::value::{TAG_CONS, TAG_MASK, TAG_VECLIKE}; @@ -17,10 +17,15 @@ use std::collections::BTreeSet; use std::mem::size_of; const EMPTY_BOUNDS: (usize, usize) = (usize::MAX, 0); -const MAX_RECLAMATION_RETRIES: usize = 3; +// Prune once the marks cleared since the last validation reach this fraction +// of the ledger. Each O(ledger) scan is then paid for by at least +// len / PRUNE_DEBT_RATIO real clears, and at most that many entries are dead. +const PRUNE_DEBT_RATIO: u64 = 4; pub(super) struct ObservedEnvelope { // Complete lifetime publication ledger, including non-inline subtypes. + // Between prunes it may also hold identities whose marks were cleared; + // membership checks consult exact metadata before trusting an entry. owners: FxHashSet, // Cached native-store eligibility from live publication. A Buffer/Window/ // Frame/Bytecode/String owner is still marked/replay-qualified in `owners`, @@ -30,6 +35,8 @@ pub(super) struct ObservedEnvelope { // slot stores use these bounds independently of observed Cons addresses. slot_addresses: SortedAddressLedger, epoch: Option, + // Global cleared-mark count acquired before the last full validation. + validated_reclaimed: u64, dump: BarrierWindow, full: (usize, usize), below: (usize, usize), @@ -49,6 +56,8 @@ pub(super) struct ObservedEnvelope { single_cons: usize, #[cfg(any(test, feature = "test-support"))] geometry_rebuilds: usize, + #[cfg(any(test, feature = "test-support"))] + validated_identities: usize, } /// Frozen size of the envelope as it was when the thread-local `StateSlot` @@ -91,6 +100,7 @@ impl ObservedEnvelope { addresses: SortedAddressLedger::new(), slot_addresses: SortedAddressLedger::new(), epoch: Some(collection_observation_epoch()), + validated_reclaimed: reclaimed_collection_observation_count(), dump: BarrierWindow::NONE, full: EMPTY_BOUNDS, below: EMPTY_BOUNDS, @@ -102,6 +112,8 @@ impl ObservedEnvelope { single_cons: 0, #[cfg(any(test, feature = "test-support"))] geometry_rebuilds: 0, + #[cfg(any(test, feature = "test-support"))] + validated_identities: 0, } } @@ -119,36 +131,48 @@ impl ObservedEnvelope { self.refresh_reclaimed(dump) } - /// The scanner cannot accept a completed concurrent clearing batch under - /// its old epoch. Ordinary stop-the-world/cooperative batches are stable - /// on their first pass. Continuous other-mutator reclamation is bounded: - /// retain a conservative surviving superset and leave the epoch dirty so - /// the next cold access retries. A false bit only removes a dead identity, - /// never a live rooted dependency whose sticky mark survives collection. + /// Acknowledge a reclamation epoch. Every sweep slice that clears a mark + /// advances the epoch, so validating the whole ledger here would make an + /// incremental sweep cost O(slices * ledger). Instead prune only once the + /// marks cleared since the last validation reach a fixed fraction of the + /// ledger: each scan is charged to that many real clears, and the dead + /// entries it can retain meanwhile are bounded by the same fraction. + /// Retained dead entries are harmless: they only widen the gate, and + /// `already_published` and the publishing caller of `insert` check exact + /// metadata before trusting one. #[cold] #[inline(never)] fn refresh_reclaimed(&mut self, dump: BarrierWindow) -> bool { - let mut changed = false; - for _ in 0..MAX_RECLAMATION_RETRIES { - let before = collection_observation_epoch(); - let old_len = self.owners.len(); - self.owners - .retain(|&bits| collection_observed_metadata(bits)); - // Other heaps share the reclamation epoch. Validate all local - // identities, but keep the ordered buffers and bounds when none of - // them died; an unrelated sweep must not rebuild this ledger. - if self.owners.len() != old_len || self.dump != dump { + let reclaimed = reclaimed_collection_observation_count(); + let debt = reclaimed.wrapping_sub(self.validated_reclaimed); + if debt.saturating_mul(PRUNE_DEBT_RATIO) < self.owners.len() as u64 { + self.epoch = Some(collection_observation_epoch()); + if self.dump != dump { self.rebuild(dump); - changed = true; - } - let after = collection_observation_epoch(); - if before == after { - self.epoch = Some(after); - return changed; + return true; } + return false; + } + // Acquire the count and epoch before scanning: a clear published + // after them is either seen by this scan or counted as later debt. + let epoch = collection_observation_epoch(); + let old_len = self.owners.len(); + #[cfg(any(test, feature = "test-support"))] + { + self.validated_identities += old_len; } - self.epoch = None; - changed + self.owners + .retain(|&bits| collection_observed_metadata(bits)); + self.validated_reclaimed = reclaimed; + self.epoch = Some(epoch); + // Other heaps share the reclamation epoch. Keep the ordered buffers + // and bounds when none of this ledger's identities died; an unrelated + // sweep must not rebuild this ledger. + if self.owners.len() != old_len || self.dump != dump { + self.rebuild(dump); + return true; + } + false } /// Insert even when another mutator already set the process-wide mark. @@ -209,7 +233,9 @@ impl ObservedEnvelope { /// before reuse/resumption; this Acquire check rejects every such change. #[inline] pub(super) fn already_published(&self, bits: usize) -> bool { - self.epoch == Some(collection_observation_epoch()) && self.owners.contains(&bits) + self.epoch == Some(collection_observation_epoch()) + && self.owners.contains(&bits) + && collection_observed_metadata(bits) } /// Compare with an epoch already acquired by the current pointer read. @@ -227,6 +253,16 @@ impl ObservedEnvelope { self.geometry_rebuilds } + #[cfg(test)] + pub(super) fn validated_identities_for_test(&self) -> usize { + self.validated_identities + } + + #[cfg(test)] + pub(super) fn owner_count_for_test(&self) -> usize { + self.owners.len() + } + pub(super) fn ranges(&self) -> [BarrierWindow; 2] { [ BarrierWindow::span(self.below.0, self.below.1), diff --git a/crates/neovm-value/src/tagged/collection_reads/tests/observed_sweep_amortization_test.rs b/crates/neovm-value/src/tagged/collection_reads/tests/observed_sweep_amortization_test.rs new file mode 100644 index 0000000000..7008578e6b --- /dev/null +++ b/crates/neovm-value/src/tagged/collection_reads/tests/observed_sweep_amortization_test.rs @@ -0,0 +1,179 @@ +//! An incremental sweep must not revalidate the whole observed ledger per slice. +//! +//! Every slice that clears an observed mark advances the shared +//! epoch, and each slice republishes the barrier window. Validating every +//! ledger identity on each such slice made one sweep cost O(slices * ledger) +//! and wedged a long-lived session's main thread inside the sweep. Retained +//! dead identities must still never suppress a reused address's new mark. + +use super::*; +use crate::tagged::gc::{TaggedHeap, collection_observed_metadata, set_tagged_heap}; +use rustc_hash::FxHashSet; + +const OWNERS: usize = 64 * 1024; + +struct ObservedMode; + +impl Drop for ObservedMode { + fn drop(&mut self) { + force_compiled_journal_for_test(None); + } +} + +fn ledger_counters() -> (usize, usize, usize) { + with_state(|state| { + let state = state.borrow(); + ( + state.observed.validated_identities_for_test(), + state.observed.geometry_rebuilds_for_test(), + state.observed.owner_count_for_test(), + ) + }) +} + +// One observed dead owner per 64, spread across the young sweep list so that +// every slice clears marks but the total stays below the prune threshold. +#[test] +fn incremental_sweep_slices_amortize_observed_ledger_validation() { + sweep_contract(64, 1); +} + +// Half of the owners die: the amortized prune must still run during the sweep +// and keep the retained dead identities to a bounded fraction of the ledger. +#[test] +fn incremental_sweep_prunes_a_mostly_dead_observed_ledger() { + sweep_contract(2, 4); +} + +fn sweep_contract(garbage_stride: usize, max_rebuilds: usize) { + crate::test_utils::init_test_tracing(); + force_compiled_journal_for_test(Some(CompiledJournalMode::Observed)); + let _mode = ObservedMode; + let mut heap = Box::new(TaggedHeap::new()); + heap.set_gc_threshold(usize::MAX); + set_tagged_heap(&mut heap); + let owners: Vec = (0..OWNERS) + .map(|index| heap.alloc_vector(vec![TaggedValue::make_int(index as i64)])) + .collect(); + let (_, reads) = capture(|| { + for owner in &owners { + owner.as_vector_data().expect("vector")[0]; + } + }); + drop(reads); + let live: Vec = owners + .iter() + .enumerate() + .filter(|(index, _)| index % garbage_stride != 0) + .map(|(_, owner)| *owner) + .collect(); + let garbage: FxHashSet = owners + .iter() + .enumerate() + .filter(|(index, _)| index % garbage_stride == 0) + .map(|(_, owner)| owner.bits()) + .collect(); + let (_, live_reads) = capture(|| live[0].as_vector_data().expect("vector")[0]); + let live_reads = live_reads.expect("rooted live dependency"); + let (validated_before, rebuilds_before, ledger_before) = ledger_counters(); + assert!(ledger_before >= OWNERS); + + // SAFETY: this test exclusively owns the quiescent private heap. + unsafe { heap.begin_collection() }; + for owner in &live { + heap.seed_root(*owner); + } + heap.incremental_drain_all(); + let bytes_before = heap.live_bytes(); + heap.incremental_finish(bytes_before, std::time::Instant::now()); + let started = std::time::Instant::now(); + let mut slices = 0usize; + while !heap.incremental_sweep_slice(1) { + slices += 1; + } + let elapsed = started.elapsed(); + let (validated_after, rebuilds_after, ledger_after) = ledger_counters(); + let validated = validated_after - validated_before; + let rebuilds = rebuilds_after - rebuilds_before; + eprintln!( + "observed sweep: stride={garbage_stride} ledger={ledger_before} slices={slices} validated={validated} \ + rebuilds={rebuilds} ledger_after={ledger_after} elapsed={elapsed:?}" + ); + assert!(slices >= 16, "the sweep must span many slices: {slices}"); + for bits in &garbage { + assert!( + !collection_observed_metadata(*bits), + "garbage was reclaimed" + ); + } + // Every slice above cleared observed marks. Per-slice validation would + // scan about slices * ledger identities; amortized pruning is bounded by + // the ledger plus PRUNE_DEBT_RATIO per cleared mark. + assert!( + validated <= ledger_before + 4 * garbage.len(), + "sweep slices revalidated the whole ledger: {validated} identities over {slices} slices" + ); + assert!( + rebuilds <= max_rebuilds, + "sweep slices rebuilt the geometry {rebuilds} times" + ); + assert!( + ledger_after <= ledger_before, + "the ledger never grows from reclamation" + ); + // Dead identities retained between prunes stay below the debt ratio. + let retained_dead = ledger_after - live.len(); + assert!( + retained_dead * 4 <= ledger_after + 4, + "{retained_dead} dead identities retained in a ledger of {ledger_after}" + ); + assert!( + live_reads.unchanged(), + "the sweep preserves live dependencies" + ); + for owner in &live { + assert!(collection_observed_metadata(owner.bits())); + } + + // Reuse the reclaimed slots. A retained dead identity at the same bits + // must neither count as published nor suppress the new owner's mark. + let mut reused = 0usize; + for index in 0..2 * garbage.len() { + let owner = heap.alloc_vector(vec![TaggedValue::make_int(index as i64)]); + if !garbage.contains(&owner.bits()) { + continue; + } + reused += 1; + assert!(!collection_observed_metadata(owner.bits())); + assert!( + !with_state(|state| state.borrow().observed.already_published(owner.bits())), + "a dead lifetime's ledger entry is not a publication of its reuse" + ); + let (_, reads) = capture(|| owner.as_vector_data().expect("vector")[0]); + let reads = reads.expect("fresh live dependency"); + assert!( + collection_observed_metadata(owner.bits()), + "the reused address must be marked again" + ); + assert!(reads.unchanged()); + assert!(crate::tagged::mutate::set_vector_slot( + owner, + 0, + TaggedValue::make_int(-1) + )); + assert!(!reads.unchanged(), "the reused owner's writes invalidate"); + } + assert!( + reused > 0, + "the allocator reused at least one reclaimed slot" + ); + assert!(crate::tagged::mutate::set_vector_slot( + live[0], + 0, + TaggedValue::make_int(-2) + )); + assert!( + !live_reads.unchanged(), + "the live dependency still invalidates" + ); +} diff --git a/crates/neovm-value/src/tagged/gc.rs b/crates/neovm-value/src/tagged/gc.rs index cf23f2c952..bbe6f743a4 100644 --- a/crates/neovm-value/src/tagged/gc.rs +++ b/crates/neovm-value/src/tagged/gc.rs @@ -2683,7 +2683,7 @@ pub(crate) use collection_observed::collection_observed; pub(crate) use collection_observed::collection_observed_metadata; pub(crate) use collection_observed::{ advance_collection_observation_epoch, clear_noncons_collection_observed_metadata, - mark_collection_observed, + mark_collection_observed, reclaimed_collection_observation_count, }; use collection_observed::{ clear_cons_observed_block, clear_cons_observed_dead, has_noncons_collection_observations, diff --git a/crates/neovm-value/src/tagged/gc/collection_observed.rs b/crates/neovm-value/src/tagged/gc/collection_observed.rs index 3f8a497999..551d95b81b 100644 --- a/crates/neovm-value/src/tagged/gc/collection_observed.rs +++ b/crates/neovm-value/src/tagged/gc/collection_observed.rs @@ -48,15 +48,34 @@ static HAS_NONCONS_MARKS: AtomicBool = AtomicBool::new(false); // collecting mutator invalidates its RECENT cache at this actual-clear edge. static OBSERVATION_EPOCH: AtomicU64 = AtomicU64::new(0); +// Monotonic count of cleared sticky marks, published (Release) after the +// clears and before the epoch advance. A ledger that has validated its +// identities against the count it Acquired can hold at most the difference +// in dead entries, so it can defer its O(ledger) prune until that debt is +// proportional to its size instead of rescanning on every reclamation batch. +static RECLAIMED_OBSERVATIONS: AtomicU64 = AtomicU64::new(0); + #[inline] #[doc(hidden)] pub fn collection_observation_epoch() -> u64 { OBSERVATION_EPOCH.load(Ordering::Acquire) } -/// Complete a reclamation batch after its sticky bits have been cleared. +#[inline] +pub(crate) fn reclaimed_collection_observation_count() -> u64 { + RECLAIMED_OBSERVATIONS.load(Ordering::Acquire) +} + +/// Complete a reclamation batch after one sticky bit has been cleared. #[inline] pub(crate) fn advance_collection_observation_epoch() { + advance_collection_observation_epoch_by(1); +} + +/// Complete a reclamation batch after `cleared` sticky bits have been cleared. +#[inline] +fn advance_collection_observation_epoch_by(cleared: u64) { + RECLAIMED_OBSERVATIONS.fetch_add(cleared, Ordering::Release); let epoch = OBSERVATION_EPOCH .fetch_add(1, Ordering::Release) .wrapping_add(1); @@ -280,7 +299,7 @@ fn clear_cons_observed_dead_slow( let Some(bitmap) = observation_radix::lookup(base) else { return; }; - let mut changed = false; + let mut cleared = 0u64; let cells_per_side_word = u64::BITS as usize / OWNED_CELL_ADDRESS_STRIDE; for (word, observed) in bitmap.cons.iter().enumerate() { let current = observed.load(Ordering::Acquire); @@ -298,11 +317,12 @@ fn clear_cons_observed_dead_slow( spread_live_bits(live & valid) }; if current & !keep != 0 { - changed |= observed.fetch_and(keep, Ordering::Release) & !keep != 0; + let previous = observed.fetch_and(keep, Ordering::Release); + cleared += u64::from((previous & !keep).count_ones()); } } - if changed { - advance_collection_observation_epoch(); + if cleared != 0 { + advance_collection_observation_epoch_by(cleared); } } @@ -330,16 +350,17 @@ pub(super) fn clear_cons_observed_block(base: usize) { #[inline(never)] fn clear_cons_observed_block_slow(base: usize) { if let Some(bitmap) = observation_radix::lookup(base) { - let mut changed = false; + let mut cleared = 0u64; for word in &bitmap.cons { - if word.load(Ordering::Acquire) != 0 { + let current = word.load(Ordering::Acquire); + if current != 0 { // Whole-granule ownership excludes concurrent new marks. word.store(0, Ordering::Release); - changed = true; + cleared += u64::from(current.count_ones()); } } - if changed { - advance_collection_observation_epoch(); + if cleared != 0 { + advance_collection_observation_epoch_by(cleared); } } }