diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index 561eb79..a7c79a2 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -8,15 +8,18 @@ use std::fs::{self, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; -use synapse_auth::{AuditEntry, AuthenticatedRequest, BoundaryKind, Capability, PolicyEnforcer}; +use synapse_auth::{ + AuditEntry, AuthenticatedRequest, BoundaryKind, Capability, ChainedRequest, PolicyEnforcer, +}; use synapse_core::{ validate_repo_relative_path, BlobDigest, ChangesetEnvelope, ChangesetId, EvidenceAttachment, FileMode, GitHubPullRequestProjection, GitOid, IdempotencyKey, MutationOp, RadicleCanonicalHead, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq, }; +use synapse_core::{ChainPath, ChangeId, ChangesetEnvelopeV2, ObsolescenceMarker}; use synapse_store::{ - CompactionReport, FsyncPolicy, IngestOutcome, RecoveryPolicy, ReviewRecord, StoreLimits, - StoredChangeset, SynapseStore, + AdmissionAuthority, CompactionReport, FsyncPolicy, IngestOutcome, RecoveryPolicy, ReviewRecord, + RevisionOutcome, StoreLimits, StoredChangeset, SynapseStore, }; mod advisory; @@ -534,6 +537,99 @@ impl SynapseService { Ok(()) } + /// Submit an envelope v2 revision (ADR 0003 B1) under an F1 delegation chain. + /// `req.payload` is the canonical envelope encoding; `req.scope` must name the + /// revision's `ChangeId` as `join_change` and exactly its mutation paths, so the chain's + /// change and path scopes are enforced (`AuthChangeOutOfScope`, `AuthPathOutOfScope`). + /// The chain must grant `Propose`; the attestation must be signed by the request's agent + /// for this repository; the base `TreeDigest` must be a registered base root or a tree + /// the tree store holds (`BaseTreeNotFound`). The store then applies the join rule + /// against the change's creating chain. + pub fn submit_revision( + &mut self, + req: &ChainedRequest, + blobs: &[(BlobDigest, Vec)], + now_ms: u64, + ) -> SynapseResult { + let envelope = ChangesetEnvelopeV2::decode(&req.payload)?; + let content = &envelope.content; + check_join_scope(req, content.change_id)?; + let paths: Vec = content.mutations.iter().map(|m| m.path.clone()).collect(); + if req.scope.paths != paths { + return Err(SynapseError::new( + RefusalCode::AuthPathOutOfScope, + "request scope paths must be exactly the revision's mutation paths", + )); + } + self.auth.authorize_chain( + BoundaryKind::Api, + "submit_revision", + &self.repo_id, + Capability::Propose, + req, + self.store.committed_seq().next(), + now_ms, + )?; + if envelope.attestation.repo_id != self.repo_id { + return Err(SynapseError::new( + RefusalCode::AuthCrossRepoDenied, + "attestation repo_id does not match service repo_id", + )); + } + if envelope.attestation.author_key != req.agent_key { + return Err(SynapseError::new( + RefusalCode::AuthSignatureInvalid, + "attestation author is not the agent that presented the chain", + )); + } + let base = content.base_tree; + if !self.base_roots.values().any(|r| *r == base) && !self.tree_store().contains(base) { + return Err(SynapseError::new( + RefusalCode::BaseTreeNotFound, + format!("base tree {base} is not known to the service"), + )); + } + let authority = admission_authority(req)?; + self.store + .admit_revision(envelope, blobs, authority, now_ms) + } + + /// Record an obsolescence marker (ADR 0003 B1) under an F1 delegation chain granting + /// `Propose`. `req.payload` is the canonical marker encoding and `req.scope.join_change` + /// must name its `ChangeId`; the marker must be signed by the request's agent. The store + /// applies the dominance rules (`AuthChainNotDominant`). + pub fn record_obsolescence( + &mut self, + req: &ChainedRequest, + now_ms: u64, + ) -> SynapseResult { + let marker = ObsolescenceMarker::decode(&req.payload)?; + check_join_scope(req, marker.change_id)?; + self.auth.authorize_chain( + BoundaryKind::Api, + "record_obsolescence", + &self.repo_id, + Capability::Propose, + req, + self.store.committed_seq().next(), + now_ms, + )?; + if marker.repo_id != self.repo_id { + return Err(SynapseError::new( + RefusalCode::AuthCrossRepoDenied, + "marker repo_id does not match service repo_id", + )); + } + if marker.signer_key != req.agent_key { + return Err(SynapseError::new( + RefusalCode::AuthSignatureInvalid, + "marker signer is not the agent that presented the chain", + )); + } + let chain = admission_authority(req)?.chain; + self.store.record_obsolescence(marker, chain, now_ms) + } + /// Index a committed (or duplicate) submission in the path index. pub fn index_submitted(&mut self, outcome: &IngestOutcome, envelope: &ChangesetEnvelope) { let cs_id = match outcome { @@ -1461,6 +1557,34 @@ fn validate_subscriber_id(id: &str) -> SynapseResult<()> { Ok(()) } +/// The request must name `change_id` as the change it joins, so F1 checks it against the +/// chain's change scope. +fn check_join_scope(req: &ChainedRequest, change_id: ChangeId) -> SynapseResult<()> { + if req.scope.join_change != Some(change_id) { + return Err(SynapseError::new( + RefusalCode::AuthChangeOutOfScope, + format!("request scope must name change {change_id} as join_change"), + )); + } + Ok(()) +} + +/// The store-side authority of a verified chain: its link digests, and the `ChangeId`s its +/// leaf grant names explicitly (a grant for any change names none). +fn admission_authority(req: &ChainedRequest) -> SynapseResult { + let chain = ChainPath::new(req.chain.link_digests().iter().map(|d| d.0).collect())?; + let change_scope = req + .chain + .leaf() + .and_then(|l| l.caveats.changes.ids()) + .map(<[ChangeId]>::to_vec) + .unwrap_or_default(); + Ok(AdmissionAuthority { + chain, + change_scope, + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/synapse-api/tests/b1_chained_revisions.rs b/crates/synapse-api/tests/b1_chained_revisions.rs new file mode 100644 index 0000000..f06ae64 --- /dev/null +++ b/crates/synapse-api/tests/b1_chained_revisions.rs @@ -0,0 +1,314 @@ +//! ADR 0003 step B1 through the API with real signed F1 capability chains: authority `A` +//! grants orchestrator `O` and outsider `X` (root links); `O` delegates worker `W` (scoped to +//! `src`) and worker `V` (scoped to change `C`). + +use ed25519_dalek::SigningKey; +use std::path::PathBuf; +use synapse_api::{SynapseService, TreeTarget}; +use synapse_auth::{ + Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, + LinkCaveats, OperationSet, PathScope, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, +}; +use synapse_core::{ + encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, + GitOid, IdempotencyKey, MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RepoId, + RevisionContent, TreeDigest, WalSeq, +}; +use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits}; + +const NOW: u64 = 2_000; +const C: ChangeId = ChangeId([0xC1; 16]); + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +fn pk(k: &SigningKey) -> [u8; 32] { + k.verifying_key().to_bytes() +} + +/// `share` is the part of the parent's quotas a child link takes (children of one parent +/// must partition its quotas). +fn caveats(paths: PathScope, changes: ChangeScope, share: u64) -> LinkCaveats { + LinkCaveats { + operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), + paths, + references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), + changes, + quotas: ChainQuotas { + max_ops_per_window: (1_000 / share) as u32, + window_duration_ms: 60_000, + storage_bytes: (1 << 30) / share, + footprint_paths: (1 << 20) / share, + max_bytes_per_op: 1 << 20, + }, + issued_at_ms: 1_000, + expires_at_ms: 100_000, + } +} + +struct Fx { + svc: SynapseService, + base: TreeDigest, + o: (SigningKey, CapabilityChain), + w: (SigningKey, CapabilityChain), + v: (SigningKey, CapabilityChain), + x: (SigningKey, CapabilityChain), + nonce: u8, +} + +impl Fx { + fn new(name: &str) -> Self { + let dir: PathBuf = std::env::temp_dir().join(format!( + "synapse-b1-api-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut svc = SynapseService::open( + &dir, + repo(), + FsyncPolicy::EveryCommit, + RecoveryPolicy::StrictFailClosed, + StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + }, + ) + .unwrap(); + let a = SigningKey::from_bytes(&[1; 32]); + let key = |n: u8| SigningKey::from_bytes(&[n; 32]); + let (o, w, v, x) = (key(2), key(3), key(4), key(9)); + svc.auth_mut() + .register_repo_authority(repo(), encode_did_key_ed25519(&pk(&a))); + let whole = PathScope::whole_repository; + let root_o = CapabilityLink::issue( + &a, + ROOT_PARENT, + [0xA0; 32], + repo(), + pk(&o), + caveats(whole(), ChangeScope::any(), 1), + ); + let root_x = CapabilityLink::issue( + &a, + ROOT_PARENT, + [0xA9; 32], + repo(), + pk(&x), + caveats(whole(), ChangeScope::any(), 1), + ); + let link_w = CapabilityLink::issue( + &o, + root_o.digest(), + [0xB3; 32], + repo(), + pk(&w), + caveats( + PathScope::new(vec!["src".into()]).unwrap(), + ChangeScope::any(), + 4, + ), + ); + let link_v = CapabilityLink::issue( + &o, + root_o.digest(), + [0xB4; 32], + repo(), + pk(&v), + caveats(whole(), ChangeScope::only(vec![C]).unwrap(), 4), + ); + let co = CapabilityChain::new(vec![root_o]); + let cx = CapabilityChain::new(vec![root_x]); + let cw = co.extended(link_w); + let cv = co.extended(link_v); + for c in [&co, &cx, &cw, &cv] { + svc.auth_mut().grant_link(c, WalSeq(0), NOW).unwrap(); + } + let base_oid = GitOid([0x0B; 20]); + svc.register_base_tree( + base_oid, + vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())], + ) + .unwrap(); + let base = svc + .tree_digest(TreeTarget::BaseGitCommit(base_oid), None) + .unwrap(); + Self { + svc, + base, + o: (o, co), + w: (w, cw), + v: (v, cv), + x: (x, cx), + nonce: 0, + } + } + + fn envelope(&self, author: &SigningKey, body: &[u8], idem: u8) -> ChangesetEnvelopeV2 { + let content = RevisionContent { + change_id: C, + base_tree: self.base, + parents: vec![], + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + }], + intent_summary: "implement the task".into(), + }; + ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey([idem; 32]), NOW) + } + + fn request( + &mut self, + who: &(SigningKey, CapabilityChain), + paths: Vec, + payload: Vec, + ) -> ChainedRequest { + self.nonce += 1; + ChainedRequest::sign_new( + &who.0, + who.1.clone(), + repo(), + Capability::Propose, + RequestScope { + paths, + reference: None, + join_change: Some(C), + }, + [self.nonce; 32], + NOW, + payload, + ) + } + + fn submit( + &mut self, + who: &(SigningKey, CapabilityChain), + body: &[u8], + idem: u8, + ) -> Result { + let env = self.envelope(&who.0, body, idem); + let req = self.request(who, vec!["src/lib.rs".into()], env.encode()); + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + self.svc + .submit_revision(&req, &blobs, NOW) + .map_err(|e| e.code) + } + + fn mark( + &mut self, + who: &(SigningKey, CapabilityChain), + pred: ChangesetId, + succ: Vec, + ) -> Result { + let m = ObsolescenceMarker::sign_new(&who.0, repo(), C, pred, succ, NOW); + let req = self.request(who, vec![], m.encode()); + self.svc.record_obsolescence(&req, NOW).map_err(|e| e.code) + } +} + +fn id(o: RevisionOutcome) -> ChangesetId { + match o { + RevisionOutcome::Admitted { changeset_id, .. } + | RevisionOutcome::IdempotentDuplicate { changeset_id, .. } => changeset_id, + } +} + +#[test] +fn b1_api_join_and_prune_follow_the_creating_chain_of_real_f1_chains() { + let mut fx = Fx::new("join-prune"); + let (o, w, v, x) = (fx.o.clone(), fx.w.clone(), fx.v.clone(), fx.x.clone()); + let a = id(fx.submit(&o, b"orchestrator attempt", 1).unwrap()); + // W descends from the creating chain (O's): it joins without change scope. + let b = id(fx.submit(&w, b"worker attempt", 1).unwrap()); + // X is outside it and its grant allows any change, which names none: refused. + assert_eq!( + fx.submit(&x, b"outsider attempt", 1).unwrap_err(), + RefusalCode::AuthChangeOutOfScope + ); + // V's grant names C explicitly. + fx.submit(&v, b"scoped attempt", 1).unwrap(); + // Pruning needs a chain that is or dominates the creating chain. + assert_eq!( + fx.mark(&w, a, vec![]).unwrap_err(), + RefusalCode::AuthChainNotDominant + ); + assert_eq!( + fx.mark(&x, a, vec![]).unwrap_err(), + RefusalCode::AuthChainNotDominant + ); + fx.mark(&o, b, vec![]).unwrap(); + let st = fx.svc.store().change_status(&repo(), C).unwrap(); + assert_eq!(st.obsolete, vec![b]); + assert!( + st.divergent, + "the orchestrator's and V's attempts are both live" + ); + // Identical content from O and W: one revision, two attestations, two witnesses. + let r1 = id(fx.submit(&o, b"agreed", 7).unwrap()); + let r2 = id(fx.submit(&w, b"agreed", 7).unwrap()); + assert_eq!(r1, r2); + let rev = fx.svc.store().get_revision(&repo(), r1).unwrap(); + assert_eq!((rev.attestations.len(), rev.witnesses.len()), (2, 2)); + let digests = |c: &CapabilityChain| c.link_digests().iter().map(|d| d.0).collect::>(); + assert_eq!(rev.witnesses[0].chain.links(), digests(&o.1).as_slice()); + assert_eq!(rev.witnesses[1].chain.links(), digests(&w.1).as_slice()); + // A repeat with the same repository, DID, and idempotency key: the first WalSeq. + let first = rev.witnesses[0].admission_seq; + assert_eq!( + fx.submit(&o, b"agreed", 7).unwrap(), + RevisionOutcome::IdempotentDuplicate { + wal_seq: first, + changeset_id: r1 + } + ); +} + +#[test] +fn b1_api_refuses_paths_outside_scope_foreign_authors_and_unknown_bases() { + let mut fx = Fx::new("refusals"); + let (o, w) = (fx.o.clone(), fx.w.clone()); + fx.submit(&o, b"created", 1).unwrap(); + // W's path scope is `src`: a revision touching `docs` is refused by F1. + let mut env = fx.envelope(&w.0, b"doc", 2); + env.content.mutations[0].path = "docs/x.md".into(); + let env = + ChangesetEnvelopeV2::sign_new(&w.0, repo(), env.content, IdempotencyKey([2; 32]), NOW); + let req = fx.request(&w, vec!["docs/x.md".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, + RefusalCode::AuthPathOutOfScope + ); + // The request scope must list exactly the mutation paths. + let env = fx.envelope(&w.0, b"x", 3); + let req = fx.request(&w, vec![], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, + RefusalCode::AuthPathOutOfScope + ); + // An envelope attested by another key than the chain's agent. + let env = fx.envelope(&o.0, b"y", 4); + let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &[], NOW).unwrap_err().code, + RefusalCode::AuthSignatureInvalid + ); + // An unknown base tree. + let mut env = fx.envelope(&w.0, b"z", 5); + env.content.base_tree = TreeDigest([0xEE; 32]); + let env = + ChangesetEnvelopeV2::sign_new(&w.0, repo(), env.content, IdempotencyKey([5; 32]), NOW); + let blobs = vec![(BlobDigest::compute(b"z"), b"z".to_vec())]; + let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, + RefusalCode::BaseTreeNotFound + ); +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 5ff93e2..9840762 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -1,5 +1,6 @@ -//! Core domain identities, canonical changeset envelope v1, `did:key` Ed25519 codec, -//! and deterministic refusal taxonomy for Synapse (ADR 0001). +//! Core domain identities, canonical changeset envelopes v1 and v2 (v2 since ADR 0003 step B1, +//! [`ChangesetEnvelopeV2`]), `did:key` Ed25519 codec, and deterministic refusal taxonomy for +//! Synapse (ADR 0001). use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use serde::{Deserialize, Serialize}; @@ -7,7 +8,14 @@ use sha1::Sha1; use sha2::{Digest, Sha256}; use std::fmt; +mod revision; mod tree; +pub use revision::{ + AdmissionWitness, AuthorshipAttestation, ChainPath, ChangesetEnvelopeV2, ObsolescenceKind, + ObsolescenceMarker, RevisionContent, WitnessSigner, DOMAIN_ADMISSION_WITNESS_V1, + DOMAIN_AUTHORSHIP_SIGN_V2, DOMAIN_CHANGESET_ID_V2, DOMAIN_OBSOLESCENCE_SIGN_V1, + ENVELOPE_V2_VERSION, MAX_CHAIN_PATH_DEPTH, MAX_OBSOLESCENCE_SUCCESSORS, +}; pub use tree::{ tree_entry_order, validate_tree_entry_name, TreeDigest, TreeNodeEncoder, DOMAIN_TREE_V1, MAX_TREE_ENTRY_NAME_BYTES, TREE_TAG_DIRECTORY, @@ -56,6 +64,9 @@ pub enum RefusalCode { // Schema, path, and consistency refusals EnvelopeVersionUnsupported, + /// A changeset envelope v2, authorship attestation, admission witness, or obsolescence + /// marker is not in its one canonical binary encoding (ADR 0003 section 5.1, step B1). + EnvelopeMalformed, RepoIdInvalid, PathInvalid, PathDuplicate, @@ -101,8 +112,17 @@ pub enum RefusalCode { AuthPathOutOfScope, /// A request touches a reference kind outside the chain's reference scope (step F1). AuthReferenceOutOfScope, - /// A request joins a `ChangeId` outside the chain's change scope (step F1). + /// A request joins a `ChangeId` outside the chain's change scope (step F1), or adds a + /// revision under a `ChangeId` whose creating chain the key does not descend from while its + /// change scope does not name that `ChangeId` (ADR 0003 section 5.1, step B1). AuthChangeOutOfScope, + /// An obsolescence marker is recorded by a chain that neither is nor dominates the chain + /// it needs: the change's creating chain for a prune, or for a rewrite or split either the + /// creating chain or the chain that first admitted the replaced revision (step B1). + AuthChainNotDominant, + /// An obsolescence marker names an unknown revision, a revision of another change, itself + /// as its own successor, or would close a cycle of markers (step B1). + ObsolescenceMarkerInvalid, // Git and Radicle canonicality refusals GitObjectCorrupt, @@ -361,9 +381,9 @@ impl fmt::Debug for IdempotencyKey { } /// One unit of intended work across all its rewrites and retries (ADR 0003 section 5.1): -/// 16 random bytes, not content-derived. Step F1 uses it only to name the `ChangeId`s a -/// capability link's change scope allows its holder to join; binding a `ChangeId` to its -/// creating chain is step B1. +/// 16 random bytes, not content-derived (content changes on rewrite). A capability link's +/// change scope names the `ChangeId`s its holder may join (step F1); the first admission under +/// a `ChangeId` binds it to its creating chain (step B1, [`ChainPath`]). #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct ChangeId(pub [u8; 16]); @@ -371,6 +391,19 @@ impl ChangeId { pub fn to_hex(self) -> String { hex::encode(self.0) } + + pub fn from_hex(s: &str) -> SynapseResult { + hex::decode(s) + .ok() + .and_then(|b| <[u8; 16]>::try_from(b).ok()) + .map(Self) + .ok_or_else(|| { + SynapseError::new( + RefusalCode::EnvelopeMalformed, + "ChangeId must be 16 bytes (32 hex chars)", + ) + }) + } } impl fmt::Debug for ChangeId { @@ -379,6 +412,12 @@ impl fmt::Debug for ChangeId { } } +impl fmt::Display for ChangeId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + /// Human-facing GitHub Pull Request projection record. /// Merging a GitHub PR never by itself confers a `RadicleCanonicalHead`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -434,6 +473,16 @@ impl FileMode { Self::Symlink120000 => 3, } } + + /// The mode with tag byte `tag` (1, 2 or 3), if any. + pub fn from_tag_byte(tag: u8) -> Option { + match tag { + 1 => Some(Self::Regular644), + 2 => Some(Self::Executable755), + 3 => Some(Self::Symlink120000), + _ => None, + } + } } /// Atomic mutation operation on a single normalized repository path. @@ -488,49 +537,9 @@ impl ChangesetEnvelope { format!("unsupported envelope version {}", self.version), )); } - if self.intent_summary.is_empty() || self.intent_summary.len() > 4096 { - return Err(SynapseError::new( - RefusalCode::QuotaPayloadTooLarge, - "intent_summary must be 1..=4096 bytes", - )); - } - - // Verify parent_changesets are sorted and deduplicated - for pair in self.parent_changesets.windows(2) { - if pair[0] >= pair[1] { - return Err(SynapseError::new( - RefusalCode::MutationsUnsorted, - "parent_changesets must be strictly sorted and unique", - )); - } - } - - // Verify mutations are non-empty, valid repo-relative paths, strictly sorted, and unique - if self.mutations.is_empty() { - return Err(SynapseError::new( - RefusalCode::PathInvalid, - "changeset must contain at least one path mutation", - )); - } - let mut prev_path: Option<&str> = None; - for m in &self.mutations { - validate_repo_relative_path(&m.path)?; - if let Some(prev) = prev_path { - if prev == m.path { - return Err(SynapseError::new( - RefusalCode::PathDuplicate, - format!("duplicate path in changeset: {}", m.path), - )); - } - if prev > m.path.as_str() { - return Err(SynapseError::new( - RefusalCode::MutationsUnsorted, - format!("unsorted path in changeset: {} after {}", m.path, prev), - )); - } - } - prev_path = Some(&m.path); - } + validate_intent_summary(&self.intent_summary)?; + validate_parent_changesets(&self.parent_changesets)?; + validate_mutations(&self.mutations)?; // Verify author_did and Ed25519 signature let pubkey_bytes = decode_did_key_ed25519(&self.author_did)?; @@ -625,6 +634,63 @@ fn put_str(buf: &mut Vec, s: &str) { buf.extend_from_slice(s.as_bytes()); } +/// Longest `intent_summary` in either envelope version. +pub const MAX_INTENT_SUMMARY_BYTES: usize = 4096; + +/// An intent summary must be 1..=`MAX_INTENT_SUMMARY_BYTES` bytes (envelopes v1 and v2). +pub(crate) fn validate_intent_summary(intent_summary: &str) -> SynapseResult<()> { + if intent_summary.is_empty() || intent_summary.len() > MAX_INTENT_SUMMARY_BYTES { + return Err(SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + "intent_summary must be 1..=4096 bytes", + )); + } + Ok(()) +} + +/// Parent changesets must be strictly ascending (sorted and unique). +pub(crate) fn validate_parent_changesets(parents: &[ChangesetId]) -> SynapseResult<()> { + for pair in parents.windows(2) { + if pair[0] >= pair[1] { + return Err(SynapseError::new( + RefusalCode::MutationsUnsorted, + "parent_changesets must be strictly sorted and unique", + )); + } + } + Ok(()) +} + +/// Mutations must be non-empty, on valid repository-relative paths, strictly sorted by path. +pub(crate) fn validate_mutations(mutations: &[PathMutation]) -> SynapseResult<()> { + if mutations.is_empty() { + return Err(SynapseError::new( + RefusalCode::PathInvalid, + "changeset must contain at least one path mutation", + )); + } + let mut prev_path: Option<&str> = None; + for m in mutations { + validate_repo_relative_path(&m.path)?; + if let Some(prev) = prev_path { + if prev == m.path { + return Err(SynapseError::new( + RefusalCode::PathDuplicate, + format!("duplicate path in changeset: {}", m.path), + )); + } + if prev > m.path.as_str() { + return Err(SynapseError::new( + RefusalCode::MutationsUnsorted, + format!("unsorted path in changeset: {} after {}", m.path, prev), + )); + } + } + prev_path = Some(&m.path); + } + Ok(()) +} + /// Validate that a path is a clean, normalized repository-relative POSIX path. /// Refuses leading/trailing `/`, empty segments, `.` or `..`, backslashes, NULs, and `.git`. pub fn validate_repo_relative_path(path: &str) -> SynapseResult<()> { diff --git a/crates/synapse-core/src/revision.rs b/crates/synapse-core/src/revision.rs new file mode 100644 index 0000000..b223201 --- /dev/null +++ b/crates/synapse-core/src/revision.rs @@ -0,0 +1,983 @@ +//! Changeset envelope v2, change identity, authorship attestations, admission witnesses, and +//! obsolescence markers (ADR 0003 sections 5.1, 5.3 and 5.8, section 9 step B1). +//! +//! * A **revision** is one immutable version of a change. Its [`RevisionContent`] is what its +//! v2 `ChangesetId` covers: the `ChangeId`, the native base `TreeDigest`, parent revisions, +//! path mutations, and the intent summary. Who submitted it and when are excluded, so a +//! rewrite (new content, same `ChangeId`) gets a new `ChangesetId` while identical content +//! from two agents is one revision. +//! * An [`AuthorshipAttestation`] is an agent's signed statement that it produced a revision +//! at a time, bound to the repository and the submission's `IdempotencyKey`. A +//! [`ChangesetEnvelopeV2`] is content plus one attestation. +//! * An [`AdmissionWitness`] is what the server records, once and never changed, when it admits +//! an envelope: repository, revision, signer, idempotency key, admission `WalSeq`, server +//! time, and the [`ChainPath`] the request was authorized under. The witness of the first +//! admission under a `ChangeId` fixes that change's **creating chain**. +//! * An [`ObsolescenceMarker`] says that one revision was replaced by zero (pruned), one +//! (rewritten), or several (split) successors. +//! +//! Envelope v1 (`ChangesetEnvelope`) is unchanged: its encoding, signature, and `ChangesetId` +//! stay exactly as they were, and v1 identities never collide with v2 ones (distinct domain +//! tags). +//! +//! Every signed and persisted form here is the fixed-width, little-endian, length-prefixed +//! binary encoding of `docs/B1_CHANGE_IDENTITY.md` (ADR 0003 principle P5, the A1 codec style): +//! one encoding per value, every length checked against the bytes that remain before anything +//! is allocated, and any other byte sequence refused with `EnvelopeMalformed` (or +//! `EnvelopeVersionUnsupported` for an unknown content version). There is no serde form. + +use crate::{ + encode_did_key_ed25519, validate_intent_summary, validate_mutations, + validate_parent_changesets, ChangeId, ChangesetId, FileMode, IdempotencyKey, MutationOp, + PathMutation, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq, + MAX_INTENT_SUMMARY_BYTES, +}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; + +/// Content format version of envelope v2 (the first field of [`RevisionContent::encode`]). +pub const ENVELOPE_V2_VERSION: u16 = 2; +/// Domain tag of a v2 `ChangesetId` (v1 uses `SYNAPSE_CHANGESET_V1\0`). +pub const DOMAIN_CHANGESET_ID_V2: &[u8] = b"SYNAPSE_CHANGESET_V2\0"; +/// Domain tag of the Ed25519 signature of an [`AuthorshipAttestation`]. +pub const DOMAIN_AUTHORSHIP_SIGN_V2: &[u8] = b"SYNAPSE_AUTHORSHIP_SIGN_V2\0"; +/// Domain tag of the Ed25519 signature of an [`ObsolescenceMarker`]. +pub const DOMAIN_OBSOLESCENCE_SIGN_V1: &[u8] = b"SYNAPSE_OBSOLESCENCE_SIGN_V1\0"; +/// Domain tag of [`AdmissionWitness::digest`]. +pub const DOMAIN_ADMISSION_WITNESS_V1: &[u8] = b"SYNAPSE_ADMISSION_WITNESS_V1\0"; +/// Most links in a [`ChainPath`] (the F1 `MAX_CHAIN_DEPTH`). +pub const MAX_CHAIN_PATH_DEPTH: usize = 16; +/// Most successors of one obsolescence marker. +pub const MAX_OBSOLESCENCE_SUCCESSORS: usize = 256; + +const MAX_PATH_BYTES: usize = 2048; +const MAX_REPO_ID_BYTES: usize = 128; +/// Encoded size of the smallest mutation (`u32` empty path and a delete tag). +const MIN_MUTATION_BYTES: usize = 4 + 1; +/// Witness signer tag of an agent admission (B5 adds the server-derived signer as tag 2). +const SIGNER_TAG_AGENT: u8 = 1; +const OP_TAG_UPSERT: u8 = 1; +const OP_TAG_DELETE: u8 = 2; + +fn malformed(msg: impl Into) -> SynapseError { + SynapseError::new(RefusalCode::EnvelopeMalformed, msg) +} + +fn put_str(buf: &mut Vec, s: &str) { + buf.extend_from_slice(&(s.len() as u32).to_le_bytes()); + buf.extend_from_slice(s.as_bytes()); +} + +fn verify_ed25519(key: &[u8; 32], msg: &[u8], sig: &[u8; 64], what: &str) -> SynapseResult<()> { + let vk = VerifyingKey::from_bytes(key).map_err(|_| { + SynapseError::new( + RefusalCode::DidKeyInvalid, + format!("{what}: invalid Ed25519 public key"), + ) + })?; + vk.verify_strict(msg, &Signature::from_bytes(sig)) + .map_err(|_| { + SynapseError::new( + RefusalCode::AuthSignatureInvalid, + format!("{what}: Ed25519 signature verification failed"), + ) + }) +} + +// --------------------------------------------------------------------------------------- +// Revision content and the v2 ChangesetId +// --------------------------------------------------------------------------------------- + +/// What a v2 `ChangesetId` covers: the content of one revision, never who submitted it or +/// when. `IntentRecord` (step B3) and conflict terms (step D2) extend it under a later content +/// version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RevisionContent { + /// The unit of intended work this revision belongs to. + pub change_id: ChangeId, + /// Native base: the `TreeDigest` the mutations apply to (envelope v1's `base_git_oid`). + pub base_tree: TreeDigest, + /// Revisions this one depends on, strictly ascending. + pub parents: Vec, + /// Path mutations, strictly ascending by path, at least one. + pub mutations: Vec, + /// Free-text intent, 1..=4096 bytes (replaced by `IntentRecord` in step B3). + pub intent_summary: String, +} + +impl RevisionContent { + /// Parents strictly ascending, mutations non-empty on valid sorted unique paths, intent + /// summary 1..=4096 bytes (the same rules and refusal codes as envelope v1). + pub fn validate(&self) -> SynapseResult<()> { + validate_intent_summary(&self.intent_summary)?; + validate_parent_changesets(&self.parents)?; + validate_mutations(&self.mutations) + } + + /// `version u16 (2) | change_id [16] | base_tree [32] | u32 count | parent [32]* | + /// u32 count | (path str | op)* | intent_summary str`, where `op` is `1 | mode u8 | + /// blob_digest [32] | size u64` (upsert) or `2` (delete) and `str` is `u32 len | UTF-8`. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(128 + 96 * self.mutations.len()); + buf.extend_from_slice(&ENVELOPE_V2_VERSION.to_le_bytes()); + buf.extend_from_slice(&self.change_id.0); + buf.extend_from_slice(&self.base_tree.0); + buf.extend_from_slice(&(self.parents.len() as u32).to_le_bytes()); + for p in &self.parents { + buf.extend_from_slice(&p.0); + } + buf.extend_from_slice(&(self.mutations.len() as u32).to_le_bytes()); + for m in &self.mutations { + put_str(&mut buf, &m.path); + match &m.op { + MutationOp::Upsert { + mode, + blob_digest, + size_bytes, + } => { + buf.push(OP_TAG_UPSERT); + buf.push(mode.tag_byte()); + buf.extend_from_slice(&blob_digest.0); + buf.extend_from_slice(&size_bytes.to_le_bytes()); + } + MutationOp::Delete => buf.push(OP_TAG_DELETE), + } + } + put_str(&mut buf, &self.intent_summary); + buf + } + + /// Decode exactly one canonical content encoding (structure only; see [`Self::validate`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let content = Self::decode_from(&mut r)?; + r.finish()?; + Ok(content) + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + let version = r.u16()?; + if version != ENVELOPE_V2_VERSION { + return Err(SynapseError::new( + RefusalCode::EnvelopeVersionUnsupported, + format!("unsupported revision content version {version}"), + )); + } + let change_id = ChangeId(r.array()?); + let base_tree = TreeDigest(r.array()?); + let n = r.count(usize::MAX, 32)?; + let mut parents = Vec::with_capacity(n); + for _ in 0..n { + parents.push(ChangesetId(r.array()?)); + } + let n = r.count(usize::MAX, MIN_MUTATION_BYTES)?; + let mut mutations = Vec::with_capacity(n); + for _ in 0..n { + let path = r.string(MAX_PATH_BYTES)?; + let op = match r.u8()? { + OP_TAG_UPSERT => { + let tag = r.u8()?; + let mode = FileMode::from_tag_byte(tag) + .ok_or_else(|| malformed(format!("unknown file mode tag {tag}")))?; + MutationOp::Upsert { + mode, + blob_digest: crate::BlobDigest(r.array()?), + size_bytes: r.u64()?, + } + } + OP_TAG_DELETE => MutationOp::Delete, + tag => return Err(malformed(format!("unknown mutation tag {tag}"))), + }; + mutations.push(PathMutation { path, op }); + } + let intent_summary = r.string(MAX_INTENT_SUMMARY_BYTES)?; + Ok(Self { + change_id, + base_tree, + parents, + mutations, + intent_summary, + }) + } + + /// `SHA-256(DOMAIN_CHANGESET_ID_V2 || u64 len || encode())`: content only. + pub fn changeset_id(&self) -> ChangesetId { + let bytes = self.encode(); + let mut h = Sha256::new(); + h.update(DOMAIN_CHANGESET_ID_V2); + h.update((bytes.len() as u64).to_le_bytes()); + h.update(&bytes); + ChangesetId(h.finalize().into()) + } +} + +// --------------------------------------------------------------------------------------- +// Authorship attestation and envelope v2 +// --------------------------------------------------------------------------------------- + +/// An agent's signed statement that it produced revision `changeset_id` of repository +/// `repo_id` at `attested_at_ms` (the agent's clock, never used for ordering or retention), +/// submitted under `idempotency_key`. An attestation added later never revokes a receipt +/// already accepted (ADR 0003 section 5.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorshipAttestation { + pub repo_id: RepoId, + pub changeset_id: ChangesetId, + pub author_key: [u8; 32], + pub idempotency_key: IdempotencyKey, + pub attested_at_ms: u64, + pub signature: [u8; 64], +} + +impl AuthorshipAttestation { + /// Sign an attestation with `author`. + pub fn sign( + author: &SigningKey, + repo_id: RepoId, + changeset_id: ChangesetId, + idempotency_key: IdempotencyKey, + attested_at_ms: u64, + ) -> Self { + let mut att = Self { + repo_id, + changeset_id, + author_key: author.verifying_key().to_bytes(), + idempotency_key, + attested_at_ms, + signature: [0u8; 64], + }; + att.signature = author.sign(&att.signable_bytes()).to_bytes(); + att + } + + /// The author's `did:key`. + pub fn author_did(&self) -> String { + encode_did_key_ed25519(&self.author_key) + } + + fn encode_body(&self, buf: &mut Vec) { + put_str(buf, self.repo_id.as_str()); + buf.extend_from_slice(&self.changeset_id.0); + buf.extend_from_slice(&self.author_key); + buf.extend_from_slice(&self.idempotency_key.0); + buf.extend_from_slice(&self.attested_at_ms.to_le_bytes()); + } + + /// `DOMAIN_AUTHORSHIP_SIGN_V2 || repo_id str || changeset_id || author_key || + /// idempotency_key || attested_at_ms u64`. + pub fn signable_bytes(&self) -> Vec { + let mut buf = Vec::with_capacity(192); + buf.extend_from_slice(DOMAIN_AUTHORSHIP_SIGN_V2); + self.encode_body(&mut buf); + buf + } + + /// Strict Ed25519 verification of the author's signature. + pub fn verify(&self) -> SynapseResult<()> { + verify_ed25519( + &self.author_key, + &self.signable_bytes(), + &self.signature, + "authorship attestation", + ) + } + + /// Body (as signed, without the domain tag) then the 64-byte signature. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(192); + self.encode_into(&mut buf); + buf + } + + fn encode_into(&self, buf: &mut Vec) { + self.encode_body(buf); + buf.extend_from_slice(&self.signature); + } + + /// Decode exactly one canonical attestation (structure only; see [`Self::verify`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let att = Self::decode_from(&mut r)?; + r.finish()?; + Ok(att) + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + Ok(Self { + repo_id: r.repo()?, + changeset_id: ChangesetId(r.array()?), + author_key: r.array()?, + idempotency_key: IdempotencyKey(r.array()?), + attested_at_ms: r.u64()?, + signature: r.array()?, + }) + } +} + +/// Signed changeset envelope v2: one revision's content plus one authorship attestation over +/// its content-only `ChangesetId`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChangesetEnvelopeV2 { + pub content: RevisionContent, + pub attestation: AuthorshipAttestation, +} + +impl ChangesetEnvelopeV2 { + /// Build and sign an envelope: the attestation names `content.changeset_id()`. + pub fn sign_new( + author: &SigningKey, + repo_id: RepoId, + content: RevisionContent, + idempotency_key: IdempotencyKey, + attested_at_ms: u64, + ) -> Self { + let id = content.changeset_id(); + let attestation = + AuthorshipAttestation::sign(author, repo_id, id, idempotency_key, attested_at_ms); + Self { + content, + attestation, + } + } + + /// The content-only v2 `ChangesetId`. + pub fn changeset_id(&self) -> ChangesetId { + self.content.changeset_id() + } + + /// Validate the content, check that the attestation names this content, and verify its + /// signature. Returns the v2 `ChangesetId`. + pub fn validate(&self) -> SynapseResult { + self.content.validate()?; + let id = self.content.changeset_id(); + if self.attestation.changeset_id != id { + return Err(SynapseError::new( + RefusalCode::AuthSignatureInvalid, + format!( + "attestation names revision {} but the content is revision {id}", + self.attestation.changeset_id + ), + )); + } + self.attestation.verify()?; + Ok(id) + } + + /// `u32 content_len | content | attestation`. + pub fn encode(&self) -> Vec { + let content = self.content.encode(); + let mut buf = Vec::with_capacity(content.len() + 196); + buf.extend_from_slice(&(content.len() as u32).to_le_bytes()); + buf.extend_from_slice(&content); + self.attestation.encode_into(&mut buf); + buf + } + + /// Decode exactly one canonical envelope (structure only; see [`Self::validate`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let len = r.u32()? as usize; + let mut inner = Reader::new(r.take(len)?); + let content = RevisionContent::decode_from(&mut inner)?; + inner.finish()?; + let attestation = AuthorshipAttestation::decode_from(&mut r)?; + r.finish()?; + Ok(Self { + content, + attestation, + }) + } +} + +// --------------------------------------------------------------------------------------- +// Chains, witnesses, markers +// --------------------------------------------------------------------------------------- + +/// A delegation chain as the digests of its capability links, root first (each digest is a +/// `synapse_auth::LinkDigest`). Chains are compared by their link digests: chain `A` +/// **dominates** chain `B` when `A` is `B` or one of its ancestors (a prefix of it), and `B` +/// then **descends from** `A`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ChainPath(Vec<[u8; 32]>); + +impl ChainPath { + /// A chain of 1..=`MAX_CHAIN_PATH_DEPTH` link digests, root first. + pub fn new(links: Vec<[u8; 32]>) -> SynapseResult { + if links.is_empty() || links.len() > MAX_CHAIN_PATH_DEPTH { + return Err(SynapseError::new( + RefusalCode::AuthChainBroken, + format!( + "chain path length {} outside 1..={MAX_CHAIN_PATH_DEPTH}", + links.len() + ), + )); + } + Ok(Self(links)) + } + + /// Link digests, root first. + pub fn links(&self) -> &[[u8; 32]] { + &self.0 + } + + /// True when `self` is `other` or an ancestor of it (a prefix of its links). + pub fn dominates(&self, other: &ChainPath) -> bool { + other.0.starts_with(&self.0) + } + + /// True when `self` is `ancestor` or descends from it. + pub fn descends_from(&self, ancestor: &ChainPath) -> bool { + ancestor.dominates(self) + } + + /// `count u8 | digest [32]*`. + pub fn encode_into(&self, buf: &mut Vec) { + buf.push(self.0.len() as u8); + for d in &self.0 { + buf.extend_from_slice(d); + } + } + + /// Decode exactly one canonical chain path. + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let c = Self::decode_from(&mut r)?; + r.finish()?; + Ok(c) + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + let n = r.u8()? as usize; + if n == 0 || n > MAX_CHAIN_PATH_DEPTH { + return Err(malformed(format!( + "chain path length {n} outside 1..={MAX_CHAIN_PATH_DEPTH}" + ))); + } + let mut links = Vec::with_capacity(n); + for _ in 0..n { + links.push(r.array()?); + } + Ok(Self(links)) + } +} + +/// Who signed an admitted revision. Step B5 adds the server-derived signer (the server's +/// machine-key signature and its `DerivationAttestation` digest) under tag 2. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WitnessSigner { + /// An agent's key and its signature over the envelope (its authorship attestation). + Agent { + author_key: [u8; 32], + signature: [u8; 64], + }, +} + +/// The immutable record of one admission of a revision (ADR 0003 section 5.1). Idempotency +/// is keyed on (`repo_id`, signer DID, `idempotency_key`); replay order is `admission_seq`; +/// retention follows the server's clock (`admitted_at_ms`), never a client clock. `chain` is +/// the delegation chain the admission was authorized under; the first admission's chain is +/// the change's creating chain. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdmissionWitness { + pub repo_id: RepoId, + pub changeset_id: ChangesetId, + pub signer: WitnessSigner, + pub idempotency_key: IdempotencyKey, + pub admission_seq: WalSeq, + pub admitted_at_ms: u64, + pub chain: ChainPath, +} + +impl AdmissionWitness { + /// The witness of admitting `attestation` at `admission_seq` under `chain`. + pub fn of_attestation( + attestation: &AuthorshipAttestation, + chain: ChainPath, + admission_seq: WalSeq, + admitted_at_ms: u64, + ) -> Self { + Self { + repo_id: attestation.repo_id.clone(), + changeset_id: attestation.changeset_id, + signer: WitnessSigner::Agent { + author_key: attestation.author_key, + signature: attestation.signature, + }, + idempotency_key: attestation.idempotency_key, + admission_seq, + admitted_at_ms, + chain, + } + } + + /// The signer's `did:key`. + pub fn signer_did(&self) -> String { + match &self.signer { + WitnessSigner::Agent { author_key, .. } => encode_did_key_ed25519(author_key), + } + } + + /// `repo_id str | changeset_id [32] | signer | idempotency_key [32] | admission_seq u64 | + /// admitted_at_ms u64 | chain`, with `signer` = `1 | author_key [32] | signature [64]`. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(256); + put_str(&mut buf, self.repo_id.as_str()); + buf.extend_from_slice(&self.changeset_id.0); + match &self.signer { + WitnessSigner::Agent { + author_key, + signature, + } => { + buf.push(SIGNER_TAG_AGENT); + buf.extend_from_slice(author_key); + buf.extend_from_slice(signature); + } + } + buf.extend_from_slice(&self.idempotency_key.0); + buf.extend_from_slice(&self.admission_seq.0.to_le_bytes()); + buf.extend_from_slice(&self.admitted_at_ms.to_le_bytes()); + self.chain.encode_into(&mut buf); + buf + } + + /// Decode exactly one canonical witness. + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let repo_id = r.repo()?; + let changeset_id = ChangesetId(r.array()?); + let signer = match r.u8()? { + SIGNER_TAG_AGENT => WitnessSigner::Agent { + author_key: r.array()?, + signature: r.array()?, + }, + tag => return Err(malformed(format!("unknown witness signer tag {tag}"))), + }; + let w = Self { + repo_id, + changeset_id, + signer, + idempotency_key: IdempotencyKey(r.array()?), + admission_seq: WalSeq(r.u64()?), + admitted_at_ms: r.u64()?, + chain: ChainPath::decode_from(&mut r)?, + }; + r.finish()?; + Ok(w) + } + + /// `SHA-256(DOMAIN_ADMISSION_WITNESS_V1 || encode())`: the admission witness digest that + /// promotion signatures cover (ADR 0003 section 5.5). + pub fn digest(&self) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(DOMAIN_ADMISSION_WITNESS_V1); + h.update(self.encode()); + h.finalize().into() + } +} + +/// How many successors replace the obsolete revision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ObsolescenceKind { + /// Zero successors: the attempt is discarded. + Pruned, + /// One successor. + Rewritten, + /// Several successors. + Split, +} + +/// A signed record that revision `predecessor` of change `change_id` was replaced by +/// `successors` (strictly ascending, never containing `predecessor`): zero for a prune, one +/// for a rewrite, several for a split (ADR 0003 sections 5.1 and 5.3). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ObsolescenceMarker { + pub repo_id: RepoId, + pub change_id: ChangeId, + pub predecessor: ChangesetId, + pub successors: Vec, + pub signer_key: [u8; 32], + pub signed_at_ms: u64, + pub signature: [u8; 64], +} + +impl ObsolescenceMarker { + /// Build and sign a marker; `successors` are sorted and deduplicated. + pub fn sign_new( + signer: &SigningKey, + repo_id: RepoId, + change_id: ChangeId, + predecessor: ChangesetId, + mut successors: Vec, + signed_at_ms: u64, + ) -> Self { + successors.sort(); + successors.dedup(); + let mut m = Self { + repo_id, + change_id, + predecessor, + successors, + signer_key: signer.verifying_key().to_bytes(), + signed_at_ms, + signature: [0u8; 64], + }; + m.signature = signer.sign(&m.signable_bytes()).to_bytes(); + m + } + + /// Pruned, rewritten, or split, by successor count. + pub fn kind(&self) -> ObsolescenceKind { + match self.successors.len() { + 0 => ObsolescenceKind::Pruned, + 1 => ObsolescenceKind::Rewritten, + _ => ObsolescenceKind::Split, + } + } + + /// The signer's `did:key`. + pub fn signer_did(&self) -> String { + encode_did_key_ed25519(&self.signer_key) + } + + fn encode_body(&self, buf: &mut Vec) { + put_str(buf, self.repo_id.as_str()); + buf.extend_from_slice(&self.change_id.0); + buf.extend_from_slice(&self.predecessor.0); + buf.extend_from_slice(&(self.successors.len() as u32).to_le_bytes()); + for s in &self.successors { + buf.extend_from_slice(&s.0); + } + buf.extend_from_slice(&self.signer_key); + buf.extend_from_slice(&self.signed_at_ms.to_le_bytes()); + } + + /// `DOMAIN_OBSOLESCENCE_SIGN_V1 || repo_id str || change_id [16] || predecessor [32] || + /// u32 count || successor [32]* || signer_key [32] || signed_at_ms u64`. + pub fn signable_bytes(&self) -> Vec { + let mut buf = Vec::with_capacity(160 + 32 * self.successors.len()); + buf.extend_from_slice(DOMAIN_OBSOLESCENCE_SIGN_V1); + self.encode_body(&mut buf); + buf + } + + /// Successors strictly ascending, at most `MAX_OBSOLESCENCE_SUCCESSORS`, never the + /// predecessor; signature verifies strictly. + pub fn validate(&self) -> SynapseResult<()> { + if self.successors.len() > MAX_OBSOLESCENCE_SUCCESSORS { + return Err(SynapseError::new( + RefusalCode::ObsolescenceMarkerInvalid, + format!("more than {MAX_OBSOLESCENCE_SUCCESSORS} successors"), + )); + } + if self.successors.windows(2).any(|w| w[0] >= w[1]) { + return Err(SynapseError::new( + RefusalCode::ObsolescenceMarkerInvalid, + "successors must be strictly ascending", + )); + } + if self.successors.contains(&self.predecessor) { + return Err(SynapseError::new( + RefusalCode::ObsolescenceMarkerInvalid, + "a revision cannot be its own successor", + )); + } + verify_ed25519( + &self.signer_key, + &self.signable_bytes(), + &self.signature, + "obsolescence marker", + ) + } + + /// Body (as signed, without the domain tag) then the 64-byte signature. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(160 + 32 * self.successors.len()); + self.encode_body(&mut buf); + buf.extend_from_slice(&self.signature); + buf + } + + /// Decode exactly one canonical marker (structure only; see [`Self::validate`]). + pub fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let repo_id = r.repo()?; + let change_id = ChangeId(r.array()?); + let predecessor = ChangesetId(r.array()?); + let n = r.count(MAX_OBSOLESCENCE_SUCCESSORS, 32)?; + let mut successors = Vec::with_capacity(n); + for _ in 0..n { + successors.push(ChangesetId(r.array()?)); + } + let m = Self { + repo_id, + change_id, + predecessor, + successors, + signer_key: r.array()?, + signed_at_ms: r.u64()?, + signature: r.array()?, + }; + r.finish()?; + Ok(m) + } + + /// `SHA-256(DOMAIN_OBSOLESCENCE_SIGN_V1 || encode())`: identity of one signed marker. + pub fn digest(&self) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(DOMAIN_OBSOLESCENCE_SIGN_V1); + h.update(self.encode()); + h.finalize().into() + } +} + +// --------------------------------------------------------------------------------------- +// Bounded reader +// --------------------------------------------------------------------------------------- + +/// Bounds-checked little-endian reader; every failure is `EnvelopeMalformed`. +struct Reader<'a> { + buf: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn new(buf: &'a [u8]) -> Self { + Self { buf, pos: 0 } + } + + fn remaining(&self) -> usize { + self.buf.len() - self.pos + } + + fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> { + if n > self.remaining() { + return Err(malformed(format!( + "truncated: need {n} bytes at offset {}, {} remain", + self.pos, + self.remaining() + ))); + } + let out = &self.buf[self.pos..self.pos + n]; + self.pos += n; + Ok(out) + } + + fn array(&mut self) -> SynapseResult<[u8; N]> { + Ok(self.take(N)?.try_into().expect("N bytes")) + } + + fn u8(&mut self) -> SynapseResult { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> SynapseResult { + Ok(u16::from_le_bytes(self.array()?)) + } + + fn u32(&mut self) -> SynapseResult { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> SynapseResult { + Ok(u64::from_le_bytes(self.array()?)) + } + + /// A `u32` count, refused above `cap` or above what `min_item_bytes` per item could fit + /// in the bytes that remain (so nothing is reserved beyond the input). + fn count(&mut self, cap: usize, min_item_bytes: usize) -> SynapseResult { + let n = self.u32()? as usize; + if n > cap || n.saturating_mul(min_item_bytes) > self.remaining() { + return Err(malformed(format!( + "count {n} above cap {cap} or the {} bytes that remain", + self.remaining() + ))); + } + Ok(n) + } + + fn string(&mut self, cap: usize) -> SynapseResult { + let len = self.u32()? as usize; + if len > cap { + return Err(malformed(format!("string length {len} above cap {cap}"))); + } + let bytes = self.take(len)?; + String::from_utf8(bytes.to_vec()).map_err(|_| malformed("string is not UTF-8")) + } + + fn repo(&mut self) -> SynapseResult { + let s = self.string(MAX_REPO_ID_BYTES)?; + RepoId::new(s).map_err(|e| malformed(format!("repository id: {}", e.message))) + } + + fn finish(&self) -> SynapseResult<()> { + if self.pos != self.buf.len() { + return Err(malformed(format!("{} trailing bytes", self.remaining()))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::BlobDigest; + + fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() + } + + fn content(change: u8, body: &[u8]) -> RevisionContent { + RevisionContent { + change_id: ChangeId([change; 16]), + base_tree: TreeDigest([0x5A; 32]), + parents: vec![], + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + }], + intent_summary: "add lib".into(), + } + } + + #[test] + fn b1_v2_changeset_id_covers_content_only_not_author_or_time() { + let a = SigningKey::from_bytes(&[1; 32]); + let b = SigningKey::from_bytes(&[2; 32]); + let c = content(7, b"x"); + let ea = ChangesetEnvelopeV2::sign_new(&a, repo(), c.clone(), IdempotencyKey([1; 32]), 10); + let eb = ChangesetEnvelopeV2::sign_new(&b, repo(), c.clone(), IdempotencyKey([2; 32]), 99); + assert_eq!(ea.validate().unwrap(), eb.validate().unwrap()); + assert_ne!(ea.attestation, eb.attestation); + let mut rewritten = c.clone(); + rewritten.intent_summary = "add lib, rewritten".into(); + assert_ne!(rewritten.changeset_id(), c.changeset_id()); + assert_eq!(rewritten.change_id, c.change_id); + } + + #[test] + fn b1_envelope_v2_round_trips_and_refuses_malformed_bytes() { + let a = SigningKey::from_bytes(&[1; 32]); + let mut c = content(7, b"x"); + c.parents = vec![ChangesetId([1; 32]), ChangesetId([2; 32])]; + c.mutations.push(PathMutation { + path: "src/old.rs".into(), + op: MutationOp::Delete, + }); + let env = ChangesetEnvelopeV2::sign_new(&a, repo(), c, IdempotencyKey([1; 32]), 10); + let bytes = env.encode(); + assert_eq!(ChangesetEnvelopeV2::decode(&bytes).unwrap(), env); + assert_eq!(ChangesetEnvelopeV2::decode(&bytes).unwrap().encode(), bytes); + for cut in 0..bytes.len() { + assert!( + ChangesetEnvelopeV2::decode(&bytes[..cut]).is_err(), + "cut {cut}" + ); + } + let mut trailing = bytes.clone(); + trailing.push(0); + assert_eq!( + ChangesetEnvelopeV2::decode(&trailing).unwrap_err().code, + RefusalCode::EnvelopeMalformed + ); + let mut huge = bytes.clone(); + huge[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!( + ChangesetEnvelopeV2::decode(&huge).unwrap_err().code, + RefusalCode::EnvelopeMalformed + ); + let mut version = bytes.clone(); + version[4] = 3; + assert_eq!( + ChangesetEnvelopeV2::decode(&version).unwrap_err().code, + RefusalCode::EnvelopeVersionUnsupported + ); + } + + #[test] + fn b1_envelope_v2_signature_binds_repo_key_and_time() { + let a = SigningKey::from_bytes(&[1; 32]); + let env = ChangesetEnvelopeV2::sign_new( + &a, + repo(), + content(7, b"x"), + IdempotencyKey([1; 32]), + 10, + ); + let mut t = env.clone(); + t.attestation.attested_at_ms = 11; + assert_eq!( + t.validate().unwrap_err().code, + RefusalCode::AuthSignatureInvalid + ); + let mut t = env.clone(); + t.attestation.repo_id = RepoId::new("aien-spark/other").unwrap(); + assert_eq!( + t.validate().unwrap_err().code, + RefusalCode::AuthSignatureInvalid + ); + let mut t = env.clone(); + t.content.intent_summary = "changed".into(); + assert_eq!( + t.validate().unwrap_err().code, + RefusalCode::AuthSignatureInvalid + ); + } + + #[test] + fn b1_chain_path_dominance_is_prefix_order() { + let r = ChainPath::new(vec![[1; 32]]).unwrap(); + let o = ChainPath::new(vec![[1; 32], [2; 32]]).unwrap(); + let w = ChainPath::new(vec![[1; 32], [2; 32], [3; 32]]).unwrap(); + let x = ChainPath::new(vec![[1; 32], [9; 32]]).unwrap(); + assert!(r.dominates(&o) && o.dominates(&w) && r.dominates(&w) && o.dominates(&o)); + assert!(!w.dominates(&o) && !x.dominates(&w) && !o.dominates(&x)); + assert!(w.descends_from(&o) && !x.descends_from(&o)); + assert!(ChainPath::new(vec![]).is_err()); + assert!(ChainPath::new(vec![[0; 32]; MAX_CHAIN_PATH_DEPTH + 1]).is_err()); + } + + #[test] + fn b1_witness_and_marker_round_trip() { + let a = SigningKey::from_bytes(&[1; 32]); + let env = ChangesetEnvelopeV2::sign_new( + &a, + repo(), + content(7, b"x"), + IdempotencyKey([1; 32]), + 10, + ); + let chain = ChainPath::new(vec![[1; 32], [2; 32]]).unwrap(); + let w = AdmissionWitness::of_attestation(&env.attestation, chain, WalSeq(4), 77); + assert_eq!(AdmissionWitness::decode(&w.encode()).unwrap(), w); + assert_eq!(w.signer_did(), env.attestation.author_did()); + let m = ObsolescenceMarker::sign_new( + &a, + repo(), + ChangeId([7; 16]), + ChangesetId([3; 32]), + vec![ + ChangesetId([5; 32]), + ChangesetId([4; 32]), + ChangesetId([5; 32]), + ], + 12, + ); + assert_eq!( + m.successors, + vec![ChangesetId([4; 32]), ChangesetId([5; 32])] + ); + assert_eq!(m.kind(), ObsolescenceKind::Split); + m.validate().unwrap(); + assert_eq!(ObsolescenceMarker::decode(&m.encode()).unwrap(), m); + let mut own = m.clone(); + own.successors = vec![m.predecessor]; + assert_eq!( + own.validate().unwrap_err().code, + RefusalCode::ObsolescenceMarkerInvalid + ); + } +} diff --git a/crates/synapse-store/src/a1_tests.rs b/crates/synapse-store/src/a1_tests.rs index d361bda..a2f0287 100644 --- a/crates/synapse-store/src/a1_tests.rs +++ b/crates/synapse-store/src/a1_tests.rs @@ -407,7 +407,7 @@ fn a1_documented_layout_decodes_and_every_non_canonical_form_is_refused() { Err(CodecRefusal::VersionUnsupported { found: 1 }) ); let mut k = review.clone(); - k[1] = 7; + k[1] = 9; // first unused kind (7 and 8 are the B1 revision records) assert_eq!(kind(decode_record(&k, CAP)), "UnknownTag"); let mut k0 = review.clone(); k0[1] = 0; @@ -521,11 +521,11 @@ fn a1_state_root_helpers_match_the_store() { ) .unwrap(); assert_eq!( - state_root_of(&s.changesets, s.committed_seq), + state_root_of(&s.changesets, &[], s.committed_seq), s.state_root_digest(None).unwrap() ); assert_eq!( - state_root_of(&s.changesets, WalSeq(3)), + state_root_of(&s.changesets, &[], WalSeq(3)), s.state_root_digest(Some(WalSeq(3))).unwrap() ); } diff --git a/crates/synapse-store/src/codec.rs b/crates/synapse-store/src/codec.rs index 87dee29..9015d85 100644 --- a/crates/synapse-store/src/codec.rs +++ b/crates/synapse-store/src/codec.rs @@ -93,6 +93,13 @@ pub enum CodecRefusal { NotCanonical { at: usize, field: &'static str }, /// A repository id fails `RepoId::new`. InvalidRepoId { at: usize }, + /// An embedded `synapse-core` encoding (envelope v2, chain path, marker) is refused + /// by its own decoder with `code`. + EmbeddedMalformed { + at: usize, + field: &'static str, + code: RefusalCode, + }, } impl CodecRefusal { @@ -107,6 +114,7 @@ impl CodecRefusal { Self::VersionUnsupported { .. } => "VersionUnsupported", Self::NotCanonical { .. } => "NotCanonical", Self::InvalidRepoId { .. } => "InvalidRepoId", + Self::EmbeddedMalformed { .. } => "EmbeddedMalformed", } } @@ -309,10 +317,39 @@ pub fn encode_record(record: &WalRecord) -> SynapseResult> { w.raw(&changeset_id.0); w.u64(*lease_expires_at_ms); } + WalRecord::RevisionAdmitted { + envelope, + chain, + admitted_at_ms, + new_blobs, + } => { + w.bytes(&envelope.encode(), "envelope v2")?; + put_chain(&mut w, chain)?; + w.u64(*admitted_at_ms); + w.len(new_blobs.len(), "new blob count")?; + for b in new_blobs { + w.raw(&b.0); + } + } + WalRecord::ObsolescenceRecorded { + marker, + chain, + recorded_at_ms, + } => { + w.bytes(&marker.encode(), "obsolescence marker")?; + put_chain(&mut w, chain)?; + w.u64(*recorded_at_ms); + } } Ok(w.0) } +fn put_chain(w: &mut Writer, chain: &ChainPath) -> SynapseResult<()> { + let mut buf = Vec::with_capacity(1 + 32 * chain.links().len()); + chain.encode_into(&mut buf); + w.bytes(&buf, "chain path") +} + // --------------------------------------------------------------------------------------- // Reader (untrusted input) // --------------------------------------------------------------------------------------- @@ -444,6 +481,21 @@ impl<'a> Reader<'a> { Ok((n as usize, Vec::with_capacity(n as usize))) } + /// A length-prefixed value in a `synapse-core` canonical encoding, decoded by `decode`. + fn embedded( + &mut self, + field: &'static str, + decode: impl FnOnce(&[u8]) -> SynapseResult, + ) -> Decoded { + let at = self.pos; + let n = self.byte_len()?; + decode(self.take(n)?).map_err(|e| CodecRefusal::EmbeddedMalformed { + at, + field, + code: e.code, + }) + } + fn finish(&self) -> Decoded<()> { match self.remaining() { 0 => Ok(()), @@ -659,6 +711,26 @@ pub fn decode_record(bytes: &[u8], cap: u64) -> Result changeset_id: ChangesetId(r.array()?), lease_expires_at_ms: r.u64()?, }, + 7 => { + let envelope = r.embedded("envelope v2", ChangesetEnvelopeV2::decode)?; + let chain = r.embedded("chain path", ChainPath::decode)?; + let admitted_at_ms = r.u64()?; + let (n, mut new_blobs) = r.vec(32)?; + for _ in 0..n { + new_blobs.push(BlobDigest(r.array()?)); + } + WalRecord::RevisionAdmitted { + envelope, + chain, + admitted_at_ms, + new_blobs, + } + } + 8 => WalRecord::ObsolescenceRecorded { + marker: r.embedded("obsolescence marker", ObsolescenceMarker::decode)?, + chain: r.embedded("chain path", ChainPath::decode)?, + recorded_at_ms: r.u64()?, + }, tag => { return Err(CodecRefusal::UnknownTag { at, @@ -711,17 +783,21 @@ pub struct CheckpointState { pub blob_first_visible_seq: BTreeMap, pub github_projections: BTreeMap, pub canonical_heads: BTreeMap, + /// Revision records (kinds 7 and 8) in sequence order (ADR 0003 B1). Written only when + /// non-empty, so checkpoints of stores without revisions keep their exact bytes. + pub revision_log: Vec<(WalSeq, WalRecord)>, } /// `state_root_digest` of a store that holds nothing (sequence 0, no changesets): the /// v1 root recorded by a store that never wrote a v1 record. pub fn empty_state_root() -> [u8; 32] { - state_root_of(&BTreeMap::new(), WalSeq::ZERO) + state_root_of(&BTreeMap::new(), &[], WalSeq::ZERO) } /// `SynapseStore::state_root_digest` over `changesets` at `snapshot_seq`. pub fn state_root_of( changesets: &BTreeMap, + revision_log: &[(WalSeq, WalRecord)], snapshot_seq: WalSeq, ) -> [u8; 32] { let mut hasher = Sha256::new(); @@ -735,6 +811,7 @@ pub fn state_root_of( hasher.update((cs.reviews.len() as u32).to_le_bytes()); } } + crate::revision::RevisionLedger::hash_into(revision_log, snapshot_seq, &mut hasher); hasher.finalize().into() } @@ -846,7 +923,7 @@ impl CheckpointState { /// State root of this state at its checkpoint sequence. pub fn state_root(&self) -> [u8; 32] { - state_root_of(&self.changesets, self.checkpoint_seq) + state_root_of(&self.changesets, &self.revision_log, self.checkpoint_seq) } /// Keys that the encoding derives from values must match them. @@ -892,6 +969,14 @@ impl CheckpointState { for c in self.canonical_heads.values() { put_canonical(&mut w, c)?; } + // Revision section (ADR 0003 B1): present only when there are revision records. + if !self.revision_log.is_empty() { + w.len(self.revision_log.len(), "revision record count")?; + for (seq, record) in &self.revision_log { + w.u64(seq.0); + w.bytes(&encode_record(record)?, "revision record")?; + } + } Ok(w.0) } @@ -961,6 +1046,40 @@ impl CheckpointState { prev = Some(c.repo_id.clone()); s.canonical_heads.insert(c.repo_id.clone(), c); } + if r.remaining() > 0 { + let at = r.pos; + let (n, _) = r.vec::(8 + MIN_STR)?; + if n == 0 { + // An empty section is written as no section at all. + return Err(CodecRefusal::NotCanonical { + at, + field: "revision records", + }); + } + let mut prev = None; + for _ in 0..n { + let at = r.pos; + let seq = WalSeq(r.u64()?); + if prev.is_some_and(|p| p >= seq) || seq > checkpoint_seq { + return Err(CodecRefusal::NotCanonical { + at, + field: "revision records", + }); + } + prev = Some(seq); + let tag_at = r.pos + 4 + 1; + let bytes = r.bytes()?; + let record = decode_record(&bytes, r.cap)?; + if !matches!(record.kind_byte(), 7 | 8) { + return Err(CodecRefusal::UnknownTag { + at: tag_at, + field: "revision record kind", + tag: record.kind_byte(), + }); + } + s.revision_log.push((seq, record)); + } + } r.finish()?; Ok(s) } diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs index 2443d4e..144657d 100644 --- a/crates/synapse-store/src/lib.rs +++ b/crates/synapse-store/src/lib.rs @@ -20,9 +20,9 @@ use std::fs::{self, File, OpenOptions}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use synapse_core::{ - BlobDigest, ChangesetEnvelope, ChangesetId, EvidenceAttachment, GitHubPullRequestProjection, - IdempotencyKey, MutationOp, RadicleCanonicalHead, RefusalCode, RepoId, SynapseError, - SynapseResult, WalSeq, + BlobDigest, ChainPath, ChangesetEnvelope, ChangesetEnvelopeV2, ChangesetId, EvidenceAttachment, + GitHubPullRequestProjection, IdempotencyKey, MutationOp, ObsolescenceMarker, + RadicleCanonicalHead, RefusalCode, RepoId, SynapseError, SynapseResult, WalSeq, }; #[cfg(test)] @@ -30,6 +30,7 @@ mod a1_tests; pub mod codec; #[cfg(test)] mod group_tests; +mod revision; pub mod segment; #[cfg(test)] mod segment_tests; @@ -37,6 +38,10 @@ mod shared; pub mod wal2; pub use codec::{CheckpointChain, CheckpointState, CodecRefusal, RecordCodec}; +pub use revision::{ + AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, StoredRevision, + DOMAIN_STATE_ROOT_REVISIONS_V1, +}; pub use shared::{GroupCommitStats, SharedStore}; /// Magic bytes for a Synapse WAL frame (`b"SWAL"`). @@ -301,6 +306,23 @@ pub enum WalRecord { changeset_id: ChangesetId, lease_expires_at_ms: u64, }, + /// Admission of an envelope v2 revision under `chain` at server time `admitted_at_ms` + /// (ADR 0003 B1). Binary codec only: it has no v1 JSON form. + #[serde(skip)] + RevisionAdmitted { + envelope: ChangesetEnvelopeV2, + chain: ChainPath, + admitted_at_ms: u64, + new_blobs: Vec, + }, + /// An obsolescence marker recorded under `chain` at server time `recorded_at_ms` + /// (ADR 0003 B1). Binary codec only. + #[serde(skip)] + ObsolescenceRecorded { + marker: ObsolescenceMarker, + chain: ChainPath, + recorded_at_ms: u64, + }, } impl WalRecord { @@ -312,8 +334,26 @@ impl WalRecord { Self::GitProjected { .. } => 4, Self::CanonicalPromoted { .. } => 5, Self::LeaseUpdated { .. } => 6, + Self::RevisionAdmitted { .. } => 7, + Self::ObsolescenceRecorded { .. } => 8, } } + + /// Blob digests the upserts of this record reference (ingest and revision records). + pub fn upsert_blobs(&self) -> Vec { + let mutations = match self { + Self::ChangesetIngest { envelope, .. } => &envelope.mutations, + Self::RevisionAdmitted { envelope, .. } => &envelope.content.mutations, + _ => return Vec::new(), + }; + mutations + .iter() + .filter_map(|m| match &m.op { + MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest), + MutationOp::Delete => None, + }) + .collect() + } } /// Stored metadata for a committed changeset in `SynapseStore`. @@ -425,6 +465,8 @@ pub struct SynapseStore { /// A binary checkpoint or a binary frame was replayed: v1 JSON frames are refused. binary_seen: bool, /// `checkpoint.v1` is not yet the tombstone although `checkpoint.v2` exists. + /// Envelope v2 revisions, changes, witnesses, and markers (ADR 0003 B1). + revisions: revision::RevisionLedger, tombstone_pending: bool, } @@ -567,6 +609,7 @@ impl SynapseStore { v1_history: false, binary_seen: false, tombstone_pending: false, + revisions: revision::RevisionLedger::default(), }; store.recover(recovery_policy)?; @@ -1532,7 +1575,11 @@ impl SynapseStore { /// Compute a deterministic SHA-256 digest of all visible state up to `snapshot_seq`. pub fn state_root_digest(&self, snapshot_seq: Option) -> SynapseResult<[u8; 32]> { let snap = self.resolve_snapshot_seq(None, snapshot_seq)?; - Ok(codec::state_root_of(&self.changesets, snap)) + Ok(codec::state_root_of( + &self.changesets, + self.revisions.log(), + snap, + )) } /// Write an atomic checkpoint, compact `wal.log`, and sweep unreferenced speculative blobs @@ -1567,6 +1614,11 @@ impl SynapseStore { } } + // Revisions are never evicted (no sweep before K1), so their v1 parents stay too. + for rev in self.revisions.revisions() { + worklist.extend(rev.content.parents.iter().copied()); + } + // Compute transitive ancestor closure over `parent_changesets` while let Some(cs_id) = worklist.pop() { if retained_cs.insert(cs_id) { @@ -1587,6 +1639,13 @@ impl SynapseStore { // 2. Compute retained blob closure from retained changesets let mut retained_blobs: BTreeSet = BTreeSet::new(); + for rev in self.revisions.revisions() { + for m in &rev.content.mutations { + if let MutationOp::Upsert { blob_digest, .. } = &m.op { + retained_blobs.insert(*blob_digest); + } + } + } for stored in self.changesets.values() { for m in &stored.envelope.mutations { if let MutationOp::Upsert { blob_digest, .. } = &m.op { @@ -1623,6 +1682,7 @@ impl SynapseStore { blob_first_visible_seq: std::mem::take(&mut self.blob_first_visible_seq), github_projections: std::mem::take(&mut self.github_projections), canonical_heads: std::mem::take(&mut self.canonical_heads), + revision_log: self.revisions.log().to_vec(), }; let encoded = codec::encode_checkpoint_v2(&state, v1_state_root, prev_checkpoint_root); self.changesets = state.changesets; @@ -2060,6 +2120,18 @@ impl SynapseStore { cs.lease_expires_at_ms = lease_expires_at_ms; } } + record @ WalRecord::RevisionAdmitted { .. } => { + if let WalRecord::RevisionAdmitted { new_blobs, .. } = &record { + for digest in new_blobs { + self.blob_first_visible_seq.entry(*digest).or_insert(seq); + } + } + for digest in record.upsert_blobs() { + self.blob_first_visible_seq.entry(digest).or_insert(seq); + } + self.revisions.apply(seq, record); + } + record @ WalRecord::ObsolescenceRecorded { .. } => self.revisions.apply(seq, record), } } @@ -2143,6 +2215,7 @@ impl SynapseStore { self.blob_first_visible_seq = s.blob_first_visible_seq; self.github_projections = s.github_projections; self.canonical_heads = s.canonical_heads; + self.revisions = revision::RevisionLedger::from_log(s.revision_log); } /// Admit a replayed (not checkpoint-covered) frame written with `codec`: the codec @@ -2378,10 +2451,10 @@ impl SynapseStore { )); } - // Verify that all blobs referenced by a committed ChangesetIngest exist and match digest - if let WalRecord::ChangesetIngest { ref envelope, .. } = record { - for m in &envelope.mutations { - if let MutationOp::Upsert { blob_digest, .. } = &m.op { + // Verify that all blobs referenced by a committed ingest or revision exist and match digest + for blob_digest in &record.upsert_blobs() { + { + { let bpath = self.blob_path(*blob_digest); let raw = fs::read(&bpath).map_err(|_| { SynapseError::new( @@ -2593,9 +2666,9 @@ impl SynapseStore { Ok((frames, next)) => { for fr in frames { self.admit_replayed_codec(fr.codec, fr.seq)?; - if let WalRecord::ChangesetIngest { envelope, .. } = &fr.record { - for m in &envelope.mutations { - if let MutationOp::Upsert { blob_digest, .. } = &m.op { + { + for blob_digest in &fr.record.upsert_blobs() { + { let inline = fr.inline.iter().any(|(d, _, _)| d == blob_digest); if inline || self.blob_locations.contains_key(blob_digest) { continue; diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs new file mode 100644 index 0000000..982e3c0 --- /dev/null +++ b/crates/synapse-store/src/revision.rs @@ -0,0 +1,604 @@ +//! Revision ledger: envelope v2 revisions, their change identities, admission witnesses, +//! and obsolescence markers (ADR 0003 section 5.1, step B1). See `docs/B1_CHANGE_IDENTITY.md`. +//! +//! The ledger is a pure function of the revision records (`RevisionAdmitted`, +//! `ObsolescenceRecorded`) applied in `WalSeq` order: replay, a checkpoint (which keeps the +//! records themselves), and a live store all rebuild exactly the same ledger. v1 changesets +//! stay in their own map with their own IDs; the two ID domains never meet. + +use crate::WalRecord; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use synapse_core::{ + AdmissionWitness, AuthorshipAttestation, BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, + ChangesetId, IdempotencyKey, MutationOp, ObsolescenceKind, ObsolescenceMarker, RefusalCode, + RepoId, RevisionContent, SynapseError, SynapseResult, WalSeq, +}; + +/// Domain tag of the revision part of the state root (only hashed when revisions exist). +pub const DOMAIN_STATE_ROOT_REVISIONS_V1: &[u8] = b"SYNAPSE_STATE_ROOT_REVISIONS_V1\0"; + +/// The authority an admission was granted under, from the verified delegation chain. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AdmissionAuthority { + /// The request's chain (link digests, root first). + pub chain: ChainPath, + /// `ChangeId`s the chain's leaf grant names explicitly in its change scope. A grant + /// that allows any change names none: it never lets a key join a change outside its + /// creating chain. + pub change_scope: Vec, +} + +/// One admitted revision: its content, every authorship attestation, and every admission +/// witness, in admission order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredRevision { + pub repo_id: RepoId, + pub changeset_id: ChangesetId, + pub content: RevisionContent, + /// Sequence of the first admission. + pub first_seq: WalSeq, + pub attestations: Vec, + pub witnesses: Vec, +} + +/// A recorded obsolescence marker with the chain it was recorded under. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RecordedMarker { + pub seq: WalSeq, + pub marker: ObsolescenceMarker, + pub chain: ChainPath, + pub recorded_at_ms: u64, +} + +/// Status of one change: its creating chain, revisions, and which of them are live. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChangeStatus { + pub repo_id: RepoId, + pub change_id: ChangeId, + /// The chain of the first admission under this `ChangeId`. + pub creating_chain: ChainPath, + /// Every revision, in first-admission order. + pub revisions: Vec, + /// Revisions no marker names as predecessor, in first-admission order. + pub live: Vec, + /// Revisions some marker names as predecessor, in first-admission order. + pub obsolete: Vec, + pub markers: Vec, + /// More than one live revision: divergent attempts (ADR 0003 section 5.1). + pub divergent: bool, +} + +/// Outcome of [`crate::SynapseStore::admit_revision`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RevisionOutcome { + /// A new admission (a new revision, or a new attestation of an existing one) at + /// `wal_seq`. + Admitted { + wal_seq: WalSeq, + changeset_id: ChangesetId, + /// The revision already existed: this admission added an attestation and a witness. + joined_existing_revision: bool, + }, + /// The same repository, signer DID, and `IdempotencyKey` were already admitted with the + /// same revision: the first admission's `WalSeq`. + IdempotentDuplicate { + wal_seq: WalSeq, + changeset_id: ChangesetId, + }, +} + +#[derive(Debug, Clone, Default)] +struct ChangeEntry { + creating_chain: Option, + revisions: Vec, + markers: Vec, +} + +/// In-memory revision state, rebuilt from revision records. +#[derive(Debug, Clone, Default)] +pub(crate) struct RevisionLedger { + /// Every revision record applied, in sequence order (what checkpoints keep). + log: Vec<(WalSeq, WalRecord)>, + revisions: BTreeMap<(RepoId, ChangesetId), StoredRevision>, + changes: BTreeMap<(RepoId, ChangeId), ChangeEntry>, + /// (repository, signer key, idempotency key) to the first admission. + idempotency: BTreeMap<(RepoId, [u8; 32], IdempotencyKey), (WalSeq, ChangesetId)>, +} + +/// Digest of one revision record over its canonical core encodings. +fn record_digest(record: &WalRecord) -> [u8; 32] { + let mut h = Sha256::new(); + h.update([record.kind_byte()]); + let mut chain = Vec::new(); + match record { + WalRecord::RevisionAdmitted { + envelope, + chain: c, + admitted_at_ms, + new_blobs, + } => { + let e = envelope.encode(); + h.update((e.len() as u64).to_le_bytes()); + h.update(&e); + c.encode_into(&mut chain); + h.update(&chain); + h.update(admitted_at_ms.to_le_bytes()); + h.update((new_blobs.len() as u64).to_le_bytes()); + for b in new_blobs { + h.update(b.0); + } + } + WalRecord::ObsolescenceRecorded { + marker, + chain: c, + recorded_at_ms, + } => { + let m = marker.encode(); + h.update((m.len() as u64).to_le_bytes()); + h.update(&m); + c.encode_into(&mut chain); + h.update(&chain); + h.update(recorded_at_ms.to_le_bytes()); + } + _ => {} + } + h.finalize().into() +} + +fn not_found(msg: String) -> SynapseError { + SynapseError::new(RefusalCode::ChangesetNotFound, msg) +} + +impl RevisionLedger { + pub(crate) fn log(&self) -> &[(WalSeq, WalRecord)] { + &self.log + } + + /// Rebuild a ledger from checkpointed records. + pub(crate) fn from_log(log: Vec<(WalSeq, WalRecord)>) -> Self { + let mut l = Self::default(); + for (seq, record) in log { + l.apply(seq, record); + } + l + } + + /// Feed the revision part of the state root (nothing when the ledger is empty, so roots + /// of stores without revisions are unchanged). + pub(crate) fn hash_into(log: &[(WalSeq, WalRecord)], snapshot: WalSeq, h: &mut Sha256) { + let visible: Vec<_> = log.iter().filter(|(s, _)| *s <= snapshot).collect(); + if visible.is_empty() { + return; + } + h.update(DOMAIN_STATE_ROOT_REVISIONS_V1); + h.update((visible.len() as u64).to_le_bytes()); + for (seq, record) in visible { + h.update(seq.0.to_le_bytes()); + h.update(record_digest(record)); + } + } + + /// Apply one revision record (other records are ignored). Total: a record that could + /// not have been admitted is still applied the same way on every replica. + pub(crate) fn apply(&mut self, seq: WalSeq, record: WalRecord) { + match &record { + WalRecord::RevisionAdmitted { + envelope, + chain, + admitted_at_ms, + .. + } => { + let att = &envelope.attestation; + let id = att.changeset_id; + let repo = att.repo_id.clone(); + let witness = + AdmissionWitness::of_attestation(att, chain.clone(), seq, *admitted_at_ms); + let entry = self + .changes + .entry((repo.clone(), envelope.content.change_id)) + .or_default(); + if entry.creating_chain.is_none() { + entry.creating_chain = Some(chain.clone()); + } + if !entry.revisions.contains(&id) { + entry.revisions.push(id); + } + self.idempotency + .entry((repo.clone(), att.author_key, att.idempotency_key)) + .or_insert((seq, id)); + let rev = + self.revisions + .entry((repo.clone(), id)) + .or_insert_with(|| StoredRevision { + repo_id: repo, + changeset_id: id, + content: envelope.content.clone(), + first_seq: seq, + attestations: Vec::new(), + witnesses: Vec::new(), + }); + rev.attestations.push(att.clone()); + rev.witnesses.push(witness); + } + WalRecord::ObsolescenceRecorded { + marker, + chain, + recorded_at_ms, + } => { + self.changes + .entry((marker.repo_id.clone(), marker.change_id)) + .or_default() + .markers + .push(RecordedMarker { + seq, + marker: marker.clone(), + chain: chain.clone(), + recorded_at_ms: *recorded_at_ms, + }); + } + _ => return, + } + self.log.push((seq, record)); + } + + pub(crate) fn get_revision(&self, repo: &RepoId, id: ChangesetId) -> Option<&StoredRevision> { + self.revisions.get(&(repo.clone(), id)) + } + + /// Every revision (for compaction roots). + pub(crate) fn revisions(&self) -> impl Iterator { + self.revisions.values() + } + + pub(crate) fn idempotent( + &self, + repo: &RepoId, + key: &[u8; 32], + idem: IdempotencyKey, + ) -> Option<(WalSeq, ChangesetId)> { + self.idempotency.get(&(repo.clone(), *key, idem)).copied() + } + + /// Join rule (ADR 0003 sections 5.1 and 5.8): a revision under an existing `ChangeId` + /// is admitted only from a chain that descends from the creating chain, or when the + /// leaf grant names the `ChangeId` in its change scope. + pub(crate) fn check_join( + &self, + repo: &RepoId, + change_id: ChangeId, + authority: &AdmissionAuthority, + ) -> SynapseResult<()> { + let Some(creating) = self + .changes + .get(&(repo.clone(), change_id)) + .and_then(|e| e.creating_chain.as_ref()) + else { + return Ok(()); + }; + if authority.chain.descends_from(creating) || authority.change_scope.contains(&change_id) { + return Ok(()); + } + Err(SynapseError::new( + RefusalCode::AuthChangeOutOfScope, + format!( + "change {change_id} belongs to another creating chain and the grant does not name it in its change scope" + ), + )) + } + + /// Checks of an obsolescence marker against the ledger. `Ok(Some(seq))` when the same + /// predecessor and successors are already recorded (the first marker's sequence). + pub(crate) fn plan_marker( + &self, + marker: &ObsolescenceMarker, + chain: &ChainPath, + ) -> SynapseResult> { + marker.validate()?; + let repo = &marker.repo_id; + let entry = self + .changes + .get(&(repo.clone(), marker.change_id)) + .filter(|e| e.creating_chain.is_some()) + .ok_or_else(|| not_found(format!("change {} not found", marker.change_id)))?; + for id in std::iter::once(&marker.predecessor).chain(&marker.successors) { + if !entry.revisions.contains(id) { + return Err(not_found(format!( + "revision {id} is not a revision of change {}", + marker.change_id + ))); + } + } + if let Some(m) = entry.markers.iter().find(|m| { + m.marker.predecessor == marker.predecessor && m.marker.successors == marker.successors + }) { + return Ok(Some(m.seq)); + } + // No cycles: no successor may already lead back to the predecessor. + let mut seen = BTreeSet::new(); + let mut work: Vec = marker.successors.clone(); + while let Some(id) = work.pop() { + if id == marker.predecessor { + return Err(SynapseError::new( + RefusalCode::ObsolescenceMarkerInvalid, + format!("marker would make revision {id} its own successor"), + )); + } + if seen.insert(id) { + for m in entry.markers.iter().filter(|m| m.marker.predecessor == id) { + work.extend(m.marker.successors.iter().copied()); + } + } + } + let creating = entry.creating_chain.as_ref().expect("filtered above"); + let allowed = match marker.kind() { + ObsolescenceKind::Pruned => chain.dominates(creating), + ObsolescenceKind::Rewritten | ObsolescenceKind::Split => { + chain.dominates(creating) + || self + .get_revision(repo, marker.predecessor) + .and_then(|r| r.witnesses.first()) + .is_some_and(|w| chain.dominates(&w.chain)) + } + }; + if !allowed { + return Err(SynapseError::new( + RefusalCode::AuthChainNotDominant, + format!( + "{:?} of revision {} needs a chain that is or dominates the creating chain of change {}", + marker.kind(), + marker.predecessor, + marker.change_id + ), + )); + } + Ok(None) + } + + pub(crate) fn change_status(&self, repo: &RepoId, change_id: ChangeId) -> Option { + let entry = self.changes.get(&(repo.clone(), change_id))?; + let creating_chain = entry.creating_chain.clone()?; + let obsoleted: BTreeSet = + entry.markers.iter().map(|m| m.marker.predecessor).collect(); + let (obsolete, live): (Vec<_>, Vec<_>) = entry + .revisions + .iter() + .copied() + .partition(|id| obsoleted.contains(id)); + Some(ChangeStatus { + repo_id: repo.clone(), + change_id, + creating_chain, + revisions: entry.revisions.clone(), + divergent: live.len() > 1, + live, + obsolete, + markers: entry.markers.clone(), + }) + } +} + +impl crate::SynapseStore { + /// Admit an envelope v2 revision under `authority` at server time `now_ms` (ADR 0003 + /// B1). Checks, in order: the envelope (content rules, attestation names this content, + /// strict signature); idempotency on (repository, signer key, `IdempotencyKey`), where a + /// repeat with the same revision returns the first `WalSeq` and any other revision is + /// `IdempotencyKeyConflict`; the path-count limit; the join rule + /// (`AuthChangeOutOfScope`); parents (an admitted revision or a v1 changeset of the same + /// repository); blobs (provided with the declared digest and size, or already visible). + /// Identical content already admitted gains one more attestation and witness. + pub fn admit_revision( + &mut self, + envelope: ChangesetEnvelopeV2, + blobs: &[(BlobDigest, Vec)], + authority: AdmissionAuthority, + now_ms: u64, + ) -> SynapseResult { + self.check_writable()?; + self.check_binary_codec()?; + let id = envelope.validate()?; + let content = &envelope.content; + let att = &envelope.attestation; + let repo = att.repo_id.clone(); + if let Some((wal_seq, existing)) = + self.revisions + .idempotent(&repo, &att.author_key, att.idempotency_key) + { + if existing == id { + return Ok(RevisionOutcome::IdempotentDuplicate { + wal_seq, + changeset_id: id, + }); + } + return Err(SynapseError::new( + RefusalCode::IdempotencyKeyConflict, + format!( + "idempotency key {} of {} already bound to revision {existing}, cannot rebind to {id}", + att.idempotency_key.to_hex(), + att.author_did() + ), + )); + } + if content.mutations.len() > self.limits.max_paths_per_changeset { + return Err(SynapseError::new( + RefusalCode::QuotaTooManyPaths, + format!( + "revision touches {} paths, exceeding limit {}", + content.mutations.len(), + self.limits.max_paths_per_changeset + ), + )); + } + self.revisions + .check_join(&repo, content.change_id, &authority)?; + for parent in &content.parents { + let parent_repo = if self.revisions.get_revision(&repo, *parent).is_some() { + &repo + } else if let Some(cs) = self.changesets.get(parent) { + &cs.envelope.repo_id + } else { + return Err(SynapseError::new( + RefusalCode::ParentChangesetNotFound, + format!("parent {parent} not found"), + )); + }; + if parent_repo != &repo { + return Err(SynapseError::new( + RefusalCode::AuthCrossRepoDenied, + "parent changeset belongs to a different repository", + )); + } + } + let mut provided: BTreeMap = BTreeMap::new(); + let mut total = 0u64; + for (declared, bytes) in blobs { + let len = bytes.len() as u64; + total = total.saturating_add(len); + if len > self.limits.max_blob_bytes || total > self.limits.max_total_changeset_bytes { + return Err(SynapseError::new( + RefusalCode::QuotaPayloadTooLarge, + "revision blobs exceed max_blob_bytes or max_total_changeset_bytes", + )); + } + let actual = BlobDigest::compute(bytes); + if actual != *declared { + return Err(SynapseError::new( + RefusalCode::BlobDigestMismatch, + format!("declared blob digest {declared} does not match computed {actual}"), + )); + } + provided.insert(*declared, bytes.as_slice()); + } + let mut inline: Vec<(BlobDigest, &[u8])> = Vec::new(); + for m in &content.mutations { + if let MutationOp::Upsert { + blob_digest, + size_bytes, + .. + } = &m.op + { + if let Some(raw) = provided.get(blob_digest) { + if raw.len() as u64 != *size_bytes { + return Err(SynapseError::new( + RefusalCode::BlobDigestMismatch, + format!( + "mutation path {} declared size {size_bytes} but blob is {} bytes", + m.path, + raw.len() + ), + )); + } + if !inline.iter().any(|(d, _)| d == blob_digest) { + inline.push((*blob_digest, raw)); + } + } else if !self.blob_first_visible_seq.contains_key(blob_digest) { + return Err(SynapseError::new( + RefusalCode::BlobNotFound, + format!( + "mutation path {} references missing blob {blob_digest}", + m.path + ), + )); + } + } + } + let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); + let record = WalRecord::RevisionAdmitted { + envelope, + chain: authority.chain, + admitted_at_ms: now_ms, + new_blobs: inline.iter().map(|(d, _)| *d).collect(), + }; + let wal_seq = self.append_revision_record(record, &inline)?; + Ok(RevisionOutcome::Admitted { + wal_seq, + changeset_id: id, + joined_existing_revision, + }) + } + + /// Record an obsolescence marker authorized under `chain` at server time `now_ms`. A + /// prune needs a chain that is or dominates the change's creating chain; a rewrite or a + /// split needs that, or a chain that is or dominates the chain of the predecessor's first + /// admission (`AuthChainNotDominant` otherwise). Predecessor and successors must be + /// revisions of the marker's change (`ChangesetNotFound`); a marker that would close a + /// cycle is `ObsolescenceMarkerInvalid`. The same predecessor and successors recorded + /// again return the first marker's `WalSeq`. + pub fn record_obsolescence( + &mut self, + marker: ObsolescenceMarker, + chain: ChainPath, + now_ms: u64, + ) -> SynapseResult { + self.check_writable()?; + self.check_binary_codec()?; + if let Some(seq) = self.revisions.plan_marker(&marker, &chain)? { + return Ok(seq); + } + let record = WalRecord::ObsolescenceRecorded { + marker, + chain, + recorded_at_ms: now_ms, + }; + self.append_revision_record(record, &[]) + } + + /// An admitted revision of `repo_id`. + pub fn get_revision( + &self, + repo_id: &RepoId, + changeset_id: ChangesetId, + ) -> SynapseResult { + self.revisions + .get_revision(repo_id, changeset_id) + .cloned() + .ok_or_else(|| not_found(format!("revision {changeset_id} not found"))) + } + + /// Creating chain, revisions, live and obsolete revisions, and divergence of a change. + pub fn change_status( + &self, + repo_id: &RepoId, + change_id: ChangeId, + ) -> SynapseResult { + self.revisions + .change_status(repo_id, change_id) + .ok_or_else(|| not_found(format!("change {change_id} not found"))) + } + + fn check_binary_codec(&self) -> SynapseResult<()> { + if self.codec == crate::RecordCodec::JsonV1 { + return Err(SynapseError::new( + RefusalCode::EnvelopeVersionUnsupported, + "this store still writes v1 JSON records: envelope v2 needs the binary codec (run the migration checkpoint first)", + )); + } + Ok(()) + } + + /// Append one revision record (blobs inline in the segment store, blob files first in + /// the `wal.log` layout) and apply it. + fn append_revision_record( + &mut self, + record: WalRecord, + blobs: &[(BlobDigest, &[u8])], + ) -> SynapseResult { + if self.v2_mode { + let encoded = crate::wal2::encode_record(&record, blobs, self.codec)?; + self.check_frame_cap(encoded.payload.len())?; + let mut ticket = self.v2_begin()?; + let result = Self::v2_write(&mut ticket, &[&encoded]); + let placed = self.v2_finish(ticket, result)?; + let seq = placed[0].seq; + self.apply_v2_ingest(&placed[0], record, &encoded.inline); + return Ok(seq); + } + let payload = self.encode_v1_payload(&record)?; + for (digest, bytes) in blobs { + self.write_blob_file(*digest, bytes)?; + } + let (seq, _, _) = self.append_v1_payload(record.kind_byte(), &payload)?; + self.apply_record(seq, record); + Ok(seq) + } +} diff --git a/crates/synapse-store/tests/a1_malformed_corpus.rs b/crates/synapse-store/tests/a1_malformed_corpus.rs index 4192410..f271f2a 100644 --- a/crates/synapse-store/tests/a1_malformed_corpus.rs +++ b/crates/synapse-store/tests/a1_malformed_corpus.rs @@ -156,6 +156,8 @@ fn length_fields(record: &WalRecord, bin: &[u8]) -> Vec { // repo_id length first. WalRecord::GitProjected { .. } | WalRecord::CanonicalPromoted { .. } => vec![2], WalRecord::LeaseUpdated { .. } => vec![], + // Embedded envelope v2 or marker length first (ADR 0003 B1). + WalRecord::RevisionAdmitted { .. } | WalRecord::ObsolescenceRecorded { .. } => vec![2], } } diff --git a/crates/synapse-store/tests/b1_change_identity.rs b/crates/synapse-store/tests/b1_change_identity.rs new file mode 100644 index 0000000..65f8813 --- /dev/null +++ b/crates/synapse-store/tests/b1_change_identity.rs @@ -0,0 +1,585 @@ +//! ADR 0003 step B1 acceptance tests (issue #27): change identity bound to its creating +//! chain, admission witnesses, obsolescence markers, envelope v2 with a native base, and v1 +//! identities unchanged. Chains here are plain link-digest paths; `synapse-api` tests the +//! same rules with real signed F1 capability chains. + +use ed25519_dalek::SigningKey; +use std::path::{Path, PathBuf}; +use synapse_core::{ + encode_did_key_ed25519, BlobDigest, ChainPath, ChangeId, ChangesetEnvelope, + ChangesetEnvelopeV2, ChangesetId, FileMode, GitOid, IdempotencyKey, MutationOp, + ObsolescenceMarker, PathMutation, RefusalCode, RepoId, RevisionContent, TreeDigest, WalSeq, +}; +use synapse_store::codec::{decode_record, encode_record}; +use synapse_store::{ + AdmissionAuthority, FsyncPolicy, IngestOutcome, RecordCodec, RecoveryPolicy, RevisionOutcome, + StoreLimits, SynapseStore, WalRecord, +}; + +const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; +const CHANGE: ChangeId = ChangeId([0xC1; 16]); + +fn temp_dir(name: &str) -> PathBuf { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("synapse-b1-{name}-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn limits() -> StoreLimits { + StoreLimits { + wal_prealloc_bytes: 64 * 1024, + ..Default::default() + } +} + +fn open(dir: &Path, policy: FsyncPolicy) -> SynapseStore { + SynapseStore::open(dir, policy, STRICT, limits()).unwrap() +} + +fn repo() -> RepoId { + RepoId::new("aien-spark/synapse").unwrap() +} + +/// The delegation tree of these tests: root authority `R`, orchestrator `O` under it, +/// workers `W1` and `W2` under `O`, and an outsider `X` under `R` beside `O`. +struct Chains { + r: ChainPath, + o: ChainPath, + w1: ChainPath, + w2: ChainPath, + x: ChainPath, +} + +fn chains() -> Chains { + let p = |v: &[u8]| ChainPath::new(v.iter().map(|b| [*b; 32]).collect()).unwrap(); + Chains { + r: p(&[1]), + o: p(&[1, 2]), + w1: p(&[1, 2, 3]), + w2: p(&[1, 2, 4]), + x: p(&[1, 9]), + } +} + +fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) +} + +fn auth(chain: &ChainPath) -> AdmissionAuthority { + AdmissionAuthority { + chain: chain.clone(), + change_scope: Vec::new(), + } +} + +/// A revision of `CHANGE` writing `body` to `src/lib.rs`, with its blob. +fn revision( + author: &SigningKey, + body: &[u8], + idem: u8, + parents: Vec, +) -> (ChangesetEnvelopeV2, Vec<(BlobDigest, Vec)>) { + let digest = BlobDigest::compute(body); + let content = RevisionContent { + change_id: CHANGE, + base_tree: TreeDigest([0x7E; 32]), + parents, + mutations: vec![PathMutation { + path: "src/lib.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: digest, + size_bytes: body.len() as u64, + }, + }], + intent_summary: "implement the task".into(), + }; + let env = + ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey([idem; 32]), 1_000); + (env, vec![(digest, body.to_vec())]) +} + +fn admitted(outcome: RevisionOutcome) -> (WalSeq, ChangesetId) { + match outcome { + RevisionOutcome::Admitted { + wal_seq, + changeset_id, + .. + } => (wal_seq, changeset_id), + other => panic!("expected an admission, got {other:?}"), + } +} + +fn admit( + s: &mut SynapseStore, + author: &SigningKey, + chain: &ChainPath, + body: &[u8], + idem: u8, +) -> ChangesetId { + let (env, blobs) = revision(author, body, idem, vec![]); + admitted(s.admit_revision(env, &blobs, auth(chain), 5_000).unwrap()).1 +} + +fn marker(signer: &SigningKey, pred: ChangesetId, succ: Vec) -> ObsolescenceMarker { + ObsolescenceMarker::sign_new(signer, repo(), CHANGE, pred, succ, 6_000) +} + +#[test] +fn b1_rewrite_keeps_change_id_and_gets_new_changeset_id() { + let c = chains(); + let dir = temp_dir("rewrite"); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + let a = admit(&mut s, &key(2), &c.o, b"fn a() {}", 1); + let a2 = admit(&mut s, &key(2), &c.o, b"fn a() { /* rewritten */ }", 2); + assert_ne!(a, a2, "a rewrite gets a new ChangesetId"); + let rev = s.get_revision(&repo(), a2).unwrap(); + assert_eq!(rev.content.change_id, CHANGE, "and keeps its ChangeId"); + assert_eq!( + s.get_revision(&repo(), a).unwrap().content.change_id, + CHANGE + ); + s.record_obsolescence(marker(&key(2), a, vec![a2]), c.o.clone(), 6_000) + .unwrap(); + let st = s.change_status(&repo(), CHANGE).unwrap(); + assert_eq!(st.revisions, vec![a, a2]); + assert_eq!(st.live, vec![a2]); + assert_eq!(st.obsolete, vec![a]); + assert!(!st.divergent); + assert_eq!(st.creating_chain, c.o); +} + +#[test] +fn b1_divergence_two_live_successors_is_detected() { + let c = chains(); + let dir = temp_dir("diverge"); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + let a = admit(&mut s, &key(2), &c.o, b"attempt 0", 1); + let b1 = admit(&mut s, &key(3), &c.w1, b"attempt 1", 1); + let b2 = admit(&mut s, &key(4), &c.w2, b"attempt 2", 1); + s.record_obsolescence(marker(&key(2), a, vec![b1]), c.o.clone(), 6_000) + .unwrap(); + s.record_obsolescence(marker(&key(2), a, vec![b2]), c.o.clone(), 6_001) + .unwrap(); + let st = s.change_status(&repo(), CHANGE).unwrap(); + assert_eq!(st.obsolete, vec![a]); + assert_eq!( + st.live, + vec![b1, b2], + "two live successors of one predecessor" + ); + assert!(st.divergent, "divergence is detected"); + // Selecting one attempt prunes the other: no longer divergent. + s.record_obsolescence(marker(&key(2), b2, vec![]), c.o.clone(), 6_002) + .unwrap(); + let st = s.change_status(&repo(), CHANGE).unwrap(); + assert_eq!(st.live, vec![b1]); + assert!(!st.divergent); + // Divergence survives a reopen (replay) unchanged. + drop(s); + let s = open(&dir, FsyncPolicy::EveryCommit); + assert_eq!(s.change_status(&repo(), CHANGE).unwrap(), st); +} + +fn identical_content_case(policy: FsyncPolicy, name: &str) { + let c = chains(); + let dir = temp_dir(name); + let mut s = open(&dir, policy); + let (env_o, blobs) = revision(&key(2), b"same bytes", 1, vec![]); + let (env_w, _) = revision(&key(3), b"same bytes", 7, vec![]); + let (s1, id) = admitted(s.admit_revision(env_o, &blobs, auth(&c.o), 5_000).unwrap()); + // The second agent provides no blob: it is already visible. + let out = s.admit_revision(env_w, &[], auth(&c.w1), 5_001).unwrap(); + let RevisionOutcome::Admitted { + wal_seq: s2, + changeset_id: id2, + joined_existing_revision: true, + } = out + else { + panic!("expected a join of the existing revision, got {out:?}"); + }; + assert_eq!(id, id2, "identical content is one revision"); + let rev = s.get_revision(&repo(), id).unwrap(); + assert_eq!(rev.attestations.len(), 2, "two attestations"); + assert_eq!(rev.witnesses.len(), 2, "two admission witnesses"); + assert_eq!( + rev.attestations[0].author_key, + key(2).verifying_key().to_bytes() + ); + assert_eq!( + rev.attestations[1].author_key, + key(3).verifying_key().to_bytes() + ); + assert_eq!( + ( + rev.witnesses[0].admission_seq, + rev.witnesses[1].admission_seq + ), + (s1, s2) + ); + assert_eq!( + ( + rev.witnesses[0].chain.clone(), + rev.witnesses[1].chain.clone() + ), + (c.o.clone(), c.w1) + ); + assert_eq!( + rev.witnesses[1].admitted_at_ms, 5_001, + "server time, not the agent's" + ); + assert_ne!(rev.witnesses[0].digest(), rev.witnesses[1].digest()); + assert_eq!( + s.change_status(&repo(), CHANGE).unwrap().revisions, + vec![id] + ); + let root = s.state_root_digest(None).unwrap(); + // Replay, then a checkpoint, then a reopen from the checkpoint rebuild the same ledger. + drop(s); + let mut s = open(&dir, policy); + assert_eq!(s.get_revision(&repo(), id).unwrap(), rev); + assert_eq!(s.state_root_digest(None).unwrap(), root); + s.checkpoint_and_compact(9_000).unwrap(); + drop(s); + let s = open(&dir, policy); + assert_eq!(s.get_revision(&repo(), id).unwrap(), rev); + assert_eq!(s.state_root_digest(None).unwrap(), root); + assert_eq!( + s.get_blob_visible(BlobDigest::compute(b"same bytes"), None, None) + .unwrap(), + b"same bytes" + ); +} + +#[test] +fn b1_identical_content_two_agents_one_chain_one_change_is_one_revision_two_attestations_two_witnesses( +) { + identical_content_case(FsyncPolicy::EveryCommit, "identical-wal-log"); + identical_content_case(FsyncPolicy::GROUP_COMMIT_DEFAULT, "identical-segments"); +} + +#[test] +fn b1_join_from_key_outside_creating_chain_without_change_scope_is_refused() { + let c = chains(); + let dir = temp_dir("join"); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + admit(&mut s, &key(2), &c.o, b"created by the orchestrator", 1); + let before = s.committed_seq(); + let (env, blobs) = revision(&key(9), b"outsider attempt", 1, vec![]); + let err = s + .admit_revision(env.clone(), &blobs, auth(&c.x), 5_000) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::AuthChangeOutOfScope); + // A scope naming another change, or the root's parent chain, is not enough either. + let other = AdmissionAuthority { + chain: c.x.clone(), + change_scope: vec![ChangeId([0xEE; 16])], + }; + assert_eq!( + s.admit_revision(env.clone(), &blobs, other, 5_000) + .unwrap_err() + .code, + RefusalCode::AuthChangeOutOfScope + ); + assert_eq!( + s.admit_revision(env.clone(), &blobs, auth(&c.r), 5_000) + .unwrap_err() + .code, + RefusalCode::AuthChangeOutOfScope, + "an ancestor chain does not descend from the creating chain" + ); + assert_eq!(s.committed_seq(), before, "nothing written on refusal"); + // The same key with a grant naming the change in its change scope may join. + let scoped = AdmissionAuthority { + chain: c.x.clone(), + change_scope: vec![CHANGE], + }; + admitted(s.admit_revision(env, &blobs, scoped, 5_000).unwrap()); + // A worker whose chain descends from the creating chain joins without any scope. + admit(&mut s, &key(3), &c.w1, b"worker attempt", 1); +} + +#[test] +fn b1_prune_by_chain_not_dominating_creating_chain_is_refused() { + let c = chains(); + let dir = temp_dir("prune"); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + let a = admit(&mut s, &key(2), &c.o, b"orchestrator attempt", 1); + let b = admit(&mut s, &key(3), &c.w1, b"worker attempt", 1); + let before = s.committed_seq(); + for (signer, chain) in [(key(3), &c.w1), (key(9), &c.x), (key(4), &c.w2)] { + let err = s + .record_obsolescence(marker(&signer, a, vec![]), chain.clone(), 6_000) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::AuthChainNotDominant, "{chain:?}"); + } + assert_eq!(s.committed_seq(), before, "nothing written on refusal"); + // A worker may rewrite its own attempt (it dominates that revision's first admission) + // but not prune it, and not rewrite the orchestrator's. + let b2 = admit(&mut s, &key(3), &c.w1, b"worker attempt, rewritten", 2); + s.record_obsolescence(marker(&key(3), b, vec![b2]), c.w1.clone(), 6_000) + .unwrap(); + assert_eq!( + s.record_obsolescence(marker(&key(3), b2, vec![]), c.w1.clone(), 6_000) + .unwrap_err() + .code, + RefusalCode::AuthChainNotDominant + ); + assert_eq!( + s.record_obsolescence(marker(&key(3), a, vec![b2]), c.w1.clone(), 6_000) + .unwrap_err() + .code, + RefusalCode::AuthChainNotDominant + ); + // The creating chain and a chain that dominates it may prune. + s.record_obsolescence(marker(&key(2), b2, vec![]), c.o.clone(), 6_001) + .unwrap(); + s.record_obsolescence(marker(&key(1), a, vec![]), c.r.clone(), 6_002) + .unwrap(); + let st = s.change_status(&repo(), CHANGE).unwrap(); + assert!(st.live.is_empty()); + // Markers that would close a cycle are refused. + assert_eq!( + s.record_obsolescence(marker(&key(2), b2, vec![b]), c.o.clone(), 6_003) + .unwrap_err() + .code, + RefusalCode::ObsolescenceMarkerInvalid + ); +} + +#[test] +fn b1_repeat_same_repo_did_idempotency_key_returns_first_wal_seq() { + let c = chains(); + let dir = temp_dir("idem"); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + let (env, blobs) = revision(&key(2), b"first", 5, vec![]); + let (first, id) = admitted( + s.admit_revision(env.clone(), &blobs, auth(&c.o), 5_000) + .unwrap(), + ); + admit(&mut s, &key(3), &c.w1, b"something else", 1); + let dup = RevisionOutcome::IdempotentDuplicate { + wal_seq: first, + changeset_id: id, + }; + let before = s.committed_seq(); + assert_eq!( + s.admit_revision(env.clone(), &blobs, auth(&c.o), 7_000) + .unwrap(), + dup + ); + assert_eq!(s.committed_seq(), before, "a repeat writes nothing"); + // The same key bound to other content is a conflict. + let (other, other_blobs) = revision(&key(2), b"second", 5, vec![]); + assert_eq!( + s.admit_revision(other, &other_blobs, auth(&c.o), 7_000) + .unwrap_err() + .code, + RefusalCode::IdempotencyKeyConflict + ); + // Another DID with the same key and content is its own admission. + let (env_w, _) = revision(&key(3), b"first", 5, vec![]); + let (seq_w, id_w) = admitted(s.admit_revision(env_w, &[], auth(&c.w1), 7_000).unwrap()); + assert_eq!(id_w, id); + assert_ne!(seq_w, first); + // Still the first WalSeq after replay and after a checkpoint. + drop(s); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + assert_eq!( + s.admit_revision(env.clone(), &blobs, auth(&c.o), 8_000) + .unwrap(), + dup + ); + s.checkpoint_and_compact(9_000).unwrap(); + drop(s); + let mut s = open(&dir, FsyncPolicy::EveryCommit); + assert_eq!( + s.admit_revision(env, &blobs, auth(&c.o), 9_000).unwrap(), + dup + ); +} + +fn fixture(name: &str) -> PathBuf { + let src = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/a1-v1") + .join(name); + let dst = temp_dir(&format!("v1-{name}")); + copy_tree(&src, &dst); + let _ = std::fs::remove_file(dst.join("EXPECT")); + dst +} + +fn copy_tree(src: &Path, dst: &Path) { + std::fs::create_dir_all(dst).unwrap(); + for e in std::fs::read_dir(src).unwrap() { + let e = e.unwrap(); + let to = dst.join(e.file_name()); + if e.file_type().unwrap().is_dir() { + copy_tree(&e.path(), &to); + } else { + std::fs::copy(e.path(), &to).unwrap(); + } + } +} + +/// Every v1 changeset of `s` resolves to its record, whose envelope still hashes to it. +fn assert_v1_ids_resolve(s: &SynapseStore, ids: &[ChangesetId]) { + for id in ids { + let cs = s.get_changeset(*id, None, None).unwrap(); + assert_eq!(cs.changeset_id, *id); + assert_eq!(cs.envelope.compute_id(), *id, "v1 identity unchanged"); + } +} + +fn v1_case(name: &str, policy: FsyncPolicy) { + let c = chains(); + let dir = fixture(name); + let mut s = open(&dir, policy); + assert_eq!(s.record_codec(), RecordCodec::JsonV1); + let ids: Vec = s + .list_changesets(None, None, None) + .unwrap() + .iter() + .map(|cs| cs.changeset_id) + .collect(); + assert!(!ids.is_empty(), "{name}: the fixture holds v1 changesets"); + assert_v1_ids_resolve(&s, &ids); + // Envelope v2 needs the binary codec: refused before the migration checkpoint. + let (env, blobs) = revision(&key(2), b"v2 on v1 history", 1, vec![ids[0]]); + assert_eq!( + s.admit_revision(env.clone(), &blobs, auth(&c.o), 0) + .unwrap_err() + .code, + RefusalCode::EnvelopeVersionUnsupported + ); + s.checkpoint_and_compact(0).unwrap(); + assert_v1_ids_resolve(&s, &ids); + // A v2 revision on top of a v1 parent; its id is in its own domain. + let (_, v2) = admitted(s.admit_revision(env, &blobs, auth(&c.o), 0).unwrap()); + assert!(!ids.contains(&v2)); + assert!( + s.get_changeset(v2, None, None).is_err(), + "v2 ids are not v1 records" + ); + assert_v1_ids_resolve(&s, &ids); + drop(s); + let mut s = open(&dir, policy); + assert_v1_ids_resolve(&s, &ids); + // Compaction keeps the v1 parent of a revision even outside the retention window. + s.checkpoint_and_compact(u64::MAX).unwrap(); + drop(s); + let s = open(&dir, policy); + assert_v1_ids_resolve(&s, &[ids[0]]); + assert_eq!( + s.get_revision(&repo(), v2).unwrap().content.parents, + vec![ids[0]] + ); +} + +/// A v1 changeset far outside the retention window, with no other root, stays because a +/// revision names it as parent; without that root compaction evicts it. +fn v1_parent_outside_retention_case(policy: FsyncPolicy, name: &str) { + let c = chains(); + let dir = temp_dir(name); + let mut s = open(&dir, policy); + let author = key(2); + let mut v1 = |body: &[u8], idem: u8| { + let mut env = ChangesetEnvelope { + version: 1, + repo_id: repo(), + base_git_oid: GitOid([0x0B; 20]), + parent_changesets: vec![], + author_did: encode_did_key_ed25519(&author.verifying_key().to_bytes()), + idempotency_key: IdempotencyKey([idem; 32]), + created_at_ms: 1, + intent_summary: "v1 work".into(), + mutations: vec![PathMutation { + path: "src/v1.rs".into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(body), + size_bytes: body.len() as u64, + }, + }], + evidence_receipts: vec![], + signature: vec![], + }; + env.sign(&author); + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + match s.ingest_changeset(env, &blobs).unwrap() { + IngestOutcome::Committed { changeset_id, .. } => changeset_id, + other => panic!("{other:?}"), + } + }; + let named = v1(b"named by a revision", 1); + let unnamed = v1(b"named by nothing", 2); + let (env, blobs) = revision(&key(2), b"on v1", 1, vec![named]); + admitted(s.admit_revision(env, &blobs, auth(&c.o), 0).unwrap()); + s.checkpoint_and_compact(u64::MAX).unwrap(); + assert!( + s.get_changeset(unnamed, None, None).is_err(), + "control: evicted" + ); + assert_v1_ids_resolve(&s, &[named]); + drop(s); + let s = open(&dir, policy); + assert_v1_ids_resolve(&s, &[named]); + assert_eq!( + s.get_blob_visible(BlobDigest::compute(b"named by a revision"), None, None) + .unwrap(), + b"named by a revision" + ); +} + +#[test] +fn b1_every_v1_changeset_id_still_resolves_to_its_record() { + v1_parent_outside_retention_case(FsyncPolicy::EveryCommit, "v1-parent-wal-log"); + v1_parent_outside_retention_case(FsyncPolicy::GROUP_COMMIT_DEFAULT, "v1-parent-segments"); + v1_case("v1-wal-log", FsyncPolicy::EveryCommit); + v1_case("v1-wal-v2-log", FsyncPolicy::GROUP_COMMIT_DEFAULT); +} + +#[test] +fn b1_revision_records_round_trip_and_malformed_bytes_are_refused_typed() { + let c = chains(); + let (env, _) = revision(&key(2), b"x", 1, vec![]); + let records = [ + WalRecord::RevisionAdmitted { + envelope: env.clone(), + chain: c.w1.clone(), + admitted_at_ms: 5, + new_blobs: vec![BlobDigest::compute(b"x")], + }, + WalRecord::ObsolescenceRecorded { + marker: marker(&key(2), env.changeset_id(), vec![ChangesetId([3; 32])]), + chain: c.o.clone(), + recorded_at_ms: 6, + }, + ]; + for record in records { + let bytes = encode_record(&record).unwrap(); + assert_eq!(decode_record(&bytes, 1 << 20).unwrap(), record); + for cut in 0..bytes.len() { + assert!(decode_record(&bytes[..cut], 1 << 20).is_err(), "cut {cut}"); + } + let mut longer = bytes.clone(); + longer.push(0); + assert!(decode_record(&longer, 1 << 20).is_err()); + // Flip each byte of the embedded value: refused or decodes to a different record, + // never a panic. + for i in 2..bytes.len() { + let mut b = bytes.clone(); + b[i] ^= 0x41; + if let Ok(r) = decode_record(&b, 1 << 20) { + assert_ne!(r, record); + } + } + // No v1 JSON form. + assert!(serde_json::to_vec(&record).is_err()); + } +} diff --git a/docs/B1_CHANGE_IDENTITY.md b/docs/B1_CHANGE_IDENTITY.md new file mode 100644 index 0000000..ff25ea6 --- /dev/null +++ b/docs/B1_CHANGE_IDENTITY.md @@ -0,0 +1,68 @@ +# B1: Change Identity, Admission Witnesses, Obsolescence Markers, Envelope v2 + +ADR 0003 section 9 step B1 (issue aien-spark/synapse#27). Sections 5.1 ("Identity"), 5.3 (rewrites and markers) and 5.8 (change scope): a `ChangeId` names one unit of intended work across all its rewrites and retries and is bound to its **creating chain**; a revision's `ChangesetId` covers its content only; every admission leaves an immutable `AdmissionWitness`; obsolescence markers record which revision replaced which. + +Code: `crates/synapse-core/src/revision.rs` (types and codecs), `crates/synapse-store/src/revision.rs` (ledger, admission, markers), `crates/synapse-store/src/{lib,codec}.rs` (WAL kinds 7 and 8, replay, checkpoint, compaction), `crates/synapse-api/src/lib.rs` (`submit_revision`, `record_obsolescence`). Tests: `crates/synapse-store/tests/b1_change_identity.rs`, `crates/synapse-api/tests/b1_chained_revisions.rs`, unit tests in `crates/synapse-core/src/revision.rs`. Evidence: `evidence/b1-change-identity/`. + +## 1. Model and invariants + +* **Revision content and identity.** `RevisionContent` = `ChangeId`, native base `TreeDigest` (C1), parents (strictly ascending), mutations (non-empty, strictly ascending valid paths), intent summary (1..=4096 bytes). Its v2 `ChangesetId` is `SHA-256("SYNAPSE_CHANGESET_V2\0" || u64 len || content)`. Author, time, repository and idempotency key are excluded, so a rewrite (new content, same `ChangeId`) gets a new `ChangesetId` and identical content from two agents is one revision. +* **Envelope v2** = content + one `AuthorshipAttestation`: repository, `ChangesetId`, author key, `IdempotencyKey`, the agent's time, Ed25519 signature (strict) under `SYNAPSE_AUTHORSHIP_SIGN_V2\0`. The attestation must name the content's ID. +* **v1 is unchanged.** `ChangesetEnvelope` keeps its encoding, signature and ID (`SYNAPSE_CHANGESET_V1\0` domain), so v1 and v2 IDs never collide. v1 records stay in their own map; `get_changeset` resolves only v1 IDs and `get_revision` only v2 IDs. +* **Chains and dominance.** A `ChainPath` is the F1 link digests of a chain, root first (1..=16). Chain A dominates chain B when A is B or a prefix of it; B then descends from A. +* **Admission witness.** Every admission records (repository, `ChangesetId`, signer key and signature, `IdempotencyKey`, admission `WalSeq` = the frame's sequence, server time, chain). The first admission under a `(repository, ChangeId)` fixes the creating chain. +* **Join rule.** A revision under an existing `ChangeId` is admitted only from a chain that descends from the creating chain, or when the leaf grant names that `ChangeId` in its change scope. A grant for any change (`ChangeScope::any`) names none. Otherwise `AuthChangeOutOfScope`. +* **Markers.** `ObsolescenceMarker` (predecessor, successors strictly ascending, at most 256, never the predecessor; signed under `SYNAPSE_OBSOLESCENCE_SIGN_V1\0`): zero successors = pruned, one = rewritten, several = split. A prune needs a chain that is or dominates the creating chain. A rewrite or split needs that, or a chain that is or dominates the chain of the predecessor's first admission (a worker may rewrite its own attempt but not prune it). Otherwise `AuthChainNotDominant`. Predecessor and successors must be revisions of the marker's change (`ChangesetNotFound`); a marker that would close a cycle is `ObsolescenceMarkerInvalid`. Several markers per predecessor are allowed: that is how divergence arises. +* **Live and divergent.** A revision is live while no marker names it as predecessor. More than one live revision of one change is divergence (`ChangeStatus::divergent`). +* **Idempotency** is keyed on (repository, signer key, `IdempotencyKey`): a repeat with the same revision returns the first `WalSeq` and writes nothing; another revision under the same key is `IdempotencyKeyConflict`. Another DID with the same key is its own admission. + +## 2. Operations + +| Operation | Store | API (F1 chained request, `Propose`) | +|---|---|---| +| Admit | `admit_revision(envelope, blobs, AdmissionAuthority, now_ms)` | `submit_revision(req, blobs, now_ms)`: payload = envelope bytes; `scope.join_change` = its `ChangeId`; `scope.paths` = exactly its mutation paths (so F1 enforces change and path scope); attestation author = request agent; base tree registered or held by the tree store (`BaseTreeNotFound`) | +| Mark | `record_obsolescence(marker, chain, now_ms)` | `record_obsolescence(req, now_ms)`: payload = marker bytes; `scope.join_change` = its `ChangeId`; signer = request agent | +| Read | `get_revision(repo, id)`, `change_status(repo, change_id)` | through `store()` | + +Admission check order: envelope (content rules, attestation names the content, signature), idempotency, path-count limit, join rule, parents (an admitted revision, or a v1 changeset, of the same repository), blobs (provided with digest and size, or already visible). Nothing is written on a refusal. A store still writing v1 JSON records refuses both writes with `EnvelopeVersionUnsupported` until its migration checkpoint. + +## 3. Canonical binary layout (principle P5) + +All integers little-endian; `str` = `u32 len | UTF-8`; every length checked against the bytes that remain before allocation; trailing bytes refused. Core decoders refuse with `EnvelopeMalformed` (`EnvelopeVersionUnsupported` for a content version other than 2). + +* Content: `version u16 = 2 | change_id [16] | base_tree [32] | u32 n | parent [32]*n | u32 m | (path str | op)*m | intent str`; `op` = `1 | mode u8 | blob_digest [32] | size u64` or `2`. +* Attestation: `repo str | changeset_id [32] | author_key [32] | idempotency_key [32] | attested_at_ms u64 | signature [64]` (signed bytes = domain tag + all but the signature). +* Envelope v2: `u32 content_len | content | attestation`. +* Chain path: `count u8 (1..=16) | digest [32]*`. +* Witness: `repo str | changeset_id [32] | 1 | author_key [32] | signature [64] | idempotency_key [32] | admission_seq u64 | admitted_at_ms u64 | chain`; tag 2 is reserved for the server-derived signer of B5. Digest = `SHA-256("SYNAPSE_ADMISSION_WITNESS_V1\0" || encoding)`. +* Marker: `repo str | change_id [16] | predecessor [32] | u32 n (<= 256) | successor [32]*n | signer_key [32] | signed_at_ms u64 | signature [64]`. +* WAL kind 7 `RevisionAdmitted`: `u32 len | envelope v2 | u32 len | chain | admitted_at_ms u64 | u32 n | new_blob [32]*n`. Kind 8 `ObsolescenceRecorded`: `u32 len | marker | u32 len | chain | recorded_at_ms u64`. Both are binary only (no v1 JSON form); an embedded value refused by its core decoder is `CodecRefusal::EmbeddedMalformed`. In the segment store a revision's new blobs are stored inline as for v1 ingests; in the `wal.log` layout they are blob files written before the frame. +* Checkpoint v2 content: after the canonical-head section, a revision section `u32 n (>= 1) | (seq u64 | u32 len | kind 7 or 8 record)*n`, sequences strictly ascending and at most the checkpoint sequence. It is written only when revision records exist (an empty present section is refused as not canonical), so checkpoints of stores without revisions keep their exact bytes. +* State root: when revision records are visible at the snapshot, the v1 root hash continues with `"SYNAPSE_STATE_ROOT_REVISIONS_V1\0" | u64 count | (seq u64 | record digest [32])*`; with none, every existing root is unchanged. + +The ledger is a pure function of the kind 7 and 8 records in sequence order, so replay, a checkpoint (which keeps the records) and a live store rebuild the same state. Compaction keeps every revision record, every blob a revision references, and every v1 changeset a revision names as parent (no sweep before K1). + +## 4. Acceptance + +| Acceptance (issue #27) | Test | +|---|---| +| A rewrite keeps `ChangeId` and gets a new `ChangesetId` | `b1_rewrite_keeps_change_id_and_gets_new_changeset_id` | +| Divergence (two live successors) is detected | `b1_divergence_two_live_successors_is_detected` | +| Identical content from two agents of one chain under one `ChangeId` yields one revision with two attestations and two admission witnesses | `b1_identical_content_two_agents_one_chain_one_change_is_one_revision_two_attestations_two_witnesses` (wal.log and segment stores, through replay and a checkpoint) | +| A join from a key outside the creating chain without change scope is refused | `b1_join_from_key_outside_creating_chain_without_change_scope_is_refused` | +| A prune by a chain that does not dominate the creating chain is refused | `b1_prune_by_chain_not_dominating_creating_chain_is_refused` | +| A repeat with the same repository, DID, and `IdempotencyKey` returns the first `WalSeq` | `b1_repeat_same_repo_did_idempotency_key_returns_first_wal_seq` (also after replay and a checkpoint) | +| Every v1 `ChangesetId` still resolves to its record | `b1_every_v1_changeset_id_still_resolves_to_its_record` (both v1 fixtures through the migration checkpoint and reopen; a v1 parent outside retention kept by the revision naming it) | + +Also: `b1_revision_records_round_trip_and_malformed_bytes_are_refused_typed`, the core unit tests (`b1_v2_changeset_id_covers_content_only_not_author_or_time`, codec and signature tests), and the API tests with real signed F1 chains (`b1_api_*`). + +Red before green: each acceptance test was run against the B1 commit with one mutation that removes the behaviour it proves (`evidence/b1-change-identity/red-green/red.txt`), and fails; `green.txt` holds the passing runs. + +## 5. Limits and deviations + +* `IntentRecord` (B3), footprints, conflict terms (D2), `DerivationAttestation` and the server-derived witness signer (B5), revision states and visibility (`Private`, `Draft`, ...) are not part of B1. Envelope v2 carries the intent summary of v1; B3 and D2 extend the content under a new content version. +* Envelope v2 has no `evidence_receipts` field: receipts bind to a `TreeDigest` in E1. +* Revision reads are not snapshot-bounded (`min_visible_seq`, `snapshot_seq`) yet; `change_status` reflects the latest state. +* The group-commit `SharedStore` path does not batch revision admissions: they are written one frame at a time through the store. +* Markers are authorized by chain dominance only; the `Undo` capability of B2 is separate. +* No performance figures: B1 has no hot-path acceptance, and none were measured. diff --git a/evidence/b1-change-identity/SHA256SUMS b/evidence/b1-change-identity/SHA256SUMS new file mode 100644 index 0000000..2f83110 --- /dev/null +++ b/evidence/b1-change-identity/SHA256SUMS @@ -0,0 +1,2 @@ +c65bbaa60c5d9330e47fea57c5a7dcdd441ef7e6d8f9fdceca1f2f311f009897 red-green/green.txt +f299d01a54a9d5b0eab89b481a78e0ee98f830438986182540552fc301ec923a red-green/red.txt diff --git a/evidence/b1-change-identity/red-green/green.txt b/evidence/b1-change-identity/red-green/green.txt new file mode 100644 index 0000000..623fb65 --- /dev/null +++ b/evidence/b1-change-identity/red-green/green.txt @@ -0,0 +1,25 @@ +# Green (2026-10-16, B1 commit b928eb9 on C1 + A2; workspace 295 passed, 0 failed; clippy -D warnings and fmt clean) + +# Command: cargo test --locked -p synapse-core --lib b1_ -- --test-threads=1 +test revision::tests::b1_chain_path_dominance_is_prefix_order ... ok +test revision::tests::b1_envelope_v2_round_trips_and_refuses_malformed_bytes ... ok +test revision::tests::b1_envelope_v2_signature_binds_repo_key_and_time ... ok +test revision::tests::b1_v2_changeset_id_covers_content_only_not_author_or_time ... ok +test revision::tests::b1_witness_and_marker_round_trip ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 8 filtered out; finished in 0.00s + +# Command: cargo test --locked -p synapse-store --test b1_change_identity -- --test-threads=1 +test b1_divergence_two_live_successors_is_detected ... ok +test b1_every_v1_changeset_id_still_resolves_to_its_record ... ok +test b1_identical_content_two_agents_one_chain_one_change_is_one_revision_two_attestations_two_witnesses ... ok +test b1_join_from_key_outside_creating_chain_without_change_scope_is_refused ... ok +test b1_prune_by_chain_not_dominating_creating_chain_is_refused ... ok +test b1_repeat_same_repo_did_idempotency_key_returns_first_wal_seq ... ok +test b1_revision_records_round_trip_and_malformed_bytes_are_refused_typed ... ok +test b1_rewrite_keeps_change_id_and_gets_new_changeset_id ... ok +test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.67s + +# Command: cargo test --locked -p synapse-api --test b1_chained_revisions -- --test-threads=1 +test b1_api_join_and_prune_follow_the_creating_chain_of_real_f1_chains ... ok +test b1_api_refuses_paths_outside_scope_foreign_authors_and_unknown_bases ... ok +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s diff --git a/evidence/b1-change-identity/red-green/red.txt b/evidence/b1-change-identity/red-green/red.txt new file mode 100644 index 0000000..66d8d4f --- /dev/null +++ b/evidence/b1-change-identity/red-green/red.txt @@ -0,0 +1,64 @@ +# Red (2026-10-16): each acceptance test run against the B1 commit b928eb9 with one mutation +# that removes the behaviour it proves; every mutation is reverted after its run. +# Command per case: cargo test --locked -p synapse-store --test b1_change_identity -- --exact + +## v2 ChangesetId covers only the ChangeId +# mutation in crates/synapse-core/src/revision.rs: +# - h.update(&bytes); +# + h.update(self.change_id.0); +# + let _ = bytes; +thread 'b1_rewrite_keeps_change_id_and_gets_new_changeset_id' (1237437) panicked at crates/synapse-store/tests/b1_change_identity.rs:140:5: +assertion `left != right` failed: a rewrite gets a new ChangesetId + left: ChangesetId(db05f57d3ad100ca1ba547b38dff63baca741eda9096ecf6db3bb9f75119bd71) + right: ChangesetId(db05f57d3ad100ca1ba547b38dff63baca741eda9096ecf6db3bb9f75119bd71) +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.03s + +## divergence never reported +# mutation in crates/synapse-store/src/revision.rs: +# - divergent: live.len() > 1, +# + divergent: false, +thread 'b1_divergence_two_live_successors_is_detected' (1240534) panicked at crates/synapse-store/tests/b1_change_identity.rs:176:5: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.08s + +## identical content from a second agent collapsed into the first (no second attestation) +# mutation in crates/synapse-store/src/revision.rs: +# + if joined_existing_revision { +# + return Ok(RevisionOutcome::IdempotentDuplicate { wal_seq: WalSeq(0), changeset_id: id }); +# + } +thread 'b1_identical_content_two_agents_one_chain_one_change_is_one_revision_two_attestations_two_witnesses' (1241525) panicked at crates/synapse-store/tests/b1_change_identity.rs:204:9: +expected a join of the existing revision, got IdempotentDuplicate { wal_seq: WalSeq(0), changeset_id: ChangesetId(40ee121239e23f3e82cef0d3d3b9c49234c7da99883ff0d4303c5cea42c5107c) } +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.02s + +## join rule disabled +# mutation in crates/synapse-store/src/revision.rs: +# - if authority.chain.descends_from(creating) || authority.change_scope.contains(&change_id) { +# + if true || authority.chain.descends_from(creating) || authority.change_scope.contains(&change_id) { +thread 'b1_join_from_key_outside_creating_chain_without_change_scope_is_refused' (1245135) panicked at crates/synapse-store/tests/b1_change_identity.rs:276:10: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.03s + +## dominance check on markers disabled +# mutation in crates/synapse-store/src/revision.rs: +# - if !allowed { +# + if false && !allowed { +thread 'b1_prune_by_chain_not_dominating_creating_chain_is_refused' (1245944) panicked at crates/synapse-store/tests/b1_change_identity.rs:318:14: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.03s + +## idempotency index ignored +# mutation in crates/synapse-store/src/revision.rs: +# - self.idempotency.get(&(repo.clone(), *key, idem)).copied() +# + { +# + let _ = (repo, key, idem, &self.idempotency); +# + None +# + } +thread 'b1_repeat_same_repo_did_idempotency_key_returns_first_wal_seq' (1246790) panicked at crates/synapse-store/tests/b1_change_identity.rs:371:5: +assertion `left == right` failed + left: Admitted { wal_seq: WalSeq(3), changeset_id: ChangesetId(b50c897316d03e965090c33d390da275d275a6a6710b41e0e1130de7f3658cc2), joined_existing_revision: true } + right: IdempotentDuplicate { wal_seq: WalSeq(1), changeset_id: ChangesetId(b50c897316d03e965090c33d390da275d275a6a6710b41e0e1130de7f3658cc2) } +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.05s + +## compaction drops v1 parents of revisions +# mutation in crates/synapse-store/src/lib.rs: +# - worklist.extend(rev.content.parents.iter().copied()); +# + let _ = rev; +thread 'b1_every_v1_changeset_id_still_resolves_to_its_record' (1247169) panicked at crates/synapse-store/tests/b1_change_identity.rs:433:51: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.07s