From 049348386f89420c8e1d4f2ffe1523fedd7e4971 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 02:15:39 -0600 Subject: [PATCH] id-store: legacy metadata read bridge and immutable snapshot migration (A9114-snapshot-migration, #10270) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New sidecar_migration module: parse_legacy reads the legacy .meta JSON form without modifying the source bytes; LegacySourceView gates migration on consistency evidence (byte-identical double read or an attested digest) so a single unaccompanied read can never publish; migrate converts one subject's complete legacy view deterministically (entries ordered by canonical CBOR bytes, duplicates collapsed) into a signed SidecarEnvelopeV1 and advances the scope head through the snapshot CAS, reporting AlreadyMigrated when the head already carries exactly this view. Integration tests include the module by path (crate-root export stays with slice 9110-02): fixed signed snapshot vector, read stability, inconsistent-source refusal, malformed/subject-absent rejection, idempotence with exactly-one generation advance, and a generated-operations comparison against a reference model. Oracle: cargo test -p id-store --test sidecar_migration — 7 passed on current main. Work adopted from the orphaned worktree of queue task 21143's expired first attempt (files written in ~/wt-lane-fz-10270, uncommitted at lease expiry); verified and landed by lane LX. --- .../crates/id-store/src/sidecar_migration.rs | 540 ++++++++++++++++ .../id-store/tests/sidecar_migration.rs | 603 ++++++++++++++++++ 2 files changed, 1143 insertions(+) create mode 100644 pkgs/id/crates/id-store/src/sidecar_migration.rs create mode 100644 pkgs/id/crates/id-store/tests/sidecar_migration.rs diff --git a/pkgs/id/crates/id-store/src/sidecar_migration.rs b/pkgs/id/crates/id-store/src/sidecar_migration.rs new file mode 100644 index 0000000000..9963ad745f --- /dev/null +++ b/pkgs/id/crates/id-store/src/sidecar_migration.rs @@ -0,0 +1,540 @@ +//! Legacy metadata read bridge and immutable snapshot migration +//! (slice A9114-snapshot-migration, issue #10270; parent #9114; design +//! `part-a-addressing/versioned-design.md` section "#9114 — Complete +//! metadata sidecars and mutable head", A-9114.1–A-9114.3, statements +//! S3.11–S3.22). +//! +//! The legacy metadata form is the `.meta` JSON document the store's +//! tag system kept before signed sidecars: one JSON object +//! `{version, tags}` whose tags carry a subject name, a key, an +//! optional value, an optional related link — a content hash or a +//! path/name reference; related links are path references, not +//! restricted to hash IDs (S3.21, S3.22) — and creation/modification +//! times. This module is the bridge from that form to the signed +//! sidecar form of [`crate::sidecar_snapshot`]: +//! +//! - [`parse_legacy`] reads the legacy form without modifying the +//! source bytes. The read is stable: the same bytes always parse +//! to the same document, before and after any migration. +//! - A migration may only run on a [`LegacySourceView`]: a parsed +//! document plus evidence that the bytes are one consistent +//! source snapshot — either two byte-identical reads, or one read +//! whose digest matches an independently attested digest. A single +//! unaccompanied read can be parsed and inspected but can never +//! publish a snapshot: the migration entry point accepts only +//! `LegacySourceView`, so claiming a consistent source snapshot +//! without evidence is unrepresentable. A parsed document whose +//! tags are internally inconsistent (a creation time after its +//! modification time) is likewise refused as a source view. +//! - [`migrate`] converts one subject's complete legacy view into a +//! signed [`SidecarEnvelopeV1`] and advances the scope head +//! through the snapshot slice's compare-and-swap +//! ([`SidecarHeadV1::genesis`] / [`SidecarHeadV1::advance`]), so +//! only a consistent source view may advance the head. The legacy +//! bytes are never modified and no legacy hash or signature is +//! rewritten: the snapshot is a new signed record whose payload is +//! the converted view, and the outcome carries the source digest +//! as provenance. +//! - Migration is idempotent: when the head already points at a +//! verified snapshot whose view equals the converted source view, +//! migration reports [`MigrationOutcome::AlreadyMigrated`] and +//! the head does not advance. +//! +//! The per-subject view conversion is total and deterministic: +//! every legacy tag for the subject appears in the view, grouped by +//! key, each tag carried as an entry map holding its times and, when +//! present, its value and link. Entries within a key are ordered by +//! their canonical CBOR bytes and exact duplicates collapse, so two +//! legacy documents that differ only in tag order migrate to the +//! same view. +//! +//! The crate-root export belongs to slice 9110-02; until that lands +//! the integration test includes this module (and +//! `sidecar_snapshot`) by path. + +use std::collections::BTreeMap; +use std::fmt; + +use ed25519_dalek::SigningKey; +use serde::{Deserialize, Serialize}; + +use id_core::canonical_cbor::{CborError, Value, encode_canonical}; +use id_core::hash_profile::ProfileDispatch; +use id_core::id_shape::{ContentId, HashProfile}; + +use crate::sidecar_snapshot::{ + SidecarBodyV1, SidecarEnvelopeV1, SidecarError, SidecarHeadV1, SnapshotId, encode_view, +}; + +/// Why a legacy document, source view or migration was rejected. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MigrationError { + /// The bytes are not a legacy metadata document this bridge can + /// read completely: not JSON, not the legacy shape, or carrying + /// a field outside the legacy schema. + LegacyJson(String), + /// Two reads of the legacy source disagree: there is no single + /// consistent source snapshot to migrate. Carries the BLAKE3 + /// digest of each read. + InconsistentReads { + /// Digest of the first read. + first: [u8; 32], + /// Digest of the second read. + second: [u8; 32], + }, + /// A read does not match the independently attested source + /// digest. + DigestMismatch { + /// The attested digest. + expected: [u8; 32], + /// The digest of the bytes actually read. + actual: [u8; 32], + }, + /// A legacy tag is internally inconsistent, so the document + /// cannot be one consistent source view. + InconsistentTag { + /// The tag's subject. + subject: String, + /// The tag's key. + key: String, + /// What was wrong. + problem: &'static str, + }, + /// The legacy document carries no tags for the subject, so + /// there is no complete view to migrate. + SubjectAbsent { + /// The subject that was asked for. + subject: String, + }, + /// A converted view entry could not be canonically encoded. + Cbor(CborError), + /// The snapshot or head operation was rejected. + Sidecar(SidecarError), +} + +impl MigrationError { + /// A stable failure class. + #[must_use] + pub fn class(&self) -> &'static str { + match self { + Self::LegacyJson(_) => "malformed_legacy", + Self::InconsistentReads { .. } | Self::InconsistentTag { .. } => "inconsistent_source", + Self::DigestMismatch { .. } => "digest_mismatch", + Self::SubjectAbsent { .. } => "subject_absent", + Self::Cbor(_) => "malformed", + Self::Sidecar(error) => error.class(), + } + } +} + +impl fmt::Display for MigrationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::LegacyJson(problem) => write!(f, "legacy metadata rejected: {problem}"), + Self::InconsistentReads { .. } => { + write!( + f, + "legacy source reads disagree: no consistent source snapshot" + ) + } + Self::DigestMismatch { .. } => { + write!(f, "legacy source does not match the attested digest") + } + Self::InconsistentTag { + subject, + key, + problem, + } => write!(f, "legacy tag {subject}/{key} is inconsistent: {problem}"), + Self::SubjectAbsent { subject } => { + write!(f, "legacy document carries no tags for subject {subject}") + } + Self::Cbor(error) => write!(f, "view encoding rejected: {error}"), + Self::Sidecar(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for MigrationError {} + +impl From for MigrationError { + fn from(error: CborError) -> Self { + Self::Cbor(error) + } +} + +impl From for MigrationError { + fn from(error: SidecarError) -> Self { + Self::Sidecar(error) + } +} + +/// The legacy metadata document, mirroring the `.meta` JSON blob +/// the legacy tag system writes (`MetaDoc` in the store's tag +/// module). The bridge reads it under its own types so the legacy +/// schema is pinned here: a field outside this schema rejects the +/// document rather than being silently dropped on conversion. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LegacyMetaDoc { + /// Schema version of the legacy document. + pub version: u32, + /// All legacy metadata tags, across every subject. + pub tags: Vec, +} + +/// A single legacy metadata tag. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LegacyMetaTag { + /// Subject this tag describes (usually a file name). + pub subject: String, + /// Tag key (e.g. `created`, `category`, `author`). + pub key: String, + /// Optional value; absent for key-only tags like `pinned`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + /// Optional link to another entity (S3.21). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub link: Option, + /// When this tag was created (unix seconds). + pub created_at: u64, + /// When this tag was last modified (unix seconds). + pub modified_at: u64, +} + +/// A legacy link target: a content hash, or a path/name reference. +/// Related links are path references, not restricted to hash IDs +/// (S3.22); both forms are preserved verbatim on conversion. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "target")] +pub enum LegacyMetaLink { + /// Points to a content hash (hex string). + Hash(String), + /// Points to a file name / tag name. + Name(String), +} + +/// The digest a source view is evidenced by: BLAKE3 over the exact +/// legacy bytes — the same hash that addresses the legacy blob in +/// the store. Computing it never modifies the bytes. +#[must_use] +pub fn legacy_source_digest(bytes: &[u8]) -> [u8; 32] { + *blake3::hash(bytes).as_bytes() +} + +/// Reads the legacy metadata form. This is the read bridge only: +/// it carries no consistency evidence, so its result can be +/// inspected and converted for display but cannot be migrated — +/// [`migrate`] requires a [`LegacySourceView`]. +/// +/// # Errors +/// +/// [`MigrationError::LegacyJson`] when the bytes are not a legacy +/// metadata document. +pub fn parse_legacy(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|error| MigrationError::LegacyJson(error.to_string())) +} + +fn validate_doc(doc: &LegacyMetaDoc) -> Result<(), MigrationError> { + for tag in &doc.tags { + if tag.created_at > tag.modified_at { + return Err(MigrationError::InconsistentTag { + subject: tag.subject.clone(), + key: tag.key.clone(), + problem: "created_at is after modified_at", + }); + } + } + Ok(()) +} + +/// A legacy document plus the evidence that its bytes are one +/// consistent source snapshot. Only values of this type may be +/// migrated; see the module docs for the evidence forms. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LegacySourceView { + doc: LegacyMetaDoc, + source_digest: [u8; 32], +} + +impl LegacySourceView { + fn from_bytes(bytes: &[u8]) -> Result { + let doc = parse_legacy(bytes)?; + validate_doc(&doc)?; + Ok(Self { + doc, + source_digest: legacy_source_digest(bytes), + }) + } + + /// Builds a source view from two reads of the legacy source. + /// The reads must be byte-identical: a source that changed + /// between reads is not one consistent snapshot. + /// + /// # Errors + /// + /// [`MigrationError::InconsistentReads`] when the reads differ, + /// or as [`parse_legacy`] / document validation. + pub fn from_double_read(first: &[u8], second: &[u8]) -> Result { + if first != second { + return Err(MigrationError::InconsistentReads { + first: legacy_source_digest(first), + second: legacy_source_digest(second), + }); + } + Self::from_bytes(first) + } + + /// Builds a source view from one read whose digest must match + /// an independently attested digest (for example the digest the + /// source was addressed by when it was fetched). + /// + /// # Errors + /// + /// [`MigrationError::DigestMismatch`] when the read does not + /// match the attested digest, or as [`parse_legacy`] / document + /// validation. + pub fn attested(bytes: &[u8], expected: &[u8; 32]) -> Result { + let actual = legacy_source_digest(bytes); + if actual != *expected { + return Err(MigrationError::DigestMismatch { + expected: *expected, + actual, + }); + } + Self::from_bytes(bytes) + } + + /// The parsed legacy document. + #[must_use] + pub const fn doc(&self) -> &LegacyMetaDoc { + &self.doc + } + + /// The digest of the exact source bytes this view was evidenced + /// from, carried into migration outcomes as provenance. + #[must_use] + pub const fn source_digest(&self) -> [u8; 32] { + self.source_digest + } + + /// The complete metadata view for one subject, in the signed + /// sidecar payload form: every legacy tag for the subject, + /// grouped by key, each tag an entry map with its times and, + /// when present, its value and link. Entries within a key are + /// ordered by their canonical CBOR bytes and exact duplicates + /// collapse, so the conversion is deterministic and independent + /// of legacy tag order. + /// + /// # Errors + /// + /// [`MigrationError::SubjectAbsent`] when the document carries + /// no tags for the subject, or [`MigrationError::Cbor`] when an + /// entry cannot be canonically encoded. + pub fn subject_view(&self, subject: &str) -> Result, MigrationError> { + let mut by_key: BTreeMap> = BTreeMap::new(); + for tag in &self.doc.tags { + if tag.subject == subject { + by_key + .entry(tag.key.clone()) + .or_default() + .push(tag_entry(tag)); + } + } + if by_key.is_empty() { + return Err(MigrationError::SubjectAbsent { + subject: subject.to_owned(), + }); + } + let mut view = BTreeMap::new(); + for (key, entries) in by_key { + let mut keyed: Vec<(Vec, Value)> = Vec::with_capacity(entries.len()); + for entry in entries { + let canonical = encode_canonical(&entry)?; + keyed.push((canonical, entry)); + } + keyed.sort_by(|a, b| a.0.cmp(&b.0)); + keyed.dedup_by(|a, b| a.0 == b.0); + view.insert( + key, + Value::Array(keyed.into_iter().map(|(_, e)| e).collect()), + ); + } + Ok(view) + } +} + +/// One legacy tag as a view entry: its times and, when present, its +/// value and link. Absent fields are omitted, never null. +fn tag_entry(tag: &LegacyMetaTag) -> Value { + // Keep the in-memory map in the same order as the canonical CBOR + // encoder (shorter text keys sort before longer keys). This makes + // a decoded snapshot view compare equal to the source view and is + // required for migration idempotence. + let mut entries: Vec<(Value, Value)> = Vec::new(); + if let Some(link) = &tag.link { + let (kind, target) = match link { + LegacyMetaLink::Hash(target) => ("hash", target), + LegacyMetaLink::Name(target) => ("name", target), + }; + entries.push(( + Value::Text("link".to_owned()), + Value::Map(vec![ + (Value::Text("kind".to_owned()), Value::Text(kind.to_owned())), + ( + Value::Text("target".to_owned()), + Value::Text(target.clone()), + ), + ]), + )); + } + if let Some(value) = &tag.value { + entries.push((Value::Text("value".to_owned()), Value::Text(value.clone()))); + } + entries.push(( + Value::Text("created_at".to_owned()), + Value::UInt(tag.created_at), + )); + entries.push(( + Value::Text("modified_at".to_owned()), + Value::UInt(tag.modified_at), + )); + Value::Map(entries) +} + +/// The scope and signing parameters a migration publishes under. +/// The legacy subject is a name; its sidecar subject identity is +/// the content ID the caller binds that name to — the bridge never +/// invents one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MigrationParams { + /// The subject this metadata describes, as a content ID. + pub subject_content_id: ContentId, + /// The namespace the snapshot is complete within. + pub namespace_id: String, + /// The tenant scope the snapshot is complete within. + pub tenant_scope: String, + /// Signing domain and context of the snapshot. + pub domain_context: String, + /// Who signs the snapshot and head, as the signer names itself. + pub signer_id: String, + /// The explicit profile snapshot payload IDs are computed under. + pub payload_profile: HashProfile, + /// Advisory creation time (unix milliseconds) of the snapshot. + pub created_at: u64, +} + +/// The result of a migration. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MigrationOutcome { + /// A new signed snapshot was published and the head advanced by + /// exactly one generation (or was created at genesis). + Advanced { + /// The new complete signed snapshot. + snapshot: SidecarEnvelopeV1, + /// The head after the compare-and-swap. + head: SidecarHeadV1, + /// Digest of the legacy source bytes, as provenance. + source_digest: [u8; 32], + }, + /// The head already pointed at a verified snapshot whose view + /// equals the converted source view; nothing was published and + /// the head did not move. + AlreadyMigrated { + /// The current head, unchanged. + head: SidecarHeadV1, + /// The snapshot the head already points at. + snapshot_id: SnapshotId, + /// Digest of the legacy source bytes, as provenance. + source_digest: [u8; 32], + }, +} + +/// Migrates one subject's complete legacy view into the signed +/// sidecar form. With no current head this publishes the genesis +/// snapshot; with a current head it publishes the exact successor +/// and advances the head through the compare-and-swap, so lost +/// updates and ABA remain detectable. When the current head's +/// verified snapshot already carries exactly this view, the +/// migration is a no-op ([`MigrationOutcome::AlreadyMigrated`]). +/// +/// # Errors +/// +/// [`MigrationError`]: the subject is absent from the source, or +/// the snapshot/head operations reject — an unverified or +/// mismatched current record, a stale head, a subject or scope +/// mismatch — classed by [`MigrationError::class`]. +pub fn migrate( + source: &LegacySourceView, + subject_name: &str, + params: &MigrationParams, + current: Option<(&SidecarHeadV1, &SidecarEnvelopeV1)>, + key: &SigningKey, +) -> Result { + let view = source.subject_view(subject_name)?; + let payload = encode_view(&view)?; + let source_digest = source.source_digest(); + if let Some((head, current_snapshot)) = current { + current_snapshot.verify(&ProfileDispatch::default())?; + if head.snapshot_id != current_snapshot.snapshot_id()? + || head.generation != current_snapshot.body.generation + { + return Err(SidecarError::StaleHead.into()); + } + if current_snapshot.view()? == view { + return Ok(MigrationOutcome::AlreadyMigrated { + head: head.clone(), + snapshot_id: head.snapshot_id, + source_digest, + }); + } + let generation = + head.generation + .checked_add(1) + .ok_or(SidecarError::GenerationMismatch { + expected: head.generation, + actual: head.generation, + })?; + let body = SidecarBodyV1::for_payload( + params.subject_content_id, + params.namespace_id.clone(), + params.tenant_scope.clone(), + generation, + Some(head.snapshot_id), + params.created_at, + params.domain_context.clone(), + params.signer_id.clone(), + key.verifying_key().to_bytes(), + params.payload_profile, + &payload, + )?; + let snapshot = SidecarEnvelopeV1::sign(body, payload, key)?; + let head = head.advance(current_snapshot, &snapshot, key)?; + Ok(MigrationOutcome::Advanced { + snapshot, + head, + source_digest, + }) + } else { + let body = SidecarBodyV1::for_payload( + params.subject_content_id, + params.namespace_id.clone(), + params.tenant_scope.clone(), + 0, + None, + params.created_at, + params.domain_context.clone(), + params.signer_id.clone(), + key.verifying_key().to_bytes(), + params.payload_profile, + &payload, + )?; + let snapshot = SidecarEnvelopeV1::sign(body, payload, key)?; + let head = SidecarHeadV1::genesis(&snapshot, key)?; + Ok(MigrationOutcome::Advanced { + snapshot, + head, + source_digest, + }) + } +} diff --git a/pkgs/id/crates/id-store/tests/sidecar_migration.rs b/pkgs/id/crates/id-store/tests/sidecar_migration.rs new file mode 100644 index 0000000000..08f7549fd7 --- /dev/null +++ b/pkgs/id/crates/id-store/tests/sidecar_migration.rs @@ -0,0 +1,603 @@ +//! Model test for the legacy metadata read bridge and immutable +//! snapshot migration (slice A9114-snapshot-migration, issue +//! #10270; design A-9114.1–A-9114.3, S3.11–S3.22). +//! +//! Oracle: **model** — expected `Before/after data-model comparison +//! plus fixed signed snapshot vector; only consistent source views +//! may advance head.` The reference model below works from the raw +//! JSON with `serde_json::Value` — never the module's own types — +//! and builds the expected per-subject view with its own grouping +//! and ordering code. Generated operations (add a legacy tag, +//! corrupt a second read, migrate) run against the model and the +//! module, and every resulting state and error class is compared: +//! a migration may advance the head by exactly one generation only +//! when the model's view changed, its snapshot's decoded view must +//! equal the model's view exactly, and re-migrating an unchanged +//! source must move nothing. +//! +//! Fixed tests cover the oracle's named notes: the fixed signed +//! snapshot vector, legacy read stability (the source bytes and +//! their digest are never rewritten), migration idempotence, +//! inconsistent sources publishing nothing, and both legacy link +//! forms surviving as path references (S3.21, S3.22). +//! +//! Why the modules are included by path: slice 9110-02 owns the +//! crate roots, so neither `sidecar_snapshot` nor +//! `sidecar_migration` is exported from id-store yet. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../src/sidecar_migration.rs"] +mod sidecar_migration; +#[path = "../src/sidecar_snapshot.rs"] +mod sidecar_snapshot; + +use std::collections::BTreeMap; + +use ed25519_dalek::SigningKey; + +use id_core::canonical_cbor::{Value, encode_canonical}; +use id_core::hash_profile::ProfileDispatch; +use id_core::id_shape::{ContentId, HashProfile}; + +use sidecar_migration::{ + LegacySourceView, MigrationOutcome, MigrationParams, legacy_source_digest, migrate, + parse_legacy, +}; +use sidecar_snapshot::{SidecarEnvelopeV1, SidecarHeadV1, decode_view}; + +const PROFILE: HashProfile = HashProfile::RawBlake3_256; +const NAMESPACE: &str = "ns/alpha"; +const TENANT: &str = "tenant/a"; +const DOMAIN: &str = "id.sidecar/v1"; +const SIGNER: &str = "migration-writer"; + +fn key() -> SigningKey { + SigningKey::from_bytes(&[7u8; 32]) +} + +fn params_for(subject_name: &str) -> MigrationParams { + MigrationParams { + subject_content_id: ContentId::of_bytes(PROFILE, subject_name.as_bytes()).unwrap(), + namespace_id: NAMESPACE.to_owned(), + tenant_scope: TENANT.to_owned(), + domain_context: DOMAIN.to_owned(), + signer_id: SIGNER.to_owned(), + payload_profile: PROFILE, + created_at: 1_700_001_000_000, + } +} + +/// A hand-written legacy document, in the exact shape the legacy +/// writer serializes: two subjects, a key-only shape implied by +/// optional fields, and both link forms (S3.21, S3.22). +const FIXED_LEGACY: &[u8] = br#"{"version":1,"tags":[ +{"subject":"README.md","key":"created","value":"1700000000","created_at":1700000000,"modified_at":1700000000}, +{"subject":"README.md","key":"category","value":"docs","created_at":1700000100,"modified_at":1700000200}, +{"subject":"README.md","key":"related","link":{"type":"Name","target":"docs/guide.md"},"created_at":1700000300,"modified_at":1700000300}, +{"subject":"README.md","key":"related","link":{"type":"Hash","target":"abc123"},"created_at":1700000250,"modified_at":1700000250}, +{"subject":"other.txt","key":"created","value":"1700000500","created_at":1700000500,"modified_at":1700000500} +]}"#; + +fn entry( + created_at: u64, + modified_at: u64, + value: Option<&str>, + link: Option<(&str, &str)>, +) -> Value { + let mut entries = Vec::new(); + if let Some((kind, target)) = link { + entries.push(( + Value::Text("link".to_owned()), + Value::Map(vec![ + (Value::Text("kind".to_owned()), Value::Text(kind.to_owned())), + ( + Value::Text("target".to_owned()), + Value::Text(target.to_owned()), + ), + ]), + )); + } + if let Some(value) = value { + entries.push(( + Value::Text("value".to_owned()), + Value::Text(value.to_owned()), + )); + } + entries.push(( + Value::Text("created_at".to_owned()), + Value::UInt(created_at), + )); + entries.push(( + Value::Text("modified_at".to_owned()), + Value::UInt(modified_at), + )); + Value::Map(entries) +} + +fn sorted_entries(mut entries: Vec) -> Value { + let mut keyed: Vec<(Vec, Value)> = entries + .drain(..) + .map(|e| (encode_canonical(&e).unwrap(), e)) + .collect(); + keyed.sort_by(|a, b| a.0.cmp(&b.0)); + keyed.dedup_by(|a, b| a.0 == b.0); + Value::Array(keyed.into_iter().map(|(_, e)| e).collect()) +} + +/// The expected complete view of `README.md` in the fixed document, +/// built by hand here — never by the module under test. +fn fixed_expected_view() -> BTreeMap { + let mut view = BTreeMap::new(); + view.insert( + "category".to_owned(), + sorted_entries(vec![entry( + 1_700_000_100, + 1_700_000_200, + Some("docs"), + None, + )]), + ); + view.insert( + "created".to_owned(), + sorted_entries(vec![entry( + 1_700_000_000, + 1_700_000_000, + Some("1700000000"), + None, + )]), + ); + view.insert( + "related".to_owned(), + sorted_entries(vec![ + entry( + 1_700_000_300, + 1_700_000_300, + None, + Some(("name", "docs/guide.md")), + ), + entry(1_700_000_250, 1_700_000_250, None, Some(("hash", "abc123"))), + ]), + ); + view +} + +#[test] +fn fixed_signed_snapshot_vector() { + let source = LegacySourceView::from_double_read(FIXED_LEGACY, FIXED_LEGACY).unwrap(); + assert_eq!(source.source_digest(), legacy_source_digest(FIXED_LEGACY)); + assert_eq!( + source.source_digest(), + *blake3::hash(FIXED_LEGACY).as_bytes() + ); + + let view = source.subject_view("README.md").unwrap(); + assert_eq!(view, fixed_expected_view()); + + let outcome = migrate(&source, "README.md", ¶ms_for("README.md"), None, &key()).unwrap(); + let MigrationOutcome::Advanced { + snapshot, + head, + source_digest, + } = outcome + else { + panic!("genesis migration must advance"); + }; + assert_eq!(source_digest, legacy_source_digest(FIXED_LEGACY)); + + // The fixed vector: the payload is exactly the encoded complete + // view, the snapshot verifies, and its ID is id-core's digest of + // the complete envelope bytes — derived here, not by the module. + assert_eq!( + decode_view(&snapshot.raw_payload_bytes).unwrap(), + fixed_expected_view() + ); + assert_eq!( + snapshot.raw_payload_bytes, + sidecar_snapshot::encode_view(&fixed_expected_view()).unwrap() + ); + snapshot.verify(&ProfileDispatch::default()).unwrap(); + let expected_id = ContentId::of_bytes(PROFILE, &snapshot.canonical_bytes().unwrap()).unwrap(); + assert_eq!(*snapshot.snapshot_id().unwrap().content_id(), expected_id); + assert_eq!(snapshot.body.generation, 0); + assert_eq!(snapshot.body.parent_snapshot_id, None); + assert_eq!(head.generation, 0); + assert_eq!(head.snapshot_id, snapshot.snapshot_id().unwrap()); + head.verify().unwrap(); +} + +#[test] +fn legacy_read_is_stable_and_never_rewrites_source() { + let bytes_before = FIXED_LEGACY.to_vec(); + let first = parse_legacy(FIXED_LEGACY).unwrap(); + let second = parse_legacy(FIXED_LEGACY).unwrap(); + assert_eq!(first, second); + assert_eq!(first.version, 1); + assert_eq!(first.tags.len(), 5); + + // Both link forms survive the read as path references (S3.21, + // S3.22): a name target and a hash target, verbatim. + let links: Vec = first + .tags + .iter() + .filter_map(|tag| match &tag.link { + Some(sidecar_migration::LegacyMetaLink::Hash(target)) => Some(format!("hash:{target}")), + Some(sidecar_migration::LegacyMetaLink::Name(target)) => Some(format!("name:{target}")), + None => None, + }) + .collect(); + assert_eq!(links, ["name:docs/guide.md", "hash:abc123"]); + + // Migrating does not touch the source bytes or their digest. + let source = + LegacySourceView::attested(FIXED_LEGACY, &legacy_source_digest(FIXED_LEGACY)).unwrap(); + let _ = migrate(&source, "README.md", ¶ms_for("README.md"), None, &key()).unwrap(); + assert_eq!(FIXED_LEGACY, bytes_before.as_slice()); + assert_eq!(parse_legacy(FIXED_LEGACY).unwrap(), first); +} + +#[test] +fn inconsistent_sources_cannot_publish() { + // Two reads that disagree: no consistent source snapshot. + let mut changed = FIXED_LEGACY.to_vec(); + let last = changed.len() - 2; + changed[last] = if changed[last] == b'0' { b'1' } else { b'0' }; + let error = LegacySourceView::from_double_read(FIXED_LEGACY, &changed).unwrap_err(); + assert_eq!(error.class(), "inconsistent_source"); + + // One read against a wrong attested digest. + let error = LegacySourceView::attested(FIXED_LEGACY, &[9u8; 32]).unwrap_err(); + assert_eq!(error.class(), "digest_mismatch"); + + // Byte-identical reads of an internally inconsistent document: + // a tag created after it was modified cannot be one consistent + // source view. + const INCONSISTENT: &[u8] = br#"{"version":1,"tags":[ +{"subject":"a.txt","key":"created","value":"5","created_at":200,"modified_at":100} +]}"#; + let error = LegacySourceView::from_double_read(INCONSISTENT, INCONSISTENT).unwrap_err(); + assert_eq!(error.class(), "inconsistent_source"); + // ... while the plain read bridge still reads it: read stability + // and migration gating are separate concerns. + assert_eq!(parse_legacy(INCONSISTENT).unwrap().tags.len(), 1); +} + +#[test] +fn malformed_legacy_rejects() { + for (bytes, _name) in [ + (&b"not json"[..], "not json"), + (&b"[1,2]"[..], "top-level array"), + ( + &br#"{"version":1,"tags":[],"surprise":true}"#[..], + "unknown field", + ), + ( + &br#"{"version":1,"tags":[{"subject":"a","key":"k","modified_at":1}]}"#[..], + "missing created_at", + ), + ( + &br#"{"version":1,"tags":[{"subject":"a","key":"k","link":{"type":"Url","target":"x"},"created_at":1,"modified_at":1}]}"#[..], + "unknown link type", + ), + ] { + let error = parse_legacy(bytes).unwrap_err(); + assert_eq!(error.class(), "malformed_legacy", "{_name}"); + } +} + +#[test] +fn subject_absent_rejects() { + let source = LegacySourceView::from_double_read(FIXED_LEGACY, FIXED_LEGACY).unwrap(); + let error = migrate( + &source, + "missing.txt", + ¶ms_for("missing.txt"), + None, + &key(), + ) + .unwrap_err(); + assert_eq!(error.class(), "subject_absent"); +} + +#[test] +fn migration_is_idempotent_and_advances_by_exactly_one() { + let key = key(); + let params = params_for("README.md"); + let source = LegacySourceView::from_double_read(FIXED_LEGACY, FIXED_LEGACY).unwrap(); + + let MigrationOutcome::Advanced { + snapshot: first_snapshot, + head: first_head, + .. + } = migrate(&source, "README.md", ¶ms, None, &key).unwrap() + else { + panic!("genesis migration must advance"); + }; + + // Re-migrating the unchanged source moves nothing. + let outcome = migrate( + &source, + "README.md", + ¶ms, + Some((&first_head, &first_snapshot)), + &key, + ) + .unwrap(); + let MigrationOutcome::AlreadyMigrated { + head, snapshot_id, .. + } = outcome + else { + panic!("unchanged source must be a no-op"); + }; + assert_eq!(head, first_head); + assert_eq!(snapshot_id, first_snapshot.snapshot_id().unwrap()); + + // A changed source advances by exactly one generation, parented + // on the prior head snapshot. + const CHANGED: &[u8] = br#"{"version":1,"tags":[ +{"subject":"README.md","key":"created","value":"1700000000","created_at":1700000000,"modified_at":1700000000}, +{"subject":"README.md","key":"category","value":"guides","created_at":1700000100,"modified_at":1700000400} +]}"#; + let changed_source = LegacySourceView::from_double_read(CHANGED, CHANGED).unwrap(); + let MigrationOutcome::Advanced { + snapshot: second_snapshot, + head: second_head, + .. + } = migrate( + &changed_source, + "README.md", + ¶ms, + Some((&first_head, &first_snapshot)), + &key, + ) + .unwrap() + else { + panic!("changed source must advance"); + }; + assert_eq!(second_head.generation, 1); + assert_eq!( + second_snapshot.body.parent_snapshot_id, + Some(first_snapshot.snapshot_id().unwrap()) + ); + assert_eq!( + second_head.snapshot_id, + second_snapshot.snapshot_id().unwrap() + ); + + // Tag order in the legacy document does not change the view or + // the snapshot: the same tags, reversed, migrate identically. + const REORDERED: &[u8] = br#"{"version":1,"tags":[ +{"subject":"README.md","key":"category","value":"guides","created_at":1700000100,"modified_at":1700000400}, +{"subject":"README.md","key":"created","value":"1700000000","created_at":1700000000,"modified_at":1700000000} +]}"#; + let reordered = LegacySourceView::from_double_read(REORDERED, REORDERED).unwrap(); + assert_eq!( + reordered.subject_view("README.md").unwrap(), + changed_source.subject_view("README.md").unwrap() + ); +} + +// --------------------------------------------------------------------- +// Generated model comparison +// --------------------------------------------------------------------- + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ModelTag { + subject: String, + key: String, + value: Option, + link: Option<(&'static str, String)>, + created_at: u64, + modified_at: u64, +} + +fn model_bytes(tags: &[ModelTag]) -> Vec { + let tag_values: Vec = tags + .iter() + .map(|tag| { + let mut object = serde_json::json!({ + "subject": tag.subject, + "key": tag.key, + "created_at": tag.created_at, + "modified_at": tag.modified_at, + }); + if let Some(value) = &tag.value { + object["value"] = serde_json::Value::String(value.clone()); + } + if let Some((kind, target)) = &tag.link { + let kind_name = if *kind == "hash" { "Hash" } else { "Name" }; + object["link"] = serde_json::json!({"type": kind_name, "target": target}); + } + object + }) + .collect(); + serde_json::to_vec(&serde_json::json!({"version": 1, "tags": tag_values})).unwrap() +} + +/// The reference view: built from the raw JSON with serde_json +/// values only — an independent implementation of the conversion. +fn model_view(bytes: &[u8], subject: &str) -> BTreeMap { + let document: serde_json::Value = serde_json::from_slice(bytes).unwrap(); + let mut by_key: BTreeMap> = BTreeMap::new(); + for tag in document["tags"].as_array().unwrap() { + if tag["subject"].as_str().unwrap() != subject { + continue; + } + let mut entries = Vec::new(); + if let Some(link) = tag.get("link") { + let kind = match link["type"].as_str().unwrap() { + "Hash" => "hash", + "Name" => "name", + other => panic!("unexpected link type {other}"), + }; + entries.push(( + Value::Text("link".to_owned()), + Value::Map(vec![ + (Value::Text("kind".to_owned()), Value::Text(kind.to_owned())), + ( + Value::Text("target".to_owned()), + Value::Text(link["target"].as_str().unwrap().to_owned()), + ), + ]), + )); + } + if let Some(value) = tag["value"].as_str() { + entries.push(( + Value::Text("value".to_owned()), + Value::Text(value.to_owned()), + )); + } + entries.push(( + Value::Text("created_at".to_owned()), + Value::UInt(tag["created_at"].as_u64().unwrap()), + )); + entries.push(( + Value::Text("modified_at".to_owned()), + Value::UInt(tag["modified_at"].as_u64().unwrap()), + )); + by_key + .entry(tag["key"].as_str().unwrap().to_owned()) + .or_default() + .push(Value::Map(entries)); + } + by_key + .into_iter() + .map(|(key, entries)| (key, sorted_entries(entries))) + .collect() +} + +#[test] +fn generated_operations_match_reference_model() { + const SUBJECTS: [&str; 2] = ["a.txt", "b.txt"]; + const KEYS: [&str; 5] = ["created", "category", "author", "related", "pinned"]; + let key = key(); + + for seed in [11u64, 42, 97] { + let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let mut tags: Vec = Vec::new(); + // Per-subject chain state: (head, current snapshot). + let mut chains: [Option<(SidecarHeadV1, SidecarEnvelopeV1)>; 2] = [None, None]; + + for _op in 0..60 { + match rng.below(10) { + // Add a legacy tag. + 0..=4 => { + let subject = SUBJECTS[rng.below(2) as usize].to_owned(); + let tag_key = KEYS[rng.below(5) as usize].to_owned(); + let created_at = 1_000 + rng.below(1_000); + let value = match rng.below(3) { + 0 => None, + _ => Some(format!("v{}", rng.below(50))), + }; + let link = match rng.below(4) { + 0 => Some(("hash", format!("h{}", rng.below(50)))), + 1 => Some(("name", format!("docs/{}.md", rng.below(50)))), + _ => None, + }; + tags.push(ModelTag { + subject, + key: tag_key, + value, + link, + created_at, + modified_at: created_at + rng.below(500), + }); + } + // A second read that disagrees can never migrate. + 5 => { + let bytes = model_bytes(&tags); + let mut changed = bytes.clone(); + changed.push(b' '); + let error = LegacySourceView::from_double_read(&bytes, &changed).unwrap_err(); + assert_eq!(error.class(), "inconsistent_source"); + } + // Migrate one subject and compare against the model. + _ => { + let index = rng.below(2) as usize; + let subject = SUBJECTS[index]; + let bytes = model_bytes(&tags); + assert_eq!( + legacy_source_digest(&bytes), + *blake3::hash(&bytes).as_bytes() + ); + let expected_view = model_view(&bytes, subject); + let source = LegacySourceView::from_double_read(&bytes, &bytes).unwrap(); + let current = chains[index] + .as_ref() + .map(|(head, snapshot)| (head, snapshot)); + let result = migrate(&source, subject, ¶ms_for(subject), current, &key); + if expected_view.is_empty() { + let error = result.unwrap_err(); + assert_eq!(error.class(), "subject_absent"); + continue; + } + let prior = chains[index].take(); + // The model's verdict: a no-op is correct exactly + // when the current head's view already equals the + // converted source view. + let unchanged = prior.as_ref().is_some_and(|(_, snapshot)| { + decode_view(&snapshot.raw_payload_bytes).unwrap() == expected_view + }); + match (result.unwrap(), prior) { + ( + MigrationOutcome::AlreadyMigrated { head, .. }, + Some((prior_head, prior_snapshot)), + ) => { + assert!(unchanged, "module no-oped a changed source view"); + assert_eq!(head, prior_head); + chains[index] = Some((prior_head, prior_snapshot)); + } + ( + MigrationOutcome::Advanced { + snapshot, + head, + source_digest, + }, + prior, + ) => { + assert!(!unchanged, "module re-published an unchanged view"); + let expected_generation = prior + .as_ref() + .map_or(0, |(prior_head, _)| prior_head.generation + 1); + assert_eq!(head.generation, expected_generation); + assert_eq!( + decode_view(&snapshot.raw_payload_bytes).unwrap(), + expected_view + ); + assert_eq!(source_digest, legacy_source_digest(&bytes)); + if let Some((_, prior_snapshot)) = &prior { + assert_eq!( + snapshot.body.parent_snapshot_id, + Some(prior_snapshot.snapshot_id().unwrap()) + ); + } + snapshot.verify(&ProfileDispatch::default()).unwrap(); + head.verify().unwrap(); + chains[index] = Some((head, snapshot)); + } + (MigrationOutcome::AlreadyMigrated { .. }, None) => { + panic!("no chain head: migration cannot be a no-op"); + } + } + } + } + } + } +}