Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions crates/neovm-value/src/tagged/collection_reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)]
Expand Down
90 changes: 63 additions & 27 deletions crates/neovm-value/src/tagged/collection_reads/observed_envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<usize>,
// Cached native-store eligibility from live publication. A Buffer/Window/
// Frame/Bytecode/String owner is still marked/replay-qualified in `owners`,
Expand All @@ -30,6 +35,8 @@ pub(super) struct ObservedEnvelope {
// slot stores use these bounds independently of observed Cons addresses.
slot_addresses: SortedAddressLedger,
epoch: Option<u64>,
// Global cleared-mark count acquired before the last full validation.
validated_reclaimed: u64,
dump: BarrierWindow,
full: (usize, usize),
below: (usize, usize),
Expand All @@ -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`
Expand Down Expand Up @@ -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,
Expand All @@ -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,
}
}

Expand All @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Debt is computed with wrapping subtraction, so a stale validated_reclaimed larger than the current count yields a huge debt and permanently suppresses pruning. The envelope is initialized from reclaimed_collection_observation_count() and only ever updated to the value it just read (line 166), so validated_reclaimed should never exceed reclaimed. But any future reordering that reads the count before the clears it will credit, or any reset of the global counter, makes the ledger stop pruning entirely and grow without bound. Use saturating subtraction to make the debt floor at zero instead.

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.
Expand Down Expand Up @@ -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.
Expand All @@ -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),
Expand Down
Original file line number Diff line number Diff line change
@@ -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<TaggedValue> = (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<TaggedValue> = owners
.iter()
.enumerate()
.filter(|(index, _)| index % garbage_stride != 0)
.map(|(_, owner)| *owner)
.collect();
let garbage: FxHashSet<usize> = 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"
);
}
2 changes: 1 addition & 1 deletion crates/neovm-value/src/tagged/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading