diff --git a/.github/workflows/continuum-rust-tests.yml b/.github/workflows/continuum-rust-tests.yml index af08d71095..ccafd76a32 100644 --- a/.github/workflows/continuum-rust-tests.yml +++ b/.github/workflows/continuum-rust-tests.yml @@ -211,6 +211,12 @@ jobs: if: fromJSON(needs.changes.outputs.lib_tests)[matrix.crate] run: cargo test --locked -p "$CRATE" --lib --profile dev-fast --features "$FEATURES" + # ---- continuum-pack: the base layer's load/store keeps its compiler lock (no unwrap, expect or + # panic outside tests; lib.rs) and lint-clean, with its derive; the --lib step above built it ---- + - name: cargo clippy -p continuum-pack -p continuum-pack-derive + if: matrix.crate == 'continuum-pack' + run: cargo clippy --locked -p continuum-pack -p continuum-pack-derive --profile dev-fast --all-targets --features continuum-pack/conformance -- -D warnings + # ---- continuum-mind: lib tests, compile-fail doc guards ---- - name: cargo test -p continuum-mind --lib if: matrix.crate == 'continuum-mind' diff --git a/Cargo.lock b/Cargo.lock index c6dc1d7367..8109cfb8c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3587,6 +3587,31 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "continuum-pack" +version = "0.1.0" +dependencies = [ + "bytes", + "continuum-base", + "continuum-host", + "continuum-pack-derive", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror 2.0.18", + "tracing", +] + +[[package]] +name = "continuum-pack-derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "continuum-perception" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 34940c3f8f..9be83ff966 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ members = [ "core/continuum-cli-lifecycle", "core/continuum-tool-protocol", "core/continuum-base", + "core/continuum-pack", + "core/continuum-pack-derive", "core/continuum-git", "core/continuum-host", "core/continuum-context", @@ -282,6 +284,11 @@ candle-core = { version = "0.9" } candle-nn = { version = "0.9" } candle-transformers = { version = "0.9" } +# The base layer's one load/store (docs/architecture/PACKAGES.md): any crate packs its state +# with `continuum-pack.workspace = true` (trait, derive, stores; `features = ["conformance"]` +# in dev-dependencies for the generic suite). +continuum-pack = { path = "core/continuum-pack" } + # Serialization serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -509,7 +516,7 @@ longest_first = [ ] # Audited with their crate name as a path prefix (`continuum-base/time/mod.rs`), not unprefixed # like the modules cut out of core (source-hygiene lib.rs `audited_files`). -split_prefixed = ["continuum-base"] +split_prefixed = ["continuum-base", "continuum-pack", "continuum-pack-derive"] # Tested but in no per-file ratchet yet (card 996e3537). unaudited = ["continuum-host"] # Not counted by the warnings ratchet yet: base (a split crate outside the count), kernel (~13 diff --git a/core/continuum-host/src/durable/mod.rs b/core/continuum-host/src/durable/mod.rs index c46b476246..c4715023e3 100644 --- a/core/continuum-host/src/durable/mod.rs +++ b/core/continuum-host/src/durable/mod.rs @@ -1,4 +1,4 @@ -//! Durable placement: a file placed here survives a crash or power loss whole, or the call fails. +//! Durable placement: a file (or directory) placed here survives a crash or power loss whole, or the call fails. //! Every write-then-rename in the core goes through `replace` (a mutable file) or `publish_new` //! (an immutable, content-addressed one); a caller never renames and syncs by hand. //! @@ -70,7 +70,18 @@ pub fn fence(file: &File, path: &Path) -> io::Result<()> { os::sync_entries(parent(path)?) } +/// Creates the directory `dir` (its parent must exist) so its entry survives power loss. An +/// existing directory is `AlreadyExists`, as from `std::fs::create_dir`. +pub fn create_dir(dir: &Path) -> io::Result<()> { + std::fs::create_dir(dir)?; + os::sync_entries(parent(dir)?) +} + +/// The directory holding `path`; a bare relative name lives in the current directory. fn parent(path: &Path) -> io::Result<&Path> { - path.parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} has no parent directory", path.display()))) + match path.parent() { + Some(p) if p.as_os_str().is_empty() => Ok(Path::new(".")), + Some(p) => Ok(p), + None => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} has no parent directory", path.display()))), + } } diff --git a/core/continuum-host/src/durable/tests.rs b/core/continuum-host/src/durable/tests.rs index b55d98a7d9..ca29d9d6cf 100644 --- a/core/continuum-host/src/durable/tests.rs +++ b/core/continuum-host/src/durable/tests.rs @@ -49,3 +49,14 @@ fn publish_new_refuses_an_occupied_address_and_a_failed_fence_is_an_error() { fault_injection::with_failed_fence(|| assert!(fence(&file, &free).is_err())); fence(&file, &free).unwrap(); } + +// what this catches: a durable directory creation creates the entry and reports an existing one +// as AlreadyExists (a racing creator relies on that kind), on this platform's sync arm. +#[test] +fn create_dir_creates_once_and_an_existing_one_is_already_exists() { + let dir = tempfile::tempdir().unwrap(); + let made = dir.path().join("objects"); + create_dir(&made).unwrap(); + assert!(made.is_dir()); + assert_eq!(create_dir(&made).unwrap_err().kind(), io::ErrorKind::AlreadyExists); +} diff --git a/core/continuum-pack-derive/Cargo.toml b/core/continuum-pack-derive/Cargo.toml new file mode 100644 index 0000000000..074b6a82fc --- /dev/null +++ b/core/continuum-pack-derive/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "continuum-pack-derive" +version = "0.1.0" +edition = "2021" +description = "#[derive(Packable)] for continuum-pack: one line per type, #[pack(...)] attributes name each field's part (field, blob, child, requires)." + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = { version = "2", features = ["full"] } diff --git a/core/continuum-pack-derive/src/lib.rs b/core/continuum-pack-derive/src/lib.rs new file mode 100644 index 0000000000..5f69688f89 --- /dev/null +++ b/core/continuum-pack-derive/src/lib.rs @@ -0,0 +1,146 @@ +//! `#[derive(Packable)]`: one line per type. Struct attribute +//! `#[pack(kind = "gene", schema = 3, migrate = GENE_MIGRATIONS)]` (migrate optional, an +//! expression of type `&'static [continuum_pack::Migration]`); field attributes name each +//! field's part: `#[pack(blob = "media/type")]` (a `Blob`), `#[pack(child)]` (a `Handle` +//! or `Vec>`), `#[pack(requires)]` (a `Required`); an unmarked field is a `field`. + +use proc_macro::TokenStream; +use proc_macro2::TokenStream as Tokens; +use quote::quote; +use syn::{parse_macro_input, Data, DeriveInput, Expr, Fields, Ident, LitInt, LitStr}; + +#[proc_macro_derive(Packable, attributes(pack))] +pub fn derive_packable(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + match expand(&input) { + Ok(tokens) => tokens.into(), + Err(e) => e.into_compile_error().into(), + } +} + +enum Role { + Field, + Blob(LitStr), + Child, + Requires, +} + +fn expand(input: &DeriveInput) -> syn::Result { + if !input.generics.params.is_empty() { + return Err(syn::Error::new_spanned( + &input.generics, + "Packable cannot be derived for a generic type; write pack/unpack by hand", + )); + } + let Data::Struct(data) = &input.data else { + return Err(syn::Error::new_spanned( + &input.ident, + "Packable can be derived only for a struct with named fields", + )); + }; + let Fields::Named(named) = &data.fields else { + return Err(syn::Error::new_spanned( + &input.ident, + "Packable can be derived only for a struct with named fields", + )); + }; + + let (mut kind, mut schema, mut migrate): (Option, Option, Option) = + (None, None, None); + for attr in input.attrs.iter().filter(|a| a.path().is_ident("pack")) { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("kind") { + kind = Some(meta.value()?.parse()?); + } else if meta.path.is_ident("schema") { + schema = Some(meta.value()?.parse()?); + } else if meta.path.is_ident("migrate") { + migrate = Some(meta.value()?.parse()?); + } else { + return Err(meta.error("expected `kind`, `schema` or `migrate`")); + } + Ok(()) + })?; + } + let kind = kind + .ok_or_else(|| syn::Error::new_spanned(&input.ident, "missing #[pack(kind = \"...\")]"))?; + let schema = schema + .ok_or_else(|| syn::Error::new_spanned(&input.ident, "missing #[pack(schema = N)]"))?; + let schema_n: u32 = schema.base10_parse()?; + if schema_n == 0 { + return Err(syn::Error::new_spanned(&schema, "schemas start at 1")); + } + + let mut packs = Vec::new(); + let mut unpacks = Vec::new(); + for field in &named.named { + let Some(ident) = field.ident.as_ref() else { + return Err(syn::Error::new_spanned(field, "unnamed field")); + }; + let name = ident.to_string(); + let (pack, unpack) = match role(field, ident)? { + Role::Field => ( + quote! { p.field(#name, &self.#ident)?; }, + quote! { u.field(#name)? }, + ), + Role::Blob(media) => ( + quote! { p.blob_value(#name, #media, &self.#ident)?; }, + quote! { u.blob(#name, #media)? }, + ), + Role::Child => ( + quote! { ::continuum_pack::ChildPart::pack_part(&self.#ident, #name, p)?; }, + quote! { ::continuum_pack::ChildPart::unpack_part(#name, u)? }, + ), + Role::Requires => ( + quote! { p.requires(#name, ::continuum_pack::Required::to_requirement(&self.#ident))?; }, + quote! { ::continuum_pack::Required::from_requirement(#name, u.requirement(#name)?)? }, + ), + }; + packs.push(pack); + unpacks.push(quote! { #ident: #unpack }); + } + + let ty = &input.ident; + let migrations = migrate.map(|m| { + quote! { + fn migrations() -> &'static [::continuum_pack::Migration] { #m } + } + }); + Ok(quote! { + impl ::continuum_pack::Packable for #ty { + const KIND: ::continuum_pack::Kind = ::continuum_pack::Kind::new(#kind, #schema_n); + type Context = (); + fn pack(&self, p: &mut ::continuum_pack::Packer<'_>) -> ::core::result::Result<(), ::continuum_pack::PackError> { + #(#packs)* + ::core::result::Result::Ok(()) + } + fn unpack(u: &mut ::continuum_pack::Unpacker<'_>, _cx: &()) -> ::core::result::Result { + ::core::result::Result::Ok(Self { #(#unpacks),* }) + } + #migrations + } + }) +} + +fn role(field: &syn::Field, ident: &Ident) -> syn::Result { + let mut role = Role::Field; + let mut seen = false; + for attr in field.attrs.iter().filter(|a| a.path().is_ident("pack")) { + attr.parse_nested_meta(|meta| { + if seen { + return Err(meta.error(format!("field `{ident}` names more than one part role"))); + } + seen = true; + if meta.path.is_ident("blob") { + role = Role::Blob(meta.value()?.parse()?); + } else if meta.path.is_ident("child") { + role = Role::Child; + } else if meta.path.is_ident("requires") { + role = Role::Requires; + } else { + return Err(meta.error("expected `blob = \"media/type\"`, `child` or `requires`")); + } + Ok(()) + })?; + } + Ok(role) +} diff --git a/core/continuum-pack/Cargo.toml b/core/continuum-pack/Cargo.toml new file mode 100644 index 0000000000..7e0dab8d05 --- /dev/null +++ b/core/continuum-pack/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "continuum-pack" +version = "0.1.0" +edition = "2021" +description = "One load/store layer for everything a mind owns: a type says WHAT it is (Packable), a store says WHERE bytes go (Store); content-addressed Merkle DAG, one ref flip per commit (docs/architecture/PACKAGES.md)." + +[dependencies] +bytes = "1" +continuum-base = { path = "../continuum-base" } +# durable placement of blobs, refs and directories (the OS seam). +continuum-host = { path = "../continuum-host" } +continuum-pack-derive = { path = "../continuum-pack-derive" } +serde = { workspace = true } +# float_roundtrip: a manifest float must parse to the nearest double, or a load/re-save moves its id. +serde_json = { workspace = true, features = ["float_roundtrip"] } +sha2 = { workspace = true } +thiserror = { workspace = true } +# continuum_base::probe! expands to ::tracing::event!. +tracing = { workspace = true } + +[features] +# FaultStore and the generic conformance suite (pack::conformance), for this crate's tests and the +# tests of every crate whose types implement Packable; production binaries never link it. +conformance = [] + +[dev-dependencies] +tempfile = "3" diff --git a/core/continuum-pack/src/blob.rs b/core/continuum-pack/src/blob.rs new file mode 100644 index 0000000000..99f8532756 --- /dev/null +++ b/core/continuum-pack/src/blob.rs @@ -0,0 +1,174 @@ +//! Large bytes: what a store takes (`BlobSource`), what it gives back (`BlobRead`), and the +//! value a packed type holds (`Blob`): resident bytes, or a lazy reference read on demand. + +use std::fmt; +use std::io::{self, Read, Write}; +use std::sync::{Arc, OnceLock}; + +use bytes::Bytes; + +use crate::error::StoreError; +use crate::id::ContentId; +use crate::store::{read_all, read_verified, ByteRange, Store}; + +/// Bytes on their way into a store. A buffer (or an mmap's slice), a reader, or a writer +/// closure the producer fills (the engine writing a KV page); never copied first. +pub enum BlobSource<'a> { + Bytes(&'a [u8]), + Reader(&'a mut (dyn Read + 'a)), + Writer(&'a mut Fill<'a>), +} + +/// A producer that writes a blob's bytes into the store's (hashing) sink. +pub type Fill<'a> = dyn FnMut(&mut dyn Write) -> io::Result<()> + 'a; + +/// Bytes on their way out of a store: shared bytes (RAM), or a stream of known length (disk). +pub enum BlobRead { + Bytes(Bytes), + Stream { + len: u64, + reader: Box, + }, +} + +impl BlobRead { + /// Everything this read yields, in memory. + pub fn into_bytes(self) -> Result { + match self { + BlobRead::Bytes(b) => Ok(b), + BlobRead::Stream { len, reader } => read_all(reader, len), + } + } +} + +/// A blob part's value. Resident when built in memory; lazy (an id and a store) when +/// unpacked, so loading a package reads no blob until someone asks for its bytes. +#[derive(Clone)] +pub struct Blob(Arc); + +enum Inner { + /// In memory; the id is computed once, on first ask or by the store's in-flight hash. + Resident { + bytes: Bytes, + id: OnceLock, + }, + /// In a store, known by id and length. + Stored { + store: Arc, + id: ContentId, + size: u64, + }, +} + +impl Blob { + /// Bytes held in memory, to be stored when packed. + pub fn from_bytes(bytes: impl Into) -> Self { + Self(Arc::new(Inner::Resident { + bytes: bytes.into(), + id: OnceLock::new(), + })) + } + + pub(crate) fn stored(store: Arc, id: ContentId, size: u64) -> Self { + Self(Arc::new(Inner::Stored { store, id, size })) + } + + /// Length in bytes. + pub fn len(&self) -> u64 { + match &*self.0 { + Inner::Resident { bytes, .. } => bytes.len() as u64, + Inner::Stored { size, .. } => *size, + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Whether the bytes are in memory (false = a lazy reference not yet read). + pub fn is_resident(&self) -> bool { + matches!(*self.0, Inner::Resident { .. }) + } + + /// The content id. A resident blob is hashed once, on first ask (packing it sets this + /// from the store's in-flight hash, so a packed blob is never hashed twice). + pub fn content_id(&self) -> ContentId { + match &*self.0 { + Inner::Resident { bytes, id } => *id.get_or_init(|| ContentId::of(bytes)), + Inner::Stored { id, .. } => *id, + } + } + + /// All the bytes, verified against the id when they come from a store. + pub fn read_all(&self) -> Result { + match &*self.0 { + Inner::Resident { bytes, .. } => Ok(bytes.clone()), + Inner::Stored { store, id, .. } => read_verified(store.as_ref(), id), + } + } + + /// A span of the bytes, NOT verified: a span cannot be checked against a whole-blob + /// digest without reading the whole blob. Use [`Blob::read_all`] where integrity matters. + pub fn read_range_unverified(&self, start: u64, len: u64) -> Result { + let range = ByteRange::Span { start, len }; + match &*self.0 { + Inner::Resident { bytes, .. } => { + let (s, n) = range.within(&self.content_id(), bytes.len() as u64)?; + // `within` proved s + n <= bytes.len(), so both fit in usize. + Ok(bytes.slice(s as usize..(s + n) as usize)) + } + Inner::Stored { store, id, .. } => store.get(id, range)?.into_bytes(), + } + } + + /// The id if it is known without hashing (stored, or resident and already hashed). + pub(crate) fn known_id(&self) -> Option { + match &*self.0 { + Inner::Resident { id, .. } => id.get().copied(), + Inner::Stored { id, .. } => Some(*id), + } + } + + pub(crate) fn state(&self) -> BlobState<'_> { + match &*self.0 { + Inner::Resident { bytes, id } => BlobState::Resident { bytes, id }, + Inner::Stored { store, id, size } => BlobState::Stored { + store, + id: *id, + size: *size, + }, + } + } +} + +/// A packer's view of a blob: what it must write, or where it can copy from. +pub(crate) enum BlobState<'b> { + Resident { + bytes: &'b Bytes, + id: &'b OnceLock, + }, + Stored { + store: &'b Arc, + id: ContentId, + size: u64, + }, +} + +/// Two blobs are equal when their contents are: the id is the content. +impl PartialEq for Blob { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.content_id() == other.content_id() + } +} + +impl Eq for Blob {} + +impl fmt::Debug for Blob { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Blob") + .field("len", &self.len()) + .field("resident", &self.is_resident()) + .field("id", &self.known_id()) + .finish() + } +} diff --git a/core/continuum-pack/src/canonical.rs b/core/continuum-pack/src/canonical.rs new file mode 100644 index 0000000000..5974f2b0d6 --- /dev/null +++ b/core/continuum-pack/src/canonical.rs @@ -0,0 +1,280 @@ +//! RFC 8785 JSON Canonicalization Scheme (JCS): the one bytes rule for a manifest and for an +//! alloy's signed payload (forge-alloy signs JCS too), so a package id and a provenance +//! signature are computed over the same canonical form and one verifier serves both. +//! +//! - object members sorted by their names' UTF-16 code units, at every depth; +//! - numbers as ECMAScript `Number.prototype.toString` renders the IEEE-754 double; +//! - strings with only `"` `\` and the C0 controls escaped (`\b \f \n \r \t`, else `\u00xx`); +//! - no insignificant whitespace. +//! +//! An integer beyond ±2^53 has no exact double, so it is refused rather than rounded. + +use serde_json::{Number, Value}; + +/// The largest integer every JCS implementation holds exactly (2^53). +const SAFE_INTEGER: u64 = 1 << 53; + +/// A value with no canonical form. +#[derive(Debug, thiserror::Error)] +pub enum CanonicalError { + #[error("integer {0} is outside ±2^53; RFC 8785 numbers are IEEE-754 doubles")] + UnsafeInteger(Number), + #[error("number {0} has no finite double")] + NotFinite(Number), +} + +/// The RFC 8785 bytes of `value`. +pub fn canonicalize(value: &Value) -> Result, CanonicalError> { + let mut out = Vec::with_capacity(256); + write(&mut out, value)?; + Ok(out) +} + +fn write(out: &mut Vec, value: &Value) -> Result<(), CanonicalError> { + match value { + Value::Null => out.extend_from_slice(b"null"), + Value::Bool(true) => out.extend_from_slice(b"true"), + Value::Bool(false) => out.extend_from_slice(b"false"), + Value::Number(n) => write_number(out, n)?, + Value::String(s) => write_str(out, s), + Value::Array(items) => { + out.push(b'['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(b','); + } + write(out, item)?; + } + out.push(b']'); + } + Value::Object(map) => { + let mut entries: Vec<(&String, &Value)> = map.iter().collect(); + entries.sort_unstable_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16())); + out.push(b'{'); + for (i, (k, v)) in entries.into_iter().enumerate() { + if i > 0 { + out.push(b','); + } + write_str(out, k); + out.push(b':'); + write(out, v)?; + } + out.push(b'}'); + } + } + Ok(()) +} + +fn write_number(out: &mut Vec, n: &Number) -> Result<(), CanonicalError> { + if let Some(u) = n.as_u64() { + return if u <= SAFE_INTEGER { + out.extend_from_slice(u.to_string().as_bytes()); + Ok(()) + } else { + Err(CanonicalError::UnsafeInteger(n.clone())) + }; + } + if let Some(i) = n.as_i64() { + return if i.unsigned_abs() <= SAFE_INTEGER { + out.extend_from_slice(i.to_string().as_bytes()); + Ok(()) + } else { + Err(CanonicalError::UnsafeInteger(n.clone())) + }; + } + match n.as_f64() { + Some(x) if x.is_finite() => write_double(out, x, n), + _ => Err(CanonicalError::NotFinite(n.clone())), + } +} + +/// ECMAScript Number::toString(x) for a finite double. +fn write_double(out: &mut Vec, x: f64, num: &Number) -> Result<(), CanonicalError> { + if x == 0.0 { + out.push(b'0'); // both zeros + return Ok(()); + } + if x < 0.0 { + out.push(b'-'); + } + // serde_json renders a double with ryu: the shortest digits that round-trip, the closest + // on a tie, which are the digits ECMAScript chooses. Only the layout differs ("1e23", + // "0.001", "100.0"), so take digits and decimal point from it and lay them out per ES. + let text = num.to_string(); + let not_finite = || CanonicalError::NotFinite(num.clone()); + let unsigned = text.trim_start_matches('-'); + let (mantissa, exp) = match unsigned.split_once(['e', 'E']) { + Some((m, e)) => (m, e.parse::().map_err(|_| not_finite())?), + None => (unsigned, 0), + }; + let (whole, frac) = match mantissa.split_once('.') { + Some(parts) => parts, + None => (mantissa, ""), + }; + let all: Vec = whole.bytes().chain(frac.bytes()).collect(); + let lead = all.iter().take_while(|b| **b == b'0').count(); + let digits = &all[lead..]; + let digits = &digits[..digits.len() - digits.iter().rev().take_while(|b| **b == b'0').count()]; + if digits.is_empty() { + return Err(not_finite()); + } + let k = digits.len() as i32; + // value = 0.d1d2..dk × 10^n + let n = whole.len() as i32 + exp - lead as i32; + if k <= n && n <= 21 { + out.extend_from_slice(digits); + out.extend(std::iter::repeat_n(b'0', (n - k) as usize)); + } else if 0 < n && n <= 21 { + let (int, frac) = digits.split_at(n as usize); + out.extend_from_slice(int); + out.push(b'.'); + out.extend_from_slice(frac); + } else if -6 < n && n <= 0 { + out.extend_from_slice(b"0."); + out.extend(std::iter::repeat_n(b'0', (-n) as usize)); + out.extend_from_slice(digits); + } else { + let e = n - 1; + let (first, rest) = digits.split_at(1); + out.extend_from_slice(first); + if !rest.is_empty() { + out.push(b'.'); + out.extend_from_slice(rest); + } + out.push(b'e'); + out.push(if e >= 0 { b'+' } else { b'-' }); + out.extend_from_slice(e.unsigned_abs().to_string().as_bytes()); + } + Ok(()) +} + +/// JCS string escaping: `"` `\` and C0 controls; everything else verbatim UTF-8. +fn write_str(out: &mut Vec, s: &str) { + const HEX: &[u8; 16] = b"0123456789abcdef"; + out.push(b'"'); + for &b in s.as_bytes() { + match b { + b'"' => out.extend_from_slice(b"\\\""), + b'\\' => out.extend_from_slice(b"\\\\"), + b'\n' => out.extend_from_slice(b"\\n"), + b'\r' => out.extend_from_slice(b"\\r"), + b'\t' => out.extend_from_slice(b"\\t"), + 0x08 => out.extend_from_slice(b"\\b"), + 0x0c => out.extend_from_slice(b"\\f"), + 0x00..=0x1f => { + out.extend_from_slice(b"\\u00"); + out.push(HEX[usize::from(b >> 4)]); + out.push(HEX[usize::from(b & 0x0f)]); + } + _ => out.push(b), + } + } + out.push(b'"'); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn jcs(v: &Value) -> String { + String::from_utf8(canonicalize(v).unwrap()).unwrap() + } + + // what this catches: any drift from ECMAScript number rendering, using every finite + // vector of RFC 8785 Appendix B (IEEE-754 bits -> expected text): exponent thresholds at + // 1e21 and 1e-7, the shortest-digits choice on near-ties, subnormals, the extremes, -0. + #[test] + fn rfc8785_appendix_b_numbers() { + let vectors: &[(u64, &str)] = &[ + (0x0000000000000000, "0"), + (0x8000000000000000, "0"), + (0x0000000000000001, "5e-324"), + (0x8000000000000001, "-5e-324"), + (0x7fefffffffffffff, "1.7976931348623157e+308"), + (0xffefffffffffffff, "-1.7976931348623157e+308"), + (0x4340000000000000, "9007199254740992"), + (0xc340000000000000, "-9007199254740992"), + (0x4430000000000000, "295147905179352830000"), + (0x44b52d02c7e14af5, "9.999999999999997e+22"), + (0x44b52d02c7e14af6, "1e+23"), + (0x44b52d02c7e14af7, "1.0000000000000001e+23"), + (0x444b1ae4d6e2ef4e, "999999999999999700000"), + (0x444b1ae4d6e2ef4f, "999999999999999900000"), + (0x444b1ae4d6e2ef50, "1e+21"), + (0x3eb0c6f7a0b5ed8c, "9.999999999999997e-7"), + (0x3eb0c6f7a0b5ed8d, "0.000001"), + (0x41b3de4355555553, "333333333.3333332"), + (0x41b3de4355555554, "333333333.33333325"), + (0x41b3de4355555555, "333333333.3333333"), + (0x41b3de4355555556, "333333333.3333334"), + (0x41b3de4355555557, "333333333.33333343"), + (0xbecbf647612f3696, "-0.0000033333333333333333"), + (0x43143ff3c1cb0959, "1424953923781206.2"), + ]; + for &(bits, want) in vectors { + let v = Value::from(f64::from_bits(bits)); + assert_eq!(jcs(&v), want, "bits {bits:016x}"); + } + } + + // what this catches: sorting by UTF-8 bytes or code points instead of UTF-16 code units + // (RFC 8785 §3.2.3: the emoji U+1F600 is the surrogate pair D83D DE00, so it sorts BEFORE + // U+FB33, where byte order puts it after). + #[test] + fn rfc8785_sorts_names_by_utf16_code_units() { + let v: Value = serde_json::from_str( + r#"{"\u20ac":"Euro Sign","\r":"Carriage Return","\ufb33":"Hebrew Letter Dalet With Dagesh","1":"One","\ud83d\ude00":"Emoji: Grinning Face","\u0080":"Control","\u00f6":"Latin Small Letter O With Diaeresis"}"#, + ) + .unwrap(); + assert_eq!( + jcs(&v), + "{\"\\r\":\"Carriage Return\",\"1\":\"One\",\"\u{80}\":\"Control\",\"\u{f6}\":\"Latin Small Letter O With Diaeresis\",\"\u{20ac}\":\"Euro Sign\",\"\u{1f600}\":\"Emoji: Grinning Face\",\"\u{fb33}\":\"Hebrew Letter Dalet With Dagesh\"}" + ); + } + + // what this catches: the RFC 8785 §3.2.2 example end to end (parse, then canonicalize): + // number re-rendering (4.50 -> 4.5, 1E30 -> 1e+30), string escapes (\u000F -> \u000f, + // \/ -> /), literals and member order. It also proves serde_json parses the hard decimal + // 333333333.33333329 to the nearest double (the `float_roundtrip` feature). + #[test] + fn rfc8785_section_3_2_2_example() { + let v: Value = serde_json::from_str( + r#"{"numbers":[333333333.33333329,1E30,4.50,2e-3,0.000000000000000000000000001],"string":"\u20ac$\u000F\u000aA'\u0042\u0022\u005c\\\"\/","literals":[null,true,false]}"#, + ) + .unwrap(); + assert_eq!( + jcs(&v), + "{\"literals\":[null,true,false],\"numbers\":[333333333.3333333,1e+30,4.5,0.002,1e-27],\"string\":\"\u{20ac}$\\u000f\\nA'B\\\"\\\\\\\\\\\"/\"}" + ); + } + + // what this catches: map order never reaches the bytes, and canonical bytes re-parse and + // re-encode to themselves (a manifest's id is stable across a load/save round trip). + #[test] + fn source_order_never_reaches_the_bytes() { + let a: Value = + serde_json::from_str(r#"{"b":1,"a":{"z":[true,null],"y":"q\"\n\u0001é"}}"#).unwrap(); + let b = json!({"a": {"y": "q\"\n\u{1}é", "z": [true, null]}, "b": 1}); + let bytes = canonicalize(&a).unwrap(); + assert_eq!(bytes, canonicalize(&b).unwrap()); + assert_eq!(bytes, r#"{"a":{"y":"q\"\n\u0001é","z":[true,null]},"b":1}"#.as_bytes()); + assert_eq!(canonicalize(&serde_json::from_slice(&bytes).unwrap()).unwrap(), bytes); + } + + // what this catches: an integer no double holds exactly is refused, never silently rounded + // into an id a JavaScript or Python verifier would compute differently; 2^53 itself passes. + #[test] + fn integers_beyond_2_pow_53_are_refused() { + assert_eq!(jcs(&json!(9_007_199_254_740_992u64)), "9007199254740992"); + assert_eq!(jcs(&json!(-9_007_199_254_740_992i64)), "-9007199254740992"); + assert!(matches!( + canonicalize(&json!({"size": 9_007_199_254_740_993u64})), + Err(CanonicalError::UnsafeInteger(_)) + )); + assert!(matches!( + canonicalize(&json!([i64::MIN])), + Err(CanonicalError::UnsafeInteger(_)) + )); + } +} diff --git a/core/continuum-pack/src/conformance.rs b/core/continuum-pack/src/conformance.rs new file mode 100644 index 0000000000..f46705341e --- /dev/null +++ b/core/continuum-pack/src/conformance.rs @@ -0,0 +1,303 @@ +//! One conformance suite for every `Packable`: implement the trait, run this, inherit the proof. +//! Compiled only for tests and the `conformance` feature. Returns a typed failure naming the +//! case instead of panicking, so a caller's test reports which contract broke. + +use std::collections::HashSet; +use std::fmt::Display; +use std::sync::Arc; + +use crate::blob::BlobSource; +use crate::canonical::canonicalize; +use crate::error::{PackError, StoreError}; +use crate::id::ContentId; +use crate::manifest::Manifest; +use crate::packable::Packable; +use crate::packer::{commit, save}; +use crate::requires::Offers; +use crate::store::{read_verified, FaultMode, FaultStore, Op, RamStore, RefName, Store}; +use crate::transport::{verify, TreeStats}; +use crate::unpacker::Loader; + +/// Two different values of the kind, what loading them needs, and recorded old manifests. +pub struct Sample { + pub a: T, + pub b: T, + pub offers: Offers, + pub recorded: Vec>, +} + +/// A manifest as an older build wrote it, and the value it must migrate to. +pub struct Recorded { + pub manifest: Vec, + pub expected: T, +} + +/// Which contract broke, and how. +#[derive(Debug)] +pub struct Failure { + pub case: &'static str, + pub detail: String, +} + +impl Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "conformance case {}: {}", self.case, self.detail) + } +} + +/// What ran, and the numbers a type-specific test can hold the kind to. +#[derive(Debug, Default)] +pub struct Report { + pub passed: Vec<&'static str>, + pub skipped: Vec<(&'static str, &'static str)>, + /// Store operations one commit of `b` over `a` takes (each was faulted, both modes). + pub commit_ops: usize, + /// The shape of `a`'s tree. + pub tree: TreeStats, + /// Store reads a load of `a` performs before anything is asked of the value. + pub gets_at_load: usize, +} + +trait Case { + fn case(self, case: &'static str) -> Result; +} + +impl Case for Result { + fn case(self, case: &'static str) -> Result { + self.map_err(|e| Failure { + case, + detail: e.to_string(), + }) + } +} + +fn require(ok: bool, case: &'static str, detail: impl FnOnce() -> String) -> Result<(), Failure> { + if ok { + Ok(()) + } else { + Err(Failure { + case, + detail: detail(), + }) + } +} + +type Fresh<'f> = &'f dyn Fn() -> Result, StoreError>; + +/// Run every case. `fresh` makes a new, empty store of the medium under test. +pub fn conformance( + sample: &Sample, + cx: &T::Context, + fresh: Fresh<'_>, +) -> Result { + let mut report = Report::default(); + let name = RefName::new("conformance", T::KIND.name).case("ref name")?; + let a_id = save(fresh().case("store")?.as_ref(), &sample.a).case("save")?; + let b_id = save(fresh().case("store")?.as_ref(), &sample.b).case("save")?; + + // round trip: load, re-pack in place and into another store; the id never moves. + let s = fresh().case("store")?; + save(s.as_ref(), &sample.a).case("round trip")?; + let x = Loader::new(s.clone(), sample.offers.clone()) + .load::(&a_id, cx) + .case("round trip")?; + let in_place = save(s.as_ref(), &x).case("round trip")?; + let elsewhere = fresh().case("store")?; + let moved = save(elsewhere.as_ref(), &x).case("round trip")?; + require(in_place == a_id && moved == a_id, "round trip", || { + format!("{a_id} re-packed as {in_place} / {moved}") + })?; + verify(elsewhere.as_ref(), &a_id).case("round trip (moved tree verifies)")?; + report.passed.push("round trip"); + + // same value, same id; different value, different id. + require(a_id != b_id, "same value same id", || { + format!("a and b share {a_id}") + })?; + report.passed.push("same value same id"); + + // one root ref flip, last. + let s = fresh().case("store")?; + commit(s.as_ref(), &name, &sample.a, None).case("one ref flip")?; + let f = FaultStore::new(s.clone()); + commit(&f, &name, &sample.b, Some(a_id)).case("one ref flip")?; + let ops = f.ops().case("one ref flip")?; + let flips = ops.iter().filter(|o| **o == Op::SetRef).count(); + require( + flips == 1 && ops.last() == Some(&Op::SetRef), + "one ref flip", + || format!("{flips} flips, ops {ops:?}"), + )?; + report.commit_ops = ops.len(); + report.passed.push("one ref flip, last"); + + // a fault at every operation leaves a loadable root: the old one, or (only when the flip + // itself completed) the new one. + for mode in [FaultMode::Before, FaultMode::After] { + for at in 1..=report.commit_ops as u64 { + let case = "fault at every op"; + let s = fresh().case(case)?; + commit(s.as_ref(), &name, &sample.a, None).case(case)?; + let f = FaultStore::failing_at(s.clone(), at, mode); + require( + commit(&f, &name, &sample.b, Some(a_id)).is_err(), + case, + || format!("fault {mode:?} at op {at} was not reported"), + )?; + let now = s.get_ref(&name).case(case)?; + let flipped = mode == FaultMode::After && at == report.commit_ops as u64; + let want = if flipped { b_id } else { a_id }; + require(now == Some(want), case, || { + format!("fault {mode:?} at op {at}: ref is {now:?}, want {want}") + })?; + Loader::new(s.clone(), sample.offers.clone()) + .load::(&want, cx) + .case(case)?; + verify(s.as_ref(), &want).case(case)?; + } + } + report.passed.push("fault at every op"); + + // a flipped byte anywhere in the tree is caught. + let s = fresh().case("store")?; + save(s.as_ref(), &sample.a).case("flipped byte")?; + let tree = nodes(s.as_ref(), &a_id).case("flipped byte")?; + + // every manifest in the tree is stored as its RFC 8785 bytes and named by their sha256, + // the id rule forge-alloy's `package` stages carry (one hash, one canonical form). + for &(node, _) in tree.iter().filter(|(_, is_manifest)| *is_manifest) { + let case = "id is sha256 of JCS bytes"; + let bytes = read_verified(s.as_ref(), &node).case(case)?; + let value: serde_json::Value = serde_json::from_slice(&bytes).case(case)?; + let jcs = canonicalize(&value).case(case)?; + require(jcs == bytes && ContentId::of(&jcs) == node, case, || { + format!("{node}: stored bytes are not their own JCS form") + })?; + } + report.passed.push("id is sha256 of JCS bytes"); + + for (node, _) in tree { + let f: Arc = Arc::new(FaultStore::tampering(s.clone(), node)); + let caught = |r: &Result<(), PackError>| matches!(r, Err(PackError::Store(StoreError::DigestMismatch { expected, .. })) if *expected == node); + let walked = verify(f.as_ref(), &a_id).map(|_| ()); + require(caught(&walked), "flipped byte", || { + format!("tampered {node}: verify gave {walked:?}") + })?; + if node == a_id { + let loaded = Loader::new(f, sample.offers.clone()) + .load::(&a_id, cx) + .map(|_| ()); + require(caught(&loaded), "flipped byte", || { + format!("tampered root: load gave {loaded:?}") + })?; + } + } + report.passed.push("flipped byte caught"); + + // an unmet requirement refuses after reading only the root manifest. + let root = + Manifest::decode(&read_verified(s.as_ref(), &a_id).case("requires")?).case("requires")?; + if root.requires.is_empty() { + report + .skipped + .push(("unmet requires", "the root records no requirement")); + } else { + let f = Arc::new(FaultStore::new(s.clone())); + let r = Loader::new(f.clone(), Offers::none()) + .load::(&a_id, cx) + .map(|_| ()); + let ops = f.ops().case("requires")?; + require( + matches!(r, Err(PackError::UnmetRequirement { .. })) && ops == [Op::Get(a_id)], + "unmet requires", + || format!("{r:?} after {ops:?}"), + )?; + report + .passed + .push("unmet requires refuses before any blob read"); + } + + // a newer schema is refused; every recorded older one migrates to its expected value. + let mut newer = root.clone(); + newer.schema = T::KIND.schema + 1; + let newer_id = s + .put(BlobSource::Bytes(&newer.encode().case("newer schema")?)) + .case("newer schema")? + .id; + let r = Loader::new(s.clone(), sample.offers.clone()) + .load::(&newer_id, cx) + .map(|_| ()); + require( + matches!(r, Err(PackError::UnknownNewerSchema { .. })), + "newer schema", + || format!("{r:?}"), + )?; + report.passed.push("newer schema refused"); + if sample.recorded.is_empty() { + report + .skipped + .push(("migration", "no recorded older schema")); + } + for rec in &sample.recorded { + let s = fresh().case("migration")?; + let old = s + .put(BlobSource::Bytes(&rec.manifest)) + .case("migration")? + .id; + let migrated = Loader::new(s.clone(), sample.offers.clone()) + .load::(&old, cx) + .case("migration")?; + let (got, want) = ( + save(s.as_ref(), &migrated).case("migration")?, + save(s.as_ref(), &rec.expected).case("migration")?, + ); + require(got == want, "migration", || { + format!("{old} migrated to {got}, expected {want}") + })?; + } + if !sample.recorded.is_empty() { + report.passed.push("recorded schemas migrate"); + } + + // every distinct node is stored once, however many parents reference it. + let ram = RamStore::with_capacity(u64::MAX); + save(&ram, &sample.a).case("stored once")?; + report.tree = verify(&ram, &a_id).case("stored once")?; + let held = ram.blob_count().case("stored once")?; + require(held as u64 == report.tree.distinct, "stored once", || { + format!("{held} blobs for {:?}", report.tree) + })?; + report.passed.push("shared nodes stored once"); + + // what a load reads before the value is used (a lazy kind reads only its root). + let f = Arc::new(FaultStore::new(s.clone())); + Loader::new(f.clone(), sample.offers.clone()) + .load::(&a_id, cx) + .case("lazy load")?; + report.gets_at_load = f + .ops() + .case("lazy load")? + .iter() + .filter(|o| matches!(o, Op::Get(_))) + .count(); + report.passed.push("load measured"); + Ok(report) +} + +/// Every distinct node id under `root`, root first, with whether it is a manifest. +fn nodes(store: &dyn Store, root: &ContentId) -> Result, PackError> { + let mut out = vec![(*root, true)]; + let mut seen = HashSet::from([*root]); + let mut manifests = vec![*root]; + while let Some(id) = manifests.pop() { + for (is_child, d) in Manifest::decode(&read_verified(store, &id)?)?.links() { + if seen.insert(d.digest) { + out.push((d.digest, is_child)); + if is_child { + manifests.push(d.digest); + } + } + } + } + Ok(out) +} diff --git a/core/continuum-pack/src/error.rs b/core/continuum-pack/src/error.rs new file mode 100644 index 0000000000..3e2a9086f3 --- /dev/null +++ b/core/continuum-pack/src/error.rs @@ -0,0 +1,117 @@ +//! Typed refusals. Every failure is a variant a caller can match; none is a default value. + +use std::io; +use std::path::PathBuf; + +use crate::id::ContentId; +use crate::requires::Requirement; +use crate::store::RefName; + +/// What a store refused, and why. +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + #[error("{op} {path}: {source}")] + Io { + op: &'static str, + path: PathBuf, + source: io::Error, + }, + #[error("{op}: {source}")] + Stream { op: &'static str, source: io::Error }, + #[error("no blob {0}")] + NotFound(ContentId), + #[error("bytes read as {expected} hash to {actual}")] + DigestMismatch { + expected: ContentId, + actual: ContentId, + }, + #[error("range {start}+{len} is outside blob {id} of {size} bytes")] + RangeOutOfBounds { + id: ContentId, + start: u64, + len: u64, + size: u64, + }, + #[error("ref {name} is {found:?}, expected {expected:?}")] + RefConflict { + name: RefName, + expected: Option, + found: Option, + }, + #[error("ref {name} is unreadable: {reason}")] + RefCorrupt { name: RefName, reason: String }, + #[error("invalid ref segment {0:?}: use [A-Za-z0-9._-], not starting with '.'")] + InvalidRefName(String), + #[error("store full: {needed} more bytes over a capacity of {capacity}")] + Full { capacity: u64, needed: u64 }, + #[error("store state poisoned by a panicked writer")] + Poisoned, + /// Produced only by the `conformance` feature's `FaultStore`. + #[error("injected fault at operation {at} ({op})")] + Injected { op: &'static str, at: u64 }, +} + +/// What packing or loading refused, and why. +#[derive(Debug, thiserror::Error)] +pub enum PackError { + #[error(transparent)] + Store(#[from] StoreError), + #[error("manifest is malformed: {0}")] + Manifest(serde_json::Error), + #[error("manifest has no RFC 8785 form: {0}")] + Canonical(#[from] crate::canonical::CanonicalError), + #[error("manifest envelope format {found} is newer than {known}")] + UnknownFormat { found: u32, known: u32 }, + #[error("expected a {expected} package, found {found}")] + KindMismatch { + expected: &'static str, + found: String, + }, + #[error("{kind} schema {found} is newer than this build knows ({known})")] + UnknownNewerSchema { + kind: &'static str, + found: u32, + known: u32, + }, + #[error("{kind} has no migration from schema {from}")] + MissingMigration { kind: &'static str, from: u32 }, + #[error("{kind} migration from schema {from} failed: {reason}")] + Migration { + kind: &'static str, + from: u32, + reason: String, + }, + #[error("requirement {part} is not met here: {requirement:?}")] + UnmetRequirement { + part: String, + requirement: Requirement, + }, + #[error("requirement {part} has the wrong shape: {found:?}")] + RequirementShape { part: String, found: Requirement }, + #[error("part {part} is missing")] + MissingPart { part: String }, + #[error("part {part} is not a {expected}")] + WrongPart { + part: String, + expected: &'static str, + }, + #[error("blob {part} is {found}, expected {expected}")] + WrongMedia { + part: String, + expected: String, + found: String, + }, + #[error("part {0} is named twice")] + DuplicatePart(String), + #[error("field {part}: {source}")] + Field { + part: String, + source: serde_json::Error, + }, + #[error("ref {0} does not exist")] + RefAbsent(RefName), + #[error( + "secret part {part}: sealing to an audience lands in slice 5; refusing to store plaintext" + )] + SealingUnavailable { part: String }, +} diff --git a/core/continuum-pack/src/handle.rs b/core/continuum-pack/src/handle.rs new file mode 100644 index 0000000000..93c84e41d2 --- /dev/null +++ b/core/continuum-pack/src/handle.rs @@ -0,0 +1,142 @@ +//! `Handle`: a child package by reference. Fresh (a value to be packed) or stored (an id +//! and a loader); a stored handle reads nothing until `.load()`. + +use std::fmt; +use std::sync::{Arc, OnceLock}; + +use crate::error::PackError; +use crate::id::ContentId; +use crate::manifest::Descriptor; +use crate::packable::Packable; +use crate::packer::{pack_node, Packer}; +use crate::store::Store; +use crate::transport; +use crate::unpacker::{Loader, Unpacker}; + +/// A lazily loaded child. Clones share one state, so a child held by many parents is packed +/// once and loaded once. +pub struct Handle(Arc>); + +enum State { + Fresh { + value: Arc, + packed: OnceLock, + }, + Stored { + at: Descriptor, + loader: Arc, + loaded: OnceLock>, + }, +} + +impl Handle { + /// A value not yet stored; packing the parent packs it. + pub fn new(value: T) -> Self { + Self(Arc::new(State::Fresh { + value: Arc::new(value), + packed: OnceLock::new(), + })) + } + + pub(crate) fn stored(at: Descriptor, loader: Arc) -> Self { + Self(Arc::new(State::Stored { + at, + loader, + loaded: OnceLock::new(), + })) + } + + /// The child's id, once it is stored (always, for a handle that came from a load). + pub fn id(&self) -> Option { + match &*self.0 { + State::Fresh { packed, .. } => packed.get().map(|d| d.digest), + State::Stored { at, .. } => Some(at.digest), + } + } + + /// Whether the value is in memory (a fresh value, or a stored one already loaded). + pub fn is_loaded(&self) -> bool { + match &*self.0 { + State::Fresh { .. } => true, + State::Stored { loaded, .. } => loaded.get().is_some(), + } + } + + /// The value: fetched, verified and unpacked on first use, then shared. + pub fn load(&self, cx: &T::Context) -> Result, PackError> { + match &*self.0 { + State::Fresh { value, .. } => Ok(value.clone()), + State::Stored { at, loader, loaded } => { + if let Some(v) = loaded.get() { + return Ok(v.clone()); + } + let v = Arc::new(loader.load::(&at.digest, cx)?); + // A concurrent first load set the same content; either Arc is the value. + Ok(loaded.get_or_init(|| v).clone()) + } + } + } + + /// This child's descriptor in `store`: referenced if present, else packed or copied. + pub(crate) fn descriptor_in(&self, store: &dyn Store) -> Result { + match &*self.0 { + State::Fresh { value, packed } => { + if let Some(d) = packed.get() { + if store.has(&d.digest)? { + return Ok(d.clone()); + } + } + let d = pack_node(store, value.as_ref())?; + Ok(packed.get_or_init(|| d).clone()) + } + State::Stored { at, loader, .. } => { + if !store.has(&at.digest)? { + transport::copy(loader.store().as_ref(), store, &at.digest)?; + } + Ok(at.clone()) + } + } + } +} + +impl Clone for Handle { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl fmt::Debug for Handle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Handle") + .field("kind", &T::KIND.name) + .field("id", &self.id()) + .field("loaded", &self.is_loaded()) + .finish() + } +} + +/// A field type the derive can store as a child part (`#[pack(child)]`). +pub trait ChildPart: Sized { + fn pack_part(&self, name: &str, p: &mut Packer<'_>) -> Result<(), PackError>; + fn unpack_part(name: &str, u: &mut Unpacker<'_>) -> Result; +} + +impl ChildPart for Handle { + fn pack_part(&self, name: &str, p: &mut Packer<'_>) -> Result<(), PackError> { + p.handle(name, self) + } + + fn unpack_part(name: &str, u: &mut Unpacker<'_>) -> Result { + u.handle(name) + } +} + +impl ChildPart for Vec> { + fn pack_part(&self, name: &str, p: &mut Packer<'_>) -> Result<(), PackError> { + p.handles(name, self.iter()) + } + + fn unpack_part(name: &str, u: &mut Unpacker<'_>) -> Result { + u.handles(name) + } +} diff --git a/core/continuum-pack/src/id.rs b/core/continuum-pack/src/id.rs new file mode 100644 index 0000000000..0a6d244a8d --- /dev/null +++ b/core/continuum-pack/src/id.rs @@ -0,0 +1,185 @@ +//! `ContentId`: the one identity of every blob and manifest. Full SHA-256 on the stack; the +//! `sha256:` spelling exists only at the edges (Display, FromStr, serde). + +use std::fmt; +use std::io::{self, Write}; +use std::str::FromStr; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use sha2::{Digest, Sha256}; + +/// The algorithm prefix of the rendered form; the only algorithm this layer names. +const PREFIX: &str = "sha256:"; + +/// A blob's or a manifest's address: the SHA-256 of its bytes. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ContentId([u8; 32]); + +impl ContentId { + /// An id from raw digest bytes. + pub const fn from_digest(digest: [u8; 32]) -> Self { + Self(digest) + } + + /// The raw digest. + pub const fn digest(&self) -> &[u8; 32] { + &self.0 + } + + /// The id of `bytes`, hashed in one pass. + pub fn of(bytes: &[u8]) -> Self { + Self(Sha256::digest(bytes).into()) + } + + /// Lowercase hex of the digest, without the prefix (a file name in a store). + pub fn hex(&self) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(64); + for b in self.0 { + out.push(char::from(HEX[usize::from(b >> 4)])); + out.push(char::from(HEX[usize::from(b & 0x0f)])); + } + out + } +} + +impl fmt::Display for ContentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{PREFIX}{}", self.hex()) + } +} + +impl fmt::Debug for ContentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +/// Why a string is not a `ContentId`. One spelling only: lowercase hex after `sha256:`. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum IdError { + #[error("content id must start with `sha256:`")] + Prefix, + #[error("content id digest must be 64 hex characters, found {0}")] + Length(usize), + #[error("content id digest must be lowercase hex")] + Hex, +} + +impl FromStr for ContentId { + type Err = IdError; + + fn from_str(s: &str) -> Result { + let hex = s.strip_prefix(PREFIX).ok_or(IdError::Prefix)?; + if hex.len() != 64 { + return Err(IdError::Length(hex.len())); + } + let nibble = |c: u8| match c { + b'0'..=b'9' => Ok(c - b'0'), + b'a'..=b'f' => Ok(c - b'a' + 10), + _ => Err(IdError::Hex), + }; + let mut out = [0u8; 32]; + for (slot, pair) in out.iter_mut().zip(hex.as_bytes().chunks_exact(2)) { + *slot = (nibble(pair[0])? << 4) | nibble(pair[1])?; + } + Ok(Self(out)) + } +} + +impl Serialize for ContentId { + fn serialize(&self, s: S) -> Result { + s.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for ContentId { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + s.parse().map_err(serde::de::Error::custom) + } +} + +/// A writer that hashes every byte on its way through: a blob is hashed in flight, never +/// read back to be hashed. +pub(crate) struct HashingWriter { + inner: W, + hasher: Sha256, + written: u64, +} + +impl HashingWriter { + pub(crate) fn new(inner: W) -> Self { + Self { + inner, + hasher: Sha256::new(), + written: 0, + } + } + + /// The id and length of everything written, and the inner writer. + pub(crate) fn finish(self) -> (ContentId, u64, W) { + ( + ContentId(self.hasher.finalize().into()), + self.written, + self.inner, + ) + } +} + +impl Write for HashingWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + let n = self.inner.write(buf)?; + self.hasher.update(&buf[..n]); + self.written += n as u64; + Ok(n) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: the edge spelling round-trips exactly, and every malformed spelling + // (no prefix, short, uppercase) is refused rather than read as some other id. + #[test] + fn the_rendered_id_round_trips_and_only_one_spelling_parses() { + let id = ContentId::of(b"abc"); + let s = id.to_string(); + assert_eq!( + s, + "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!(s.parse::(), Ok(id)); + assert_eq!(serde_json::to_string(&id).unwrap(), format!("\"{s}\"")); + assert_eq!( + serde_json::from_str::(&format!("\"{s}\"")).unwrap(), + id + ); + assert_eq!(s[7..].parse::(), Err(IdError::Prefix)); + assert_eq!("sha256:abc".parse::(), Err(IdError::Length(3))); + assert_eq!( + s.to_uppercase() + .replace("SHA256", "sha256") + .parse::(), + Err(IdError::Hex) + ); + } + + // what this catches: the in-flight hash equals the one-shot hash, so a streamed blob and a + // buffered blob of the same bytes get the same id. + #[test] + fn hashing_in_flight_matches_hashing_at_once() { + let data = vec![7u8; 100_003]; + let mut w = HashingWriter::new(Vec::new()); + for chunk in data.chunks(4096) { + w.write_all(chunk).unwrap(); + } + let (id, n, out) = w.finish(); + assert_eq!((id, n, out.len()), (ContentId::of(&data), 100_003, 100_003)); + } +} diff --git a/core/continuum-pack/src/lib.rs b/core/continuum-pack/src/lib.rs new file mode 100644 index 0000000000..a29a54b8f4 --- /dev/null +++ b/core/continuum-pack/src/lib.rs @@ -0,0 +1,53 @@ +//! Packages: one load/store for every layer, any depth (docs/architecture/PACKAGES.md). +//! +//! A type says WHAT it is ([`Packable`], usually `#[derive(Packable)]`); a store says WHERE +//! bytes go ([`Store`]). A package is an RFC 8785 (JCS) manifest whose parts are inline fields, +//! content-addressed blobs and child packages, so a tree is a Merkle DAG: one root id commits +//! to every byte below it, identical subtrees are stored once, and a save of any depth +//! commits by ONE ref flip ([`commit`]). Loads are lazy ([`Handle`], [`Blob`]) and every byte +//! read is verified against the id that named it. +//! +//! A base-layer crate: it depends on `continuum-base` and `continuum-host` and nothing else in +//! Continuum, so every crate above may use it with one line. + +#![cfg_attr( + not(test), + deny(clippy::unwrap_used, clippy::expect_used, clippy::panic) +)] + +// The derive emits `::continuum_pack::` paths; this lets them resolve inside this crate too. +extern crate self as continuum_pack; + +mod blob; +mod canonical; +#[cfg(any(test, feature = "conformance"))] +pub mod conformance; +mod error; +mod handle; +mod id; +mod manifest; +mod packable; +mod packer; +mod requires; +mod store; +mod transport; +mod unpacker; + +pub use blob::{Blob, BlobRead, BlobSource, Fill}; +pub use canonical::{canonicalize, CanonicalError}; +pub use continuum_pack_derive::Packable; +pub use error::{PackError, StoreError}; +pub use handle::{ChildPart, Handle}; +pub use id::{ContentId, IdError}; +pub use manifest::{Descriptor, Manifest, Part, FORMAT, MANIFEST_MEDIA, PROVENANCE_MEDIA}; +pub use packable::{Kind, Migration, Packable}; +pub use packer::{commit, save, Packer}; +pub use requires::{Audience, Offers, Required, Requirement}; +pub use store::{read_verified, ByteRange, DiskStore, RamStore, RefName, Store, Stored}; +#[cfg(any(test, feature = "conformance"))] +pub use store::{FaultMode, FaultStore, Op}; +pub use transport::{copy, verify, TreeStats}; +pub use unpacker::{Loader, Unpacker}; + +#[cfg(test)] +mod tests; diff --git a/core/continuum-pack/src/manifest.rs b/core/continuum-pack/src/manifest.rs new file mode 100644 index 0000000000..ceed414d0b --- /dev/null +++ b/core/continuum-pack/src/manifest.rs @@ -0,0 +1,98 @@ +//! The manifest: a package's one small document. Fields inline, every other part a +//! descriptor (`mediaType`, `digest`, `size`, the OCI descriptor shape), requirements first. +//! Stored as RFC 8785 JCS bytes, so its id (sha256 of those bytes) is a pure function of the +//! value, and the same bytes rule forge-alloy signs. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::canonical; +use crate::error::PackError; +use crate::id::ContentId; +use crate::requires::Requirement; + +/// The media type of a manifest stored as a blob (a child part's descriptor carries it). +pub const MANIFEST_MEDIA: &str = "application/vnd.continuum.pack.manifest.v1+json"; + +/// The media type of a package's provenance part: a forge-alloy chain whose final stage names +/// this package's id. Only the name lives here; attaching and verifying alloys sits a layer up. +pub const PROVENANCE_MEDIA: &str = "application/vnd.forge-alloy+json"; + +/// The envelope format this build writes and reads. A newer one is refused, never guessed at. +pub const FORMAT: u32 = 1; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub format: u32, + pub kind: String, + pub schema: u32, + pub requires: BTreeMap, + pub fields: BTreeMap, + pub parts: BTreeMap, +} + +/// A non-field part: a blob, one child package, or an ordered list of children. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub enum Part { + Blob(Descriptor), + Child(Descriptor), + Children(Vec), +} + +/// Content by address: what it is, its id, how long it is. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Descriptor { + #[serde(rename = "mediaType")] + pub media_type: String, + pub digest: ContentId, + pub size: u64, +} + +impl Manifest { + pub(crate) fn new(kind: &str, schema: u32) -> Self { + Self { + format: FORMAT, + kind: kind.to_owned(), + schema, + requires: BTreeMap::new(), + fields: BTreeMap::new(), + parts: BTreeMap::new(), + } + } + + /// The RFC 8785 (JCS) bytes; the package id is their sha256. + pub fn encode(&self) -> Result, PackError> { + let value = serde_json::to_value(self).map_err(PackError::Manifest)?; // boundary: the manifest's canonical bytes are the stored/wire format + Ok(canonical::canonicalize(&value)?) + } + + /// Parse a manifest, refusing an envelope newer than this build. + pub fn decode(bytes: &[u8]) -> Result { + let m: Self = serde_json::from_slice(bytes).map_err(PackError::Manifest)?; + if m.format > FORMAT { + return Err(PackError::UnknownFormat { + found: m.format, + known: FORMAT, + }); + } + Ok(m) + } + + /// Every descriptor this manifest links to (`true` = a child manifest), in part-name order. + pub(crate) fn links(&self) -> Vec<(bool, &Descriptor)> { + let mut out = Vec::with_capacity(self.parts.len()); + for part in self.parts.values() { + match part { + Part::Blob(d) => out.push((false, d)), + Part::Child(d) => out.push((true, d)), + Part::Children(ds) => out.extend(ds.iter().map(|d| (true, d))), + } + } + out + } +} diff --git a/core/continuum-pack/src/packable.rs b/core/continuum-pack/src/packable.rs new file mode 100644 index 0000000000..22245b7689 --- /dev/null +++ b/core/continuum-pack/src/packable.rs @@ -0,0 +1,43 @@ +//! The type's side: what a package of this kind is made of. Usually derived. + +use crate::error::PackError; +use crate::manifest::Manifest; +use crate::packer::Packer; +use crate::unpacker::Unpacker; + +/// A package kind and the schema this build writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Kind { + pub name: &'static str, + pub schema: u32, +} + +impl Kind { + pub const fn new(name: &'static str, schema: u32) -> Self { + Self { name, schema } + } +} + +/// One step of a kind's migration chain: a pure rewrite of a schema-`from` manifest into +/// schema `from + 1` (the chain bumps the number). Run on load, before requirements are +/// checked and before any part is read. +#[derive(Clone, Copy)] +pub struct Migration { + pub from: u32, + pub apply: fn(&mut Manifest) -> Result<(), PackError>, +} + +/// A type that packs itself into parts and unpacks itself from them. +pub trait Packable: Sized + Send + Sync + 'static { + const KIND: Kind; + /// What loading needs from the host (a model, an embedder, keys); `()` for most kinds. + type Context: ?Sized; + + fn pack(&self, p: &mut Packer<'_>) -> Result<(), PackError>; + fn unpack(u: &mut Unpacker<'_>, cx: &Self::Context) -> Result; + + /// The recorded migrations, one per past schema; empty for a kind still on schema 1. + fn migrations() -> &'static [Migration] { + &[] + } +} diff --git a/core/continuum-pack/src/packer.rs b/core/continuum-pack/src/packer.rs new file mode 100644 index 0000000000..dc0c03b4ea --- /dev/null +++ b/core/continuum-pack/src/packer.rs @@ -0,0 +1,196 @@ +//! Packing: a value describes itself as parts; the packer stores blobs and children +//! bottom-up and writes the manifest last, so a manifest that exists has every part below it. + +use std::collections::BTreeSet; + +use serde::Serialize; + +use crate::blob::{Blob, BlobSource, BlobState}; +use crate::error::PackError; +use crate::handle::Handle; +use crate::manifest::{Descriptor, Manifest, Part, MANIFEST_MEDIA}; +use crate::packable::Packable; +use crate::requires::{Audience, Requirement}; +use crate::store::{copy_blob, RefName, Store}; + +/// The verbs a type packs itself with. Every part name is used once, across all verbs. +pub struct Packer<'s> { + store: &'s dyn Store, + manifest: Manifest, + names: BTreeSet, +} + +impl<'s> Packer<'s> { + fn new(store: &'s dyn Store, name: &str, schema: u32) -> Self { + Self { + store, + manifest: Manifest::new(name, schema), + names: BTreeSet::new(), + } + } + + fn claim(&mut self, name: &str) -> Result { + if self.names.insert(name.to_owned()) { + Ok(name.to_owned()) + } else { + Err(PackError::DuplicatePart(name.to_owned())) + } + } + + /// Small structured data, inline in the manifest. + pub fn field(&mut self, name: &str, value: &T) -> Result<(), PackError> { + let part = self.claim(name)?; + let v = serde_json::to_value(value) // boundary: a manifest field is the package's stored/wire format + .map_err(|source| PackError::Field { part: part.clone(), source })?; + self.manifest.fields.insert(part, v); + Ok(()) + } + + /// Large bytes from any source, stored as their own blob and hashed in flight. + pub fn blob( + &mut self, + name: &str, + media: &str, + src: BlobSource<'_>, + ) -> Result { + let part = self.claim(name)?; + let stored = self.store.put(src)?; + let d = Descriptor { + media_type: media.to_owned(), + digest: stored.id, + size: stored.size, + }; + self.manifest.parts.insert(part, Part::Blob(d.clone())); + Ok(d) + } + + /// A [`Blob`] value: written if resident, referenced if this store has it, copied (and + /// verified) from its own store otherwise. + pub fn blob_value(&mut self, name: &str, media: &str, blob: &Blob) -> Result<(), PackError> { + let part = self.claim(name)?; + let (digest, size) = match blob.state() { + BlobState::Resident { bytes, id } => match id.get() { + Some(known) if self.store.has(known)? => (*known, bytes.len() as u64), + _ => { + let stored = self.store.put(BlobSource::Bytes(bytes))?; + // A resident id already set is the same content's hash; nothing to record. + let _ = id.set(stored.id); + (stored.id, stored.size) + } + }, + BlobState::Stored { store, id, size } => { + if !self.store.has(&id)? { + copy_blob(store.as_ref(), self.store, &id)?; + } + (id, size) + } + }; + let d = Descriptor { + media_type: media.to_owned(), + digest, + size, + }; + self.manifest.parts.insert(part, Part::Blob(d)); + Ok(()) + } + + /// Another package, packed eagerly into the same store. + pub fn child(&mut self, name: &str, value: &C) -> Result { + let part = self.claim(name)?; + let d = pack_node(self.store, value)?; + self.manifest.parts.insert(part, Part::Child(d.clone())); + Ok(d) + } + + /// An ordered list of packages. + pub fn children<'c, C: Packable>( + &mut self, + name: &str, + values: impl IntoIterator, + ) -> Result<(), PackError> { + let part = self.claim(name)?; + let ds = values + .into_iter() + .map(|v| pack_node(self.store, v)) + .collect::, _>>()?; + self.manifest.parts.insert(part, Part::Children(ds)); + Ok(()) + } + + /// A lazy child: referenced if stored here, otherwise packed (fresh) or copied (stored). + pub fn handle(&mut self, name: &str, handle: &Handle) -> Result<(), PackError> { + let part = self.claim(name)?; + let d = handle.descriptor_in(self.store)?; + self.manifest.parts.insert(part, Part::Child(d)); + Ok(()) + } + + /// An ordered list of lazy children. + pub fn handles<'h, C: Packable>( + &mut self, + name: &str, + handles: impl IntoIterator>, + ) -> Result<(), PackError> { + let part = self.claim(name)?; + let ds = handles + .into_iter() + .map(|h| h.descriptor_in(self.store)) + .collect::, _>>()?; + self.manifest.parts.insert(part, Part::Children(ds)); + Ok(()) + } + + /// What a loader must offer before any part of this package is read. + pub fn requires(&mut self, name: &str, requirement: Requirement) -> Result<(), PackError> { + let part = self.claim(name)?; + self.manifest.requires.insert(part, requirement); + Ok(()) + } + + /// A part only `audience` may read. Sealing lands in slice 5; until then this refuses, + /// so no secret is ever stored in plaintext. + pub fn secret( + &mut self, + name: &str, + _value: &T, + _audience: &Audience, + ) -> Result<(), PackError> { + let part = self.claim(name)?; + Err(PackError::SealingUnavailable { part }) + } +} + +/// Pack `value` and everything under it into `store`; return its manifest's descriptor. +pub(crate) fn pack_node( + store: &dyn Store, + value: &T, +) -> Result { + let mut p = Packer::new(store, T::KIND.name, T::KIND.schema); + value.pack(&mut p)?; + let bytes = p.manifest.encode()?; + let stored = store.put(BlobSource::Bytes(&bytes))?; + Ok(Descriptor { + media_type: MANIFEST_MEDIA.to_owned(), + digest: stored.id, + size: stored.size, + }) +} + +/// Store `value`'s whole tree; return the root manifest's id. Names nothing: see [`commit`]. +pub fn save(store: &dyn Store, value: &T) -> Result { + Ok(pack_node(store, value)?.digest) +} + +/// Store `value`'s whole tree, then flip `name` onto its root iff `name` is at `expect`. +/// The flip is the one mutation: a failure anywhere before it leaves the old root current. +pub fn commit( + store: &dyn Store, + name: &RefName, + value: &T, + expect: Option, +) -> Result { + let root = save(store, value)?; + store.set_ref(name, root, expect)?; + continuum_base::probe!(class = "decision", verdict = "commit", kind = T::KIND.name, reference = %name, root = %root); + Ok(root) +} diff --git a/core/continuum-pack/src/requires.rs b/core/continuum-pack/src/requires.rs new file mode 100644 index 0000000000..5367c9cea1 --- /dev/null +++ b/core/continuum-pack/src/requires.rs @@ -0,0 +1,68 @@ +//! What a loader must match before any part is read, and what a host offers. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use crate::error::PackError; +use crate::id::ContentId; + +/// Who may open a sealed part: the digests of the public keys it is sealed to. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct Audience { + pub keys: BTreeSet, +} + +/// One thing a package needs from the host that loads it. Checked from the manifest, before +/// any blob is read; an unmet one is a typed refusal, never a degraded load. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub enum Requirement { + /// The exact base weights, by content. + Model(ContentId), + /// A KV layout produced by `model` in the engine's named cache `format`. + KvFormat { model: ContentId, format: String }, + /// The exact embedder whose vectors a part holds. + Embedder(ContentId), + /// A key of this audience, to open the package's sealed parts. + Key(Audience), +} + +/// What a host can satisfy. A requirement is met when it is offered exactly. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Offers(BTreeSet); + +impl Offers { + /// A host that offers nothing (only packages with no requirements load). + pub fn none() -> Self { + Self(BTreeSet::new()) + } + + /// This host also offers `requirement`. + pub fn with(mut self, requirement: Requirement) -> Self { + self.0.insert(requirement); + self + } + + /// Whether `requirement` is met here. + pub fn satisfies(&self, requirement: &Requirement) -> bool { + self.0.contains(requirement) + } +} + +/// A field type that is stored as a requirement (`#[pack(requires)]`): it converts to the +/// requirement it names and back, so the requirement is recorded once. +pub trait Required: Sized { + fn to_requirement(&self) -> Requirement; + fn from_requirement(part: &str, requirement: &Requirement) -> Result; +} + +impl Required for Requirement { + fn to_requirement(&self) -> Requirement { + self.clone() + } + + fn from_requirement(_part: &str, requirement: &Requirement) -> Result { + Ok(requirement.clone()) + } +} diff --git a/core/continuum-pack/src/store/disk.rs b/core/continuum-pack/src/store/disk.rs new file mode 100644 index 0000000000..0f2027a319 --- /dev/null +++ b/core/continuum-pack/src/store/disk.rs @@ -0,0 +1,264 @@ +//! `DiskStore`: `blobs/sha256/` and `refs//` under one root. ONE write path +//! for every byte this layer persists: a temp file under `tmp/`, synced, published (a blob by +//! create-if-absent, a ref by replace), its directory synced, every error returned. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use continuum_host::durable; + +use super::{drain, ByteRange, RefName, Store, Stored}; +use crate::blob::{BlobRead, BlobSource}; +use crate::error::StoreError; +use crate::id::{ContentId, HashingWriter}; + +/// A content-addressed store on a local file system. +pub struct DiskStore { + root: PathBuf, +} + +/// Distinguishes this process's temp files from each other (the pid separates processes). +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +fn io_err<'a>(op: &'static str, path: &'a Path) -> impl FnOnce(io::Error) -> StoreError + 'a { + move |source| StoreError::Io { + op, + path: path.to_path_buf(), + source, + } +} + +impl DiskStore { + /// Open (creating if needed) a store rooted at `root`. + pub fn open(root: impl Into) -> Result { + let store = Self { root: root.into() }; + for dir in [ + store.root.join("blobs").join("sha256"), + store.root.join("refs"), + store.root.join("tmp"), + ] { + ensure_dir(&dir)?; + } + Ok(store) + } + + pub fn root(&self) -> &Path { + &self.root + } + + /// Where a blob lives (exposed so tests and tools can prove what is on disk). + pub fn blob_path(&self, id: &ContentId) -> PathBuf { + self.root.join("blobs").join("sha256").join(id.hex()) + } + + fn ref_path(&self, name: &RefName) -> PathBuf { + self.root.join("refs").join(name.scope()).join(name.name()) + } + + /// A new, exclusively created temp file and the guard that removes it. + fn temp(&self) -> Result<(Temp, File), StoreError> { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let path = self + .root + .join("tmp") + .join(format!("{}-{seq}", std::process::id())); + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(io_err("create temp", &path))?; + Ok((Temp { path }, file)) + } +} + +/// A temp file that removes itself. Removal on drop is best effort by necessity (drop cannot +/// return an error); the failure that caused the drop has already been returned, and a +/// leftover temp holds no reachable state. +struct Temp { + path: PathBuf, +} + +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +/// Create `dir` (and parents) and make each new entry durable in its parent. +fn ensure_dir(dir: &Path) -> Result<(), StoreError> { + if dir.as_os_str().is_empty() || dir.is_dir() { + return Ok(()); + } + if let Some(parent) = dir.parent() { + ensure_dir(parent)?; + } + match durable::create_dir(dir) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(io_err("create dir", dir)(e)), + } + Ok(()) +} + +impl Store for DiskStore { + fn put(&self, src: BlobSource<'_>) -> Result { + let (temp, file) = self.temp()?; + let mut w = HashingWriter::new(BufWriter::with_capacity(1 << 20, file)); + drain(src, &mut w)?; + let (id, size, buf) = w.finish(); + let file = buf + .into_inner() + .map_err(|e| io_err("flush temp", &temp.path)(e.into_error()))?; + file.sync_all().map_err(io_err("sync temp", &temp.path))?; + drop(file); + let dest = self.blob_path(&id); + match durable::publish_new(&temp.path, &dest) { + Ok(()) => {} + // Same content is already here (an earlier put, or a racing one): finish its + // fence rather than trusting a name a racer may not have synced yet. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + let existing = OpenOptions::new() + .read(true) + .write(true) + .open(&dest) + .map_err(io_err("open blob", &dest))?; + durable::fence(&existing, &dest).map_err(io_err("sync blob", &dest))?; + } + Err(e) => return Err(io_err("publish blob", &dest)(e)), + } + Ok(Stored { id, size }) + } + + fn get(&self, id: &ContentId, range: ByteRange) -> Result { + let path = self.blob_path(id); + let mut file = match File::open(&path) { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(StoreError::NotFound(*id)), + Err(e) => return Err(io_err("open blob", &path)(e)), + }; + let size = file.metadata().map_err(io_err("stat blob", &path))?.len(); + let (start, len) = range.within(id, size)?; + if start > 0 { + file.seek(SeekFrom::Start(start)) + .map_err(io_err("seek blob", &path))?; + } + Ok(BlobRead::Stream { + len, + reader: Box::new(BufReader::with_capacity(1 << 20, file).take(len)), + }) + } + + fn has(&self, id: &ContentId) -> Result { + let path = self.blob_path(id); + path.try_exists().map_err(io_err("stat blob", &path)) + } + + fn set_ref( + &self, + name: &RefName, + to: ContentId, + expect: Option, + ) -> Result<(), StoreError> { + let path = self.ref_path(name); + let dir = self.root.join("refs").join(name.scope()); + ensure_dir(&dir)?; + // One writer per ref across processes: an exclusive lock on a sibling that is never + // deleted (deleting a lock file races the next locker). + let lock_path = dir.join(format!(".{}.lock", name.name())); + let lock = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&lock_path) + .map_err(io_err("open ref lock", &lock_path))?; + lock.lock().map_err(io_err("lock ref", &lock_path))?; + let found = self.get_ref(name)?; + if found != expect { + continuum_base::probe!(class = "decision", verdict = "ref-conflict", reference = %name); + return Err(StoreError::RefConflict { + name: name.clone(), + expected: expect, + found, + }); + } + let (temp, mut file) = self.temp()?; + file.write_all(format!("{to}\n").as_bytes()) + .map_err(io_err("write ref", &temp.path))?; + file.sync_all().map_err(io_err("sync ref", &temp.path))?; + drop(file); + durable::replace(&temp.path, &path).map_err(io_err("publish ref", &path))?; + Ok(()) + } + + fn get_ref(&self, name: &RefName) -> Result, StoreError> { + let path = self.ref_path(name); + let text = match fs::read_to_string(&path) { + Ok(t) => t, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_err("read ref", &path)(e)), + }; + text.trim_end_matches('\n') + .parse() + .map(Some) + .map_err(|e| StoreError::RefCorrupt { + name: name.clone(), + reason: format!("{e}"), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: the on-disk layout the design names (blobs/sha256/, + // refs//), an idempotent put that leaves no temp behind, a range read, a + // compare-and-swap that refuses a stale expectation, and a corrupt ref file reported as + // corrupt rather than read as "no ref". + #[test] + fn layout_idempotent_put_ranges_and_ref_cas() { + let dir = tempfile::tempdir().unwrap(); + let s = DiskStore::open(dir.path().join("store")).unwrap(); + let a = s.put(BlobSource::Bytes(b"hello world")).unwrap(); + let again = s.put(BlobSource::Bytes(b"hello world")).unwrap(); + assert_eq!(a, again); + assert_eq!(fs::read(s.blob_path(&a.id)).unwrap(), b"hello world"); + assert_eq!( + fs::read_dir(s.root().join("tmp")).unwrap().count(), + 0, + "no temp left behind" + ); + let span = s + .get(&a.id, ByteRange::Span { start: 6, len: 5 }) + .unwrap() + .into_bytes() + .unwrap(); + assert_eq!(&span[..], b"world"); + assert!(matches!( + s.get(&a.id, ByteRange::Span { start: 6, len: 6 }), + Err(StoreError::RangeOutOfBounds { .. }) + )); + + let name = RefName::new("persona", "helper").unwrap(); + let b = s.put(BlobSource::Bytes(b"other")).unwrap(); + s.set_ref(&name, a.id, None).unwrap(); + assert!(matches!( + s.set_ref(&name, b.id, None), + Err(StoreError::RefConflict { .. }) + )); + s.set_ref(&name, b.id, Some(a.id)).unwrap(); + assert_eq!(s.get_ref(&name).unwrap(), Some(b.id)); + assert_eq!( + fs::read_to_string(dir.path().join("store/refs/persona/helper")).unwrap(), + format!("{}\n", b.id) + ); + fs::write(dir.path().join("store/refs/persona/helper"), "garbage").unwrap(); + assert!(matches!( + s.get_ref(&name), + Err(StoreError::RefCorrupt { .. }) + )); + assert!(RefName::new("..", "x").is_err() && RefName::new("a/b", "x").is_err()); + } +} diff --git a/core/continuum-pack/src/store/fault.rs b/core/continuum-pack/src/store/fault.rs new file mode 100644 index 0000000000..e9c8a4592c --- /dev/null +++ b/core/continuum-pack/src/store/fault.rs @@ -0,0 +1,130 @@ +//! `FaultStore`: wraps any store, logs every operation, and fails the Nth one (before or after +//! delegating it) or flips a byte in reads of one blob. Compiled only for tests and the +//! `conformance` feature. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use bytes::{Bytes, BytesMut}; + +use super::{ByteRange, RefName, Store, Stored}; +use crate::blob::{BlobRead, BlobSource}; +use crate::error::StoreError; +use crate::id::ContentId; + +/// One logged operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Op { + Put, + Get(ContentId), + Has(ContentId), + SetRef, + GetRef, +} + +/// Where the injected fault lands relative to the real operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FaultMode { + /// The operation never reaches the inner store. + Before, + /// The operation completes, then reports failure (a sync that failed after a rename). + After, +} + +pub struct FaultStore { + inner: Arc, + fail_at: Option<(u64, FaultMode)>, + tamper: Option, + count: AtomicU64, + ops: Mutex>, +} + +impl FaultStore { + /// A pass-through that only logs. + pub fn new(inner: Arc) -> Self { + Self { + inner, + fail_at: None, + tamper: None, + count: AtomicU64::new(0), + ops: Mutex::new(Vec::new()), + } + } + + /// Fail operation number `n` (1-based). + pub fn failing_at(inner: Arc, n: u64, mode: FaultMode) -> Self { + Self { + fail_at: Some((n, mode)), + ..Self::new(inner) + } + } + + /// Flip one byte of every read of `id`. + pub fn tampering(inner: Arc, id: ContentId) -> Self { + Self { + tamper: Some(id), + ..Self::new(inner) + } + } + + /// The operations so far, in order. + pub fn ops(&self) -> Result, StoreError> { + Ok(self.ops.lock().map_err(|_| StoreError::Poisoned)?.clone()) + } + + fn run( + &self, + op: Op, + name: &'static str, + f: impl FnOnce() -> Result, + ) -> Result { + self.ops.lock().map_err(|_| StoreError::Poisoned)?.push(op); + let at = self.count.fetch_add(1, Ordering::SeqCst) + 1; + match self.fail_at { + Some((n, FaultMode::Before)) if n == at => Err(StoreError::Injected { op: name, at }), + Some((n, FaultMode::After)) if n == at => { + f().and(Err(StoreError::Injected { op: name, at })) + } + _ => f(), + } + } +} + +impl Store for FaultStore { + fn put(&self, src: BlobSource<'_>) -> Result { + self.run(Op::Put, "put", || self.inner.put(src)) + } + + fn get(&self, id: &ContentId, range: ByteRange) -> Result { + self.run(Op::Get(*id), "get", || { + let read = self.inner.get(id, range)?; + if self.tamper != Some(*id) { + return Ok(read); + } + let mut b = BytesMut::from(&read.into_bytes()?[..]); + if let Some(first) = b.first_mut() { + *first ^= 0x01; + } + Ok(BlobRead::Bytes(Bytes::from(b))) + }) + } + + fn has(&self, id: &ContentId) -> Result { + self.run(Op::Has(*id), "has", || self.inner.has(id)) + } + + fn set_ref( + &self, + name: &RefName, + to: ContentId, + expect: Option, + ) -> Result<(), StoreError> { + self.run(Op::SetRef, "set_ref", || { + self.inner.set_ref(name, to, expect) + }) + } + + fn get_ref(&self, name: &RefName) -> Result, StoreError> { + self.run(Op::GetRef, "get_ref", || self.inner.get_ref(name)) + } +} diff --git a/core/continuum-pack/src/store/mod.rs b/core/continuum-pack/src/store/mod.rs new file mode 100644 index 0000000000..f2ca2f4ff0 --- /dev/null +++ b/core/continuum-pack/src/store/mod.rs @@ -0,0 +1,196 @@ +//! The medium's side: five verbs. Blobs are immutable and named by content, so they need no +//! commit protocol; `set_ref` (a compare-and-swap of a name onto a manifest) is the only +//! mutation. + +mod disk; +#[cfg(any(test, feature = "conformance"))] +mod fault; +mod ram; + +use std::fmt; +use std::io::{self, Read}; + +use bytes::Bytes; + +pub use disk::DiskStore; +#[cfg(any(test, feature = "conformance"))] +pub use fault::{FaultMode, FaultStore, Op}; +pub use ram::RamStore; + +use crate::blob::{BlobRead, BlobSource}; +use crate::error::StoreError; +use crate::id::{ContentId, HashingWriter}; + +/// Where packages' bytes live. Every implementation verifies nothing on the caller's behalf +/// except what it hashed itself at `put`; readers verify with [`read_verified`]. +pub trait Store: Send + Sync { + /// Store bytes under their content id, hashing in flight. Idempotent. + fn put(&self, src: BlobSource<'_>) -> Result; + /// Read a blob, whole or a span. + fn get(&self, id: &ContentId, range: ByteRange) -> Result; + /// Whether the blob is here. An I/O failure is an error, never "absent". + fn has(&self, id: &ContentId) -> Result; + /// Point `name` at `to` iff it currently points at `expect` (`None` = it must not exist). + fn set_ref( + &self, + name: &RefName, + to: ContentId, + expect: Option, + ) -> Result<(), StoreError>; + /// Where `name` points, or `None` if it was never set. + fn get_ref(&self, name: &RefName) -> Result, StoreError>; +} + +/// The result of a `put`: the content's id and length. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stored { + pub id: ContentId, + pub size: u64, +} + +/// Which bytes of a blob to read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ByteRange { + Full, + Span { start: u64, len: u64 }, +} + +impl ByteRange { + /// The `(start, len)` this range selects from a blob of `size` bytes, or a typed refusal. + pub(crate) fn within(self, id: &ContentId, size: u64) -> Result<(u64, u64), StoreError> { + match self { + ByteRange::Full => Ok((0, size)), + ByteRange::Span { start, len } => match start.checked_add(len) { + Some(end) if end <= size => Ok((start, len)), + _ => Err(StoreError::RangeOutOfBounds { + id: *id, + start, + len, + size, + }), + }, + } + } +} + +/// A ref's typed name: `/`, each one path-safe segment. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct RefName { + /// `scope/name`, held as one string (the error types that carry a name stay small). + path: String, + scope_len: usize, +} + +impl RefName { + pub fn new(scope: &str, name: &str) -> Result { + let (scope, name) = (segment(scope)?, segment(name)?); + Ok(Self { + path: format!("{scope}/{name}"), + scope_len: scope.len(), + }) + } + + // Slicing cannot fail: `new` is the only constructor, and it put an ASCII `/` at + // `scope_len` with both segments non-empty ASCII. + pub fn scope(&self) -> &str { + &self.path[..self.scope_len] + } + + pub fn name(&self) -> &str { + &self.path[self.scope_len + 1..] + } +} + +impl fmt::Display for RefName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.path) + } +} + +/// One path segment a ref may use on every store: no separators, no dot-files (so no `..` and +/// no collision with a store's own `.lock`/temp names), no empty name. +fn segment(s: &str) -> Result<&str, StoreError> { + let ok = !s.is_empty() + && s.len() <= 200 + && !s.starts_with('.') + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); + if ok { + Ok(s) + } else { + Err(StoreError::InvalidRefName(s.to_owned())) + } +} + +/// Read a whole blob and prove its bytes hash to `id`. Whatever store or peer served it, a +/// mismatch is a typed refusal: stores are trusted for availability, never integrity. +pub fn read_verified(store: &dyn Store, id: &ContentId) -> Result { + let bytes = store.get(id, ByteRange::Full)?.into_bytes()?; + let actual = ContentId::of(&bytes); + if actual != *id { + continuum_base::probe!(class = "decision", verdict = "digest-mismatch", expected = %id, actual = %actual); + return Err(StoreError::DigestMismatch { + expected: *id, + actual, + }); + } + Ok(bytes) +} + +/// Copy one blob from `src` to `dst` if `dst` lacks it, verifying the bytes in flight. +pub(crate) fn copy_blob( + src: &dyn Store, + dst: &dyn Store, + id: &ContentId, +) -> Result { + match src.get(id, ByteRange::Full)? { + BlobRead::Bytes(b) => check(dst.put(BlobSource::Bytes(&b))?, id), + BlobRead::Stream { mut reader, .. } => check(dst.put(BlobSource::Reader(&mut reader))?, id), + } +} + +fn check(stored: Stored, expected: &ContentId) -> Result { + if stored.id == *expected { + Ok(stored) + } else { + Err(StoreError::DigestMismatch { + expected: *expected, + actual: stored.id, + }) + } +} + +/// Drain any source into `w` (the store's sink, wrapped in a hasher). +pub(crate) fn drain( + src: BlobSource<'_>, + w: &mut HashingWriter, +) -> Result<(), StoreError> { + let r = match src { + BlobSource::Bytes(b) => io::Write::write_all(w, b), + BlobSource::Reader(r) => io::copy(r, w).map(|_| ()), + BlobSource::Writer(f) => f(w), + }; + r.map_err(|source| StoreError::Stream { + op: "write blob", + source, + }) +} + +/// Read a whole stream (used by `BlobRead::into_bytes`). +pub(crate) fn read_all(mut reader: impl Read, len: u64) -> Result { + let cap = usize::try_from(len).map_err(|_| StoreError::Stream { + op: "read blob", + source: io::Error::new( + io::ErrorKind::OutOfMemory, + "blob larger than the address space", + ), + })?; + let mut buf = Vec::with_capacity(cap); + reader + .read_to_end(&mut buf) + .map_err(|source| StoreError::Stream { + op: "read blob", + source, + })?; + Ok(Bytes::from(buf)) +} diff --git a/core/continuum-pack/src/store/ram.rs b/core/continuum-pack/src/store/ram.rs new file mode 100644 index 0000000000..5a9d04be18 --- /dev/null +++ b/core/continuum-pack/src/store/ram.rs @@ -0,0 +1,126 @@ +//! `RamStore`: blobs as shared bytes, refs in a map, bounded by a byte capacity the caller +//! sizes. Full is a typed refusal; eviction belongs to the tier that composes stores. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Mutex, MutexGuard}; + +use bytes::Bytes; + +use super::{drain, ByteRange, RefName, Store, Stored}; +use crate::blob::{BlobRead, BlobSource}; +use crate::error::StoreError; +use crate::id::{ContentId, HashingWriter}; + +pub struct RamStore { + capacity: u64, + state: Mutex, +} + +#[derive(Default)] +struct State { + blobs: HashMap, + refs: BTreeMap, + bytes: u64, +} + +impl RamStore { + /// A store that holds at most `capacity` bytes of blobs. + pub fn with_capacity(capacity: u64) -> Self { + Self { + capacity, + state: Mutex::new(State::default()), + } + } + + fn state(&self) -> Result, StoreError> { + self.state.lock().map_err(|_| StoreError::Poisoned) + } + + /// How many distinct blobs are held. + pub fn blob_count(&self) -> Result { + Ok(self.state()?.blobs.len()) + } + + /// How many bytes of blobs are held. + pub fn bytes(&self) -> Result { + Ok(self.state()?.bytes) + } +} + +impl Store for RamStore { + fn put(&self, src: BlobSource<'_>) -> Result { + let stored = |id, b: &Bytes| Stored { + id, + size: b.len() as u64, + }; + let bytes = match src { + // A buffer is hashed and copied once; there is nothing to stream. + BlobSource::Bytes(b) => { + let id = ContentId::of(b); + if let Some(have) = self.state()?.blobs.get(&id) { + return Ok(stored(id, have)); + } + (id, Bytes::copy_from_slice(b)) + } + other => { + let mut w = HashingWriter::new(Vec::new()); + drain(other, &mut w)?; + let (id, _, buf) = w.finish(); + (id, Bytes::from(buf)) + } + }; + let (id, data) = bytes; + let mut st = self.state()?; + if let Some(have) = st.blobs.get(&id) { + return Ok(stored(id, have)); + } + let len = data.len() as u64; + if st.bytes.saturating_add(len) > self.capacity { + return Err(StoreError::Full { + capacity: self.capacity, + needed: len, + }); + } + st.bytes += len; + let out = stored(id, &data); + st.blobs.insert(id, data); + Ok(out) + } + + fn get(&self, id: &ContentId, range: ByteRange) -> Result { + let st = self.state()?; + let b = st.blobs.get(id).ok_or(StoreError::NotFound(*id))?; + let (start, len) = range.within(id, b.len() as u64)?; + // `within` proved start + len <= b.len(), so both fit in usize. + Ok(BlobRead::Bytes( + b.slice(start as usize..(start + len) as usize), + )) + } + + fn has(&self, id: &ContentId) -> Result { + Ok(self.state()?.blobs.contains_key(id)) + } + + fn set_ref( + &self, + name: &RefName, + to: ContentId, + expect: Option, + ) -> Result<(), StoreError> { + let mut st = self.state()?; + let found = st.refs.get(name).copied(); + if found != expect { + return Err(StoreError::RefConflict { + name: name.clone(), + expected: expect, + found, + }); + } + st.refs.insert(name.clone(), to); + Ok(()) + } + + fn get_ref(&self, name: &RefName) -> Result, StoreError> { + Ok(self.state()?.refs.get(name).copied()) + } +} diff --git a/core/continuum-pack/src/tests.rs b/core/continuum-pack/src/tests.rs new file mode 100644 index 0000000000..f39bd6e3c9 --- /dev/null +++ b/core/continuum-pack/src/tests.rs @@ -0,0 +1,396 @@ +//! The contract, proven on two outlier kinds: a tiny manifest-only struct with a recorded old +//! schema, and a three-level tree with multi-MB blobs, a shared child and a hand-written leaf. +//! Both run the generic conformance suite on RAM and on disk; the rest pins what is specific +//! to each shape. +#![cfg(test)] + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +use crate::conformance::{conformance, Recorded, Report, Sample}; +use crate::*; + +/// A manifest-only kind on schema 2; schema 1 called `name` `label`. +#[derive(Packable, Debug, PartialEq)] +#[pack(kind = "test.tiny", schema = 2, migrate = TINY_MIGRATIONS)] +struct Tiny { + name: String, + count: u32, + #[pack(requires)] + model: Requirement, +} + +const TINY_MIGRATIONS: &[Migration] = &[Migration { + from: 1, + apply: label_became_name, +}]; + +fn label_became_name(m: &mut Manifest) -> Result<(), PackError> { + let v = m.fields.remove("label").ok_or(PackError::MissingPart { + part: "label".into(), + })?; + m.fields.insert("name".into(), v); + Ok(()) +} + +/// Exactly what a schema-1 build wrote (canonical, recorded byte for byte). +const TINY_V1: &str = r#"{"fields":{"count":7,"label":"old"},"format":1,"kind":"test.tiny","parts":{},"requires":{"model":{"model":"sha256:1111111111111111111111111111111111111111111111111111111111111111"}},"schema":1}"#; + +fn model() -> ContentId { + ContentId::from_digest([0x11; 32]) +} + +fn tiny(name: &str, count: u32) -> Tiny { + Tiny { + name: name.into(), + count, + model: Requirement::Model(model()), + } +} + +/// A typed requirement field, the way a real kind names its base model. +#[derive(Debug, Clone, PartialEq)] +struct ModelId(ContentId); + +impl Required for ModelId { + fn to_requirement(&self) -> Requirement { + Requirement::Model(self.0) + } + + fn from_requirement(part: &str, r: &Requirement) -> Result { + match r { + Requirement::Model(id) => Ok(Self(*id)), + other => Err(PackError::RequirementShape { + part: part.into(), + found: other.clone(), + }), + } + } +} + +#[derive(Packable, Debug)] +#[pack(kind = "test.root", schema = 1)] +struct Root { + title: String, + #[pack(blob = "application/octet-stream")] + weights: Blob, + #[pack(child)] + primary: Handle, + #[pack(child)] + parents: Vec>, + #[pack(requires)] + base: ModelId, +} + +#[derive(Packable, Debug)] +#[pack(kind = "test.mid", schema = 1)] +struct Mid { + #[pack(blob = "application/vnd.test.page")] + page: Blob, + #[pack(child)] + leaf: Handle, +} + +/// Hand-written, to prove the trait and the derive meet in one tree. +#[derive(Debug, PartialEq)] +struct Leaf { + note: String, + tags: Vec, +} + +impl Packable for Leaf { + const KIND: Kind = Kind::new("test.leaf", 1); + type Context = (); + + fn pack(&self, p: &mut Packer<'_>) -> Result<(), PackError> { + p.field("note", &self.note)?; + p.field("tags", &self.tags) + } + + fn unpack(u: &mut Unpacker<'_>, _cx: &()) -> Result { + Ok(Self { + note: u.field("note")?, + tags: u.field("tags")?, + }) + } +} + +fn noise(len: usize, seed: u64) -> Vec { + let mut x = seed | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +fn tree(title: &str, note: &str) -> Root { + let leaf = Handle::new(Leaf { + note: note.into(), + tags: vec!["a".into(), "b".into()], + }); + let m1 = Handle::new(Mid { + page: Blob::from_bytes(noise(1 << 20, 2)), + leaf: leaf.clone(), + }); + let m2 = Handle::new(Mid { + page: Blob::from_bytes(noise(64 << 10, 3)), + leaf, + }); + Root { + title: title.into(), + weights: Blob::from_bytes(noise(3 << 20, 1)), + primary: m1.clone(), + parents: vec![m1, m2], + base: ModelId(model()), + } +} + +fn ram() -> Result, StoreError> { + Ok(Arc::new(RamStore::with_capacity(u64::MAX))) +} + +/// A fresh DiskStore per call, each in its own directory under one temp root. +fn disks(root: &tempfile::TempDir) -> impl Fn() -> Result, StoreError> + '_ { + let n = AtomicU64::new(0); + move || { + Ok(Arc::new(DiskStore::open( + root.path() + .join(n.fetch_add(1, Ordering::Relaxed).to_string()), + )?) as Arc) + } +} + +fn run>(sample: &Sample) -> (Report, Report) { + let dir = tempfile::tempdir().unwrap(); + let on_ram = conformance(sample, &(), &ram).unwrap_or_else(|f| panic!("RAM: {f}")); + let on_disk = conformance(sample, &(), &disks(&dir)).unwrap_or_else(|f| panic!("disk: {f}")); + eprintln!( + "{} on RAM: {on_ram:?}\n{} on disk: {on_disk:?}", + T::KIND.name, + T::KIND.name + ); + (on_ram, on_disk) +} + +// what this catches: the whole generic contract on the smallest kind, on both stores: round +// trip, identity, one ref flip, a fault before/after every op, a flipped byte, an unmet +// requirement read nothing but the root, a newer schema refused, and the RECORDED schema-1 +// manifest migrating to the schema-2 value. +#[test] +fn a_manifest_only_kind_conforms() { + let sample = Sample { + a: tiny("a", 1), + b: tiny("b", 2), + offers: Offers::none().with(Requirement::Model(model())), + recorded: vec![Recorded { + manifest: TINY_V1.as_bytes().to_vec(), + expected: tiny("old", 7), + }], + }; + let (r, d) = run(&sample); + for report in [&r, &d] { + assert!( + report.skipped.is_empty(), + "every case ran: {:?}", + report.skipped + ); + assert_eq!( + (report.tree.distinct, report.gets_at_load), + (1, 1), + "one manifest, one read" + ); + assert_eq!(report.commit_ops, 2, "manifest put + ref flip"); + } + // The recorded manifest is canonical: this build writes those exact bytes for schema 1, + // and its id is the one forge-alloy's shared vector pins (test-vectors/jcs.json + // `contentIds`), so a `package` stage in an alloy names it by the same hash. + let m = Manifest::decode(TINY_V1.as_bytes()).unwrap(); + assert_eq!(m.encode().unwrap(), TINY_V1.as_bytes()); + assert_eq!( + ContentId::of(TINY_V1.as_bytes()).to_string(), + "sha256:631135120fe75465ac31c0957e2acb6e38771cde30c6e67af767defa3d4857ae" + ); +} + +// what this catches: the contract on a deep, shared, multi-MB tree, plus its shape: a load +// reads only the root manifest; a shared Mid and a shared Leaf are stored once though +// referenced twice; and a whole three-level tree commits by its one root flip. +#[test] +fn a_nested_tree_with_blobs_and_shared_children_conforms() { + let sample = Sample { + a: tree("a", "leaf"), + b: tree("b", "leaf"), + offers: Offers::none().with(Requirement::Model(model())), + recorded: vec![], + }; + let (r, d) = run(&sample); + for report in [&r, &d] { + // root, weights, m1, m1.page, m2, m2.page, leaf: 7 nodes behind 9 references. + assert_eq!( + (report.tree.distinct, report.tree.references), + (7, 9), + "{:?}", + report.tree + ); + assert_eq!( + report.gets_at_load, 1, + "a lazy kind reads only its root manifest" + ); + } +} + +// what this catches: laziness end to end (a handle reads its child only on load, once, and a +// blob reads nothing until asked), and that loaded bytes equal what was packed. +#[test] +fn handles_and_blobs_load_on_first_use_only() { + let s = Arc::new(FaultStore::new(ram().unwrap())); + let original = tree("t", "leaf"); + let id = save(&*s, &original).unwrap(); + let loader = Loader::new(s.clone(), Offers::none().with(Requirement::Model(model()))); + let before = s.ops().unwrap().len(); + let root: Root = loader.load(&id, &()).unwrap(); + let gets = |from: usize| { + s.ops().unwrap()[from..] + .iter() + .filter(|o| matches!(o, Op::Get(_))) + .count() + }; + assert_eq!(gets(before), 1); + assert!(!root.primary.is_loaded() && !root.weights.is_resident()); + let mark = s.ops().unwrap().len(); + let mid = root.primary.load(&()).unwrap(); + let again = root.primary.load(&()).unwrap(); + assert!(Arc::ptr_eq(&mid, &again)); + assert_eq!( + gets(mark), + 1, + "one read for the child, none for the second load" + ); + assert_eq!(mid.leaf.load(&()).unwrap().note, "leaf"); + assert_eq!( + root.weights.read_all().unwrap(), + original.weights.read_all().unwrap() + ); + assert_eq!( + root.weights.read_range_unverified(10, 5).unwrap(), + original.weights.read_all().unwrap().slice(10..15) + ); + assert_eq!(root.title, "t"); + assert_eq!(root.base, ModelId(model())); +} + +// what this catches: the Merkle property (a change one level deep changes the root id) and +// that a flipped byte in a real file on disk is caught at the read that uses it, while the +// rest of the tree still loads. +#[test] +fn a_deep_change_moves_the_root_and_disk_corruption_is_caught_where_read() { + let ram_store = RamStore::with_capacity(u64::MAX); + assert_ne!( + save(&ram_store, &tree("t", "x")).unwrap(), + save(&ram_store, &tree("t", "y")).unwrap() + ); + + let dir = tempfile::tempdir().unwrap(); + let disk = Arc::new(DiskStore::open(dir.path()).unwrap()); + let original = tree("t", "leaf"); + let id = save(&*disk, &original).unwrap(); + let page = original.primary.load(&()).unwrap().page.content_id(); + let path = disk.blob_path(&page); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[1234] ^= 0x80; + std::fs::write(&path, bytes).unwrap(); + let root: Root = Loader::new(disk, Offers::none().with(Requirement::Model(model()))) + .load(&id, &()) + .unwrap(); + let mid = root.primary.load(&()).unwrap(); + assert!( + matches!(mid.page.read_all(), Err(StoreError::DigestMismatch { expected, .. }) if expected == page) + ); + assert!( + root.weights.read_all().is_ok(), + "the untouched blob still verifies" + ); +} + +// what this catches: refusals that must be typed, never a degraded result: a secret is never +// stored in plaintext before sealing exists; a package loaded as the wrong kind; a missing +// ref; a stale compare-and-swap at the package level. +#[test] +fn refusals_are_typed() { + struct Diary; + impl Packable for Diary { + const KIND: Kind = Kind::new("test.diary", 1); + type Context = (); + fn pack(&self, p: &mut Packer<'_>) -> Result<(), PackError> { + p.secret( + "entry", + "hers alone", + &Audience { + keys: Default::default(), + }, + ) + } + fn unpack(_: &mut Unpacker<'_>, _: &()) -> Result { + Ok(Diary) + } + } + let s = RamStore::with_capacity(u64::MAX); + assert!(matches!( + save(&s, &Diary), + Err(PackError::SealingUnavailable { .. }) + )); + assert_eq!(s.blob_count().unwrap(), 0, "nothing was written"); + + let s: Arc = ram().unwrap(); + let name = RefName::new("test", "tiny").unwrap(); + let id = commit(s.as_ref(), &name, &tiny("a", 1), None).unwrap(); + let loader = Loader::new(s.clone(), Offers::none().with(Requirement::Model(model()))); + assert!(matches!( + loader.load::(&id, &()), + Err(PackError::KindMismatch { .. }) + )); + assert!(matches!( + loader.load_ref::(&RefName::new("test", "none").unwrap(), &()), + Err(PackError::RefAbsent(_)) + )); + assert!(matches!( + commit(s.as_ref(), &name, &tiny("b", 2), None), + Err(PackError::Store(StoreError::RefConflict { .. })) + )); + assert_eq!(loader.load_ref::(&name, &()).unwrap(), tiny("a", 1)); +} + +// what this catches: the cost the design's budget rests on (SHA-256 throughput on this +// machine, and a whole DiskStore put of the same blob including fsync). Run with +// `cargo test -p continuum-pack --release -- --ignored --nocapture throughput`. +#[test] +#[ignore = "a measurement, not a check; run in release"] +fn hashing_throughput() { + let data = noise(512 << 20, 9); + let mb = data.len() as f64 / (1024.0 * 1024.0); + let best = |f: &dyn Fn()| { + (0..3) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() + }) + .fold(f64::MAX, f64::min) + }; + let hash = best(&|| { + std::hint::black_box(ContentId::of(&data)); + }); + let dir = tempfile::tempdir().unwrap(); + let n = std::cell::Cell::new(0u32); + let put = best(&|| { + n.set(n.get() + 1); + let s = DiskStore::open(dir.path().join(n.get().to_string())).unwrap(); + std::hint::black_box(s.put(BlobSource::Bytes(&data)).unwrap()); + std::fs::remove_dir_all(s.root()).unwrap(); + }); + eprintln!("sha256: {:.0} MB/s ({mb:.0} MB in {hash:.3} s); DiskStore put incl. fsync: {:.0} MB/s ({put:.3} s)", mb / hash, mb / put); +} diff --git a/core/continuum-pack/src/transport.rs b/core/continuum-pack/src/transport.rs new file mode 100644 index 0000000000..ea0c8757ca --- /dev/null +++ b/core/continuum-pack/src/transport.rs @@ -0,0 +1,85 @@ +//! The DAG between stores: walk from a root, verify or copy what is missing. Kind-agnostic, +//! so one function moves any package between any two stores. +//! +//! Invariant every writer keeps: a manifest is written after every part below it, so a store +//! that HAS a manifest has its whole subtree. `copy` relies on it to skip present subtrees. + +use std::collections::HashSet; + +use crate::blob::BlobSource; +use crate::error::{PackError, StoreError}; +use crate::id::ContentId; +use crate::manifest::Manifest; +use crate::store::{copy_blob, read_verified, Store}; + +/// The shape of a tree: references counted with multiplicity, nodes counted once. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TreeStats { + pub references: u64, + pub distinct: u64, + pub bytes: u64, +} + +/// Read every node under `root` and prove each hashes to its id. +pub fn verify(store: &dyn Store, root: &ContentId) -> Result { + let mut stats = TreeStats { + references: 1, + ..TreeStats::default() + }; + let mut seen = HashSet::new(); + verify_node(store, root, &mut seen, &mut stats)?; + Ok(stats) +} + +fn verify_node( + store: &dyn Store, + id: &ContentId, + seen: &mut HashSet, + stats: &mut TreeStats, +) -> Result<(), PackError> { + if !seen.insert(*id) { + return Ok(()); + } + let bytes = read_verified(store, id)?; + stats.distinct += 1; + stats.bytes += bytes.len() as u64; + let m = Manifest::decode(&bytes)?; + for (is_child, d) in m.links() { + stats.references += 1; + if is_child { + verify_node(store, &d.digest, seen, stats)?; + } else if seen.insert(d.digest) { + stats.distinct += 1; + stats.bytes += read_verified(store, &d.digest)?.len() as u64; + } + } + Ok(()) +} + +/// Copy the tree at `root` from `src` to `dst`, skipping whatever `dst` has, children before +/// parents, every byte re-hashed on arrival. Returns how many nodes were written. +pub fn copy(src: &dyn Store, dst: &dyn Store, root: &ContentId) -> Result { + if dst.has(root)? { + return Ok(0); + } + let bytes = read_verified(src, root)?; + let m = Manifest::decode(&bytes)?; + let mut written = 0; + for (is_child, d) in m.links() { + if is_child { + written += copy(src, dst, &d.digest)?; + } else if !dst.has(&d.digest)? { + copy_blob(src, dst, &d.digest)?; + written += 1; + } + } + let stored = dst.put(BlobSource::Bytes(&bytes))?; + if stored.id != *root { + return Err(StoreError::DigestMismatch { + expected: *root, + actual: stored.id, + } + .into()); + } + Ok(written + 1) +} diff --git a/core/continuum-pack/src/unpacker.rs b/core/continuum-pack/src/unpacker.rs new file mode 100644 index 0000000000..44d54380ab --- /dev/null +++ b/core/continuum-pack/src/unpacker.rs @@ -0,0 +1,228 @@ +//! Loading: top-down and lazy. The root manifest is read and verified, its kind and schema +//! checked and migrated, its requirements checked; only then does `unpack` see a part, and +//! blobs and handled children are read only when asked for. + +use std::sync::Arc; + +use serde::de::DeserializeOwned; + +use crate::blob::Blob; +use crate::error::PackError; +use crate::handle::Handle; +use crate::id::ContentId; +use crate::manifest::{Descriptor, Manifest, Part}; +use crate::packable::Packable; +use crate::requires::{Audience, Offers, Requirement}; +use crate::store::{read_verified, RefName, Store}; + +/// A store and what this host offers: everything a load needs besides the kind's context. +pub struct Loader { + store: Arc, + offers: Offers, +} + +impl Loader { + pub fn new(store: Arc, offers: Offers) -> Arc { + Arc::new(Self { store, offers }) + } + + pub fn store(&self) -> &Arc { + &self.store + } + + /// Load the package at `id` as a `T`. + pub fn load( + self: &Arc, + id: &ContentId, + cx: &T::Context, + ) -> Result { + let manifest = self.open::(id)?; + let mut u = Unpacker { + loader: self, + manifest, + }; + T::unpack(&mut u, cx) + } + + /// Load the package `name` points at. + pub fn load_ref( + self: &Arc, + name: &RefName, + cx: &T::Context, + ) -> Result { + let id = self + .store + .get_ref(name)? + .ok_or_else(|| PackError::RefAbsent(name.clone()))?; + self.load(&id, cx) + } + + /// The manifest at `id`, verified, kind-checked, migrated to `T`'s schema, requirements met. + fn open(&self, id: &ContentId) -> Result { + let bytes = read_verified(self.store.as_ref(), id)?; + let mut m = Manifest::decode(&bytes)?; + let kind = T::KIND; + if m.kind != kind.name { + return Err(PackError::KindMismatch { + expected: kind.name, + found: m.kind, + }); + } + if m.schema > kind.schema { + continuum_base::probe!( + class = "decision", + verdict = "refuse-newer-schema", + kind = kind.name, + found = m.schema, + known = kind.schema + ); + return Err(PackError::UnknownNewerSchema { + kind: kind.name, + found: m.schema, + known: kind.schema, + }); + } + while m.schema < kind.schema { + let from = m.schema; + let step = T::migrations().iter().find(|g| g.from == from).ok_or( + PackError::MissingMigration { + kind: kind.name, + from, + }, + )?; + (step.apply)(&mut m)?; + m.schema = from + 1; + } + if let Some((part, requirement)) = + m.requires.iter().find(|(_, r)| !self.offers.satisfies(r)) + { + continuum_base::probe!(class = "decision", verdict = "refuse-unmet-requirement", kind = kind.name, part = %part); + return Err(PackError::UnmetRequirement { + part: part.clone(), + requirement: requirement.clone(), + }); + } + Ok(m) + } +} + +/// The verbs a type unpacks itself with; the mirror of [`crate::Packer`]. +pub struct Unpacker<'l> { + loader: &'l Arc, + manifest: Manifest, +} + +impl Unpacker<'_> { + /// The (migrated) manifest being unpacked. + pub fn manifest(&self) -> &Manifest { + &self.manifest + } + + /// A field. Missing is a typed refusal: a default would hide a schema change that + /// should have been a migration. + pub fn field(&self, name: &str) -> Result { + let v = self + .manifest + .fields + .get(name) + .ok_or_else(|| missing(name))?; + T::deserialize(v).map_err(|source| PackError::Field { + part: name.to_owned(), + source, + }) + } + + /// A blob, lazily: no bytes are read here. + pub fn blob(&self, name: &str, media: &str) -> Result { + match self.part(name)? { + Part::Blob(d) if d.media_type == media => { + Ok(Blob::stored(self.loader.store().clone(), d.digest, d.size)) + } + Part::Blob(d) => Err(PackError::WrongMedia { + part: name.to_owned(), + expected: media.to_owned(), + found: d.media_type.clone(), + }), + _ => Err(wrong(name, "blob")), + } + } + + /// A child, eagerly loaded. + pub fn child(&self, name: &str, cx: &C::Context) -> Result { + let d = self.one_child(name)?; + self.loader.load(&d.digest, cx) + } + + /// An ordered list of children, eagerly loaded. + pub fn children(&self, name: &str, cx: &C::Context) -> Result, PackError> { + self.many_children(name)? + .iter() + .map(|d| self.loader.load(&d.digest, cx)) + .collect() + } + + /// A child by handle: nothing is read until the handle is loaded. + pub fn handle(&self, name: &str) -> Result, PackError> { + let d = self.one_child(name)?; + Ok(Handle::stored(d.clone(), self.loader.clone())) + } + + /// An ordered list of children by handle. + pub fn handles(&self, name: &str) -> Result>, PackError> { + Ok(self + .many_children(name)? + .iter() + .map(|d| Handle::stored(d.clone(), self.loader.clone())) + .collect()) + } + + /// A recorded requirement (already proven met). + pub fn requirement(&self, name: &str) -> Result<&Requirement, PackError> { + self.manifest + .requires + .get(name) + .ok_or_else(|| missing(name)) + } + + /// A sealed part. Opening lands with sealing in slice 5; until then this refuses. + pub fn secret( + &self, + name: &str, + _audience: &Audience, + ) -> Result { + Err(PackError::SealingUnavailable { + part: name.to_owned(), + }) + } + + fn part(&self, name: &str) -> Result<&Part, PackError> { + self.manifest.parts.get(name).ok_or_else(|| missing(name)) + } + + fn one_child(&self, name: &str) -> Result<&Descriptor, PackError> { + match self.part(name)? { + Part::Child(d) => Ok(d), + _ => Err(wrong(name, "child")), + } + } + + fn many_children(&self, name: &str) -> Result<&[Descriptor], PackError> { + match self.part(name)? { + Part::Children(ds) => Ok(ds), + _ => Err(wrong(name, "children")), + } + } +} + +fn missing(name: &str) -> PackError { + PackError::MissingPart { + part: name.to_owned(), + } +} + +fn wrong(name: &str, expected: &'static str) -> PackError { + PackError::WrongPart { + part: name.to_owned(), + expected, + } +} diff --git a/core/source-hygiene/src/budget_discipline/writes.rs b/core/source-hygiene/src/budget_discipline/writes.rs index d314c555c2..4ff7c1b8f9 100644 --- a/core/source-hygiene/src/budget_discipline/writes.rs +++ b/core/source-hygiene/src/budget_discipline/writes.rs @@ -7,8 +7,14 @@ use super::{is_vendored, owned_by}; use crate::{sites, SourceFile, SourceRule, Violation}; -/// The owners of persistent bytes: the ORM (stores) and the disk classes. -const OWNERS: &[&str] = &["core/continuum-kernel/src/orm/", "core/continuum-kernel/src/system_resources/disk_reporters"]; +/// The owners of persistent bytes: the ORM (stores), the disk classes, and continuum-pack's +/// stores (the content-addressed byte store every layer packs through; it writes only under the +/// root its caller hands it, so the class claim belongs to that caller, docs/architecture/PACKAGES.md). +const OWNERS: &[&str] = &[ + "core/continuum-kernel/src/orm/", + "core/continuum-kernel/src/system_resources/disk_reporters", + "core/continuum-pack/src/store/", +]; /// The ways Rust code creates or appends to a file. const WRITES: &[&str] = &["fs::write(", "File::create(", "OpenOptions::new()"]; diff --git a/docs/architecture/MODULE-ARCHITECTURE.md b/docs/architecture/MODULE-ARCHITECTURE.md index 3896c9d8e3..a2d1959875 100644 --- a/docs/architecture/MODULE-ARCHITECTURE.md +++ b/docs/architecture/MODULE-ARCHITECTURE.md @@ -359,6 +359,12 @@ between them? | Grid | discovery, trust, routing (airc) | every node | airc + `grid/` | | Clients | desktop, web, TUI, phone, MCP: render ViewState, send commands | anywhere | separate, through the generated SDK | +Below every module sits the **base layer**, which imports nothing above itself and which every +module may import: `continuum-base` (time, config, probes), `continuum-host` (the OS seam: durable +placement, positioned reads, local streams) and `continuum-pack` (with `continuum-pack-derive`), the +one load/store every module packs its state through: KV pages, genes, memories, personas, projects +([PACKAGES.md](PACKAGES.md)). Store's remotes are `continuum-pack` stores. + Rules: 1. **One binary set, placed by capability.** A node advertises what it has (`grid/nodes` already carries compute and VRAM); the governor places modules from that. No machine-specific role in