lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 0235b502a87b0cad0b3c90d65e04e800962594f5
parent dc04b333826e1e7f0e2bee4f69bf6fd309ca91d5
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 00:34:20 +0000

execution: retain immutable native issuance windows

- capture checked preparation time and authorization-bounded first issuance
- persist exact windows in protected operations and preserve them on replay
- refuse clock rollback and predecessor schemas without inferred timestamps
- verify native expiry races, restored bounds, public APIs and coverage

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 7+++++++
Mcontracts/api_baselines/radroots_storage.txt | 3++-
Mcontracts/execution/workspace.v1.json | 17+++++++++++------
Acrates/domain/src/issuance.rs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/lib.rs | 2++
Acrates/domain/tests/issuance.rs | 40++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/src/command.rs | 18++++++++++++++++--
Mcrates/storage/tests/command.rs | 50+++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/admission.rs | 23++++++++++++++++-------
Mcrates/storage_sqlite/src/workspace/crypto.rs | 2+-
Mcrates/storage_sqlite/src/workspace/operation.rs | 17++++++++++++++---
Mcrates/storage_sqlite/src/workspace/tests/mod.rs | 4++--
Mcrates/storage_sqlite/src/workspace/tests/operation_records.rs | 6+++++-
Mcrates/storage_sqlite/src/workspace/worker.rs | 4++--
Mcrates/storage_sqlite/tests/workspace_admission.rs | 176++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
15 files changed, 389 insertions(+), 32 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -230,6 +230,12 @@ impl serde_core::ser::Serialize for radroots_domain::GrantId pub fn radroots_domain::GrantId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::GrantId pub fn radroots_domain::GrantId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::IssuanceWindow +impl radroots_domain::IssuanceWindow +pub fn radroots_domain::IssuanceWindow::capture(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError> +pub const fn radroots_domain::IssuanceWindow::first_issue_not_after(self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::IssuanceWindow::new(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError> +pub const fn radroots_domain::IssuanceWindow::prepared_at(self) -> radroots_domain::UnixSeconds pub struct radroots_domain::MessageId(_) impl radroots_domain::MessageId pub const fn radroots_domain::MessageId::as_bytes(&self) -> &[u8; 32] @@ -400,3 +406,4 @@ impl serde_core::ser::Serialize for radroots_domain::WorkspaceId pub fn radroots_domain::WorkspaceId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::WorkspaceId pub fn radroots_domain::WorkspaceId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub const radroots_domain::FIRST_ISSUANCE_MAX_SECONDS: u64 diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -797,8 +797,9 @@ pub const fn radroots_storage::command::CommitAttempt::transaction_id(self) -> c pub const fn radroots_storage::command::CommitAttempt::workspace_id(self) -> radroots_domain::identifier::WorkspaceId pub struct radroots_storage::command::PreparedOperation impl radroots_storage::command::PreparedOperation -pub fn radroots_storage::command::PreparedOperation::from_committed_store(radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::context::Sequence) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::PreparedOperation::from_committed_store(radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::context::Sequence, radroots_domain::issuance::IssuanceWindow) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage::command::PreparedOperation::identity(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::command::PreparedOperation::issuance_window(&self) -> radroots_domain::issuance::IssuanceWindow pub const fn radroots_storage::command::PreparedOperation::request(&self) -> &radroots_storage::command::AdmissionRequest pub const fn radroots_storage::command::PreparedOperation::revision(&self) -> radroots_domain::context::Sequence pub const fn radroots_storage::command::PreparedOperation::transaction_id(&self) -> radroots_domain::identifier::TransactionId diff --git a/contracts/execution/workspace.v1.json b/contracts/execution/workspace.v1.json @@ -1,7 +1,7 @@ { "schema_version": 1, "contract_id": "radroots.execution.workspace.v1", - "state": "native_buyer_chat_preparation_component_implemented", + "state": "native_buyer_preparation_window_implemented", "ownership": { "domain": "Validated actor, authority, checkpoint and captured-context descriptors; descriptors grant no rights", "execution": "Owned authenticated workspace session and opaque captured command context", @@ -63,7 +63,9 @@ "Independent canonical command and approval-intent vectors and closed shape/byte/depth refusals", "Actual inquiry commit/reopen/replay, original correlation, digest conflict, proof/revocation/deadline and transaction-time grant checks", "Actual SQLite statement failure/confirmed rollback, deferred-constraint commit failure/unknown latch, lost observer and bounded queue/drain", - "Protected operation-context substitution refusal and predecessor-schema byte preservation" + "Protected operation-context substitution refusal and predecessor-schema byte preservation", + "Exact retained preparation/issuance timing bounds and invalid restored-window refusal", + "Actual first-window expiry/clock rollback between checked observation and T0, plus replay/reopen preserving the original window" ], "remaining": [ "Complete operation receipts, authenticated reply/history and actual known-kind listing/chat T1/S/T2/D execution", @@ -72,7 +74,7 @@ "Actual browser/platform providers, generated bindings, coherent consumers and final acceptance" ], "implementation_claimed": true, - "implementation_scope": "Fresh protected local buyer attachment/context and actual inquiry Prepared admission/query only; no installed message, issuance/delivery, complete receipt, seller stock, remote pairing or general recovery qualification.", + "implementation_scope": "Fresh protected local buyer attachment/context and actual inquiry Prepared admission/query, including the retained checked preparation observation and fixed first-issue window. No installed message, issuance/delivery, complete receipt, seller stock, remote pairing or general recovery qualification.", "package_publication_authorized": false, "command_data": { "types": [ @@ -88,7 +90,7 @@ "private_buffers": "Zeroizing retained canonical command and decoded private text; borrowed raw private JSON during parsing" }, "prepared_journal": { - "schema_user_version": 2, + "schema_user_version": 3, "catalog": [ "workspace_grant", "operations", @@ -104,7 +106,10 @@ "known_failure": "No write was attempted, or actual rollback completed; commit/rollback uncertainty never becomes a known failure", "unavailable_history": "Reply parents and order expectations are refused until authenticated history is implemented", "approval": "Caller-provided approval descriptors are refused without a qualified protected consent origin", - "predecessor_schema": "Preserve and refuse the prior grant-only namespace; no implicit rewrite, deletion, re-enrollment or import", - "transaction_recheck": "The short transaction matches complete workspace/operation, participant/grant, command type/digest, original transaction, prepared phase/revision and exact retained protected bytes; matching ciphertext alone cannot hide changed indexed facts." + "predecessor_schema": "Preserve and refuse grant-only schema 1 and preparation-without-window schema 2; no inferred timestamp, implicit rewrite, deletion, re-enrollment or import.", + "transaction_recheck": "The short transaction matches complete workspace/operation, participant/grant, command type/digest, original transaction, prepared phase/revision and exact retained protected bytes; matching ciphertext alone cannot hide changed indexed facts.", + "protected_payload_schema": "radroots.workspace.operation.v2", + "preparation_observation": "Retain the actual checked grant-authentication clock observation before protected command preparation; this is distinct from the earlier captured attachment observation.", + "first_issuance_window": "Immutable exclusive deadline, at most 120 seconds after preparation and no later than captured authorization expiry. Transaction-time clock rollback or expiry blocks new preparation. Exact replay/reopen preserves the original window, including after expiry. Expiry never proves nonissuance." } } diff --git a/crates/domain/src/issuance.rs b/crates/domain/src/issuance.rs @@ -0,0 +1,52 @@ +use crate::{ContextError, UnixSeconds}; + +/// Maximum interval between checked preparation and first signing invocation. +pub const FIRST_ISSUANCE_MAX_SECONDS: u64 = 120; + +/// Validated retained timing data. This value observes no clock and grants no +/// permission to sign. Current authority and dispatch must be checked separately; +/// expiry never proves that an already dispatched request remained unissued. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct IssuanceWindow { + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, +} +impl IssuanceWindow { + /// Validates an explicitly retained, possibly stricter first-issue interval. + pub fn new( + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, + ) -> Result<Self, ContextError> { + if prepared_at.get() == 0 + || first_issue_not_after <= prepared_at + || first_issue_not_after.get() - prepared_at.get() > FIRST_ISSUANCE_MAX_SECONDS + { + return Err(ContextError::OutOfRange); + } + Ok(Self { + prepared_at, + first_issue_not_after, + }) + } + /// Captures the default interval using the host's checked observation and + /// exact authorization deadline. Neither input is independently trusted here. + pub fn capture( + prepared_at: UnixSeconds, + authorization_not_after: UnixSeconds, + ) -> Result<Self, ContextError> { + let ceiling = prepared_at + .get() + .checked_add(FIRST_ISSUANCE_MAX_SECONDS) + .ok_or(ContextError::OutOfRange)?; + let deadline = UnixSeconds::new(core::cmp::min(ceiling, authorization_not_after.get()))?; + Self::new(prepared_at, deadline) + } + /// Returns the original checked preparation observation. + pub const fn prepared_at(self) -> UnixSeconds { + self.prepared_at + } + /// Returns the exclusive first-issue bound; retries must never extend it. + pub const fn first_issue_not_after(self) -> UnixSeconds { + self.first_issue_not_after + } +} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -8,6 +8,7 @@ extern crate alloc; mod amount; mod context; mod identifier; +mod issuance; /// The identity-owned validated participant key; no second key type is defined. pub use radroots_identity::PublicKey; @@ -22,3 +23,4 @@ pub use identifier::{ IdentifierError, MessageId, OperationId, OrderId, RecordId, RouteDigest, SourceId, ThreadId, TransactionId, WorkspaceId, }; +pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; diff --git a/crates/domain/tests/issuance.rs b/crates/domain/tests/issuance.rs @@ -0,0 +1,40 @@ +use radroots_domain::{ContextError, FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow, UnixSeconds}; + +fn time(value: u64) -> UnixSeconds { + UnixSeconds::new(value).unwrap() +} + +#[test] +fn preparation_captures_exact_fixed_window_and_shorter_authorization() { + assert_eq!(FIRST_ISSUANCE_MAX_SECONDS, 120); + for (prepared, authorization, deadline) in [ + (100, 900, 220), + (100, 150, 150), + (100, 101, 101), + (253_402_300_798, 253_402_300_799, 253_402_300_799), + ] { + let window = IssuanceWindow::capture(time(prepared), time(authorization)).unwrap(); + assert_eq!(window.prepared_at(), time(prepared)); + assert_eq!(window.first_issue_not_after(), time(deadline)); + assert_eq!( + IssuanceWindow::new(time(prepared), time(deadline)).unwrap(), + window + ); + } +} + +#[test] +fn invalid_or_extended_retained_windows_are_refused_without_reading_a_clock() { + for (prepared, deadline) in [(0, 1), (100, 0), (100, 100), (100, 99), (100, 221)] { + assert_eq!( + IssuanceWindow::new(time(prepared), time(deadline)), + Err(ContextError::OutOfRange) + ); + } + for (prepared, deadline) in [(0, 100), (100, 0), (100, 100), (100, 99)] { + assert_eq!( + IssuanceWindow::capture(time(prepared), time(deadline)), + Err(ContextError::OutOfRange) + ); + } +} diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -4,7 +4,9 @@ use crate::workspace::{AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore}; use core::fmt; -use radroots_domain::{CommandDigest, OperationId, Sequence, TransactionId, WorkspaceId}; +use radroots_domain::{ + CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, WorkspaceId, +}; use radroots_protocol::command::CapturedChatCommand; use radroots_transport::BoxFuture; @@ -163,6 +165,7 @@ pub struct PreparedOperation { request: Box<AdmissionRequest>, transaction_id: TransactionId, revision: Sequence, + issuance_window: IssuanceWindow, } impl PreparedOperation { /// Validates a concrete store's structural report. The adapter must first @@ -171,14 +174,20 @@ impl PreparedOperation { request: AdmissionRequest, transaction_id: TransactionId, revision: Sequence, + issuance_window: IssuanceWindow, ) -> Result<Self, OperationError> { - if revision.get() == 0 { + if revision.get() == 0 + || issuance_window.prepared_at() < request.binding().observed_at() + || issuance_window.first_issue_not_after() > request.command().context().not_after() + || issuance_window.first_issue_not_after() > request.binding().expires_at() + { return Err(OperationError::RecoveryRequired); } Ok(Self { request: Box::new(request), transaction_id, revision, + issuance_window, }) } /// Borrows the captured original request, including its diagnostic correlation. @@ -193,6 +202,11 @@ impl PreparedOperation { pub const fn revision(&self) -> Sequence { self.revision } + /// Returns the original preparation observation and first-issue deadline. + /// It remains historical after expiry and never establishes nonissuance. + pub const fn issuance_window(&self) -> IssuanceWindow { + self.issuance_window + } /// Returns the exact retained identity/commitment anchor. pub fn identity(&self) -> CommitAttempt { let context = self.request.command().context(); diff --git a/crates/storage/tests/command.rs b/crates/storage/tests/command.rs @@ -43,6 +43,9 @@ fn binding() -> WorkspaceBinding { .unwrap() } fn request() -> AdmissionRequest { + request_until(150) +} +fn request_until(not_after: u64) -> AdmissionRequest { let binding = binding(); let input = binding.input(); let context = CommandContextData::new( @@ -53,7 +56,7 @@ fn request() -> AdmissionRequest { input.route_digest(), None, None, - UnixSeconds::new(150).unwrap(), + UnixSeconds::new(not_after).unwrap(), None, ) .unwrap(); @@ -72,6 +75,26 @@ fn request() -> AdmissionRequest { } #[test] +fn retained_window_cannot_precede_attachment_or_exceed_command_or_grant() { + for (prepared, deadline, authorization) in [(99, 150, 150), (100, 151, 150), (100, 201, 300)] { + let window = radroots_domain::IssuanceWindow::new( + UnixSeconds::new(prepared).unwrap(), + UnixSeconds::new(deadline).unwrap(), + ) + .unwrap(); + assert!(matches!( + PreparedOperation::from_committed_store( + request_until(authorization), + TransactionId::from_bytes([8; 32]), + Sequence::new(1).unwrap(), + window, + ), + Err(OperationError::RecoveryRequired) + )); + } +} + +#[test] fn structural_reports_preserve_full_original_anchor_without_minting_commit_proof() { let captured = request(); let digest = captured.command().digest(); @@ -81,12 +104,29 @@ fn structural_reports_preserve_full_original_anchor_without_minting_commit_proof let parsed = AdmissionRequest::from_protected_wire(binding, &wire).unwrap(); let transaction = TransactionId::from_bytes([8; 32]); assert!(matches!( - PreparedOperation::from_committed_store(request(), transaction, Sequence::new(0).unwrap()), + PreparedOperation::from_committed_store( + request(), + transaction, + Sequence::new(0).unwrap(), + radroots_domain::IssuanceWindow::capture( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(150).unwrap() + ) + .unwrap() + ), Err(OperationError::RecoveryRequired) )); - let reported = - PreparedOperation::from_committed_store(parsed, transaction, Sequence::new(1).unwrap()) - .unwrap(); + let reported = PreparedOperation::from_committed_store( + parsed, + transaction, + Sequence::new(1).unwrap(), + radroots_domain::IssuanceWindow::capture( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(150).unwrap(), + ) + .unwrap(), + ) + .unwrap(); let anchor = reported.identity(); assert_eq!(reported.transaction_id(), transaction); assert_eq!(reported.revision().get(), 1); diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -2,7 +2,7 @@ use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, fs::Namespace, operation, record::GrantRecord, worker, }; -use radroots_domain::{CommandDigest, OperationId, TransactionId}; +use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, TransactionId}; use radroots_storage::command::{ AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, }; @@ -22,7 +22,7 @@ impl Journal<'_> { &mut self, binding: &WorkspaceBinding, proof: &AttachmentProof, - ) -> Result<(GrantRecord, Vec<u8>), OperationError> { + ) -> Result<(GrantRecord, Vec<u8>, WorkspaceBinding), OperationError> { if *self.uncertain { return Err(OperationError::RecoveryRequired); } @@ -40,7 +40,7 @@ impl Journal<'_> { let current = record.authenticate(binding.input(), proof, self.clock.now()?)?; same_binding(binding, &current)?; self.namespace.validate()?; - Ok((record, protected)) + Ok((record, protected, current)) } pub(super) async fn admit( @@ -48,7 +48,7 @@ impl Journal<'_> { request: AdmissionRequest, proof: AttachmentProof, ) -> Result<AdmissionOutcome, OperationError> { - let (record, grant) = self.access(request.binding(), &proof).await?; + let (record, grant, observed) = self.access(request.binding(), &proof).await?; let context = request.command().context(); let workspace = context.workspace_id(); let operation_id = context.operation_id(); @@ -95,10 +95,15 @@ impl Journal<'_> { if context.approval().is_some() { return Err(OperationError::UnverifiedApproval); } + if observed.observed_at() < request.binding().observed_at() { + return Err(super::WorkspaceError::Unavailable.into()); + } + let window = IssuanceWindow::capture(observed.observed_at(), context.not_after()) + .map_err(|_| OperationError::DeadlineExceeded)?; let transaction_id = TransactionId::from_bytes(super::random()?); let anchor = CommitAttempt::new(workspace, operation_id, digest, Some(transaction_id)); // Encryption/provider work finishes before opening the write transaction. - let protected = operation::protect(&request, transaction_id, self.crypto).await?; + let protected = operation::protect(&request, transaction_id, window, self.crypto).await?; let mut transaction = self .connection .begin_with("BEGIN IMMEDIATE") @@ -116,7 +121,10 @@ impl Journal<'_> { self.clock, ) .await?; - if context.not_after() <= current.observed_at() + if current.observed_at() < window.prepared_at() { + return Err(super::WorkspaceError::Unavailable.into()); + } + if window.first_issue_not_after() <= current.observed_at() || context.not_after() > current.expires_at() { return Err(OperationError::DeadlineExceeded); @@ -140,6 +148,7 @@ impl Journal<'_> { request, transaction_id, radroots_domain::Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + window, )?, )) } @@ -151,7 +160,7 @@ impl Journal<'_> { digest: Option<CommandDigest>, proof: AttachmentProof, ) -> Result<Option<PreparedOperation>, OperationError> { - let (record, grant) = self.access(&binding, &proof).await?; + let (record, grant, _) = self.access(&binding, &proof).await?; let result = operation::read(self.connection, self.selected, operation_id, self.crypto).await?; if let Some((snapshot, _)) = &result { diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -187,7 +187,7 @@ fn operation_context( .map_err(|_| WorkspaceError::InvalidInput)?, EnvelopeSubject::parse("workspace_operation", format!("{workspace}{operation}")) .map_err(|_| WorkspaceError::InvalidInput)?, - PayloadSchemaId::parse("radroots.workspace.operation.v1") + PayloadSchemaId::parse("radroots.workspace.operation.v2") .map_err(|_| WorkspaceError::InvalidInput)?, )) } diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -1,7 +1,9 @@ //! Retained non-stock command preparation. No signing or delivery occurs here. use super::{AttachmentInput, WorkspaceBinding, crypto::WorkspaceCrypto}; -use radroots_domain::{CommandDigest, OperationId, Sequence, TransactionId, UnixSeconds}; +use radroots_domain::{ + CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds, +}; use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; use serde::{Deserialize, Serialize}; use sqlx::{Row, SqliteConnection}; @@ -21,6 +23,8 @@ struct Encoded<'a> { captured_observed_at: UnixSeconds, transaction_id: TransactionId, revision: Sequence, + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, command: &'a serde_json::value::RawValue, } #[derive(Deserialize)] @@ -34,6 +38,8 @@ struct Decoded<'a> { captured_observed_at: UnixSeconds, transaction_id: TransactionId, revision: Sequence, + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, #[serde(borrow)] command: &'a serde_json::value::RawValue, } @@ -41,11 +47,12 @@ struct Decoded<'a> { pub(super) async fn protect( request: &AdmissionRequest, transaction_id: TransactionId, + window: IssuanceWindow, crypto: &WorkspaceCrypto, ) -> Result<Vec<u8>, OperationError> { let binding = request.binding(); let encoded = Encoded { - version: 1, + version: 2, selection: binding.input(), principal: binding.principal_id(), grant_revision: binding.grant_revision(), @@ -53,6 +60,8 @@ pub(super) async fn protect( captured_observed_at: binding.observed_at(), transaction_id, revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + prepared_at: window.prepared_at(), + first_issue_not_after: window.first_issue_not_after(), command: serde_json::from_slice(request.command().protected_wire()) .map_err(|_| OperationError::InvalidCommand)?, }; @@ -109,7 +118,7 @@ pub(super) async fn read( let snapshot = plaintext.expose_secret(|bytes| { let decoded: Decoded<'_> = serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?; - if decoded.version != 1 + if decoded.version != 2 || decoded.revision.get() == 0 || phase != "prepared" || revision != 1 @@ -154,6 +163,8 @@ pub(super) async fn read( request, decoded.transaction_id, decoded.revision, + IssuanceWindow::new(decoded.prepared_at, decoded.first_issue_not_after) + .map_err(|_| OperationError::RecoveryRequired)?, )?; Ok::<_, OperationError>(snapshot) })?; diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -556,7 +556,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .await .unwrap(); let statement = match fault { - 0 => "PRAGMA user_version=3", + 0 => "PRAGMA user_version=4", 1 => "DELETE FROM workspace_grant", 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", @@ -602,7 +602,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .fetch_one(&mut connection) .await .unwrap(); - assert_eq!(version, if fault == 0 { 3 } else { 2 }); + assert_eq!(version, if fault == 0 { 4 } else { 3 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); if (3..=5).contains(&fault) { let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") diff --git a/crates/storage_sqlite/src/workspace/tests/operation_records.rs b/crates/storage_sqlite/src/workspace/tests/operation_records.rs @@ -72,7 +72,11 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj .unwrap(); let value: Value = opened.expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); for (pointer, replacement) in [ - ("/version", json!(2)), + ("/version", json!(3)), + ("/prepared_at", json!("0")), + ("/prepared_at", json!("99")), + ("/first_issue_not_after", json!("100")), + ("/first_issue_not_after", json!("151")), ("/revision", json!("0")), ("/revision", json!("2")), ("/selection/endpoint", json!("local://changed")), diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -357,7 +357,7 @@ async fn initialize( .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; - sqlx::query("PRAGMA user_version=2") + sqlx::query("PRAGMA user_version=3") .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -379,7 +379,7 @@ async fn initialize( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if version != 2 { + if version != 3 { return Err(WorkspaceError::RecoveryRequired); } let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=3 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 WHEN type='table' AND name='operations' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=3 THEN 1 ELSE 0 END FROM sqlite_schema") diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -133,13 +133,24 @@ impl Fixture { AttachmentProof, WorkspaceBinding, ) { + self.create_with_expiry(200).await + } + async fn create_with_expiry( + &self, + expiry: u64, + ) -> ( + Arc<NativeWorkspace>, + AttachmentInput, + AttachmentProof, + WorkspaceBinding, + ) { let (store, input, proof) = NativeWorkspace::initialize_local_outbox( &self.path, LocalOutboxConfig::new( key(), key(), "synthetic-device", - UnixSeconds::new(200).unwrap(), + UnixSeconds::new(expiry).unwrap(), ) .unwrap(), self.crypto(), @@ -179,6 +190,15 @@ fn copy(proof: &AttachmentProof) -> AttachmentProof { proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) } fn request(binding: &WorkspaceBinding, id: u8, text: &str, correlation: &str) -> AdmissionRequest { + request_until(binding, id, text, correlation, 150) +} +fn request_until( + binding: &WorkspaceBinding, + id: u8, + text: &str, + correlation: &str, + not_after: u64, +) -> AdmissionRequest { let input = binding.input(); let context = CommandContextData::new( OperationId::from_bytes([id; 32]), @@ -188,7 +208,7 @@ fn request(binding: &WorkspaceBinding, id: u8, text: &str, correlation: &str) -> input.route_digest(), None, None, - UnixSeconds::new(150).unwrap(), + UnixSeconds::new(not_after).unwrap(), Some(CorrelationId::new(correlation).unwrap()), ) .unwrap(); @@ -804,3 +824,155 @@ async fn bounded_admission_queue_refuses_overflow_and_drains_every_accepted_requ Err(OperationError::Workspace(WorkspaceError::Closed)) )); } + +#[tokio::test] +async fn retained_first_issue_window_never_restarts_on_reopen_or_replay() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_with_expiry(2000).await; + let original = committed( + store + .admit_command_and_hold( + request_until(&binding, 66, "fixed window", "one", 900), + copy(&proof), + ) + .await + .unwrap(), + ); + let anchor = original.identity(); + assert_eq!(original.issuance_window().prepared_at().get(), 100); + assert_eq!( + original.issuance_window().first_issue_not_after().get(), + 220 + ); + store.close().await.unwrap(); + fixture.clock.now.store(500, Ordering::SeqCst); + let reopened = fixture.reopen(input).await; + let recovered = reopened + .operation( + binding.clone(), + anchor.operation_id(), + Some(anchor.command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(recovered.issuance_window(), original.issuance_window()); + let replay = committed( + reopened + .admit_command_and_hold( + request_until(&binding, 66, "fixed window", "retry", 900), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(replay.identity(), anchor); + assert_eq!(replay.issuance_window(), original.issuance_window()); + let fresh = committed( + reopened + .admit_command_and_hold( + request_until(&binding, 67, "new operation", "new", 900), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(fresh.issuance_window().prepared_at().get(), 500); + assert_eq!(fresh.issuance_window().first_issue_not_after().get(), 620); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn predecessor_preparation_schema_marker_is_preserved_without_inferring_a_window() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + committed( + store + .admit_command_and_hold(request(&binding, 70, "retained", "one"), copy(&proof)) + .await + .unwrap(), + ); + store.close().await.unwrap(); + let mut database = fixture.database().await; + sqlx::query("PRAGMA user_version=2") + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + let path = fixture.path.join("execution_v1.sqlite"); + let before = std::fs::read(&path).unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + assert_eq!(std::fs::read(path).unwrap(), before); +} + +#[tokio::test] +async fn transaction_checks_first_window_expiry_and_clock_rollback_after_preparation() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create_with_expiry(2000).await; + for (id, changed_clock) in [(68, 220), (69, 90)] { + fixture.clock.now.store(100, Ordering::SeqCst); + let request = request_until(&binding, id, "clock boundary", "one", 900); + let (arrived, resume) = fixture.clock.arm(1); + let owner = store.clone(); + let secret = copy(&proof); + let task = tokio::spawn(async move { owner.admit_command_and_hold(request, secret).await }); + reached(arrived).await; + fixture.clock.now.store(changed_clock, Ordering::SeqCst); + resume.send(()).unwrap(); + let result = task.await.unwrap(); + if changed_clock == 220 { + assert!(matches!(result, Err(OperationError::DeadlineExceeded))); + } else { + assert!(matches!( + result, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + )); + } + fixture.clock.now.store(100, Ordering::SeqCst); + assert!( + store + .operation( + binding.clone(), + OperationId::from_bytes([id; 32]), + None, + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + } + store.close().await.unwrap(); +} + +#[tokio::test] +async fn new_preparation_refuses_clock_rollback_before_its_first_observation() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + fixture.clock.now.store(90, Ordering::SeqCst); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 71, "clock rollback", "one"), copy(&proof)) + .await, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + )); + fixture.clock.now.store(100, Ordering::SeqCst); + assert!( + store + .operation(binding, OperationId::from_bytes([71; 32]), None, proof) + .await + .unwrap() + .is_none() + ); + store.close().await.unwrap(); +}