commit a18c88450b34a5321aa09e2bc29da1bc2fc126b0
parent 26756c1823984a6c26210d46ee7dbd56b90e5e1e
Author: triesap <tyson@radroots.org>
Date: Thu, 29 Oct 2026 11:44:07 +0000
storage: qualify stock delivery process and commit recovery
- Extend the private child harness across confirmed delivery and observation writes.
- Verify original bytes, transaction identities, retained attempts and conserved stock after reopen.
- Exercise ordinary outer and result retention through statement and COMMIT failures with clockless repair.
- Preserve frozen catalogs and qualify the affected native and default-stack Linux paths.
Diffstat:
3 files changed, 529 insertions(+), 141 deletions(-)
diff --git a/crates/radroots/src/native_stock_delivery_tests.rs b/crates/radroots/src/native_stock_delivery_tests.rs
@@ -2,66 +2,88 @@
use super::*;
#[tokio::test]
-async fn obtained_outer_is_retained_through_failed_sql_capture_and_clockless_drain() {
+async fn obtained_outer_is_retained_through_statement_and_commit_failure_and_clockless_drain() {
use sqlx::Connection;
- let r = Rig::new().await;
- r.control.pause_peer.store(true, Ordering::SeqCst);
- let (command, context) = r.captured().await;
- let (private, public, minimum) = r.minima().await;
- let input = AcceptOrderInput::new(
- command.input().request(),
- command.input().terms_digest(),
- AllocationSelection::automatic(),
- );
- let client = r.client.clone();
- let scope = r.scope.clone();
- let waiter = tokio::spawn(async move {
- client
- .orders(&scope)
- .accept(context, minimum, private, public, input)
- .await
- });
- tokio::time::timeout(
- std::time::Duration::from_secs(30),
- r.control.entered.notified(),
- )
- .await
- .unwrap();
- let path = r._temp.path().join("stock/stock_execution_v1.sqlite");
- let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display()))
- .await
- .unwrap();
- sqlx::query("CREATE TRIGGER controlled_outer_failure BEFORE INSERT ON stock_envelopes BEGIN SELECT RAISE(ABORT, 'controlled_outer_failure'); END").execute(&mut fault).await.unwrap();
- r.control.release.notify_one();
- let error = waiter.await.unwrap().unwrap_err();
- assert_eq!(error.code(), crate::Code::StorageFailure);
- assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1);
- assert!(r.io.sent.lock().unwrap().is_empty());
- sqlx::query("DROP TRIGGER controlled_outer_failure")
- .execute(&mut fault)
- .await
- .unwrap();
- fault.close().await.unwrap();
- r.clock.0.store(0, Ordering::SeqCst);
- r.client.stock(&r.scope).drain_evidence().await.unwrap();
- assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1);
- r.clock.0.store(150, Ordering::SeqCst);
- let resumed = r
- .client
- .orders(&r.scope)
- .resume_acceptance(minimum, command.context().operation_id(), command.digest())
+ for uncertain in [false, true] {
+ let r = Rig::new().await;
+ r.control.pause_peer.store(true, Ordering::SeqCst);
+ let (command, context) = r.captured().await;
+ let (private, public, minimum) = r.minima().await;
+ let input = AcceptOrderInput::new(
+ command.input().request(),
+ command.input().terms_digest(),
+ AllocationSelection::automatic(),
+ );
+ let client = r.client.clone();
+ let scope = r.scope.clone();
+ let waiter = tokio::spawn(async move {
+ client
+ .orders(&scope)
+ .accept(context, minimum, private, public, input)
+ .await
+ });
+ tokio::time::timeout(
+ std::time::Duration::from_secs(30),
+ r.control.entered.notified(),
+ )
.await
.unwrap();
- assert!(
- resumed
- .delivery()
- .unwrap()
- .iter()
- .all(|v| v.acceptance_satisfied().unwrap())
- );
- assert_eq!(r.io.wraps.load(Ordering::SeqCst), 2);
- assert_eq!(r.control.signs.load(Ordering::SeqCst), 2);
- r.client.close().await.unwrap();
+ let path = r._temp.path().join("stock/stock_execution_v1.sqlite");
+ let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display()))
+ .await
+ .unwrap();
+ if uncertain {
+ sqlx::raw_sql("CREATE TABLE outer_deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER controlled_outer_failure AFTER INSERT ON stock_envelopes BEGIN INSERT INTO outer_deferred_fault VALUES(2); END").execute(&mut fault).await.unwrap();
+ } else {
+ sqlx::query("CREATE TRIGGER controlled_outer_failure BEFORE INSERT ON stock_envelopes BEGIN SELECT RAISE(ABORT, 'controlled_outer_failure'); END").execute(&mut fault).await.unwrap();
+ }
+ r.control.release.notify_one();
+ let error = waiter.await.unwrap().unwrap_err();
+ assert_eq!(
+ error.code(),
+ if uncertain {
+ crate::Code::RecoveryRequired
+ } else {
+ crate::Code::StorageFailure
+ }
+ );
+ assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1);
+ assert!(r.io.sent.lock().unwrap().is_empty());
+ r.clock.0.store(0, Ordering::SeqCst);
+ assert!(r.client.stock(&r.scope).drain_evidence().await.is_err());
+ assert!(r.provider.upgrade().is_some());
+ sqlx::query("DROP TRIGGER controlled_outer_failure")
+ .execute(&mut fault)
+ .await
+ .unwrap();
+ if uncertain {
+ sqlx::query("DROP TABLE outer_deferred_fault")
+ .execute(&mut fault)
+ .await
+ .unwrap();
+ }
+ fault.close().await.unwrap();
+ r.clock.0.store(0, Ordering::SeqCst);
+ r.client.stock(&r.scope).drain_evidence().await.unwrap();
+ assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1);
+ r.clock.0.store(150, Ordering::SeqCst);
+ let resumed = r
+ .client
+ .orders(&r.scope)
+ .resume_acceptance(minimum, command.context().operation_id(), command.digest())
+ .await
+ .unwrap();
+ assert!(
+ resumed
+ .delivery()
+ .unwrap()
+ .iter()
+ .all(|v| v.acceptance_satisfied().unwrap())
+ );
+ assert_eq!(r.io.wraps.load(Ordering::SeqCst), 2);
+ assert_eq!(r.control.signs.load(Ordering::SeqCst), 2);
+ r.client.close().await.unwrap();
+ }
}
#[tokio::test]
@@ -322,56 +344,86 @@ async fn repeated_command_does_not_resend_and_signerless_resume_uses_exact_origi
}
#[tokio::test]
-async fn obtained_delivery_survives_failed_append_lost_waiter_and_clock_loss() {
+async fn obtained_delivery_survives_statement_and_commit_failure_lost_waiter_and_clock_loss() {
use sqlx::Connection;
- let r = Rig::new().await;
- r.io.pause_delivery.store(true, Ordering::SeqCst);
- let (command, context) = r.captured().await;
- let (private, public, minimum) = r.minima().await;
- let input = AcceptOrderInput::new(
- command.input().request(),
- command.input().terms_digest(),
- AllocationSelection::automatic(),
- );
- let client = r.client.clone();
- let scope = r.scope.clone();
- let waiter = tokio::spawn(async move {
- client
- .orders(&scope)
- .accept(context, minimum, private, public, input)
+ for uncertain in [false, true] {
+ let r = Rig::new().await;
+ r.io.pause_delivery.store(true, Ordering::SeqCst);
+ let (command, context) = r.captured().await;
+ let (private, public, minimum) = r.minima().await;
+ let input = AcceptOrderInput::new(
+ command.input().request(),
+ command.input().terms_digest(),
+ AllocationSelection::automatic(),
+ );
+ let client = r.client.clone();
+ let scope = r.scope.clone();
+ let waiter = tokio::spawn(async move {
+ client
+ .orders(&scope)
+ .accept(context, minimum, private, public, input)
+ .await
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(30), r.io.entered.notified())
.await
- });
- tokio::time::timeout(std::time::Duration::from_secs(30), r.io.entered.notified())
- .await
- .unwrap();
- assert_eq!(r.io.sent.lock().unwrap().len(), 1);
- assert_eq!(r.control.signs.load(Ordering::SeqCst), 1);
- waiter.abort();
- assert!(waiter.await.unwrap_err().is_cancelled());
- let path = r._temp.path().join("stock/stock_execution_v1.sqlite");
- let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display()))
- .await
- .unwrap();
- sqlx::query("CREATE TRIGGER controlled_d_failure BEFORE INSERT ON stock_delivery_observations BEGIN SELECT RAISE(ABORT, 'controlled_d_failure'); END").execute(&mut fault).await.unwrap();
- r.clock.0.store(0, Ordering::SeqCst);
- r.io.release.notify_one();
- // Close drains the admitted task and then its retained raw result, keeping
- // the original credential and resource lease through the actual SQL fault.
- let error = r.client.close().await.unwrap_err();
- assert_eq!(error.code(), crate::Code::StorageFailure);
- assert!(r.provider.upgrade().is_some());
- sqlx::query("DROP TRIGGER controlled_d_failure")
- .execute(&mut fault)
- .await
- .unwrap();
- r.client.close().await.unwrap();
- assert!(r.provider.upgrade().is_none());
- let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_delivery_observations")
- .fetch_one(&mut fault)
- .await
- .unwrap();
- assert_eq!(count, 1);
- assert_eq!(r.io.sent.lock().unwrap().len(), 1);
- assert_eq!(r.control.signs.load(Ordering::SeqCst), 1);
- fault.close().await.unwrap();
+ .unwrap();
+ assert_eq!(r.io.sent.lock().unwrap().len(), 1);
+ assert_eq!(r.control.signs.load(Ordering::SeqCst), 1);
+ waiter.abort();
+ assert!(waiter.await.unwrap_err().is_cancelled());
+ let path = r._temp.path().join("stock/stock_execution_v1.sqlite");
+ let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display()))
+ .await
+ .unwrap();
+ let original: (Vec<u8>, Vec<u8>) =
+ sqlx::query_as("SELECT entry_id,request_key FROM stock_delivery_attempts")
+ .fetch_one(&mut fault)
+ .await
+ .unwrap();
+ if uncertain {
+ sqlx::raw_sql("CREATE TABLE delivery_deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER controlled_d_failure AFTER INSERT ON stock_delivery_observations BEGIN INSERT INTO delivery_deferred_fault VALUES(2); END").execute(&mut fault).await.unwrap();
+ } else {
+ sqlx::query("CREATE TRIGGER controlled_d_failure BEFORE INSERT ON stock_delivery_observations BEGIN SELECT RAISE(ABORT, 'controlled_d_failure'); END").execute(&mut fault).await.unwrap();
+ }
+ r.clock.0.store(0, Ordering::SeqCst);
+ r.io.release.notify_one();
+ // Close drains the admitted task and then its retained raw result, keeping
+ // the original credential and resource lease through the actual SQL fault.
+ let error = r.client.close().await.unwrap_err();
+ assert_eq!(
+ error.code(),
+ if uncertain {
+ crate::Code::RecoveryRequired
+ } else {
+ crate::Code::StorageFailure
+ }
+ );
+ assert!(r.provider.upgrade().is_some());
+ sqlx::query("DROP TRIGGER controlled_d_failure")
+ .execute(&mut fault)
+ .await
+ .unwrap();
+ if uncertain {
+ sqlx::query("DROP TABLE delivery_deferred_fault")
+ .execute(&mut fault)
+ .await
+ .unwrap();
+ }
+ r.client.close().await.unwrap();
+ assert!(r.provider.upgrade().is_none());
+ let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_delivery_observations")
+ .fetch_one(&mut fault)
+ .await
+ .unwrap();
+ assert_eq!(count, 1);
+ let attempts: Vec<(Vec<u8>, Vec<u8>)> =
+ sqlx::query_as("SELECT entry_id,request_key FROM stock_delivery_attempts")
+ .fetch_all(&mut fault)
+ .await
+ .unwrap();
+ assert_eq!(attempts, vec![original]);
+ assert_eq!(r.io.sent.lock().unwrap().len(), 1);
+ assert_eq!(r.control.signs.load(Ordering::SeqCst), 1);
+ fault.close().await.unwrap();
+ }
}
diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs
@@ -1,6 +1,6 @@
-//! Private process-death qualification of S, T2, original outer retention and abort.
+//! Private process-death qualification of confirmed stock and original delivery writes.
use super::*;
-use radroots_domain::{CommandDigest, OperationId};
+use radroots_domain::{CommandDigest, OperationId, TransactionId};
use radroots_secrets::{
file::{FileOpenMode, FileProvider},
wrapping::SecretMaterial,
@@ -16,13 +16,17 @@ use std::{
const BARRIER: &str = "RADROOTS_STOCK_PROCESS_BOUNDARY_V1";
const CHILD: &str = "workspace::stock::public_source::tests::provider::history::acceptance::signing::claims::evidence::installations::process_death::stock_process_child";
+#[path = "process_delivery_tests.rs"]
+mod delivery;
-#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
enum Edge {
Capture,
Install,
Abort,
Envelope,
+ Delivery,
+ Observation,
}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
@@ -36,6 +40,7 @@ struct Control {
wrapping_key: Option<[u8; 32]>,
edge: Edge,
before: bool,
+ delivery_transaction: Option<TransactionId>,
}
struct KillOnDrop(Child);
impl Drop for KillOnDrop {
@@ -44,7 +49,7 @@ impl Drop for KillOnDrop {
let _ = self.0.wait();
}
}
-fn stop_at_boundary(root: &std::path::Path) {
+fn stop_at_boundary(root: &std::path::Path) -> Option<TransactionId> {
let mut child = KillOnDrop(
Command::new(std::env::current_exe().unwrap())
.args([
@@ -66,21 +71,26 @@ fn stop_at_boundary(root: &std::path::Path) {
let stdout = child.0.stdout.take().unwrap();
let (send, receive) = mpsc::channel();
let reader = std::thread::spawn(move || {
+ let mut transaction = None;
for line in std::io::BufReader::new(stdout).lines().take(12) {
let line = line.unwrap();
+ if let Some(value) = line.strip_prefix("STOCK_TRANSACTION=") {
+ transaction = serde_json::from_str(value).unwrap();
+ }
if line.ends_with(BARRIER) {
- let _ = send.send(());
+ let _ = send.send(transaction);
return;
}
}
});
- receive.recv_timeout(Duration::from_secs(60)).unwrap();
+ let transaction = receive.recv_timeout(Duration::from_secs(60)).unwrap();
assert!(child.0.try_wait().unwrap().is_none());
child.0.kill().unwrap();
let status = child.0.wait().unwrap();
use std::os::unix::process::ExitStatusExt;
assert_eq!(status.signal(), Some(9));
reader.join().unwrap();
+ transaction
}
#[tokio::test]
@@ -139,12 +149,15 @@ async fn stock_process_child() {
.await
.unwrap();
let minimum = store
- .stock_authority(control.input, &proof)
+ .stock_authority(control.input.clone(), &proof)
.await
.unwrap()
.inventory_checkpoint()
.unwrap();
- let capture = if matches!(control.edge, Edge::Abort | Edge::Envelope) {
+ let capture = if matches!(
+ control.edge,
+ Edge::Abort | Edge::Envelope | Edge::Delivery | Edge::Observation
+ ) {
None
} else {
let report = store
@@ -240,15 +253,24 @@ async fn stock_process_child() {
.unwrap(),
);
}
+ Edge::Delivery | Edge::Observation => {
+ return Some(delivery::apply(&store, binding, minimum, &proof, &control).await);
+ }
}
+ None
};
let mut work = Box::pin(work);
- if control.before {
+ let transaction = if control.before {
assert!(futures::poll!(work.as_mut()).is_pending());
provider.gate.entered();
+ None
} else {
- work.as_mut().await;
- }
+ work.as_mut().await
+ };
+ println!(
+ "\nSTOCK_TRANSACTION={}",
+ serde_json::to_string(&transaction).unwrap()
+ );
println!("{BARRIER}");
std::io::stdout().flush().unwrap();
loop {
@@ -257,10 +279,18 @@ async fn stock_process_child() {
}
#[tokio::test]
-async fn process_death_before_and_after_capture_install_abort_or_envelope_preserves_original_stock_and_evidence()
+async fn process_death_before_and_after_confirmed_stock_writes_preserves_originals_and_dispatch_boundaries()
{
- for edge in [Edge::Capture, Edge::Install, Edge::Abort, Edge::Envelope] {
+ for edge in [
+ Edge::Capture,
+ Edge::Install,
+ Edge::Abort,
+ Edge::Envelope,
+ Edge::Delivery,
+ Edge::Observation,
+ ] {
for before in [true, false] {
+ println!("stock boundary {edge:?} before={before}");
let mut r = Rig::new().await;
let receipt = if matches!(edge, Edge::Abort) {
Box::pin(prepared(&r)).await.1
@@ -274,7 +304,10 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
let (report, raw) = Box::pin(obtained(&r, &receipt, recipient)).await;
(Some(report), raw)
};
- if matches!(edge, Edge::Install | Edge::Envelope) {
+ if matches!(
+ edge,
+ Edge::Install | Edge::Envelope | Edge::Delivery | Edge::Observation
+ ) {
let capture = StockEvidenceCapture::verify(
r.binding.clone(),
report.as_ref().unwrap(),
@@ -289,22 +322,22 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
.unwrap(),
);
}
- let wrapping_key = if matches!(edge, Edge::Envelope) {
- installed(install(&r, &receipt).await.unwrap());
- let pending = radroots_nostr::signing::gift_wrap::wrap_retained_seal(
- &raw,
- recipient,
- std::num::NonZeroU64::new(150000).unwrap(),
- &radroots_nostr::signing::OsNonceSource,
- )
- .unwrap();
- raw = pending.signed_json().to_owned();
- Some(pending.with_wrapping_key(|key| *key))
- } else {
- None
- };
- let minimum = inventory_minimum(&r).await;
- let control = Control {
+ let wrapping_key =
+ if matches!(edge, Edge::Envelope | Edge::Delivery | Edge::Observation) {
+ installed(install(&r, &receipt).await.unwrap());
+ let pending = radroots_nostr::signing::gift_wrap::wrap_retained_seal(
+ &raw,
+ recipient,
+ std::num::NonZeroU64::new(150).unwrap(),
+ &radroots_nostr::signing::OsNonceSource,
+ )
+ .unwrap();
+ raw = pending.signed_json().to_owned();
+ Some(pending.with_wrapping_key(|key| *key))
+ } else {
+ None
+ };
+ let mut control = Control {
input: r.enrollment.input().clone(),
proof: r.enrollment.proof().with_secret(|bytes| bytes.to_vec()),
operation: receipt.attempt().operation_id(),
@@ -314,7 +347,12 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
wrapping_key,
edge,
before,
+ delivery_transaction: None,
};
+ if matches!(edge, Edge::Delivery | Edge::Observation) {
+ control.delivery_transaction = Box::pin(delivery::prepare(&r, &control)).await;
+ }
+ let minimum = inventory_minimum(&r).await;
let mut file = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
@@ -325,7 +363,7 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
.unwrap();
file.sync_all().unwrap();
r.store.close().await.unwrap();
- stop_at_boundary(&r.fixture.root());
+ let transaction = stop_at_boundary(&r.fixture.root());
reopen_plain(&mut r).await;
let current = inventory_minimum(&r).await;
assert_eq!(
@@ -358,11 +396,14 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
.iter()
.find(|value| value.recipient() == recipient)
.unwrap();
- let has_evidence = matches!(edge, Edge::Install | Edge::Envelope)
- || (matches!(edge, Edge::Capture) && !before);
+ let has_evidence = matches!(
+ edge,
+ Edge::Install | Edge::Envelope | Edge::Delivery | Edge::Observation
+ ) || (matches!(edge, Edge::Capture) && !before);
assert_eq!(peer.first_evidence().is_some(), has_evidence);
let has_installation =
- matches!(edge, Edge::Envelope) || (matches!(edge, Edge::Install) && !before);
+ matches!(edge, Edge::Envelope | Edge::Delivery | Edge::Observation)
+ || (matches!(edge, Edge::Install) && !before);
assert_eq!(snapshot.installation().is_some(), has_installation);
let has_abort = matches!(edge, Edge::Abort) && !before;
assert_eq!(snapshot.aborted().is_some(), has_abort);
@@ -384,6 +425,9 @@ async fn process_death_before_and_after_capture_install_abort_or_envelope_preser
balances(&r, 81, 8, 2, 0, 2).await;
}
assert_eq!(inventory_minimum(&r).await, current);
+ if matches!(edge, Edge::Delivery | Edge::Observation) {
+ Box::pin(delivery::verify(&r, &control, transaction)).await;
+ }
if matches!(edge, Edge::Abort) {
let first = aborts::released(aborts::abort(&r, &receipt).await.unwrap());
if let Some(original) = snapshot.aborted() {
diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/process_delivery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/process_delivery_tests.rs
@@ -0,0 +1,292 @@
+//! Delivery edges of the private stock process-death harness.
+use super::*;
+use radroots_storage::{
+ command::{DeliveryIntent, PrivateEnvelopeCandidate},
+ inventory::*,
+};
+use radroots_transport::{
+ Target, TargetSet,
+ outcome::DeliveryOutcome,
+ policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy},
+ sink::DeliveryTargetReceipt,
+};
+
+fn candidate(c: &Control) -> PrivateEnvelopeCandidate {
+ PrivateEnvelopeCandidate::from_obtained(c.recipient, &c.raw, &c.wrapping_key.unwrap()).unwrap()
+}
+fn intent(c: &Control) -> DeliveryIntent {
+ DeliveryIntent::new(
+ &format!("{:064x}", 23),
+ candidate(c).event_id(),
+ &TargetSet::new(vec![Target::nostr_relay("wss://relay.example").unwrap()]).unwrap(),
+ &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()),
+ std::num::NonZeroU64::new(180000).unwrap(),
+ )
+ .unwrap()
+}
+fn source(
+ binding: radroots_storage::workspace::WorkspaceBinding,
+ minimum: InventoryCheckpointRef,
+ c: &Control,
+) -> StockEnvelopeRequest {
+ StockEnvelopeRequest::new(binding, minimum, c.operation, c.digest, c.recipient, None).unwrap()
+}
+fn request(
+ binding: radroots_storage::workspace::WorkspaceBinding,
+ minimum: InventoryCheckpointRef,
+ c: &Control,
+) -> StockDeliveryRequest {
+ StockDeliveryRequest::new(
+ binding,
+ minimum,
+ c.operation,
+ c.digest,
+ c.recipient,
+ intent(c),
+ )
+ .unwrap()
+}
+fn observation(
+ attempt: &StockDeliveryAttempt,
+ outcome: DeliveryOutcome,
+) -> StockDeliveryObservation {
+ StockDeliveryObservation::from_store_report(
+ attempt,
+ &DeliveryTargetReceipt::attempted(attempt.intent().targets().targets()[0].clone(), outcome),
+ None,
+ )
+ .unwrap()
+}
+pub(super) async fn prepare(r: &Rig, c: &Control) -> Option<TransactionId> {
+ assert!(matches!(
+ r.store
+ .capture_stock_envelope(
+ source(r.binding.clone(), inventory_minimum(r).await, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ &candidate(c),
+ )
+ .await
+ .unwrap(),
+ StockEnvelopeOutcome::Committed(_)
+ ));
+ if matches!(c.edge, Edge::Observation) {
+ let StockDeliveryAttemptOutcome::Claimed(attempt) = r
+ .store
+ .prepare_stock_delivery_attempt(
+ request(r.binding.clone(), inventory_minimum(r).await, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("new confirmed D required")
+ };
+ Some(attempt.transaction_id())
+ } else {
+ None
+ }
+}
+pub(super) async fn apply(
+ store: &NativeWorkspace,
+ binding: radroots_storage::workspace::WorkspaceBinding,
+ minimum: InventoryCheckpointRef,
+ proof: &AttachmentProof,
+ c: &Control,
+) -> TransactionId {
+ if matches!(c.edge, Edge::Delivery) {
+ let StockDeliveryAttemptOutcome::Claimed(attempt) = store
+ .prepare_stock_delivery_attempt(
+ request(binding, minimum, c),
+ proof
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("new confirmed D required")
+ };
+ attempt.transaction_id()
+ } else {
+ let attempt = store
+ .stock_delivery_attempt(
+ source(binding.clone(), minimum, c),
+ intent(c).request_id().clone(),
+ proof
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(Some(attempt.transaction_id()), c.delivery_transaction);
+ let StockDeliveryObservationOutcome::Committed(saved) = store
+ .record_stock_delivery_observation(
+ &binding,
+ proof,
+ &observation(&attempt, DeliveryOutcome::accepted()),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("confirmed original observation required")
+ };
+ saved.transaction_id()
+ }
+}
+pub(super) async fn verify(r: &Rig, c: &Control, transaction: Option<TransactionId>) {
+ let minimum = inventory_minimum(r).await;
+ let outer = r
+ .store
+ .stock_envelope(
+ source(r.binding.clone(), minimum, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ outer.with_json(|raw| assert_eq!(raw, c.raw));
+ let loaded = r
+ .store
+ .stock_delivery_attempt(
+ source(r.binding.clone(), minimum, c),
+ intent(c).request_id().clone(),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ loaded.is_some(),
+ matches!(c.edge, Edge::Observation) || !c.before
+ );
+ assert_eq!(transaction.is_some(), !c.before);
+ let has_attempt = loaded.is_some();
+ if let Some(attempt) = loaded {
+ attempt.source().with_json(|raw| assert_eq!(raw, c.raw));
+ assert_eq!(attempt.intent(), &intent(c));
+ assert_eq!(
+ Some(attempt.transaction_id()),
+ if matches!(c.edge, Edge::Delivery) {
+ transaction
+ } else {
+ c.delivery_transaction
+ }
+ );
+ // Recovery queries and exact existing D requests grant no new invocation.
+ let StockDeliveryAttemptOutcome::Retained(repeated) = r
+ .store
+ .prepare_stock_delivery_attempt(
+ request(r.binding.clone(), minimum, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("reopened D must never grant dispatch")
+ };
+ assert_eq!(repeated.transaction_id(), attempt.transaction_id());
+ let page = r
+ .store
+ .stock_delivery_observations(
+ source(r.binding.clone(), minimum, c),
+ None,
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert!(page.next_after().is_none());
+ let confirmed = matches!(c.edge, Edge::Observation) && !c.before;
+ assert_eq!(page.entries().len(), usize::from(confirmed));
+ if confirmed {
+ let original = &page.entries()[0];
+ assert_eq!(Some(original.transaction_id()), transaction);
+ assert_eq!(
+ original.observation(),
+ &observation(&attempt, DeliveryOutcome::accepted())
+ );
+ assert!(original.observation().observed_at_unix_ms().is_none());
+ let StockDeliveryObservationOutcome::Committed(repeated) = r
+ .store
+ .record_stock_delivery_observation(
+ &r.binding,
+ r.enrollment.proof(),
+ original.observation(),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("original observation must remain confirmed")
+ };
+ assert_eq!(&*repeated, original);
+ // A later class is independent evidence; it cannot replace accepted.
+ let StockDeliveryObservationOutcome::Committed(later) = r
+ .store
+ .record_stock_delivery_observation(
+ &r.binding,
+ r.enrollment.proof(),
+ &observation(&attempt, DeliveryOutcome::unavailable()),
+ )
+ .await
+ .unwrap()
+ else {
+ panic!("independent class must append")
+ };
+ assert_ne!(later.transaction_id(), original.transaction_id());
+ let summary = r
+ .store
+ .stock_delivery_summary(
+ source(r.binding.clone(), minimum, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert!(summary.acceptance_satisfied().unwrap());
+ } else {
+ assert_eq!(inventory_minimum(r).await, minimum);
+ }
+ } else {
+ assert_eq!(inventory_minimum(r).await, minimum);
+ }
+ let summary = r
+ .store
+ .stock_delivery_summary(
+ source(r.binding.clone(), minimum, c),
+ r.enrollment
+ .proof()
+ .with_secret(|bytes| AttachmentProof::from_protected_input(bytes))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(summary.attempt_count(), u16::from(has_attempt));
+ assert_eq!(
+ summary.acceptance_satisfied().unwrap(),
+ matches!(c.edge, Edge::Observation) && !c.before
+ );
+ if has_attempt {
+ assert_eq!(summary.targets()[0].potential_attempts(), 1);
+ }
+ balances(r, 80, 9, 0, 1, 3).await;
+ balances(r, 81, 8, 0, 2, 3).await;
+}