commit eb449d4609197e68ee1c6beb11e3dba1e6272260
parent bb9f9bc50669e83048ff442845a873a413b4ad56
Author: triesap <tyson@radroots.org>
Date: Mon, 26 Oct 2026 17:36:26 +0000
execution: retain obtained command bytes before conversion
- Register original artifacts, attempts and credentials before fallible mapping.
- Gate fresh signing while obtained material requires exact capture recovery.
- Preserve original operation and storage failures through drain and close.
- Verify conversion refusal, SQLite retry, portable callers and public API.
Diffstat:
11 files changed, 309 insertions(+), 29 deletions(-)
diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt
@@ -6,7 +6,7 @@ pub mod radroots_execution::session
pub mod radroots_execution::session::command
pub struct radroots_execution::session::command::CommandRuntime
impl radroots_execution::session::command::CommandRuntime
-pub async fn radroots_execution::session::command::CommandRuntime::drain(&self) -> core::result::Result<(), radroots_storage::command::OperationError>
+pub async fn radroots_execution::session::command::CommandRuntime::drain(&self) -> radroots_execution::Result<()>
pub fn radroots_execution::session::command::CommandRuntime::new(alloc::sync::Arc<dyn radroots_execution::session::command::CommandIo>) -> Self
pub trait radroots_execution::session::command::CommandIo: radroots_execution::session::HostBound
pub fn radroots_execution::session::command::CommandIo::delivery_id(&self) -> core::result::Result<alloc::string::String, radroots_storage::command::OperationError>
diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json
@@ -246,6 +246,8 @@
"ordinary_peer_installed_before_self_work": true,
"ordinary_accepted_task_survives_observer_loss": true,
"ordinary_obtained_owned_before_descriptor_conversion": true,
+ "generic_obtained_owned_before_descriptor_conversion": true,
+ "retained_drain_preserves_original_error_and_operation": true,
"rejected_signer_error": "SignerTampering",
"effectful_command_result": "ExecutionResult",
"common_error_max_bytes": 64,
diff --git a/crates/execution/README.md b/crates/execution/README.md
@@ -244,3 +244,14 @@ 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.
+
+Generic chat/listing execution registers the original obtained artifact and
+attempt with prepared capture credentials and its resource lease before
+fallible storage conversion. Conversion or append failure retains the original
+bytes, blocks further issuance and permits only original capture reconciliation.
+`CommandRuntime::drain` returns the compact execution `Error`, preserving the
+actual store code, original confirmed operation and manual reconciliation
+through resume and close, including when another operation encounters that
+retained obligation. Observation append failures likewise retain their original
+operation. A failed conversion is cached without discarding its signed input;
+neither a new caller nor close may relabel it as a successful capture.
diff --git a/crates/execution/src/session/client_commands.rs b/crates/execution/src/session/client_commands.rs
@@ -66,10 +66,7 @@ impl<H: SessionHost + 'static> ClientSession<H> {
let (reply, observed) = futures::channel::oneshot::channel();
host.submit(Box::pin(async move {
let result = async {
- runtime
- .drain()
- .await
- .map_err(|error| Error::operation(error, proposed))?;
+ runtime.drain().await?;
let prepared = journal
.operation(
binding.clone(),
diff --git a/crates/execution/src/session/command.rs b/crates/execution/src/session/command.rs
@@ -2,6 +2,9 @@
#[path = "inquiry_routes.rs"]
mod routes;
pub use routes::{capture_dm_route, selected_dm_targets};
+#[path = "command_obtained.rs"]
+mod obtained;
+use obtained::Obtained;
use super::{HostBound, HostFuture, Shared, SignerSession};
use alloc::{string::String, vec::Vec};
@@ -21,11 +24,10 @@ use radroots_signing::{
};
use radroots_storage::{
command::{
- ArtifactEvidence, BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest,
- DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation,
- EnvelopeCandidate, EvidenceCaptureOutcome, InstallationRequest, OperationError,
- OperationJournal, PlanBindingOutcome, PreparedOperation, PublicationArtifact,
- PublicationWork,
+ BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, DeliveryAttemptOutcome,
+ DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation, EnvelopeCandidate,
+ EvidenceCaptureOutcome, InstallationRequest, OperationError, OperationJournal,
+ PlanBindingOutcome, PreparedOperation, PublicationArtifact, PublicationWork,
},
workspace::{AttachmentProof, WorkspaceBinding},
};
@@ -78,7 +80,7 @@ struct PendingCapture {
journal: Shared<dyn OperationJournal>,
binding: WorkspaceBinding,
proof: AttachmentProof,
- evidence: ArtifactEvidence,
+ obtained: Obtained,
// Keeps both the resource permit and conservative live-byte reservation.
_lease: Shared<dyn HostBound>,
}
@@ -108,10 +110,16 @@ pub(super) enum RunMode {
Resume,
}
pub(super) enum CommandFailure {
+ Retained(crate::Error),
Host(OperationError, Option<RejectedArtifact>),
Capture(OperationError),
Rejected(RejectedArtifact),
}
+impl From<crate::Error> for CommandFailure {
+ fn from(error: crate::Error) -> Self {
+ Self::Retained(error)
+ }
+}
impl From<OperationError> for CommandFailure {
fn from(error: OperationError) -> Self {
Self::Host(error, None)
@@ -124,6 +132,7 @@ impl CommandFailure {
) -> crate::ExecutionFailure {
let context = crate::OperationContext::retained(operation);
match self {
+ Self::Retained(error) => error.into(),
Self::Host(error, Some(rejected)) => {
crate::ExecutionFailure::host_after_rejection(error, operation, rejected)
}
@@ -145,7 +154,7 @@ impl CommandRuntime {
}
/// Retries only already obtained original evidence. Failure retains its
/// exact bytes and resource ownership, including when this wait is dropped.
- pub async fn drain(&self) -> Result<(), OperationError> {
+ pub async fn drain(&self) -> crate::Result<()> {
let _serial = self.draining.lock().await;
loop {
let next = self
@@ -157,14 +166,23 @@ impl CommandRuntime {
let Some(next) = next else {
break;
};
+ let fail = |error| {
+ crate::Error::capture_pending(
+ error,
+ crate::OperationContext::retained(next.obtained.operation()),
+ )
+ };
+ let evidence = next.obtained.evidence().map_err(fail)?;
match next
.journal
- .reconcile_unknown(next.binding.input().clone(), &next.proof, &next.evidence)
+ .reconcile_unknown(next.binding.input().clone(), &next.proof, evidence)
.await
- .map_err(|_| OperationError::RecoveryRequired)?
+ .map_err(fail)?
{
EvidenceCaptureOutcome::Committed(_) => self.remove(&next),
- EvidenceCaptureOutcome::Unknown(_) => return Err(OperationError::RecoveryRequired),
+ EvidenceCaptureOutcome::Unknown(_) => {
+ return Err(fail(OperationError::RecoveryRequired));
+ }
}
}
loop {
@@ -177,10 +195,28 @@ impl CommandRuntime {
let Some(next) = next else {
return Ok(());
};
- self.capture_observation(&next)
- .await
- .map_err(|_| OperationError::RecoveryRequired)?;
+ self.capture_observation(&next).await.map_err(|error| {
+ crate::Error::capture_pending(
+ error,
+ crate::OperationContext::retained(
+ next.observation.work().evidence().operation_id(),
+ ),
+ )
+ })?;
+ }
+ }
+ pub(super) fn ensure_ready(&self) -> crate::Result<()> {
+ let pending = self
+ .pending
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(entry) = pending.first() {
+ return Err(crate::Error::capture_pending(
+ OperationError::RecoveryRequired,
+ crate::OperationContext::retained(entry.obtained.operation()),
+ ));
}
+ Ok(())
}
async fn capture_observation(
&self,
@@ -485,6 +521,8 @@ impl CommandRuntime {
if intent.binding() != attempt.binding() {
return Err(OperationError::RecoveryRequired.into());
}
+ let capture_proof = copy(proof)?;
+ self.ensure_ready()?;
stock_captures.ensure_ready()?;
let outcome = signer.sign_exact(intent).await;
let (_, kind) = outcome.into_parts();
@@ -492,22 +530,20 @@ impl CommandRuntime {
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())
- })?;
let entry = Shared::new(PendingCapture {
journal: journal.clone(),
binding: binding.clone(),
- proof: copy(proof)?,
- evidence,
+ proof: capture_proof,
+ obtained: Obtained::new(attempt, artifact),
_lease: lease.clone(),
});
self.pending
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(entry.clone());
+ let evidence = entry.obtained.evidence().map_err(CommandFailure::Capture)?;
match journal
- .capture_evidence(binding.input().clone(), &entry.proof, &entry.evidence)
+ .capture_evidence(binding.input().clone(), &entry.proof, evidence)
.await
.map_err(CommandFailure::Capture)?
{
diff --git a/crates/execution/src/session/command_obtained.rs b/crates/execution/src/session/command_obtained.rs
@@ -0,0 +1,41 @@
+//! Original obtained bytes outlive any fallible storage-evidence conversion.
+use radroots_domain::OperationId;
+use radroots_signing::issuance::SignedArtifact;
+use radroots_storage::command::{ArtifactEvidence, OperationError, SigningAttempt};
+use std::sync::OnceLock;
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+#[path = "command_obtained_tests.rs"]
+mod tests;
+
+pub(super) struct Obtained {
+ attempt: SigningAttempt,
+ artifact: SignedArtifact,
+ evidence: OnceLock<Result<ArtifactEvidence, OperationError>>,
+}
+impl Obtained {
+ pub(super) fn new(attempt: SigningAttempt, artifact: SignedArtifact) -> Self {
+ Self {
+ attempt,
+ artifact,
+ evidence: OnceLock::new(),
+ }
+ }
+ pub(super) fn operation(&self) -> OperationId {
+ self.attempt.identity().operation_id()
+ }
+ pub(super) fn evidence(&self) -> Result<&ArtifactEvidence, OperationError> {
+ self.evidence
+ .get_or_init(|| {
+ self.artifact.with_json(|raw| {
+ ArtifactEvidence::verify(
+ &self.attempt,
+ raw,
+ self.artifact.observed_at_unix_ms(),
+ )
+ })
+ })
+ .as_ref()
+ .map_err(|error| *error)
+ }
+}
diff --git a/crates/execution/src/session/command_obtained_tests.rs b/crates/execution/src/session/command_obtained_tests.rs
@@ -0,0 +1,157 @@
+//! A refused storage descriptor must not discard authenticated original bytes.
+use super::*;
+use alloc::vec;
+use radroots_domain::*;
+use radroots_protocol::{
+ command::CapturedOrderAcceptance,
+ commerce::{self, CommerceSigningPlan, EncodedCommerceRumor},
+ intent::SigningReplay,
+ listing::{CapturedListingCommand, PublicSigningPlan, PublishInput},
+ plan::SigningTarget,
+};
+use radroots_signing::{
+ issuance::{OutcomeKind, SigningIntent, SigningOutcome},
+ provider::ProviderCall,
+ request::CancellationSignal,
+};
+use radroots_storage::{
+ command::{AdmissionRequest, BoundSigningPlan, PreparedOperation},
+ workspace::{AttachmentInput, WorkspaceBinding, WorkspaceScope},
+};
+use std::num::NonZeroU64;
+
+fn foreign_attempt() -> SigningAttempt {
+ let key =
+ PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
+ .unwrap();
+ let input = AttachmentInput::new(
+ WorkspaceId::from_bytes([1; 32]),
+ AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()),
+ key,
+ "local://model",
+ key,
+ GrantId::from_bytes([3; 32]),
+ CheckpointRef::new(
+ CheckpointDigest::from_bytes([4; 32]),
+ Sequence::new(0).unwrap(),
+ Coverage::Partial,
+ vec![],
+ )
+ .unwrap(),
+ RouteDigest::from_bytes([5; 32]),
+ )
+ .unwrap();
+ let binding = WorkspaceBinding::from_authenticated_host(
+ input.clone(),
+ WorkspaceScope::NewSellerOutbox,
+ ActorRef::new(key, ActorRole::Seller, None, Some(input.grant_id())),
+ "model",
+ Sequence::new(1).unwrap(),
+ UnixSeconds::new(200).unwrap(),
+ UnixSeconds::new(100).unwrap(),
+ )
+ .unwrap();
+ let context = CommandContextData::new(
+ OperationId::from_bytes([8; 32]),
+ binding.actor(),
+ input.workspace_id(),
+ input.authority(),
+ input.route_digest(),
+ None,
+ None,
+ UnixSeconds::new(150).unwrap(),
+ None,
+ )
+ .unwrap();
+ // Synthetic structural listing only; this descriptor has no store authority.
+ let listing = PublishInput::parse(br#"{
+ "id":"01010101010101010101010101010101","title":"Carrots",
+ "summary":"Ask for terms","description_markdown":"Synthetic",
+ "published_at":"100","profile":{"profile":"radroots.listing","version":1,
+ "state":"active","product":{"name":"Carrots","description":"Synthetic","producer":null,"origin_summary":null},
+ "default_option":"0202020202020202020202020202020202020202020202020202020202020202",
+ "options":[{"id":"0202020202020202020202020202020202020202020202020202020202020202",
+ "label":"Bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},
+ "minimum":"1","increment":"1","price":{"type":"quote_required"},
+ "supply":{"type":"available","amount":"10"},"lead_seconds":"0"}],
+ "fulfillment":{"modes":["pickup"],"area":"Synthetic","lead_seconds":"0"},
+ "authority":null,"media":[]}}"#).unwrap();
+ let command = CapturedListingCommand::capture(context, listing).unwrap();
+ let now = UnixSeconds::new(100).unwrap();
+ let plan = PublicSigningPlan::capture(
+ &command,
+ now,
+ &["wss://synthetic.invalid".into()],
+ SigningReplay::NonReplayable,
+ )
+ .unwrap();
+ let prepared = PreparedOperation::from_committed_store(
+ AdmissionRequest::new(binding, command).unwrap(),
+ TransactionId::from_bytes([9; 32]),
+ Sequence::new(1).unwrap(),
+ IssuanceWindow::new(now, UnixSeconds::new(150).unwrap()).unwrap(),
+ )
+ .unwrap();
+ let bound = BoundSigningPlan::from_committed_store(
+ prepared,
+ plan,
+ TransactionId::from_bytes([10; 32]),
+ now,
+ )
+ .unwrap();
+ SigningAttempt::from_committed_store(
+ bound,
+ SigningTarget::PublicEvent,
+ SigningAttemptId::from_bytes([11; 32]),
+ TransactionId::from_bytes([12; 32]),
+ now,
+ )
+ .unwrap()
+}
+
+#[test]
+fn refused_descriptor_keeps_actual_obtained_bytes_and_original_observation() {
+ let command = CapturedOrderAcceptance::parse(include_bytes!(
+ "../../tests/fixtures/commerce_verification/command_wire.json"
+ ))
+ .unwrap();
+ let record = commerce::decode(include_bytes!(
+ "../../tests/fixtures/commerce_verification/record_wire.json"
+ ))
+ .unwrap();
+ let rumor = EncodedCommerceRumor::capture(record.content()).unwrap();
+ let plan = CommerceSigningPlan::parse(
+ command.context().operation_id(),
+ command.digest(),
+ &rumor,
+ include_bytes!("../../tests/fixtures/commerce_verification/plan_wire.bin"),
+ )
+ .unwrap();
+ let intent = SigningIntent::from_commerce_seal(
+ &plan.seals()[0],
+ ProviderCall::new(
+ rumor.author(),
+ NonZeroU64::new(600000).unwrap(),
+ CancellationSignal::new(),
+ ),
+ )
+ .unwrap();
+ let wire = include_str!("../../tests/fixtures/commerce_verification/seal_signed.json");
+ let (_, OutcomeKind::Obtained(artifact)) =
+ SigningOutcome::capture(&intent, wire.into(), None).into_parts()
+ else {
+ panic!("retained independent bytes must authenticate against the original intent")
+ };
+ let event = artifact.event_id();
+ let retained = Obtained::new(foreign_attempt(), artifact);
+ for _ in 0..2 {
+ assert!(matches!(
+ retained.evidence(),
+ Err(OperationError::InvalidEvidence)
+ ));
+ assert_eq!(retained.operation(), OperationId::from_bytes([8; 32]));
+ assert_eq!(retained.artifact.event_id(), event);
+ assert_eq!(retained.artifact.observed_at_unix_ms(), None);
+ retained.artifact.with_json(|raw| assert_eq!(raw, wire));
+ }
+}
diff --git a/crates/execution/src/session/commerce_run.rs b/crates/execution/src/session/commerce_run.rs
@@ -176,7 +176,7 @@ impl CommandRuntime {
if snapshot.aborted() || !self.io.enabled() {
return Ok(status);
}
- self.drain().await.map_err(fail)?;
+ self.drain().await?;
resources.stock_captures.ensure_ready().map_err(fail)?;
let Some(signer) = resources.signer.as_ref() else {
return Ok(status);
@@ -280,6 +280,7 @@ impl CommandRuntime {
if report != claim || request.original().binding() != claim.binding {
return Err(fail(OperationError::RecoveryRequired));
}
+ self.ensure_ready()?;
match signer.recover_exact(request).await.into_parts().1 {
ExactRecoveryKind::Obtained(artifact) => Some((artifact, report)),
ExactRecoveryKind::Rejected(rejected) => {
@@ -318,6 +319,7 @@ impl CommandRuntime {
if intent.binding() != expected || report.binding != expected {
return Err(fail(OperationError::RecoveryRequired));
}
+ self.ensure_ready()?;
resources.stock_captures.ensure_ready().map_err(fail)?;
match signer.sign_exact(intent).await.into_parts().1 {
OutcomeKind::Obtained(artifact) => Some((artifact, report)),
diff --git a/crates/radroots/src/client.rs b/crates/radroots/src/client.rs
@@ -181,9 +181,7 @@ impl SessionHost for StoreHost {
crate::native_tasks::ControlKind::Drain,
Box::pin(async move {
if let Some(commands) = commands {
- commands.drain().await.map_err(|error| {
- Error::operation(error, OperationContext::proposed(None))
- })?;
+ commands.drain().await?;
}
Ok(())
}),
diff --git a/crates/radroots/tests/support/receipt_workflow_faults.rs b/crates/radroots/tests/support/receipt_workflow_faults.rs
@@ -495,8 +495,28 @@ async fn failed_obtained_capture_blocks_close_retains_writer_and_retries_without
assert_eq!(error.retry(), radroots::RetryClass::ManualReconciliation);
assert_eq!(error.context().admission(), Admission::Confirmed);
assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1);
+ let blocked = ready
+ .client
+ .inbox()
+ .inquire(ready.context(209, now() + 120), inquiry())
+ .await
+ .unwrap_err();
+ assert_eq!(blocked.code(), Code::StorageFailure);
+ assert_eq!(blocked.retry(), radroots::RetryClass::ManualReconciliation);
+ assert_eq!(
+ blocked.context().operation_id(),
+ Some(OperationId::from_bytes([205; 32]))
+ );
+ assert_eq!(blocked.context().admission(), Admission::Confirmed);
+ assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1);
let error = ready.client.close().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().operation_id(),
+ Some(OperationId::from_bytes([205; 32]))
+ );
+ assert_eq!(error.context().admission(), Admission::Confirmed);
assert_eq!(ready.client.state(), SessionState::Closing);
ready.writer_is_retained().await;
sqlx::query("DROP TRIGGER capture_insert_fault")
diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs
@@ -329,6 +329,8 @@ struct SigningPlanBinding {
ordinary_peer_installed_before_self_work: bool,
ordinary_accepted_task_survives_observer_loss: bool,
ordinary_obtained_owned_before_descriptor_conversion: bool,
+ generic_obtained_owned_before_descriptor_conversion: bool,
+ retained_drain_preserves_original_error_and_operation: bool,
rejected_signer_error: String,
effectful_command_result: String,
common_error_max_bytes: u16,
@@ -629,6 +631,12 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> {
&& stock
.signing_plan_binding
.ordinary_obtained_owned_before_descriptor_conversion
+ && stock
+ .signing_plan_binding
+ .generic_obtained_owned_before_descriptor_conversion
+ && stock
+ .signing_plan_binding
+ .retained_drain_preserves_original_error_and_operation
&& 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
@@ -1746,6 +1754,14 @@ mod tests {
fn signing_plans_require_complete_original_qualified_intents_before_any_signing() {
for (field, bad) in [
("effectful_command_result", json!("unbounded_error")),
+ (
+ "generic_obtained_owned_before_descriptor_conversion",
+ json!(false),
+ ),
+ (
+ "retained_drain_preserves_original_error_and_operation",
+ json!(false),
+ ),
("common_error_max_bytes", json!(128)),
("execution_failure_max_bytes", json!(256)),
("rejected_signer_error", json!("success")),