lib

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

commit bb9f9bc50669e83048ff442845a873a413b4ad56
parent af36dd34fbc12bd56d20dcb938ff581b1699829e
Author: triesap <tyson@radroots.org>
Date:   Mon, 26 Oct 2026 17:14:48 +0000

execution: preserve bounded signer rejection diagnostics

- Return original rejection reasons and fingerprint coverage without raw bytes.
- Preserve peer installation before reporting a rejected self callback.
- Keep actual storage failures and stop delivery after uncertain installation.
- Verify native faults, original recovery, portable features and caller APIs.

Diffstat:
Mcontracts/api_baselines/radroots.txt | 12+++++++-----
Mcontracts/api_baselines/radroots_execution.txt | 26+++++++++++++++++++++-----
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 8++++++++
Mcrates/execution/README.md | 17+++++++++++++++++
Mcrates/execution/src/error.rs | 10++++++++++
Acrates/execution/src/failure.rs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/lib.rs | 7+++++++
Mcrates/execution/src/session/client_commands.rs | 29+++++++++++++++--------------
Mcrates/execution/src/session/client_commerce.rs | 20+++++++++++---------
Mcrates/execution/src/session/command.rs | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mcrates/execution/src/session/commerce_run.rs | 16++++++++++++++--
Mcrates/radroots/README.md | 10++++++++++
Mcrates/radroots/src/inbox.rs | 4++--
Mcrates/radroots/src/lib.rs | 1+
Mcrates/radroots/src/listings.rs | 4++--
Mcrates/radroots/src/native_commerce_tests.rs | 303++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/radroots/src/operations.rs | 2+-
Mcrates/radroots/src/orders.rs | 4++--
Mcrates/radroots/tests/package_boundary.rs | 3++-
Mcrates/radroots/tests/support/receipt_client.rs | 2+-
Mcrates/radroots/tests/support/receipt_workflow_faults.rs | 3++-
Mtools/xtask/src/architecture/decision_package.rs | 34++++++++++++++++++++++++++++++++++
22 files changed, 632 insertions(+), 84 deletions(-)

diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -10,6 +10,8 @@ pub use radroots::CommandError pub use radroots::Delivery pub use radroots::DeliveryObservation pub use radroots::Error +pub use radroots::ExecutionFailure +pub use radroots::ExecutionResult pub use radroots::Issuance pub use radroots::OperationContext pub use radroots::OperationId @@ -107,7 +109,7 @@ pub use radroots::inbox::InquireInput pub use radroots::inbox::ListingRevisionRef pub struct radroots::inbox::Inbox<'a> impl<'a> radroots::inbox::Inbox<'a> -pub async fn radroots::inbox::Inbox<'a>::inquire(&self, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::Result<radroots_execution::receipt::OperationReceipt<radroots_domain::message::ChatMessage>> +pub async fn radroots::inbox::Inbox<'a>::inquire(&self, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::ExecutionResult<radroots_execution::receipt::OperationReceipt<radroots_domain::message::ChatMessage>> pub mod radroots::knowledge pub use radroots::knowledge::AddressableRef pub use radroots::knowledge::KnowledgeClaim @@ -144,7 +146,7 @@ pub use radroots::listings::Listing pub use radroots::listings::PublishInput pub struct radroots::listings::Listings<'a> impl<'a> radroots::listings::Listings<'a> -pub async fn radroots::listings::Listings<'a>::publish(&self, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::Result<radroots_execution::receipt::OperationReceipt<radroots_domain::listing::view::Listing>> +pub async fn radroots::listings::Listings<'a>::publish(&self, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::ExecutionResult<radroots_execution::receipt::OperationReceipt<radroots_domain::listing::view::Listing>> pub mod radroots::operations pub struct radroots::operations::Operations<'a> impl<'a> radroots::operations::Operations<'a> @@ -152,7 +154,7 @@ pub async fn radroots::operations::Operations<'a>::abort_proven_unissued(&self, pub async fn radroots::operations::Operations<'a>::get(&self, radroots_domain::identifier::OperationId) -> radroots_execution::Result<core::option::Option<radroots_execution::receipt::OperationStatus>> pub async fn radroots::operations::Operations<'a>::get_matching(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<core::option::Option<radroots_execution::receipt::OperationStatus>> pub async fn radroots::operations::Operations<'a>::preparation_abort(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<core::option::Option<radroots_storage::inventory::abort::StockAbortReceipt>> -pub async fn radroots::operations::Operations<'a>::resume(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<radroots_execution::receipt::OperationStatus> +pub async fn radroots::operations::Operations<'a>::resume(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::ExecutionResult<radroots_execution::receipt::OperationStatus> pub mod radroots::orders pub use radroots::orders::AcceptOrderInput pub use radroots::orders::AcceptanceRecipient @@ -160,9 +162,9 @@ pub use radroots::orders::AcceptanceStatus pub use radroots::orders::InstalledAcceptance pub struct radroots::orders::Orders<'a> impl<'a> radroots::orders::Orders<'a> -pub async fn radroots::orders::Orders<'a>::accept(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots::orders::Orders<'a>::accept(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots::orders::Orders<'a>::acceptance_status(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> -pub async fn radroots::orders::Orders<'a>::resume_acceptance(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots::orders::Orders<'a>::resume_acceptance(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub mod radroots::signing pub use radroots::signing::ArtifactRole pub use radroots::signing::AuthorizationHeader diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -105,13 +105,13 @@ pub async fn radroots_execution::session::ClientSession<H>::stock_option_mapping pub async fn radroots_execution::session::ClientSession<H>::stock_pool(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId) -> radroots_execution::Result<core::option::Option<radroots_domain::stock::PoolView>> pub async fn radroots_execution::session::ClientSession<H>::stock_preparation_abort(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<core::option::Option<radroots_storage::inventory::abort::StockAbortReceipt>> impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> -pub async fn radroots_execution::session::ClientSession<H>::accept_stock_order(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> -pub async fn radroots_execution::session::ClientSession<H>::resume_stock_acceptance(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots_execution::session::ClientSession<H>::accept_stock_order(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots_execution::session::ClientSession<H>::resume_stock_acceptance(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots_execution::session::ClientSession<H>::stock_acceptance_status(&self, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> -pub async fn radroots_execution::session::ClientSession<H>::inquire(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>> -pub async fn radroots_execution::session::ClientSession<H>::publish_listing(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::listing::view::Listing>> -pub async fn radroots_execution::session::ClientSession<H>::resume_command(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, &radroots_execution::workspace::WorkspaceSession, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<radroots_execution::OperationStatus> +pub async fn radroots_execution::session::ClientSession<H>::inquire(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::ExecutionResult<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>> +pub async fn radroots_execution::session::ClientSession<H>::publish_listing(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::ExecutionResult<radroots_execution::OperationReceipt<radroots_domain::listing::view::Listing>> +pub async fn radroots_execution::session::ClientSession<H>::resume_command(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, &radroots_execution::workspace::WorkspaceSession, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::ExecutionResult<radroots_execution::OperationStatus> impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H> pub async fn radroots_execution::session::ClientSession<H>::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::SignerSession> pub async fn radroots_execution::session::ClientSession<H>::attach_workspace(&self, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceStore>, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> @@ -352,9 +352,24 @@ pub const fn radroots_execution::Error::detail(self) -> core::option::Option<rad pub const fn radroots_execution::Error::new(radroots_execution::Code, radroots_execution::OperationContext, radroots_execution::RetryClass, core::option::Option<radroots_execution::Detail>) -> core::result::Result<Self, radroots_execution::InvalidErrorContext> pub const fn radroots_execution::Error::operation(radroots_storage::command::OperationError, radroots_execution::OperationContext) -> Self pub const fn radroots_execution::Error::retry(self) -> radroots_execution::RetryClass +impl core::convert::From<radroots_execution::Error> for radroots_execution::ExecutionFailure +pub fn radroots_execution::ExecutionFailure::from(radroots_execution::Error) -> Self impl core::error::Error for radroots_execution::Error impl core::fmt::Display for radroots_execution::Error pub fn radroots_execution::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_execution::ExecutionFailure +impl radroots_execution::ExecutionFailure +pub const fn radroots_execution::ExecutionFailure::code(self) -> radroots_execution::Code +pub const fn radroots_execution::ExecutionFailure::context(self) -> radroots_execution::OperationContext +pub const fn radroots_execution::ExecutionFailure::detail(self) -> core::option::Option<radroots_execution::Detail> +pub const fn radroots_execution::ExecutionFailure::error(self) -> radroots_execution::Error +pub const fn radroots_execution::ExecutionFailure::retry(self) -> radroots_execution::RetryClass +pub const fn radroots_execution::ExecutionFailure::signer_rejection(self) -> core::option::Option<radroots_signing::issuance::RejectedArtifact> +impl core::convert::From<radroots_execution::Error> for radroots_execution::ExecutionFailure +pub fn radroots_execution::ExecutionFailure::from(radroots_execution::Error) -> Self +impl core::error::Error for radroots_execution::ExecutionFailure +impl core::fmt::Display for radroots_execution::ExecutionFailure +pub fn radroots_execution::ExecutionFailure::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_execution::OperationContext impl radroots_execution::OperationContext pub const fn radroots_execution::OperationContext::admission(self) -> radroots_execution::Admission @@ -401,5 +416,6 @@ pub const fn radroots_execution::OperationReceipt<T>::wait_termination(&self) -> pub fn radroots_execution::OperationReceipt<T>::with_wait_termination(self, radroots_execution::WaitTermination) -> Self impl<T> core::fmt::Debug for radroots_execution::OperationReceipt<T> pub fn radroots_execution::OperationReceipt<T>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub type radroots_execution::ExecutionResult<T> = core::result::Result<T, radroots_execution::ExecutionFailure> pub type radroots_execution::OperationStatus = radroots_execution::OperationReceipt<radroots_execution::OperationValue> pub type radroots_execution::Result<T> = core::result::Result<T, radroots_execution::Error> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -246,6 +246,14 @@ "ordinary_peer_installed_before_self_work": true, "ordinary_accepted_task_survives_observer_loss": true, "ordinary_obtained_owned_before_descriptor_conversion": true, + "rejected_signer_error": "SignerTampering", + "effectful_command_result": "ExecutionResult", + "common_error_max_bytes": 64, + "execution_failure_max_bytes": 128, + "rejected_signer_metadata_owner": "radroots_signing.issuance.RejectedArtifact", + "rejected_signer_report_is_nonissuance": false, + "generic_peer_installed_before_rejected_self_return": true, + "unknown_installation_blocks_delivery": true, "ordinary_existing_claim_grants_first_dispatch": false, "ordinary_replay_requires_original_policy_and_current_permit": true, "ordinary_acceptance_implies_delivery": false, diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -227,3 +227,20 @@ and close retains callback roots through settlement and durable capture. Query facts keep preparation, recipient evidence, installation and actual abort separate. This path performs no outer wrapping, relay publication, stock release or proof of original nonissuance; full commerce/accounting closure remains open. + +Observed rejected signer output returns `SignerTampering` with the original +confirmed operation identity. Effectful commands return `ExecutionResult`; +its allocation-free Copy `ExecutionFailure` retains the compact primitive Error +plus optional fixed Signing rejection through `signer_rejection()`, including +exact prefix coverage. The primitive Error keeps its 64-byte budget and the +separate command failure is bounded to 128 bytes; neither +failure type owns an untrusted raw payload. Ordinary acceptance +and the generic chat/listing loop stop further issuance on rejection. Already +captured peer evidence remains retained and matching installation completes +before reporting a self-copy rejection. A later installation failure preserves +its actual error code together with signer diagnostics and manual recovery. +Unknown installation stops delivery. These diagnostics are caller observations, +not durable forensic records, authenticated business output or proof that the +original signer never issued. Missing/unsupported/uncertain outcomes keep their +existing conservative claims; no rejection authorizes another first dispatch, +stock release or renewed deadline. diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -190,9 +190,19 @@ pub struct Error { retry: RetryClass, detail: Option<Detail>, } +const _: () = assert!(core::mem::size_of::<Error>() <= 64); impl Error { #[cfg(feature = "workspace_session")] + pub(crate) const fn signer_tampering(operation: OperationId) -> Self { + Self { + code: Code::SignerTampering, + context: OperationContext::retained(operation), + retry: RetryClass::ManualReconciliation, + detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Conflict)), + } + } + #[cfg(feature = "workspace_session")] pub(crate) const fn with_context(mut self, context: OperationContext) -> Self { self.context = context; self diff --git a/crates/execution/src/failure.rs b/crates/execution/src/failure.rs @@ -0,0 +1,76 @@ +//! Bounded command failure diagnostics separate from compact resource errors. +use crate::{Code, Detail, Error, OperationContext, RetryClass}; +use core::fmt; +use radroots_signing::issuance::RejectedArtifact; + +/// Allocation-free command failure. The primitive Error retains its 64-byte +/// contract; this separate Copy value can also retain fixed rejection metadata. +/// It owns no untrusted raw signer payload, dynamic message or backend cause. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ExecutionFailure { + error: Error, + rejection: Option<RejectedArtifact>, +} +const _: () = assert!(core::mem::size_of::<ExecutionFailure>() <= 128); +impl From<Error> for ExecutionFailure { + fn from(error: Error) -> Self { + Self { + error, + rejection: None, + } + } +} +impl ExecutionFailure { + /// Primitive compact diagnostic; it supplies no business/nonissuance proof. + pub const fn error(self) -> Error { + self.error + } + /// Original fixed diagnostic code, including actual storage failures. + pub const fn code(self) -> Code { + self.error.code() + } + /// Original reported operation identity and admission observation. + pub const fn context(self) -> OperationContext { + self.error.context() + } + /// Conservative original-operation continuation requirement. + pub const fn retry(self) -> RetryClass { + self.error.retry() + } + /// Optional fixed redacted diagnostic categories. + pub const fn detail(self) -> Option<Detail> { + self.error.detail() + } + /// Actual fixed signer rejection and optional exact fingerprint coverage. + /// This is caller diagnostic data, never authenticated business evidence. + pub const fn signer_rejection(self) -> Option<RejectedArtifact> { + self.rejection + } + #[cfg(feature = "workspace_session")] + pub(crate) const fn rejected( + operation: radroots_domain::OperationId, + rejection: RejectedArtifact, + ) -> Self { + Self { + error: Error::signer_tampering(operation), + rejection: Some(rejection), + } + } + #[cfg(feature = "workspace_session")] + pub(crate) fn host_after_rejection( + error: radroots_storage::command::OperationError, + operation: radroots_domain::OperationId, + rejection: RejectedArtifact, + ) -> Self { + Self { + error: Error::capture_pending(error, OperationContext::retained(operation)), + rejection: Some(rejection), + } + } +} +impl fmt::Display for ExecutionFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.error.fmt(f) + } +} +impl core::error::Error for ExecutionFailure {} diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -5,6 +5,13 @@ mod diagnostic; mod error; +#[cfg(feature = "signer_session")] +mod failure; +#[cfg(feature = "signer_session")] +pub use failure::ExecutionFailure; +/// Effectful command results, including optional bounded signer diagnostics. +#[cfg(feature = "signer_session")] +pub type ExecutionResult<T> = core::result::Result<T, ExecutionFailure>; extern crate alloc; mod receipt; pub use receipt::{ diff --git a/crates/execution/src/session/client_commands.rs b/crates/execution/src/session/client_commands.rs @@ -30,7 +30,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { scope: &WorkspaceSession, operation: OperationId, expected: Option<CommandDigest>, - ) -> crate::Result<OperationStatus> { + ) -> crate::ExecutionResult<OperationStatus> { let proposed = OperationContext::proposed(Some(operation)); let permit = self .session @@ -46,7 +46,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if !scopes.iter().any(|owned| owned.same_scope(scope)) { - return Err(Error::operation(OperationError::Unauthorized, proposed)); + return Err(Error::operation(OperationError::Unauthorized, proposed).into()); } } let (binding, proof) = scope @@ -101,14 +101,14 @@ impl<H: SessionHost + 'static> ClientSession<H> { crate::session::command::RunMode::Resume, ) .await - .map_err(|error| Error::operation(error, retained))?; + .map_err(|error| error.into_failure(operation))?; let snapshot = journal .operation_snapshot(binding, operation, Some(digest), proof) .await .map_err(|error| Error::operation(error, retained))? .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; OperationStatus::try_from_snapshot(&snapshot) - .map_err(|error| Error::operation(error, retained)) + .map_err(|error| Error::operation(error, retained).into()) } .await; let _ = reply.send(result); @@ -118,7 +118,8 @@ impl<H: SessionHost + 'static> ClientSession<H> { Err(Error::operation( OperationError::RecoveryRequired, OperationContext::admission_unknown(operation), - )) + ) + .into()) }) } /// Captures and durably admits one inquiry through the configured journal. @@ -130,7 +131,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { journal: Shared<dyn OperationJournal>, context: CommandContext, input: InquireInput, - ) -> crate::Result<OperationReceipt<ChatMessage>> { + ) -> crate::ExecutionResult<OperationReceipt<ChatMessage>> { self.submit_command( journal, context, @@ -146,7 +147,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { journal: Shared<dyn OperationJournal>, context: CommandContext, input: PublishInput, - ) -> crate::Result<OperationReceipt<Listing>> { + ) -> crate::ExecutionResult<OperationReceipt<Listing>> { self.submit_command( journal, context, @@ -161,7 +162,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { context: CommandContext, capture: F, project: ReceiptProjection<T>, - ) -> crate::Result<OperationReceipt<T>> + ) -> crate::ExecutionResult<OperationReceipt<T>> where F: FnOnce(radroots_domain::CommandContextData) -> Result<CapturedCommand, CommandError>, { @@ -189,7 +190,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if !scopes.iter().any(|scope| scope.owns_context(&context)) { - return Err(Error::operation(OperationError::Unauthorized, proposed)); + return Err(Error::operation(OperationError::Unauthorized, proposed).into()); } } let (binding, proof) = context @@ -225,7 +226,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .map_err(|error| error.with_context(proposed))?; observed .await - .unwrap_or_else(|_| Err(Error::admission_uncertain(operation))) + .unwrap_or_else(|_| Err(Error::admission_uncertain(operation).into())) } else { execute_command( journal, @@ -291,7 +292,7 @@ async fn execute_command<T: HostBound + 'static>( runtime: Option<Shared<CommandRuntime>>, resources: SigningResources, project: ReceiptProjection<T>, -) -> crate::Result<OperationReceipt<T>> { +) -> crate::ExecutionResult<OperationReceipt<T>> { let operation = request.command().context().operation_id(); let proposed = OperationContext::proposed(Some(operation)); resources @@ -312,7 +313,7 @@ async fn execute_command<T: HostBound + 'static>( .await .map_err(|error| Error::operation(error, proposed))?; match result { - AdmissionOutcome::Unknown(_) => Err(Error::admission_uncertain(operation)), + AdmissionOutcome::Unknown(_) => Err(Error::admission_uncertain(operation).into()), AdmissionOutcome::Committed(prepared) => { let retained = OperationContext::retained(operation); if let Some(runtime) = runtime { @@ -325,14 +326,14 @@ async fn execute_command<T: HostBound + 'static>( crate::session::command::RunMode::Command, ) .await - .map_err(|error| Error::operation(error, retained))?; + .map_err(|error| error.into_failure(operation))?; } let snapshot = journal .operation_snapshot(binding, operation, Some(digest), query_proof) .await .map_err(|error| Error::operation(error, retained))? .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; - project(&snapshot).map_err(|error| Error::operation(error, retained)) + project(&snapshot).map_err(|error| Error::operation(error, retained).into()) } } } diff --git a/crates/execution/src/session/client_commerce.rs b/crates/execution/src/session/client_commerce.rs @@ -38,13 +38,14 @@ impl<H: SessionHost + 'static> ClientSession<H> { sources: StockSourceCheckpointRef, listings: StockListingCheckpointRef, input: AcceptOrderInput, - ) -> crate::Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { let operation = context.data().operation_id(); if !scope.owns_context(&context) { return Err(Error::operation( OperationError::Unauthorized, OperationContext::proposed(Some(operation)), - )); + ) + .into()); } self.submit_acceptance( inventory, @@ -88,7 +89,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { minimum: InventoryCheckpointRef, operation: OperationId, digest: CommandDigest, - ) -> crate::Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { self.submit_acceptance( inventory, store, @@ -149,7 +150,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { (AcceptanceSelection, Option<StockAcceptanceRequest>), OperationError, >, - ) -> crate::Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { let proposed = OperationContext::proposed(Some(operation)); if matches!(&mode, RunMode::Command) { self.stock_captures @@ -167,7 +168,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if !scopes.iter().any(|v| v.same_scope(scope)) { - return Err(Error::operation(OperationError::Unauthorized, proposed)); + return Err(Error::operation(OperationError::Unauthorized, proposed).into()); } } let host = self @@ -209,7 +210,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .map_err(|e| Error::operation(e, proposed))? { StockAcceptanceOutcome::Unknown(_) => { - return Err(Error::admission_uncertain(operation)); + return Err(Error::admission_uncertain(operation).into()); } StockAcceptanceOutcome::Prepared(value) if value.attempt().workspace_id() @@ -227,7 +228,8 @@ impl<H: SessionHost + 'static> ClientSession<H> { return Err(Error::operation( OperationError::RecoveryRequired, OperationContext::admission_unknown(operation), - )); + ) + .into()); } } } @@ -242,7 +244,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .await .map_err(|e| Error::operation(e, retained))?; crate::session::commerce::observe(&selection, view.as_ref()) - .map_err(|e| Error::operation(e, retained)) + .map_err(|e| Error::operation(e, retained).into()) } } .await; @@ -251,6 +253,6 @@ impl<H: SessionHost + 'static> ClientSession<H> { .map_err(|e| e.with_context(proposed))?; observed .await - .unwrap_or_else(|_| Err(Error::admission_uncertain(operation))) + .unwrap_or_else(|_| Err(Error::admission_uncertain(operation).into())) } } diff --git a/crates/execution/src/session/command.rs b/crates/execution/src/session/command.rs @@ -15,7 +15,7 @@ use radroots_protocol::{ plan::{CapturedSigningPlan, SigningTarget}, }; use radroots_signing::{ - issuance::{OutcomeKind, SigningIntent}, + issuance::{OutcomeKind, RejectedArtifact, SigningIntent}, provider::{PrivateCiphertext, PrivateText, ProviderCall}, request::CancellationSignal, }; @@ -107,6 +107,32 @@ pub(super) enum RunMode { Command, Resume, } +pub(super) enum CommandFailure { + Host(OperationError, Option<RejectedArtifact>), + Capture(OperationError), + Rejected(RejectedArtifact), +} +impl From<OperationError> for CommandFailure { + fn from(error: OperationError) -> Self { + Self::Host(error, None) + } +} +impl CommandFailure { + pub(super) fn into_failure( + self, + operation: radroots_domain::OperationId, + ) -> crate::ExecutionFailure { + let context = crate::OperationContext::retained(operation); + match self { + Self::Host(error, Some(rejected)) => { + crate::ExecutionFailure::host_after_rejection(error, operation, rejected) + } + Self::Host(error, None) => crate::Error::operation(error, context).into(), + Self::Capture(error) => crate::Error::capture_pending(error, context).into(), + Self::Rejected(rejected) => crate::ExecutionFailure::rejected(operation, rejected), + } + } +} impl CommandRuntime { /// Owns explicit IO without performing effects or starting a runtime. pub fn new(io: Shared<dyn CommandIo>) -> Self { @@ -208,7 +234,7 @@ impl CommandRuntime { proof: &AttachmentProof, resources: SigningResources, mode: RunMode, - ) -> Result<(), OperationError> { + ) -> Result<(), CommandFailure> { if !self.io.enabled() { return Ok(()); } @@ -231,42 +257,62 @@ impl CommandRuntime { .await? { PlanBindingOutcome::Committed(bound) => bound, - PlanBindingOutcome::Unknown(_) => return Err(OperationError::RecoveryRequired), + PlanBindingOutcome::Unknown(_) => { + return Err(OperationError::RecoveryRequired.into()); + } } } }; - self.issue( - journal.clone(), - &bound, - proof, - signer.as_ref(), - resources.lease.clone(), - &resources.stock_captures, - ) - .await?; - let snapshot = journal - .operation_snapshot(binding.clone(), operation, Some(digest), copy(proof)?) - .await? - .ok_or(OperationError::RecoveryRequired)?; - if snapshot - .artifacts() - .iter() - .any(|recipient| recipient.obtained().is_some()) - { - journal - .install_transition_and_outbox( - InstallationRequest::new( - binding.clone(), - operation, - digest, - *bound.plan().digest(), - ), - copy(proof)?, - ) - .await?; + let rejected = self + .issue( + journal.clone(), + &bound, + proof, + signer.as_ref(), + resources.lease.clone(), + &resources.stock_captures, + ) + .await?; + let installation: Result<(), OperationError> = async { + let snapshot = journal + .operation_snapshot(binding.clone(), operation, Some(digest), copy(proof)?) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if snapshot + .artifacts() + .iter() + .any(|recipient| recipient.obtained().is_some()) + { + let outcome = journal + .install_transition_and_outbox( + InstallationRequest::new( + binding.clone(), + operation, + digest, + *bound.plan().digest(), + ), + copy(proof)?, + ) + .await?; + if matches!( + outcome, + radroots_storage::command::InstallationOutcome::Unknown(_) + ) { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } + .await; + if let Err(error) = installation { + return Err(CommandFailure::Host(error, rejected)); + } + if let Some(rejected) = rejected { + return Err(CommandFailure::Rejected(rejected)); } self.deliver(journal, &bound, proof, resources.lease, mode) .await + .map_err(Into::into) } async fn plan( &self, @@ -372,7 +418,7 @@ impl CommandRuntime { signer: Option<&SignerSession>, lease: Shared<dyn HostBound>, stock_captures: &super::stock_evidence::Owner, - ) -> Result<(), OperationError> { + ) -> Result<Option<RejectedArtifact>, CommandFailure> { let prepared = bound.prepared(); let binding = prepared.request().binding(); let targets = match bound.plan() { @@ -414,7 +460,7 @@ impl CommandRuntime { stock_captures.ensure_ready()?; let attempt = match journal.claim_attempt(select(), copy(proof)?).await { Err(OperationError::DeadlineExceeded) => continue, - Err(error) => return Err(error), + Err(error) => return Err(error.into()), Ok(outcome) => match outcome { ClaimAttemptOutcome::Claimed(attempt) => attempt, ClaimAttemptOutcome::Retained(_) | ClaimAttemptOutcome::Unknown(_) => continue, @@ -437,11 +483,14 @@ impl CommandRuntime { ) .map_err(|_| OperationError::InvalidCommand)?; if intent.binding() != attempt.binding() { - return Err(OperationError::RecoveryRequired); + return Err(OperationError::RecoveryRequired.into()); } stock_captures.ensure_ready()?; let outcome = signer.sign_exact(intent).await; let (_, kind) = outcome.into_parts(); + if let OutcomeKind::Rejected(rejected) = kind { + return Ok(Some(rejected)); + } if let OutcomeKind::Obtained(artifact) = kind { let evidence = artifact.with_json(|raw| { ArtifactEvidence::verify(&attempt, raw, artifact.observed_at_unix_ms()) @@ -460,16 +509,16 @@ impl CommandRuntime { match journal .capture_evidence(binding.input().clone(), &entry.proof, &entry.evidence) .await - .map_err(|_| OperationError::RecoveryRequired)? + .map_err(CommandFailure::Capture)? { EvidenceCaptureOutcome::Committed(_) => self.remove(&entry), EvidenceCaptureOutcome::Unknown(_) => { - return Err(OperationError::RecoveryRequired); + return Err(CommandFailure::Capture(OperationError::RecoveryRequired)); } } } } - Ok(()) + Ok(None) } async fn deliver( &self, diff --git a/crates/execution/src/session/commerce_run.rs b/crates/execution/src/session/commerce_run.rs @@ -142,9 +142,9 @@ impl CommandRuntime { proof: &AttachmentProof, resources: SigningResources, mode: RunMode, - ) -> crate::Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { let retained = OperationContext::retained(selection.operation); - let fail = |e| Error::operation(e, retained); + let fail = |e| crate::ExecutionFailure::from(Error::operation(e, retained)); let mut snapshot = store .snapshot(selection.clone(), proof) .await @@ -282,6 +282,12 @@ impl CommandRuntime { } match signer.recover_exact(request).await.into_parts().1 { ExactRecoveryKind::Obtained(artifact) => Some((artifact, report)), + ExactRecoveryKind::Rejected(rejected) => { + return Err(crate::ExecutionFailure::rejected( + selection.operation, + rejected, + )); + } _ => None, } } @@ -315,6 +321,12 @@ impl CommandRuntime { resources.stock_captures.ensure_ready().map_err(fail)?; match signer.sign_exact(intent).await.into_parts().1 { OutcomeKind::Obtained(artifact) => Some((artifact, report)), + OutcomeKind::Rejected(rejected) => { + return Err(crate::ExecutionFailure::rejected( + selection.operation, + rejected, + )); + } _ => None, } } diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -136,6 +136,16 @@ discard accepted work or obtained material. Application migrations, full order transitions/accounting, original negative reconciliation and final qualification remain separate required work. +Effectful commands return `ExecutionResult` with a bounded allocation-free +`ExecutionFailure`; resource and query errors keep the compact `Error`. +Rejected signer callbacks return `SignerTampering` and bounded original +`error.signer_rejection()` metadata. This contains a fixed reason and optional +digest with its actual coverage, with no raw signer payload. Inspect the original +operation separately: a peer commitment may already be installed while self +history remains unresolved. A later storage failure retains its actual code and +the same signer diagnostic. Rejection is no original nonissuance or stock-release +proof, and caller diagnostics are not durable forensic storage. + `radroots::domain` provides exact decimals and distinct order, thread, workspace, executor and operation identities. `radroots::OperationId` is the 256-bit retained identity. These values alone perform no authorization or transaction. diff --git a/crates/radroots/src/inbox.rs b/crates/radroots/src/inbox.rs @@ -1,5 +1,5 @@ //! Private inquiry commands through the client's actual protected journal. -use crate::{Client, CommandContext, OperationReceipt, Result}; +use crate::{Client, CommandContext, OperationReceipt}; use radroots_domain::ChatMessage; pub use radroots_execution::inbox::{InquireInput, ListingRevisionRef}; @@ -18,7 +18,7 @@ impl<'a> Inbox<'a> { &self, context: CommandContext, input: InquireInput, - ) -> Result<OperationReceipt<ChatMessage>> { + ) -> crate::ExecutionResult<OperationReceipt<ChatMessage>> { self.client .session .inquire(self.client.journal()?, context, input) diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -43,5 +43,6 @@ pub use radroots_execution::{ TargetObservation, WaitTermination, }; pub use radroots_execution::{Error, Result}; +pub use radroots_execution::{ExecutionFailure, ExecutionResult}; pub use radroots_protocol::command::CommandError; pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof}; diff --git a/crates/radroots/src/listings.rs b/crates/radroots/src/listings.rs @@ -1,5 +1,5 @@ //! Initial public listing commands through the shared protected execution owner. -use crate::{Client, CommandContext, OperationReceipt, Result}; +use crate::{Client, CommandContext, OperationReceipt}; pub use radroots_domain::listing::Listing; pub use radroots_protocol::listing::PublishInput; @@ -17,7 +17,7 @@ impl<'a> Listings<'a> { &self, context: CommandContext, input: PublishInput, - ) -> Result<OperationReceipt<Listing>> { + ) -> crate::ExecutionResult<OperationReceipt<Listing>> { self.client .session .publish_listing(self.client.journal()?, context, input) diff --git a/crates/radroots/src/native_commerce_tests.rs b/crates/radroots/src/native_commerce_tests.rs @@ -81,6 +81,10 @@ impl WorkspaceClock for Clock { } } struct Control { + pause_rejected: AtomicBool, + tamper_recovery: AtomicBool, + tamper_self: AtomicBool, + rejected: std::sync::Mutex<Option<radroots_signing::issuance::RejectedArtifact>>, recovery_supported: AtomicBool, signs: AtomicUsize, recoveries: AtomicUsize, @@ -92,6 +96,10 @@ struct Control { impl Control { fn new() -> Self { Self { + pause_rejected: AtomicBool::new(false), + tamper_recovery: AtomicBool::new(false), + tamper_self: AtomicBool::new(false), + rejected: std::sync::Mutex::new(None), recovery_supported: AtomicBool::new(true), signs: AtomicUsize::new(0), recoveries: AtomicUsize::new(0), @@ -149,6 +157,28 @@ impl ParticipantProvider for Provider { return SigningOutcome::not_dispatched(intent.binding(), ProviderError::Cancelled); } let result = self.inner.sign_exact(intent).await; + if is_self && self.control.tamper_self.load(Ordering::SeqCst) { + let foreign = radroots_signing::issuance::IntentBinding::from_components( + OperationId::from_bytes([0xa1; 32]), + [0xa2; 32], + [0xa3; 32], + radroots_signing::issuance::ArtifactRole::BusinessSeal, + Some(self.inner.public_key()), + NonZeroU64::new(230000).unwrap(), + ) + .unwrap(); + let rejected = result.enforce_binding(foreign); + let radroots_signing::issuance::OutcomeKind::Rejected(metadata) = rejected.kind() + else { + panic!("actual artifact must retain bounded mismatch metadata") + }; + *self.control.rejected.lock().unwrap() = Some(*metadata); + if self.control.pause_rejected.swap(false, Ordering::SeqCst) { + self.control.entered.notify_one(); + self.control.release.notified().await; + } + return rejected; + } if !is_self && self.control.pause_peer.swap(false, Ordering::SeqCst) { self.control.entered.notify_one(); self.control.release.notified().await; @@ -159,7 +189,27 @@ impl ParticipantProvider for Provider { fn recover_exact(&self, request: ExactRecoveryRequest) -> BoxFuture<'_, ExactRecoveryOutcome> { Box::pin(async move { self.control.recoveries.fetch_add(1, Ordering::SeqCst); - self.inner.recover_exact(request).await + let result = self.inner.recover_exact(request).await; + if self.control.tamper_recovery.load(Ordering::SeqCst) { + let foreign = radroots_signing::issuance::IntentBinding::from_components( + OperationId::from_bytes([0xa1; 32]), + [0xa2; 32], + [0xa3; 32], + radroots_signing::issuance::ArtifactRole::BusinessSeal, + Some(self.inner.public_key()), + NonZeroU64::new(230000).unwrap(), + ) + .unwrap(); + let rejected = result.enforce_binding(foreign); + let radroots_signing::issuance::ExactRecoveryKind::Rejected(metadata) = + rejected.kind() + else { + panic!("actual recovered artifact must retain bounded mismatch metadata") + }; + *self.control.rejected.lock().unwrap() = Some(*metadata); + return rejected; + } + result }) } } @@ -919,3 +969,254 @@ async fn identical_authenticated_foreign_scope_cannot_start_this_clients_accepta r.client.close().await.unwrap(); other.close().await.unwrap(); } + +fn assert_rejected(error: crate::ExecutionFailure, operation: OperationId, control: &Control) { + assert_eq!(error.code(), crate::Code::SignerTampering); + assert_eq!(error.context().operation_id(), Some(operation)); + assert_eq!(error.context().admission(), crate::Admission::Confirmed); + assert_eq!(error.retry(), crate::RetryClass::ManualReconciliation); + let rejected = error + .signer_rejection() + .expect("preserve the actual bounded rejection"); + assert_eq!( + rejected, + *control.rejected.lock().unwrap().as_ref().unwrap() + ); + let fingerprint = rejected + .fingerprint() + .expect("actual returned bytes have fingerprint coverage"); + assert!(fingerprint.covered_bytes() > 0); + assert_eq!(fingerprint.covered_bytes(), fingerprint.total_bytes()); + assert!(fingerprint.covered_bytes() <= 65536); +} + +#[tokio::test] +async fn rejected_self_callback_returns_bounded_tampering_without_losing_peer_installation() { + let r = Rig::new().await; + r.control.tamper_self.store(true, Ordering::SeqCst); + let (command, context) = r.captured().await; + let (private, public, minimum) = r.minima().await; + let error = r + .client + .orders(&r.scope) + .accept( + context, + minimum, + private, + public, + AcceptOrderInput::new( + command.input().request(), + command.input().terms_digest(), + AllocationSelection::automatic(), + ), + ) + .await + .unwrap_err(); + assert_rejected(error, command.context().operation_id(), &r.control); + let status = r + .client + .orders(&r.scope) + .acceptance_status(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + let installed = status + .installation() + .expect("actual peer S installs before self rejection"); + assert_eq!( + status + .recipients() + .iter() + .filter(|v| v.evidence.is_some()) + .count(), + 1 + ); + assert!(!status.aborted()); + r.control.tamper_self.store(false, Ordering::SeqCst); + let resumed = r + .client + .orders(&r.scope) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + assert_eq!(resumed.installation(), Some(installed)); + assert!(resumed.recipients().iter().all(|v| v.evidence.is_some())); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + assert_eq!(r.control.recoveries.load(Ordering::SeqCst), 1); + r.client.close().await.unwrap(); + assert!(r.provider.upgrade().is_none()); +} + +#[tokio::test] +async fn generic_inquiry_installs_actual_peer_and_returns_original_bounded_self_rejection() { + for fail_install in [false, true] { + let r = Rig::new().await; + r.control + .pause_rejected + .store(fail_install, Ordering::SeqCst); + r.control.tamper_self.store(true, Ordering::SeqCst); + let crypto = WorkspaceCrypto::new( + r.vault.clone(), + SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap(); + let key = r.enrollment.input().participant(); + let (native, input, credential) = NativeWorkspace::initialize_local_outbox( + &r._temp.path().join("chat"), + radroots_storage_sqlite::workspace::LocalOutboxConfig::new( + key, + key, + "synthetic-rejected-chat", + UnixSeconds::new(300).unwrap(), + ) + .unwrap(), + crypto, + r.clock.clone(), + ) + .await + .unwrap(); + let path = r._temp.path().join("chat_cache"); + std::fs::create_dir(&path).unwrap(); + let options = OpenOptions::new(Paths::from_directory(path).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([20; 32]).unwrap(), 1) + .unwrap(); + let mut client = Client::open(NativeConfig::public_read(options).with_workspace(native)) + .await + .unwrap(); + client.session = client + .session + .clone() + .with_command_runtime(Arc::new(CommandRuntime::new(Arc::new(Io(r.clock.clone()))))); + let scope = client.attach(input, proof(&credential)).await.unwrap(); + client + .attach_signer(SignerHandle::new( + r.provider.upgrade().unwrap(), + Arc::new(Callbacks), + )) + .await + .unwrap(); + client.start(StartMode::LocalOnly).await.unwrap(); + let operation = OperationId::from_bytes([95; 32]); + let context = scope + .command_context(operation, None, None, UnixSeconds::new(230).unwrap()) + .unwrap(); + let peer = data()["scope"]["buyer"].as_str().unwrap().parse().unwrap(); + let input = crate::inbox::InquireInput::new( + radroots_domain::ThreadId::from_bytes([96; 32]), + peer, + None, + "synthetic private inquiry", + ) + .unwrap(); + let observer_client = client.clone(); + let observer = + tokio::spawn(async move { observer_client.inbox().inquire(context, input).await }); + let mut injected = None; + if fail_install { + use sqlx::Connection; + tokio::time::timeout( + std::time::Duration::from_secs(20), + r.control.entered.notified(), + ) + .await + .unwrap(); + let path = r._temp.path().join("chat/execution_v1.sqlite"); + let mut connection = + sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display())) + .await + .unwrap(); + sqlx::query("CREATE TRIGGER controlled_t2_failure BEFORE INSERT ON chat_messages BEGIN SELECT RAISE(ABORT, 'controlled_t2_failure'); END").execute(&mut connection).await.unwrap(); + injected = Some(connection); + r.control.release.notify_one(); + } + let error = observer.await.unwrap().unwrap_err(); + if fail_install { + assert_eq!(error.code(), crate::Code::StorageFailure); + assert_eq!(error.context().operation_id(), Some(operation)); + assert_eq!(error.context().admission(), crate::Admission::Confirmed); + assert_eq!(error.retry(), crate::RetryClass::ManualReconciliation); + assert_eq!( + error.signer_rejection(), + *r.control.rejected.lock().unwrap() + ); + } else { + assert_rejected(error, operation, &r.control) + } + if let Some(mut connection) = injected { + use sqlx::Connection; + sqlx::query("DROP TRIGGER controlled_t2_failure") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + } + let status = client + .operations(&scope) + .get(operation) + .await + .unwrap() + .unwrap(); + assert_eq!( + status.business_installation(), + if fail_install { + crate::BusinessInstallation::NotInstalled + } else { + crate::BusinessInstallation::Installed + } + ); + assert_eq!( + status + .artifacts() + .iter() + .filter(|v| v.issuance() == crate::Issuance::Obtained) + .count(), + 1 + ); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + client.close().await.unwrap(); + r.client.close().await.unwrap(); + assert!(r.provider.upgrade().is_none()); + } +} + +#[tokio::test] +async fn rejected_exact_recovery_keeps_original_binding_and_cannot_release_installed_peer() { + let r = Rig::new().await; + r.control.fail_self.store(true, Ordering::SeqCst); + let (command, status) = r.accept().await; + let installed = status.installation().unwrap(); + r.control.fail_self.store(false, Ordering::SeqCst); + r.control.tamper_recovery.store(true, Ordering::SeqCst); + let (_, _, minimum) = r.minima().await; + let error = r + .client + .orders(&r.scope) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap_err(); + assert_rejected(error, command.context().operation_id(), &r.control); + let current = r + .client + .orders(&r.scope) + .acceptance_status(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + assert_eq!(current.installation(), Some(installed)); + assert_eq!( + current + .recipients() + .iter() + .filter(|v| v.evidence.is_some()) + .count(), + 1 + ); + assert!(!current.aborted()); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + assert_eq!(r.control.recoveries.load(Ordering::SeqCst), 1); + r.client.close().await.unwrap(); +} diff --git a/crates/radroots/src/operations.rs b/crates/radroots/src/operations.rs @@ -53,7 +53,7 @@ impl<'a> Operations<'a> { &self, operation: OperationId, expected: Option<CommandDigest>, - ) -> Result<radroots_execution::OperationStatus> { + ) -> crate::ExecutionResult<radroots_execution::OperationStatus> { self.client .session .resume_command(self.client.journal()?, &self.scope, operation, expected) diff --git a/crates/radroots/src/orders.rs b/crates/radroots/src/orders.rs @@ -30,7 +30,7 @@ impl<'a> Orders<'a> { sources: StockSourceCheckpointRef, listings: StockListingCheckpointRef, input: AcceptOrderInput, - ) -> Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { self.client .session .accept_stock_order( @@ -52,7 +52,7 @@ impl<'a> Orders<'a> { minimum: InventoryCheckpointRef, operation: OperationId, digest: CommandDigest, - ) -> Result<AcceptanceStatus> { + ) -> crate::ExecutionResult<AcceptanceStatus> { self.client .session .resume_stock_acceptance( diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs @@ -80,7 +80,8 @@ fn root_has_exact_exports_and_no_sdk_namespace() { ) ); assert!(ROOT.contains("pub use radroots_protocol::command::CommandError;")); - assert_eq!(ROOT.matches("pub use ").count(), 10); + assert!(ROOT.contains("pub use radroots_execution::{ExecutionFailure, ExecutionResult};")); + assert_eq!(ROOT.matches("pub use ").count(), 11); assert!(README.contains("```compile_fail\nuse radroots::sdk;\n```")); } diff --git a/crates/radroots/tests/support/receipt_client.rs b/crates/radroots/tests/support/receipt_client.rs @@ -57,7 +57,7 @@ impl Ordinary { id: u8, text: &str, correlation: &str, - ) -> radroots::Result<OperationReceipt<ChatMessage>> { + ) -> radroots::ExecutionResult<OperationReceipt<ChatMessage>> { self.client .inbox() .inquire(self.context(id, correlation), input(text)) diff --git a/crates/radroots/tests/support/receipt_workflow_faults.rs b/crates/radroots/tests/support/receipt_workflow_faults.rs @@ -491,7 +491,8 @@ async fn failed_obtained_capture_blocks_close_retains_writer_and_retries_without .inquire(ready.context(205, now() + 120), inquiry()) .await .unwrap_err(); - assert_eq!(error.code(), Code::RecoveryRequired); + assert_eq!(error.code(), Code::StorageFailure); + assert_eq!(error.retry(), radroots::RetryClass::ManualReconciliation); assert_eq!(error.context().admission(), Admission::Confirmed); assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); let error = ready.client.close().await.unwrap_err(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -329,6 +329,14 @@ struct SigningPlanBinding { ordinary_peer_installed_before_self_work: bool, ordinary_accepted_task_survives_observer_loss: bool, ordinary_obtained_owned_before_descriptor_conversion: bool, + rejected_signer_error: String, + effectful_command_result: String, + common_error_max_bytes: u16, + execution_failure_max_bytes: u16, + rejected_signer_metadata_owner: String, + rejected_signer_report_is_nonissuance: bool, + generic_peer_installed_before_rejected_self_return: bool, + unknown_installation_blocks_delivery: bool, ordinary_existing_claim_grants_first_dispatch: bool, ordinary_replay_requires_original_policy_and_current_permit: bool, ordinary_acceptance_implies_delivery: bool, @@ -621,6 +629,21 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock .signing_plan_binding .ordinary_obtained_owned_before_descriptor_conversion + && stock.signing_plan_binding.rejected_signer_error == "SignerTampering" + && stock.signing_plan_binding.effectful_command_result == "ExecutionResult" + && stock.signing_plan_binding.common_error_max_bytes == 64 + && stock.signing_plan_binding.execution_failure_max_bytes == 128 + && stock.signing_plan_binding.rejected_signer_metadata_owner + == "radroots_signing.issuance.RejectedArtifact" + && !stock + .signing_plan_binding + .rejected_signer_report_is_nonissuance + && stock + .signing_plan_binding + .generic_peer_installed_before_rejected_self_return + && stock + .signing_plan_binding + .unknown_installation_blocks_delivery && !stock .signing_plan_binding .ordinary_existing_claim_grants_first_dispatch @@ -1722,6 +1745,17 @@ mod tests { #[test] fn signing_plans_require_complete_original_qualified_intents_before_any_signing() { for (field, bad) in [ + ("effectful_command_result", json!("unbounded_error")), + ("common_error_max_bytes", json!(128)), + ("execution_failure_max_bytes", json!(256)), + ("rejected_signer_error", json!("success")), + ("rejected_signer_metadata_owner", json!("raw_payload")), + ("rejected_signer_report_is_nonissuance", json!(true)), + ( + "generic_peer_installed_before_rejected_self_return", + json!(false), + ), + ("unknown_installation_blocks_delivery", json!(false)), ( "ordinary_obtained_owned_before_descriptor_conversion", json!(false),