commit ed2cd2eabbf16afd96c54913b6030ab3c162ea65 parent 241a0257a36be4c47d37cdb7562428b3d3354468 Author: triesap <tyson@radroots.org> Date: Tue, 27 Oct 2026 05:02:10 +0000 storage: persist exact replay admission before returning permission - Bind current replay admission to the protected original claim and authorization. - Commit a distinct ledger family before current permits can escape. - Preserve original markers, retained catalogs and stock across refusal or loss. - Verify rollback, uncertain commits, tampering and native caller boundaries. Diffstat:
44 files changed, 1128 insertions(+), 125 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -596,6 +596,7 @@ pub const fn radroots_storage_sqlite::workspace::StockEvidencePage::next(&self) pub fn radroots_storage_sqlite::workspace::StockEvidencePage::receipts(&self) -> &[radroots_storage::inventory::evidence::StockEvidenceReceipt] pub struct radroots_storage_sqlite::workspace::StockExactReplayPermit impl radroots_storage_sqlite::workspace::StockExactReplayPermit +pub const fn radroots_storage_sqlite::workspace::StockExactReplayPermit::admission(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt> pub const fn radroots_storage_sqlite::workspace::StockExactReplayPermit::authorized_at(&self) -> radroots_domain::context::UnixSeconds pub fn radroots_storage_sqlite::workspace::StockExactReplayPermit::into_recovery_request(self, radroots_signing::provider::ProviderCall) -> core::result::Result<(radroots_signing::issuance::exact_recovery::ExactRecoveryRequest, radroots_storage_sqlite::workspace::StockSigningAttempt), radroots_storage::command::OperationError> pub const fn radroots_storage_sqlite::workspace::StockExactReplayPermit::report(&self) -> &radroots_storage_sqlite::workspace::StockSigningAttempt @@ -691,6 +692,15 @@ pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::first_e pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::original_unissued(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockUnissuedReceipt> pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::progress(&self) -> radroots_storage_sqlite::workspace::StockSigningProgress pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::replay_admission(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt> +pub struct radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt +impl radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::authorization(&self) -> radroots_storage::workspace::seller_stock::authorization::StockAuthorizationRef +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::observed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockReplayAdmissionReceipt::signing_attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId pub struct radroots_storage_sqlite::workspace::StockRequestSnapshot impl radroots_storage_sqlite::workspace::StockRequestSnapshot pub const fn radroots_storage_sqlite::workspace::StockRequestSnapshot::checkpoint(&self) -> &radroots_domain::context::CheckpointRef diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -82,7 +82,7 @@ "adapter": "radroots_nostr.signing.LocalSigner", "native_authorizer": "NativeWorkspace.authorize_stock_exact_replay", "captured_replay": "local_replay_safe", - "native_catalog": 14, + "native_catalog": 15, "worker_charge_bytes": 1048576, "existing_protected_claim_required": true, "current_execute_consent_required": true, @@ -93,12 +93,22 @@ "provider_work_inside_sql": false, "unsupported_legacy_fallback": false, "after_expiry_retrieval_available": false, - "legacy_and_first_dispatch_unchanged": true + "legacy_and_first_dispatch_unchanged": true, + "current_replay_admission_required": true, + "replay_admission_journal_family": 9, + "replay_admission_payload_version": 1, + "replay_admission_payload_bytes": 184, + "replay_admission_unknown_returns_permit": false, + "replay_admission_reauthorizes_current": true, + "replay_admission_clear_on_refusal": false, + "replay_admission_stock_effect": false, + "retained_untracked_catalogs": [13, 14], + "replay_admission_report_is_release_authority": false }, "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 14, + "schema_version": 15, "retained_enrollment_versions": [ 1 ], @@ -114,9 +124,10 @@ 10, 11, 12, - 13 + 13, + 14 ], - "authority_payload_schema": "radroots.seller_stock.authority.v14", + "authority_payload_schema": "radroots.seller_stock.authority.v15", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if matches!(version, 4..=14) { + if matches!(version, 4..=15) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -742,8 +742,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v12\0".as_slice() } else if version == 13 { b"radroots.seller_stock.authority_context.v13\0".as_slice() - } else { + } else if version == 14 { b"radroots.seller_stock.authority_context.v14\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v15\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -772,8 +774,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v12" } else if version == 13 { "radroots.seller_stock.authority.v13" - } else { + } else if version == 14 { "radroots.seller_stock.authority.v14" + } else { + "radroots.seller_stock.authority.v15" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -891,12 +895,12 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3..=14, "pool") => return Ok(original), + (2, _) | (3..=15, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", (5 | 6, "operation") => "radroots.seller_stock.operation.v4", - (7..=14, "operation") => "radroots.seller_stock.operation.v5", - (3..=14, "movement") => "radroots.seller_stock.movement.v2", + (7..=15, "operation") => "radroots.seller_stock.operation.v5", + (3..=15, "movement") => "radroots.seller_stock.movement.v2", _ => return Err(WorkspaceError::RecoveryRequired), }; Ok(EnvelopeContext::new( diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -31,10 +31,10 @@ pub use stock::{ StockHistorySnapshot, StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, StockOperationSnapshot, StockPublicationWork, StockRecipientSnapshot, - StockRequestSnapshot, StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, - StockSigningProgress, StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, - StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, StockUnissuedInvocation, - StockUnissuedOutcome, StockUnissuedReceipt, + StockReplayAdmissionReceipt, StockRequestSnapshot, StockSigningAttempt, + StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, StockSnapshotRequest, + StockSourceCapture, StockSourceOutcome, StockSourceProfile, StockSourceReceipt, + StockSourceSnapshot, StockUnissuedInvocation, StockUnissuedOutcome, StockUnissuedReceipt, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -30,7 +30,8 @@ mod order_state; pub use issuance::{ StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchOutcome, StockDispatchPermit, StockEvidenceCapture, StockEvidencePage, StockExactReplayPermit, - StockSigningAttempt, StockUnissuedInvocation, StockUnissuedOutcome, StockUnissuedReceipt, + StockReplayAdmissionReceipt, StockSigningAttempt, StockUnissuedInvocation, + StockUnissuedOutcome, StockUnissuedReceipt, }; pub(in crate::workspace) mod signing_plan; pub(in crate::workspace) mod snapshot; @@ -443,10 +444,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=14) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=15) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=14) { + if matches!(self.catalog, 8..=15) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -698,7 +699,7 @@ impl Authority { public_sources: None, } } - 8..=14 => { + 8..=15 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -828,7 +829,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=14") + sqlx::query("PRAGMA user_version=15") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -422,7 +422,7 @@ pub(in crate::workspace) async fn issue( proof: AttachmentProof, ) -> Result<StockConsentOutcome, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=14) { + if !matches!(access.authority.catalog, 7..=15) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() @@ -683,7 +683,7 @@ pub(in crate::workspace) async fn query( proof: AttachmentProof, ) -> Result<Option<StockConsentReceipt>, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=14) { + if !matches!(access.authority.catalog, 7..=15) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() && access.current.input().grant_id() != subject { diff --git a/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs @@ -74,7 +74,7 @@ impl KeyWrapping for Provider { fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { Box::pin(async move { let result = self.inner.wrap(request).await; - if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v14" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v15" { self.gate.pause(); } diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -324,7 +324,7 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if !(4..=14).contains(&authority.catalog) { + if !(4..=15).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -452,7 +452,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=14) { + let framed = if matches!(catalog, 7..=15) { Some( super::ledger::prepare( self.crypto, @@ -866,7 +866,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=14) { + let (frame, request, decoded) = if matches!(catalog, 7..=15) { let retained = super::ledger::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs @@ -149,7 +149,7 @@ pub(in crate::workspace) async fn abort( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=14) { + if !matches!(auth.access.authority.catalog, 13..=15) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; @@ -389,7 +389,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=14) { + if !matches!(auth.access.authority.catalog, 13..=15) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -236,7 +236,7 @@ pub(in crate::workspace) async fn admit( let access = turn .access(request.binding(), request.minimum_checkpoint(), &proof) .await?; - if !matches!(access.authority.catalog, 9..=14) { + if !matches!(access.authority.catalog, 9..=15) { return Err(OperationError::UnsupportedOperation); } let command = request.command(); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -323,7 +323,7 @@ pub(in crate::workspace::stock) async fn read( .map_err(|_| OperationError::RecoveryRequired)?; let operation_keyed = match catalog { 1..=12 => false, - 13 | 14 => true, + 13..=15 => true, _ => return Err(OperationError::RecoveryRequired), }; let actor = header.actor.participant(); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -68,7 +68,15 @@ impl MinimumProof { let related: Option<Vec<u8>> = row .try_get(2) .map_err(|_| OperationError::RecoveryRequired)?; - if !(0..=if catalog >= 14 { 8 } else { 7 }).contains(&family) { + if !(0..=if catalog >= 15 { + 9 + } else if catalog >= 14 { + 8 + } else { + 7 + }) + .contains(&family) + { return Err(OperationError::RecoveryRequired); } let subject: Option<Vec<u8>> = row @@ -94,7 +102,7 @@ impl MinimumProof { .await?, ); } - if matches!(family, 4 | 5 | 8) { + if matches!(family, 4 | 5 | 8 | 9) { hash.update( super::super::issuance::raw_projection( connection, &actor, &operation, family, @@ -143,7 +151,7 @@ pub(in crate::workspace::stock) async fn authenticate_order_state( authority: &Authority, order: radroots_domain::OrderId, ) -> Result<super::super::order_state::Checked, OperationError> { - if !matches!(authority.catalog, 13..=14) { + if !matches!(authority.catalog, 13..=15) { return Err(OperationError::UnsupportedOperation); } let current = authority @@ -212,7 +220,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=14) { + if !matches!(authority.catalog, 9..=15) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -294,7 +302,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=14); + let multipart = matches!(authority.catalog, 7..=15); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -471,7 +479,7 @@ pub(in crate::workspace::stock) async fn authenticate_minimum_with_local( minimum.revision().get().max(1) }; let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=14); + let multipart = matches!(authority.catalog, 7..=15); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -735,7 +743,7 @@ async fn authenticate_projected( .ok_or(OperationError::UnsupportedOperation)?; let upper = current.revision.get(); let mut expected = current.head; - let multipart = matches!(authority.catalog, 7..=14); + let multipart = matches!(authority.catalog, 7..=15); let mut hash = history_hash(multipart); for revision in (1..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -120,7 +120,7 @@ pub(super) fn encode_operation( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; - if matches!(catalog, 5..=14) { + if matches!(catalog, 5..=15) { return super::encode(&OperationV4 { version: 4, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -158,7 +158,7 @@ fn decode_inner( catalog: i64, allow_mapping: bool, ) -> Result<(InventoryRequest, OperationData), OperationError> { - if matches!(catalog, 5..=14) { + if matches!(catalog, 5..=15) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -222,7 +222,7 @@ pub(in crate::workspace) async fn install( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=14) { + if !matches!(auth.access.authority.catalog, 12..=15) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; @@ -481,7 +481,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=14) { + if !matches!(auth.access.authority.catalog, 12..=15) { return Err(OperationError::UnsupportedOperation); } let (retained, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -58,7 +58,7 @@ impl MappingRead { } } pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { - if !(5..=14).contains(&access.authority.catalog) { + if !(5..=15).contains(&access.authority.catalog) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3..=14 => Ok(2), + 3..=15 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance.rs b/crates/storage_sqlite/src/workspace/stock/issuance.rs @@ -13,6 +13,7 @@ pub(in crate::workspace) mod claim; pub(in crate::workspace) mod evidence; mod projection; pub(in crate::workspace) mod recovery; +pub(in crate::workspace) mod replay_admission; pub(in crate::workspace) mod unissued; pub(super) use claim::read_entry; pub use claim::{ @@ -22,6 +23,7 @@ pub use claim::{ pub use evidence::{StockCapturedEvidence, StockEvidenceCapture, StockEvidencePage}; pub(super) use projection::{Projection, ProjectionKind, raw_projection}; pub use recovery::StockExactReplayPermit; +pub use replay_admission::StockReplayAdmissionReceipt; pub use unissued::{StockUnissuedOutcome, StockUnissuedReceipt}; pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<(), WorkspaceError> { @@ -44,6 +46,13 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() return Err(WorkspaceError::RecoveryRequired); } } + if catalog >= 15 { + let (rows,entries):(i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_replay_admissions),(SELECT count(*) FROM stock_operations WHERE family=9)") + .fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if rows != entries { + return Err(WorkspaceError::RecoveryRequired); + } + } if catalog >= 12 { let (agreements, installs, work):(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_agreements),(SELECT count(*) FROM stock_operations WHERE family=6),(SELECT count(*) FROM stock_publication_work)").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; if agreements != installs diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs b/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs @@ -11,6 +11,7 @@ pub(in crate::workspace::stock) enum ProjectionKind { Claim, Obtained([u8; 32]), OriginalUnissued(u8), + ReplayAdmission, } impl ProjectionKind { fn family(self) -> i64 { @@ -18,6 +19,7 @@ impl ProjectionKind { Self::Claim => 4, Self::Obtained(_) => 5, Self::OriginalUnissued(_) => 8, + Self::ReplayAdmission => 9, } } } @@ -31,6 +33,7 @@ impl Projection { hash.update(self.recipient.as_bytes()); match self.kind { ProjectionKind::Claim => hash.update([0]), + ProjectionKind::ReplayAdmission => hash.update([3]), ProjectionKind::Obtained(value) => { hash.update([1]); hash.update(value); @@ -71,6 +74,7 @@ pub(in crate::workspace::stock) async fn raw_projection( 4 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,NULL FROM stock_signing_claims WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, 5 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,CASE WHEN length(evidence_digest)=32 THEN evidence_digest END FROM stock_signing_evidence WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, 8 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,reason FROM stock_original_unissued WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, + 9 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,NULL FROM stock_replay_admissions WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, _ => return Err(OperationError::RecoveryRequired), }.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; let field = |index| { @@ -86,6 +90,7 @@ pub(in crate::workspace::stock) async fn raw_projection( .map_err(|_| OperationError::RecoveryRequired)?, kind: match family { 4 => ProjectionKind::Claim, + 9 => ProjectionKind::ReplayAdmission, 5 => ProjectionKind::Obtained(field(2)?), 8 => { let reason: u8 = row diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs b/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs @@ -3,7 +3,10 @@ use super::super::{ inventory::{Turn, acceptance}, order_state, }; -use super::{StockClaimRequest, StockSigningAttempt, claim, signing_plan}; +use super::{ + StockClaimRequest, StockReplayAdmissionReceipt, StockSigningAttempt, claim, replay_admission, + signing_plan, +}; use crate::workspace::{AttachmentProof, NativeWorkspace, WorkspaceError}; use radroots_domain::UnixSeconds; use radroots_protocol::intent::SigningReplay; @@ -20,8 +23,16 @@ use sqlx::Connection; pub struct StockExactReplayPermit { report: StockSigningAttempt, at: UnixSeconds, + admission: Option<StockReplayAdmissionReceipt>, } impl StockExactReplayPermit { + /// Confirmed first replay admission in current catalog15. Retained13/14 + /// permits are explicitly untracked and return None; no report authorizes + /// stock release, a fresh first dispatch or another replay invocation. + pub const fn admission(&self) -> Option<StockReplayAdmissionReceipt> { + self.admission + } + /// Borrows the original protected attempt; this report cannot mint a permit. pub const fn report(&self) -> &StockSigningAttempt { &self.report @@ -70,7 +81,7 @@ pub(in crate::workspace) async fn authorize( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=14) { + if !matches!(auth.access.authority.catalog, 13..=15) { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; @@ -112,6 +123,11 @@ pub(in crate::workspace) async fn authorize( auth.original.receipt.held_pools(), )) .await?; + let pending = if auth.access.authority.catalog >= 15 { + Some(Box::pin(replay_admission::prepare(turn, &auth, &retained, at)).await?) + } else { + None + }; let mut tx = turn .connection .begin_with("BEGIN IMMEDIATE") @@ -131,18 +147,38 @@ pub(in crate::workspace) async fn authorize( if current.observed_at() < at || current.observed_at() < retained.report.claimed_at() { return Err(WorkspaceError::Unavailable.into()); } + if let Some(pending) = &pending { + pending.apply(&mut tx, turn.selected, &auth).await?; + } + turn.namespace.validate()?; Ok(current.observed_at()) } .await; - // No write, claim, stock movement, provider call or durable result is - // manufactured by authorization. A failed rollback still fences the owner. - if tx.rollback().await.is_err() { + let authorized_at = match checked { + Ok(value) => value, + Err(error) => { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + return Err(error); + } + }; + // A current fresh marker must be committed before a permit can escape. + // Existing markers and retained13/14 authorization require no new write. + let done = if pending.as_ref().is_some_and(|v| v.writes()) { + tx.commit().await + } else { + tx.rollback().await + }; + if done.is_err() { *turn.uncertain = true; return Err(OperationError::RecoveryRequired); } Ok(StockExactReplayPermit { report: retained.report, - at: checked?, + at: authorized_at, + admission: pending.as_ref().map(|v| v.receipt()), }) } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/replay_admission.rs b/crates/storage_sqlite/src/workspace/stock/issuance/replay_admission.rs @@ -0,0 +1,417 @@ +//! A confirmed current-catalog replay admission precedes every returned permit. +use super::super::inventory::Turn; +use super::*; +use radroots_domain::CheckpointDigest; +use radroots_storage::workspace::seller_stock::StockAuthorizationRef; +use zeroize::Zeroizing; + +const MAGIC: &[u8; 8] = b"RDSTRP1\0"; +const BYTES: usize = 184; + +/// Authenticated first admission of possible exact replay, never a dispatch or +/// nonissuance certificate. Later current authorization does not erase this fact. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StockReplayAdmissionReceipt { + attempt: CommitAttempt, + claim: SigningAttemptId, + recipient: PublicKey, + observed_at: UnixSeconds, + authorization: StockAuthorizationRef, + checkpoint: InventoryCheckpointRef, +} +impl StockReplayAdmissionReceipt { + /// Original operation and confirmed first admission transaction. + pub const fn attempt(&self) -> CommitAttempt { + self.attempt + } + /// Exact original durable signing claim. + pub const fn signing_attempt_id(&self) -> SigningAttemptId { + self.claim + } + /// Original recipient, independently of other recipient observations. + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + /// First checked authorization observation, captured before protection IO. + /// Permission and the original window are rechecked before actual commit. + pub const fn observed_at(&self) -> UnixSeconds { + self.observed_at + } + /// Authenticated grant-set observation captured by the first admission. + pub const fn authorization(&self) -> StockAuthorizationRef { + self.authorization + } + /// Protected first admission checkpoint; metadata supplies no permission. + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } +} +fn body( + original: &claim::codec::Retained, + at: UnixSeconds, + auth: StockAuthorizationRef, +) -> Zeroizing<Vec<u8>> { + let mut bytes = Zeroizing::new(Vec::with_capacity(BYTES)); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(original.frame.header.operation.as_bytes()); + bytes.extend_from_slice(original.frame.header.transaction.as_bytes()); + bytes.extend_from_slice(original.frame.header.head.as_bytes()); + bytes.extend_from_slice(original.report.binding().digest()); + bytes.extend_from_slice(&at.get().to_be_bytes()); + bytes.extend_from_slice(&auth.generation().get().to_be_bytes()); + bytes.extend_from_slice(auth.digest().as_bytes()); + bytes +} +fn head(header: &ledger::Header, bytes: &[u8]) -> CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.replay_admission_chain.v1\0"); + hash.update(header.namespace.workspace_id().as_bytes()); + hash.update(header.namespace.authority().executor_id().as_bytes()); + hash.update( + header + .namespace + .authority() + .generation() + .get() + .to_be_bytes(), + ); + hash.update(header.namespace.route_digest().as_bytes()); + hash.update(header.actor.participant().as_bytes()); + hash.update( + header + .actor + .grant_id() + .map(|v| *v.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.revision.get().to_be_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32])); + hash.update(Sha256::digest(bytes)); + CheckpointDigest::from_bytes(hash.finalize().into()) +} +fn receipt( + input: &AttachmentInput, + header: &ledger::Header, + original: &claim::codec::Retained, + at: UnixSeconds, + auth: StockAuthorizationRef, +) -> Result<StockReplayAdmissionReceipt, OperationError> { + Ok(StockReplayAdmissionReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + original.report.attempt().operation_id(), + header.digest, + Some(header.transaction), + ), + claim: original.report.attempt_id(), + recipient: original.report.recipient(), + observed_at: at, + authorization: auth, + checkpoint: InventoryCheckpointRef::from_host_metadata( + input.authority(), + header.revision, + Some(header.head), + )? + .with_authorization(auth), + }) +} +pub(in crate::workspace::stock) struct Retained { + frame: ledger::Retained, + value: StockReplayAdmissionReceipt, + projection: Projection, +} +impl Retained { + pub(in crate::workspace::stock) fn receipt(&self) -> StockReplayAdmissionReceipt { + self.value + } + pub(in crate::workspace::stock) async fn confirm( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?; + ledger::confirm_parts( + connection, + self.frame.header.actor, + self.frame.header.operation, + self.frame.parts_witness, + self.frame.header.parts, + ) + .await?; + self.projection + .confirm( + connection, + self.frame.header.actor.participant(), + self.frame.header.operation, + ) + .await?; + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", + ) + .bind(self.frame.header.actor.participant().as_bytes().as_slice()) + .bind(self.frame.header.operation.as_bytes().as_slice()) + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { + ledger::HistoryEntry { + aborted: None, + preparation: None, + local_record: None, + installation: None, + header: self.frame.header, + protected: self.frame.protected, + parts_witness: self.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + signing: Some(self.projection), + } + } +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + entry: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = ledger::read(connection, input, crypto, entry).await? else { + return Ok(None); + }; + let raw = frame.body.as_slice(); + if frame.header.family != ledger::Family::ReplayAdmission + || raw.len() != BYTES + || &raw[..8] != MAGIC + { + return Err(OperationError::RecoveryRequired); + } + let array = |start, end| { + raw[start..end] + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let original = Box::pin(claim::read_entry( + connection, + input, + crypto, + OperationId::from_bytes(array(8, 40)?), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let at = UnixSeconds::new(u64::from_be_bytes( + raw[136..144] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + .map_err(|_| OperationError::RecoveryRequired)?; + let authorization = StockAuthorizationRef::from_host_metadata( + Sequence::new(u64::from_be_bytes( + raw[144..152] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + .map_err(|_| OperationError::RecoveryRequired)?, + CheckpointDigest::from_bytes(array(152, 184)?), + )?; + if original.frame.header.transaction != TransactionId::from_bytes(array(40, 72)?) + || original.frame.header.head != CheckpointDigest::from_bytes(array(72, 104)?) + || original.report.binding().digest() != &array(104, 136)? + || frame.header.actor.participant() != original.frame.header.actor.participant() + || frame.header.related_operation != original.frame.header.related_operation + || frame.header.order != original.frame.header.order + || frame.header.digest != original.frame.header.digest + || frame.header.revision <= original.frame.header.revision + || original.report.bound_plan().plan().replay() + != radroots_protocol::intent::SigningReplay::LocalReplaySafe + || at < original.report.claimed_at() + || at < original.report.bound_plan().bound_at() + || at + >= original + .report + .bound_plan() + .preparation() + .first_issue_deadline() + || head(&frame.header, raw) != frame.header.head + { + return Err(OperationError::RecoveryRequired); + } + let projection = Projection { + operation: original.report.attempt().operation_id(), + recipient: original.report.recipient(), + kind: ProjectionKind::ReplayAdmission, + }; + let value = receipt(input, &frame.header, &original, at, authorization)?; + let retained = Retained { + frame, + value, + projection, + }; + retained.confirm(connection).await?; + Ok(Some(retained)) +} +pub(in crate::workspace::stock) async fn lookup( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, + recipient: PublicKey, +) -> Result<Option<Retained>, OperationError> { + let entry:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_replay_admissions WHERE actor=? AND operation_id=? AND recipient=?") + .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(entry) = entry else { return Ok(None) }; + let retained = Box::pin(read_entry( + connection, + input, + crypto, + OperationId::from_bytes( + entry + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.value.attempt.operation_id() != operation || retained.value.recipient != recipient { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(retained)) +} +pub(super) struct Pending { + old: Option<Retained>, + frame: Option<ledger::Prepared>, + root: Option<Vec<u8>>, + value: StockReplayAdmissionReceipt, +} +impl Pending { + pub(super) fn receipt(&self) -> StockReplayAdmissionReceipt { + self.value + } + /// Called only after current authorization and all original witnesses have + /// been rechecked in the same transaction, with no provider IO inside it. + pub(super) async fn apply( + &self, + connection: &mut SqliteConnection, + input: &AttachmentInput, + auth: &signing_plan::Authorized, + ) -> Result<(), OperationError> { + if let Some(old) = &self.old { + old.confirm(connection).await?; + } + if let Some(frame) = &self.frame { + frame.insert_record(connection).await?; + sqlx::query("INSERT INTO stock_replay_admissions(actor,operation_id,recipient,entry_id) VALUES(?,?,?,?)") + .bind(input.participant().as_bytes().as_slice()).bind(self.value.attempt.operation_id().as_bytes().as_slice()).bind(self.value.recipient.as_bytes().as_slice()).bind(frame.header.operation.as_bytes().as_slice()) + .execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + let changed = sqlx::query( + "UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?", + ) + .bind(self.root.as_ref().ok_or(OperationError::RecoveryRequired)?) + .bind(&auth.access.root) + .execute(connection) + .await + .map_err(|_| OperationError::StorageFailure)?; + if changed.rows_affected() != 1 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } + pub(super) fn writes(&self) -> bool { + self.frame.is_some() + } +} +pub(super) async fn prepare( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + original: &claim::codec::Retained, + at: UnixSeconds, +) -> Result<Pending, OperationError> { + let old = Box::pin(lookup( + turn.connection, + turn.selected, + turn.crypto, + original.report.attempt().operation_id(), + original.report.recipient(), + )) + .await?; + if let Some(old) = old { + if at < old.value.observed_at { + return Err(WorkspaceError::Unavailable.into()); + } + if old.value.claim != original.report.attempt_id() { + return Err(OperationError::RecoveryRequired); + } + let value = old.value; + return Ok(Pending { + old: Some(old), + frame: None, + root: None, + value, + }); + } + let before = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let authorization = auth + .access + .authority + .authorization + .ok_or(OperationError::RecoveryRequired)?; + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let bytes = body(original, at, authorization); + let mut header = ledger::Header { + version: 5, + family: ledger::Family::ReplayAdmission, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: auth.access.current.actor(), + operation: OperationId::from_bytes(super::super::super::random()?), + digest: original.report.attempt().command_digest(), + transaction: TransactionId::from_bytes(super::super::super::random()?), + revision, + previous: before.head, + head: CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: original.frame.header.order, + related_operation: Some(original.report.attempt().operation_id()), + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = head(&header, &bytes); + let value = receipt(turn.selected, &header, original, at, authorization)?; + let frame = ledger::prepare(turn.crypto, turn.selected, header, &bytes).await?; + let mut next = auth.access.authority.clone(); + next.inventory = Some(super::super::InventoryCheckpoint { + revision, + head: Some(frame.header.head), + ..before + }); + let root = turn + .crypto + .seal_stock_root(turn.selected, next.catalog, &next.encode()?) + .await?; + Ok(Pending { + old: None, + frame: Some(frame), + root: Some(root), + value, + }) +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs b/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs @@ -329,7 +329,7 @@ pub(in crate::workspace) async fn capture( } let (authority, record, root, grant) = super::super::read(turn.connection, input, turn.crypto).await?; - if authority.catalog != 14 { + if !matches!(authority.catalog, 14..=15) { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -483,7 +483,7 @@ pub(in crate::workspace) async fn read( &proof, ) .await?; - if auth.access.authority.catalog != 14 { + if !matches!(auth.access.authority.catalog, 14..=15) { return Err(OperationError::UnsupportedOperation); } let witness = Box::pin(checkpoint::authenticate_minimum( diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -24,6 +24,7 @@ pub(super) enum Family { Installation, AbortedPreparation, OriginalUnissued, + ReplayAdmission, } #[derive(Serialize, Deserialize)] @@ -79,6 +80,7 @@ impl Header { | Family::Installation | Family::AbortedPreparation | Family::OriginalUnissued + | Family::ReplayAdmission ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 @@ -334,6 +336,7 @@ impl Family { Self::Installation => 6, Self::AbortedPreparation => 7, Self::OriginalUnissued => 8, + Self::ReplayAdmission => 9, } } } @@ -537,7 +540,7 @@ pub(super) async fn history( movements: vec![], })) } - Some(2) if matches!(authority.catalog, 9..=14) => Ok(Some( + Some(2) if matches!(authority.catalog, 9..=15) => Ok(Some( Box::pin(super::inventory::acceptance::codec::read( connection, input, crypto, operation, )) @@ -546,7 +549,7 @@ pub(super) async fn history( .into_history(), )), Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10..=14) => { + Some(3) if matches!(authority.catalog, 10..=15) => { let retained = Box::pin(super::signing_plan::read_entry( connection, input, crypto, operation, )) @@ -570,7 +573,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(6) if matches!(authority.catalog, 12..=14) => Ok(Some( + Some(6) if matches!(authority.catalog, 12..=15) => Ok(Some( Box::pin(super::inventory::installation::read_entry( connection, input, crypto, operation, )) @@ -586,7 +589,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(8) if authority.catalog == 14 => Ok(Some( + Some(8) if authority.catalog >= 14 => Ok(Some( Box::pin(super::issuance::unissued::read_entry( connection, input, crypto, operation, )) @@ -594,6 +597,14 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), + Some(9) if authority.catalog >= 15 => Ok(Some( + Box::pin(super::issuance::replay_admission::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), Some(_) => Err(OperationError::RecoveryRequired), } } @@ -662,10 +673,19 @@ impl HistoryEntry { } match (header.family, self.signing) { ( - Family::SigningClaim | Family::SigningEvidence | Family::OriginalUnissued, + Family::SigningClaim + | Family::SigningEvidence + | Family::OriginalUnissued + | Family::ReplayAdmission, Some(projection), ) => hash.update(projection.digest(header.actor.participant(), header.operation)), - (Family::SigningClaim | Family::SigningEvidence | Family::OriginalUnissued, None) => { + ( + Family::SigningClaim + | Family::SigningEvidence + | Family::OriginalUnissued + | Family::ReplayAdmission, + None, + ) => { return Err(OperationError::RecoveryRequired); } (_, Some(_)) => return Err(OperationError::RecoveryRequired), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs @@ -122,7 +122,7 @@ async fn late_order_grant_pool_and_unrelated_preparation_changes_never_commit_a_ .unwrap(); provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), @@ -279,7 +279,7 @@ async fn losing_abort_observer_drains_original_admitted_work_before_reopen() { let selected = abort_request(&r, &receipt).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs @@ -450,7 +450,7 @@ async fn lost_observer_retains_actual_two_pool_preparation_and_drain_precedes_re let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -504,7 +504,7 @@ async fn source_mapping_pool_order_and_grant_rows_are_rechecked_after_final_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -541,7 +541,7 @@ async fn final_clock_recheck_refuses_expiry_and_rollback_after_protection_withou let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -329,7 +329,7 @@ async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), @@ -406,7 +406,7 @@ async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs @@ -128,13 +128,13 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v15", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); // The authorized old snapshot has already been read. Future schema then // refuses read-only preflight after close; no migration or repair occurs. - sqlx::raw_sql("PRAGMA user_version=15") + sqlx::raw_sql("PRAGMA user_version=16") .execute(&mut database) .await .unwrap(); @@ -146,7 +146,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .fetch_one(&mut database) .await .unwrap(), - 15 + 16 ); let wrong = AttachmentProof::from_protected_input(&[99; 32]).unwrap(); assert!( @@ -155,7 +155,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .is_err() ); request.with_json(|value| assert_eq!(value, raw)); - sqlx::raw_sql("PRAGMA user_version=14") + sqlx::raw_sql("PRAGMA user_version=15") .execute(&mut database) .await .unwrap(); @@ -184,7 +184,7 @@ async fn lost_reconciliation_observer_drains_the_actual_replacement_and_original remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v15", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs @@ -446,7 +446,7 @@ async fn lost_capture_observer_drains_owned_input_and_reopens_the_exact_original let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), @@ -534,7 +534,7 @@ async fn capture_rechecks_original_claim_plan_root_and_grant_after_provider_io() let mut rawdb = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs @@ -48,6 +48,9 @@ fn signer() -> LocalSigner { .unwrap() } +#[path = "replay_admission_tests.rs"] +mod admissions; + #[tokio::test] async fn original_local_claim_reopens_recovers_exact_s_and_installs_once_without_another_hold() { let mut r = Rig::new().await; @@ -70,7 +73,12 @@ async fn original_local_claim_reopens_recovers_exact_s_and_installs_once_without let permitted = authorize(&r, &receipt, recipient).await.unwrap(); assert_eq!(permitted.report().attempt_id(), original_attempt); assert_eq!(permitted.report().binding(), original_binding); - assert_eq!(inventory_minimum(&r).await, acknowledged); + let admission = permitted + .admission() + .expect("current replay must be durably tracked"); + assert_eq!(inventory_minimum(&r).await, admission.checkpoint()); + assert!(admission.checkpoint().revision() > acknowledged.revision()); + let (request, report) = permitted.into_recovery_request(call(&r, 250000)).unwrap(); assert_eq!(request.binding(), original_binding); let expected_event = request.original().with_event(|_, id| id); @@ -429,7 +437,7 @@ async fn replay_authorization_rechecks_actual_late_root_grant_plan_claim_backing let mut raw = database(&r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), @@ -483,7 +491,7 @@ async fn observer_loss_drains_authorization_without_signing_or_a_new_claim_and_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), @@ -496,11 +504,13 @@ async fn observer_loss_drains_authorization_without_signing_or_a_new_claim_and_r provider.gate.release(); closing.await.unwrap(); reopen_plain(&mut r).await; - assert_eq!(inventory_minimum(&r).await, before); + let admitted = inventory_minimum(&r).await; + assert!(admitted.revision() > before.revision()); let permitted = authorize(&r, &receipt, recipient).await.unwrap(); assert_eq!(permitted.report().attempt_id(), original); + assert_eq!(permitted.admission().unwrap().checkpoint(), admitted); drop(permitted); - assert_eq!(inventory_minimum(&r).await, before); + assert_eq!(inventory_minimum(&r).await, admitted); assert_pool(&r, 80, 9, 1, 2).await; r.store.close().await.unwrap(); } diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -412,7 +412,7 @@ async fn lost_t2_observer_drains_and_reopens_one_atomic_installation() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), @@ -451,7 +451,7 @@ async fn late_t2_backing_or_grant_or_evidence_change_never_commits_partial_insta let mut db = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs @@ -164,7 +164,7 @@ async fn stock_process_child() { if control.before { provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); } let work = async { match control.edge { diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/replay_admission_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/replay_admission_tests.rs @@ -0,0 +1,312 @@ +//! Actual replay admission transactions, original identity and uncertainty. +use super::*; +use crate::workspace::{StockReplayAdmissionReceipt, StockSnapshotRequest}; +use sqlx::Connection; + +async fn prepared_claim(r: &Rig) -> (StockAcceptanceReceipt, radroots_domain::SigningAttemptId) { + let receipt = local_ready(r).await; + let StockClaimOutcome::Fresh(permit) = claim(r, &receipt, receipt.rumor().recipients()[0]) + .await + .unwrap() + else { + panic!("fresh original claim") + }; + let id = permit.report().attempt_id(); + drop(permit); + (receipt, id) +} +async fn marker( + r: &Rig, + original: &StockAcceptanceReceipt, +) -> Result<Option<StockReplayAdmissionReceipt>, OperationError> { + marker_at(r, original, inventory_minimum(r).await).await +} +async fn marker_at( + r: &Rig, + original: &StockAcceptanceReceipt, + minimum: radroots_storage::inventory::InventoryCheckpointRef, +) -> Result<Option<StockReplayAdmissionReceipt>, OperationError> { + let snapshot = r + .store + .stock_operation_snapshot( + StockSnapshotRequest::new( + r.binding.clone(), + minimum, + original.attempt().operation_id(), + original.attempt().command_digest(), + ), + r.enrollment.proof(), + ) + .await?; + Ok(snapshot.recipients()[0].replay_admission()) +} +async fn pools(r: &Rig) -> Vec<(Vec<u8>, i64, Vec<u8>)> { + let mut connection = database(r).await; + let values = + sqlx::query_as("SELECT pool_id,revision,protected FROM stock_pools ORDER BY pool_id") + .fetch_all(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + values +} +#[tokio::test] +async fn current_permit_follows_one_durable_admission_and_reauthorization_preserves_original_marker_and_stock() + { + let mut r = Rig::new().await; + let (original, claim) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + assert!(marker(&r, &original).await.unwrap().is_none()); + let before = inventory_minimum(&r).await; + let stock = pools(&r).await; + let permit = authorize(&r, &original, recipient).await.unwrap(); + let first = permit + .admission() + .expect("current permit must follow committed admission"); + assert_eq!(first.signing_attempt_id(), claim); + assert_eq!(first.recipient(), recipient); + assert_eq!( + first.attempt().operation_id(), + original.attempt().operation_id() + ); + assert_eq!( + first.attempt().command_digest(), + original.attempt().command_digest() + ); + assert!(first.attempt().transaction_id().is_some()); + assert_eq!( + first.checkpoint().revision().get(), + before.revision().get() + 1 + ); + assert_eq!(marker(&r, &original).await.unwrap(), Some(first)); + assert_eq!(pools(&r).await, stock); + drop(permit); + r.clock.0.store(151, Ordering::SeqCst); + let again = authorize(&r, &original, recipient).await.unwrap(); + assert_eq!(again.admission(), Some(first)); + assert_eq!(again.authorized_at(), UnixSeconds::new(151).unwrap()); + assert_eq!(inventory_minimum(&r).await, first.checkpoint()); + drop(again); + reopen_plain(&mut r).await; + assert_eq!(marker(&r, &original).await.unwrap(), Some(first)); + assert_eq!(pools(&r).await, stock); + let mut connection = database(&r).await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_replay_admissions") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(count, 1); + let movements:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE operation_id IN (SELECT entry_id FROM stock_replay_admissions)").fetch_one(&mut connection).await.unwrap(); + assert_eq!(movements, 0); + connection.close().await.unwrap(); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn every_replay_admission_write_failure_returns_no_permit_and_rolls_back_original_state() { + for fault in [ + "CREATE TRIGGER replay_fault BEFORE INSERT ON stock_operations WHEN NEW.family=9 BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER replay_fault BEFORE INSERT ON stock_operation_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER replay_fault BEFORE INSERT ON stock_replay_admissions BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER replay_fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", + ] { + let r = Rig::new().await; + let (original, _) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + let before = inventory_minimum(&r).await; + let stock = pools(&r).await; + let mut connection = database(&r).await; + sqlx::query(fault).execute(&mut connection).await.unwrap(); + assert_eq!( + authorize(&r, &original, recipient).await.unwrap_err(), + OperationError::StorageFailure + ); + assert_eq!(inventory_minimum(&r).await, before); + assert!(marker(&r, &original).await.unwrap().is_none()); + assert_eq!(pools(&r).await, stock); + sqlx::query("DROP TRIGGER replay_fault") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + assert!( + authorize(&r, &original, recipient) + .await + .unwrap() + .admission() + .is_some() + ); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn uncertain_replay_admission_returns_no_permit_fences_owner_and_reopens_original_claim() { + let mut r = Rig::new().await; + let (original, claim) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + let stock = pools(&r).await; + let minimum = inventory_minimum(&r).await; + let mut connection = database(&r).await; + sqlx::raw_sql("CREATE TABLE replay_deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER replay_fault AFTER INSERT ON stock_replay_admissions BEGIN INSERT INTO replay_deferred_fault VALUES(2); END").execute(&mut connection).await.unwrap(); + assert_eq!( + r.store + .authorize_stock_exact_replay( + StockClaimRequest::new( + r.binding.clone(), + minimum, + original.attempt().operation_id(), + original.attempt().command_digest(), + recipient + ), + r.enrollment.proof() + ) + .await + .unwrap_err(), + OperationError::RecoveryRequired + ); + assert_eq!( + r.store + .authorize_stock_exact_replay( + StockClaimRequest::new( + r.binding.clone(), + minimum, + original.attempt().operation_id(), + original.attempt().command_digest(), + recipient + ), + r.enrollment.proof() + ) + .await + .unwrap_err(), + OperationError::RecoveryRequired + ); + sqlx::raw_sql("DROP TRIGGER replay_fault; DROP TABLE replay_deferred_fault") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + reopen_plain(&mut r).await; + assert!(marker(&r, &original).await.unwrap().is_none()); + assert_eq!(pools(&r).await, stock); + let permit = authorize(&r, &original, recipient).await.unwrap(); + assert_eq!(permit.report().attempt_id(), claim); + assert_eq!(permit.admission().unwrap().signing_attempt_id(), claim); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn replay_admission_projection_and_protected_body_damage_are_never_read_as_absence_or_permission() + { + for fault in [ + "DELETE FROM stock_replay_admissions", + "UPDATE stock_replay_admissions SET recipient=randomblob(32)", + "UPDATE stock_operation_parts SET protected=randomblob(length(protected)) WHERE operation_id IN (SELECT entry_id FROM stock_replay_admissions)", + ] { + let r = Rig::new().await; + let (original, _) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + drop(authorize(&r, &original, recipient).await.unwrap()); + let minimum = inventory_minimum(&r).await; + let mut connection = database(&r).await; + sqlx::query(fault).execute(&mut connection).await.unwrap(); + connection.close().await.unwrap(); + assert_eq!( + marker_at(&r, &original, minimum).await.unwrap_err().code(), + "recovery_required", + "{fault}" + ); + assert_eq!( + r.store + .authorize_stock_exact_replay( + StockClaimRequest::new( + r.binding.clone(), + minimum, + original.attempt().operation_id(), + original.attempt().command_digest(), + recipient + ), + r.enrollment.proof() + ) + .await + .unwrap_err() + .code(), + "recovery_required", + "{fault}" + ); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn existing_replay_marker_never_renews_the_original_window_or_allows_a_backwards_clock() { + let r = Rig::new().await; + let (original, _) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + r.clock.0.store(160, Ordering::SeqCst); + let first = authorize(&r, &original, recipient) + .await + .unwrap() + .admission() + .unwrap(); + r.clock.0.store(159, Ordering::SeqCst); + assert!(authorize(&r, &original, recipient).await.is_err()); + r.clock + .0 + .store(original.first_issue_deadline().get(), Ordering::SeqCst); + assert_eq!( + authorize(&r, &original, recipient).await.unwrap_err(), + OperationError::DeadlineExceeded + ); + r.clock.0.store(160, Ordering::SeqCst); + assert_eq!(marker(&r, &original).await.unwrap(), Some(first)); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn retained_13_14_replay_stays_untracked_without_migration_or_stock_effect() { + for catalog in [13, 14] { + let mut r = Rig::with_catalog(catalog).await; + let (original, claim) = prepared_claim(&r).await; + let recipient = original.rumor().recipients()[0]; + let before = inventory_minimum(&r).await; + let stock = pools(&r).await; + let permit = authorize(&r, &original, recipient).await.unwrap(); + assert_eq!(permit.report().attempt_id(), claim); + assert!(permit.admission().is_none()); + drop(permit); + assert_eq!(inventory_minimum(&r).await, before); + assert!(marker(&r, &original).await.unwrap().is_none()); + assert_eq!(pools(&r).await, stock); + reopen_plain(&mut r).await; + let permit = authorize(&r, &original, recipient).await.unwrap(); + assert!(permit.admission().is_none()); + let (request, report) = permit.into_recovery_request(call(&r, 250000)).unwrap(); + assert_eq!(report.attempt_id(), claim); + let expected = request.original().with_event(|_, id| id); + let outcome = signer().recover_exact(request).await; + assert_eq!(outcome.binding(), report.binding()); + let (_, ExactRecoveryKind::Obtained(signed)) = outcome.into_parts() else { + panic!("retained exact local replay"); + }; + assert_eq!(signed.event_id(), expected); + assert_eq!(inventory_minimum(&r).await, before); + assert_eq!(pools(&r).await, stock); + let mut connection = database(&r).await; + let actual: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(actual, catalog); + let markers: i64 = sqlx::query_scalar( + "SELECT count(*) FROM sqlite_schema WHERE name='stock_replay_admissions'", + ) + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(markers, 0); + connection.close().await.unwrap(); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs @@ -354,7 +354,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -408,7 +408,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs @@ -157,7 +157,7 @@ async fn public_source_close_drains_admitted_work_after_observer_loss() { let minimum = r.minimum().await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, @@ -213,7 +213,7 @@ async fn public_source_writes_recheck_expiry_and_head_rows_after_actual_protecti let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/tests.rs @@ -43,6 +43,9 @@ struct Rig { } impl Rig { async fn new() -> Self { + Self::with_catalog(super::super::schema::CURRENT).await + } + async fn with_catalog(catalog: i64) -> Self { let fixture = CryptoFixture::new(); let path = fixture.root().join("public-sources"); let owner = PublicKey::from_hex(vectors()["author"].as_str().unwrap()).unwrap(); @@ -58,14 +61,27 @@ impl Rig { clock.as_ref(), ) .unwrap(); - let store = NativeWorkspace::initialize_seller_stock( - &path, - &enrollment, - fixture.crypto(), - clock.clone(), - ) - .await - .unwrap(); + let store = if catalog == super::super::schema::CURRENT { + NativeWorkspace::initialize_seller_stock( + &path, + &enrollment, + fixture.crypto(), + clock.clone(), + ) + .await + .unwrap() + } else { + super::super::tests::literal_enrollment_catalog(&fixture, &path, catalog, &enrollment) + .await; + NativeWorkspace::open_seller_stock( + &path, + enrollment.input().clone(), + fixture.crypto(), + clock.clone(), + ) + .await + .unwrap() + }; let binding = store .authenticate(enrollment.input().clone(), enrollment.proof()) .await diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs @@ -31,7 +31,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !matches!(authority.catalog, 8..=14) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=15) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs @@ -364,7 +364,7 @@ async fn lost_original_negative_append_waiter_drains_and_reopens_the_same_fact() let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v15", 0); let mut pending = Box::pin(capture(&r, &value)); assert!(futures::poll!(pending.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 14; +pub(super) const CURRENT: i64 = 15; const AUTHORITY: &str = "CREATE TABLE stock_authority (singleton INTEGER PRIMARY KEY CHECK(singleton=1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; const GRANTS: &str = "CREATE TABLE stock_grants (grant_id BLOB PRIMARY KEY CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; const POOLS: &str = "CREATE TABLE stock_pools (pool_id BLOB PRIMARY KEY CHECK(length(pool_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; @@ -18,6 +18,7 @@ const OPERATIONS_V11: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL const OPERATIONS_V12: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 6), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 6 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V13: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 7), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 7 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V14: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 8), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 8 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; +const OPERATIONS_V15: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 9), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 9 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const MOVEMENTS: &str = "CREATE TABLE stock_movements (movement_id BLOB PRIMARY KEY CHECK(length(movement_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID"; pub(super) fn objects( version: i64, @@ -28,13 +29,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=14 => objects.extend([ + 2..=15 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 14 { + if version >= 15 { + OPERATIONS_V15 + } else if version >= 14 { OPERATIONS_V14 } else if version >= 13 { OPERATIONS_V13 @@ -85,7 +88,7 @@ pub(super) fn objects( if version >= 5 { objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); } - if (6..=14).contains(&version) { + if (6..=15).contains(&version) { objects.push(("table","stock_source_records","stock_source_records","CREATE TABLE stock_source_records (record_id BLOB PRIMARY KEY CHECK(length(record_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("table","stock_source_evidence","stock_source_evidence","CREATE TABLE stock_source_evidence (envelope_id BLOB PRIMARY KEY CHECK(length(envelope_id)=32), record_id BLOB REFERENCES stock_source_records(record_id), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_source_transaction_identity","stock_source_evidence","CREATE UNIQUE INDEX stock_source_transaction_identity ON stock_source_evidence(transaction_id)")); @@ -121,7 +124,7 @@ pub(super) fn objects( objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); } } - if matches!(version, 8..=14) { + if matches!(version, 8..=15) { objects.push(("table","stock_public_events","stock_public_events","CREATE TABLE stock_public_events (event_id BLOB PRIMARY KEY CHECK(length(event_id)=32), listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), created_at BLOB NOT NULL CHECK(length(created_at)=8), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_public_transaction_identity","stock_public_events","CREATE UNIQUE INDEX stock_public_transaction_identity ON stock_public_events(transaction_id)")); objects.push(( @@ -179,6 +182,10 @@ pub(super) fn objects( objects.push(("table","stock_original_unissued","stock_original_unissued","CREATE TABLE stock_original_unissued (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), reason INTEGER NOT NULL CHECK(reason BETWEEN 1 AND 9), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,operation_id,recipient) REFERENCES stock_signing_claims(actor,operation_id,recipient), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_original_unissued_entry","stock_original_unissued","CREATE UNIQUE INDEX stock_original_unissued_entry ON stock_original_unissued(actor,entry_id)")); } + if version >= 15 { + objects.push(("table","stock_replay_admissions","stock_replay_admissions","CREATE TABLE stock_replay_admissions (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,operation_id,recipient) REFERENCES stock_signing_claims(actor,operation_id,recipient), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_replay_admission_entry","stock_replay_admissions","CREATE UNIQUE INDEX stock_replay_admission_entry ON stock_replay_admissions(actor,entry_id)")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = turn.access(binding, minimum, proof).await?; - if !matches!(access.authority.catalog, 10..=14) { + if !matches!(access.authority.catalog, 10..=15) { return Err(OperationError::UnsupportedOperation); } let original = Box::pin(acceptance::codec::read( diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -73,6 +73,7 @@ pub struct StockRecipientSnapshot { count: Sequence, first: Option<StockEvidenceReceipt>, unissued: Option<super::StockUnissuedReceipt>, + replay: Option<super::StockReplayAdmissionReceipt>, } impl StockRecipientSnapshot { pub const fn recipient(&self) -> PublicKey { @@ -95,6 +96,11 @@ impl StockRecipientSnapshot { pub const fn original_unissued(&self) -> Option<super::StockUnissuedReceipt> { self.unissued } + /// First durable current-catalog replay admission, not invocation or S. + /// Retained catalogs without this family return None. + pub const fn replay_admission(&self) -> Option<super::StockReplayAdmissionReceipt> { + self.replay + } pub const fn progress(&self) -> StockSigningProgress { if self.first.is_some() { StockSigningProgress::Obtained @@ -159,12 +165,23 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; + Box::pin(read_authorized(turn, request, proof, auth)).await +} + +// Keep authorization loading outside the projection's larger polling frame. +async fn read_authorized( + turn: &mut Turn<'_>, + request: StockSnapshotRequest, + proof: AttachmentProof, + auth: signing_plan::Authorized, +) -> Result<StockOperationSnapshot, OperationError> { if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let mut reports = Vec::with_capacity(2); let mut claims = Vec::with_capacity(2); let mut refusals = Vec::with_capacity(2); + let mut replays = Vec::with_capacity(2); let mut summaries = Vec::with_capacity(2); for recipient in auth.original.receipt.rumor().recipients() { let (retained, claim_proof) = @@ -232,6 +249,24 @@ pub(in crate::workspace) async fn read( { return Err(OperationError::RecoveryRequired); } + let replay = if auth.access.authority.catalog >= 15 { + Box::pin(issuance::replay_admission::lookup( + turn.connection, + turn.selected, + turn.crypto, + request.operation, + *recipient, + )) + .await? + } else { + None + }; + if replay + .as_ref() + .is_some_and(|v| reference.is_none_or(|c| c.id != v.receipt().signing_attempt_id())) + { + return Err(OperationError::RecoveryRequired); + } reports.push(StockRecipientSnapshot { recipient: *recipient, expected, @@ -239,8 +274,10 @@ pub(in crate::workspace) async fn read( count: summary.count, first, unissued: unissued.as_ref().map(|v| v.receipt()), + replay: replay.as_ref().map(|v| v.receipt()), }); refusals.push(unissued); + replays.push(replay); claims.push(claim_proof); summaries.push(summary); } @@ -341,6 +378,9 @@ pub(in crate::workspace) async fn read( } for (index, report) in reports.iter().enumerate() { claims[index].confirm(&mut tx).await?; + if let Some(value) = &replays[index] { + value.confirm(&mut tx).await?; + } if let Some(value) = &refusals[index] { value.confirm(&mut tx).await?; } diff --git a/crates/storage_sqlite/src/workspace/stock/source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/source/transaction.rs @@ -28,7 +28,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !(6..=14).contains(&authority.catalog) { + if !(6..=15).contains(&authority.catalog) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; @@ -114,7 +114,7 @@ pub(in crate::workspace) async fn history( proof: AttachmentProof, ) -> Result<StockHistorySnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=14) { + if !matches!(access.authority.catalog, 8..=15) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::history::prepare( @@ -175,7 +175,7 @@ pub(in crate::workspace) async fn inspect_request( proof: AttachmentProof, ) -> Result<StockRequestSnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=14) { + if !matches!(access.authority.catalog, 8..=15) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::request::prepare( diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -109,7 +109,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang ) .await .unwrap(); - assert_eq!(schema::admit(&mut connection).await, Ok(14)); + assert_eq!(schema::admit(&mut connection).await, Ok(15)); assert_eq!(schema::integrity(&mut connection).await, Ok(())); let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") .fetch_one(&mut connection) @@ -117,18 +117,18 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang .unwrap(); let clear = fixture .crypto() - .open_stock_root(enrollment.input(), 14, &root) + .open_stock_root(enrollment.input(), 15, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 14)) + .expose_secret(|bytes| Authority::decode(bytes, 15)) .unwrap(); clear.expose_secret(|bytes| { let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); assert_eq!(original["inventory"]["mappings"],"0"); for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { let mut value=original.clone();value["inventory"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),14).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),15).is_err()); } for bad in [ serde_json::json!([]), @@ -139,7 +139,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang serde_json::json!({"revision":"1","records":"2","parts":"3","head":"01".repeat(32)}), ] { let mut value=original.clone();value["sources"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),14).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),15).is_err()); } }); assert_eq!(authority.input, *enrollment.input()); @@ -189,7 +189,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - for version in [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] { + for version in [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -277,7 +277,7 @@ async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { } #[tokio::test] async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { - assert_eq!(schema::CURRENT, 14); + assert_eq!(schema::CURRENT, 15); retained_inventory_catalog(11).await; } // Exact catalog fixtures exercise retained/successor codecs; they are not @@ -302,6 +302,47 @@ pub(super) async fn literal_catalog( AttachmentProof::from_protected_input(&[0xA3; 32]).unwrap(), ) .unwrap(); + literal_catalog_contents( + fixture, + path, + catalog, + &input, + record, + TransactionId::from_bytes([9; 32]), + ) + .await; + (input, proof) +} + +/// Creates an exact retained schema/root with a caller's enrollment and key. +/// This is literal-shape/current-code evidence, never predecessor-binary evidence. +pub(in crate::workspace::stock) async fn literal_enrollment_catalog( + fixture: &CryptoFixture, + path: &std::path::Path, + catalog: i64, + enrollment: &StockEnrollment, +) { + assert!(matches!(catalog, 13 | 14)); + let record = enrollment.record.lock().unwrap().take().unwrap(); + literal_catalog_contents( + fixture, + path, + catalog, + enrollment.input(), + record, + enrollment.transaction_id(), + ) + .await; +} +async fn literal_catalog_contents( + fixture: &CryptoFixture, + path: &std::path::Path, + catalog: i64, + input: &AttachmentInput, + record: GrantRecord, + transaction: TransactionId, +) { + let input = input.clone(); // Literal retained catalog/root shapes from published creation/correction source; not predecessor-binary evidence. let crypto = fixture.crypto(); let grant_clear = if catalog >= 4 { @@ -325,9 +366,9 @@ pub(super) async fn literal_catalog( }; // The v4 namespace, grant2 and operation3 envelopes remain frozen literals. let mut value = if catalog >= 4 { - serde_json::json!({"version":4,"namespace":SellerAuthoritySelection::from_attachment(&input),"administrator":input.grant_id(),"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null},"authorization":grants::single_state(input.grant_id(),&grant).unwrap()}) + serde_json::json!({"version":4,"namespace":SellerAuthoritySelection::from_attachment(&input),"administrator":input.grant_id(),"transaction":transaction,"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null},"authorization":grants::single_state(input.grant_id(),&grant).unwrap()}) } else { - serde_json::json!({"version":catalog,"input":input,"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}}) + serde_json::json!({"version":catalog,"input":input,"transaction":transaction,"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}}) }; if catalog >= 5 { value["version"] = serde_json::json!(catalog); @@ -340,7 +381,7 @@ pub(super) async fn literal_catalog( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=14) { + if matches!(catalog, 8..=15) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -387,6 +428,7 @@ pub(super) async fn literal_catalog( 12 => "PRAGMA user_version=12", 13 => "PRAGMA user_version=13", 14 => "PRAGMA user_version=14", + 15 => "PRAGMA user_version=15", _ => unreachable!(), }) .execute(&mut *tx) @@ -395,7 +437,6 @@ pub(super) async fn literal_catalog( tx.commit().await.unwrap(); connection.close().await.unwrap(); drop(namespace); - (input, proof) } async fn retained_inventory_catalog(catalog: i64) { @@ -412,7 +453,7 @@ async fn retained_inventory_catalog(catalog: i64) { assert_eq!(authority.source_checkpoint().is_some(), catalog >= 6); assert_eq!( authority.listing_checkpoint().is_some(), - matches!(catalog, 8..=14) + matches!(catalog, 8..=15) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -655,7 +696,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=14) { + let old = if matches!(catalog, 7..=15) { let retained = ledger::read( &mut connection, &input, @@ -708,7 +749,7 @@ async fn retained_inventory_catalog(catalog: i64) { // inside a real SQL transaction. Row counts and the protected header // stay unchanged while one referenced ciphertext changes. for part in [false, true] { - if part && !matches!(catalog, 7..=14) { + if part && !matches!(catalog, 7..=15) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -785,6 +826,7 @@ async fn retained_inventory_catalog(catalog: i64) { 12 => "PRAGMA user_version=11", 13 => "PRAGMA user_version=12", 14 => "PRAGMA user_version=13", + 15 => "PRAGMA user_version=14", _ => unreachable!(), }) .execute(&mut connection) @@ -914,18 +956,24 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() #[tokio::test] async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 14); + assert_eq!(schema::CURRENT, 15); retained_inventory_catalog(12).await; } #[tokio::test] async fn retained_v13_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 14); + assert_eq!(schema::CURRENT, 15); retained_inventory_catalog(13).await; } #[tokio::test] -async fn current_v14_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 14); +async fn retained_v14_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 15); retained_inventory_catalog(14).await; } + +#[tokio::test] +async fn current_v15_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 15); + retained_inventory_catalog(15).await; +} diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=14") + sqlx::query("PRAGMA user_version=15") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -244,6 +244,16 @@ struct QualifiedLocalRecovery { unsupported_legacy_fallback: bool, after_expiry_retrieval_available: bool, legacy_and_first_dispatch_unchanged: bool, + current_replay_admission_required: bool, + replay_admission_journal_family: u16, + replay_admission_payload_version: u16, + replay_admission_payload_bytes: u16, + replay_admission_unknown_returns_permit: bool, + replay_admission_reauthorizes_current: bool, + replay_admission_clear_on_refusal: bool, + replay_admission_stock_effect: bool, + retained_untracked_catalogs: Vec<u16>, + replay_admission_report_is_release_authority: bool, } #[derive(Deserialize)] @@ -594,10 +604,10 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.scope == "seller_stock_owner" && stock.database == "stock_execution_v1.sqlite" && stock.lock == ".stock_execution_v1.lock" - && stock.schema_version == 14 + && stock.schema_version == 15 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v14" + && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v15" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -876,7 +886,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.qualified_local_recovery.native_authorizer == "NativeWorkspace.authorize_stock_exact_replay" && stock.qualified_local_recovery.captured_replay == "local_replay_safe" - && stock.qualified_local_recovery.native_catalog == 14 + && stock.qualified_local_recovery.native_catalog == 15 && stock.qualified_local_recovery.worker_charge_bytes == 1048576 && stock .qualified_local_recovery @@ -900,6 +910,35 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock .qualified_local_recovery .legacy_and_first_dispatch_unchanged + && stock + .qualified_local_recovery + .current_replay_admission_required + && stock + .qualified_local_recovery + .replay_admission_journal_family + == 9 + && stock + .qualified_local_recovery + .replay_admission_payload_version + == 1 + && stock + .qualified_local_recovery + .replay_admission_payload_bytes + == 184 + && !stock + .qualified_local_recovery + .replay_admission_unknown_returns_permit + && stock + .qualified_local_recovery + .replay_admission_reauthorizes_current + && !stock + .qualified_local_recovery + .replay_admission_clear_on_refusal + && !stock.qualified_local_recovery.replay_admission_stock_effect + && stock.qualified_local_recovery.retained_untracked_catalogs == [13, 14] + && !stock + .qualified_local_recovery + .replay_admission_report_is_release_authority && stock.preparation_abort.payload_version == 1 && stock.preparation_abort.journal_family == 7 && stock.preparation_abort.worker_charge_bytes == 1048576 @@ -1790,6 +1829,16 @@ mod tests { ("unsupported_legacy_fallback", json!(true)), ("after_expiry_retrieval_available", json!(true)), ("legacy_and_first_dispatch_unchanged", json!(false)), + ("current_replay_admission_required", json!(false)), + ("replay_admission_journal_family", json!(8)), + ("replay_admission_payload_version", json!(2)), + ("replay_admission_payload_bytes", json!(185)), + ("replay_admission_unknown_returns_permit", json!(true)), + ("replay_admission_reauthorizes_current", json!(false)), + ("replay_admission_clear_on_refusal", json!(true)), + ("replay_admission_stock_effect", json!(true)), + ("retained_untracked_catalogs", json!([15])), + ("replay_admission_report_is_release_authority", json!(true)), ] { assert!( validate_bytes(&changed(