lib

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

commit f406f431629f17c38a1756cb8186238ffe169b59
parent 4d73dcb5d73d81031e799a2c9f200ca5e6a417ff
Author: triesap <tyson@radroots.org>
Date:   Mon, 26 Oct 2026 00:37:45 +0000

execution: own private inventory through the ordinary client

- Route typed stock commands and recovery through the selected workspace.
- Retain accepted tasks and byte permits through settlement and close.
- Preserve unknown admission when an accepted task loses its reply.
- Verify native and Linux effects, scoped refusal, APIs and shared WASM.

Diffstat:
Mcontracts/api_baselines/radroots.txt | 20++++++++++++++++++++
Mcontracts/api_baselines/radroots_execution.txt | 9+++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 10++++++++++
Mcrates/execution/Cargo.toml | 2+-
Mcrates/execution/README.md | 14+++++++++++++-
Mcrates/execution/src/session/client.rs | 4++++
Acrates/execution/src/session/client_inventory.rs | 274+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/tests/support/workspace_inventory.rs | 387+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/tests/workspace.rs | 3+++
Mcrates/radroots/README.md | 19++++++++++++++++++-
Mcrates/radroots/src/client.rs | 47++++++++++++++++++++++++++++++++++++++++-------
Mcrates/radroots/src/lib.rs | 1+
Mcrates/radroots/src/operations.rs | 38++++++++++++++++++++++++++++++++++++++
Acrates/radroots/src/stock.rs | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots/tests/stock.rs | 598+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/architecture/decision_package.rs | 53++++++++++++++++++++++++++++++++++++++++++++++++++++-
16 files changed, 1611 insertions(+), 11 deletions(-)

diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -40,6 +40,7 @@ pub fn radroots::client::Client::preview() -> Self pub fn radroots::client::Client::signer_session(&self) -> core::option::Option<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::start(&self, radroots_execution::session::StartMode) -> radroots_execution::Result<radroots::client::SessionStatus> pub fn radroots::client::Client::state(&self) -> radroots_execution::session::SessionState +pub fn radroots::client::Client::stock(&self, &radroots_execution::workspace::WorkspaceSession) -> radroots::stock::Stock<'_> pub async fn radroots::client::Client::storage_status(&self) -> radroots_execution::Result<radroots_storage::status::StorageStatus> pub struct radroots::client::CloseReceipt impl radroots::client::CloseReceipt @@ -146,8 +147,10 @@ pub async fn radroots::listings::Listings<'a>::publish(&self, radroots_execution pub mod radroots::operations pub struct radroots::operations::Operations<'a> impl<'a> radroots::operations::Operations<'a> +pub async fn radroots::operations::Operations<'a>::abort_proven_unissued(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_storage::inventory::abort::StockAbortOutcome> 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 mod radroots::signing pub use radroots::signing::ArtifactRole @@ -163,6 +166,22 @@ pub use radroots::signing::SignedArtifact pub use radroots::signing::SigningIntent pub use radroots::signing::SigningOutcome pub use radroots::signing::blossom_upload_request +pub mod radroots::stock +pub use radroots::stock::CreatePoolInput +pub use radroots::stock::InventoryCheckpointRef +pub use radroots::stock::InventoryOutcome +pub use radroots::stock::InventoryReceipt +pub use radroots::stock::MapOptionInput +pub use radroots::stock::PoolCorrectionInput +pub struct radroots::stock::Stock<'a> +impl<'a> radroots::stock::Stock<'a> +pub async fn radroots::stock::Stock<'a>::adjust(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock_correction::PoolCorrectionInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots::stock::Stock<'a>::create_pool(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock::CreatePoolInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots::stock::Stock<'a>::map_option(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock_mapping::MapOptionInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots::stock::Stock<'a>::operation(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<core::option::Option<radroots_storage::inventory::InventoryReceipt>> +pub async fn radroots::stock::Stock<'a>::option_mapping(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey) -> radroots_execution::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>> +pub async fn radroots::stock::Stock<'a>::pool(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId) -> radroots_execution::Result<core::option::Option<radroots_domain::stock::PoolView>> +pub async fn radroots::stock::Stock<'a>::spoil(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock_correction::PoolCorrectionInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> pub mod radroots::storage pub use radroots::storage::IntegrityStatus pub use radroots::storage::Operations @@ -232,6 +251,7 @@ pub fn radroots::client::Client::preview() -> Self pub fn radroots::client::Client::signer_session(&self) -> core::option::Option<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::start(&self, radroots_execution::session::StartMode) -> radroots_execution::Result<radroots::client::SessionStatus> pub fn radroots::client::Client::state(&self) -> radroots_execution::session::SessionState +pub fn radroots::client::Client::stock(&self, &radroots_execution::workspace::WorkspaceSession) -> radroots::stock::Stock<'_> pub async fn radroots::client::Client::storage_status(&self) -> radroots_execution::Result<radroots_storage::status::StorageStatus> pub struct radroots::CloseReceipt impl radroots::client::CloseReceipt diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -35,6 +35,15 @@ pub radroots_execution::session::StartMode::LocalOnly pub radroots_execution::session::StartMode::Online pub struct radroots_execution::session::ClientSession<H: radroots_execution::session::SessionHost> impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> +pub async fn radroots_execution::session::ClientSession<H>::abort_proven_unissued(&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<radroots_storage::inventory::abort::StockAbortOutcome> +pub async fn radroots_execution::session::ClientSession<H>::correct_stock_pool(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock_correction::PoolCorrectionInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots_execution::session::ClientSession<H>::create_stock_pool(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock::CreatePoolInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots_execution::session::ClientSession<H>::inventory_operation(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<core::option::Option<radroots_storage::inventory::InventoryReceipt>> +pub async fn radroots_execution::session::ClientSession<H>::map_stock_option(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock_mapping::MapOptionInput) -> radroots_execution::Result<radroots_storage::inventory::InventoryOutcome> +pub async fn radroots_execution::session::ClientSession<H>::stock_option_mapping(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey) -> radroots_execution::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>> +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>::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> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -772,6 +772,16 @@ "first_issuance_seconds": 120 }, "execution": { + "ordinary_inventory_owner": { + "execution": "radroots_execution.ClientSession", + "facade": "radroots.Client", + "selected_workspace_views_share_owner": true, + "exact_owned_attachment_required": true, + "bounded_task_host_required": true, + "observer_loss_cancels_accepted_work": false, + "close_drains_before_workspace_disposal": true, + "stock_signer_or_transport_constructed": false + }, "phases": [ "T0", "T1", diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -17,7 +17,7 @@ default = [] session = ["dep:futures"] signer_session = ["session", "dep:radroots_signing"] client_session = ["signer_session"] -workspace_session = ["client_session", "receipts", "radroots_protocol/commands", "radroots_protocol/listing", "radroots_signing/artifacts", "dep:radroots_transport"] +workspace_session = ["client_session", "receipts", "radroots_protocol/commands", "radroots_protocol/listing", "radroots_signing/artifacts", "dep:radroots_transport", "radroots_storage/protected_outbox"] receipts = ["dep:radroots_storage", "radroots_storage/command_journal"] [dependencies] diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -108,7 +108,19 @@ through an explicitly selected client-owned scope, independently of the old first-issue deadline. The qualified concrete bounded worker owns accepted native admission through observer loss; its close must drain accepted work. -Package upload is not authorized. Inventory authority, complete listing revision +`ClientSession` routes explicit private inventory creation, corrections, mapping, +original-effect reads and proven-unissued cleanup through the supplied inventory +port and this client's exact owned attachment. These calls require a bounded +`TaskHost`; no inline fallback starts them. The existing resource permit and live +byte reservation move into each accepted task until the store settles, including +after observer loss. Close drains these tasks before disposal. The concrete store +must still authenticate current scope, independently retained minima and actual +protected effects. A custom port or a missing query result proves no authority, +safe nonissuance or commit. These paths construct no signer or transport. +An accepted admission task lost before replying reports unknown initial admission +with its original operation ID and manual reconciliation, never known failure. + +Package upload is not authorized. Full commerce authority, complete listing revision behavior, final browser qualification and new bindings remain separate requirements. Revalidating a context is not durable admission; the authoritative transaction must recheck its scope. diff --git a/crates/execution/src/session/client.rs b/crates/execution/src/session/client.rs @@ -10,6 +10,10 @@ use std::{ #[path = "client_commands.rs"] mod commands; +#[cfg(feature = "workspace_session")] +#[path = "client_inventory.rs"] +mod inventory; + struct Resources<H> { host: H, signer: Shared<Mutex<Option<SignerSession>>>, diff --git a/crates/execution/src/session/client_inventory.rs b/crates/execution/src/session/client_inventory.rs @@ -0,0 +1,274 @@ +//! Owned calls into the explicitly selected private inventory store. +use super::{ClientSession, SessionHost, Shared}; +use crate::{ + Error, OperationContext, + session::{HostBound, HostFuture}, + workspace::{CommandContext, WorkspaceSession}, +}; +use alloc::boxed::Box; +use radroots_domain::{ + CommandDigest, OperationId, PoolId, + stock::{OptionMappingKey, OptionPoolMapping, PoolView}, +}; +use radroots_protocol::command::{ + CapturedInventoryCommand, CapturedOptionMapping, CapturedPoolCorrection, CapturedPoolCreation, + CreatePoolInput, MapOptionInput, PoolCorrectionInput, +}; +use radroots_storage::{ + command::OperationError, + inventory::{ + InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, InventoryRequest, + InventoryStore, StockAbortOutcome, StockAbortReceipt, StockAbortRequest, + }, + workspace::{AttachmentProof, WorkspaceBinding}, +}; + +impl<H: SessionHost + 'static> ClientSession<H> { + /// Captures pool creation from this client's own selected attachment. + /// Actual authority, conservation and commit remain the store's obligation. + pub async fn create_stock_pool( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: CreatePoolInput, + ) -> crate::Result<InventoryOutcome> { + self.submit_inventory(store, scope, context, minimum, |data| { + CapturedPoolCreation::new(data, input).map(Into::into) + }) + .await + } + + /// Captures an exact available-stock correction or spoilage command. + pub async fn correct_stock_pool( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: PoolCorrectionInput, + ) -> crate::Result<InventoryOutcome> { + self.submit_inventory(store, scope, context, minimum, |data| { + CapturedPoolCorrection::new(data, input).map(Into::into) + }) + .await + } + + /// Captures a private option-to-pool mapping without signing or transport. + pub async fn map_stock_option( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: MapOptionInput, + ) -> crate::Result<InventoryOutcome> { + self.submit_inventory(store, scope, context, minimum, |data| { + CapturedOptionMapping::new(data, input).map(Into::into) + }) + .await + } + + async fn submit_inventory( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + context: CommandContext, + minimum: InventoryCheckpointRef, + capture: impl FnOnce( + radroots_domain::CommandContextData, + ) -> Result< + CapturedInventoryCommand, + radroots_protocol::command::CommandError, + >, + ) -> crate::Result<InventoryOutcome> { + let proposed = OperationContext::proposed(Some(context.data().operation_id())); + if !scope.owns_context(&context) { + return Err(Error::operation(OperationError::Unauthorized, proposed)); + } + self.run_stock_with_loss( + scope, + proposed, + Error::admission_uncertain(context.data().operation_id()), + move |binding, proof| { + // Capture only after resource and byte reservations. This closure + // performs no store, signer or transport call before submission. + let request = capture(context.data().clone()) + .map_err(|_| OperationError::InvalidCommand) + .and_then(|command| InventoryRequest::new(binding, minimum, command)); + Box::pin(async move { store.execute_inventory(request?, proof).await }) + }, + ) + .await + } + + /// Explicitly asks the selected store to prove original claim absence and + /// atomically release only that preparation. Selectors are never proof. + pub async fn abort_proven_unissued( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> crate::Result<StockAbortOutcome> { + self.run_stock( + scope, + OperationContext::proposed(Some(operation)), + move |binding, proof| { + let request = StockAbortRequest::new(binding, minimum, operation, digest); + Box::pin(async move { store.abort_proven_unissued(request, proof).await }) + }, + ) + .await + } + + /// Reads an original abort without inferring safe nonissuance from absence. + pub async fn stock_preparation_abort( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> crate::Result<Option<StockAbortReceipt>> { + self.run_stock( + scope, + OperationContext::proposed(Some(operation)), + move |binding, proof| { + let request = StockAbortRequest::new(binding, minimum, operation, digest); + Box::pin(async move { store.stock_preparation_abort(request, proof).await }) + }, + ) + .await + } + + /// Reads the original private inventory effect under an independent minimum. + pub async fn inventory_operation( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: Option<CommandDigest>, + ) -> crate::Result<Option<InventoryReceipt>> { + self.run_stock( + scope, + OperationContext::proposed(Some(operation)), + move |binding, proof| { + Box::pin(async move { + store + .inventory_operation(binding, minimum, operation, digest, proof) + .await + }) + }, + ) + .await + } + + /// Reads a private pool; a missing row never constructs stock or authority. + pub async fn stock_pool( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + minimum: InventoryCheckpointRef, + pool: PoolId, + ) -> crate::Result<Option<PoolView>> { + self.run_stock( + scope, + OperationContext::proposed(None), + move |binding, proof| { + Box::pin(async move { store.pool(binding, minimum, pool, proof).await }) + }, + ) + .await + } + + /// Reads the actual private mapping under current owner access. + pub async fn stock_option_mapping( + &self, + store: Shared<dyn InventoryStore>, + scope: &WorkspaceSession, + minimum: InventoryCheckpointRef, + key: OptionMappingKey, + ) -> crate::Result<Option<OptionPoolMapping>> { + self.run_stock( + scope, + OperationContext::proposed(None), + move |binding, proof| { + Box::pin(async move { store.option_mapping(binding, minimum, key, proof).await }) + }, + ) + .await + } + + async fn run_stock<T: HostBound + 'static>( + &self, + scope: &WorkspaceSession, + proposed: OperationContext, + work: impl FnOnce( + WorkspaceBinding, + AttachmentProof, + ) -> HostFuture<'static, Result<T, OperationError>>, + ) -> crate::Result<T> { + self.run_stock_with_loss( + scope, + proposed, + Error::operation(OperationError::RecoveryRequired, proposed), + work, + ) + .await + } + + async fn run_stock_with_loss<T: HostBound + 'static>( + &self, + scope: &WorkspaceSession, + proposed: OperationContext, + lost_observation: Error, + work: impl FnOnce( + WorkspaceBinding, + AttachmentProof, + ) -> HostFuture<'static, Result<T, OperationError>>, + ) -> crate::Result<T> { + let permit = self + .session + .admit() + .map_err(|error| error.with_context(proposed))?; + let budget = self + .task_budget + .reserve() + .map_err(|error| error.with_context(proposed))?; + { + let scopes = self + .workspaces + .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)); + } + } + let host = self + .task_host + .as_ref() + .ok_or_else(|| Error::operation(OperationError::UnsupportedOperation, proposed))?; + let (binding, proof) = scope + .captured_input() + .map_err(|error| Error::operation(error.into(), proposed))?; + let future = work(binding, proof); + let lease: Shared<dyn HostBound> = Shared::new((permit, budget)); + let (reply, observed) = futures::channel::oneshot::channel(); + host.submit(Box::pin(async move { + let result = future + .await + .map_err(|error| Error::operation(error, proposed)); + let _ = reply.send(result); + // Observer loss cannot drop the permit before the store settles. + drop(lease); + })) + .map_err(|error| error.with_context(proposed))?; + // An accepted admission task lost before its reply has unknown T0; + // reads/recovery cannot manufacture a confirmed business phase either. + observed.await.unwrap_or(Err(lost_observation)) + } +} diff --git a/crates/execution/tests/support/workspace_inventory.rs b/crates/execution/tests/support/workspace_inventory.rs @@ -0,0 +1,387 @@ +//! Mechanical task ownership with a controlled port, not SQL qualification. +use super::*; +use radroots_execution::{Code, RetryClass, session::tasks::TaskHost}; +use radroots_storage::{command::OperationError, inventory::*}; + +#[derive(Default)] +struct Tasks { + queued: Mutex<Vec<HostFuture<'static, ()>>>, + refuse: AtomicBool, +} +impl TaskHost for Tasks { + fn submit(&self, task: HostFuture<'static, ()>) -> radroots_execution::Result<()> { + if self.refuse.load(Ordering::SeqCst) { + return Err(radroots_execution::Error::operation( + OperationError::UnsupportedOperation, + radroots_execution::OperationContext::proposed(None), + )); + } + let mut queued = self.queued.lock().unwrap(); + assert!( + queued.len() < 2, + "the owner's byte budget must bound admission first" + ); + queued.push(task); + Ok(()) + } +} +struct Store { + model: Shared<Model>, + calls: Mutex<Vec<(OperationId, CommandDigest)>>, + waiting: AtomicBool, + waker: AtomicWaker, +} +impl WorkspaceStore for Store { + fn authenticate( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> { + self.model.authenticate(input, proof) + } + fn close_workspace( + &self, + ) -> radroots_storage::event::BoxFuture<'_, Result<(), WorkspaceError>> { + Box::pin(async { Ok(()) }) + } +} +impl InventoryStore for Store { + fn abort_proven_unissued( + &self, + request: StockAbortRequest, + proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<StockAbortOutcome, OperationError>> { + Box::pin(async move { + assert_eq!(proof.with_secret(|bytes| *bytes), [7; 32]); + assert_eq!(request.binding().input(), &input(5)); + self.calls + .lock() + .unwrap() + .push((request.operation_id(), request.command_digest())); + poll_fn(|cx| { + self.waker.register(cx.waker()); + if self.waiting.load(Ordering::SeqCst) { + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await; + // A mechanical report only. No absence, release or SQL proof. + Ok(StockAbortOutcome::Unknown(request.attempt())) + }) + } + fn stock_preparation_abort( + &self, + _request: StockAbortRequest, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<Option<StockAbortReceipt>, OperationError>> + { + Box::pin(async { Err(OperationError::MissingHistory) }) + } + fn option_mapping( + &self, + _binding: WorkspaceBinding, + _minimum: InventoryCheckpointRef, + _key: radroots_domain::stock::OptionMappingKey, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture< + '_, + Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError>, + > { + panic!("unexpected port call") + } + fn execute_inventory( + &self, + _request: InventoryRequest, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<InventoryOutcome, OperationError>> { + panic!("unexpected port call") + } + fn inventory_operation( + &self, + _binding: WorkspaceBinding, + _minimum: InventoryCheckpointRef, + _operation: OperationId, + _digest: Option<CommandDigest>, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<Option<InventoryReceipt>, OperationError>> + { + panic!("unexpected port call") + } + fn pool( + &self, + _binding: WorkspaceBinding, + _minimum: InventoryCheckpointRef, + _pool: PoolId, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture< + '_, + Result<Option<radroots_domain::stock::PoolView>, OperationError>, + > { + panic!("unexpected port call") + } +} +fn store() -> Shared<Store> { + Shared::new(Store { + model: new_model(), + calls: Mutex::new(vec![]), + waiting: AtomicBool::new(false), + waker: AtomicWaker::new(), + }) +} +fn minimum(scope: &WorkspaceSession) -> InventoryCheckpointRef { + InventoryCheckpointRef::from_host_metadata( + scope.binding().input().authority(), + Sequence::new(0).unwrap(), + None, + ) + .unwrap() +} +fn operation() -> OperationId { + OperationId::from_bytes([80; 32]) +} +fn digest() -> CommandDigest { + CommandDigest::from_bytes([81; 32]) +} + +#[test] +fn admitted_inventory_work_survives_observer_loss_bounds_bytes_and_blocks_close_until_settled() { + block_on(async { + let store = store(); + let tasks = Shared::new(Tasks::default()); + let client = ClientSession::new_with_task_host( + Host, + core::num::NonZeroU16::new(8).unwrap(), + tasks.clone(), + ); + let scope = client + .attach_workspace(store.clone(), input(5), proof()) + .await + .unwrap(); + client.start().await.unwrap(); + let minimum = minimum(&scope); + drop(client.abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest())); + assert!(tasks.queued.lock().unwrap().is_empty()); + let mut first = Box::pin(client.abort_proven_unissued( + store.clone(), + &scope, + minimum, + operation(), + digest(), + )); + let mut second = Box::pin(client.abort_proven_unissued( + store.clone(), + &scope, + minimum, + operation(), + digest(), + )); + assert!(futures::poll!(first.as_mut()).is_pending()); + assert!(futures::poll!(second.as_mut()).is_pending()); + assert_eq!(tasks.queued.lock().unwrap().len(), 2); + assert!(store.calls.lock().unwrap().is_empty()); + assert_eq!( + client + .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + drop(first); + drop(second); + let mut closing = Box::pin(client.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + assert!( + scope + .command_context(operation(), None, None, UnixSeconds::new(150).unwrap()) + .is_err() + ); + let mut jobs = core::mem::take(&mut *tasks.queued.lock().unwrap()); + store.waiting.store(true, Ordering::SeqCst); + assert!(futures::poll!(jobs[0].as_mut()).is_pending()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + store.waiting.store(false, Ordering::SeqCst); + store.waker.wake(); + for task in jobs { + task.await; + } + assert_eq!( + *store.calls.lock().unwrap(), + vec![(operation(), digest()); 2] + ); + closing.await.unwrap(); + assert_eq!( + client + .abort_proven_unissued(store, &scope, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + }); +} + +#[test] +fn task_refusal_foreign_scope_closed_scope_and_missing_host_dispatch_nothing() { + block_on(async { + let store = store(); + let tasks = Shared::new(Tasks::default()); + let client = ClientSession::new_with_task_host( + Host, + core::num::NonZeroU16::new(8).unwrap(), + tasks.clone(), + ); + let scope = client + .attach_workspace(store.clone(), input(5), proof()) + .await + .unwrap(); + let foreign = WorkspaceSession::attach(store.clone(), input(5), proof()) + .await + .unwrap(); + client.start().await.unwrap(); + let minimum = minimum(&scope); + assert_eq!( + client + .abort_proven_unissued(store.clone(), &foreign, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::Unauthorized + ); + tasks.refuse.store(true, Ordering::SeqCst); + assert_eq!( + client + .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + tasks.refuse.store(false, Ordering::SeqCst); + let mut observed = Box::pin(client.abort_proven_unissued( + store.clone(), + &scope, + minimum, + operation(), + digest(), + )); + assert!(futures::poll!(observed.as_mut()).is_pending()); + let task = tasks.queued.lock().unwrap().pop().unwrap(); + task.await; + let StockAbortOutcome::Unknown(anchor) = observed.await.unwrap() else { + panic!("must preserve uncertainty") + }; + assert_eq!(anchor.operation_id(), operation()); + assert_eq!(anchor.command_digest(), digest()); + assert!(anchor.transaction_id().is_none()); + let mut query = Box::pin(client.stock_preparation_abort( + store.clone(), + &scope, + minimum, + operation(), + digest(), + )); + assert!(futures::poll!(query.as_mut()).is_pending()); + let task = tasks.queued.lock().unwrap().pop().unwrap(); + task.await; + let error = query.await.unwrap_err(); + assert_eq!(error.code(), Code::MissingHistory); + assert_eq!(error.context().operation_id(), Some(operation())); + assert_eq!(error.retry(), RetryClass::AfterStateRefresh); + scope.close(); + assert_eq!( + client + .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + client.close().await.unwrap(); + let without_host = ClientSession::new(Host, core::num::NonZeroU16::MIN); + let scope = without_host + .attach_workspace(store.clone(), input(5), proof()) + .await + .unwrap(); + without_host.start().await.unwrap(); + assert_eq!( + without_host + .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + without_host.close().await.unwrap(); + assert_eq!(store.calls.lock().unwrap().len(), 1); + assert!(tasks.queued.lock().unwrap().is_empty()); + }); +} + +#[test] +fn loss_of_an_accepted_admission_task_never_reports_known_nonadmission() { + block_on(async { + let store = store(); + // Port metadata only. This test deliberately drops an accepted host + // task; it does not qualify that host or any native transaction. + *store.model.binding.lock().unwrap() = WorkspaceBinding::from_authenticated_host( + input(5), + radroots_storage::workspace::WorkspaceScope::SellerStockOwner, + ActorRef::new(key(), ActorRole::Seller, None, Some(input(5).grant_id())), + "device", + Sequence::new(1).unwrap(), + UnixSeconds::new(200).unwrap(), + UnixSeconds::new(100).unwrap(), + ) + .unwrap(); + let tasks = Shared::new(Tasks::default()); + let client = + ClientSession::new_with_task_host(Host, core::num::NonZeroU16::MIN, tasks.clone()); + let scope = client + .attach_workspace(store.clone(), input(5), proof()) + .await + .unwrap(); + client.start().await.unwrap(); + let input = radroots_protocol::command::CreatePoolInput::new( + PoolId::from_bytes([82; 32]), + "private model stock", + radroots_domain::stock::PoolUnit::new( + radroots_domain::listing::MeasurementUnit::Each, + 0, + ) + .unwrap(), + Quantity::new( + "1".parse().unwrap(), + radroots_domain::listing::MeasurementUnit::Each, + ) + .unwrap(), + ) + .unwrap(); + let context = scope + .command_context(operation(), None, None, UnixSeconds::new(150).unwrap()) + .unwrap(); + let mut observed = Box::pin(client.create_stock_pool( + store.clone(), + &scope, + context, + minimum(&scope), + input, + )); + assert!(futures::poll!(observed.as_mut()).is_pending()); + // Simulate a nonconforming host losing its accepted task. Silence + // cannot prove the store never committed, and must not authorize retry. + drop(tasks.queued.lock().unwrap().pop().unwrap()); + let error = observed.await.unwrap_err(); + assert_eq!(error.code(), Code::CommitUnknown); + assert_eq!( + error.context().admission(), + radroots_execution::Admission::Unknown + ); + assert_eq!(error.context().operation_id(), Some(operation())); + assert_eq!(error.retry(), RetryClass::ManualReconciliation); + assert!(store.calls.lock().unwrap().is_empty()); + client.close().await.unwrap(); + }); +} diff --git a/crates/execution/tests/workspace.rs b/crates/execution/tests/workspace.rs @@ -384,3 +384,6 @@ fn close_invalidates_clones_and_an_already_pending_context_revalidation() { #[path = "support/workspace_commands.rs"] mod commands; + +#[path = "support/workspace_inventory.rs"] +mod inventory; diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -94,7 +94,7 @@ Its `OperationReceipt<domain::Listing>` contains a business result only after actual installation. Text and exact terms come from the captured command; author, revision and event time come from its retained public signing plan and obtained evidence. An existing coordinate cannot be replaced by publishing it -again. Revision editing, pause/withdraw and stock remain separate requirements. +again. Revision editing, pause/withdraw and full stock commitments remain separate requirements. Public planning uses the configured public relay targets and exact-event signing. It performs no private-route query, encryption or wrapping. Delivery @@ -105,6 +105,23 @@ resume preserves the original bytes, criterion, targets and retry budget. ## Values and retained capabilities +`client.stock(&scope)` selects this client's authenticated attachment for private +pool creation, exact available-stock adjustment/spoilage, private option mapping, +pool/mapping reads and original-effect recovery. Inputs are typed; each call +requires an independently retained inventory minimum. The native configuration +retains journal and inventory views of the same explicitly opened workspace, +and close drains the same bounded task owner before closing that workspace. +Public-cache and preview construction cannot adopt a foreign stock attachment. +An ordinary outbox cannot become a stock owner through these calls. + +`client.operations(&scope).abort_proven_unissued(minimum, operation, digest)` +explicitly requests the store's proven original-preparation cleanup; its selectors +assert no nonissuance proof. `preparation_abort` reads the original result and +absence authorizes nothing. Claims and unknown issuance remain nonspendable. +These calls neither sign nor publish, and cleanup is separate from business +cancellation or stopping delivery. Full commerce orchestration, qualified claimed +attempt reconciliation and the final common receipt/binding surface remain open. + `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/client.rs b/crates/radroots/src/client.rs @@ -62,13 +62,20 @@ impl CloseReceipt { } } +// These are views of one configured owner, never separately selected stores. +#[derive(Clone)] +struct WorkspaceResource { + journal: Shared<dyn radroots_storage::command::OperationJournal>, + inventory: Shared<dyn radroots_storage::inventory::InventoryStore>, +} + /// Explicit native public-cache opening, without participant/stock authority. /// Participant protected-workspace opening requires the separate authenticated /// workspace/authority contract and is not inferred from cache generations. #[cfg(feature = "native")] pub struct NativeConfig { options: radroots_storage_sqlite::OpenOptions, - workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + workspace: Option<WorkspaceResource>, #[cfg(not(target_arch = "wasm32"))] commands: Option<Shared<crate::native_commands::NativeCommands>>, } @@ -91,7 +98,11 @@ impl NativeConfig { mut self, workspace: radroots_storage_sqlite::workspace::NativeWorkspace, ) -> Self { - self.workspace = Some(Shared::new(workspace)); + let owner = Shared::new(workspace); + self.workspace = Some(WorkspaceResource { + journal: owner.clone(), + inventory: owner, + }); self } /// Selects explicit relay destinations and a relay-acceptance criterion. @@ -128,7 +139,7 @@ impl TargetRuntime { } pub(crate) struct StoreHost { store: Shared<dyn Storage>, - workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + workspace: Option<WorkspaceResource>, closed: Shared<Mutex<Option<CloseReceipt>>>, runtime: TargetRuntime, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] @@ -208,6 +219,7 @@ impl SessionHost for StoreHost { } if let Some(workspace) = &self.workspace { workspace + .journal .close_workspace() .await .map_err(|_| STORAGE_FAILURE)?; @@ -231,7 +243,7 @@ impl SessionHost for StoreHost { pub struct Client { pub(crate) session: ClientSession<StoreHost>, store: Shared<dyn Storage>, - workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + workspace: Option<WorkspaceResource>, closed: Shared<Mutex<Option<CloseReceipt>>>, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] native_commands: Option<Shared<crate::native_commands::NativeCommands>>, @@ -240,7 +252,7 @@ impl Client { #[cfg(any(feature = "client", feature = "native"))] fn from_store( store: Shared<dyn Storage>, - workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + workspace: Option<WorkspaceResource>, runtime: TargetRuntime, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] native_commands: Option< Shared<crate::native_commands::NativeCommands>, @@ -330,7 +342,26 @@ impl Client { pub(crate) fn journal( &self, ) -> crate::Result<Shared<dyn radroots_storage::command::OperationJournal>> { - self.workspace.clone().ok_or(MISSING_WORKSPACE) + self.workspace + .as_ref() + .map(|workspace| workspace.journal.clone()) + .ok_or(MISSING_WORKSPACE) + } + pub(crate) fn inventory( + &self, + ) -> crate::Result<Shared<dyn radroots_storage::inventory::InventoryStore>> { + self.workspace + .as_ref() + .map(|workspace| workspace.inventory.clone()) + .ok_or(MISSING_WORKSPACE) + } + /// Selects owner-private stock operations through this client's explicit + /// authenticated attachment. Access alone creates no authority or work. + pub fn stock( + &self, + scope: &radroots_execution::workspace::WorkspaceSession, + ) -> crate::stock::Stock<'_> { + crate::stock::Stock::new(self, scope.clone()) } /// Accesses private inquiry execution. Access alone performs no work. pub const fn inbox(&self) -> crate::inbox::Inbox<'_> { @@ -392,7 +423,9 @@ impl Client { proof: radroots_storage::workspace::AttachmentProof, ) -> crate::Result<radroots_execution::workspace::WorkspaceSession> { let workspace = self.workspace.clone().ok_or(MISSING_WORKSPACE)?; - self.session.attach_workspace(workspace, input, proof).await + self.session + .attach_workspace(workspace.journal, input, proof) + .await } /// Permanently stops admission, drains resources and scoped callbacks, then /// closes the actual store last. Failed/cancelled closure must be resumed. diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -14,6 +14,7 @@ pub mod listing; pub mod listings; pub mod operations; pub mod signing; +pub mod stock; pub mod storage; pub mod sync; pub mod trade; diff --git a/crates/radroots/src/operations.rs b/crates/radroots/src/operations.rs @@ -8,6 +8,44 @@ pub struct Operations<'a> { scope: WorkspaceSession, } impl<'a> Operations<'a> { + /// Explicitly requests original preparation cleanup. Only the selected + /// store can prove all original claims absent and release the exact hold. + /// This is separate from business cancellation and stopping delivery. + pub async fn abort_proven_unissued( + &self, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> Result<radroots_storage::inventory::StockAbortOutcome> { + self.client + .session + .abort_proven_unissued( + self.client.inventory()?, + &self.scope, + minimum, + operation, + digest, + ) + .await + } + /// Reads original cleanup. Absence never permits issuance or release. + pub async fn preparation_abort( + &self, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> Result<Option<radroots_storage::inventory::StockAbortReceipt>> { + self.client + .session + .stock_preparation_abort( + self.client.inventory()?, + &self.scope, + minimum, + operation, + digest, + ) + .await + } /// Explicitly resumes one original command. Retained signing claims never /// permit reissuance. Delivery retries use the original exact artifact and /// criterion, preserving accepted targets and the original business result. diff --git a/crates/radroots/src/stock.rs b/crates/radroots/src/stock.rs @@ -0,0 +1,143 @@ +//! Typed private stock commands through one selected authenticated attachment. +use crate::{Client, CommandContext, OperationContext, Result, WorkspaceSession}; +use radroots_domain::{ + CommandDigest, OperationId, PoolId, + stock::{AvailableStockCorrection, OptionMappingKey, OptionPoolMapping, PoolView}, +}; +pub use radroots_protocol::command::{CreatePoolInput, MapOptionInput, PoolCorrectionInput}; +pub use radroots_storage::inventory::{InventoryCheckpointRef, InventoryOutcome, InventoryReceipt}; + +/// Borrowed access to this client's explicitly selected private stock owner. +pub struct Stock<'a> { + client: &'a Client, + scope: WorkspaceSession, +} +impl<'a> Stock<'a> { + pub(crate) const fn new(client: &'a Client, scope: WorkspaceSession) -> Self { + Self { client, scope } + } + /// Creates a private pool with actual atomic conservation and idempotency. + /// The report claims neither Nostr signing nor transport delivery. + pub async fn create_pool( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: CreatePoolInput, + ) -> Result<InventoryOutcome> { + self.client + .session + .create_stock_pool( + self.client.inventory()?, + &self.scope, + context, + minimum, + input, + ) + .await + } + /// Applies an explicit positive addition or available-stock removal. + pub async fn adjust( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: PoolCorrectionInput, + ) -> Result<InventoryOutcome> { + if input.kind() == AvailableStockCorrection::Spoil { + return Err(invalid(&context)); + } + self.correct(context, minimum, input).await + } + /// Records physical spoilage without silently spending held quantities. + pub async fn spoil( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: PoolCorrectionInput, + ) -> Result<InventoryOutcome> { + if input.kind() != AvailableStockCorrection::Spoil { + return Err(invalid(&context)); + } + self.correct(context, minimum, input).await + } + async fn correct( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: PoolCorrectionInput, + ) -> Result<InventoryOutcome> { + self.client + .session + .correct_stock_pool( + self.client.inventory()?, + &self.scope, + context, + minimum, + input, + ) + .await + } + /// Updates an owner-private option mapping with exact expected progress. + pub async fn map_option( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + input: MapOptionInput, + ) -> Result<InventoryOutcome> { + self.client + .session + .map_stock_option( + self.client.inventory()?, + &self.scope, + context, + minimum, + input, + ) + .await + } + /// Reads the actual protected pool under an independently retained minimum. + pub async fn pool( + &self, + minimum: InventoryCheckpointRef, + pool: PoolId, + ) -> Result<Option<PoolView>> { + self.client + .session + .stock_pool(self.client.inventory()?, &self.scope, minimum, pool) + .await + } + /// Reads a private mapping; absence supplies no default allocation. + pub async fn option_mapping( + &self, + minimum: InventoryCheckpointRef, + key: OptionMappingKey, + ) -> Result<Option<OptionPoolMapping>> { + self.client + .session + .stock_option_mapping(self.client.inventory()?, &self.scope, minimum, key) + .await + } + /// Recovers an original private effect, without executing a fresh command. + pub async fn operation( + &self, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: Option<CommandDigest>, + ) -> Result<Option<InventoryReceipt>> { + self.client + .session + .inventory_operation( + self.client.inventory()?, + &self.scope, + minimum, + operation, + digest, + ) + .await + } +} +fn invalid(context: &CommandContext) -> crate::Error { + crate::Error::operation( + radroots_storage::command::OperationError::InvalidCommand, + OperationContext::proposed(Some(context.data().operation_id())), + ) +} diff --git a/crates/radroots/tests/stock.rs b/crates/radroots/tests/stock.rs @@ -0,0 +1,598 @@ +#![cfg(all(feature = "native", unix))] +//! Actual ordinary-client private inventory, not a model of SQL effects. +use radroots::stock::{ + CreatePoolInput, InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, MapOptionInput, + PoolCorrectionInput, +}; +use radroots::{ + Client, Code, CommandContext, NativeConfig, OperationId, StartMode, WorkspaceSession, +}; +use radroots_domain::{ + CommandDigest, ListingOptionId, PoolId, PublicKey, Quantity, Sequence, UnixSeconds, + listing::{ListingCoordinate, ListingId, MeasurementUnit}, + stock::{AvailableStockCorrection, OptionMappingKey, PoolUnit}, +}; +use radroots_secrets::{ + SecretId, SecretRef, + envelope::Nonce, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, + wrapping::SecretMaterial, +}; +use radroots_storage::{ + event::SourceGeneration, + workspace::{AttachmentProof, WorkspaceClock, WorkspaceError}, +}; +use radroots_storage_sqlite::{ + OpenMode, OpenOptions, Paths, + workspace::{ + LocalOutboxConfig, NativeWorkspace, SellerStockConfig, StockEnrollment, WorkspaceCrypto, + }, +}; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; + +struct Clock(AtomicU64); +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ) +} +fn proof(value: &AttachmentProof) -> AttachmentProof { + value + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap() +} +struct Fixture { + _temp: tempfile::TempDir, + root: std::path::PathBuf, + provider: Arc<FileProvider>, + clock: Arc<Clock>, +} +impl Fixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + root.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), + ) + .unwrap(), + ); + provider + .provision( + &reference(), + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([0x11; 24]), + ) + .unwrap(); + Self { + _temp: temp, + root, + provider, + clock: Arc::new(Clock(AtomicU64::new(100))), + } + } + fn crypto(&self) -> WorkspaceCrypto { + WorkspaceCrypto::new( + self.provider.clone(), + reference(), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + } + fn options(&self) -> OpenOptions { + let path = self.root.join("cache"); + std::fs::create_dir_all(&path).unwrap(); + OpenOptions::new(Paths::from_directory(path).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1) + .unwrap() + } + async fn client(&self, workspace: NativeWorkspace) -> Client { + Client::open(NativeConfig::public_read(self.options()).with_workspace(workspace)) + .await + .unwrap() + } + async fn owner(&self) -> (Client, NativeWorkspace, StockEnrollment) { + let enrollment = StockEnrollment::prepare( + SellerStockConfig::new( + key(), + key(), + "synthetic-stock-owner", + UnixSeconds::new(300).unwrap(), + ) + .unwrap(), + self.clock.as_ref(), + ) + .unwrap(); + let store = NativeWorkspace::initialize_seller_stock( + &self.root.join("stock"), + &enrollment, + self.crypto(), + self.clock.clone(), + ) + .await + .unwrap(); + (self.client(store.clone()).await, store, enrollment) + } +} +fn context(scope: &WorkspaceSession, op: u8) -> CommandContext { + scope + .command_context( + OperationId::from_bytes([op; 32]), + None, + None, + UnixSeconds::new(150).unwrap(), + ) + .unwrap() +} +fn pool() -> PoolId { + PoolId::from_bytes([70; 32]) +} +fn quantity(value: &str) -> Quantity { + Quantity::new(value.parse().unwrap(), MeasurementUnit::Each).unwrap() +} +fn creation() -> CreatePoolInput { + CreatePoolInput::new( + pool(), + "private test vegetables", + PoolUnit::new(MeasurementUnit::Each, 0).unwrap(), + quantity("10"), + ) + .unwrap() +} +fn correction(version: u64, kind: AvailableStockCorrection, amount: &str) -> PoolCorrectionInput { + PoolCorrectionInput::new( + pool(), + Sequence::new(version).unwrap(), + kind, + amount.parse().unwrap(), + "synthetic audited correction", + ) + .unwrap() +} +fn committed(value: InventoryOutcome) -> InventoryReceipt { + let InventoryOutcome::Committed(value) = value else { + panic!("effect must confirm") + }; + *value +} +fn native_future<T: Send>(future: T) -> T { + future +} + +#[tokio::test] +async fn ordinary_stock_effects_queries_original_replay_and_reopen_use_the_selected_native_owner() { + let f = Fixture::new(); + let (client, native, enrollment) = f.owner().await; + let scope = client + .attach(enrollment.input().clone(), proof(enrollment.proof())) + .await + .unwrap(); + let first_minimum = native + .stock_authority(enrollment.input().clone(), enrollment.proof()) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + client.start(StartMode::LocalOnly).await.unwrap(); + let stock = client.stock(&scope); + drop(stock.create_pool(context(&scope, 80), first_minimum, creation())); + assert!(stock.pool(first_minimum, pool()).await.unwrap().is_none()); + let original = committed( + native_future(stock.create_pool(context(&scope, 80), first_minimum, creation())) + .await + .unwrap(), + ); + assert_eq!(original.pool().version().get(), 1); + assert_eq!(original.pool().balances().physical().available.get(), 10); + let added = committed( + stock + .adjust( + context(&scope, 81), + original.checkpoint(), + correction(1, AvailableStockCorrection::Add, "3"), + ) + .await + .unwrap(), + ); + let removed = committed( + stock + .adjust( + context(&scope, 82), + added.checkpoint(), + correction(2, AvailableStockCorrection::Remove, "2"), + ) + .await + .unwrap(), + ); + let spoiled = committed( + stock + .spoil( + context(&scope, 83), + removed.checkpoint(), + correction(3, AvailableStockCorrection::Spoil, "1"), + ) + .await + .unwrap(), + ); + assert_eq!(spoiled.pool().version().get(), 4); + assert_eq!(spoiled.pool().balances().introduced().get(), 13); + assert_eq!(spoiled.pool().balances().physical().available.get(), 10); + assert_eq!(spoiled.pool().balances().physical().removed.get(), 2); + assert_eq!(spoiled.pool().balances().physical().waste.get(), 1); + let key = OptionMappingKey::new( + ListingCoordinate::new(key(), ListingId::from_bytes([89; 16])), + ListingOptionId::from_bytes([90; 32]), + ); + let mapped = committed( + stock + .map_option( + context(&scope, 84), + spoiled.checkpoint(), + MapOptionInput::new(key, pool(), quantity("2"), Sequence::new(0).unwrap()).unwrap(), + ) + .await + .unwrap(), + ); + assert_eq!(mapped.pool(), spoiled.pool()); + assert_eq!( + stock + .option_mapping(mapped.checkpoint(), key) + .await + .unwrap(), + mapped.mapping() + ); + let current = mapped.checkpoint(); + assert_eq!( + stock + .pool(current, pool()) + .await + .unwrap() + .unwrap() + .snapshot(), + spoiled.pool() + ); + assert_eq!( + stock + .operation( + current, + original.attempt().operation_id(), + Some(original.attempt().command_digest()) + ) + .await + .unwrap() + .unwrap(), + original + ); + assert_eq!( + stock + .adjust( + context(&scope, 85), + current, + correction(1, AvailableStockCorrection::Add, "1") + ) + .await + .unwrap_err() + .code(), + Code::StaleState + ); + assert_eq!( + stock + .adjust( + context(&scope, 85), + current, + correction(4, AvailableStockCorrection::Spoil, "1") + ) + .await + .unwrap_err() + .code(), + Code::InvalidInput + ); + assert_eq!( + stock + .spoil( + context(&scope, 85), + current, + correction(4, AvailableStockCorrection::Add, "1") + ) + .await + .unwrap_err() + .code(), + Code::InvalidInput + ); + let missing = OperationId::from_bytes([99; 32]); + let digest = CommandDigest::from_bytes([98; 32]); + // The native original-preparation loader reports a missing selected T0 as + // StaleState, before any consent lookup or cleanup. Preserve that refusal. + assert_eq!( + client + .operations(&scope) + .abort_proven_unissued(current, missing, digest) + .await + .unwrap_err() + .code(), + Code::StaleState + ); + assert_eq!( + client + .operations(&scope) + .preparation_abort(current, missing, digest) + .await + .unwrap_err() + .code(), + Code::StaleState + ); + f.clock.0.store(160, Ordering::SeqCst); + let replay = committed( + stock + .create_pool(context(&scope, 80), first_minimum, creation()) + .await + .unwrap(), + ); + assert_eq!(replay, original); + assert_eq!( + stock + .pool(current, pool()) + .await + .unwrap() + .unwrap() + .snapshot(), + spoiled.pool() + ); + client.close().await.unwrap(); + assert!( + native + .authenticate(enrollment.input().clone(), enrollment.proof()) + .await + .is_err() + ); + let native = NativeWorkspace::open_seller_stock( + &f.root.join("stock"), + enrollment.input().clone(), + f.crypto(), + f.clock.clone(), + ) + .await + .unwrap(); + let client = f.client(native.clone()).await; + let scope = client + .attach(enrollment.input().clone(), proof(enrollment.proof())) + .await + .unwrap(); + client.start(StartMode::LocalOnly).await.unwrap(); + assert_eq!( + client + .stock(&scope) + .pool(current, pool()) + .await + .unwrap() + .unwrap() + .snapshot(), + spoiled.pool() + ); + assert_eq!( + client + .stock(&scope) + .operation( + current, + original.attempt().operation_id(), + Some(original.attempt().command_digest()) + ) + .await + .unwrap() + .unwrap(), + original + ); + client.close().await.unwrap(); +} + +#[tokio::test] +async fn identical_but_foreign_and_closed_scopes_cannot_reach_the_selected_owner() { + let f = Fixture::new(); + let (client, native, enrollment) = f.owner().await; + let scope = client + .attach(enrollment.input().clone(), proof(enrollment.proof())) + .await + .unwrap(); + let foreign = WorkspaceSession::attach( + Arc::new(native.clone()), + enrollment.input().clone(), + proof(enrollment.proof()), + ) + .await + .unwrap(); + let minimum = native + .stock_authority(enrollment.input().clone(), enrollment.proof()) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + client.start(StartMode::LocalOnly).await.unwrap(); + assert_eq!( + client + .stock(&foreign) + .pool(minimum, pool()) + .await + .unwrap_err() + .code(), + Code::Unauthorized + ); + assert_eq!( + client + .stock(&scope) + .create_pool(context(&foreign, 80), minimum, creation()) + .await + .unwrap_err() + .code(), + Code::Unauthorized + ); + scope.close(); + assert_eq!( + client + .stock(&scope) + .pool(minimum, pool()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + foreign.close(); + client.close().await.unwrap(); + assert_eq!( + client + .stock(&scope) + .pool(minimum, pool()) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); +} + +#[tokio::test] +async fn public_cache_and_preview_never_adopt_a_foreign_stock_workspace() { + let f = Fixture::new(); + let (owner, native, enrollment) = f.owner().await; + let scope = owner + .attach(enrollment.input().clone(), proof(enrollment.proof())) + .await + .unwrap(); + let minimum = native + .stock_authority(enrollment.input().clone(), enrollment.proof()) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + let public = tempfile::tempdir().unwrap(); + let options = OpenOptions::new( + Paths::from_directory(public.path()).unwrap(), + OpenMode::Create, + ) + .with_source_generation(SourceGeneration::new([18; 32]).unwrap(), 1) + .unwrap(); + let cache = Client::open(NativeConfig::public_read(options)) + .await + .unwrap(); + let preview = Client::preview(); + for client in [&cache, &preview] { + client.start(StartMode::LocalOnly).await.unwrap(); + assert_eq!( + client + .stock(&scope) + .create_pool(context(&scope, 80), minimum, creation()) + .await + .unwrap_err() + .code(), + Code::MissingAuthority + ); + assert_eq!( + client + .operations(&scope) + .abort_proven_unissued( + minimum, + OperationId::from_bytes([99; 32]), + CommandDigest::from_bytes([98; 32]) + ) + .await + .unwrap_err() + .code(), + Code::MissingAuthority + ); + client.close().await.unwrap(); + } + native + .authenticate(enrollment.input().clone(), enrollment.proof()) + .await + .unwrap(); + assert_eq!( + native + .stock_authority(enrollment.input().clone(), enrollment.proof()) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(), + minimum + ); + owner.close().await.unwrap(); +} + +#[tokio::test] +async fn ordinary_outbox_refuses_cleanup_and_never_creates_stock_authority() { + let f = Fixture::new(); + let path = f.root.join("outbox"); + let (native, input, credential) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + key(), + key(), + "synthetic-outbox", + UnixSeconds::new(300).unwrap(), + ) + .unwrap(), + f.crypto(), + f.clock.clone(), + ) + .await + .unwrap(); + let client = f.client(native.clone()).await; + let scope = client + .attach(input.clone(), proof(&credential)) + .await + .unwrap(); + let minimum = InventoryCheckpointRef::from_host_metadata( + input.authority(), + Sequence::new(0).unwrap(), + None, + ) + .unwrap(); + client.start(StartMode::LocalOnly).await.unwrap(); + let operation = OperationId::from_bytes([99; 32]); + let digest = CommandDigest::from_bytes([98; 32]); + assert_eq!( + client + .operations(&scope) + .abort_proven_unissued(minimum, operation, digest) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + assert_eq!( + client + .operations(&scope) + .preparation_abort(minimum, operation, digest) + .await + .unwrap_err() + .code(), + Code::CapabilityUnavailable + ); + assert_eq!( + client + .stock(&scope) + .create_pool(context(&scope, 80), minimum, creation()) + .await + .unwrap_err() + .code(), + Code::Unauthorized + ); + assert!(!path.join("stock_execution_v1.sqlite").exists()); + native.authenticate(input, &credential).await.unwrap(); + client.close().await.unwrap(); +} diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -362,6 +362,7 @@ struct Values { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Execution { + ordinary_inventory_owner: OrdinaryInventoryOwner, phases: Vec<String>, selected_executor_required_for_stock: bool, fresh_same_key_cache_can_allocate: bool, @@ -380,6 +381,19 @@ struct Execution { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct OrdinaryInventoryOwner { + execution: String, + facade: String, + selected_workspace_views_share_owner: bool, + exact_owned_attachment_required: bool, + bounded_task_host_required: bool, + observer_loss_cancels_accepted_work: bool, + close_drains_before_workspace_disposal: bool, + stock_signer_or_transport_constructed: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct Protocol { listing_kind: u16, chat_rumor_kind: u16, @@ -1009,7 +1023,21 @@ fn validate_values(v: &Values, limits: &BTreeMap<String, u64>) -> Result<(), Str fn validate_execution(e: &Execution, p: &Protocol, c: &Cutover) -> Result<(), String> { require( - e.phases == ["T0", "T1", "S", "T2", "D"] + e.ordinary_inventory_owner.execution == "radroots_execution.ClientSession" + && e.ordinary_inventory_owner.facade == "radroots.Client" + && e.ordinary_inventory_owner + .selected_workspace_views_share_owner + && e.ordinary_inventory_owner.exact_owned_attachment_required + && e.ordinary_inventory_owner.bounded_task_host_required + && !e + .ordinary_inventory_owner + .observer_loss_cancels_accepted_work + && e.ordinary_inventory_owner + .close_drains_before_workspace_disposal + && !e + .ordinary_inventory_owner + .stock_signer_or_transport_constructed + && e.phases == ["T0", "T1", "S", "T2", "D"] && e.selected_executor_required_for_stock && !e.fresh_same_key_cache_can_allocate && !e.shared_route_local_fallback_allowed @@ -1350,6 +1378,29 @@ mod tests { } #[test] + fn ordinary_inventory_keeps_selected_owner_and_accepted_task_lifetime() { + for (field, bad) in [ + ("execution", json!("application")), + ("facade", json!("native_backend")), + ("selected_workspace_views_share_owner", json!(false)), + ("exact_owned_attachment_required", json!(false)), + ("bounded_task_host_required", json!(false)), + ("observer_loss_cancels_accepted_work", json!(true)), + ("close_drains_before_workspace_disposal", json!(false)), + ("stock_signer_or_transport_constructed", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/execution/ordinary_inventory_owner/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn public_sources_require_original_signatures_bounded_parts_and_profile_independent_heads() { for (field, bad) in [ ("schema_version", json!(7)),