diff --git a/core/crates/layerfs-storage/src/encoding/decode.rs b/core/crates/layerfs-storage/src/encoding/decode.rs index e0d1ca07b9..d6ad45610d 100644 --- a/core/crates/layerfs-storage/src/encoding/decode.rs +++ b/core/crates/layerfs-storage/src/encoding/decode.rs @@ -55,8 +55,22 @@ impl GroupCache { Some(&entry.body) } - /// Retains authenticated decoded input within the same byte allowance. - /// Duplicate immutable input is idempotent; changed or oversized input fails. + /// Borrows retained input without recording recency: for a guess that + /// must leave the cache as it found it (`read/hints.rs` `chain_ahead`). + pub(crate) fn peek(&self, pack_id: i64, group_number: usize) -> Option<&[u8]> { + self.bodies + .get(&(pack_id, group_number)) + .map(|entry| entry.body.as_slice()) + } + + /// Retains decoded input within the same byte allowance, evicting the least + /// recently used bodies. What the input is depends on the owner: a reader's + /// or Save's cache holds bodies its decoding authenticated, while the + /// private per-call cache of `read/hints.rs` `chain_ahead` (filled through + /// `delta::read::cached_base`) holds unauthenticated bytes for guesses that + /// nothing trusts; no other owner reads it and it is dropped when that call + /// returns. Duplicate immutable input is idempotent; changed or oversized + /// input fails. pub fn insert( &mut self, pack_id: i64, diff --git a/core/crates/layerfs-storage/src/encoding/delta/branch.rs b/core/crates/layerfs-storage/src/encoding/delta/branch.rs index fd9e16d2d3..5f6dfbc7a8 100644 --- a/core/crates/layerfs-storage/src/encoding/delta/branch.rs +++ b/core/crates/layerfs-storage/src/encoding/delta/branch.rs @@ -12,8 +12,11 @@ //! fit the budgets in the same way. Exactly one trial runs, with the pooled //! producer and its match budget; the program is kept only when it is shorter //! than the whole record, and for a directory page only when it saves at least a -//! quarter of it (`worth`). Every refusal stores the page whole, which -//! is what every Store before this form holds. +//! quarter of it (`worth`). A program against a re-based root is kept only when +//! it is at most half the whole record as well (`select::rebased_delta_kept`, +//! #758), so a page that drifts from its root starts a new chain instead of +//! anchoring every read of it to a growing program. Every refusal stores the +//! page whole, which is what every Store before this form holds. use layerfs_content::{ObjectId, ObjectRole}; @@ -45,6 +48,10 @@ pub struct BranchCounters { pub work_exceeded: u64, /// Predecessors replaced by the whole branch at the root of their chain (#89). pub rebased: u64, + /// Programs against a re-based root that `worth` keeps but that are longer + /// than half the whole record, stored whole instead (#758): only the + /// decisions the rule changed, as `DeltaCounters::rebased_full`. + pub rebased_full: u64, /// Branches stored, by chain depth (whole is 0). pub depths: super::select::DepthHistogram, } @@ -60,6 +67,7 @@ impl BranchCounters { (&mut self.depth_capped, other.depth_capped), (&mut self.work_exceeded, other.work_exceeded), (&mut self.rebased, other.rebased), + (&mut self.rebased_full, other.rebased_full), ] { *total = total.saturating_add(value); } @@ -115,6 +123,7 @@ fn trial( } let capacities = input.capacities; let mut base_id = base_id; + let mut rebased = false; let (mut base, mut chain) = acquire(input, location)?; let capped = chain.depth >= capacities.metadata_delta_max_depth; if capped { @@ -133,6 +142,7 @@ fn trial( return Err(crate::error::StorageError::Integrity("branch chain root")); } base_id = root.object_id; + rebased = true; let branch = counters(input.counters, role); branch.rebased = branch.rebased.saturating_add(1); } else if capped { @@ -154,6 +164,11 @@ fn trial( if !worth(role, program.len(), full.record.len()) { return Ok(None); } + if rebased && !select::rebased_delta_kept(program.len(), full.record.len()) { + let branch = counters(input.counters, role); + branch.rebased_full = branch.rebased_full.saturating_add(1); + return Ok(None); + } let branch = counters(input.counters, role); branch.delta_branches = branch.delta_branches.saturating_add(1); note_depth(&mut branch.depths, chain.depth.saturating_add(1)); diff --git a/core/crates/layerfs-storage/src/encoding/delta/read.rs b/core/crates/layerfs-storage/src/encoding/delta/read.rs index 071b31ec3e..101f1c8c79 100644 --- a/core/crates/layerfs-storage/src/encoding/delta/read.rs +++ b/core/crates/layerfs-storage/src/encoding/delta/read.rs @@ -94,6 +94,8 @@ pub struct Resolver<'a> { workspace: &'a mut DecompressionWorkspace, counters: &'a mut ChainCounters, packs_read: u64, + /// Identities the current resolution walked, for the hint fallback. + walked: Vec, } impl<'a> Resolver<'a> { @@ -116,6 +118,7 @@ impl<'a> Resolver<'a> { workspace, counters, packs_read: 0, + walked: Vec::new(), } } @@ -164,13 +167,38 @@ impl<'a> Resolver<'a> { self.resolve_charged(root, false) } + /// One resolution; when it fails in a way a stale delta-chain hint can + /// cause and a hinted locator was in use, it is rebuilt once from + /// authoritative locators (#758). A second failure stands. fn resolve_charged( &mut self, root: ObjectLocation, charge_self: bool, + ) -> StorageResult<(Vec, ObjectId)> { + match self.resolve_once(root, charge_self) { + Err(error) if crate::read::hint_failure(&error) => { + let walked = std::mem::take(&mut self.walked); + if !self.connection.drop_hints(&walked)? { + return Err(error); + } + let root = self + .connection + .location(root.object_id, self.ceiling)? + .ok_or(StorageError::ObjectMissing(root.object_id))?; + self.resolve_once(root, charge_self) + } + other => other, + } + } + + fn resolve_once( + &mut self, + root: ObjectLocation, + charge_self: bool, ) -> StorageResult<(Vec, ObjectId)> { *self.counters = ChainCounters::default(); self.packs_read = 0; + self.walked = vec![root.object_id]; if root.pack_id > self.ceiling { return Err(StorageError::VisibilityCeiling { pack_id: root.pack_id, @@ -248,6 +276,7 @@ impl<'a> Resolver<'a> { return Err(StorageError::Integrity("dependency cycle")); } chain.push(current); + self.walked.push(current.object_id); let Some(base) = self.base_of(¤t)? else { break; }; @@ -508,7 +537,7 @@ pub fn stored_base( view, bytes: selected, } = selected; - match header.lane { + let base = match header.lane { PackLane::Ordinary => { let body: &[u8] = match view.codec { crate::pack::layout::GroupCodec::Raw => selected, @@ -530,42 +559,82 @@ pub fn stored_base( if body.len() != view.decoded_length { return Err(StorageError::Integrity("group body length")); } - let record = crate::encoding::decode::framed_record(body, location.record_number)?; - crate::encoding::delta::record::stored_base( - PackLane::Ordinary, - record, - location.canonical_length, - location.role, - ) + record_base(PackLane::Ordinary, body, location) } - PackLane::WholeFile => { - let record = crate::encoding::decode::framed_record(selected, location.record_number)?; - crate::encoding::delta::record::stored_base( - PackLane::WholeFile, - record, - location.canonical_length, - location.role, - ) - } - PackLane::Chunk => { - let record = crate::encoding::decode::framed_record(selected, location.record_number)?; - crate::encoding::delta::record::stored_base( - PackLane::Chunk, - record, - location.canonical_length, - location.role, - ) - } - PackLane::Singleton => { - let record = crate::encoding::decode::framed_record(selected, 0)?; - crate::encoding::delta::record::stored_base( - PackLane::Singleton, - record, - location.canonical_length, - location.role, - ) + lane => record_base(lane, selected, location), + }?; + connection.bind_base(location, base)?; + Ok(base) +} + +/// The base the record at `location` of `body` names: an ordinary lane's +/// decoded group body, or another lane's encoded group. +fn record_base( + lane: PackLane, + body: &[u8], + location: &ObjectLocation, +) -> StorageResult> { + let at = match lane { + PackLane::Singleton => 0, + _ => location.record_number, + }; + let record = crate::encoding::decode::framed_record(body, at)?; + crate::encoding::delta::record::stored_base( + lane, + record, + location.canonical_length, + location.role, + ) +} + +/// The base the record at `location` names, read only from bytes `packs` +/// and `groups` already hold, leaving both as they were (#758): a guess +/// for a locate, never trusted, so any miss or malformed byte is `None`. +/// The record is not authenticated and `location` may be wrong. A group +/// neither `groups` nor the caller's own `decoded` cache holds is +/// decompressed, counted in `decodes` and kept in `decoded` (when it fits +/// that cache's byte bound), so the caller decodes it again only after +/// `decoded` evicted it or when it was too large to keep. +pub(crate) fn cached_base( + packs: &crate::encoding::PackCache, + groups: &GroupCache, + decoded: &mut GroupCache, + workspace: &mut DecompressionWorkspace, + decodes: &mut u64, + location: &ObjectLocation, +) -> Option { + let selected = packs.peek_group(location.pack_id, location.group_number)?; + let fresh; + let body: &[u8] = match (selected.header.lane, selected.view.codec) { + (PackLane::Ordinary, crate::pack::layout::GroupCodec::Zstandard) => { + let key = (location.pack_id, location.group_number); + match groups.peek(key.0, key.1) { + Some(cached) => cached, + None if decoded.peek(key.0, key.1).is_some() => decoded.peek(key.0, key.1)?, + None => { + *decodes = decodes.saturating_add(1); + let body = workspace + .decompress_group(selected.bytes, selected.view.decoded_length) + .ok()?; + // A body over the bound is used once and not kept. + if body.len() > crate::policy::DECODED_GROUP_CACHE_BYTES { + fresh = body; + &fresh + } else { + decoded.insert(key.0, key.1, body).ok()?; + decoded.peek(key.0, key.1)? + } + } + } } + _ => selected.bytes, + }; + if selected.header.lane == PackLane::Ordinary && body.len() != selected.view.decoded_length { + return None; } + record_base(selected.header.lane, body, location) + .ok() + .flatten() } /// Adds one resolved chain's work to an operation's totals. @@ -593,6 +662,7 @@ fn group_of<'b>( connection: &dyn Source, location: &ObjectLocation, ) -> StorageResult<(crate::encoding::GroupSlice<'b>, bool)> { + connection.prefetch_chain(location, packs)?; let (fetched, _) = packs.acquire_groups(connection, location.pack_id, &[location.group_number])?; let selected = packs diff --git a/core/crates/layerfs-storage/src/encoding/delta/select.rs b/core/crates/layerfs-storage/src/encoding/delta/select.rs index c293559691..91a5fdf4c1 100644 --- a/core/crates/layerfs-storage/src/encoding/delta/select.rs +++ b/core/crates/layerfs-storage/src/encoding/delta/select.rs @@ -17,6 +17,14 @@ //! acquired and authenticated. A codec, allocation or read failure is returned as //! a failure and never becomes an alternative representation. //! +//! A re-based trial keeps its PREFIX only when the record is at most half the +//! object's FULL record ([`rebased_delta_kept`], #758): the root delta is the one +//! record of a chain whose base can be any number of versions older than its +//! target, so without a limit it grows as the object drifts, and every read of +//! the chain pays it. Past half, the FULL repays its extra stored bytes within +//! one read and starts a new chain. A trial against the named candidate, even a +//! FULL one, is one version's change and is not limited. +//! //! A chunk offered a base that its last trials in this Save all lost against, //! or won by less than 1/8 of the FULL record, is stored FULL without a trial, //! with retries at doubling gaps ([`LosingBases`]): an incompressible append @@ -69,6 +77,13 @@ pub struct DeltaCounters { /// reached the depth cap or would exceed a work budget with the new object on /// it (#89). The one trial runs against the root. pub rebased: u64, + /// Re-based trials the half-FULL rule turned into FULL ([`rebased_delta_kept`]): + /// the PREFIX record was shorter than the FULL record, so it would have been + /// stored, but longer than half of it. A re-based PREFIX that is not shorter + /// loses the comparison anyway and is not counted here. Each firing also + /// counts in `full_losses`. `BranchCounters::rebased_full` counts the same + /// for program pages. + pub rebased_full: u64, /// Chunk candidates not tried because this Save's trials against the same /// base kept losing ([`LosingBases`]); each stored FULL without a trial. pub losing_skipped: u64, @@ -104,6 +119,7 @@ impl DeltaCounters { (&mut self.work_exceeded, other.work_exceeded), (&mut self.depth_capped, other.depth_capped), (&mut self.rebased, other.rebased), + (&mut self.rebased_full, other.rebased_full), (&mut self.losing_skipped, other.losing_skipped), ] { *total = total.saturating_add(value); @@ -176,6 +192,11 @@ impl DepthCache { self.costs.is_empty() } + /// True when `id`'s cost is cached. + pub fn knows(&self, id: ObjectId) -> bool { + self.costs.contains_key(&id) + } + /// Depth of `id` in its dependency chain, or `None` when it is not stored. pub fn depth_of( &mut self, @@ -319,6 +340,25 @@ const LOSING_BASE_MAX_GAP_LOG2: u32 = 16; /// Live entries of the per-save losing-base memo. const LOSING_BASE_ENTRIES: usize = 4_096; +/// A re-based delta is kept only when its record is at most 1/`REBASED_DELTA_DIVISOR` +/// of the object's FULL record (#758). +/// +/// The bound it keeps: the anchor of a re-based chain, its root plus the one delta +/// against it, costs a read at most the root's FULL plus half the target's FULL +/// (1.5 FULL records for equal sizes), instead of up to two. Storing the FULL +/// costs `full - delta` more bytes once and saves about `delta` on every later +/// read through that record, so it repays itself within one read exactly when +/// `delta > full / 2`. The fraction is fixed: it never depends on sizes, counts, +/// history or engine. +pub const REBASED_DELTA_DIVISOR: usize = 2; + +/// True when a delta record of `delta` bytes against a re-based chain root is +/// kept over the FULL record of `full` bytes ([`REBASED_DELTA_DIVISOR`]). Both are +/// stored record lengths, the quantities the selection's own comparison uses. +pub fn rebased_delta_kept(delta: usize, full: usize) -> bool { + delta.saturating_mul(REBASED_DELTA_DIVISOR) <= full +} + /// Per-save memo of chunk delta bases whose trials keep losing. /// /// A content hint names the same base for many chunks when nothing in the @@ -590,7 +630,7 @@ pub fn select( // re-basing may replace (`LosingBases`). let offered = (role == ObjectRole::Chunk).then_some(base_id); let base_cost = chain_cost(input, base_id)?; - let Some((base_id, base_cost)) = + let Some((base_id, base_cost, rebased)) = trial_base(input, base_id, base_cost, canonical.len() as u64, depth_cap)? else { return refused_by_budget(input, id, role, raw, prehashed, full); @@ -636,14 +676,24 @@ pub fn select( ); SaveProfile::charge(&mut input.profile.delta_ns, started); let prefix = prefix?; - let won = prefix.record.len() < full.record.len(); + // A re-based PREFIX over half the FULL record stores FULL (#758): it would + // anchor the chain, and every read of it, to a delta that grows with drift. + // Only a PREFIX that would otherwise win counts as the rule's firing. + let shorter = prefix.record.len() < full.record.len(); + let over_root_fraction = + shorter && rebased && !rebased_delta_kept(prefix.record.len(), full.record.len()); + if over_root_fraction { + input.counters.rebased_full = input.counters.rebased_full.saturating_add(1); + } + let won = shorter && !over_root_fraction; if let Some(offered) = offered { // A win that saves less than 1/LOSING_BASE_MIN_SAVING of the FULL - // record is still stored, but counts as a loss for the memo. + // record is still stored, but counts as a loss for the memo; so does a + // PREFIX not stored. let saving = full.record.len().saturating_sub(prefix.record.len()); input.losing.note( offered, - saving * LOSING_BASE_MIN_SAVING >= full.record.len(), + won && saving * LOSING_BASE_MIN_SAVING >= full.record.len(), ); } if won { @@ -719,11 +769,12 @@ fn chain_cost(input: &mut SelectInput<'_>, id: ObjectId) -> StorageResult StorageResult> { +) -> StorageResult> { let capped = cost.depth >= depth_cap; if capped { input.counters.depth_capped = input.counters.depth_capped.saturating_add(1); @@ -742,7 +793,7 @@ fn trial_base( let fits = cost.canonical.saturating_add(target) <= input.capacities.chain_canonical_limit && cost.encoded.saturating_add(target) <= input.capacities.chain_encoded_limit; if cost.depth == 0 || (fits && !capped) { - return Ok(Some((id, cost))); + return Ok(Some((id, cost, false))); } let started = Instant::now(); let root = chain_root(input.connection, input.packs, input.decode, id); @@ -753,7 +804,7 @@ fn trial_base( return Ok(None); } input.counters.rebased = input.counters.rebased.saturating_add(1); - Ok(Some((root, root_cost))) + Ok(Some((root, root_cost, true))) } /// Location of the FULL record at the bottom of `id`'s stored chain. diff --git a/core/crates/layerfs-storage/src/encoding/pack_cache.rs b/core/crates/layerfs-storage/src/encoding/pack_cache.rs index b6924b8dfc..b0bcd6da16 100644 --- a/core/crates/layerfs-storage/src/encoding/pack_cache.rs +++ b/core/crates/layerfs-storage/src/encoding/pack_cache.rs @@ -202,6 +202,37 @@ impl PackCache { })) } } + /// A held group's bytes for a guess only (#758, `read/hints.rs` + /// `chain_ahead`): no descriptor check, no recency, no counter, so the + /// cache and the handle are left as they were. Never a source of bytes a + /// read returns: [`Self::group`] serves those. + pub(crate) fn peek_group(&self, id: i64, number: usize) -> Option> { + let entry = self + .entries + .get(&(id, None)) + .or_else(|| self.entries.get(&(id, Some(number))))?; + if let Some((header, view)) = entry.unit { + return Some(super::GroupSlice { + header, + view, + bytes: &entry.body, + }); + } + let header = crate::pack::layout::parse_header(&entry.body).ok()?; + let view = crate::pack::layout::group_view(&entry.body, header, number).ok()?; + Some(super::GroupSlice { + header, + view, + bytes: entry.body.get(view.start..view.end)?, + }) + } + /// The entry that holds `id`'s group `number` (its whole body or that + /// group's unit) and its retained bytes, without touching recency. + pub(crate) fn held(&self, id: i64, number: usize) -> Option<((i64, Option), usize)> { + [(id, None), (id, Some(number))] + .into_iter() + .find_map(|key| self.entries.get(&key).map(|entry| (key, entry.body.len()))) + } // A whole body's immutable directory is shared only within this cohort. // Descriptor eligibility and recency still apply separately to every hit. fn whole_cohort( @@ -282,6 +313,19 @@ impl PackCache { if whole_for_reuse && !matches!(&acquired, super::PackAcquisition::Whole { .. }) { return Err(StorageError::Integrity("whole reuse selection reply")); } + self.admit_groups(source, id, &wanted, &missing, acquired) + } + /// Admits one acquisition of pack `id`'s `missing` groups, which leaves + /// every `wanted` group cached: from [`Self::acquire_groups`], or from a + /// group read that already holds the bytes (#758). + pub(crate) fn admit_groups( + &mut self, + source: &dyn crate::source::Source, + id: i64, + wanted: &BTreeSet, + missing: &[usize], + acquired: super::PackAcquisition, + ) -> StorageResult<(bool, usize)> { let before = self.work; let bytes = match acquired { super::PackAcquisition::Whole { info, body } => { @@ -298,7 +342,7 @@ impl PackCache { return Err(StorageError::Integrity("cached whole domain")); } source.note_pack_directory_validation(wanted.len(), header.group_count); - crate::pack::layout::validate_group_demand(&body, header, &wanted)?; + crate::pack::layout::validate_group_demand(&body, header, wanted)?; let bytes = body.len(); let keys: Vec<_> = self .entries @@ -371,10 +415,10 @@ impl PackCache { self.work.evictions - before.evictions, self.work.evicted_bytes - before.evicted_bytes, ); - if self.whole_cohort(source, id, &wanted)? { + if self.whole_cohort(source, id, wanted)? { return Ok((true, bytes)); } - for group in wanted { + for &group in wanted { if self.group(source, id, group)?.is_none() { return Err(StorageError::Integrity("cohort evicted required group")); } diff --git a/core/crates/layerfs-storage/src/encoding/pool/branch.rs b/core/crates/layerfs-storage/src/encoding/pool/branch.rs index 8847402689..329fad3bc4 100644 --- a/core/crates/layerfs-storage/src/encoding/pool/branch.rs +++ b/core/crates/layerfs-storage/src/encoding/pool/branch.rs @@ -17,7 +17,8 @@ //! the caller's caches, bounded by the metadata depth cap and charged record //! bytes against the metadata chain budgets, then decoded base first, every //! element authenticated against its own locator. Every element has the root's -//! role. +//! role: an authoritative locator's, or, for an element a chain hint located +//! (#758), the role its authenticated page header declares. use layerfs_content::{ObjectId, ObjectRole}; @@ -121,7 +122,37 @@ pub struct BranchChain { pub encoded: u64, } +/// The program role a canonical page's own header declares: the role of a +/// chain element whose locator came from a chain hint, which carries no role +/// (#758), checked once its bytes are authenticated. +fn declared_role(canonical: &[u8]) -> Option { + use layerfs_content::filesystem::sorted::format as sorted; + let value = layerfs_content::object::decode_bytes_object(canonical).ok()?; + let (magic, role) = (value.get(..8)?, *value.get(10)?); + if magic == sorted::DIRECTORY_MAGIC { + return match role { + sorted::DIRECTORY_LEAF_ROLE => Some(ObjectRole::DirectoryLeaf), + sorted::DIRECTORY_BRANCH_ROLE => Some(ObjectRole::DirectoryBranch), + _ => None, + }; + } + if magic == sorted::INODE_MAGIC { + return (role == sorted::INODE_BRANCH_ROLE).then_some(ObjectRole::InodeBranch); + } + match layerfs_content::file::mapping::decode_node(canonical).ok()? { + layerfs_content::file::mapping::ExtentNode::Leaf { .. } => Some(ObjectRole::ExtentLeaf), + layerfs_content::file::mapping::ExtentNode::Branch { .. } => Some(ObjectRole::ExtentBranch), + } +} + impl PoolReader { + /// Whether the last program-page reconstruction failed at an element + /// whose locator came from a chain hint, or in a walk such an element + /// may have redirected (#758): only such a failure may be a stale hint's. + pub(crate) fn hint_blamed(&self) -> bool { + self.hint_blamed + } + /// The authenticated canonical page of one stored program page. pub(crate) fn branch_canonical_with_caches( &mut self, @@ -132,8 +163,17 @@ impl PoolReader { root: ObjectLocation, caches: Option>, ) -> StorageResult<(Vec, BranchChain)> { - let result = - self.reconstruct_branch(connection, capacities, ceiling, workspace, root, caches); + let mut suspect = false; + let result = self.reconstruct_branch( + connection, + capacities, + ceiling, + workspace, + root, + caches, + &mut suspect, + ); + self.hint_blamed = result.is_err() && suspect; let counters = &mut self.counters; let inode = root.role == ObjectRole::InodeBranch; let (requests, edges) = match inode { @@ -156,6 +196,15 @@ impl PoolReader { result } + /// `suspect` is left true when a failure is attributable to an element + /// a chain hint located, or to an element reached through one: every + /// element below the first hinted one was named by an unauthenticated + /// record (the hinted element's own, or one below it), so a failure while + /// reading, binding or decoding any of them, or of a walk past the depth + /// cap, may be the hint's. A failure above the first hinted element is + /// never a hint's, except the chain work check: its totals include the + /// elements below, so it is suspect whenever any element was hinted. + #[allow(clippy::too_many_arguments)] fn reconstruct_branch( &mut self, connection: &dyn Source, @@ -164,17 +213,23 @@ impl PoolReader { workspace: &mut DecompressionWorkspace, root: ObjectLocation, mut caches: Option>, + suspect: &mut bool, ) -> StorageResult<(Vec, BranchChain)> { if !is_program_role(root.role) { return Err(StorageError::Integrity("branch record role")); } let cap = usize::from(capacities.metadata_delta_max_depth); let mut chain: Vec<(ObjectLocation, Vec)> = Vec::with_capacity(cap + 1); + // Whether each element of `chain` was located from a chain hint + // (#758); the root never is. + let mut hinted: Vec = Vec::with_capacity(cap + 1); + let mut current_hinted = false; let mut current = root; // The element the walk stopped at because this reader already rebuilt // and authenticated it: the chain below it is not read again. let mut known: Option<(ObjectId, Known)> = None; loop { + *suspect = current_hinted || hinted.contains(&true); if current.pack_id > ceiling { return Err(StorageError::VisibilityCeiling { pack_id: current.pack_id, @@ -194,6 +249,7 @@ impl PoolReader { if let Some(held) = held { // The depth a full walk would have reached, under the same cap. if chain.len() + usize::from(held.depth) > cap { + *suspect = hinted.contains(&true); return Err(StorageError::Integrity("branch chain depth")); } known = Some((current.object_id, held)); @@ -201,11 +257,18 @@ impl PoolReader { } let record = self.record(connection, workspace, ¤t, caches.as_mut())?; let base = stored_base(&record)?; + // Only a Save's check of its bases binds a program page's chain + // member here (#758, `Fetch::bind`); every element below is still + // hashed to the id its child's record names. + connection.bind_base(¤t, base)?; chain.push((current, record)); + hinted.push(current_hinted); let Some(base) = base else { break; }; if chain.len() > cap { + // Any hinted element's record may have named a wrong base. + *suspect = hinted.contains(&true); return Err(StorageError::Integrity("branch chain depth")); } // A base a stored record names is re-located, never answered by a @@ -226,6 +289,9 @@ impl PoolReader { { return Err(StorageError::Integrity("branch chain chronology")); } + // A hinted locator carries the root's role, not a checked one: + // its element's role is checked from its bytes below. + current_hinted = connection.hinted(location.object_id); current = location; } // A known element brings the work its own chain charged, so the @@ -242,7 +308,16 @@ impl PoolReader { let mut highest_pack = known.as_ref().map_or(0, |(_, held)| held.highest_pack); let mut page: Option<(ObjectId, Vec)> = known.map(|(id, held)| (id, held.bytes)); let mut applies = 0_u64; - for (position, (location, record)) in chain.iter().rev().enumerate() { + // The first hinted element, root first: it and every element below + // it were located through a record not yet authenticated. + let first_hinted = hinted.iter().position(|from_hint| *from_hint); + for (position, ((location, record), from_hint)) in + chain.iter().zip(&hinted).rev().enumerate() + { + // Elements below this one are authenticated: a failure from here + // to the next element is this one's, and a hint's when this one + // is at or below the first hinted element. + *suspect = first_hinted.is_some_and(|first| chain.len() - 1 - position >= first); work.canonical = work .canonical .saturating_add(location.canonical_length as u64); @@ -250,6 +325,11 @@ impl PoolReader { if work.canonical > capacities.metadata_chain_canonical_limit || work.encoded > capacities.metadata_chain_encoded_limit { + // The totals include every element below this one, so a + // hinted element's record or canonical length may be what + // crossed the limit, even at an authoritative element above + // it (fix 3b). + *suspect = first_hinted.is_some(); return Err(StorageError::Integrity("branch chain work")); } let decoded = match parse(record)? { @@ -279,6 +359,9 @@ impl PoolReader { if ObjectId::for_bytes(&decoded) != location.object_id { return Err(StorageError::Integrity("branch canonical identity")); } + if *from_hint && declared_role(&decoded) != Some(root.role) { + return Err(StorageError::Integrity("branch chain role")); + } highest_pack = highest_pack.max(location.pack_id); if let Some(memo) = self.memo.as_mut() { // Authenticated just above, with the chain facts up to here. diff --git a/core/crates/layerfs-storage/src/encoding/pool/read.rs b/core/crates/layerfs-storage/src/encoding/pool/read.rs index b8be525fb3..c08ee68503 100644 --- a/core/crates/layerfs-storage/src/encoding/pool/read.rs +++ b/core/crates/layerfs-storage/src/encoding/pool/read.rs @@ -50,6 +50,9 @@ pub struct PoolReader { /// asked for them to be kept ([`Self::with_chain_memo`]). pub(super) memo: Option, pub(super) counters: PoolReadCounters, + /// The last program-page reconstruction failed at an element a chain + /// hint located (#758, [`Self::hint_blamed`]). + pub(super) hint_blamed: bool, } /// One pooled chain rebuilt to physical bodies, root last, with the work it diff --git a/core/crates/layerfs-storage/src/port/mod.rs b/core/crates/layerfs-storage/src/port/mod.rs index 619a44d596..5d6e1f2ba1 100644 --- a/core/crates/layerfs-storage/src/port/mod.rs +++ b/core/crates/layerfs-storage/src/port/mod.rs @@ -7,7 +7,8 @@ mod read_scoped; mod read_selection; pub use pack::ObjectKey; pub use persistence::{ - PackPersistence, PersistenceError, Publication, Published, PublishedPack, Reserve, Reserved, + GroupRead, GroupReadAnswer, PackPersistence, PersistenceError, Publication, Published, + PublishedPack, Reserve, Reserved, }; pub use read_pack::PersistedPack; @@ -17,3 +18,4 @@ pub use read_selection::{ }; pub use read_scoped::{AcquiredPackRead, AcquiredPackUnits}; +pub(crate) use read_selection::check_ranges; diff --git a/core/crates/layerfs-storage/src/port/persistence.rs b/core/crates/layerfs-storage/src/port/persistence.rs index febce663c1..e79ab1aee4 100644 --- a/core/crates/layerfs-storage/src/port/persistence.rs +++ b/core/crates/layerfs-storage/src/port/persistence.rs @@ -1,8 +1,8 @@ //! Bounded atomic physical persistence; one transaction attempt per operation. -use super::{ObjectKey, PackReadPlan, PersistedPack, PersistedPackRead}; +use super::{ObjectKey, PackRange, PackReadPlan, PersistedPack, PersistedPackRead}; use crate::location::{ - InodeValueRow, LocatedObject, ObjectLocation, PackDomain, PackInfo, SignatureRow, + InodeValueRow, LocatedChains, LocatedObject, ObjectLocation, PackDomain, PackInfo, SignatureRow, }; use crate::policy::StoragePolicy; use layerfs_content::ObjectId; @@ -58,6 +58,26 @@ impl PublishedPack { } } +/// Whole encoded groups of one pack (#758): sorted, disjoint ranges that each +/// cover complete groups, or no ranges for the whole pack. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct GroupRead { + /// The pack, as a locate or chain locate named it. + pub pack: PackInfo, + /// Requested extents; empty asks for the whole pack. + pub ranges: Vec, +} + +/// One [`GroupRead`]'s bytes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GroupReadAnswer { + /// The complete pack, length and SHA-256 checked. + Whole(PersistedPack), + /// The bytes of each requested range, in request order. Unauthenticated + /// until the objects rebuilt from them pass their id hash. + Ranges(Vec>), +} + /// One atomic batch, closed under direct references before this call. #[derive(Clone, Debug, Default)] pub struct Publication { @@ -116,6 +136,52 @@ pub trait PackPersistence: Send + Sync { ids: &[ObjectId], out: &mut Vec, ) -> Result<(), PersistenceError>; + /// Locates `roots` like [`Self::locate`] and, for each located delta root + /// whose chain the provider records, returns its members and, where it + /// has them, the directories of the packs rows and members name, in one + /// provider call. The reader calls it for every locate wave. Default: + /// `locate` and no chains. + fn locate_chains( + &self, + roots: &[ObjectId], + rows: &mut Vec, + chains: &mut LocatedChains, + ) -> Result<(), PersistenceError> { + chains.chains.clear(); + chains.directories.clear(); + self.locate(roots, rows) + } + /// Whole encoded groups of several packs, one answer per read in request + /// order, at most DEPENDENCY_PACK_CACHE_BYTES requested in all. `Ranges` + /// answers are unauthenticated physical units, as `read_scoped_pack` + /// returns. Default: `read_packs` on the packs, answered `Whole`, one + /// call per cache bound of whole packs. + fn read_groups( + &self, + reads: &[GroupRead], + out: &mut Vec, + ) -> Result<(), PersistenceError> { + out.clear(); + let mut rest = reads; + while !rest.is_empty() { + // `read_packs` takes whole packs within one cache bound per call. + let mut bytes = 0; + let take = rest + .iter() + .take_while(|read| { + bytes += read.pack.length; + bytes <= crate::policy::DEPENDENCY_PACK_CACHE_BYTES + }) + .count() + .max(1); + let ids: Vec = rest[..take].iter().map(|read| read.pack.pack_id).collect(); + let mut packs = Vec::new(); + self.read_packs(&ids, &mut packs)?; + out.extend(packs.into_iter().map(GroupReadAnswer::Whole)); + rest = &rest[take..]; + } + Ok(()) + } /// Reads complete packs totalling at most DEPENDENCY_PACK_CACHE_BYTES, /// or one separately bounded singleton up to SINGLETON_PACK_LIMIT. /// Results use `PersistedPack::authenticate`: length/digest verified once, @@ -162,6 +228,14 @@ pub trait PackPersistence: Send + Sync { fn whole_pack_bytes(&self) -> usize { super::PACK_READ_PREFIX_BYTES } + /// Whether the reader also fetches the chains it knows from its own + /// cache in one `read_groups` wave (#758): the bases this handle + /// published, followed through its authoritative locators. A provider + /// whose every read is a network round trip returns true; the default + /// reads each level when the walk reaches it. + fn batched_chain_reads(&self) -> bool { + false + } /// Canonical bytes one preparation wave holds and one publication carries, /// and the sealed bytes it publishes. The default is the shared /// transaction bound, 4 MiB less one byte; a provider whose every diff --git a/core/crates/layerfs-storage/src/port/read_selection.rs b/core/crates/layerfs-storage/src/port/read_selection.rs index afff979beb..45076efc5c 100644 --- a/core/crates/layerfs-storage/src/port/read_selection.rs +++ b/core/crates/layerfs-storage/src/port/read_selection.rs @@ -130,7 +130,7 @@ impl PersistedPackRead { } } } -pub(super) fn check_ranges( +pub(crate) fn check_ranges( info: PackInfo, prefix: usize, ranges: &[PackRange], diff --git a/core/crates/layerfs-storage/src/read/counters.rs b/core/crates/layerfs-storage/src/read/counters.rs index c4b19aa0f1..6971593310 100644 --- a/core/crates/layerfs-storage/src/read/counters.rs +++ b/core/crates/layerfs-storage/src/read/counters.rs @@ -90,4 +90,26 @@ pub struct Diagnostics { pub prefetch_group_decodes: u64, /// Lanes sealed because registration requires reference closure. pub forced_seals: u64, + /// Located rows that came with chain members (#758). + pub chain_rows: u64, + /// Chain members received. + pub chain_members: u64, + /// Bases located from a member, with no locate. + pub chain_hinted_bases: u64, + /// Hinted bases a Save kept as authoritative after hashing their chains. + pub chain_verified_bases: u64, + /// Hints dropped at the walk or at reconstruction. + pub chain_hint_stale: u64, + /// Delta roots a read walked without a chain, level by level. + pub chain_unhinted_roots: u64, + /// `read_groups` calls. + pub group_reads: u64, + /// Packs those calls named. + pub group_read_packs: u64, + /// Ranges those calls named. + pub group_read_ranges: u64, + /// Bytes those calls returned. + pub group_read_bytes: u64, + /// Packs read whole by plan or by the provider's answer. + pub group_read_whole: u64, } diff --git a/core/crates/layerfs-storage/src/read/fetch.rs b/core/crates/layerfs-storage/src/read/fetch.rs index f384ddb0d5..4985c56f3d 100644 --- a/core/crates/layerfs-storage/src/read/fetch.rs +++ b/core/crates/layerfs-storage/src/read/fetch.rs @@ -65,9 +65,10 @@ impl Published { } } -/// Restores the earlier serving state when a continuing reader's call ends. -pub(crate) struct ServePublished<'a>(&'a Cell, bool); -impl Drop for ServePublished<'_> { +/// Restores a flag's earlier value when its scope ends: the serving state +/// of a continuing reader's call, or the Save mode of a Save's own reads. +pub(crate) struct Restore<'a>(&'a Cell, bool); +impl Drop for Restore<'_> { fn drop(&mut self) { self.0.set(self.1); } @@ -75,14 +76,30 @@ impl Drop for ServePublished<'_> { pub(crate) struct Fetch { pub(crate) metadata: Arc, - locators: RefCell, - absent: RefCell>, - descriptors: RefCell>, + pub(super) locators: RefCell, + pub(super) absent: RefCell>, + pub(super) descriptors: RefCell>, signatures: RefCell>>, published: RefCell, /// Set while a reader that continues the latest Save reads. - serve_published: Cell, + pub(super) serve_published: Cell, counters: Cell, + /// Chain hints from chain locates (#758). + pub(super) hints: RefCell, + /// The handle's chain depth bounds, once its policy is read. + pub(crate) capacities: Cell>, + /// Tests and benches: a stale hint fails as `delta chain hint`. + pub(crate) strict_hints: Cell, + /// A read binds members to locators; a Save only prefetches their groups. + pub(super) bind_hints: Cell, + /// Program pages bind members too: set only while a Save rebuilds and + /// hashes its bases (`save/wave.rs`), never for a read. + pub(super) bind_pages: Cell, + /// Set while a Save reads through a reader (its lost registrations' + /// winners): those demands bind nothing either. + saving: Cell, + /// Cleared by a failure a hint may have caused, until the next demand. + pub(super) trust_hints: Cell, } impl Fetch { pub(crate) fn new(metadata: Arc) -> Self { @@ -95,6 +112,13 @@ impl Fetch { published: RefCell::new(Published::default()), serve_published: Cell::new(false), counters: Cell::new(Diagnostics::default()), + hints: RefCell::default(), + capacities: Cell::new(None), + strict_hints: Cell::new(false), + bind_hints: Cell::new(true), + bind_pages: Cell::new(false), + saving: Cell::new(false), + trust_hints: Cell::new(true), } } pub(crate) fn note(&self, change: impl FnOnce(&mut Diagnostics)) { @@ -140,27 +164,10 @@ impl Fetch { }; check_info(pack)?; self.remember_pack(pack)?; - let mut cache = self.locators.borrow_mut(); - if cache.len() >= READ_OBJECT_LIMIT { - let work = cache.make_room(1, &[]); - self.note(|c| { - c.locator_evictions += work.removed; - c.locator_eviction_probes += work.probes; - c.locator_second_chances += work.second_chances; - }); - } - if cache.len() >= READ_OBJECT_LIMIT { - self.note(|c| c.locator_evictions += cache.len() as u64); - cache.clear(); - } - cache.insert( - id, - crate::location::LocatedObject { - location: *row, - pack, - }, - ); + let location = *row; + self.keep_locator(crate::location::LocatedObject { location, pack }, false); } + self.published_directories(&batch.packs); let mut published = self.published.borrow_mut(); for pack in &batch.packs { if pack.info().domain == PackDomain::Metadata { @@ -177,8 +184,22 @@ impl Fetch { *self.published.borrow_mut() = Published::default(); } /// Serves the latest Save's published bodies until the guard drops. - pub(crate) fn serving_published(&self) -> ServePublished<'_> { - ServePublished(&self.serve_published, self.serve_published.replace(true)) + pub(crate) fn serving_published(&self) -> Restore<'_> { + Restore(&self.serve_published, self.serve_published.replace(true)) + } + /// Holds every demand to a Save's rule (no binding) until the guard drops. + pub(crate) fn save_reads(&self) -> Restore<'_> { + Restore(&self.saving, self.saving.replace(true)) + } + /// Binds chain members, for a Save's check of its bases, until the guard + /// drops. + pub(crate) fn binding(&self) -> Restore<'_> { + Restore(&self.bind_hints, self.bind_hints.replace(true)) + } + /// Lets program pages bind members too, for a Save's check of its + /// program-page bases, until the guard drops. + pub(crate) fn binding_pages(&self) -> Restore<'_> { + Restore(&self.bind_pages, self.bind_pages.replace(true)) } /// A body the latest Save published, to a reader that continues it, /// validated as a fetched one would be. @@ -198,8 +219,45 @@ impl Fetch { pub(crate) fn invalidate_signatures(&self) { *self.signatures.borrow_mut() = None; } - pub(crate) fn begin_demand(&self) { + /// A read demand binds chain members to locators; a Save's (`bind` + /// false), and any demand while [`Self::save_reads`] holds, uses chains + /// only to prefetch groups, so its selection walks see authoritative + /// locators only. A hinted locator serves only the demand that bound it. + pub(crate) fn begin_demand(&self, bind: bool) { self.absent.borrow_mut().clear(); + self.trust_hints.set(true); + self.bind_hints.set(bind && !self.saving.get()); + self.locators.borrow_mut().remove_hinted(); + self.forget_member_packs(); + } + /// Keeps one checked locator within the cache bound. + pub(super) fn keep_locator(&self, row: crate::location::LocatedObject, hinted: bool) { + let mut cache = self.locators.borrow_mut(); + if cache.len() >= READ_OBJECT_LIMIT { + let work = cache.make_room(1, &[]); + self.note(|c| { + c.locator_evictions += work.removed; + c.locator_eviction_probes += work.probes; + c.locator_second_chances += work.second_chances; + }); + } + self.insert_locator(&mut cache, row, hinted); + } + /// Inserts one checked locator, clearing a cache with no room left. + fn insert_locator( + &self, + cache: &mut LocatorCache, + row: crate::location::LocatedObject, + hinted: bool, + ) { + if cache.len() >= READ_OBJECT_LIMIT { + self.note(|c| c.locator_evictions += cache.len() as u64); + cache.clear(); + } + cache.insert_as(row.location.object_id, row, hinted); + } + pub(super) fn published_has(&self, id: i64) -> bool { + self.published.borrow().get(id).is_some() } pub(crate) fn locate(&self, ids: &[ObjectId]) -> StorageResult<()> { let mut missing = BTreeSet::new(); @@ -220,8 +278,9 @@ impl Fetch { } for page in missing.chunks(READ_OBJECT_LIMIT) { let mut rows = Vec::new(); + let mut chains = crate::location::LocatedChains::default(); self.note(|c| c.locate += 1); - self.metadata.locate(page, &mut rows)?; + self.metadata.locate_chains(page, &mut rows, &mut chains)?; if rows.len() > page.len() { return Err(StorageError::Integrity("locator cardinality")); } @@ -236,27 +295,30 @@ impl Fetch { }); } } - let mut seen = BTreeSet::new(); - for row in rows { + // The whole answer, rows and chains, is checked before any of it + // is kept. + let mut seen = BTreeMap::new(); + for row in &rows { let location = row.location; if page.binary_search(&location.object_id).is_err() - || !seen.insert(location.object_id) + || seen.insert(location.object_id, location.role).is_some() || location.pack_id != row.pack.pack_id || location.pack_id <= 0 - || location.canonical_length > crate::policy::CANONICAL_LIMIT - || location.group_number >= crate::policy::GROUP_COUNT_LIMIT - || location.record_number >= crate::policy::RECORD_COUNT_LIMIT + || bad_position( + location.group_number, + location.record_number, + location.canonical_length, + ) { return Err(StorageError::Integrity("port locator")); } check_info(row.pack)?; + } + self.install_chains(&seen, chains)?; + for row in rows { self.remember_pack(row.pack)?; let mut cache = self.locators.borrow_mut(); - if cache.len() >= READ_OBJECT_LIMIT { - self.note(|c| c.locator_evictions += cache.len() as u64); - cache.clear(); - } - cache.insert(location.object_id, row); + self.insert_locator(&mut cache, row, false); self.note(|c| { c.locator_bookkeeping_live_peak_bytes = c .locator_bookkeeping_live_peak_bytes @@ -264,7 +326,7 @@ impl Fetch { }); } let mut absent = self.absent.borrow_mut(); - for id in page.iter().filter(|id| !seen.contains(id)) { + for id in page.iter().filter(|id| !seen.contains_key(id)) { if absent.len() >= READ_OBJECT_LIMIT { absent.clear(); } @@ -295,13 +357,35 @@ impl Fetch { } count } - fn remember_pack(&self, info: PackInfo) -> StorageResult<()> { - let mut cache = self.descriptors.borrow_mut(); - if cache.get(&info.pack_id).is_some_and(|old| *old != info) { - return Err(StorageError::Integrity("inconsistent pack descriptor")); + /// Keeps a descriptor a source gave, and confirms one only a chain member + /// named (#758, `remember_member_pack`). Every caller confirms: locate + /// rows, whole-pack replies (length and digest authenticated), but also + /// a group read's ranged admission and a pack-cache hit, whose descriptor + /// may itself be a member's, so a member's descriptor whose group was + /// read counts as authoritative from then on. A descriptor that + /// contradicts a still-marked one makes the hint stale (counted, strict + /// refuses) and drops every hint at once, so a later failure of that + /// walk at a hinted element is no longer rebuilt on a read (the failure + /// stands) and is not counted again by a Save's check; one + /// that contradicts an unmarked descriptor fails as + /// `inconsistent pack descriptor`. Pack ids are never reused, so either + /// contradiction means a provider answered a chain unlike its own pack + /// row. + pub(super) fn remember_pack(&self, info: PackInfo) -> StorageResult<()> { + let from_member = self.confirm_member_pack(info.pack_id); + let old = self.descriptors.borrow().get(&info.pack_id).copied(); + if old.is_some_and(|old| old != info) { + if !from_member { + return Err(StorageError::Integrity("inconsistent pack descriptor")); + } + self.descriptors.borrow_mut().remove(&info.pack_id); + self.forget_hints(); + self.stale()?; } + let mut cache = self.descriptors.borrow_mut(); if cache.len() >= READ_OBJECT_LIMIT && !cache.contains_key(&info.pack_id) { cache.clear(); + self.forget_member_marks(); } cache.insert(info.pack_id, info); Ok(()) @@ -409,6 +493,26 @@ impl Fetch { validate_frame(info, &body)?; Ok(body) } + /// A whole pack a reply returned: refused as `reason` unless it is the + /// one asked for (`bound`), else its descriptor is kept and its frame + /// checked, and the pack cache may admit it. + pub(super) fn whole_reply( + &self, + bound: bool, + reason: &'static str, + info: PackInfo, + body: Vec, + ) -> StorageResult { + if !bound { + return Err(StorageError::Integrity(reason)); + } + self.remember_pack(info)?; + validate_frame(info, &body)?; + Ok(crate::encoding::PackAcquisition::Whole { + info: Some(info), + body, + }) + } } impl Source for Fetch { fn ordered_dependencies(&self) -> bool { @@ -491,11 +595,9 @@ impl Source for Fetch { match reply { crate::port::AcquiredPackRead::Whole(row) => { let (info, body) = row.into_parts(); - if info.pack_id != id { - return Err(StorageError::Integrity("selected whole binding")); - } - self.remember_pack(info)?; - validate_frame(info, &body)?; + let length = body.len() as u64; + let whole = + self.whole_reply(info.pack_id == id, "selected whole binding", info, body)?; self.note(|c| { c.whole_selected += 1; match plan.whole_reason { @@ -507,15 +609,12 @@ impl Source for Fetch { } if info.domain == PackDomain::Payload { c.payload_reads += 1; - c.payload_read_bytes += body.len() as u64; + c.payload_read_bytes += length; } else { - c.pack_read_bytes += body.len() as u64; + c.pack_read_bytes += length; } }); - Ok(crate::encoding::PackAcquisition::Whole { - info: Some(info), - body, - }) + Ok(whole) } crate::port::AcquiredPackRead::Units(row) => { if row.info().pack_id != id { @@ -621,8 +720,31 @@ impl Source for Fetch { fn note_pack_cache_hit(&self) { self.note(|c| c.pack_hits += 1); } + fn prefetch_chain( + &self, + location: &ObjectLocation, + packs: &mut crate::encoding::PackCache, + ) -> StorageResult<()> { + self.prefetch_groups(std::slice::from_ref(location), packs) + } + fn bind_base(&self, child: &ObjectLocation, base: Option) -> StorageResult<()> { + self.bind(child, base) + } + fn hinted(&self, id: ObjectId) -> bool { + self.locators.borrow().is_hinted(&id) + } + fn drop_hints(&self, chain: &[ObjectId]) -> StorageResult { + Fetch::drop_hints(self, chain) + } +} +/// Whether a located position is out of bounds: a row's and a chain +/// member's alike (a member's length must also be at least one). +pub(super) fn bad_position(group: usize, record: usize, canonical_length: usize) -> bool { + canonical_length > crate::policy::CANONICAL_LIMIT + || group >= crate::policy::GROUP_COUNT_LIMIT + || record >= crate::policy::RECORD_COUNT_LIMIT } -fn check_info(info: PackInfo) -> StorageResult<()> { +pub(super) fn check_info(info: PackInfo) -> StorageResult<()> { if info.pack_id <= 0 || !(32..=SINGLETON_PACK_LIMIT).contains(&info.length) { return Err(StorageError::Integrity("port pack descriptor")); } @@ -631,7 +753,7 @@ fn check_info(info: PackInfo) -> StorageResult<()> { } Ok(()) } -fn validate_frame(info: PackInfo, body: &[u8]) -> StorageResult<()> { +pub(super) fn validate_frame(info: PackInfo, body: &[u8]) -> StorageResult<()> { check_info(info)?; let header = layout::parse_header(body)?; if layout::declared_length(body)? != body.len() diff --git a/core/crates/layerfs-storage/src/read/hints.rs b/core/crates/layerfs-storage/src/read/hints.rs new file mode 100644 index 0000000000..86aba6443e --- /dev/null +++ b/core/crates/layerfs-storage/src/read/hints.rs @@ -0,0 +1,769 @@ +//! Delta-chain hints (#758): validation, binding, group prefetch and fallback. +//! +//! A chain member says where a base might be stored. The walk binds it to the +//! base the child record names and checks it there; reconstruction then hashes +//! every object. A hint that disagrees is dropped and counted, and the read +//! goes on level by level from authoritative locates. + +use super::{ + fetch::{bad_position, check_info}, + units::GroupPlan, + Fetch, +}; +use crate::{ + encoding::{delta::read::cached_base, PackAcquisition, PackCache, PackUnit}, + error::{StorageError, StorageResult}, + location::{ChainMember, LocatedChains, LocatedObject, ObjectLocation, PackInfo}, + pack::layout, + policy::{DEPENDENCY_PACK_CACHE_BYTES, READ_OBJECT_LIMIT}, + port::PersistenceError, + port::{AcquiredPackRead, GroupRead, GroupReadAnswer, PackReadChoice, PackReadPlan}, +}; +use layerfs_content::{ObjectId, ObjectRole}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Positions one chain contributes at most: its root and every member. +const CHAIN_ENTRIES: usize = layerfs_content::MAXIMUM_DELTA_MAX_DEPTH as usize + 1; + +/// Chains of located roots, the walk's position in each, and pack directories. +/// Bounded: cleared whole when a bound is reached. +#[derive(Default)] +pub(super) struct Hints { + chains: BTreeMap)>, + /// A child's base is member `depth` of `root`'s chain of that generation. + next: BTreeMap, + directories: BTreeMap)>, + directory_bytes: usize, + generation: u64, + /// Packs whose descriptor only a bound member gave: forgotten with the + /// hints and at the next demand, unless confirmed first. + packs: BTreeSet, +} +impl Hints { + /// Keeps one checked pack directory within the bound. + fn directory(&mut self, pack: PackInfo, prefix: Vec) { + if self.directory_bytes + prefix.len() > DEPENDENCY_PACK_CACHE_BYTES { + (self.directories, self.directory_bytes) = Default::default(); + } + self.directory_bytes += prefix.len(); + self.directories.insert(pack.pack_id, (pack, prefix)); + } + /// `child`'s chain position: root, generation, depth and the remaining members. + fn rest(&self, child: ObjectId) -> Option<(ObjectId, u64, usize, &[ChainMember])> { + let &(root, generation, depth) = self.next.get(&child)?; + let (current, members) = self.chains.get(&root)?; + (*current == generation).then(|| (root, generation, depth, &members[depth..])) + } +} + +/// One pack a page plans: its uncached wanted groups, sorted, whether an +/// authoritative row names it, and its request with its returned-byte cost. +#[derive(Clone)] +struct Planned { + info: PackInfo, + groups: Vec, + own: bool, + read: Option<(GroupRead, usize)>, +} +impl Planned { + fn cost(&self) -> usize { + self.read.as_ref().map_or(0, |read| read.1) + } +} + +/// Reasons that a provider's answer is itself malformed: a defect, which +/// fails hard and is never taken for a stale hint and replayed. +const PROVIDER_DEFECTS: &[&str] = &[ + "delta chain hint", + "port locator", + "port chain locator", + "port pack descriptor", + "locator cardinality", + "inconsistent pack descriptor", + "group read reply", + "metadata pack bound", + "metadata pack cardinality/bytes", + "metadata pack descriptor", + "payload descriptor", + "selected descriptor binding", + "selected strategy/extent reply", + "selected whole binding", + "selected pack binding", + "unrequested inode value", + "metadata ordinal missing", + "content index over slot bound", +]; + +/// Whether `error` may come from a stale hint: an object, pack or record that +/// is not where the hint said, or bytes that are not what it named. Never an +/// I/O outcome or a provider defect, which are not replayed. +pub(crate) fn hint_failure(error: &StorageError) -> bool { + match error { + StorageError::ObjectMissing(_) => true, + StorageError::Integrity(reason) => !PROVIDER_DEFECTS.contains(reason), + other => missing_pack(other), + } +} + +/// A provider's `Missing`: the pack a position names is not stored. +fn missing_pack(error: &StorageError) -> bool { + let StorageError::Io(io) = error else { + return false; + }; + io.get_ref() + .and_then(|inner| inner.downcast_ref::()) + .is_some_and(|inner| *inner == PersistenceError::Missing) +} + +impl Fetch { + /// Validates one chain locate's answer and keeps its chains. A malformed + /// answer is a provider defect and fails hard. + pub(super) fn install_chains( + &self, + located: &BTreeMap, + answer: LocatedChains, + ) -> StorageResult<()> { + const BAD: StorageError = StorageError::Integrity("port chain locator"); + let mut roots = std::collections::BTreeSet::new(); + let mut members = 0; + for chain in &answer.chains { + let depth = located.get(&chain.root).map(|role| self.depth_for(*role)); + if !roots.insert(chain.root) + || !depth.is_some_and(|depth| (1..=depth).contains(&chain.members.len())) + || chain.members.iter().any(|m| { + check_info(m.pack).is_err() + || bad_position(m.group_number, m.record_number, m.canonical_length) + || m.canonical_length == 0 + }) + { + return Err(BAD); + } + members += chain.members.len() as u64; + } + for directory in &answer.directories { + check_directory(directory.pack, &directory.prefix).map_err(|_| BAD)?; + } + let rows = answer.chains.len() as u64; + self.note(|c| { + c.chain_rows += rows; + c.chain_members += members; + }); + if !self.trust_hints.get() { + return Ok(()); + } + let mut hints = self.hints.borrow_mut(); + for chain in answer.chains { + if hints.chains.len() >= READ_OBJECT_LIMIT + || hints.next.len() >= READ_OBJECT_LIMIT * CHAIN_ENTRIES + { + (hints.chains, hints.next) = Default::default(); + } + hints.generation += 1; + let generation = hints.generation; + hints.chains.insert(chain.root, (generation, chain.members)); + hints.next.insert(chain.root, (chain.root, generation, 0)); + } + for directory in answer.directories { + hints.directory(directory.pack, directory.prefix); + } + Ok(()) + } + /// Keeps the directories of the packs this handle published, so a group + /// read plans their ranges (#758), when the provider batches chains. + pub(super) fn published_directories(&self, packs: &[crate::port::PublishedPack]) { + if !self.metadata.batched_chain_reads() { + return; + } + let mut hints = self.hints.borrow_mut(); + for pack in packs { + let body = pack.body(); + if let Ok(header) = layout::parse_header(body) { + hints.directory(pack.info(), body[..header.body_offset].to_vec()); + } + } + } + fn depth_for(&self, role: ObjectRole) -> usize { + usize::from( + self.capacities + .get() + .map_or(layerfs_content::MAXIMUM_DELTA_MAX_DEPTH, |capacities| { + capacities.delta_depth_for_role(role) + }), + ) + } + /// Whether `id`'s base has a chain member to bind. + pub(crate) fn has_hint(&self, id: ObjectId) -> bool { + self.hints.borrow().rest(id).is_some() + } + /// Binds the base `child`'s record names to its member and keeps it as a + /// hinted locator, so the walk's own locate sends nothing. A member whose + /// id or end disagrees with the record is stale: its chain is dropped. + /// Pooled leaves and program pages are rebuilt by the pool reader, which + /// has no rebuild of its own, so a read locates their bases as before; + /// only a Save's check of its program-page bases binds theirs + /// ([`Self::binding_pages`]), and it walks them again from authoritative + /// locates when the check fails. + pub(super) fn bind(&self, child: &ObjectLocation, base: Option) -> StorageResult<()> { + if !self.bind_hints.get() + || !self.trust_hints.get() + || child.role == ObjectRole::InodeLeaf + || (crate::encoding::pool::branch::is_program_role(child.role) + && !self.bind_pages.get()) + { + return Ok(()); + } + let mut hints = self.hints.borrow_mut(); + let Some((root, generation, depth, rest)) = hints.rest(child.object_id) else { + return Ok(()); + }; + let (member, base) = match (rest.first().copied(), base) { + (None, None) => return Ok(()), + (Some(m), Some(x)) if m.object_id.is_none_or(|id| id == x) && self.known(&m) => (m, x), + _ => { + hints.chains.remove(&root); + drop(hints); + return self.stale(); + } + }; + hints.next.insert(base, (root, generation, depth + 1)); + drop(hints); + if self.locators.borrow().contains_key(&base) { + return Ok(()); + } + self.remember_member_pack(member.pack); + let location = ObjectLocation { + object_id: base, + role: child.role, + canonical_length: member.canonical_length, + pack_id: member.pack.pack_id, + group_number: member.group_number, + record_number: member.record_number, + base: None, + }; + let row = LocatedObject { + location, + pack: member.pack, + }; + self.keep_locator(row, true); + self.absent.borrow_mut().remove(&base); + self.note(|c| c.chain_hinted_bases += 1); + Ok(()) + } + /// A member whose pack descriptor does not contradict a known one. + fn known(&self, member: &ChainMember) -> bool { + let descriptors = self.descriptors.borrow(); + descriptors + .get(&member.pack.pack_id) + .is_none_or(|old| *old == member.pack) + } + /// Keeps the descriptor of a bound member's pack for the walk that + /// bound it. One no other source gave is a hint: forgotten with the hints + /// and at the next demand, unless an authoritative descriptor confirms it + /// first ([`Self::remember_pack`]). + fn remember_member_pack(&self, info: PackInfo) { + let mut cache = self.descriptors.borrow_mut(); + // `known` refused a member that contradicts a kept descriptor. + if cache.contains_key(&info.pack_id) { + return; + } + if cache.len() >= READ_OBJECT_LIMIT { + cache.clear(); + self.forget_member_marks(); + } + cache.insert(info.pack_id, info); + self.hints.borrow_mut().packs.insert(info.pack_id); + } + /// Whether `pack`'s kept descriptor came from a member alone; it no + /// longer counts as one. + pub(super) fn confirm_member_pack(&self, pack: i64) -> bool { + self.hints.borrow_mut().packs.remove(&pack) + } + /// Forgets which descriptors came from members (their descriptors were + /// cleared with the rest). + pub(super) fn forget_member_marks(&self) { + self.hints.borrow_mut().packs.clear(); + } + /// Forgets every descriptor that only a bound member gave. + pub(super) fn forget_member_packs(&self) { + let packs = std::mem::take(&mut self.hints.borrow_mut().packs); + let mut cache = self.descriptors.borrow_mut(); + for pack in packs { + cache.remove(&pack); + } + } + pub(super) fn stale(&self) -> StorageResult<()> { + self.note(|c| c.chain_hint_stale += 1); + if self.strict_hints.get() { + return Err(StorageError::Integrity("delta chain hint")); + } + Ok(()) + } + /// After a failure that a hint may have caused, on the walk of `chain` + /// (empty: any walk): when a hinted locator was on it, evicts every hinted + /// locator, uses no hint until the next demand and returns true, so the + /// caller rebuilds once from authoritative locates. + pub(crate) fn drop_hints(&self, chain: &[ObjectId]) -> StorageResult { + let involved = { + let cache = self.locators.borrow(); + chain.is_empty() || chain.iter().any(|id| cache.is_hinted(id)) + }; + if !involved || self.forget_hints() == 0 { + return Ok(false); + } + self.stale().map(|()| true) + } + /// A failure a stale hint may have caused, at an element a hint located + /// or reached through one, in a walk that has no rebuild of its own (a + /// Save's check of a program-page base, `save/wave.rs`): uses no hint + /// until the next demand and counts the stale hint (strict refuses), + /// unless `counted`: the walk already counted that stale hint (a member + /// that disagreed with its record, or a descriptor that contradicted a + /// member's), which is counted once. + pub(crate) fn hint_stale(&self, counted: bool) -> StorageResult<()> { + self.forget_hints(); + match counted { + true => Ok(()), + false => self.stale(), + } + } + /// Uses no hint until the next demand; returns how many hinted locators + /// were evicted. The descriptors only their members gave go with them. + pub(super) fn forget_hints(&self) -> usize { + self.trust_hints.set(false); + self.forget_member_packs(); + *self.hints.borrow_mut() = Hints::default(); + self.locators.borrow_mut().remove_hinted() + } + /// Keeps every hinted locator, and the descriptor of its pack, as + /// authoritative. Called only after a reconstruction hashed every element + /// of the chain that bound them (a Save's check of its bases, + /// `save/wave.rs`). + pub(crate) fn promote_hints(&self) { + self.forget_member_marks(); + let promoted = self.locators.borrow_mut().promote_hinted() as u64; + self.note(|c| c.chain_verified_bases += promoted); + } + /// The ids further down the chains of `edges` (each a walked child and + /// the base its record names) that a locate of this level can carry + /// (#758): member `k` of a child's chain says where its level-`k` base + /// may be stored, so the base id the record there names, read from bytes + /// the caches already hold ([`cached_base`]), is a guess for level + /// `k + 1`. Nothing is trusted: the guesses are only located with the + /// level's own ids, so their rows are authoritative, and the walk still + /// takes every base id from the record at its base's authoritative + /// location; a wrong guess only leaves the next level to locate its base + /// as before. Empty unless this level locates anyway (`level` holds an + /// id the cache lacks), and never more than fills that locate's page, so + /// that locate is the only statement the guesses join. Only the chains of + /// edges whose base this level has to locate are followed: a base already + /// cached was bound from a member or located earlier, and a chain a read + /// binds binds its deeper bases with no locate (fix 3b). So this serves + /// the chains a read does not bind (program pages, pooled leaves) and a + /// Save's reads, which bind none. + /// + /// Presence checks set no locator-cache referenced bit and the pack and + /// decoded-group caches are only peeked. Effects that remain: a wrong + /// guess's row is cached (or, when absent, remembered as absent), adding + /// locator-cache pressure, and a guessed row's authoritative descriptor + /// that contradicts a marked member descriptor makes the hints stale + /// ([`Fetch::remember_pack`]). A group a guess needs decoded is + /// decompressed into a decoded-group cache of this call's own (least + /// recently used eviction, bounded by + /// [`crate::policy::DECODED_GROUP_CACHE_BYTES`], dropped on return) and + /// reused while it is held there: a call whose groups fit that bound + /// decodes each once, but a body over the bound is never kept and a call + /// that interleaves more distinct groups than fit decodes an evicted one + /// again. Every decompression is counted in `prefetch_group_decodes`. + pub(crate) fn chain_ahead( + &self, + level: &[ObjectId], + edges: &[(ObjectLocation, ObjectId)], + packs: &PackCache, + groups: &crate::encoding::GroupCache, + workspace: &mut crate::encoding::codec::DecompressionWorkspace, + ) -> Vec { + if !self.trust_hints.get() { + return Vec::new(); + } + let cached = + |id: &ObjectId| self.locators.borrow().holds(id) || self.absent.borrow().contains(id); + let missing: BTreeSet<_> = level.iter().filter(|id| !cached(id)).collect(); + if missing.is_empty() { + return Vec::new(); + } + let room = READ_OBJECT_LIMIT.saturating_sub(missing.len()); + let hints = self.hints.borrow(); + let mut ahead = BTreeSet::new(); + let mut decoded = crate::encoding::GroupCache::new(); + let mut decodes = 0_u64; + 'edges: for (child, base) in edges { + if !missing.contains(base) { + continue; + } + let Some((_, _, _, rest)) = hints.rest(child.object_id) else { + continue; + }; + let mut id = *base; + for member in rest.iter().take_while(|m| self.known(m)) { + if ahead.len() >= room { + break 'edges; + } + let location = ObjectLocation { + object_id: id, + role: child.role, + canonical_length: member.canonical_length, + pack_id: member.pack.pack_id, + group_number: member.group_number, + record_number: member.record_number, + base: None, + }; + let next = cached_base( + packs, + groups, + &mut decoded, + workspace, + &mut decodes, + &location, + ); + let Some(next) = next else { + break; + }; + if !cached(&next) && !missing.contains(&next) { + ahead.insert(next); + } + id = next; + } + } + if decodes > 0 { + self.note(|c| c.prefetch_group_decodes += decodes); + } + ahead.into_iter().collect() + } + /// Fetches the uncached groups `locations` and their chains need in one + /// `read_groups` call, as the first page of [`Self::page`] does. Nothing + /// happens unless a member or a local chain is involved, so rows with no + /// chain keep today's acquisition. + pub(crate) fn prefetch_groups( + &self, + locations: &[ObjectLocation], + packs: &mut PackCache, + ) -> StorageResult<()> { + self.fetch_page([locations], packs, true).map(drop) + } + /// Pages a demand (#758): fetches the uncached groups of the longest + /// leading run of `consumers` (each the rows one consumer reads next) and + /// of their chains in one `read_groups` call of at most + /// [`DEPENDENCY_PACK_CACHE_BYTES`] of returned bytes, into `packs`, and + /// returns that run's length. The caller consumes the run before it asks + /// for the next page, so the pack cache still holds every group of it. A + /// first consumer that does not fit alone has the packs that fit read and + /// counts as covered. Returns 0, reading nothing, when the provider has no + /// chains to batch: the caller acquires as before. + pub(crate) fn page<'a>( + &self, + consumers: impl IntoIterator, + packs: &mut PackCache, + ) -> StorageResult { + self.fetch_page(consumers, packs, false) + } + /// [`Self::page`]; with `chained`, nothing is read unless a member or a + /// local chain is involved. + /// + /// A pack only members name is a hint: a member whose descriptor + /// contradicts a known one is left out, and a failure of a read planned + /// for members alone makes the hints stale (counted, not used again this + /// demand) while the read goes on as before. A failure of a pack that + /// the rows themselves name stays hard. + fn fetch_page<'a>( + &self, + consumers: impl IntoIterator, + packs: &mut PackCache, + chained: bool, + ) -> StorageResult { + let batched = self.metadata.batched_chain_reads(); + if !self.trust_hints.get() || !batched && self.hints.borrow().chains.is_empty() { + return Ok(0); + } + let (mut page, mut bytes, mut covered, mut members) = (Vec::::new(), 0, 0, false); + // Cached entries the page keeps resident, counted in its bytes. + let mut kept = BTreeSet::new(); + for rows in consumers { + let mut needs = Vec::new(); + members |= self.needs(rows, batched, &mut needs); + // This consumer's packs, each with the page's groups and its own, + // and the cached entries it adds to the page. + let mut trial: Vec = Vec::new(); + let mut keep = BTreeMap::new(); + for (info, group, own) in needs { + if self.serve_published.get() && self.published_has(info.pack_id) { + continue; + } + if packs.group(self, info.pack_id, group)?.is_some() { + keep.extend( + packs + .held(info.pack_id, group) + .filter(|e| !kept.contains(&e.0)), + ); + continue; + } + let at = match trial.iter().position(|p| p.info.pack_id == info.pack_id) { + Some(at) => at, + None => { + let known = page.iter().find(|p| p.info.pack_id == info.pack_id); + trial.push(known.cloned().unwrap_or(Planned { + info, + groups: Vec::new(), + own: false, + read: None, + })); + trial.len() - 1 + } + }; + trial[at].own |= own; + if let Err(slot) = trial[at].groups.binary_search(&group) { + trial[at].groups.insert(slot, group); + } + } + let cost = |page: &[Planned], id: i64| { + page.iter() + .find(|p| p.info.pack_id == id) + .map_or(0, Planned::cost) + }; + let mut next = bytes + keep.values().sum::(); + for planned in &mut trial { + next -= cost(&page, planned.info.pack_id); + planned.read = self.plan_read(planned.info, &planned.groups); + next += planned.cost(); + } + if next > DEPENDENCY_PACK_CACHE_BYTES && covered > 0 { + break; + } + bytes += keep.values().sum::(); + kept.extend(keep.into_keys()); + for planned in trial { + // A first consumer over the bound keeps the packs that fit. + let after = bytes - cost(&page, planned.info.pack_id) + planned.cost(); + if after > DEPENDENCY_PACK_CACHE_BYTES { + continue; + } + bytes = after; + match page + .iter() + .position(|p| p.info.pack_id == planned.info.pack_id) + { + Some(at) => page[at] = planned, + None => page.push(planned), + } + } + covered += 1; + if next > DEPENDENCY_PACK_CACHE_BYTES { + break; + } + } + if chained && !members { + return Ok(covered); + } + let (reads, planned): (Vec, Vec<(Vec, bool)>) = page + .into_iter() + .filter_map(|p| p.read.map(|(read, _)| (read, (p.groups, p.own)))) + .unzip(); + if reads.is_empty() { + return Ok(covered); + } + let hinted_only = planned.iter().any(|(_, own)| !own); + let mut answers = Vec::new(); + match self.metadata.read_groups(&reads, &mut answers) { + Err(PersistenceError::Missing | PersistenceError::Malformed) if hinted_only => { + self.forget_hints(); + return self.stale().map(|()| covered); + } + other => other?, + } + if answers.len() != reads.len() { + return Err(StorageError::Integrity("group read reply")); + } + let ranges: usize = reads.iter().map(|read| read.ranges.len()).sum(); + self.note(|c| { + c.group_reads += 1; + c.group_read_packs += reads.len() as u64; + c.group_read_ranges += ranges as u64; + }); + let mut stale = false; + for ((read, answer), (groups, own)) in reads.iter().zip(answers).zip(&planned) { + let wanted = groups.iter().copied().collect(); + let admitted = self.admit(read, answer, groups).and_then(|acquisition| { + packs.admit_groups(self, read.pack.pack_id, &wanted, groups, acquisition) + }); + match admitted { + Err(_) if !own => stale = true, + other => { + other?; + } + } + } + if stale { + self.forget_hints(); + return self.stale().map(|()| covered); + } + Ok(covered) + } + /// The groups `rows` need, each with its pack and whether an + /// authoritative row names it: their own, their chains' members and, + /// when the provider batches them, their local chains. True when a member + /// or a local chain is involved. + fn needs( + &self, + rows: &[ObjectLocation], + batched: bool, + out: &mut Vec<(PackInfo, usize, bool)>, + ) -> bool { + let hints = self.hints.borrow(); + let mut members = false; + for location in rows { + let info = self.descriptors.borrow().get(&location.pack_id).copied(); + out.extend(info.map(|info| (info, location.group_number, true))); + let rest = hints + .rest(location.object_id) + .map_or(&[][..], |hint| hint.3); + members |= !rest.is_empty(); + let known = rest.iter().filter(|m| self.known(m)); + out.extend(known.map(|m| (m.pack, m.group_number, false))); + if batched { + members |= self.local_chain(location, &mut |info, group| { + out.push((info, group, true)); + }); + } + } + members + } + /// Adds the groups of `location`'s chain as this handle's cache knows + /// it: published rows carry their `base`, followed through authoritative + /// locators only (a lost row was invalidated, so its winner is located + /// again) until a base is not cached or the record is FULL. + fn local_chain( + &self, + location: &ObjectLocation, + add: &mut impl FnMut(PackInfo, usize), + ) -> bool { + let cache = self.locators.borrow(); + let mut base = location.base; + let mut found = false; + for _ in 0..CHAIN_ENTRIES { + let Some(row) = base.and_then(|id| cache.authoritative(&id)) else { + break; + }; + add(row.pack, row.location.group_number); + found = true; + base = row.location.base; + } + found + } + /// The authoritative locations this handle holds for `ids`, in order. + pub(crate) fn located(&self, ids: impl Iterator) -> Vec { + let cache = self.locators.borrow(); + ids.filter_map(|id| cache.authoritative(&id).map(|row| row.location)) + .collect() + } + /// One pack's request and its returned-byte cost: the planned ranges where + /// a directory is known, else the whole pack; `None` when the request + /// would not fit one call. + fn plan_read(&self, info: PackInfo, groups: &[usize]) -> Option<(GroupRead, usize)> { + let hints = self.hints.borrow(); + let whole = Some(( + GroupRead { + pack: info, + ranges: Vec::new(), + }, + info.length, + )) + .filter(|_| info.length <= DEPENDENCY_PACK_CACHE_BYTES); + let Some((_, prefix)) = hints.directories.get(&info.pack_id).filter(|d| d.0 == info) else { + return whole; + }; + let mut plan = GroupPlan::ranged(info.pack_id, groups); + match plan.select(info, prefix) { + Ok(PackReadChoice::Ranges(ranges)) + if crate::port::check_ranges(info, prefix.len(), &ranges).is_ok() => + { + let cost = ranges.iter().map(|range| range.length).sum(); + Some((GroupRead { pack: info, ranges }, cost)) + } + Ok(_) => whole, + // A member naming a group the directory lacks is a stale position: + // the walk meets it there and falls back. + Err(_) => None, + } + } + /// Checks one answer and turns it into the acquisition the pack cache admits. + fn admit( + &self, + read: &GroupRead, + answer: GroupReadAnswer, + groups: &[usize], + ) -> StorageResult { + let bad = StorageError::Integrity("group read reply"); + match answer { + GroupReadAnswer::Whole(pack) => { + let (info, body) = pack.into_parts(); + let length = body.len() as u64; + let whole = self.whole_reply(info == read.pack, "group read reply", info, body)?; + self.note(|c| { + c.group_read_whole += 1; + c.group_read_bytes += length; + }); + Ok(whole) + } + GroupReadAnswer::Ranges(bodies) => { + let hints = self.hints.borrow(); + let directory = hints.directories.get(&read.pack.pack_id); + let prefix = directory.filter(|d| d.0 == read.pack).map(|d| &d.1); + let lengths = bodies.iter().map(Vec::len); + let (Some(prefix), false) = (prefix, read.ranges.is_empty()) else { + return Err(bad); + }; + if !lengths.eq(read.ranges.iter().map(|range| range.length)) { + return Err(bad); + } + let mut plan = GroupPlan::ranged(read.pack.pack_id, groups); + let acquired = AcquiredPackRead::acquire(read.pack, &mut plan, |at, out| { + let end = at + out.len(); + if end <= prefix.len() { + out.copy_from_slice(&prefix[at..end]); + return Ok(()); + } + let (range, body) = read + .ranges + .iter() + .zip(&bodies) + .find(|(range, _)| range.offset <= at && end <= range.offset + range.length) + .ok_or(PersistenceError::Malformed)?; + out.copy_from_slice(&body[at - range.offset..end - range.offset]); + Ok(()) + }); + if let Some(error) = plan.error { + return Err(error); + } + let AcquiredPackRead::Units(units) = acquired? else { + return Err(bad); + }; + drop(hints); + self.remember_pack(read.pack)?; + let returned: usize = bodies.iter().map(Vec::len).sum(); + self.note(|c| c.group_read_bytes += returned as u64); + Ok(PackAcquisition::Units(PackUnit::from_acquired(units)?)) + } + } + } +} + +/// A directory must be exactly `body[0..body_offset)` of a valid pack of its lane. +fn check_directory(info: PackInfo, prefix: &[u8]) -> StorageResult<()> { + check_info(info)?; + let header = layout::parse_directory_header(prefix, info.length)?; + if prefix.len() != header.body_offset + || crate::location::PackDomain::for_lane(header.lane) != info.domain + { + return Err(StorageError::Integrity("pack directory width")); + } + layout::directory_group_views(prefix, header).map(|_| ()) +} diff --git a/core/crates/layerfs-storage/src/read/length.rs b/core/crates/layerfs-storage/src/read/length.rs index e7bdd85caf..95a1ec3afc 100644 --- a/core/crates/layerfs-storage/src/read/length.rs +++ b/core/crates/layerfs-storage/src/read/length.rs @@ -18,7 +18,7 @@ pub(super) fn read( actual: ids.len() as u64, }); } - storage.source.begin_demand(); + storage.source.begin_demand(true); storage.source.locate(ids)?; let mut lengths = vec![0; ids.len()]; let mut states = Vec::new(); diff --git a/core/crates/layerfs-storage/src/read/locator_cache.rs b/core/crates/layerfs-storage/src/read/locator_cache.rs index 4eae07c887..946f2ada85 100644 --- a/core/crates/layerfs-storage/src/read/locator_cache.rs +++ b/core/crates/layerfs-storage/src/read/locator_cache.rs @@ -6,11 +6,15 @@ use std::{cell::Cell, collections::BTreeMap, ops::Bound}; struct Entry { row: LocatedObject, referenced: Cell, + /// Bound from a chain member (#758), not located authoritatively. + hinted: bool, } #[derive(Default)] pub(crate) struct LocatorCache { entries: BTreeMap, hand: Option, + /// Entries that are hinted, so a demand with none skips the scan. + hinted: usize, } #[derive(Default)] pub(crate) struct EvictionWork { @@ -30,21 +34,59 @@ impl LocatorCache { pub(crate) fn contains_key(&self, id: &ObjectId) -> bool { self.get(id).is_some() } + /// Presence only: unlike [`Self::contains_key`], sets no referenced bit, + /// so the second-chance order is left as it was. + pub(crate) fn holds(&self, id: &ObjectId) -> bool { + self.entries.contains_key(id) + } pub(crate) fn remove(&mut self, id: &ObjectId) { - self.entries.remove(id); + if let Some(entry) = self.entries.remove(id) { + self.hinted -= usize::from(entry.hinted); + } } pub(crate) fn clear(&mut self) { self.entries.clear(); self.hand = None; + self.hinted = 0; + } + pub(crate) fn insert_as(&mut self, id: ObjectId, row: LocatedObject, hinted: bool) { + let referenced = Cell::new(true); + let entry = Entry { + row, + referenced, + hinted, + }; + if let Some(old) = self.entries.insert(id, entry) { + self.hinted -= usize::from(old.hinted); + } + self.hinted += usize::from(hinted); + } + /// A locator located or published authoritatively, without touching recency. + pub(crate) fn authoritative(&self, id: &ObjectId) -> Option { + self.entries + .get(id) + .filter(|entry| !entry.hinted) + .map(|entry| entry.row) } - pub(crate) fn insert(&mut self, id: ObjectId, row: LocatedObject) { - self.entries.insert( - id, - Entry { - row, - referenced: Cell::new(true), - }, - ); + pub(crate) fn is_hinted(&self, id: &ObjectId) -> bool { + self.entries.get(id).is_some_and(|entry| entry.hinted) + } + /// Removes every hinted locator; returns how many there were. + pub(crate) fn remove_hinted(&mut self) -> usize { + if self.hinted == 0 { + return 0; + } + let before = self.entries.len(); + self.entries.retain(|_, entry| !entry.hinted); + self.hinted = 0; + before - self.entries.len() + } + /// Keeps every hinted locator as authoritative; returns how many. + pub(crate) fn promote_hinted(&mut self) -> usize { + for entry in self.entries.values_mut() { + entry.hinted = false; + } + std::mem::take(&mut self.hinted) } /// Fixed/live field bytes beyond the original map and LocatedObject values. /// BTree node capacity and allocator overhead are not included in this count. @@ -89,7 +131,7 @@ impl LocatorCache { work.second_chances += 1; continue; } - self.entries.remove(&id); + self.remove(&id); work.removed += 1; return true; } diff --git a/core/crates/layerfs-storage/src/read/mod.rs b/core/crates/layerfs-storage/src/read/mod.rs index 22f15fdc01..7227ca32d5 100644 --- a/core/crates/layerfs-storage/src/read/mod.rs +++ b/core/crates/layerfs-storage/src/read/mod.rs @@ -2,6 +2,7 @@ mod counters; mod fetch; +mod hints; mod length; mod locator_cache; mod objects; @@ -11,4 +12,5 @@ mod units; pub use counters::Diagnostics; pub(crate) use fetch::Fetch; +pub(crate) use hints::hint_failure; pub use provider::{KeptReads, ReadCache, Reader}; diff --git a/core/crates/layerfs-storage/src/read/objects.rs b/core/crates/layerfs-storage/src/read/objects.rs index 45fe173ce3..4b1ab56ef7 100644 --- a/core/crates/layerfs-storage/src/read/objects.rs +++ b/core/crates/layerfs-storage/src/read/objects.rs @@ -109,7 +109,7 @@ impl ReadState { actual: ids.len() as u64, }); } - source.begin_demand(); + source.begin_demand(true); self.pool.forget_prepared(); source.locate(ids)?; let roots = ids @@ -141,22 +141,32 @@ impl ReadState { (row.pack_id, row.group_number, row.record_number) }); let mut out = vec![Vec::new(); ids.len()]; + let sorted: Vec<_> = order.iter().map(|p| roots[*p]).collect(); // A demand whose packs pass the pack cache's bound is served one // cohort of packs at a time, each within the bound, so a pack it - // acquires stays cached until its objects are resolved (#97). + // acquires stays cached until its objects are resolved (#97). When + // the locate returned chains (#758), a cohort is the roots one page + // of groups covers, their chains' included, in one call. let mut start = 0; while start < order.len() { - let end = start + source.cohort(order[start..].iter().map(|p| roots[*p].pack_id)); - let cohort: Vec<_> = order[start..end].iter().map(|p| roots[*p]).collect(); - let located: Vec = cohort.iter().map(|row| row.pack_id).collect(); - source.whole_packs(&located, &mut self.packs)?; - let prefetch = prefetch::chains( - source, - &cohort, - &mut self.packs, - workspace, - &mut self.groups, - )?; + let paged = source.page(sorted[start..].chunks(1), &mut self.packs)?; + let end = start + + match paged { + 0 => source.cohort(sorted[start..].iter().map(|row| row.pack_id)), + covered => covered, + }; + let cohort = &sorted[start..end]; + if paged == 0 { + let located: Vec = cohort.iter().map(|row| row.pack_id).collect(); + source.whole_packs(&located, &mut self.packs)?; + } + let mut walk = + || prefetch::chains(source, cohort, &mut self.packs, workspace, &mut self.groups); + // A walk a stale hint broke runs once more without hints. + let prefetch = match walk() { + Err(error) if super::hint_failure(&error) && source.drop_hints(&[])? => walk()?, + other => other?, + }; self.prefetch_pool.accumulate(prefetch); let mut from = start; while from < end { diff --git a/core/crates/layerfs-storage/src/read/prefetch.rs b/core/crates/layerfs-storage/src/read/prefetch.rs index a9aa4a8557..6f76461405 100644 --- a/core/crates/layerfs-storage/src/read/prefetch.rs +++ b/core/crates/layerfs-storage/src/read/prefetch.rs @@ -20,14 +20,17 @@ pub(crate) fn chains( let mut frontier = roots.to_vec(); let mut visited = BTreeSet::new(); let mut pooled = crate::encoding::pool::PoolReadCounters::default(); - for _ in 0..=layerfs_content::MAXIMUM_DELTA_MAX_DEPTH { + for level in 0..=layerfs_content::MAXIMUM_DELTA_MAX_DEPTH { if frontier.is_empty() { return Ok(pooled); } + // One call for the frontier's and its chains' uncached groups (#758). + source.prefetch_groups(&frontier, packs)?; // Consume each byte-bounded physical cohort before acquiring another. // Discovery and reconstruction share the owning operation's group cache. frontier.sort_unstable_by_key(|row| (row.pack_id, row.group_number, row.record_number)); let mut next = BTreeSet::new(); + let mut edges = Vec::new(); let mut from = 0; let mut decodes = 0; while from < frontier.len() { @@ -49,11 +52,13 @@ pub(crate) fn chains( continue; } let before = decodes; - if let Some(base) = - stored_base(source, packs, groups, workspace, &mut decodes, location)? - { - next.insert(base); + let unhinted = level == 0 && !source.has_hint(location.object_id); + let base = stored_base(source, packs, groups, workspace, &mut decodes, location)?; + if unhinted && base.is_some() { + source.note(|c| c.chain_unhinted_roots += 1); } + edges.extend(base.map(|base| (*location, base))); + next.extend(base); if location.role == layerfs_content::ObjectRole::InodeLeaf && decodes > before { pooled.physical_group_decodes += decodes - before; pooled.physical_group_decoded_bytes += groups @@ -66,7 +71,10 @@ pub(crate) fn chains( } source.note(|c| c.prefetch_group_decodes += decodes); let ids: Vec = next.into_iter().collect(); - source.locate(&ids)?; + // One locate for this level's bases and the deeper bases its chains + // let the cached records name (#758): authoritative rows only. + let ahead = source.chain_ahead(&ids, &edges, packs, groups, workspace); + source.locate(&[ids.as_slice(), ahead.as_slice()].concat())?; frontier = ids .into_iter() .filter(|id| !visited.contains(id)) diff --git a/core/crates/layerfs-storage/src/read/units.rs b/core/crates/layerfs-storage/src/read/units.rs index 7e95f9c54b..7fc6ecc958 100644 --- a/core/crates/layerfs-storage/src/read/units.rs +++ b/core/crates/layerfs-storage/src/read/units.rs @@ -11,6 +11,8 @@ pub(crate) struct GroupPlan<'a> { groups: &'a [usize], whole_for_reuse: bool, whole_bytes: usize, + /// A group read's plan (#758): ranges however sparse or many they are. + ranged: bool, pub(crate) error: Option, pub(crate) selected_info: Option, pub(crate) selected_choice: Option, @@ -29,12 +31,22 @@ impl<'a> GroupPlan<'a> { groups, whole_for_reuse, whole_bytes, + ranged: false, error: None, selected_info: None, selected_choice: None, whole_reason: None, } } + /// A group read's plan: whole only for a singleton or a pack within the + /// control prefix, else the groups' ranges, all in one call. + pub(crate) fn ranged(id: i64, groups: &'a [usize]) -> Self { + let plan = Self::new(id, groups, false, crate::port::PACK_READ_PREFIX_BYTES); + Self { + ranged: true, + ..plan + } + } fn choice(&mut self, info: PackInfo, prefix: &[u8]) -> StorageResult { if info.pack_id != self.id || self.groups.is_empty() @@ -77,7 +89,7 @@ impl<'a> GroupPlan<'a> { Some("singleton") } else if info.length <= self.whole_bytes.max(crate::port::PACK_READ_PREFIX_BYTES) { Some("small") - } else if useful >= info.length.div_ceil(2) || ranges.len() > 4 { + } else if !self.ranged && (useful >= info.length.div_ceil(2) || ranges.len() > 4) { Some("density") } else if self.whole_for_reuse { Some("reuse") diff --git a/core/crates/layerfs-storage/src/save/provider.rs b/core/crates/layerfs-storage/src/save/provider.rs index 35cad899d5..244b03576a 100644 --- a/core/crates/layerfs-storage/src/save/provider.rs +++ b/core/crates/layerfs-storage/src/save/provider.rs @@ -27,7 +27,7 @@ impl Save<'_> { actual: ids.len() as u64, }); } - state.storage.source.begin_demand(); + state.storage.source.begin_demand(false); // This Save's own pending and sealed objects are read from it; only // the rest are located in the Store. let stored: Vec = ids diff --git a/core/crates/layerfs-storage/src/save/publication.rs b/core/crates/layerfs-storage/src/save/publication.rs index 7ae7ba9d77..beb0f2c229 100644 --- a/core/crates/layerfs-storage/src/save/publication.rs +++ b/core/crates/layerfs-storage/src/save/publication.rs @@ -55,7 +55,7 @@ impl State<'_> { .ready .iter() .flat_map(|p| &p.members) - .map(|(l, m)| (l.object_id, (*l, m.references.clone(), m.prefix))) + .map(|(l, m)| (l.object_id, (*l, m.references.clone(), m.base.is_some()))) .collect(); let external: Vec<_> = members .values() @@ -256,7 +256,12 @@ impl State<'_> { .map(|id| self.resolve(*id)) .collect::>>()?; self.storage.source.invalidate(&ids); - let actual = self.storage.reader()?.read_objects(&ids)?; + // The winners are read as this Save reads (#758): no chain member + // is bound, so the Save's later walks see authoritative locators. + let actual = { + let _save = self.storage.source.save_reads(); + self.storage.reader()?.read_objects(&ids)? + }; for ((id, expected), actual) in ids.iter().zip(expected).zip(actual) { let winner = self .storage diff --git a/core/crates/layerfs-storage/src/save/seal.rs b/core/crates/layerfs-storage/src/save/seal.rs index c152b348f4..01d3d36e7c 100644 --- a/core/crates/layerfs-storage/src/save/seal.rs +++ b/core/crates/layerfs-storage/src/save/seal.rs @@ -17,7 +17,8 @@ pub(super) struct Member { pub(super) role: ObjectRole, pub(super) length: usize, pub(super) references: Vec, - pub(super) prefix: bool, + /// The record's delta base; `None` for a FULL record. + pub(super) base: Option, } #[derive(Default)] pub(super) struct Group { @@ -260,6 +261,7 @@ impl Packer { pack_id, group_number, record_number, + base: member.base, }, member, )); diff --git a/core/crates/layerfs-storage/src/save/select.rs b/core/crates/layerfs-storage/src/save/select.rs index c7a70a78ed..4bfea9d24e 100644 --- a/core/crates/layerfs-storage/src/save/select.rs +++ b/core/crates/layerfs-storage/src/save/select.rs @@ -169,7 +169,7 @@ impl State<'_> { role: object.role(), length: object.canonical_len(), references, - prefix: record.base.is_some(), + base: record.base, }); if lane == PackLane::Singleton { self.packer.seal( diff --git a/core/crates/layerfs-storage/src/save/source.rs b/core/crates/layerfs-storage/src/save/source.rs index 92d6b2956c..7ccf698ddf 100644 --- a/core/crates/layerfs-storage/src/save/source.rs +++ b/core/crates/layerfs-storage/src/save/source.rs @@ -120,4 +120,23 @@ impl Source for WaveSource<'_> { fn note_pack_cache_hit(&self) { self.fetch.note_pack_cache_hit(); } + fn prefetch_chain( + &self, + location: &ObjectLocation, + packs: &mut crate::encoding::PackCache, + ) -> StorageResult<()> { + match self.packer.location(location.object_id) { + Some(_) => Ok(()), + None => self.fetch.prefetch_chain(location, packs), + } + } + fn bind_base(&self, child: &ObjectLocation, base: Option) -> StorageResult<()> { + self.fetch.bind_base(child, base) + } + fn hinted(&self, id: ObjectId) -> bool { + self.packer.location(id).is_none() && self.fetch.hinted(id) + } + fn drop_hints(&self, chain: &[ObjectId]) -> StorageResult { + self.fetch.drop_hints(chain) + } } diff --git a/core/crates/layerfs-storage/src/save/wave.rs b/core/crates/layerfs-storage/src/save/wave.rs index 75594eca92..1b8b2e1d59 100644 --- a/core/crates/layerfs-storage/src/save/wave.rs +++ b/core/crates/layerfs-storage/src/save/wave.rs @@ -1,12 +1,17 @@ //! Membership, exact reuse and one preparation wave. use super::{source::WaveSource, state::State}; use crate::{ - encoding::delta::read::{BodyCaches, Resolver}, + encoding::{ + delta::read::{BodyCaches, ChainCounters, Resolver}, + pool::{branch::is_program_role, read::PooledCaches, PoolReader}, + }, error::{StorageError, StorageResult}, + location::ObjectLocation, policy::READ_OBJECT_LIMIT, + read::hint_failure, source::Source, }; -use layerfs_content::{FinalizedObject, ObjectId}; +use layerfs_content::{FinalizedObject, ObjectId, ObjectRole}; use std::collections::{BTreeMap, BTreeSet}; impl State<'_> { pub(super) fn reserve_packs(&mut self, required: usize) -> StorageResult<()> { @@ -40,7 +45,7 @@ impl State<'_> { if objects.is_empty() { return Ok(()); } - self.storage.source.begin_demand(); + self.storage.source.begin_demand(false); let mut prepared = BTreeMap::::new(); let mut start = 0; while start < objects.len() { @@ -52,17 +57,44 @@ impl State<'_> { let membership = self.storage.work.span(super::Stage::Membership); let (end, ids) = demand(&objects, start); self.storage.source.locate(&ids)?; + // The stored bases, none of them private to the Save, of each + // object that is not stored itself (an exact reuse reads none). + let fetch = &self.storage.source; + let bases: Vec> = objects[start..end] + .iter() + .map( + |object| match fetch.located(std::iter::once(object.id())).is_empty() { + true => { + let ids = object.predecessors().ids(); + fetch.located(ids.filter(|id| self.packer.location(*id).is_none())) + } + false => Vec::new(), + }, + ) + .collect(); + drop(membership); // Exact reuse and representation selection walk and authenticate // their own required chains. Consume those inputs with the object // demand: a wave-wide physical prewalk can exceed retention and // evict them before admission, or acquire candidates selection - // never needs. - drop(membership); - let admission = self.storage.work.span(super::Stage::Admission); - for index in start..end { - self.admit(&objects, index, &mut prepared)?; + // never needs. When the provider batches chains (#758), the + // objects are admitted a page at a time: one group read holds + // their bases' chains, consumed before the next. + let mut index = start; + while index < end { + let admission = self.storage.work.span(super::Stage::Admission); + let pages = bases[index - start..].iter().map(Vec::as_slice); + let next = match self.storage.source.page(pages, &mut self.packs)? { + 0 => end, + covered => index + covered, + }; + self.verify_bases(&objects[index..next], &bases[index - start..next - start])?; + for at in index..next { + self.admit(&objects, at, &mut prepared)?; + } + drop(admission); + index = next; } - drop(admission); start = end; } let flush = self.storage.work.span(super::Stage::Flush); @@ -129,6 +161,119 @@ impl State<'_> { } Ok(()) } + /// Rebuilds the stored base of each object whose chain selection may walk + /// and that came with a chain, binding its members (#758), and keeps the + /// bound locators as authoritative once the rebuild has hashed every + /// element of the chain, so selection walks those chains with no locate + /// per level. Selection still sees authoritative locators only: an + /// element whose hash failed is never kept, the rebuild falls back to + /// authoritative locates (a stale hint, counted), and a chain with no + /// member is walked as before. A program page is rebuilt by a pool + /// reader of its own (its counts are not the Save's): that reader has no + /// rebuild, so a failure at an element a hint located drops every hint + /// (counted) and selection walks that chain from authoritative locates, + /// as it did before; any other failure is the Save's. + fn verify_bases( + &mut self, + objects: &[FinalizedObject], + bases: &[Vec], + ) -> StorageResult<()> { + let fetch = &self.storage.source; + let mut seen = BTreeSet::new(); + let chained: Vec = objects + .iter() + .zip(bases) + .filter_map(|(object, stored)| self.walked_base(object, stored)) + .filter(|base| fetch.has_hint(base.object_id)) + .filter(|base| seen.insert(base.object_id)) + .collect(); + if chained.is_empty() { + return Ok(()); + } + let _bind = fetch.binding(); + let _pages = fetch.binding_pages(); + let view = WaveSource { + fetch, + packer: &self.packer, + signatures: &self.signatures, + values: &self.values, + }; + let capacities = self.storage.capacities(); + let mut counters = ChainCounters::default(); + let mut pages = PoolReader::new(); + for base in chained { + // A stale hint on an earlier base drops every hint. + if !fetch.has_hint(base.object_id) { + continue; + } + if is_program_role(base.role) { + let stale_before = fetch.counters().chain_hint_stale; + let caches = PooledCaches { + encoded: &mut self.packs, + decoded: &mut self.groups, + }; + let rebuilt = pages.branch_canonical_with_caches( + &view, + &capacities, + i64::MAX, + &mut self.decode, + base, + Some(caches), + ); + match rebuilt { + Ok(_) => {} + Err(error) if hint_failure(&error) && pages.hint_blamed() => { + // One stale hint, counted once. + let counted = fetch.counters().chain_hint_stale > stale_before; + fetch.hint_stale(counted)?; + continue; + } + Err(error) => return Err(error), + } + } else { + Resolver::new( + &view, + i64::MAX, + &capacities, + BodyCaches { + packs: &mut self.packs, + pool: &mut self.pool, + }, + &mut self.groups, + &mut self.decode, + &mut counters, + ) + .resolve_at(base)?; + } + fetch.promote_hints(); + } + Ok(()) + } + /// The stored base whose chain selection may walk for `object`, among + /// `stored` (its stored predecessors, none private, in order), if it is + /// one a Save checks. Wider than selection: `object` may still turn out + /// private to this Save or repeated in the wave (never selected), and an + /// ordinary role whose selection walks no base is checked too. A program + /// page's is its first advisory predecessor when stored with the page's + /// role (`encoding::delta::branch::trial`); + /// any other object's is its first stored predecessor of an ordinary + /// role, unless the Save already knows its depth. Pooled leaves bind no + /// member (`Fetch::bind`). + fn walked_base( + &self, + object: &FinalizedObject, + stored: &[ObjectLocation], + ) -> Option { + let base = stored.first().copied()?; + if is_program_role(object.role()) { + let first = object.predecessors().ids().next()?; + return (base.object_id == first && base.role == object.role()).then_some(base); + } + (base.role != ObjectRole::InodeLeaf + && !is_program_role(base.role) + && !self.depths.knows(base.object_id)) + .then_some(base) + } pub(super) fn flush_signatures(&mut self) -> StorageResult<()> { let view = WaveSource { fetch: &self.storage.source, diff --git a/core/crates/layerfs-storage/src/store/handle.rs b/core/crates/layerfs-storage/src/store/handle.rs index 7d52b5830f..6707efee8f 100644 --- a/core/crates/layerfs-storage/src/store/handle.rs +++ b/core/crates/layerfs-storage/src/store/handle.rs @@ -34,6 +34,7 @@ impl Storage { let policy = source.metadata.policy()?.validated()?; let capacities = StorageCapacities::from_policy(policy)? .with_publication_bytes(source.metadata.publication_bytes())?; + source.capacities.set(Some(capacities)); Ok(Self { source, work: crate::save::Work::default(), @@ -70,6 +71,12 @@ impl Storage { pub fn save_work(&self) -> crate::save::SaveHistory { self.work.snapshot() } + /// For tests and benches only: a stale delta-chain hint fails as + /// `Integrity("delta chain hint")` instead of falling back to a + /// level-by-level read, so a broken hint invariant fails a check (#758). + pub fn set_strict_hints(&self, strict: bool) { + self.source.strict_hints.set(strict); + } /// Cumulative operation counts, labelled diagnostics; no timing claims. pub fn diagnostics(&self) -> Diagnostics { self.source.counters() diff --git a/core/crates/layerfs-storage/src/store/location.rs b/core/crates/layerfs-storage/src/store/location.rs index 19b45518ae..20a92ccf5b 100644 --- a/core/crates/layerfs-storage/src/store/location.rs +++ b/core/crates/layerfs-storage/src/store/location.rs @@ -17,6 +17,10 @@ pub struct ObjectLocation { pub group_number: usize, /// Record ordinal inside the group. pub record_number: usize, + /// The direct delta base the record names, `None` when it is FULL (#758). + /// A publish input: the provider derives what it stores from it. Rows + /// read back carry `None` unless the provider stores base ids. + pub base: Option, } /// One stored inode value: the row a pooled leaf names by its ordinal. @@ -82,3 +86,49 @@ pub struct LocatedObject { /// Immutable body descriptor. pub pack: PackInfo, } + +/// One member of a located delta chain, nearest base first (#758). It is a +/// hint about where a base is stored: the reader binds it to the base the +/// child record names and verifies it before use. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ChainMember { + /// The member's id when the provider stores ids; `None` from a physical + /// list, where the reader binds the id the child record names. + pub object_id: Option, + /// The pack holding the member's record. + pub pack: PackInfo, + /// Group ordinal inside the pack. + pub group_number: usize, + /// Record ordinal inside the group. + pub record_number: usize, + /// Canonical length of the member object. + pub canonical_length: usize, +} + +/// One located delta root's chain: every member down to its FULL record. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LocatedChain { + /// A root the caller asked to locate. + pub root: ObjectId, + /// Members, nearest base first; the last one is the FULL record. + pub members: Vec, +} + +/// A pack's control header and group directory, `body[0..body_offset)`. +/// Untrusted: the reader parses it against the pack length before use. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PackDirectory { + /// The pack these bytes open. + pub pack: PackInfo, + /// The pack's first `body_offset` bytes. + pub prefix: Vec, +} + +/// What a chain locate returns beside the located rows. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct LocatedChains { + /// At most one chain per located root. + pub chains: Vec, + /// Directories of packs the rows or members name, where known. + pub directories: Vec, +} diff --git a/core/crates/layerfs-storage/src/store/source.rs b/core/crates/layerfs-storage/src/store/source.rs index 88418224f3..f1a4112aa6 100644 --- a/core/crates/layerfs-storage/src/store/source.rs +++ b/core/crates/layerfs-storage/src/store/source.rs @@ -58,6 +58,31 @@ pub trait Source { fn note_pack_directory_validation(&self, _groups: usize, _entries: usize) {} /// Records capacity eviction of real acquired bodies, never private invalidation. fn note_pack_evictions(&self, _entries: u64, _bytes: u64) {} + /// Before a walk reads `location`'s group: fetches it together with the + /// groups of its recorded delta chain (#758). Default: nothing. + fn prefetch_chain( + &self, + _location: &ObjectLocation, + _packs: &mut crate::encoding::PackCache, + ) -> StorageResult<()> { + Ok(()) + } + /// The walk decoded `base` from `child`'s record: binds and checks the + /// chain member there, if any (#758). Default: nothing. + fn bind_base(&self, _child: &ObjectLocation, _base: Option) -> StorageResult<()> { + Ok(()) + } + /// Whether `id`'s locator came from a chain hint (#758) and is not + /// authoritative. Default: never. + fn hinted(&self, _id: ObjectId) -> bool { + false + } + /// After a failure a stale hint may have caused on the walk of `chain` + /// (empty: any walk): drops every hint; true when a hinted locator was on + /// it, so the caller rebuilds once. + fn drop_hints(&self, _chain: &[ObjectId]) -> StorageResult { + Ok(false) + } /// Stores the bounded signature changes in the caller's transaction. fn write_signatures(&self, rows: &[SignatureRow]) -> StorageResult; } diff --git a/core/crates/layerfs-storage/tests/chain_hints.rs b/core/crates/layerfs-storage/tests/chain_hints.rs new file mode 100644 index 0000000000..c6fbf4f835 --- /dev/null +++ b/core/crates/layerfs-storage/tests/chain_hints.rs @@ -0,0 +1,1474 @@ +//! Delta-chain hints (#758): a chain locate lets a read walk every level with +//! no further locate, a hint that disagrees with its record or its bytes is +//! dropped and counted while the read stays correct, strict handles fail on +//! it, a malformed answer fails hard and keeps nothing, a Save binds members +//! only to rebuild and hash its bases (keeping what passed), a hinted locator +//! serves one demand, and a Store without chains costs exactly the default +//! calls. +#[path = "support/chain_provider.rs"] +mod chains; +#[path = "support/memory_metadata.rs"] +mod metadata; + +use chains::{copy, depth, history, history_with, read, ChainProvider, Shape}; +use layerfs_content::filesystem::directory::{apply_bindings, build_directory}; +use layerfs_content::filesystem::{DirectoryRoot, FilesystemObjects, PathName}; +use layerfs_content::{ + AdvisoryPredecessors, ContentResult, FinalizedConsumer, FinalizedObject, ObjectId, ObjectRole, +}; +use layerfs_storage::{ + encoding::delta::edge::RecordDirectory, + location::{ChainMember, LocatedChains}, + pack::layout, + policy::{CANONICAL_LIMIT, GROUP_COUNT_LIMIT, RECORD_COUNT_LIMIT}, + port::ObjectKey, + Storage, StorageCapacities, StorageError, StoragePolicy, +}; +use std::sync::{Arc, Mutex}; + +const EDITS: Shape = Shape { + files: 4, + versions: 8, + size: 24_000, + rewrite: false, + reopen: None, +}; + +fn refused(got: &layerfs_storage::StorageResult>>, reason: &str) { + assert!( + matches!(got, Err(StorageError::Integrity(found)) if *found == reason), + "{got:?}" + ); +} + +fn chain_port(memory: &metadata::MemoryMetadata) -> ChainProvider { + ChainProvider::new(copy(memory)) +} + +fn editing( + mut provider: ChainProvider, + edit: impl FnMut(&mut LocatedChains) + Send + 'static, +) -> Arc { + provider.edit = std::sync::Mutex::new(Some(Box::new(edit))); + Arc::new(provider) +} + +#[test] +fn a_hinted_chain_walk_sends_one_locate_and_one_group_read() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let levels = depth(&memory, root); + assert!(levels >= 5, "fixture chain depth {levels}"); + let plain = copy(&memory); + let (expected, before) = read(plain.clone(), &[root], true); + let expected = expected.unwrap(); + assert_eq!( + before.locate, + levels as u64 + 1, + "today: one locate per level" + ); + for ids in [false, true] { + let mut provider = chain_port(&memory); + provider.ids = ids; + let provider = Arc::new(provider); + let (got, after) = read(provider.clone(), &[root], true); + assert_eq!(got.unwrap(), expected); + assert_eq!(provider.calls("locate"), 1); + assert_eq!(after.locate, 1); + assert_eq!(provider.calls("read_groups"), 1); + assert_eq!(provider.calls("read_scoped_pack"), 0); + assert_eq!(provider.calls("read_packs"), 0); + assert_eq!(after.group_reads, 1); + assert_eq!(after.chain_rows, 1); + assert_eq!(after.chain_members, levels as u64); + assert_eq!(after.chain_hinted_bases, levels as u64); + assert_eq!(after.chain_hint_stale, 0); + assert_eq!(after.chain_unhinted_roots, 0); + } +} + +#[test] +fn saves_through_a_chain_port_store_what_the_default_port_stores() { + // The last Save runs on a fresh handle, so its bases are located again. + let shape = Shape { + reopen: Some(EDITS.versions - 1), + ..EDITS + }; + let (plain, plain_roots, _) = history(shape, |m| m); + let (hinted, hinted_roots, work) = history(shape, |m| Arc::new(ChainProvider::new(m))); + assert_eq!(plain_roots, hinted_roots); + let (plain, hinted) = (plain.state.lock().unwrap(), hinted.state.lock().unwrap()); + assert_eq!(plain.objects, hinted.objects); + assert_eq!(plain.packs, hinted.packs); + assert!(work.chain_rows > 0, "Saves located chains"); + assert_eq!(work.chain_hint_stale, 0); +} + +#[test] +fn a_fresh_handle_save_rebuilds_its_bases_without_a_locate_per_level() { + // 24 files whose bases are chains of depth >= 7; the last Save opens a + // fresh handle, so none of its bases' chain elements is located yet. + let shape = Shape { + files: 24, + versions: 9, + reopen: Some(8), + ..EDITS + }; + let last = shape.versions - 1; + let count = |calls: &[(&str, usize)], name| calls.iter().filter(|c| c.0 == name).count(); + let (plain, roots, _) = history(shape, |m| m); + let levels = roots.iter().map(|root| depth(&plain, *root)).min().unwrap(); + assert!(levels >= 7, "fixture depth {levels}"); + let plain_save = last_save(&plain, last); + // Today: a locate per base per level. + assert!(count(&plain_save, "locate") >= shape.files * (levels - 1)); + for batched in [false, true] { + let mut work = None; + let (memory, hinted_roots, _) = history_with( + shape, + |m| { + let mut provider = ChainProvider::new(m); + provider.batched = batched; + Arc::new(provider) + }, + |storage, objects| { + let before = storage.diagnostics(); + let save = storage.begin_save().unwrap(); + for object in objects { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + work = Some((before, storage.diagnostics())); + }, + ); + assert_eq!(roots, hinted_roots); + { + let (a, b) = (plain.state.lock().unwrap(), memory.state.lock().unwrap()); + assert_eq!(a.objects, b.objects, "the same records"); + assert_eq!(a.packs, b.packs, "byte-identical packs"); + } + let (before, after) = work.unwrap(); + let save = last_save(&memory, last); + // The membership locate of each wave and one group read per 2 MiB + // page; every base's chain hashed and kept, none located by level. + let waves = after.locate - before.locate; + let bytes = after.group_read_bytes - before.group_read_bytes; + assert_eq!(count(&save, "locate") as u64, waves, "{save:?}"); + assert!(waves <= 2, "{save:?}"); + assert!( + count(&save, "read_groups") as u64 <= waves + bytes.div_ceil(2 << 20), + "{save:?}" + ); + assert_eq!( + count(&save, "read_scoped_pack") + count(&save, "read_packs"), + 0 + ); + let verified = after.chain_verified_bases - before.chain_verified_bases; + assert!( + verified >= (shape.files * (levels - 1)) as u64, + "{verified}" + ); + assert_eq!(after.chain_hint_stale, 0); + } +} + +/// The calls of the last version's Save, after its construction reads. +fn last_save(memory: &metadata::MemoryMetadata, version: usize) -> Vec<(&'static str, usize)> { + let calls = memory.calls.lock().unwrap(); + let at = calls + .iter() + .rposition(|call| *call == ("save", version)) + .unwrap(); + calls[at + 1..].to_vec() +} + +#[test] +fn a_writer_reads_its_own_bases_chains_in_one_group_read() { + // One writer handle: its own published rows are cached, so no locate + // reaches the provider and only the local chain prefetch can batch. + let shape = Shape { + versions: 9, + ..EDITS + }; + let last = shape.versions - 1; + let (plain, roots, _) = history(shape, |m| m); + let plain_save = last_save(&plain, last); + let count = |calls: &[(&str, usize)], name| calls.iter().filter(|c| c.0 == name).count(); + assert!(depth(&plain, roots[0]) >= 7); + assert!( + count(&plain_save, "read_scoped_pack") >= 7, + "today: a read per level" + ); + for batched in [true, false] { + let (memory, batched_roots, work) = history(shape, |m| { + let mut provider = ChainProvider::new(m); + provider.chains = false; + provider.batched = batched; + Arc::new(provider) + }); + assert_eq!(roots, batched_roots); + { + let (a, b) = (plain.state.lock().unwrap(), memory.state.lock().unwrap()); + assert_eq!(a.objects, b.objects); + assert_eq!(a.packs, b.packs); + } + let save = last_save(&memory, last); + if batched { + assert_eq!(count(&save, "read_groups"), 1, "{save:?}"); + assert_eq!(count(&save, "read_scoped_pack"), 0, "{save:?}"); + assert_eq!(count(&save, "read_packs"), 0, "{save:?}"); + assert_eq!(work.chain_hint_stale, 0); + } else { + assert_eq!(save, plain_save); + assert_eq!(*memory.calls.lock().unwrap(), *plain.calls.lock().unwrap()); + assert_eq!(work.group_reads, 0); + } + } +} + +#[test] +fn a_member_naming_another_base_is_stale_and_the_walk_goes_on_level_by_level() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let levels = depth(&memory, root) as u64; + let (expected, _) = read(copy(&memory), &[root], true); + // Only the root's own chain is wrong; the bases' chains are right. + let wrong = move |chains: &mut LocatedChains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == root) { + chain.members[1].object_id = Some(ObjectId::for_bytes(b"not this base")); + } + }; + for strict in [false, true] { + let mut provider = chain_port(&memory); + provider.ids = true; + let provider = editing(provider, wrong); + let (got, after) = read(provider.clone(), &[root], strict); + assert_eq!(after.chain_hint_stale, 1); + if strict { + refused(&got, "delta chain hint"); + continue; + } + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + // The root's locate, then the authoritative locate of the base the + // stale member named, whose own (right) chain carries the rest. + assert_eq!(after.locate, 2); + assert_eq!(after.chain_rows, 2); + assert_eq!(after.chain_hinted_bases, levels - 1); + } +} + +/// The member of a depth-one chain moved onto another FULL record of the same +/// role: the walk cannot tell, the base's hash at reconstruction can. +fn misplaced_member() -> (Arc, ObjectId, ChainMember) { + let shape = Shape { + versions: 2, + ..EDITS + }; + let (memory, roots, _) = history(shape, |m| m); + assert_eq!(depth(&memory, roots[0]), 1); + let state = memory.state.lock().unwrap(); + let other = state.objects[&state.objects[&roots[1]].base.unwrap()]; + let member = ChainMember { + object_id: None, + pack: state.packs[&other.pack_id].info, + group_number: other.group_number, + record_number: other.record_number, + canonical_length: other.canonical_length, + }; + drop(state); + (memory, roots[0], member) +} + +#[test] +fn a_misplaced_member_fails_its_hash_and_the_read_rebuilds_once() { + let (memory, root, member) = misplaced_member(); + let (expected, _) = read(copy(&memory), &[root], true); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == root) { + chain.members[0] = member; + } + }); + let (got, after) = read(provider.clone(), &[root], strict); + assert_eq!(after.chain_hint_stale, 1); + if strict { + refused(&got, "delta chain hint"); + } else { + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + // The rebuild located the base itself. + assert_eq!(provider.calls("locate"), 2); + } + } +} + +#[test] +fn bytes_that_fail_their_hash_at_the_authoritative_location_stay_a_hard_failure() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + // The last byte of the FULL record at the bottom of the chain. + let (full, at) = { + let state = memory.state.lock().unwrap(); + let mut id = root; + while let Some(base) = state.objects[&id].base { + id = base; + } + let location = state.objects[&id]; + let body = &state.packs[&location.pack_id].body; + let header = layout::parse_header(body).unwrap(); + let view = layout::group_view(body, header, location.group_number).unwrap(); + assert_eq!(view.codec, layout::GroupCodec::Raw, "a stored FULL group"); + let records = RecordDirectory::of(&body[view.start..view.end]).unwrap(); + let (_, end) = records.range(location.record_number).unwrap(); + (location.pack_id, view.start + end - 1) + }; + let provider = chain_port(&memory); + *provider.corrupt_range.lock().unwrap() = Some((full, at)); + let provider = Arc::new(provider); + let (got, after) = read(provider.clone(), &[root], false); + let ranged = provider.requests.lock().unwrap()[0] + .iter() + .any(|read| read.pack.pack_id == full && !read.ranges.is_empty()); + assert!(ranged, "the FULL record's group was read as a range"); + refused(&got, "dependency identity"); + assert_eq!( + after.chain_hint_stale, 1, + "one rebuild, then the failure stands" + ); +} + +#[test] +fn malformed_chain_answers_are_refused() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let cap = StorageCapacities::from_policy(StoragePolicy::frozen_default()) + .unwrap() + .delta_depth_for_role(ObjectRole::WholeFile); + type Edit = fn(&mut LocatedChains, u8); + let edits: [(&str, Edit); 9] = [ + ("unasked root", |c, _| { + c.chains[0].root = ObjectId::for_bytes(b"unasked") + }), + ("two chains for one root", |c, _| { + c.chains.push(c.chains[0].clone()) + }), + ("more members than the role allows", |c, cap| { + let last = *c.chains[0].members.last().unwrap(); + c.chains[0].members.resize(usize::from(cap) + 1, last); + }), + ("no members", |c, _| c.chains[0].members.clear()), + ("group ordinal", |c, _| { + c.chains[0].members[0].group_number = GROUP_COUNT_LIMIT + }), + ("record ordinal", |c, _| { + c.chains[0].members[0].record_number = RECORD_COUNT_LIMIT + }), + ("empty length", |c, _| { + c.chains[0].members[0].canonical_length = 0 + }), + ("length over the limit", |c, _| { + c.chains[0].members[0].canonical_length = CANONICAL_LIMIT + 1 + }), + ("directory short of its body offset", |c, _| { + c.directories[0].prefix.pop(); + }), + ]; + for (name, edit) in edits { + let provider = editing(chain_port(&memory), move |chains| edit(chains, cap)); + let (got, _) = read(provider, &[root], true); + assert!( + matches!(got, Err(StorageError::Integrity("port chain locator"))), + "{name}: {got:?}" + ); + } +} + +#[test] +fn full_rewrites_cost_exactly_the_default_calls() { + let shape = Shape { + versions: 3, + rewrite: true, + ..EDITS + }; + let (plain, roots, plain_work) = history(shape, |m| m); + let (hinted, hinted_roots, hinted_work) = history(shape, |m| Arc::new(ChainProvider::new(m))); + assert_eq!(roots, hinted_roots); + assert!(roots.iter().all(|root| depth(&plain, *root) == 0)); + assert_eq!(*plain.calls.lock().unwrap(), *hinted.calls.lock().unwrap()); + assert_eq!(plain_work, hinted_work); + assert_eq!(hinted_work.chain_rows + hinted_work.group_reads, 0); + let plain_port = copy(&plain); + let hinted_port = Arc::new(chain_port(&plain)); + let (expected, plain_read) = read(plain_port.clone(), &roots, true); + let (got, hinted_read) = read(hinted_port.clone(), &roots, true); + assert_eq!(got.unwrap(), expected.unwrap()); + assert_eq!(plain_read, hinted_read); + assert_eq!( + *plain_port.calls.lock().unwrap(), + *hinted_port.inner.calls.lock().unwrap() + ); +} + +#[test] +fn a_save_that_loses_its_registrations_binds_no_member_reading_the_winners() { + // Another writer publishes the last version's objects, stored against + // their predecessors, just before this Save publishes them without any: + // every registration is lost and the Save reads the winners back through + // a chain locate. The Save's handle is fresh and its Save walks no + // chain, so the winners' deeper bases are not among its locators. + let shape = Shape { + versions: 6, + reopen: Some(5), + ..EDITS + }; + let port: Arc>>> = Arc::default(); + let wrapped = port.clone(); + let mut raced = None; + history_with( + shape, + move |memory| { + let provider = Arc::new(ChainProvider::new(memory)); + *wrapped.lock().unwrap() = Some(provider.clone()); + provider + }, + |storage, objects| { + let provider = port.lock().unwrap().clone().unwrap(); + let (memory, theirs) = (provider.inner.clone(), objects.clone()); + *provider.before_publish.lock().unwrap() = Some(Box::new(move || { + let other = Storage::new(memory).unwrap(); + let save = other.begin_save().unwrap(); + for object in theirs { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + })); + let count = objects.len() as u64; + let before = storage.diagnostics(); + let save = storage.begin_save().unwrap(); + for object in objects { + save.accept(object.with_predecessors(AdvisoryPredecessors::new())) + .unwrap(); + } + let outcome = save.finish().unwrap(); + raced = Some((count, outcome, before, storage.diagnostics())); + }, + ); + let (count, outcome, before, after) = raced.unwrap(); + assert_eq!(outcome.reused, count, "every registration was lost"); + assert!(after.chain_rows > before.chain_rows, "the winners' chains"); + assert_eq!(after.chain_hinted_bases, before.chain_hinted_bases); + assert_eq!(after.chain_hint_stale, 0); +} + +#[test] +fn a_hinted_locator_serves_only_the_demand_that_bound_it() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let base = memory.state.lock().unwrap().objects[&root].base.unwrap(); + let plain = Storage::new(copy(&memory)).unwrap(); + let length = plain.reader().unwrap().file_lengths(&[base]).unwrap(); + let bytes = plain.reader().unwrap().read_objects(&[base]).unwrap(); + for lengths in [true, false] { + let provider = Arc::new(chain_port(&memory)); + let storage = Storage::new(provider.clone()).unwrap(); + storage.set_strict_hints(true); + let reader = storage.reader().unwrap(); + reader.read_objects(&[root]).unwrap(); + let bound = storage.diagnostics(); + assert!( + bound.chain_hinted_bases > 0, + "the first demand bound the base" + ); + // The next demand's root is that base: located again, not served + // from the earlier demand's hint (its length or position). + if lengths { + assert_eq!(reader.file_lengths(&[base]).unwrap(), length); + } else { + assert_eq!(reader.read_objects(&[base]).unwrap(), bytes); + } + let after = storage.diagnostics(); + assert_eq!(after.locate - bound.locate, 1); + assert_eq!(provider.asked.lock().unwrap().last(), Some(&vec![base])); + assert_eq!(after.chain_hint_stale, 0); + } +} + +#[derive(Default)] +struct Emitted(Vec); +impl FinalizedConsumer for Emitted { + fn accept(&mut self, object: FinalizedObject) -> ContentResult<()> { + self.0.push(object); + Ok(()) + } +} + +fn name(serial: u64) -> PathName { + PathName::new(&format!("source-file-{serial:06}.rs")).unwrap() +} + +/// A directory of 4,000 names and three small changes, one Save each, so +/// its pages are stored as programs against the pages they replace. +fn directory_history() -> Arc { + let memory = Arc::new(metadata::MemoryMetadata::default()); + let storage = Storage::new(memory.clone()).unwrap(); + let mut root: Option = None; + for round in 0..4_u64 { + let reader = storage.reader().unwrap(); + let mut emitted = Emitted::default(); + { + let mut objects = FilesystemObjects::new(&reader, &mut emitted); + root = Some(match root { + None => { + build_directory(&mut objects, (1..=4_000).map(|s| Ok((name(s), s)))) + .unwrap() + .0 + } + Some(base) => { + let added = 4_001 + round; + let mut changes = vec![(name(10 + round), None), (name(added), Some(added))]; + changes.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); + apply_bindings( + &mut objects, + Some(base), + changes.into_iter().map(Ok), + layerfs_content::filesystem::MAXIMUM_SCRATCH_BYTES, + &mut |_, _| Ok(()), + ) + .unwrap() + .0 + } + }); + } + drop(reader); + let save = storage.begin_save().unwrap(); + for object in emitted.0 { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + } + memory +} + +#[test] +fn a_program_page_binds_no_member_so_a_misplaced_one_cannot_break_its_read() { + let memory = directory_history(); + let program = |role| { + matches!( + role, + ObjectRole::DirectoryLeaf + | ObjectRole::DirectoryBranch + | ObjectRole::InodeBranch + | ObjectRole::ExtentLeaf + | ObjectRole::ExtentBranch + ) + }; + // A page stored against another, and the member of its chain moved onto + // another page of its role: the pool reader that rebuilds it has no + // rebuild of its own. + let (page, member) = { + let state = memory.state.lock().unwrap(); + let page = *state + .objects + .values() + .find(|row| program(row.role) && row.base.is_some()) + .expect("a page stored as a program"); + let base = state.objects[&page.base.unwrap()]; + let other = state + .objects + .values() + .find(|row| { + row.role == page.role + && row.object_id != base.object_id + && row.object_id != page.object_id + && (row.pack_id, row.group_number, row.record_number) + != (base.pack_id, base.group_number, base.record_number) + }) + .expect("another page of the role"); + let member = ChainMember { + object_id: None, + pack: state.packs[&other.pack_id].info, + group_number: other.group_number, + record_number: other.record_number, + canonical_length: other.canonical_length, + }; + (page.object_id, member) + }; + let (expected, _) = read(copy(&memory), &[page], true); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == page) { + chain.members[0] = member; + } + }); + let (got, after) = read(provider.clone(), &[page], strict); + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + assert!(after.chain_rows > 0, "the page's chain was located"); + assert_eq!(after.chain_hinted_bases, 0); + assert_eq!(after.chain_hint_stale, 0); + } +} + +/// A directory of 4,000 names changed in `rounds` Saves on one handle; the +/// objects of one more change, constructed on that handle, are returned +/// unsaved with the Store, so a fresh handle can Save them. +fn directory_change(rounds: u64) -> (Arc, Vec) { + let memory = Arc::new(metadata::MemoryMetadata::default()); + let storage = Storage::new(memory.clone()).unwrap(); + let mut root: Option = None; + for round in 0..=rounds { + let reader = storage.reader().unwrap(); + let mut emitted = Emitted::default(); + { + let mut objects = FilesystemObjects::new(&reader, &mut emitted); + root = Some(match root { + None => { + build_directory(&mut objects, (1..=4_000).map(|s| Ok((name(s), s)))) + .unwrap() + .0 + } + Some(base) => { + let added = 4_001 + round; + let mut changes = vec![(name(10 + round), None), (name(added), Some(added))]; + changes.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); + apply_bindings( + &mut objects, + Some(base), + changes.into_iter().map(Ok), + layerfs_content::filesystem::MAXIMUM_SCRATCH_BYTES, + &mut |_, _| Ok(()), + ) + .unwrap() + .0 + } + }); + } + drop(reader); + if round == rounds { + return (memory, emitted.0); + } + let save = storage.begin_save().unwrap(); + for object in emitted.0 { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + } + unreachable!() +} + +#[test] +fn a_fresh_handle_save_rebuilds_its_program_page_bases_without_a_locate_per_level() { + // Directory pages stored as programs against the pages they replace, + // chains of depth >= 4; the change is Saved by a fresh handle, so no + // element of its bases' chains is located yet. + let (memory, objects) = directory_change(6); + let program_bases: Vec = objects + .iter() + .filter(|object| object.role() == ObjectRole::DirectoryLeaf) + .filter_map(|object| object.predecessors().ids().next()) + .map(|base| depth(&memory, base)) + .filter(|levels| *levels > 0) + .collect(); + assert!(!program_bases.is_empty(), "a page stored against a program"); + let levels = program_bases.iter().copied().max().unwrap(); + assert!(levels >= 4, "fixture depth {levels}"); + let save = |port: Arc| { + let storage = Storage::new(port).unwrap(); + storage.set_strict_hints(true); + let save = storage.begin_save().unwrap(); + for object in objects.clone() { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + storage.diagnostics() + }; + let plain = copy(&memory); + let plain_work = save(plain.clone()); + let count = |memory: &metadata::MemoryMetadata, name| { + let calls = memory.calls.lock().unwrap(); + calls.iter().filter(|c| c.0 == name).count() + }; + // Today: every level of a program page's chain is located alone. + let today = count(&plain, "locate"); + assert!(today > program_bases.len() * levels, "{plain_work:?}"); + for batched in [false, true] { + let mut provider = chain_port(&memory); + provider.batched = batched; + let provider = Arc::new(provider); + let work = save(provider.clone()); + { + let (a, b) = ( + plain.state.lock().unwrap(), + provider.inner.state.lock().unwrap(), + ); + assert_eq!(a.objects, b.objects, "the same records"); + assert_eq!(a.packs, b.packs, "byte-identical packs"); + } + // The membership locate of each wave and the closure check of its + // publication; every program-page base hashed and kept, none located + // by level. + let locates = count(&provider.inner, "locate"); + assert_eq!(locates as u64, work.locate); + assert!(locates <= 2, "{work:?}"); + assert!( + work.chain_verified_bases >= (program_bases.len() * levels) as u64, + "{work:?}" + ); + assert_eq!(work.chain_hint_stale, 0); + } +} + +/// Saves `objects` on a fresh handle over `port`, with or without strict +/// hints: the outcome, the handle's counts and the handle. +fn fresh_save( + port: Arc, + objects: &[FinalizedObject], + strict: bool, +) -> ( + layerfs_storage::StorageResult<()>, + layerfs_storage::Diagnostics, + Storage, +) { + let storage = Storage::new(port).unwrap(); + storage.set_strict_hints(strict); + let done = (|| { + let save = storage.begin_save()?; + for object in objects { + save.accept(object.clone())?; + } + save.finish().map(drop) + })(); + let work = storage.diagnostics(); + (done, work, storage) +} + +fn is_program(role: ObjectRole) -> bool { + matches!( + role, + ObjectRole::DirectoryLeaf + | ObjectRole::DirectoryBranch + | ObjectRole::InodeBranch + | ObjectRole::ExtentLeaf + | ObjectRole::ExtentBranch + ) +} + +/// The first program page of `objects` whose first predecessor is stored +/// with its role as a program itself: the page's index and that base. +fn program_base( + memory: &metadata::MemoryMetadata, + objects: &[FinalizedObject], +) -> (usize, ObjectId) { + let state = memory.state.lock().unwrap(); + objects + .iter() + .enumerate() + .find_map(|(at, object)| { + let base = object.predecessors().ids().next()?; + let row = state.objects.get(&base)?; + (is_program(object.role()) && row.role == object.role() && row.base.is_some()) + .then_some((at, base)) + }) + .expect("a page whose predecessor is a program") +} + +fn same_store(a: &metadata::MemoryMetadata, b: &metadata::MemoryMetadata) { + let (a, b) = (a.state.lock().unwrap(), b.state.lock().unwrap()); + assert_eq!(a.objects, b.objects, "the same records"); + assert_eq!(a.packs, b.packs, "byte-identical packs"); +} + +#[test] +fn a_misplaced_member_of_a_program_base_fails_its_hash_and_the_save_walks_it_from_locates() { + // The member under a program base, moved onto another page of its role: + // the Save's check of that base fails at the moved element, drops every + // hint and selection walks the chain from authoritative locates. + let (memory, objects) = directory_change(6); + let (_, base) = program_base(&memory, &objects); + let (below, member) = { + let state = memory.state.lock().unwrap(); + let row = state.objects[&base]; + let below = state.objects[&row.base.unwrap()]; + let other = state + .objects + .values() + .find(|other| { + other.role == row.role + && other.object_id != below.object_id + && other.object_id != base + && (other.pack_id, other.group_number, other.record_number) + != (below.pack_id, below.group_number, below.record_number) + }) + .expect("another page of the role"); + let member = ChainMember { + object_id: None, + pack: state.packs[&other.pack_id].info, + group_number: other.group_number, + record_number: other.record_number, + canonical_length: other.canonical_length, + }; + (below.object_id, member) + }; + let plain = copy(&memory); + fresh_save(plain.clone(), &objects, true).0.unwrap(); + let (expected, _) = read(copy(&memory), &[below], true); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == base) { + chain.members[0] = member; + } + }); + let (done, work, storage) = fresh_save(provider.clone(), &objects, strict); + assert!(work.chain_hint_stale >= 1, "{work:?}"); + if strict { + assert!( + matches!(done, Err(StorageError::Integrity("delta chain hint"))), + "{done:?}" + ); + continue; + } + done.unwrap(); + same_store(&plain, &provider.inner); + // No locator at the moved position was kept: the element below the + // base reads back through this handle. + let got = storage.reader().unwrap().read_objects(&[below]); + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + } +} + +/// An object of `role` whose bytes are 2,000 fixed noise bytes with one +/// byte changed by `change`, so versions differ by one byte, and that +/// declare no page role; its predecessor is `base`. +fn noise_page(role: ObjectRole, change: u8, base: Option) -> FinalizedObject { + let mut state = 0x9e37_79b9_u32; + let mut bytes: Vec = (0..2_000) + .map(|_| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .collect(); + bytes[1_000] ^= change; + let canonical = layerfs_content::object::encode_bytes_object(&bytes).unwrap(); + let object = FinalizedObject::new(role, canonical).unwrap(); + match base { + Some(base) => object.with_predecessors(AdvisoryPredecessors::explicit(base).unwrap()), + None => object, + } +} + +/// Two noise pages of `role`, one Save each, the second stored as a program +/// against the first: the Store and the second page's id. +fn noise_history(role: ObjectRole) -> (Arc, ObjectId) { + let memory = Arc::new(metadata::MemoryMetadata::default()); + let storage = Storage::new(memory.clone()).unwrap(); + let mut base = None; + for change in 1..=2 { + let object = noise_page(role, change, base); + base = Some(object.id()); + let save = storage.begin_save().unwrap(); + save.accept(object).unwrap(); + save.finish().unwrap(); + } + let base = base.unwrap(); + assert_eq!(depth(&memory, base), 1, "the second page is a program"); + (memory, base) +} + +#[test] +fn a_hinted_element_whose_page_header_names_another_role_is_not_kept() { + // Pages stored under the directory-leaf role whose bytes declare no + // page role: the catalog says directory leaf, a member carries no role, + // so only the hinted element's authenticated bytes can say otherwise. + let (memory, base) = noise_history(ObjectRole::DirectoryLeaf); + let objects = vec![noise_page(ObjectRole::DirectoryLeaf, 3, Some(base))]; + let plain = copy(&memory); + fresh_save(plain.clone(), &objects, true).0.unwrap(); + assert_eq!(depth(&plain, objects[0].id()), 2); + for strict in [false, true] { + let provider = Arc::new(chain_port(&memory)); + let (done, work, _) = fresh_save(provider.clone(), &objects, strict); + assert_eq!(work.chain_hint_stale, 1, "{work:?}"); + assert_eq!(work.chain_verified_bases, 0, "{work:?}"); + if strict { + assert!( + matches!(done, Err(StorageError::Integrity("delta chain hint"))), + "{done:?}" + ); + continue; + } + done.unwrap(); + same_store(&plain, &provider.inner); + } +} + +#[test] +fn a_program_base_whose_own_row_is_wrong_fails_with_its_own_error_not_as_a_stale_hint() { + // The base's catalog length disagrees with its record: a failure at the + // authoritative root, which no hint below it caused. + let (memory, objects) = directory_change(6); + let (_, base) = program_base(&memory, &objects); + let corrupt = || { + let port = copy(&memory); + port.state + .lock() + .unwrap() + .objects + .get_mut(&base) + .unwrap() + .canonical_length += 1; + port + }; + let (done, _, _) = fresh_save(corrupt(), &objects, true); + let Err(StorageError::Integrity(reason)) = done else { + panic!("{done:?}"); + }; + assert_eq!(reason, "branch delta length"); + for strict in [false, true] { + let provider = Arc::new(ChainProvider::new(corrupt())); + let (done, work, _) = fresh_save(provider, &objects, strict); + assert!( + matches!(done, Err(StorageError::Integrity(found)) if found == reason), + "{done:?}" + ); + assert_eq!(work.chain_hint_stale, 0, "{work:?}"); + } +} + +#[test] +fn a_save_checks_only_the_chain_selection_walks() { + // A directory leaf whose only predecessor is a stored directory branch: + // selection takes no base of another role, so the Save walks none of + // that branch's chain, even one whose root row is wrong. + let (memory, branch) = noise_history(ObjectRole::DirectoryBranch); + let objects = vec![noise_page(ObjectRole::DirectoryLeaf, 3, Some(branch))]; + let corrupt = || { + let port = copy(&memory); + port.state + .lock() + .unwrap() + .objects + .get_mut(&branch) + .unwrap() + .canonical_length += 1; + port + }; + let plain = corrupt(); + fresh_save(plain.clone(), &objects, true).0.unwrap(); + assert_eq!(depth(&plain, objects[0].id()), 0, "no base of another role"); + for strict in [false, true] { + let provider = Arc::new(ChainProvider::new(corrupt())); + let (done, work, _) = fresh_save(provider.clone(), &objects, strict); + done.unwrap(); + assert_eq!(work.chain_hint_stale, 0, "{work:?}"); + same_store(&plain, &provider.inner); + } +} + +#[test] +fn a_pack_descriptor_only_a_stale_member_gave_is_forgotten_with_the_hints() { + // The bottom member names its pack under another digest and a group the + // pack lacks, with a matching directory, so no group read reaches it: the + // walk binds it and fails there. The rebuild then locates that base and + // meets the pack's real descriptor, which must not contradict the + // member's: that descriptor went with the hints. + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let bottom = depth(&memory, root) - 1; + let pack = { + let state = memory.state.lock().unwrap(); + let mut packs = vec![state.objects[&root].pack_id]; + let mut id = root; + while let Some(base) = state.objects[&id].base { + packs.push(state.objects[&base].pack_id); + id = base; + } + let pack = packs.pop().unwrap(); + assert!( + !packs.contains(&pack), + "the bottom member's pack is its own" + ); + state.packs[&pack].info + }; + let named = layerfs_storage::location::PackInfo { + key: ObjectKey::for_bytes(b"another digest"), + ..pack + }; + let (expected, _) = read(copy(&memory), &[root], true); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == root) { + chain.members[bottom].pack = named; + chain.members[bottom].group_number = GROUP_COUNT_LIMIT - 1; + } + for directory in &mut chains.directories { + if directory.pack == pack { + directory.pack = named; + } + } + }); + let (got, after) = read(provider.clone(), &[root], strict); + assert_eq!(after.chain_hint_stale, 1); + if strict { + refused(&got, "delta chain hint"); + continue; + } + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + } +} + +#[test] +fn a_member_pack_that_does_not_answer_as_named_is_stale_and_the_read_goes_on() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let bottom = depth(&memory, root) - 1; + let (expected, _) = read(copy(&memory), &[root], true); + type Wrong = fn(&mut ChainMember); + let cases: [(&str, Wrong); 2] = [ + ("a pack that is not stored", |m| m.pack.pack_id += 1_000_000), + ("another digest", |m| { + m.pack.key = ObjectKey::for_bytes(b"another digest") + }), + ]; + for (name, wrong) in cases { + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == root) { + wrong(&mut chain.members[bottom]); + } + }); + let (got, after) = read(provider.clone(), &[root], strict); + assert_eq!(after.chain_hint_stale, 1, "{name}"); + assert_eq!(provider.calls("read_groups"), 1, "{name}"); + if strict { + refused(&got, "delta chain hint"); + continue; + } + assert_eq!(got.unwrap(), *expected.as_ref().unwrap(), "{name}"); + } + } +} + +#[test] +fn a_provider_defect_on_a_hinted_walk_is_not_replayed() { + let (memory, roots, _) = history(EDITS, |m| m); + let (hinted, unhinted) = (roots[0], roots[1]); + let mut locates = 0; + // The second root comes without a chain, so the walk locates its base + // while the first root's base is bound; that answer is malformed. + let provider = editing(chain_port(&memory), move |chains| { + locates += 1; + chains.chains.retain(|c| c.root != unhinted); + if locates == 2 { + let mut unasked = chains.chains[0].clone(); + unasked.root = ObjectId::for_bytes(b"unasked"); + chains.chains.push(unasked); + } + }); + let (got, after) = read(provider.clone(), &[hinted, unhinted], false); + refused(&got, "port chain locator"); + assert!(after.chain_hinted_bases > 0, "a hinted locator was in use"); + assert_eq!(after.chain_hint_stale, 0); + assert_eq!( + provider.asked.lock().unwrap().len(), + 2, + "no locate after it" + ); +} + +#[test] +fn a_refused_chain_answer_keeps_none_of_its_rows() { + let (memory, roots, _) = history(EDITS, |m| m); + let root = roots[0]; + let (expected, _) = read(copy(&memory), &[root], true); + let mut first = true; + let provider = editing(chain_port(&memory), move |chains| { + if std::mem::take(&mut first) { + chains.chains.push(chains.chains[0].clone()); + } + }); + let storage = Storage::new(provider.clone()).unwrap(); + storage.set_strict_hints(true); + let reader = storage.reader().unwrap(); + refused(&reader.read_objects(&[root]), "port chain locator"); + assert_eq!(reader.read_objects(&[root]).unwrap(), expected.unwrap()); + let asked = provider.asked.lock().unwrap(); + assert_eq!(asked.len(), 2); + assert_eq!(asked[1], vec![root], "the root is located again"); +} + +#[test] +fn a_group_read_admits_its_ranges_when_the_pack_is_dense_in_the_cache() { + let (memory, roots, _) = history(EDITS, |m| m); + // Roots 0, 2 and 3 end in groups 0, 1 and 2 of one pack; by the third + // read the first two hold over half of it, so the cache would take the + // pack whole if it were acquiring it. + { + let state = memory.state.lock().unwrap(); + let bottom = |mut id: ObjectId| { + while let Some(base) = state.objects[&id].base { + id = base; + } + state.objects[&id] + }; + let ends: Vec<_> = [roots[0], roots[2], roots[3]].map(bottom).to_vec(); + assert!(ends.iter().all(|row| row.pack_id == ends[0].pack_id)); + let groups: Vec<_> = ends.iter().map(|row| row.group_number).collect(); + assert_eq!(groups, [0, 1, 2]); + let pack = &state.packs[&ends[0].pack_id]; + let header = layout::parse_header(&pack.body).unwrap(); + let held: usize = (0..2) + .map(|g| { + let view = layout::group_view(&pack.body, header, g).unwrap(); + view.end - view.start + }) + .sum(); + assert!(held >= pack.info.length.div_ceil(2), "fixture density"); + } + let provider = Arc::new(chain_port(&memory)); + let storage = Storage::new(provider.clone()).unwrap(); + storage.set_strict_hints(true); + let reader = storage.reader().unwrap(); + for root in [roots[0], roots[2], roots[3]] { + let (expected, _) = read(copy(&memory), &[root], true); + assert_eq!(reader.read_objects(&[root]).unwrap(), expected.unwrap()); + } + assert_eq!(provider.calls("read_groups"), 3); + assert_eq!(provider.calls("read_scoped_pack"), 0); + assert_eq!(provider.calls("read_packs"), 0); +} + +#[test] +fn a_program_page_read_locates_every_deeper_level_of_its_chain_in_one_locate() { + // A read binds no member of a program page's chain; the levels below + // the first are still located together, from the base ids the cached + // records name, with no member trusted (#758 fix 3). + let (memory, _) = directory_change(6); + let (page, levels) = { + let state = memory.state.lock().unwrap(); + let pages: Vec = state + .objects + .values() + .filter(|row| is_program(row.role) && row.base.is_some()) + .map(|row| row.object_id) + .collect(); + drop(state); + pages + .into_iter() + .map(|page| (page, depth(&memory, page))) + .max_by_key(|(_, levels)| *levels) + .expect("a page stored as a program") + }; + assert!(levels >= 4, "fixture depth {levels}"); + let (expected, today) = read(copy(&memory), &[page], true); + let expected = expected.unwrap(); + assert_eq!(today.locate, levels as u64 + 1, "today: one per level"); + for batched in [false, true] { + let mut provider = chain_port(&memory); + provider.batched = batched; + let provider = Arc::new(provider); + let (got, after) = read(provider.clone(), &[page], true); + assert_eq!(got.unwrap(), expected); + // The page's own locate, then one for every level of its chain. + assert_eq!(after.locate, 2, "{after:?}"); + let asked = provider.asked.lock().unwrap().clone(); + assert_eq!(asked.len(), 2); + assert_eq!(asked[1].len(), levels, "every level's base, located"); + assert_eq!(after.chain_hinted_bases, 0, "no member trusted"); + assert_eq!(after.chain_hint_stale, 0); + } + // A member that names a record off the chain makes the guesses below it + // wrong: the read stays correct, locates those levels as before, and + // counts nothing stale, strict or not. + let other = { + let state = memory.state.lock().unwrap(); + let chain = chain_of(&state.objects, page); + let member = state + .objects + .values() + .find(|other| is_program(other.role) && !chain.contains(&other.object_id)) + .expect("a page outside the chain"); + ChainMember { + object_id: None, + pack: state.packs[&member.pack_id].info, + group_number: member.group_number, + record_number: member.record_number, + canonical_length: member.canonical_length, + } + }; + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == page) { + chain.members[1] = other; + } + }); + let (got, after) = read(provider.clone(), &[page], strict); + assert_eq!(got.unwrap(), expected); + assert!(after.locate > 2, "{after:?}"); + assert!(after.locate <= levels as u64 + 1, "{after:?}"); + assert_eq!(after.chain_hinted_bases, 0); + assert_eq!(after.chain_hint_stale, 0); + } +} + +/// `id`'s stored chain, `id` first. +fn chain_of( + objects: &std::collections::BTreeMap, + id: ObjectId, +) -> Vec { + let mut chain = vec![id]; + while let Some(base) = objects[chain.last().unwrap()].base { + chain.push(base); + } + chain +} + +/// [`directory_change`] with one more change of the same pages Saved on +/// that handle after the returned objects were constructed, so the pages +/// the returned objects replace have stored descendants. +fn directory_change_with_sibling( + rounds: u64, +) -> (Arc, Vec) { + let memory = Arc::new(metadata::MemoryMetadata::default()); + let storage = Storage::new(memory.clone()).unwrap(); + let change = |root: Option, removed: u64, added: u64| { + let reader = storage.reader().unwrap(); + let mut emitted = Emitted::default(); + let root = { + let mut objects = FilesystemObjects::new(&reader, &mut emitted); + match root { + None => { + build_directory(&mut objects, (1..=4_000).map(|s| Ok((name(s), s)))) + .unwrap() + .0 + } + Some(base) => { + let mut changes = vec![(name(removed), None), (name(added), Some(added))]; + changes.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); + apply_bindings( + &mut objects, + Some(base), + changes.into_iter().map(Ok), + layerfs_content::filesystem::MAXIMUM_SCRATCH_BYTES, + &mut |_, _| Ok(()), + ) + .unwrap() + .0 + } + } + }; + (root, emitted.0) + }; + let save = |objects: Vec| { + let save = storage.begin_save().unwrap(); + for object in objects { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + }; + let mut root = None; + for round in 0..rounds { + let (next, objects) = change(root, 10 + round, 4_001 + round); + save(objects); + root = Some(next); + } + let (_, returned) = change(root, 10 + rounds, 4_001 + rounds); + let (_, sibling) = change(root, 11 + rounds, 5_001 + rounds); + save(sibling); + (memory, returned) +} + +#[test] +fn a_hinted_element_whose_record_leads_back_to_an_authoritative_one_is_a_stale_hint() { + // A program base R with a stored descendant S (stored against R): the + // member under R moved onto S's record leads the Save's check from that + // hinted element back to R, located authoritatively, so the walk fails + // as a cycle at an element only an unauthenticated record named. That + // is the hint's failure: counted once (strict refuses) and selection + // walks the chain from authoritative locates; the Save stores what the + // default port stores. + let (memory, objects) = directory_change_with_sibling(6); + let (base, member) = { + let state = memory.state.lock().unwrap(); + let found = objects.iter().find_map(|object| { + let first = object.predecessors().ids().next()?; + let row = state.objects.get(&first)?; + if !is_program(object.role()) || row.role != object.role() || row.base.is_none() { + return None; + } + let descendant = state.objects.values().find(|other| { + other.base == Some(first) && objects.iter().all(|o| o.id() != other.object_id) + })?; + Some((first, *descendant)) + }); + let (base, descendant) = found.expect("a program base with a stored descendant"); + let member = ChainMember { + object_id: None, + pack: state.packs[&descendant.pack_id].info, + group_number: descendant.group_number, + record_number: descendant.record_number, + canonical_length: descendant.canonical_length, + }; + (base, member) + }; + let plain = copy(&memory); + fresh_save(plain.clone(), &objects, true).0.unwrap(); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + for chain in chains.chains.iter_mut().filter(|c| c.root == base) { + chain.members[0] = member; + } + }); + let (done, work, _) = fresh_save(provider.clone(), &objects, strict); + assert_eq!(work.chain_hint_stale, 1, "{done:?} {work:?}"); + if strict { + assert!( + matches!(done, Err(StorageError::Integrity("delta chain hint"))), + "{done:?}" + ); + continue; + } + done.unwrap(); + same_store(&plain, &provider.inner); + } +} + +#[test] +fn an_authoritative_descriptor_that_contradicts_a_member_s_makes_the_hint_stale() { + // Two roots read together whose bases share one pack P. The member under + // the first names P under another digest and a group P lacks (with a + // matching directory), so no group read reaches it and its descriptor + // stays a member's; the second comes with no chain, so its base is + // located at the next level and brings P's real descriptor. That + // contradiction is a stale hint (counted once; strict refuses), every + // hint is dropped, and the read stays correct. + let (memory, roots, _) = history(EDITS, |m| m); + let (first, second, pack) = { + let state = memory.state.lock().unwrap(); + let base = |id: &ObjectId| state.objects[&state.objects[id].base.unwrap()]; + let chained: Vec = roots + .iter() + .copied() + .filter(|id| state.objects[id].base.is_some()) + .collect(); + let (first, second) = chained + .iter() + .flat_map(|a| chained.iter().map(move |b| (*a, *b))) + .find(|(a, b)| a != b && base(a).pack_id == base(b).pack_id) + .expect("two roots whose bases share a pack"); + (first, second, state.packs[&base(&first).pack_id].info) + }; + let named = layerfs_storage::location::PackInfo { + key: ObjectKey::for_bytes(b"another digest"), + ..pack + }; + let (expected, _) = read(copy(&memory), &[first, second], true); + for strict in [false, true] { + let provider = editing(chain_port(&memory), move |chains| { + chains.chains.retain(|c| c.root != second); + for chain in chains.chains.iter_mut().filter(|c| c.root == first) { + chain.members[0].pack = named; + chain.members[0].group_number = GROUP_COUNT_LIMIT - 1; + } + for directory in &mut chains.directories { + if directory.pack == pack { + directory.pack = named; + } + } + }); + let (got, after) = read(provider.clone(), &[first, second], strict); + assert_eq!(after.chain_hint_stale, 1, "{got:?} {after:?}"); + if strict { + refused(&got, "delta chain hint"); + continue; + } + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + assert_eq!(after.chain_hinted_bases, 1, "the member was bound first"); + } +} + +#[test] +fn a_chain_a_read_binds_adds_no_guesses_to_another_chain_s_locate() { + // Two chained roots with disjoint chains, the second answered without + // its chain: the first root's members bind every level of its chain with + // no locate, so the locates the second root's levels make carry none of + // the first chain's ids (fix 3b; before it, the second locate carried the + // first chain's deeper bases as guesses). + let (memory, roots, _) = history(EDITS, |m| m); + let (first, second, first_chain) = { + let state = memory.state.lock().unwrap(); + let chained: Vec = roots + .iter() + .copied() + .filter(|id| state.objects[id].base.is_some()) + .collect(); + let (first, second) = chained + .iter() + .flat_map(|a| chained.iter().map(move |b| (*a, *b))) + .find(|(a, b)| { + let ca = chain_of(&state.objects, *a); + let cb = chain_of(&state.objects, *b); + a != b && ca.iter().all(|x| !cb.contains(x)) + }) + .expect("two chained roots with disjoint chains"); + (first, second, chain_of(&state.objects, first)) + }; + assert!(depth(&memory, first) >= 2, "a chain with deeper levels"); + let (expected, _) = read(copy(&memory), &[first, second], true); + let (_, alone) = read(Arc::new(chain_port(&memory)), &[first], true); + assert!(alone.chain_hinted_bases > 0, "{alone:?}"); + let provider = editing(chain_port(&memory), move |chains| { + chains.chains.retain(|c| c.root != second); + }); + let (got, after) = read(provider.clone(), &[first, second], true); + assert_eq!(got.unwrap(), expected.unwrap()); + let asked = provider.asked.lock().unwrap().clone(); + assert!(asked.len() >= 2, "{asked:?}"); + for (call, ids) in asked.iter().enumerate().skip(1) { + let carried = ids.iter().filter(|id| first_chain.contains(id)).count(); + assert_eq!(carried, 0, "locate {call} carries the bound chain's ids"); + } + // Every level of the first chain is bound (here by the level walk and + // again by the resolution), never located. + assert!( + after.chain_hinted_bases >= alone.chain_hinted_bases, + "{after:?}" + ); + assert_eq!(after.chain_hint_stale, 0); +} + +#[test] +fn guesses_decode_each_group_once_per_level_and_count_it() { + // Every program page of a changed directory read at once: their chains' + // records lie in the groups of the Saves that wrote them, which several + // pages share. A level's guesses decode each such group at most once and + // count it in `prefetch_group_decodes` (fix 3b; before it, they decoded + // a shared group once per page and counted nothing). + let (memory, _) = directory_change(6); + let (pages, chain_groups) = { + let state = memory.state.lock().unwrap(); + let pages: Vec = state + .objects + .values() + .filter(|row| is_program(row.role) && row.base.is_some()) + .map(|row| row.object_id) + .collect(); + let groups: std::collections::BTreeSet<(i64, usize)> = pages + .iter() + .flat_map(|page| chain_of(&state.objects, *page).into_iter().skip(1)) + .map(|id| (state.objects[&id].pack_id, state.objects[&id].group_number)) + .collect(); + (pages, groups.len() as u64) + }; + assert!(pages.len() >= 2, "several program pages"); + let (expected, plain) = read(copy(&memory), &pages, true); + let provider = Arc::new(chain_port(&memory)); + let (got, after) = read(provider, &pages, true); + assert_eq!(got.unwrap(), expected.unwrap()); + assert_eq!(after.chain_hinted_bases, 0, "no member trusted"); + let guessed = after + .prefetch_group_decodes + .saturating_sub(plain.prefetch_group_decodes); + assert!(guessed >= 1, "the guesses' decodes are counted: {after:?}"); + assert!( + guessed <= chain_groups, + "at most once per group: {guessed} > {chain_groups}" + ); +} diff --git a/core/crates/layerfs-storage/tests/group_reads.rs b/core/crates/layerfs-storage/tests/group_reads.rs new file mode 100644 index 0000000000..ffdadf1855 --- /dev/null +++ b/core/crates/layerfs-storage/tests/group_reads.rs @@ -0,0 +1,218 @@ +//! Group reads (#758): needed groups of several packs come back in one call +//! as ranges or whole packs, in request order and within the cache bound; a +//! cached unit refuses its pack under another digest; ranged bytes are +//! authenticated by the objects rebuilt from them. +#[path = "support/chain_provider.rs"] +mod chains; +#[path = "support/memory_metadata.rs"] +mod metadata; + +use chains::{copy, history, read, ChainProvider, Shape}; +use layerfs_content::ObjectId; +use layerfs_storage::{ + encoding::{PackAcquisition, PackCache, PackUnit}, + location::{ObjectLocation, PackInfo, SignatureRow}, + pack::layout, + port::{ + AcquiredPackRead, ObjectKey, PackRange, PackReadChoice, PackReadPlan, PersistenceError, + }, + source::Source, + StorageError, StorageResult, +}; +use std::sync::Arc; + +const EDITS: Shape = Shape { + files: 4, + versions: 6, + size: 24_000, + rewrite: false, + reopen: None, +}; + +#[test] +fn ranges_where_a_directory_is_known_and_whole_packs_where_not() { + let (memory, roots, _) = history(EDITS, |m| m); + let (expected, _) = read(copy(&memory), &roots[..1], true); + let ranged = Arc::new(ChainProvider::new(copy(&memory))); + let (got, work) = read(ranged.clone(), &roots[..1], true); + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + let requests = ranged.requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 1); + let ranges: usize = requests[0].iter().map(|read| read.ranges.len()).sum(); + let whole = requests[0] + .iter() + .filter(|read| read.ranges.is_empty()) + .count(); + assert!(ranges > 0, "a sparse pack is read as ranges"); + assert_eq!(work.group_read_ranges, ranges as u64); + assert_eq!(work.group_read_whole, whole as u64); + assert_eq!(work.group_read_packs, requests[0].len() as u64); + let returned: u64 = requests[0] + .iter() + .map(|read| match read.ranges.is_empty() { + true => read.pack.length as u64, + false => read.ranges.iter().map(|range| range.length as u64).sum(), + }) + .sum(); + assert_eq!(work.group_read_bytes, returned); + // Without directories every pack is asked for whole, and the port's + // default answer (whole packs through `read_packs`) serves the read. + let mut plain = ChainProvider::new(copy(&memory)); + plain.directories = false; + plain.ranged = false; + let plain = Arc::new(plain); + let (got, work) = read(plain.clone(), &roots[..1], true); + assert_eq!(got.unwrap(), expected.unwrap()); + let requests = plain.requests.lock().unwrap().clone(); + assert!(requests.iter().flatten().all(|read| read.ranges.is_empty())); + assert_eq!(work.group_read_whole, work.group_read_packs); + assert_eq!(work.chain_hint_stale, 0); +} + +#[test] +fn each_call_stays_within_the_cache_bound() { + let shape = Shape { + files: 48, + versions: 3, + size: 60_000, + ..EDITS + }; + let (memory, roots, _) = history(shape, |m| m); + let (expected, _) = read(copy(&memory), &roots, true); + for directories in [true, false] { + let mut provider = ChainProvider::new(copy(&memory)); + provider.directories = directories; + let provider = Arc::new(provider); + // The provider refuses any call over the bound. + let (got, work) = read(provider.clone(), &roots, true); + assert_eq!(got.unwrap(), *expected.as_ref().unwrap()); + assert!(provider.calls("read_groups") >= 2, "the demand spans calls"); + assert_eq!(work.chain_hint_stale, 0); + } +} + +#[test] +fn answers_out_of_request_order_are_refused() { + let (memory, roots, _) = history(EDITS, |m| m); + let mut provider = ChainProvider::new(copy(&memory)); + provider.ranged = false; + provider.reverse = true; + let (got, _) = read(Arc::new(provider), &roots[..1], true); + assert!( + matches!(got, Err(StorageError::Integrity("group read reply"))), + "{got:?}" + ); +} + +#[test] +fn a_corrupted_range_fails_at_the_object_hash() { + let (memory, roots, _) = history(EDITS, |m| m); + let provider = Arc::new(ChainProvider::new(copy(&memory))); + let (_, _) = read(provider.clone(), &roots[..1], true); + let target = provider.requests.lock().unwrap()[0] + .iter() + .find(|read| !read.ranges.is_empty()) + .map(|read| (read.pack.pack_id, read.ranges[0])) + .expect("a ranged read"); + // Every byte of that range, one at a time, is either unused by the read + // or caught: never a silently wrong answer. + let (pack, range) = target; + let mut caught = 0; + for at in (range.offset..range.offset + range.length).step_by(997) { + let provider = ChainProvider::new(copy(&memory)); + *provider.corrupt_range.lock().unwrap() = Some((pack, at)); + match read(Arc::new(provider), &roots[..1], false).0 { + Ok(bytes) => assert_eq!(bytes, read(copy(&memory), &roots[..1], true).0.unwrap()), + Err(StorageError::Integrity(_)) => caught += 1, + Err(other) => panic!("{other:?}"), + } + } + assert!(caught > 0, "a used byte was corrupted"); +} + +/// Serves one real pack's groups under a chosen digest. +struct Keyed { + info: PackInfo, + body: Vec, +} +struct Groups<'a>(&'a [usize]); +impl PackReadPlan for Groups<'_> { + fn select( + &mut self, + info: PackInfo, + prefix: &[u8], + ) -> Result { + let header = layout::parse_directory_header(prefix, info.length).unwrap(); + let views = layout::directory_group_views(prefix, header).unwrap(); + Ok(PackReadChoice::Ranges( + self.0 + .iter() + .map(|group| PackRange { + offset: views[*group].start, + length: views[*group].end - views[*group].start, + }) + .collect(), + )) + } +} +impl Source for Keyed { + fn location(&self, _: ObjectId, _: i64) -> StorageResult> { + Ok(None) + } + fn pack_bytes(&self, _: i64) -> StorageResult> { + Ok(self.body.clone()) + } + fn acquire_groups(&self, _: i64, groups: &[usize], _: bool) -> StorageResult { + let read = AcquiredPackRead::acquire(self.info, &mut Groups(groups), |at, out| { + out.copy_from_slice(&self.body[at..at + out.len()]); + Ok(()) + })?; + let AcquiredPackRead::Units(units) = read else { + panic!("ranges were planned"); + }; + Ok(PackAcquisition::Units(PackUnit::from_acquired(units)?)) + } + fn inode_values(&self, _: &[u32]) -> StorageResult> { + unreachable!() + } + fn signatures(&self) -> StorageResult> { + unreachable!() + } + fn write_signatures(&self, _: &[SignatureRow]) -> StorageResult { + unreachable!() + } +} + +#[test] +fn a_cached_range_refuses_its_pack_under_another_digest() { + let (memory, _, _) = history(EDITS, |m| m); + let state = memory.state.lock().unwrap(); + let pack = state + .packs + .values() + .find(|pack| layout::parse_header(&pack.body).unwrap().group_count >= 2) + .expect("a pack of several groups"); + let first = Keyed { + info: pack.info, + body: pack.body.as_ref().clone(), + }; + let mut info = pack.info; + info.key = ObjectKey::for_bytes(b"the same pack id under another digest"); + let second = Keyed { + info, + body: pack.body.as_ref().clone(), + }; + let id = pack.info.pack_id; + drop(state); + let mut cache = PackCache::new(); + cache.acquire_groups(&first, id, &[0]).unwrap(); + assert!(cache.group(&first, id, 0).unwrap().is_some()); + assert!(matches!( + cache.acquire_groups(&second, id, &[1]), + Err(StorageError::Integrity( + "immutable cached descriptor changed" + )) + )); + assert!(cache.group(&first, id, 0).unwrap().is_some(), "kept"); + assert_eq!(cache.work().evictions, 0); +} diff --git a/core/crates/layerfs-storage/tests/inode_branch_deltas.rs b/core/crates/layerfs-storage/tests/inode_branch_deltas.rs index 1a592b8c1c..e227e8301e 100644 --- a/core/crates/layerfs-storage/tests/inode_branch_deltas.rs +++ b/core/crates/layerfs-storage/tests/inode_branch_deltas.rs @@ -8,6 +8,10 @@ //! * chains grow 1..8 and, at the metadata depth cap, restart at depth one //! against the whole branch at their root instead of storing the branch whole //! (#89), and every table, old and new, reads back value for value; +//! * a program against that root longer than half the whole branch is stored +//! whole instead (#758 fix 4): edits within one leaf keep every re-based +//! program, edits spread across the table store both re-based root-branch +//! programs whole, and either way every table reads back; //! * a Store first written with whole branches only (the form every Store //! before this change holds) keeps reading identically once delta branches //! join it; @@ -19,7 +23,8 @@ mod metadata; use layerfs_content::filesystem::attributes::portable::PortableMetadata; use layerfs_content::filesystem::inode::{ - apply_inode_values, lookup, lookup_many, InodeReadWork, InodeTable, + apply_inode_values, decode_inode_page, lookup, lookup_many, InodePage, InodeReadWork, + InodeTable, }; use layerfs_content::filesystem::{FilesystemObjects, MAXIMUM_SCRATCH_BYTES}; use layerfs_content::object::inode_leaf::{InodeKind, InodeMetadata, InodeValue}; @@ -148,6 +153,63 @@ fn small_commits( .collect() } +/// Neighbouring serials one leaf holds: a leaf has at least +/// `MINIMUM_INODE_LEAF_ROWS` (50) rows and the first starts at serial 1. +const CLUSTER: u64 = 16; + +/// As [`small_commits`], but every edit stays within the first `CLUSTER` +/// serials, as successive small Commits to one directory's files do: each Save +/// still rewrites the root branch and one child branch, and both keep differing +/// from their chain's root in one child reference only, so a program against +/// that root stays small (#758 keeps it only up to half the whole branch). +fn clustered_commits( + storage: &Storage, + root: &mut ObjectId, + versions: &mut [u64], + count: u64, + first: u64, +) -> Vec { + (first..first + count) + .map(|round| { + let serial = 1 + (round * 7_919) % CLUSTER; + versions[serial as usize] += 1; + let (next, outcome) = commit( + storage, + Some(*root), + vec![(serial, value(serial, versions[serial as usize]))], + ); + *root = next; + outcome + }) + .collect() +} + +/// Reads every branch page of the table at `root` through a fresh reader and +/// checks each is byte-identical to the page its identity names, returning +/// how many were read. +fn branch_pages_match_their_ids(storage: &Storage, root: ObjectId) -> usize { + let reader = storage.reader().unwrap(); + let mut level = vec![root]; + let mut read = 0; + while !level.is_empty() { + let pages = reader.read_objects(&level).unwrap(); + let mut next = Vec::new(); + for (id, page) in level.iter().zip(&pages) { + assert_eq!(ObjectId::for_bytes(page), *id, "branch page bytes"); + read += 1; + match decode_inode_page(page).unwrap() { + InodePage::Branch { + level, children, .. + } if level > 1 => next.extend(children.into_iter().map(|(_, child)| child)), + InodePage::Branch { .. } => {} + InodePage::Leaf { .. } => panic!("a table root is a branch here"), + } + } + level = next; + } + read +} + fn initial(storage: &Storage) -> (ObjectId, Vec) { let versions = vec![0_u64; INODES as usize + 1]; let rows = (1..=INODES) @@ -172,7 +234,11 @@ fn branch_chains_grow_to_the_cap_re_base_onto_their_root_and_read_back() { let mut roots = vec![(root, versions.clone())]; let mut total = layerfs_storage::encoding::delta::branch::BranchCounters::default(); for round in 0..20 { - let outcome = small_commits(&storage, &mut root, &mut versions, 1, round).remove(0); + // Clustered edits (#758 fix 4c): spread edits make the program against + // a re-based root longer than half the whole branch, which the size + // rule stores whole; that case is the next test, on this test's + // original spread fixture. + let outcome = clustered_commits(&storage, &mut root, &mut versions, 1, round).remove(0); let branch = outcome.delta.branch; // The root and one child branch change; both are offered. assert_eq!(branch.branches, 2, "round {round}: {branch:?}"); @@ -191,11 +257,14 @@ fn branch_chains_grow_to_the_cap_re_base_onto_their_root_and_read_back() { total.accumulate(&branch); roots.push((root, versions.clone())); } - // The root branch's chain: depth 1..8, then at the cap a program against the + // Each branch chain: depth 1..8, then at the cap a program against the // whole branch at the chain's root (depth 1 again), then 2..8 again; no - // branch is stored whole after the initial table (#89). + // branch is stored whole after the initial table (#89), and every program + // against a re-based root is kept under the size rule (#758). assert!(total.depth_capped >= 2, "{total:?}"); assert_eq!(total.rebased, total.depth_capped, "{total:?}"); + assert!(total.rebased >= 1, "{total:?}"); + assert_eq!(total.rebased_full, 0, "{total:?}"); assert_eq!(total.work_exceeded, 0, "{total:?}"); assert_eq!(total.full_branches, 0, "{total:?}"); assert_eq!(total.depths[0], 0, "{total:?}"); @@ -215,6 +284,74 @@ fn branch_chains_grow_to_the_cap_re_base_onto_their_root_and_read_back() { } } +#[test] +fn re_based_branch_programs_over_half_the_whole_are_stored_whole_and_read_back() { + // The previous test's fixture as it stood before #758 fix 4c, unchanged: + // the default policy, the 50,000-inode initial table, and twenty rounds of + // one edit each spread across the table (`small_commits`, serial + // 1 + round * 7,919 mod 50,000). The root branch reaches the metadata depth + // cap twice and is re-based onto its chain's root; by then the spread edits + // have replaced most of its child references, so each program against the + // root is longer than half the whole branch, and the size rule stores the + // branch whole (#758 fix 4). + let (_, storage) = storage(StoragePolicy::default()); + let (mut root, mut versions) = initial(&storage); + let reader = storage.reader().unwrap(); + assert_eq!(branch_levels(&reader, root), 2, "a two-level table"); + drop(reader); + let mut roots = vec![(root, versions.clone())]; + let mut total = layerfs_storage::encoding::delta::branch::BranchCounters::default(); + for round in 0..20 { + let outcome = small_commits(&storage, &mut root, &mut versions, 1, round).remove(0); + let branch = outcome.delta.branch; + assert_eq!(branch.branches, 2, "round {round}: {branch:?}"); + // A firing stores that branch whole: depth 0, in the same Save. + assert_eq!(branch.full_branches, branch.rebased_full, "{branch:?}"); + assert_eq!(branch.depths[0], branch.full_branches, "{branch:?}"); + assert_eq!( + branch.depths.iter().sum::(), + branch.branches, + "{branch:?}" + ); + total.accumulate(&branch); + roots.push((root, versions.clone())); + } + println!("spread fixture: {total:?}"); + // Both re-based programs are stored whole; nothing else is. + assert_eq!(total.rebased, 2, "{total:?}"); + assert_eq!(total.rebased, total.depth_capped, "{total:?}"); + assert_eq!(total.full_branches, 2, "{total:?}"); + assert_eq!(total.rebased_full, 2, "{total:?}"); + assert_eq!(total.full_branches, total.rebased_full, "{total:?}"); + assert_eq!(total.depths[0], total.full_branches, "{total:?}"); + assert_eq!(total.work_exceeded, 0, "{total:?}"); + assert_eq!( + total.trials, total.branches, + "one trial per branch: {total:?}" + ); + assert_eq!( + total.delta_branches + total.full_branches, + total.branches, + "{total:?}" + ); + assert_eq!( + total.depths.iter().sum::(), + total.branches, + "{total:?}" + ); + // Each whole branch restarts its chain at depth 0: the root branch runs + // 1..8, whole, 1..8, whole, 1..2, and its child branches (each edited at + // most three times) 1..3. The histogram of this input, exactly. + assert_eq!(total.depths[..9], [2, 18, 7, 3, 2, 2, 2, 2, 2], "{total:?}"); + assert_eq!(total.depths[9..].iter().sum::(), 0, "{total:?}"); + // Every table, old and new, reads back value for value, and every branch + // page byte for byte, from a fresh reader each. + for (root, versions) in &roots { + assert_eq!(read_all(&storage, *root), expected(versions)); + assert!(branch_pages_match_their_ids(&storage, *root) >= 2); + } +} + #[test] fn a_store_of_whole_branches_reads_identically_after_delta_branches_join_it() { // Metadata depth 0 writes no metadata delta at all: every branch whole, the diff --git a/core/crates/layerfs-storage/tests/pooled_dependency_integrity.rs b/core/crates/layerfs-storage/tests/pooled_dependency_integrity.rs index be08d4ad1f..28fa6fad40 100644 --- a/core/crates/layerfs-storage/tests/pooled_dependency_integrity.rs +++ b/core/crates/layerfs-storage/tests/pooled_dependency_integrity.rs @@ -86,6 +86,7 @@ fn literal_delta_cannot_hide_a_wrong_canonical_base() { pack_id: i as i64 + 1, group_number: 0, record_number: 0, + base: None, }) .collect(), inode_values: values diff --git a/core/crates/layerfs-storage/tests/rebased_delta_fraction.rs b/core/crates/layerfs-storage/tests/rebased_delta_fraction.rs new file mode 100644 index 0000000000..144c9f7e0e --- /dev/null +++ b/core/crates/layerfs-storage/tests/rebased_delta_fraction.rs @@ -0,0 +1,262 @@ +//! A re-based delta is kept only when it is at most half the object's FULL +//! record (#758 fix 4). +//! +//! #89 re-bases a candidate whose chain is at its depth cap onto the FULL root +//! of that chain. As an object drifts from that root, the delta against it +//! grows with history, and every read of the chain pays it. The rule stores a +//! new FULL instead once that delta would exceed half the FULL record, so the +//! anchor of every chain (its root plus the one delta against it) costs a read +//! at most 1.5 FULL records, and a read of a member at depth `d` at most that +//! plus its `d - 1` one-version deltas, however long the history. +//! +//! Both fixtures drift: each version replaces a fresh region of the content +//! with new incompressible bytes, so the delta against the root covers every +//! region replaced since the root was written. +#[path = "support/memory_metadata.rs"] +mod metadata; +mod support; + +use layerfs_content::{ + construct_bytes_with_predecessor, AdvisoryPredecessors, ConstructionPolicy, ContentResult, + FinalizedConsumer, FinalizedObject, ObjectId, ObjectRole, PredecessorBase, +}; +use layerfs_storage::{Storage, StoragePolicy, WriteOutcome}; +use std::sync::Arc; + +/// Deterministic incompressible bytes, distinct per seed. +fn noise(len: usize, seed: u64) -> Vec { + let mut state = 0x9e37_79b9_7f4a_7c15_u64 ^ seed.wrapping_mul(0xa076_1d64_78bd_642f); + (0..len) + .map(|_| { + state ^= state << 7; + state ^= state >> 9; + state ^= state << 8; + state as u8 + }) + .collect() +} + +/// Version `version` of a drifting file of `len` bytes: version 0 is +/// `noise(len, 0)`, and each later version replaces the next of `regions` +/// equal regions with fresh bytes. +fn drift(bytes: &mut [u8], version: usize, regions: usize) { + if version == 0 { + return; + } + let width = bytes.len() / regions; + let at = ((version - 1) % regions) * width; + bytes[at..at + width].copy_from_slice(&noise(width, version as u64)); +} + +/// Bytes a fresh handle fetches to read `ids`. +fn fetched(metadata: &Arc, ids: &[ObjectId]) -> u64 { + let storage = Storage::new(metadata.clone()).unwrap(); + storage.reader().unwrap().read_objects(ids).unwrap(); + let d = storage.diagnostics(); + d.pack_read_bytes + d.range_acquired_bytes + d.group_read_bytes +} + +fn depth(outcome: &WriteOutcome) -> usize { + let depths = &outcome.delta.whole_file_depths; + assert_eq!(depths.iter().sum::(), 1, "{outcome:?}"); + depths.iter().position(|n| *n == 1).unwrap() +} + +#[test] +fn a_drifting_file_stores_full_when_its_re_based_delta_passes_half_the_full() { + // Whole-file depth cap 2: versions 3, 5 and 7 have a capped candidate and + // are re-based onto the chain root. Each version replaces one eighth of a + // 16 KiB file, so the delta of version 3 against version 0 covers three + // eighths (kept) and that of version 5 five eighths: over half, a FULL. + let metadata = Arc::new(metadata::MemoryMetadata::default()); + metadata.state.lock().unwrap().policy = StoragePolicy::new(1, 131_072, 2, 4); + let storage = Storage::new(metadata.clone()).unwrap(); + let mut bytes = noise(16 * 1024, 0); + let mut previous: Option = None; + let mut versions = Vec::new(); + let mut outcomes = Vec::new(); + for version in 0..8 { + drift(&mut bytes, version, 8); + let mut object = FinalizedObject::new( + ObjectRole::WholeFile, + support::assembled_small_object(&bytes), + ) + .unwrap(); + if let Some(base) = previous { + object = object.with_predecessors(AdvisoryPredecessors::explicit(base).unwrap()); + } + previous = Some(object.id()); + let save = storage.begin_save().unwrap(); + save.accept(object.clone()).unwrap(); + outcomes.push(save.finish().unwrap()); + versions.push(object); + } + let depths: Vec = outcomes.iter().map(depth).collect(); + // Version 5 starts a new chain; 6 and 7 chain on it. + assert_eq!(depths, [0, 1, 2, 1, 2, 0, 1, 2]); + for (version, o) in outcomes.iter().enumerate() { + let fired = u64::from(version == 5); + assert_eq!(o.delta.rebased, u64::from(version == 3 || version == 5)); + assert_eq!(o.delta.rebased_full, fired, "{version}: {o:?}"); + assert_eq!(o.delta.full_losses, fired, "{version}: {o:?}"); + assert_eq!(o.full_records, u64::from(version == 0 || version == 5)); + } + // Every version reads back, and its read stays within the bound: the + // root's FULL, half a FULL for the re-based delta, and one one-version + // delta per further level (each pack's framing counts on both sides). + let full = fetched(&metadata, &[versions[0].id()]); + let step = fetched(&metadata, &[versions[1].id()]) - full; + let reader = storage.reader().unwrap(); + for (version, object) in versions.iter().enumerate() { + assert_eq!( + reader.read_objects(&[object.id()]).unwrap(), + vec![object.canonical().to_vec()] + ); + let read = fetched(&metadata, &[object.id()]); + let inner = depths[version].saturating_sub(1) as u64 * step; + assert!( + 2 * read <= 3 * full + 2 * inner, + "version {version}: read {read} B, FULL {full} B, inner {inner} B" + ); + } +} + +#[test] +fn a_re_based_prefix_that_loses_anyway_is_not_counted_as_the_rule_firing() { + // Whole-file depth cap 2: versions 1 and 2 drift one eighth each, so + // version 3's candidate (version 2) is capped and the trial is re-based + // onto version 0. Version 3 is fresh noise: its PREFIX against the root is + // no shorter than its FULL record and loses the comparison on its own, so + // the half-FULL rule changed nothing and `rebased_full` stays 0 (fix 4b; + // fix 4 counted every re-based PREFIX over half the FULL, here 1). + let metadata = Arc::new(metadata::MemoryMetadata::default()); + metadata.state.lock().unwrap().policy = StoragePolicy::new(1, 131_072, 2, 4); + let storage = Storage::new(metadata.clone()).unwrap(); + let mut bytes = noise(16 * 1024, 0); + let mut previous: Option = None; + let mut outcomes = Vec::new(); + for version in 0..4 { + if version == 3 { + bytes = noise(16 * 1024, 1_000); + } else { + drift(&mut bytes, version, 8); + } + let mut object = FinalizedObject::new( + ObjectRole::WholeFile, + support::assembled_small_object(&bytes), + ) + .unwrap(); + if let Some(base) = previous { + object = object.with_predecessors(AdvisoryPredecessors::explicit(base).unwrap()); + } + previous = Some(object.id()); + let save = storage.begin_save().unwrap(); + save.accept(object).unwrap(); + outcomes.push(save.finish().unwrap()); + } + let depths: Vec = outcomes.iter().map(depth).collect(); + assert_eq!(depths, [0, 1, 2, 0]); + let last = &outcomes[3]; + assert_eq!(last.delta.rebased, 1, "{last:?}"); + assert_eq!(last.delta.trials, 1, "{last:?}"); + assert_eq!(last.delta.full_losses, 1, "{last:?}"); + assert_eq!(last.delta.rebased_full, 0, "{last:?}"); + let fired: u64 = outcomes.iter().map(|o| o.delta.rebased_full).sum(); + assert_eq!(fired, 0, "{outcomes:?}"); +} + +#[derive(Default)] +struct Emitted(Vec); +impl FinalizedConsumer for Emitted { + fn accept(&mut self, object: FinalizedObject) -> ContentResult<()> { + self.0.push(object); + Ok(()) + } +} + +/// Constructs `bytes` against `base`, saves it, and returns the file root. +fn construct(storage: &Storage, bytes: &[u8], base: Option) -> (ObjectId, WriteOutcome) { + let policy = ConstructionPolicy::frozen_default(); + let reader = storage.reader().unwrap(); + let mut emitted = Emitted::default(); + let file = layerfs_telemetry::timer::Timing::disabled("test.construct", |scope| { + construct_bytes_with_predecessor( + policy, + &policy.capacities(), + bytes, + base.map(|root| PredecessorBase::new(&reader, root)), + &mut emitted, + scope.child("content"), + ) + }) + .0 + .unwrap(); + drop(reader); + let save = storage.begin_save().unwrap(); + for object in emitted.0 { + save.accept(object).unwrap(); + } + (file.root, save.finish().unwrap()) +} + +/// The read of a whole file from a fresh reader: its bytes and the stored +/// record bytes its program-page chains read. +fn read_file(metadata: &Arc, root: ObjectId) -> (Vec, u64) { + let storage = Storage::new(metadata.clone()).unwrap(); + let reader = storage.reader().unwrap(); + let mut out = Vec::new(); + layerfs_telemetry::timer::Timing::disabled("test.read", |scope| { + layerfs_content::read_all(&reader, root, &mut out, scope.child("read")) + }) + .0 + .unwrap(); + (out, reader.pooled_read_counters().program_chain_encoded) +} + +#[test] +fn a_drifting_extent_page_stores_whole_when_its_re_based_program_passes_half() { + // A 1 MiB chunked file whose extent page lists every chunk; metadata depth + // cap 2, so every second version re-bases the page onto its chain root. + // Each version replaces one sixteenth of the file, so the program against + // the root grows by about one sixteenth of the page per version until it + // passes half the whole page, which is then stored whole. + let metadata = Arc::new(metadata::MemoryMetadata::default()); + metadata.state.lock().unwrap().policy = StoragePolicy::default().with_metadata_depth(2); + let storage = Storage::new(metadata.clone()).unwrap(); + let mut bytes = noise(1 << 20, 0); + let mut root: Option = None; + let mut versions = Vec::new(); + let mut outcomes = Vec::new(); + for version in 0..14 { + drift(&mut bytes, version, 16); + let (next, outcome) = construct(&storage, &bytes, root); + root = Some(next); + versions.push((next, bytes.clone())); + outcomes.push(outcome); + } + let fired: Vec = outcomes + .iter() + .map(|o| o.delta.extent.rebased_full) + .collect(); + assert!(fired.iter().all(|n| *n <= 1), "{fired:?}"); + assert!(fired.iter().any(|n| *n == 1), "the rule fired: {fired:?}"); + let rebased: u64 = outcomes.iter().map(|o| o.delta.extent.rebased).sum(); + assert!(rebased >= 3, "{rebased}"); + let depth = |o: &WriteOutcome| o.delta.extent.depths.iter().rposition(|n| *n > 0).unwrap(); + // Every version reads back, and its page chain stays within the bound: + // the root's whole page, half a whole page for the re-based program, and + // one one-version program per further level. + let (_, whole) = read_file(&metadata, versions[0].0); + let (_, one) = read_file(&metadata, versions[1].0); + let step = one - whole; + for (version, ((root, expected), outcome)) in versions.iter().zip(&outcomes).enumerate() { + let (read, encoded) = read_file(&metadata, *root); + assert!(read == *expected, "version {version} reads back"); + let inner = depth(outcome).saturating_sub(1) as u64 * step; + assert!( + 2 * encoded <= 3 * whole + 2 * inner, + "version {version}: page chain {encoded} B, whole {whole} B, inner {inner} B, \ + fired {fired:?}" + ); + } +} diff --git a/core/crates/layerfs-storage/tests/selected_group_reads.rs b/core/crates/layerfs-storage/tests/selected_group_reads.rs index 50b444a561..fdcb71a2e2 100644 --- a/core/crates/layerfs-storage/tests/selected_group_reads.rs +++ b/core/crates/layerfs-storage/tests/selected_group_reads.rs @@ -56,6 +56,7 @@ fn fixture() -> (Arc, Vec, usize) { pack_id: 1, group_number: number, record_number: 0, + base: None, }) .collect(), ..Publication::default() @@ -248,6 +249,7 @@ fn a_sparse_prefix_target_reconstructs_its_required_base_exactly() { pack_id: 1, group_number: number, record_number: 0, + base: None, }) .collect(), ..Publication::default() @@ -330,6 +332,7 @@ fn chunk_fixture(packs: usize) -> (Arc, Vec ObjectLocation { pack_id: 7, group_number: 0, record_number, + base: None, } } diff --git a/core/crates/layerfs-storage/tests/support/chain_provider.rs b/core/crates/layerfs-storage/tests/support/chain_provider.rs new file mode 100644 index 0000000000..7f140ae282 --- /dev/null +++ b/core/crates/layerfs-storage/tests/support/chain_provider.rs @@ -0,0 +1,400 @@ +//! A provider that answers chain locates and group reads (#758) over the +//! memory engine, with switches that make its answers wrong on purpose. +#![allow(dead_code)] +use crate::metadata::MemoryMetadata; +use layerfs_content::{ + construct_bytes_with_predecessor, ConstructionPolicy, ContentResult, FinalizedConsumer, + FinalizedObject, ObjectId, PredecessorBase, +}; +use layerfs_storage::{ + location::{ + ChainMember, InodeValueRow, LocatedChain, LocatedChains, LocatedObject, PackDirectory, + SignatureRow, + }, + pack::layout, + policy::{StoragePolicy, DEPENDENCY_PACK_CACHE_BYTES}, + port::*, + Storage, +}; +use std::{ + collections::BTreeSet, + sync::{Arc, Mutex}, +}; + +type Edit = Box; +type Step = Box; + +/// Chains follow the `base` the memory engine stored with each published row. +pub struct ChainProvider { + pub inner: Arc, + /// Members carry ids (a logical list) instead of `None` (a physical one). + pub ids: bool, + /// Directories of every pack the rows and members name. + pub directories: bool, + /// `read_groups` answers ranged requests with `Ranges`; else the default. + pub ranged: bool, + /// Rewrites each chain answer before it is returned. + pub edit: Mutex>, + /// Flips this byte, (pack, offset), wherever a returned range holds it. + pub corrupt_range: Mutex>, + /// Answers in reverse request order. + pub reverse: bool, + /// Every `read_groups` request. + pub requests: Mutex>>, + /// Answers chain locates at all; else `locate` and no chains. + pub chains: bool, + /// The `batched_chain_reads` knob. + pub batched: bool, + /// The roots of every chain locate, in call order. + pub asked: Mutex>>, + /// Runs before the next publication, as another writer would. + pub before_publish: Mutex>, +} +impl ChainProvider { + pub fn new(inner: Arc) -> Self { + Self { + inner, + ids: false, + directories: true, + ranged: true, + edit: Mutex::new(None), + corrupt_range: Mutex::new(None), + reverse: false, + requests: Mutex::new(Vec::new()), + chains: true, + batched: false, + asked: Mutex::new(Vec::new()), + before_publish: Mutex::new(None), + } + } + pub fn calls(&self, name: &str) -> usize { + let calls = self.inner.calls.lock().unwrap(); + calls.iter().filter(|(call, _)| *call == name).count() + } +} +impl PackPersistence for ChainProvider { + fn policy(&self) -> Result { + self.inner.policy() + } + fn locate( + &self, + ids: &[ObjectId], + out: &mut Vec, + ) -> Result<(), PersistenceError> { + self.inner.locate(ids, out) + } + fn locate_chains( + &self, + roots: &[ObjectId], + rows: &mut Vec, + chains: &mut LocatedChains, + ) -> Result<(), PersistenceError> { + self.asked.lock().unwrap().push(roots.to_vec()); + self.inner.locate(roots, rows)?; + chains.chains.clear(); + chains.directories.clear(); + if !self.chains { + return Ok(()); + } + let state = self.inner.state.lock().unwrap(); + let mut packs = BTreeSet::new(); + for row in rows.iter() { + packs.insert(row.pack.pack_id); + let mut members = Vec::new(); + let mut base = row.location.base; + while let Some(id) = base { + let location = state.objects[&id]; + members.push(ChainMember { + object_id: self.ids.then_some(id), + pack: state.packs[&location.pack_id].info, + group_number: location.group_number, + record_number: location.record_number, + canonical_length: location.canonical_length, + }); + packs.insert(location.pack_id); + base = location.base; + } + if !members.is_empty() { + let root = row.location.object_id; + chains.chains.push(LocatedChain { root, members }); + } + } + if self.directories { + for id in packs { + let pack = &state.packs[&id]; + let header = layout::parse_header(&pack.body).unwrap(); + let prefix = pack.body[..header.body_offset].to_vec(); + chains.directories.push(PackDirectory { + pack: pack.info, + prefix, + }); + } + } + drop(state); + if let Some(edit) = self.edit.lock().unwrap().as_mut() { + edit(chains); + } + Ok(()) + } + fn read_groups( + &self, + reads: &[GroupRead], + out: &mut Vec, + ) -> Result<(), PersistenceError> { + self.inner + .calls + .lock() + .unwrap() + .push(("read_groups", reads.len())); + self.requests.lock().unwrap().push(reads.to_vec()); + let state = self.inner.state.lock().unwrap(); + let requested: usize = reads + .iter() + .map(|read| match read.ranges.is_empty() { + true => read.pack.length, + false => read.ranges.iter().map(|range| range.length).sum(), + }) + .sum(); + assert!( + requested <= DEPENDENCY_PACK_CACHE_BYTES, + "byte cap per call" + ); + out.clear(); + for read in reads { + let Some(pack) = state.packs.get(&read.pack.pack_id) else { + return Err(PersistenceError::Missing); + }; + if read.ranges.is_empty() || !self.ranged { + let body = pack.body.as_ref().clone(); + out.push(GroupReadAnswer::Whole(PersistedPack::authenticate( + pack.info, body, + )?)); + continue; + } + let mut bodies: Vec> = read + .ranges + .iter() + .map(|range| pack.body[range.offset..range.offset + range.length].to_vec()) + .collect(); + if let Some((pack, at)) = *self.corrupt_range.lock().unwrap() { + for (range, body) in read.ranges.iter().zip(&mut bodies) { + let inside = range.offset <= at && at < range.offset + range.length; + if pack == read.pack.pack_id && inside { + body[at - range.offset] ^= 0x5a; + } + } + } + out.push(GroupReadAnswer::Ranges(bodies)); + } + if self.reverse { + out.reverse(); + } + Ok(()) + } + fn batched_chain_reads(&self) -> bool { + self.batched + } + fn read_packs( + &self, + ids: &[i64], + out: &mut Vec, + ) -> Result<(), PersistenceError> { + self.inner.read_packs(ids, out) + } + fn read_pack_selection( + &self, + id: i64, + plan: &mut dyn PackReadPlan, + ) -> Result { + self.inner.read_pack_selection(id, plan) + } + fn read_scoped_pack( + &self, + id: i64, + plan: &mut dyn PackReadPlan, + ) -> Result { + self.inner.read_scoped_pack(id, plan) + } + fn inode_values( + &self, + ordinals: &[u32], + out: &mut Vec, + ) -> Result<(), PersistenceError> { + self.inner.inode_values(ordinals, out) + } + fn signatures(&self, out: &mut Vec) -> Result<(), PersistenceError> { + self.inner.signatures(out) + } + fn reserve(&self, request: Reserve) -> Result { + self.inner.reserve(request) + } + fn publish(&self, batch: &Publication) -> Result { + let step = self.before_publish.lock().unwrap().take(); + if let Some(step) = step { + step(); + } + self.inner.publish(batch) + } +} + +#[derive(Default)] +struct Emitted(Vec); +impl FinalizedConsumer for Emitted { + fn accept(&mut self, object: FinalizedObject) -> ContentResult<()> { + self.0.push(object); + Ok(()) + } +} + +fn noise(seed: u64, len: usize) -> Vec { + let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + state ^= state << 7; + state ^= state >> 9; + state ^= state << 8; + state as u8 + }) + .collect() +} + +/// The shape of a [`history`]. +#[derive(Clone, Copy)] +pub struct Shape { + pub files: usize, + pub versions: usize, + pub size: usize, + /// Each version rewritten whole instead of edited in a few bytes. + pub rewrite: bool, + /// The version whose Save opens a fresh handle, with cold caches. + pub reopen: Option, +} + +/// `files` small files saved over `versions` Saves through `wrap`'s port, +/// strict about hints, each version offered the last as its base. Returns +/// the Store, the newest version of each file and the writer's counts. +pub fn history( + shape: Shape, + wrap: impl Fn(Arc) -> Arc, +) -> ( + Arc, + Vec, + layerfs_storage::Diagnostics, +) { + history_with(shape, wrap, |storage, objects| { + let save = storage.begin_save().unwrap(); + for object in objects { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + }) +} + +/// [`history`] whose last version's objects go to `last` instead of a Save. +pub fn history_with( + shape: Shape, + wrap: impl Fn(Arc) -> Arc, + last: impl FnOnce(&Storage, Vec), +) -> ( + Arc, + Vec, + layerfs_storage::Diagnostics, +) { + let mut last = Some(last); + let memory = Arc::new(MemoryMetadata::default()); + let open = || { + let storage = Storage::new(wrap(memory.clone())).unwrap(); + storage.set_strict_hints(true); + storage + }; + let mut storage = open(); + let mut contents: Vec> = (0..shape.files) + .map(|file| noise(file as u64 + 1, shape.size + file * 977)) + .collect(); + let mut roots: Vec> = vec![None; shape.files]; + let policy = ConstructionPolicy::frozen_default(); + for version in 0..shape.versions { + if shape.reopen == Some(version) { + storage = open(); + } + for (file, bytes) in contents.iter_mut().enumerate() { + if shape.rewrite { + *bytes = noise((version * 1000 + file) as u64 + 7, bytes.len()); + } else { + let at = (version * 7919 + file * 104_729) % (bytes.len() - 64); + bytes[at..at + 64].copy_from_slice(&noise((version * 97 + file) as u64, 64)); + } + } + let reader = storage.reader().unwrap(); + let mut emitted = Emitted::default(); + let next: Vec = contents + .iter() + .zip(&roots) + .map(|(bytes, base)| { + layerfs_telemetry::timer::Timing::disabled("test.construct", |scope| { + construct_bytes_with_predecessor( + policy, + &policy.capacities(), + bytes, + base.map(|root| PredecessorBase::new(&reader, root)), + &mut emitted, + scope.child("content"), + ) + }) + .0 + .unwrap() + .root + }) + .collect(); + drop(reader); + // Marks where this version's Save starts in the call log. + memory.calls.lock().unwrap().push(("save", version)); + if version + 1 == shape.versions { + (last.take().unwrap())(&storage, emitted.0); + } else { + let save = storage.begin_save().unwrap(); + for object in emitted.0 { + save.accept(object).unwrap(); + } + save.finish().unwrap(); + } + roots = next.into_iter().map(Some).collect(); + } + let roots = roots.into_iter().map(Option::unwrap).collect(); + (memory, roots, storage.diagnostics()) +} + +/// Reads `ids` through a fresh handle over `port`. +pub fn read( + port: Arc, + ids: &[ObjectId], + strict: bool, +) -> ( + layerfs_storage::StorageResult>>, + layerfs_storage::Diagnostics, +) { + let storage = Storage::new(port).unwrap(); + storage.set_strict_hints(strict); + let read = storage.reader().unwrap().read_objects(ids); + (read, storage.diagnostics()) +} + +/// The depth of `id`'s stored chain. +pub fn depth(memory: &MemoryMetadata, id: ObjectId) -> usize { + let state = memory.state.lock().unwrap(); + let mut depth = 0; + let mut base = state.objects[&id].base; + while let Some(next) = base { + depth += 1; + base = state.objects[&next].base; + } + depth +} + +/// A fresh copy of the Store with an empty call log. +pub fn copy(memory: &MemoryMetadata) -> Arc { + let state = memory.state.lock().unwrap().clone(); + let copy = MemoryMetadata::default(); + *copy.state.lock().unwrap() = state; + Arc::new(copy) +} diff --git a/docs/architecture/core/physical-storage/README.md b/docs/architecture/core/physical-storage/README.md index b196c70b6b..dcf5af7e0c 100644 --- a/docs/architecture/core/physical-storage/README.md +++ b/docs/architecture/core/physical-storage/README.md @@ -26,10 +26,12 @@ are read back authenticated, and the ports a persistence backend implements. +------------------------------------|-------------------------------+ | reserve() / publish() +--------------------- PackPersistence (engine backend) -------------+ - | policy locate read_packs read_pack_selection read_scoped_pack | - | inode_values signatures reserve publication_pack_cost publish | + | policy locate locate_chains read_packs read_groups | + | read_pack_selection read_scoped_pack inode_values signatures | + | reserve publication_pack_cost publish | +------------------------------------^-------------------------------+ - | locate() / read_scoped_pack() + | locate_chains() / read_groups() + | / read_scoped_pack() +--------------------- Reader (one operation) -----------------------+ | locate --> prefetch chains --> acquire groups --> PackCache | | --> resolver: decode base first, hash, compare with the id | @@ -137,11 +139,18 @@ keeps its Store open across Saves. ```text read_objects(ids) <= 4,096 ids, <= 32 MiB canonical - 1 locate LocatorCache, then PackPersistence::locate (<= 4,096 ids) - 2 cohorts packs that fit the 2 MiB pack cache together, in order - 3 prefetch level by level: acquire groups, read base ids, locate bases - 4 fetch PackCache::acquire_groups(missing groups) - 5 decode resolver: walk chain, decode base first, hash each object + 1 locate LocatorCache, then PackPersistence::locate_chains (<= 4,096 ids) + 2 cohorts with chains: the roots one page covers, a page being one + read_groups call of <= 2 MiB returned for the roots' and their + chains' uncached groups, consumed before the next page; + without: packs that fit the 2 MiB pack cache together, in + order, then the whole-pack batch + 4 prefetch level by level: acquire groups, read base ids, bind each base + to its chain member or locate it; a level that locates also + locates the deeper bases its members' cached records name + 5 fetch PackCache::acquire_groups(missing groups) + 6 decode resolver: walk chain, decode base first, hash each object; + a failure on a hinted chain rebuilds once without hints --> canonical bytes in demand order ``` @@ -151,11 +160,15 @@ keeps its Store open across Saves. | Locator cache | 4,096 entries, second-chance eviction that skips the current demand; after a publication won locations are kept, lost ones invalidated | [`read/locator_cache.rs`](../../../../core/crates/layerfs-storage/src/read/locator_cache.rs) | | Absent set | 4,096 ids, cleared at each demand; a base named by a stored record drops its negative mark before it is asked again | [`read/fetch.rs`](../../../../core/crates/layerfs-storage/src/read/fetch.rs) | | Whole-pack batch | when the provider takes packs whole (`whole_pack_bytes`: 4,120 B default, 256 KiB on PostgreSQL), a cohort's small uncached packs are read in one `read_packs` call | same | +| Chain hints (#758) | every locate wave calls `locate_chains`; a malformed answer (unasked root, two chains for one root, more members than the role's depth, a member outside the locator bounds or with length 0, a directory that is not exactly `body[0..body_offset)`) is `Integrity("port chain locator")`, and the whole answer (rows and chains) is checked before any of it is kept. When a walk decodes base `X` from a record whose chain has a member there, `X` is bound to that member and kept as a hinted locator, so the walk's own locate sends nothing; a hinted locator serves only the demand that bound it (every demand starts by evicting them). A member whose id differs from `X`, whose pack descriptor contradicts a known one, or a list that does not end exactly at a FULL record, is stale: dropped, counted (`chain_hint_stale`) and the walk locates on. A pack descriptor only a bound member gave is a hint too: forgotten with the hints and at the next demand. It is confirmed, and counts as authoritative from then on, by promotion or by any later `remember_pack` of an equal descriptor: a locate row, a whole-pack reply (length and digest authenticated), but also a group read's ranged admission or a pack-cache hit, which carry the descriptor the group was read under and may be the member's own; so a member's descriptor whose group was read is not forgotten with the hints. A descriptor that contradicts a still-marked one makes the hint stale (counted once; strict refuses) and drops every hint at once, so a later failure of that walk at a hinted element is not rebuilt on a read (the failure stands); one that contradicts a confirmed descriptor fails as `inconsistent pack descriptor`. Pack ids are never reused, so either contradiction means a provider answered a chain unlike its own pack row. A failure a hint can cause (`ObjectMissing`, a provider `Missing`, an `Integrity` that is not a provider defect such as a malformed answer) on a chain holding a hinted locator evicts every hinted locator, turns hints off until the next demand and rebuilds once; a second failure stands, and a provider defect is never rebuilt. On a read, pooled leaves and program pages bind no member (their pool reader has no rebuild): their bases are located from authoritative rows. A chain walk level that has to locate also carries the deeper base ids that the chains of the bases it locates point at (`Fetch::chain_ahead`): member `k` gives the position of the level-`k` base, and the base id the record there names is read from bytes the pack and decoded-group caches already hold, which are only peeked (`PackCache::peek_group`, `GroupCache::peek`, `delta::read::cached_base`), as a guess for level `k + 1`. A chain whose base is already cached (bound from a member, or located earlier) is not followed: a chain a read binds binds its deeper bases with no locate. A group a guess needs decoded is decompressed into a decoded-group cache of that call's own (512 KiB, least recently used eviction, dropped after it) and reused while held there, so a level whose groups fit decodes each once; a body over 512 KiB is never kept and a level that interleaves more distinct groups than fit decodes an evicted one again. Every such decompression is counted in `prefetch_group_decodes`; presence checks set no locator-cache referenced bit. The guesses fill at most the rest of that locate's page of 4,096 ids, so they join only a locate the level makes anyway; a wrong guess's row is still cached, or remembered as absent, adding locator-cache pressure, and a guessed row whose authoritative descriptor contradicts a still-marked member descriptor makes the hint stale, as any authoritative row does. Nothing is trusted: their rows are authoritative, and every level still takes its base id from the record at its base's authoritative location, so a wrong guess (a stale member, a record that cannot be parsed) only leaves the next level to locate as before, with nothing counted stale. A program page's chain then costs the page's locate and one more for all its levels instead of one per level. A Save's demands, and the reads a Save makes of its lost registrations' winners, use chains only to prefetch groups, with one exception that keeps selection on authoritative locators: before a page's objects are admitted, the stored base whose chain selection may walk, when it came with a chain, is rebuilt with its members bound (for an ordinary object its first stored predecessor of an ordinary role whose cost the Save does not know; for a program page its first advisory predecessor when stored with the page's role, as `delta::branch::trial` takes it). The rule is wider than selection: it also checks the bases of objects this Save already holds privately or repeats within the wave (they never reach selection), and, for ordinary objects, of roles whose selection walks no base (file states, attributes, symlinks, filesystem roots, a whole file whose predecessor is a file state), so a base selection would not have read can still fail the Save when its failure is not a hint's; and the bound locators are kept as authoritative only after the rebuild hashed every element of the chain (`chain_verified_bases`). A hashed element's bytes are that object's, at a position only a catalog row can name, so selection walks the chain with no locate per level and charges the depth, canonical bytes and record bytes a reader walks; an element that fails its hash is never kept (the rebuild falls back once to authoritative locates, a counted stale hint). A program-page base (directory, extent or inode-table branch page; not a pooled leaf) is checked the same way by a pool reader of the Save's own, whose counts are discarded: its walk binds each member (`Fetch::binding_pages`, held only for this check) and hashes every element, base first, to the id its child's record names, with the canonical length the member gave. A member carries no role, so the hinted locator takes the root's and each hinted element's role is checked from its authenticated page header instead (`branch chain role`); its catalog row is not read. That reader has no rebuild, so a failure attributable to an element a hint located or reached through one (any element at or below the first hinted element, which an unauthenticated record named, being read, bound or decoded, for example a record there that names an element already walked; any element of a walk past the depth cap; or the chain work limit crossed anywhere in a walk with a hinted element, since its totals include the hinted elements' record and canonical lengths) evicts every hinted locator, counts a stale hint once, even when the walk already counted it (strict hints refuse) and leaves the chain to selection's own walk from authoritative locates, as it did before; any other failure (one at the authoritative root, for example a row whose length disagrees with its record) is the Save's own error, and strict hints do not turn it into `delta chain hint`. Without trusted chains (SQLite, or after a stale hint until the next demand) nothing is checked and the Save's calls are unchanged | [`read/hints.rs`](../../../../core/crates/layerfs-storage/src/read/hints.rs), [`delta/read.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/read.rs) | +| Group reads (#758) | a demand is paged: each page is the longest leading run of consumers (a read's roots in physical order, a Save's objects in admission order) whose uncached groups and chains' groups fit one `read_groups` call of ≤ 2 MiB returned, with the cached groups the run needs counted too, so the pack cache keeps the whole page while the run is consumed; the next page is planned only then. A first consumer that does not fit alone has the packs that fit read. Ranges come from `GroupPlan::ranged` (whole only for a singleton or a pack within the 4,120 B control prefix, however sparse or many the ranges) where a directory is known (from the chain locate, or from the packs the handle published), else the whole pack; a pack that does not fit a call is acquired as before. `Ranges` answers pass through `AcquiredPackRead::acquire` over the directory and returned bytes, so framing checks are those of a scoped read, and every answer is admitted to the pack cache as it came (`PackCache::admit_groups`), with no second read; answers out of request order are `Integrity("group read reply")`. A pack only chain members name is a hint: a member contradicting a known descriptor is left out, and a `Missing` or `Malformed` call, or an answer that fails admission, for such a pack makes the hints stale (counted, off until the next demand) while the read goes on as before; a failure of a pack the rows themselves name stays hard | [`read/hints.rs`](../../../../core/crates/layerfs-storage/src/read/hints.rs) | +| Local chains (#758) | when the provider's `batched_chain_reads` is true, the same group read also takes the chains the handle's own cache knows: the `base` of rows it published, followed through authoritative locators only (a lost row is invalidated, so its winner is located again) until a base is not cached or the record is FULL. A Save admits each slice a page at a time: the stored predecessors of the objects that are not stored themselves (an exact reuse reads none), with their chains. Default false (SQLite): nothing changes; PostgreSQL turns it on and answers `locate_chains` from stored ancestor lists ([PostgreSQL delta chains](../../engine/store/postgresql.md#delta-chains)) | [`read/hints.rs`](../../../../core/crates/layerfs-storage/src/read/hints.rs), [`save/wave.rs`](../../../../core/crates/layerfs-storage/src/save/wave.rs) | +| Strict hints | `Storage::set_strict_hints(true)`, for tests and benches only: a stale hint fails `Integrity("delta chain hint")` | [`store/handle.rs`](../../../../core/crates/layerfs-storage/src/store/handle.rs) | | Read units | `GroupPlan` sees the directory, then takes the pack whole (singleton, small, wanted groups ≥ half or > 4 ranges, already kept) or coalesced ranges; scratch ≤ 2 MiB | [`read/units.rs`](../../../../core/crates/layerfs-storage/src/read/units.rs) | | After a Save | only `Storage::reader_after_save` reuses the latest Save's published bodies (2 MiB) and values (512 KiB) | [`read/fetch.rs`](../../../../core/crates/layerfs-storage/src/read/fetch.rs) | | Kept caches | `Reader` for one operation; `ReadCache` and `Send`able `KeptReads` (3 MiB) across demands | [`read/provider.rs`](../../../../core/crates/layerfs-storage/src/read/provider.rs) | | File lengths | `Reader::file_lengths`: whole files from locator length − 23 without payload; chunked or empty files read only their file state; this attests no payload | [`read/length.rs`](../../../../core/crates/layerfs-storage/src/read/length.rs) | -| Counters | `Storage::diagnostics`: cumulative counts per handle (port calls, acquisition choices, bytes, cache hits), never timings | [`read/counters.rs`](../../../../core/crates/layerfs-storage/src/read/counters.rs) | +| Counters | `Storage::diagnostics`: cumulative counts per handle (port calls, acquisition choices, bytes, cache hits, `chain_*` and `group_read*`), never timings | [`read/counters.rs`](../../../../core/crates/layerfs-storage/src/read/counters.rs) | ### Ports @@ -163,16 +176,20 @@ keeps its Store open across Saves. | --- | --- | | `policy` | the persisted `StoragePolicy`, once per handle | | `locate` | ≤ 4,096 distinct ids; absent ids omitted | +| `locate_chains` | `locate` plus, per located delta root, at most one `LocatedChain` (members nearest base first, each an optional id, `PackInfo`, group, record and canonical length, the last one FULL) and the `PackDirectory` of packs it names; default `locate` and no chains | +| `read_groups` | one answer per `GroupRead` in request order: `Whole(PersistedPack)` or `Ranges` (the bytes of each requested range, unauthenticated); ≤ 2 MiB requested per call; an empty range list asks for the whole pack; default `read_packs` per 2 MiB of whole packs | | `read_packs` | whole packs ≤ 2 MiB in total, or one singleton, each a length- and SHA-256-checked `PersistedPack` | | `read_pack_selection` | strict selected read: the whole pack is scanned and hashed, chosen ranges kept; default `BackendUnavailable` | | `read_scoped_pack` | selected units, framing checked, not hashed; each used object is authenticated by its id; default `BackendUnavailable` | | `inode_values` | ≤ 4,096 ascending ordinals in one statement | | `signatures` | ≤ 8,192 signature-ring rows in insertion order | | `reserve` | one block of pack ids and/or ordinals | -| `publish` | one atomic `Publication` (packs, locators insert-if-absent, inode values, signatures, released ordinals); returns `Published { lost }` | +| `publish` | one atomic `Publication` (packs, locators insert-if-absent, inode values, signatures, released ordinals); each locator carries its record's logical delta `base`, which a provider may store in any form or ignore; returns `Published { lost }` | [`port/persistence.rs`](../../../../core/crates/layerfs-storage/src/port/persistence.rs) -also has `whole_pack_bytes`, `publication_bytes` and `publication_pack_cost`. +also has `whole_pack_bytes`, `batched_chain_reads` (default false; a provider +whose every read is a network round trip returns true), `publication_bytes` +and `publication_pack_cost`. A reply that differs from the plan is `Integrity`; a missing selected read is `BackendUnavailable`, never a whole-read fallback. @@ -206,6 +223,7 @@ Three kinds of reuse can meet in one Save: | Canonical work per chain | 4 × cutoff (512 KiB at 128 KiB; 4 MiB at 1 MiB) | `CHAIN_CANONICAL_CUTOFFS` | | Encoded work per chain | 2 × cutoff (256 KiB at 128 KiB) | `CHAIN_ENCODED_CUTOFFS` | | Selection test | chain decoded bytes + target length ≤ 4 × cutoff, chain encoded bytes + target length ≤ 2 × cutoff | [`delta/select.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/select.rs) | +| Re-based delta (#758 fix 4) | a delta against a re-based chain root is kept only when its record is at most half the FULL record, so a chain's anchor reads at most the root's FULL plus half the target's FULL record (1.5 FULL records only when both are the same size; [encoding](encoding.md)) | `rebased_delta_kept` in [`delta/select.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/select.rs), [`delta/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/branch.rs) | Stored-byte savings cost read work: a 4 KiB logical read may need a whole chunk, a complete group and several delta bases, and a whole-file object is @@ -217,6 +235,7 @@ proportional to the bytes requested. | Rule | Enforced by | | --- | --- | | Reads verify what they decode: every chain element is hashed against its locator's id | `Resolver::resolve_charged` in [`delta/read.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/read.rs) | +| A chain hint costs speed, never correctness: it is checked against the record and the bytes, and a provider without chains (SQLite) sends exactly the statements it did before | [`read/hints.rs`](../../../../core/crates/layerfs-storage/src/read/hints.rs) | | A whole pack across the port matches its length and SHA-256 key | `PersistedPack::authenticate` in [`port/read_pack.rs`](../../../../core/crates/layerfs-storage/src/port/read_pack.rs) | | A pack's key is computed once, at seal | `PublishedPack::seal` in [`port/persistence.rs`](../../../../core/crates/layerfs-storage/src/port/persistence.rs) | | Header and directory are validated before any body; no trial decoding | `parse_control_header`, `visit_directory` in [`pack/layout.rs`](../../../../core/crates/layerfs-storage/src/pack/layout.rs) | @@ -252,6 +271,10 @@ command gets a wall timeout of at most 120 s. | [`verified_pack_read.rs`](../../../../core/crates/layerfs-storage/tests/verified_pack_read.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test verified_pack_read` | any | A wrong length, digest or domain is refused | | [`delta_base_budget.rs`](../../../../core/crates/layerfs-storage/tests/delta_base_budget.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test delta_base_budget` | any | A base over the chain budgets is refused and the object stored FULL; a corrupt base inside them fails the Save | | [`capacity_refusal.rs`](../../../../core/crates/layerfs-storage/tests/capacity_refusal.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test capacity_refusal` | any | Only `Refused { status: "Capacity" }` counts as full disk | +| [`chain_hints.rs`](../../../../core/crates/layerfs-storage/tests/chain_hints.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test chain_hints` | any | A hinted chain is read with one locate and one group read; stale and misplaced members, and member packs that do not answer as named, fall back and are counted, or fail strict; malformed answers are refused and keep nothing; a provider defect is not replayed; a hinted locator serves one demand; program pages and pooled leaves bind no member on a read, yet a program page's chain below its first level is located in one locate from the bases its members' cached records name, and a member off the chain only brings back the per-level locates, with nothing stale; a chain a read binds adds no guess to another chain's locate, and the guesses count every decode and, when a level's groups fit the call's 512 KiB decoded-group cache, decode each group once; a Save binds members only to rebuild and hash its bases; a fresh-handle Save of a chained history, and of a directory whose pages are programs, sends one locate per wave and one group read per page, not a locate per base per level, and stores the default port's bytes; a misplaced member under a program base, or a hinted element whose page header declares another role, is a stale hint (strict refuses) and the Save stores the default port's bytes; a program base's own wrong row fails with its own error; a Save walks no chain selection does not walk; a hinted element whose record leads back to the authoritative root is a stale hint, counted once, and the Save stores the default port's bytes; an authoritative descriptor that contradicts a member's makes the hint stale and the read stays correct; a pack descriptor only a stale member gave goes with the hints; a group read is admitted with no second read; full rewrites send the default calls | +| [`rebased_delta_fraction.rs`](../../../../core/crates/layerfs-storage/tests/rebased_delta_fraction.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test rebased_delta_fraction` | any | A drifting whole file and a drifting extent page store FULL (whole) once a re-based delta would pass half the FULL record, and every version's read stays within the root's FULL, half a FULL and one one-version delta per further level; a re-based PREFIX that loses the comparison anyway is not counted in `rebased_full` | +| [`inode_branch_deltas.rs`](../../../../core/crates/layerfs-storage/tests/inode_branch_deltas.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test inode_branch_deltas` | any | Inode-table branch chains on a 50,000-inode table: edits within one leaf grow each chain to the metadata depth cap and re-base onto its root, keeping every program (no branch whole, `rebased_full` 0); the same table under spread edits stores both re-based root-branch programs whole (`full_branches` = `rebased_full` = 2) because each passes half the whole branch; every table reads back value for value and every branch page byte for byte | +| [`group_reads.rs`](../../../../core/crates/layerfs-storage/tests/group_reads.rs) | `cargo +1.85.1 test --locked -p layerfs-storage --test group_reads` | any | Ranged and whole answers, the per-call byte bound, request order, a cached range refusing its pack under another digest, corrupted ranges caught | ## Pages diff --git a/docs/architecture/core/physical-storage/encoding.md b/docs/architecture/core/physical-storage/encoding.md index 4183de4fde..f08789fc68 100644 --- a/docs/architecture/core/physical-storage/encoding.md +++ b/docs/architecture/core/physical-storage/encoding.md @@ -66,7 +66,67 @@ for one whole-file or chunk payload: | 4 Eligibility | stored, same role, below the depth cap; else FULL | | 5 Chain budget | from stored record sizes; a delta candidate that does not fit is replaced by its chain's independent root; still over budget: FULL | | 6 One trial | the base is read and authenticated, then one PREFIX frame is built; chain plus object must still fit | -| 7 Compare | PREFIX wins only when its record is shorter than FULL | +| 7 Compare | PREFIX wins only when its record is shorter than FULL; a PREFIX against a re-based root (step 5) also has to be at most half the FULL record, else FULL (`rebased_delta_kept`, #758 fix 4) | + +**Re-based delta limit (#758 fix 4).** A re-based trial (step 5) runs +against a root that can be any number of versions older than its target, so +as an object drifts the delta against it grows with history, and every read +of the chain pays it. The trial keeps its PREFIX (or a program page its +program) only when `2 × delta record ≤ FULL record`, both the stored record +lengths the step 7 comparison already uses (`REBASED_DELTA_DIVISOR` = 2 in +[`delta/select.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/select.rs)). +Bound: the anchor of a re-based chain (root plus the one delta against it) +costs a read at most the root's FULL plus half the target's FULL, 1.5 FULL +records for equal sizes instead of up to two, and a member at depth `d` at +most that plus its `d − 1` inner deltas (depth caps 16 / 8 / 8). The rule +limits only the re-based delta: an inner delta, or a first delta tried +directly against a FULL candidate, is held only by step 7 (below the +target's FULL). Against the caller's named predecessor it is one version's +change; against a base the signature ring proposed (a whole file at a new +path) it is not. Storing the FULL costs `full − delta` more bytes once and +saves about `delta` on every later read through it, so it repays itself +within one read exactly past half. + +Storage cost: a firing stores `F` where a delta in `(F/2, F)` would have been +stored, so it adds less than `F/2`. It can only happen at a re-base, and a +lineage re-bases at its effective chain length `L`, the deepest member it +reaches before its candidate is capped or no longer fits step 5: +`L = min(C, 1 + largest d whose candidate fits)`. With `S` the canonical +length of each version, `E` the FULL record, `e_i` the delta records and `K` +the cutoff, a depth-`d` candidate fits when `(d + 2)·S ≤ 4K` and +`E + Σ_{i≤d} e_i + S ≤ 2K` (whole file and chunk; a program page of `P` +bytes: `(d + 2)·P ≤ 65,536` and records plus the page's whole record +`≤ 139,281`). After a firing the new FULL is depth 0 and the next re-base +comes `L + 1` versions later, so a lineage adds less than `F / (2(L + 1))` +per version. A depth-0 candidate is never re-based, so `L ≥ 1` and the worst +case is `F / 4` per version. At the 128 KiB default: + +| Case | Arithmetic | `L` | Added per version | +| --- | --- | --- | --- | +| Incompressible whole file near the cutoff | depth 1: `E + e_1 + S ≈ 2S + e_1 > 256 KiB` | 1 | `< F/4` | +| Compressible whole file, `S ≤ K` | `4S ≤ 512 KiB` (and `5S > 512 KiB` above `4K/5`) | ≥ 3 | `< F/8` | +| Compressible whole file at the cutoff, `S > K` (envelope up to 23 bytes) | depth 1: `3S ≤ 512 KiB`; depth 2: `4S > 512 KiB` | 2 | `< F/6` | +| Whole file reaching the cap | depth 15: `17S ≤ 512 KiB`, `S ≤ 30,840` bytes, encoded budget holding | 16 | `< F/34` | +| Chunk (≤ 32 KiB), every record a full chunk | canonical fits past the cap; depth 5: `7 × ~32.8 KiB ≤ 256 KiB`, depth 6: `8 × ~32.8 KiB > 256 KiB` | ≥ 6 | `< F/14` | +| Chunk, small deltas | cap | 8 | `< F/18` | +| Program page of 8,192 bytes | depth 6: `8P ≤ 65,536`; depth 7: `9P > 65,536` | 7 | `< F/16` | +| Program page of ≤ 7,281 bytes | depth 7: `9P ≤ 65,536`; depth 8 is the cap | 8 | `< F/18` | + +A firing on a re-based ring proposal is not a version of a lineage: it adds +less than `F/2` for that object, with no per-version spreading. These figures +count only the firing's own bytes against the delta it replaced; later +records of the lineage differ from that alternative and are not bounded by +it. + +The fraction is fixed: no branch on size, count, history or engine. A trial +against the candidate itself (named by the caller or proposed by the ring, +even a FULL one) is not limited; pooled leaves never re-base and are +unchanged. This is a write-behaviour change for every Store, SQLite +included; reads and the format are unchanged (a FULL is an existing record). +A firing (only a decision the rule changed: a PREFIX or program that would +have been kept but was over half) counts in `full_losses` and +`DeltaCounters::rebased_full` (`BranchCounters::rebased_full` for program +pages); for a chunk the losing-base memo notes it as a loss. A whole-file object stored FULL enters the signature ring: 8,192 slots, `INDEX_BYTES` 704 KiB, rows persisted through `signatures` @@ -116,7 +176,7 @@ Decoded ordinary group bodies are kept in a `GroupCache` of 512 KiB. | COPY/INSERT | 4,096-bucket table over 16-byte seeds, 128 KiB match budget (an exhausted budget yields no program); program ≤ 64 KiB | [`pool/delta.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/delta.rs) | | Leaf record | ≤ 8,192 bytes | [`pool/leaf.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/leaf.rs) | | Program pages | candidate is the first advisory predecessor (the replaced page, or for extent pages the stored page at the same level and position) with the same role; one trial; kept only when shorter, and for a directory page only when it saves at least a quarter | [`pool/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/branch.rs), [`delta/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/branch.rs) | -| Re-base | a candidate chain at its depth cap or budgets restarts at the whole page at its root (depth one) instead of storing the page whole | [`delta/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/branch.rs) | +| Re-base | a candidate chain at its depth cap or budgets restarts at the whole page at its root (depth one) instead of storing the page whole; that program is kept only when it is at most half the whole record, else the page is stored whole (#758 fix 4) | [`delta/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/delta/branch.rs) | | Metadata chain budgets | depth 8 by default; 65,536 canonical and 139,281 encoded bytes | [`store/policy.rs`](../../../../core/crates/layerfs-storage/src/store/policy.rs) | | Read | rebuild the body from the chain, look up all ordinals in one call, rebuild the leaf, check its id; a demand of several leaves prepares up to 128 leaves (1 MiB of bodies) ahead and looks up their ordinals together | [`pool/read.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/read.rs) | | Chain memo | off unless the reader's owner asks (`PoolReader::with_chain_memo(bytes)`). The reader then keeps each chain element it rebuilt and checked against its identity (a program page's canonical bytes, a pooled leaf's body) with the depth, canonical bytes, record bytes and highest pack of the chain below it, and a later chain stops at the first element held. The depth cap, the chain budgets and the visibility ceiling are applied to the kept figures, so every answer and refusal is that of a full walk. Two generations of half the byte limit each; the old one is dropped when the young one fills | [`pool/memo.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/memo.rs), [`pool/branch.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/branch.rs), [`pool/read.rs`](../../../../core/crates/layerfs-storage/src/encoding/pool/read.rs) | @@ -140,7 +200,8 @@ refuses by version rather than inside a decode. | --- | --- | | Owner | one reader, kept read cache or Save; never shared | | Changed bytes for a cached id | `Integrity("immutable cached pack changed")` | -| Acquisition | `acquire_groups` fetches only missing groups, as one body or selected units | +| Another descriptor for a cached pack id | `Integrity("immutable cached descriptor changed")` | +| Acquisition | `acquire_groups` fetches only missing groups, as one body or selected units; `admit_groups` admits an acquisition already in hand (a group read, #758) under the same checks; `held` names the entry holding a group and its bytes, which a group read's page counts | | Work counts | `PackCacheWork`: evictions, evicted bytes, peak bytes | Pack ids only grow and published packs never change, so a kept body cannot diff --git a/docs/architecture/engine/store/README.md b/docs/architecture/engine/store/README.md index 3eff6ba720..b79bb3a01e 100644 --- a/docs/architecture/engine/store/README.md +++ b/docs/architecture/engine/store/README.md @@ -59,7 +59,7 @@ except the statements PostgreSQL replaces | Allocation | `reserve` advances `next_pack_id` and `next_ordinal` in one write; a publication may hand back an unused ordinal tail only while the cursor still ends there. | [`metadata/allocation.rs`](../../../../engine/crates/layerfs-persistence/src/metadata/allocation.rs) | | Locations and signatures | `locate` accepts only rows asked for, once each; `object_location` is insert-only, so the first publication of an object wins and later ones report it `lost`. The signature ring is an upsert by slot that keeps the newer stamp. | [`locations.rs`](../../../../engine/crates/layerfs-persistence/src/metadata/locations.rs), [`signatures.rs`](../../../../engine/crates/layerfs-persistence/src/metadata/signatures.rs) | | Value and hint blocks | Inode values and binding hints live in append-only blocks of at most 4,000 bytes and 255 entries, each ending in a CRC32C checked on every decode. Encoding is field packing only, so each entry expands to its exact canonical bytes. | [`blocks/`](../../../../engine/crates/layerfs-persistence/src/blocks), [`metadata/values.rs`](../../../../engine/crates/layerfs-persistence/src/metadata/values.rs) | -| Object reads | `read_packs`, `read_pack_selection` and `read_scoped_pack` read rows that never change once visible, so they run without `BEGIN`. | [`objects/read.rs`](../../../../engine/crates/layerfs-persistence/src/objects/read.rs) | +| Object reads | `read_packs`, `read_pack_selection` and `read_scoped_pack` read rows that never change once visible, so they run without `BEGIN`. SQLite takes the core defaults of `locate_chains` and `read_groups` (`locate`, whole packs), ignores a published locator's `base` and keeps `batched_chain_reads` false; PostgreSQL answers them from ancestor lists and ranged reads and turns it on ([delta chains](postgresql.md#delta-chains)). | [`objects/read.rs`](../../../../engine/crates/layerfs-persistence/src/objects/read.rs) | | Storage publication | `publish` validates a batch without SQL, then writes packs, locations, value blocks, the released ordinal tail and signatures in one short write. | [`publication.rs`](../../../../engine/crates/layerfs-persistence/src/storage/publication.rs) | | The publish lane | `publish_lane()` holds one admission turn plus the cross-process writer (SQLite) or the `store_lane` row (PostgreSQL) across several short transactions, so a Commit's head check, merge step and publish run as one step. | [`sqlite/lane/lane.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs), [`postgresql/lane/lane.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs) | | Diagnosis | Read-only audits over one pinned snapshot; see [Diagnostics](diagnostics.md). | [`diagnostic/`](../../../../engine/crates/layerfs-persistence/src/diagnostic) | diff --git a/docs/architecture/engine/store/diagnostics.md b/docs/architecture/engine/store/diagnostics.md index aebc674480..30b3939139 100644 --- a/docs/architecture/engine/store/diagnostics.md +++ b/docs/architecture/engine/store/diagnostics.md @@ -91,7 +91,7 @@ authority, objects or history | --- | --- | | Authentication, database or schema access and a wrong saved binding are access or authority failures; dependent coverage is blocked and no corruption is inferred. The second open validates the saved identity again. | [`postgresql.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs) | | Admission compares the saved schema source and column definition with shipped constants on the server, from permission-independent catalogs; nothing unbounded is returned to the client to compare. | [`postgresql/schema_diagnostic.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/schema_diagnostic.rs) | -| Required constraints, indexes, triggers and trigger functions are compared on the server with 210 normalized signatures from the shipped DDL; extra indexes are allowed; a different deparse on another server major is `Unknown`, not corruption. Nothing is created to do this. | [`postgresql_contract.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql_contract.rs), [`postgresql_contract_expected.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql_contract_expected.rs) | +| Required constraints, indexes, triggers, the trigger function and the ancestor-list functions are compared on the server with 215 normalized signatures from the shipped DDL; extra indexes are allowed; a different deparse on another server major is `Unknown`, not corruption. Nothing is created to do this. | [`postgresql_contract.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql_contract.rs), [`postgresql_contract_expected.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql_contract_expected.rs) | | Heap tables, materialized views and sequences get `verify_heapam(check_toast, skip=none)`; ready, valid B-tree indexes get `bt_index_check(heapallindexed)`. Other relations are `Unknown` without a call. | [`postgresql.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/postgresql.rs) | | Missing amcheck, a missing signature or denied execution is `Unknown`; SQLSTATE `XX001`/`XX002` or returned heap rows are a `Fail` for that relation. amcheck is never installed, `bt_index_parent_check` never called, offline checksums never claimed. Heap output is capped at 100 rows. | same | | Randomized multi-host admission is refused rather than changing the saved selection's meaning. | [`driver.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/driver.rs) | diff --git a/docs/architecture/engine/store/postgresql.md b/docs/architecture/engine/store/postgresql.md index 7dba0d8961..0798853394 100644 --- a/docs/architecture/engine/store/postgresql.md +++ b/docs/architecture/engine/store/postgresql.md @@ -35,11 +35,11 @@ There is no `postgresql` cargo feature: every build serves both Store kinds. | Difference from SQLite | PostgreSQL | Source | | --- | --- | --- | | Types and order | `bigint`, `bytea`; history names `COLLATE "C"`, so paging matches SQLite byte order | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | -| Pack bodies | one `bytea` per pack, `STORAGE EXTERNAL` (uncompressed, out of line) for ranged `substring` reads; no `pack_unit` table | same | -| Object locations | narrow rows; no unique key on the id but a B-tree `object_location_prefix` on its first eight bytes, with the full id compared in the heap; a location is inserted only when its id is absent, which is unique because every location insert holds the lane, including a nested one whose lane connection dies (see [the lane barrier](#lane-barrier)) | [`objects/publish.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/objects/publish.rs), [`metadata/reads.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/reads.rs) | +| Pack bodies | one `bytea` per pack, `STORAGE EXTERNAL` (uncompressed, out of line) for ranged `substring` reads; no `pack_unit` table; beside it `directory`, the pack's header and group directory (`body[0..body_offset)`, `STORAGE PLAIN`), which a CHECK holds to the body's prefix (see [delta chains](#delta-chains)) | same | +| Object locations | narrow rows; no unique key on the id but a B-tree `object_location_prefix` on its first eight bytes, with the full id compared in the heap; a location is inserted only when its id is absent, which is unique because every location insert holds the lane, including a nested one whose lane connection dies (see [the lane barrier](#lane-barrier)); each row also carries `ancestors`, its record's delta chain as a physical list (see [delta chains](#delta-chains)) | [`objects/publish.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/objects/publish.rs), [`metadata/reads.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/reads.rs) | | Short values | bounded `bytea`/`text` columns and both block bodies are `STORAGE PLAIN` (column storage in `CREATE TABLE`, PostgreSQL 16 or newer), so those tables have no TOAST relation | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | | Merge records | `pg_temp` tables of the writer connection: outside the checked schema, seen by that connection only, gone with it; writes are `Stage` transactions | [`merge_records.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/merge_records.rs) | -| Schema version | `SCHEMA_VERSION = 2`; 19 tables, or 22 with acquisition; version 1 is refused (`Integrity`), never converted | [`schema.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs) | +| Schema version | `SCHEMA_VERSION = 3` (2.0's ancestor lists and pack directories, #758); 19 tables, or 22 with acquisition; version 1 is refused (`Integrity`); version 2 is refused as `Refused` ("not supported by this release and not migrated; create a new Store") by the Full, Light and diagnostic checks before any source comparison; nothing is converted | [`schema.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs) | | File operations | none: no seal, snapshot, heads digest, checkpoint or reclamation (`Handles::file` is `None`) | [`selection.rs`](../../../../engine/crates/layerfs-persistence/src/store/selection.rs) | ## Authority and access @@ -374,6 +374,37 @@ Chosen per Store in `PostgresSelection` and applied with `SET LOCAL` to every `Write`, `Stage` and `Publish` transaction ([`config.rs`](../../../../engine/crates/layerfs-persistence/src/store/config.rs)). +## Delta chains + +\#758. A read of a delta record used to locate each base level by level, +one round trip per level. A PostgreSQL Store records each row's chain when +it publishes the row, so a cold read locates a whole chain in one wave and +reads the groups it needs in one ranged statement per 2 MiB. A chain a read +does not bind to its members (program pages, pooled leaves) costs one more +wave for all its levels: core locates them together from the base ids the +cached records at the members' positions name, each located as an ordinary +authoritative row ([physical storage](../../core/physical-storage/README.md)). + +| Piece | What it does | Source | +| --- | --- | --- | +| `object_location.ancestors` | The record's chain, nearest base first, ending at a FULL record: per base `varint(zigzag(pack - previous)) \|\| u8 group \|\| varint(record) \|\| varint(canonical_length - 1)`, `previous` starting at the row's own pack, so a child's list is its base's entry followed by the base's list verbatim. A FULL row stores `''`; `NULL` means unrecorded (never read as a chain). At most 850 bytes (50 entries of at most 17) | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | +| `ancestor_varint`, `ancestor_entry`, `ancestor_entries` | SQL functions: the first two build an entry (inlinable SQL, not `STRICT`, operands passed as columns of `OFFSET 0` subqueries so they stay inlined); `ancestor_entries` decodes a list, answering one row with a NULL pack for a malformed list. They serve publication, compaction verification and the doctor; the read path decodes lists in Rust | same | +| Publication | The rows statement ([`publish_rows.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/publish_rows.sql)) derives each new row's list from `ObjectLocation.base`: a base stored earlier gives its stored list (one more prefix probe); a base in the same batch is resolved by a recursive CTE over the batch, children after their base, at most 64 levels. A row whose base is stored nowhere, or whose list would pass 850 bytes, is left `NULL`. A lost row keeps the winner's list. The pack COPY writes `directory` with the body; rows and packs are only inserted, never updated | [`objects/publish.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/objects/publish.rs) | +| `locate_chains` | Two autocommit statements. Statement 1 ([`chain_roots.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/chain_roots.sql), `$1` ids `bytea[]`, `$2` prefix keys `bigint[]`) probes each root through `object_location_prefix` as `locate` does and returns the rows with their raw lists, plus the roots' own pack rows with directories by `pack_pkey`. The lists are decoded in Rust ([`metadata/chains.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/chains.rs)): `NULL`, `''`, malformed lists and lists deeper than the role's depth cap are dropped (the root still locates). Statement 2 ([`chain_packs.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/chain_packs.sql), `$1` member pack ids `bigint[]`) reads, by `pack_pkey`, only the member packs statement 1 did not return; it is skipped when there are none. The session keeps the pack rows both statements returned (`ChainPacks`: rows of immutable packs, per catalog incarnation, within 2 MiB of directories, cleared whole at the bound), so statement 2 reads only member packs the session has not seen; every pack a retained row's list names stays stored. A chain whose member pack is absent is dropped | [`storage/provider.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/storage/provider.rs) | +| Group reads | `read_groups` answers every read in one statement per 2 MiB of returned bytes through the multi-range `substring` reader (`objects::read::ranges`; ranges under 8 KiB apart are fetched as one span and cut in the statement): a ranged read's ranges, and a whole read's body as one range, authenticated against the descriptor it named; answers in request order, an absent pack `Missing`. `batched_chain_reads` is true, so core pages every demand (reads and Save slices) into such calls, with a handle's own published chains in the same pages | same | +| Locate | the plain locate statement is [`locate.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/locate.sql); the bench's `b8_locate.sql` is the same text | [`metadata/reads.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/reads.rs) | +| Compaction | The rebuild copies `ancestors` and `directory` with their rows, keeping pack ids and positions, so every list stays valid. Before the swap, `verify_ancestors` counts scratch rows whose list is malformed or names a pack or group the scratch Store lacks, and a non-zero count fails the round with `Integrity("compaction ancestor lists")`. A future repack that moves records must rewrite the lists. The table fingerprint includes TOAST reloptions | [`compact/build.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/compact/build.rs), [`compact/op.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/compact/op.rs) | +| Freezing | `pack`, its TOAST relation and `object_location` are insert-only, so they set `autovacuum_freeze_min_age = 0` and `autovacuum_vacuum_insert_scale_factor = 0.05`: inserted pages freeze early instead of in one wraparound pass | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | +| Doctor | `store.catalog.chain_lists` (unrecorded lists), and in a full audit `store.catalog.chain_entries` (malformed lists or entries naming no stored pack or group) and `store.catalog.chain_hints` (a first entry naming no matching row, or a list whose rest is not that row's list) | [`diagnostic/catalog.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/catalog.rs), [`diagnostic/scan.rs`](../../../../engine/crates/layerfs-persistence/src/diagnostic/scan.rs) | + +| Test | Command | Checks | +| --- | --- | --- | +| [`postgresql_ancestor_lists.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_ancestor_lists.rs) | `LAYERFS_TEST_POSTGRES_URL=… cargo +1.85.1 test --locked -p layerfs-persistence --test postgresql_ancestor_lists` | Lists equal the record-header chain in and out of a batch, for a lost base and under eight concurrent writers; a cold read of a chain costs one wave and three statements on a fresh session, two on a session that holds its member packs' rows; a corrupted entry is a counted stale hint, an error under strict hints; a schema-2 Store is refused | +| [`postgresql_group_directory.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_group_directory.rs) | same, `--test postgresql_group_directory` | `directory` is the body prefix, the CHECK refuses anything else, and the chain locate returns the root and member packs' directories; a demand past 2 MiB reads its groups in ranged pages within the amended A8 (≤ 3 round trips per wave with chains + 1 per 2 MiB) | +| [`postgresql_chain_property.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_chain_property.rs) | same, `--test postgresql_chain_property` | 40 random histories past the depth caps: exact lists, strict reads equal the default port's with no stale hint, one wave per cold file read | +| [`postgresql_history_scaling.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_history_scaling.rs) | same, `--test postgresql_history_scaling` runs stage 1; stages 2–5 by name in the order the file states | The bench workload grown to 800 versions in five staged processes over a kept schema, probed at 50, 200 and 800: equal counted read, chain locate and fresh-session Save costs, bytes per read, catalog bytes per Commit and list bytes per delta row; no row updated; locate, chain and publish statements indexed with no `Seq Scan` | +| [`postgresql_compact_fixtures.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_compact_fixtures.rs) | same, `--test postgresql_compact_fixtures` | A live chain keeps its lists across two compactions and reads strictly with no stale hint | + ## Acquisition `PostgresAcquisition` implements SQLite's acquisition port with the same row diff --git a/docs/general/cas_cdc_deltaencoding_handbook.md b/docs/general/cas_cdc_deltaencoding_handbook.md index 5eb4de5fd6..4983a32e5f 100644 --- a/docs/general/cas_cdc_deltaencoding_handbook.md +++ b/docs/general/cas_cdc_deltaencoding_handbook.md @@ -428,9 +428,14 @@ reads it unchanged. A candidate that is itself independent has no other root, so it still yields an independent result when it does not fit. The root is found by walking the stored chain through the selection's own view (located bases, including this Save's registered packs), exactly as the cost walk does. A root -grows older as the file drifts from it; once a PREFIX record against it no longer -beats the independent record, the comparison stores the independent record and -that becomes the next chain's root. `DeltaCounters.rebased` counts re-based +grows older as the file drifts from it, so since #758 fix 4 a PREFIX record +against a re-based root is kept only while it is at most half the independent +record; past that the independent record is stored and becomes the next chain's +root, so the root plus its delta never reads more than the root's independent +record plus half the target's (1.5 independent records when both are the same +size; the same limit applies to a program page's re-based program). +`rebased_full` counts only the decisions the limit changed: a re-based PREFIX +(or program) that would have been kept but was over half. `DeltaCounters.rebased` counts re-based selections; `depth_capped` counts candidates found at the cap (all re-based), and `work_exceeded` counts only the budget refusals that stored an independent record. diff --git a/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs b/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs index 8e107f1cf0..7d4c9d4d99 100644 --- a/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs +++ b/engine/crates/layerfs-persistence/examples/gc_bench/gc_fixture.rs @@ -354,6 +354,7 @@ fn publish_record( pack_id: reserved.first_pack_id, group_number: 0, record_number: 0, + base: None, }], ..Publication::default() }) diff --git a/engine/crates/layerfs-persistence/examples/pg_client_profile.rs b/engine/crates/layerfs-persistence/examples/pg_client_profile.rs new file mode 100644 index 0000000000..e2be201276 --- /dev/null +++ b/engine/crates/layerfs-persistence/examples/pg_client_profile.rs @@ -0,0 +1,231 @@ +//! #758 open risk 1 DIAGNOSTIC: per-byte cost of reading pack bodies from +//! PostgreSQL in the Rust client, by stage, against the same bytes read by +//! other clients and paths. Not a qualification; one sample per arm. +//! +//! ```text +//! cargo +1.85.1 build --locked -j 6 --release -p layerfs-persistence --example pg_client_profile +//! target/release/examples/pg_client_profile "" +//! ``` +//! +//! The pack set is every pack of `` (a Store written by +//! `storage_gate_bench`, so real pack lengths and bodies), read in pack-id +//! order. Cache state (declared): the server's buffers are warmed by one +//! unmeasured COPY of the set; every arm then reads the same set once. +//! +//! Arms, all over the same connection string (macOS host, published port): +//! - `server`: server-only time, `EXPLAIN (ANALYZE, SERIALIZE BINARY)` of the +//! batched statement (detoast and serialization, nothing sent); +//! - `copy_out`: `COPY (...) TO STDOUT (FORMAT binary)` through +//! `postgres::Client::copy_out`, bytes counted and dropped: the driver's +//! transport floor; +//! - `rows_borrow`: one prepared statement for the whole set, binary result, +//! each body borrowed as `&[u8]` (no copy); +//! - `rows_vec`: the same, each body decoded as `Vec` (one copy), the +//! product's decode; +//! - `per_pack_vec`: one statement per pack (the product's per-pack round +//! trip shape), `Vec`; +//! - `text_hex`: the simple (text) protocol, bytea as hex text, decoded; +//! - `sha256`: SHA-256 over the bodies already in memory (the product's +//! whole-pack authentication); +//! - `port_read_packs`: the product port, `PostgresStorage::read_packs` in +//! batches within its 2 MiB budget (statement, decode, copy, SHA-256). +//! +//! The non-Rust comparisons (psql inside the server container over its Unix +//! socket and over TCP in its network namespace, and a Python stdlib client +//! on the host over the published port) are run by +//! `storage_gate_bench/pg_copy_probe.py`; see `758-impl/phase0-client-profile.md`. +use layerfs_persistence::{PostgresHandles, PostgresSelection}; +use layerfs_storage::port::PackPersistence; +use postgres::{Client, NoTls, SimpleQueryMessage}; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::time::Instant; + +const BINDING: &[u8] = b"delta-hint-bench"; +const CURSOR: [u8; 32] = [58; 32]; +const BUDGET: usize = 2 * 1024 * 1024; + +fn report(arm: &str, ms: f64, bytes: u64, statements: usize) { + println!( + "arm={arm} ms={ms:.2} bytes={bytes} statements={statements} ms_per_mb={:.3} mb_per_s={:.1}", + ms / (bytes as f64 / 1e6), + bytes as f64 / 1e6 / (ms / 1e3) + ); +} + +fn hex(text: &str) -> Vec { + let raw = text.strip_prefix("\\x").expect("hex bytea").as_bytes(); + let nibble = |c: u8| match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + _ => panic!("hex digit"), + }; + raw.chunks(2) + .map(|p| (nibble(p[0]) << 4) | nibble(p[1])) + .collect() +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (url, schema) = (&args[1], &args[2]); + let mut c = Client::connect(url, NoTls).unwrap(); + let packs: Vec<(i64, i64)> = c + .query( + &format!("SELECT pack_id, length FROM {schema}.pack ORDER BY pack_id"), + &[], + ) + .unwrap() + .iter() + .map(|r| (r.get(0), r.get(1))) + .collect(); + let ids: Vec = packs.iter().map(|p| p.0).collect(); + let total: i64 = packs.iter().map(|p| p.1).sum(); + let list = ids.iter().map(i64::to_string).collect::>().join(","); + let copy = format!( + "COPY (SELECT body FROM {schema}.pack WHERE pack_id IN ({list}) ORDER BY pack_id) TO STDOUT (FORMAT binary)" + ); + println!( + "set: schema={schema} packs={} body_bytes={total} mean_pack={:.0}", + packs.len(), + total as f64 / packs.len() as f64 + ); + + // Warm the server's buffers (unmeasured). + let mut sink = Vec::new(); + c.copy_out(copy.as_str()) + .unwrap() + .read_to_end(&mut sink) + .unwrap(); + + // server + let plan = c + .query( + &format!("EXPLAIN (ANALYZE, SERIALIZE BINARY, TIMING OFF, SUMMARY ON, FORMAT TEXT) SELECT body FROM {schema}.pack WHERE pack_id = ANY($1) ORDER BY pack_id"), + &[&ids], + ) + .unwrap(); + for row in &plan { + let line: String = row.get(0); + if line.contains("Execution Time") || line.contains("Serialization") { + println!("arm=server {}", line.trim()); + } + } + + // copy_out + let t = Instant::now(); + let mut reader = c.copy_out(copy.as_str()).unwrap(); + let mut buffer = vec![0u8; 1 << 20]; + let mut wire = 0u64; + loop { + let n = reader.read(&mut buffer).unwrap(); + if n == 0 { + break; + } + wire += n as u64; + } + drop(reader); + report("copy_out", t.elapsed().as_secs_f64() * 1e3, wire, 1); + + let batched = c + .prepare(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id = ANY($1) ORDER BY pack_id" + )) + .unwrap(); + // rows_borrow + let t = Instant::now(); + let rows = c.query(&batched, &[&ids]).unwrap(); + let mut n = 0u64; + for row in &rows { + n += row.get::<_, &[u8]>(0).len() as u64; + } + report("rows_borrow", t.elapsed().as_secs_f64() * 1e3, n, 1); + drop(rows); + + // rows_vec + let t = Instant::now(); + let rows = c.query(&batched, &[&ids]).unwrap(); + let bodies: Vec> = rows.iter().map(|r| r.get::<_, Vec>(0)).collect(); + let n: u64 = bodies.iter().map(|b| b.len() as u64).sum(); + report("rows_vec", t.elapsed().as_secs_f64() * 1e3, n, 1); + drop(rows); + + // per_pack_vec + let one = c + .prepare(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id = $1" + )) + .unwrap(); + let t = Instant::now(); + let mut n = 0u64; + for id in &ids { + let row = c.query_one(&one, &[id]).unwrap(); + n += row.get::<_, Vec>(0).len() as u64; + } + report( + "per_pack_vec", + t.elapsed().as_secs_f64() * 1e3, + n, + ids.len(), + ); + + // text_hex + let t = Instant::now(); + let messages = c + .simple_query(&format!( + "SELECT body FROM {schema}.pack WHERE pack_id IN ({list}) ORDER BY pack_id" + )) + .unwrap(); + let received = t.elapsed().as_secs_f64() * 1e3; + let mut n = 0u64; + for m in &messages { + if let SimpleQueryMessage::Row(r) = m { + n += hex(r.get(0).unwrap()).len() as u64; + } + } + let decoded = t.elapsed().as_secs_f64() * 1e3; + println!("arm=text_hex received_ms={received:.2} (hex text, 2x bytes on the wire)"); + report("text_hex", decoded, n, 1); + drop(messages); + + // sha256 + let t = Instant::now(); + let mut acc = 0u8; + for b in &bodies { + acc ^= Sha256::digest(b)[0]; + } + report("sha256", t.elapsed().as_secs_f64() * 1e3, n, 0); + std::hint::black_box(acc); + drop(bodies); + + // port_read_packs + let handles = + PostgresHandles::open_read_only(&PostgresSelection::new(url, schema), BINDING, CURSOR) + .unwrap(); + let port = handles.storage.clone(); + let mut batches: Vec> = vec![Vec::new()]; + let mut held = 0usize; + for (id, length) in &packs { + if held + *length as usize > BUDGET && !batches.last().unwrap().is_empty() { + batches.push(Vec::new()); + held = 0; + } + held += *length as usize; + batches.last_mut().unwrap().push(*id); + } + let w0 = port.diagnostics().unwrap(); + let t = Instant::now(); + let mut out = Vec::new(); + let mut n = 0u64; + for batch in &batches { + port.read_packs(batch, &mut out).unwrap(); + n += out.iter().map(|p| p.body().len() as u64).sum::(); + } + let ms = t.elapsed().as_secs_f64() * 1e3; + let w1 = port.diagnostics().unwrap(); + report( + "port_read_packs", + ms, + n, + (w1.statements - w0.statements) as usize, + ); +} diff --git a/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs b/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs new file mode 100644 index 0000000000..8ed33b9816 --- /dev/null +++ b/engine/crates/layerfs-persistence/examples/storage_gate_bench.rs @@ -0,0 +1,95 @@ +//! #758 release-gate benchmark rows B1-B4, B7 and B8 (spec `SPEC-758-2.0.md` +//! section 5), each one bounded command, longer rows as resumable steps. +//! +//! Build once (release, as the baselines were): +//! +//! ```text +//! cargo +1.85.1 build --locked -j 6 --release -p layerfs-persistence --example storage_gate_bench +//! BIN=target/release/examples/storage_gate_bench +//! U="host=127.0.0.1 port=55758 user=postgres dbname=postgres sslmode=disable" +//! export LAYERFS_CONSTRUCTION_WORKERS=1 +//! ``` +//! +//! Server: the dedicated bench container `lfs-bench-758-pg` (published port +//! 55758; `GATE_PG_CONTAINER` overrides the name used for wire bytes, guest +//! space and netem). Shipped defaults (`synchronous_commit = local`); `SYNC=off` +//! only for B6-style diagnostics. Add `--strict-hints` to every read row once +//! Phase 1's switch is wired (`common::strict`, marked HOOK); until then it +//! is refused as NOT_WIRED. +//! +//! | Row | Commands, in order | Key output | +//! |---|---|---| +//! | B1 | `$BIN b1 postgresql "$U" g0_b1 g0` | `write:` `catalog:` `cold_read:` (as the baselines), `cold_read_counters:`, `cold_read_bytes:` (`model_per_read` (gate), `model_union`, `ratio_product`, `ratio_union`), `cold_read_server:` | +//! | B2 | `$BIN netem add`; `$BIN b1 postgresql "$U" g0_b2 g0+1ms`; `$BIN netem del` | as B1; `arm: rtt_select1_median_us` shows the delay | +//! | B3 | `$BIN reset "$U" g0_b3`; `$BIN b3 build "$U" g0_b3 --to 4`; `... --to 7`; `... --to 10`; `$BIN b3 read "$U" g0_b3` | `b3_save:` per version; `b3_cold_read:` (`locate_waves`, `round_trips`, `a8_budget_round_trips`), `b3_cold_read_bytes:` (`model_per_read`, `model_union`, `ratio_product`, `ratio_union`) | +//! | B4 | `$BIN b4 save "$U" g0_b3` (after B3) | `b4_shape:`, `b4_construct:`, `b4_save:` (`packs_added`, `shape_ok`, `base_fetch_round_trips` (client-attributed base locates + base reads), `membership_locates`, `old_base_fetch_round_trips`, per-class calls) | +//! | B7 | `$BIN reset "$U" g0_b7`; `b7 grow --to 100`; `b7 probe`; `b7 grow --to 400`; `b7 probe`; `b7 grow --to 1000`; `b7 grow --to 1600`; `b7 probe` (each `"$U" g0_b7`, probes with `--chain-sql FILE` once Phase 2 exists) | `b7_grow:`, `b7_catalog:`, `b7_cold_read:`, `b7_chain_statement:`, `b7_save:` | +//! | B8 | per size S in {`g0_b8_x1` (copy 0), `g0_b8_x10` (copies 0-9)}: `b8 create "$U" S --pack-lengths packs.tsv`; `b8 load "$U" S --copy C` per copy; `b8 index`; [`b8 sql "$U" S extra.sql`]; `b8 analyze`; `b8 samples [--commit-packs FILE]` (FILE adds the B5 real-history samples `early`/`late`); `b8 measure "$U" S --sql STATEMENT --label L`; after both sizes, `b8 drop` each | `b8_catalog:` (`bytes_per_locator`), `b8_statement:` per sample (`exec_ms`, `buffers`, `plan_md5`, `plan`); `b5_real_history:` (late vs early) | +//! +//! `b8 measure` with `storage_gate_bench/b8_locate.sql` runs today's locate +//! statement; the Phase 2 chain statement goes in a file of the same form +//! (`{schema}`, `$1` ids `bytea[]`, optional `$2` keys `bigint[]`). The +//! `g0_b8_x1` measurement is also the B5 row (real locators, product row). +//! `b8 space` prints the Docker guest's free bytes; `load` refuses a copy +//! that would leave under 20 GiB. +//! +//! **Counters.** `statements`/`round_trips`/`prepares` are the port's own +//! `SqlWork` (the baselines' counters). Server time and the per-class call +//! counts come from `pg_stat_statements`, reset before each phase, the +//! bench's own statements excluded (`monitor`). Wire bytes are the server +//! container's `eth0` counters read before and after, outside timed regions. +//! The needed-groups model is in `storage_gate_bench/model.rs`. +//! +//! **Cache state (declared).** As the baselines: each read row's reader is a +//! fresh `Storage` (empty locator and pack caches); the server's buffers are +//! warm (the Store was just written). B8 runs one unmeasured execution before +//! its one measured EXPLAIN. One sample per case; nothing is rerun for a +//! number. Size overrides (`VERSIONS`, `FILES_*`, `B3_MIB`, `B4_FILES`) exist +//! for smoke runs only; rows print `gate_size=false` when one is set. +//! +//! Every command fits the 2-minute limit at gate size except where the +//! how-to (`758-impl/phase0-bench-howto.md`) says otherwise; split B3/B7 +//! steps further with smaller `--to` increments if a step approaches it. + +#[path = "storage_gate_bench/b1.rs"] +mod b1; +#[path = "storage_gate_bench/b7.rs"] +mod b7; +#[path = "storage_gate_bench/b8.rs"] +mod b8; +#[path = "storage_gate_bench/common.rs"] +mod common; +#[path = "storage_gate_bench/large.rs"] +mod large; +#[path = "storage_gate_bench/model.rs"] +mod model; +#[path = "storage_gate_bench/monitor.rs"] +mod monitor; + +fn main() { + let args: Vec = std::env::args().collect(); + let row = args.get(1).map(String::as_str).unwrap_or(""); + let step = args.get(2).map(String::as_str).unwrap_or(""); + match (row, step) { + ("b1", _) => b1::run(&args), + ("b3", "build") => large::b3_build(&args), + ("b3", "read") => large::b3_read(&args), + ("b4", "save") => large::b4_save(&args), + ("b7", "grow") => b7::grow(&args), + ("b7", "probe") => b7::probe(&args), + ("b8", _) => b8::run(&args), + ("netem", action) => std::process::exit(monitor::netem(action)), + ("reset", _) => large::reset(&args), + _ => { + eprintln!( + "usage: storage_gate_bench b1 (postgresql | sqlite )