lib

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

pool_creation.rs (36295B)


      1 use super::*;
      2 use radroots_domain::{
      3     CommandContextData, Decimal, OperationId, PoolId, Quantity, listing::MeasurementUnit,
      4     stock::PoolUnit,
      5 };
      6 use radroots_protocol::command::{CapturedPoolCreation, CreatePoolInput};
      7 use radroots_storage::{
      8     command::OperationError,
      9     inventory::{
     10         InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, InventoryRequest,
     11         InventoryStore,
     12     },
     13 };
     14 use radroots_storage_sqlite::workspace::{SellerStockConfig, StockEnrollment};
     15 use sqlx::Connection;
     16 fn proof(value: &AttachmentProof) -> AttachmentProof {
     17     value
     18         .with_secret(|b| AttachmentProof::from_protected_input(b))
     19         .unwrap()
     20 }
     21 fn minimum(binding: &radroots_storage::workspace::WorkspaceBinding) -> InventoryCheckpointRef {
     22     InventoryCheckpointRef::from_host_metadata(
     23         binding.input().authority(),
     24         radroots_domain::Sequence::new(0).unwrap(),
     25         None,
     26     )
     27     .unwrap()
     28     .with_optional_authorization(binding.stock_authorization())
     29 }
     30 fn request(
     31     binding: &radroots_storage::workspace::WorkspaceBinding,
     32     operation: u8,
     33     pool: u8,
     34     label: &str,
     35 ) -> InventoryRequest {
     36     let input = binding.input();
     37     let context = CommandContextData::new(
     38         OperationId::from_bytes([operation; 32]),
     39         binding.actor(),
     40         input.workspace_id(),
     41         input.authority(),
     42         input.route_digest(),
     43         None,
     44         None,
     45         UnixSeconds::new(150).unwrap(),
     46         None,
     47     )
     48     .unwrap();
     49     let quantity = Quantity::new(
     50         "0.25".parse::<Decimal>().unwrap(),
     51         MeasurementUnit::Kilogram,
     52     )
     53     .unwrap();
     54     InventoryRequest::new(
     55         binding.clone(),
     56         minimum(binding),
     57         CapturedPoolCreation::new(
     58             context,
     59             CreatePoolInput::new(
     60                 PoolId::from_bytes([pool; 32]),
     61                 label,
     62                 PoolUnit::new(MeasurementUnit::Kilogram, 3).unwrap(),
     63                 quantity,
     64             )
     65             .unwrap(),
     66         )
     67         .unwrap(),
     68     )
     69     .unwrap()
     70 }
     71 async fn create(
     72     f: &Fixture,
     73 ) -> (
     74     NativeWorkspace,
     75     StockEnrollment,
     76     radroots_storage::workspace::WorkspaceBinding,
     77 ) {
     78     let enrollment = StockEnrollment::prepare(
     79         SellerStockConfig::new(
     80             key(),
     81             key(),
     82             "inventory-owner",
     83             UnixSeconds::new(200).unwrap(),
     84         )
     85         .unwrap(),
     86         f.clock.as_ref(),
     87     )
     88     .unwrap();
     89     let store =
     90         NativeWorkspace::initialize_seller_stock(&f.path, &enrollment, f.crypto(), f.clock.clone())
     91             .await
     92             .unwrap();
     93     let binding = store
     94         .authenticate(enrollment.input().clone(), enrollment.proof())
     95         .await
     96         .unwrap();
     97     (store, enrollment, binding)
     98 }
     99 fn committed(outcome: InventoryOutcome) -> InventoryReceipt {
    100     match outcome {
    101         InventoryOutcome::Committed(receipt) => *receipt,
    102         InventoryOutcome::Unknown(_) => panic!("expected confirmed inventory commit"),
    103     }
    104 }
    105 async fn database(f: &Fixture) -> sqlx::SqliteConnection {
    106     sqlx::SqliteConnection::connect_with(
    107         &sqlx::sqlite::SqliteConnectOptions::new()
    108             .filename(f.path.join("stock_execution_v1.sqlite"))
    109             .foreign_keys(true),
    110     )
    111     .await
    112     .unwrap()
    113 }
    114 #[tokio::test]
    115 async fn real_inventory_operation_commits_reopens_and_replays_original_effect_after_command_expiry()
    116 {
    117     let f = Fixture::new();
    118     let (store, e, binding) = create(&f).await;
    119     let original = request(&binding, 1, 2, "Carrots");
    120     let digest = original.command().digest();
    121     let receipt = committed(
    122         store
    123             .execute_inventory(original, proof(e.proof()))
    124             .await
    125             .unwrap(),
    126     );
    127     assert_eq!(receipt.pool().balances().physical().available.get(), 250);
    128     assert_eq!(receipt.pool().balances().introduced().get(), 250);
    129     assert_eq!(receipt.pool().unit().scale(), 3);
    130     assert_eq!(receipt.pool().version().get(), 1);
    131     assert_eq!(
    132         store
    133             .pool(
    134                 binding.clone(),
    135                 minimum(&binding),
    136                 PoolId::from_bytes([2; 32]),
    137                 proof(e.proof())
    138             )
    139             .await
    140             .unwrap()
    141             .map(|view| {
    142                 assert_eq!(view.label(), "Carrots");
    143                 view.snapshot()
    144             }),
    145         Some(receipt.pool())
    146     );
    147     assert_eq!(
    148         store
    149             .inventory_operation(
    150                 binding.clone(),
    151                 minimum(&binding),
    152                 OperationId::from_bytes([1; 32]),
    153                 Some(digest),
    154                 proof(e.proof())
    155             )
    156             .await
    157             .unwrap(),
    158         Some(receipt.clone())
    159     );
    160     f.clock.0.store(175, Ordering::SeqCst);
    161     assert_eq!(
    162         committed(
    163             store
    164                 .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    165                 .await
    166                 .unwrap()
    167         ),
    168         receipt
    169     );
    170     assert!(matches!(
    171         store
    172             .execute_inventory(request(&binding, 1, 2, "Changed"), proof(e.proof()))
    173             .await,
    174         Err(OperationError::IdempotencyConflict)
    175     ));
    176     assert!(matches!(
    177         store
    178             .execute_inventory(request(&binding, 3, 4, "Late"), proof(e.proof()))
    179             .await,
    180         Err(OperationError::DeadlineExceeded)
    181     ));
    182     store.close().await.unwrap();
    183     let store =
    184         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    185             .await
    186             .unwrap();
    187     assert_eq!(
    188         store
    189             .inventory_operation(
    190                 binding.clone(),
    191                 minimum(&binding),
    192                 OperationId::from_bytes([1; 32]),
    193                 Some(digest),
    194                 proof(e.proof())
    195             )
    196             .await
    197             .unwrap(),
    198         Some(receipt)
    199     );
    200     store.close().await.unwrap();
    201     let mut connection = database(&f).await;
    202     for table in ["stock_pools", "stock_operations", "stock_movements"] {
    203         let sql = format!("SELECT count(*) FROM {table}");
    204         let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
    205             .fetch_one(&mut connection)
    206             .await
    207             .unwrap();
    208         assert_eq!(count, 1);
    209     }
    210     let protected: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_pools")
    211         .fetch_one(&mut connection)
    212         .await
    213         .unwrap();
    214     assert!(!String::from_utf8_lossy(&protected).contains("Carrots"));
    215     connection.close().await.unwrap();
    216 }
    217 #[tokio::test]
    218 async fn each_actual_inventory_write_failure_rolls_back_pool_journal_movement_and_root() {
    219     for (table, statement) in [
    220         (
    221             "stock_pools",
    222             "CREATE TRIGGER fail_inventory BEFORE INSERT ON stock_pools BEGIN SELECT RAISE(ABORT,'isolated fault'); END",
    223         ),
    224         (
    225             "stock_operations",
    226             "CREATE TRIGGER fail_inventory BEFORE INSERT ON stock_operations BEGIN SELECT RAISE(ABORT,'isolated fault'); END",
    227         ),
    228         (
    229             "stock_movements",
    230             "CREATE TRIGGER fail_inventory BEFORE INSERT ON stock_movements BEGIN SELECT RAISE(ABORT,'isolated fault'); END",
    231         ),
    232         (
    233             "stock_authority",
    234             "CREATE TRIGGER fail_inventory BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'isolated fault'); END",
    235         ),
    236     ] {
    237         let f = Fixture::new();
    238         let (store, e, binding) = create(&f).await;
    239         let mut connection = database(&f).await;
    240         sqlx::raw_sql(statement)
    241             .execute(&mut connection)
    242             .await
    243             .unwrap();
    244         assert!(
    245             store
    246                 .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    247                 .await
    248                 .is_err(),
    249             "{table}"
    250         );
    251         for name in ["stock_pools", "stock_operations", "stock_movements"] {
    252             let sql = format!("SELECT count(*) FROM {name}");
    253             let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
    254                 .fetch_one(&mut connection)
    255                 .await
    256                 .unwrap();
    257             assert_eq!(count, 0, "{table}/{name}");
    258         }
    259         store
    260             .stock_authority(e.input().clone(), e.proof())
    261             .await
    262             .unwrap();
    263         sqlx::raw_sql("DROP TRIGGER fail_inventory")
    264             .execute(&mut connection)
    265             .await
    266             .unwrap();
    267         connection.close().await.unwrap();
    268         store.close().await.unwrap();
    269         let store = NativeWorkspace::open_seller_stock(
    270             &f.path,
    271             e.input().clone(),
    272             f.crypto(),
    273             f.clock.clone(),
    274         )
    275         .await
    276         .unwrap();
    277         assert!(
    278             store
    279                 .pool(
    280                     binding.clone(),
    281                     minimum(&binding),
    282                     PoolId::from_bytes([2; 32]),
    283                     proof(e.proof())
    284                 )
    285                 .await
    286                 .unwrap()
    287                 .is_none()
    288         );
    289         store.close().await.unwrap();
    290     }
    291 }
    292 #[tokio::test]
    293 async fn actual_inventory_commit_failure_is_unknown_and_fenced_until_reopen() {
    294     let f = Fixture::new();
    295     let (store, e, binding) = create(&f).await;
    296     let mut connection = database(&f).await;
    297     sqlx::raw_sql("CREATE TABLE deferred_inventory_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER inventory_commit_fault AFTER INSERT ON stock_movements BEGIN INSERT INTO deferred_inventory_fault VALUES(2); END").execute(&mut connection).await.unwrap();
    298     let original = request(&binding, 1, 2, "Carrots");
    299     let digest = original.command().digest();
    300     let anchor = match store
    301         .execute_inventory(original, proof(e.proof()))
    302         .await
    303         .unwrap()
    304     {
    305         InventoryOutcome::Unknown(anchor) => anchor,
    306         InventoryOutcome::Committed(_) => panic!("COMMIT must fail"),
    307     };
    308     assert_eq!(anchor.command_digest(), digest);
    309     assert!(anchor.transaction_id().is_some());
    310     assert!(matches!(
    311         store
    312             .inventory_operation(
    313                 binding.clone(),
    314                 minimum(&binding),
    315                 OperationId::from_bytes([1; 32]),
    316                 Some(digest),
    317                 proof(e.proof())
    318             )
    319             .await,
    320         Err(OperationError::RecoveryRequired)
    321     ));
    322     store.close().await.unwrap();
    323     sqlx::raw_sql("DROP TRIGGER inventory_commit_fault; DROP TABLE deferred_inventory_fault")
    324         .execute(&mut connection)
    325         .await
    326         .unwrap();
    327     connection.close().await.unwrap();
    328     let store =
    329         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    330             .await
    331             .unwrap();
    332     assert!(
    333         store
    334             .inventory_operation(
    335                 binding.clone(),
    336                 minimum(&binding),
    337                 OperationId::from_bytes([1; 32]),
    338                 Some(digest),
    339                 proof(e.proof())
    340             )
    341             .await
    342             .unwrap()
    343             .is_none()
    344     );
    345     assert!(
    346         store
    347             .pool(
    348                 binding.clone(),
    349                 minimum(&binding),
    350                 PoolId::from_bytes([2; 32]),
    351                 proof(e.proof())
    352             )
    353             .await
    354             .unwrap()
    355             .is_none()
    356     );
    357     store.close().await.unwrap();
    358 }
    359 #[tokio::test]
    360 async fn sealed_root_detects_missing_inventory_history_instead_of_fresh_stock() {
    361     let f = Fixture::new();
    362     let (store, e, binding) = create(&f).await;
    363     committed(
    364         store
    365             .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    366             .await
    367             .unwrap(),
    368     );
    369     let mut connection = database(&f).await;
    370     sqlx::raw_sql(
    371         "DELETE FROM stock_movements; DELETE FROM stock_operation_parts; DELETE FROM stock_operations; DELETE FROM stock_pools",
    372     )
    373     .execute(&mut connection)
    374     .await
    375     .unwrap();
    376     connection.close().await.unwrap();
    377     assert!(
    378         store
    379             .pool(
    380                 binding.clone(),
    381                 minimum(&binding),
    382                 PoolId::from_bytes([2; 32]),
    383                 proof(e.proof())
    384             )
    385             .await
    386             .is_err()
    387     );
    388     store.close().await.unwrap();
    389     assert!(
    390         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    391             .await
    392             .is_err()
    393     );
    394 }
    395 
    396 #[tokio::test]
    397 async fn acknowledged_minimum_refuses_a_complete_older_database_snapshot() {
    398     let f = Fixture::new();
    399     let (store, e, binding) = create(&f).await;
    400     store.close().await.unwrap();
    401     let path = f.path.join("stock_execution_v1.sqlite");
    402     let original = std::fs::read(&path).unwrap();
    403     let store =
    404         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    405             .await
    406             .unwrap();
    407     let receipt = committed(
    408         store
    409             .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    410             .await
    411             .unwrap(),
    412     );
    413     let acknowledged = receipt.checkpoint();
    414     assert_eq!(acknowledged.revision().get(), 1);
    415     assert!(acknowledged.head().is_some());
    416     assert_eq!(
    417         store
    418             .stock_authority(e.input().clone(), e.proof())
    419             .await
    420             .unwrap()
    421             .inventory_checkpoint(),
    422         Some(acknowledged)
    423     );
    424     store.close().await.unwrap();
    425     std::fs::write(&path, original).unwrap();
    426     let store =
    427         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    428             .await
    429             .unwrap();
    430     assert!(matches!(
    431         store
    432             .pool(
    433                 binding.clone(),
    434                 acknowledged,
    435                 PoolId::from_bytes([2; 32]),
    436                 proof(e.proof())
    437             )
    438             .await,
    439         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    440     ));
    441     assert!(matches!(
    442         store
    443             .inventory_operation(
    444                 binding.clone(),
    445                 acknowledged,
    446                 OperationId::from_bytes([1; 32]),
    447                 Some(receipt.attempt().command_digest()),
    448                 proof(e.proof())
    449             )
    450             .await,
    451         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    452     ));
    453     let captured = request(&binding, 3, 4, "New stock");
    454     let captured = InventoryRequest::new(
    455         binding,
    456         acknowledged,
    457         CapturedPoolCreation::parse(captured.command().protected_wire()).unwrap(),
    458     )
    459     .unwrap();
    460     assert!(matches!(
    461         store.execute_inventory(captured, proof(e.proof())).await,
    462         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    463     ));
    464     store.close().await.unwrap();
    465     let mut connection = database(&f).await;
    466     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_pools")
    467         .fetch_one(&mut connection)
    468         .await
    469         .unwrap();
    470     assert_eq!(count, 0);
    471     connection.close().await.unwrap();
    472 }
    473 
    474 #[tokio::test]
    475 async fn an_empty_pool_is_a_zero_genesis_without_a_fictitious_movement() {
    476     let f = Fixture::new();
    477     let (store, e, binding) = create(&f).await;
    478     let input = binding.input();
    479     let context = CommandContextData::new(
    480         OperationId::from_bytes([7; 32]),
    481         binding.actor(),
    482         input.workspace_id(),
    483         input.authority(),
    484         input.route_digest(),
    485         None,
    486         None,
    487         UnixSeconds::new(150).unwrap(),
    488         None,
    489     )
    490     .unwrap();
    491     let command = CapturedPoolCreation::new(
    492         context,
    493         CreatePoolInput::new(
    494             PoolId::from_bytes([8; 32]),
    495             "Empty",
    496             PoolUnit::new(MeasurementUnit::Each, 0).unwrap(),
    497             Quantity::new(Decimal::ZERO, MeasurementUnit::Each).unwrap(),
    498         )
    499         .unwrap(),
    500     )
    501     .unwrap();
    502     let digest = command.digest();
    503     let request = InventoryRequest::new(binding.clone(), minimum(&binding), command).unwrap();
    504     let receipt = committed(
    505         store
    506             .execute_inventory(request, proof(e.proof()))
    507             .await
    508             .unwrap(),
    509     );
    510     assert_eq!(receipt.pool().balances().introduced().get(), 0);
    511     assert_eq!(receipt.checkpoint().revision().get(), 1);
    512     assert_eq!(
    513         store
    514             .inventory_operation(
    515                 binding.clone(),
    516                 minimum(&binding),
    517                 OperationId::from_bytes([7; 32]),
    518                 Some(digest),
    519                 proof(e.proof())
    520             )
    521             .await
    522             .unwrap(),
    523         Some(receipt)
    524     );
    525     store.close().await.unwrap();
    526     let mut connection = database(&f).await;
    527     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_movements")
    528         .fetch_one(&mut connection)
    529         .await
    530         .unwrap();
    531     assert_eq!(count, 0);
    532     connection.close().await.unwrap();
    533     let store =
    534         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    535             .await
    536             .unwrap();
    537     assert_eq!(
    538         store
    539             .pool(
    540                 binding.clone(),
    541                 minimum(&binding),
    542                 PoolId::from_bytes([8; 32]),
    543                 proof(e.proof())
    544             )
    545             .await
    546             .unwrap()
    547             .unwrap()
    548             .snapshot()
    549             .balances()
    550             .introduced()
    551             .get(),
    552         0
    553     );
    554     store.close().await.unwrap();
    555 }
    556 
    557 struct AdmissionClock {
    558     armed: std::sync::atomic::AtomicBool,
    559     calls: AtomicU64,
    560     next: u64,
    561 }
    562 impl WorkspaceClock for AdmissionClock {
    563     fn now(&self) -> Result<UnixSeconds, WorkspaceError> {
    564         let next =
    565             if self.armed.load(Ordering::SeqCst) && self.calls.fetch_add(1, Ordering::SeqCst) > 0 {
    566                 self.next
    567             } else {
    568                 100
    569             };
    570         if next == 0 {
    571             Err(WorkspaceError::Unavailable)
    572         } else {
    573             Ok(UnixSeconds::new(next).unwrap())
    574         }
    575     }
    576 }
    577 #[tokio::test]
    578 async fn expiry_or_clock_failure_inside_inventory_transaction_has_no_effect() {
    579     for next in [0, 150, 200] {
    580         let f = Fixture::new();
    581         let clock = Arc::new(AdmissionClock {
    582             armed: std::sync::atomic::AtomicBool::new(false),
    583             calls: AtomicU64::new(0),
    584             next,
    585         });
    586         let e = StockEnrollment::prepare(
    587             SellerStockConfig::new(
    588                 key(),
    589                 key(),
    590                 "inventory-owner",
    591                 UnixSeconds::new(200).unwrap(),
    592             )
    593             .unwrap(),
    594             clock.as_ref(),
    595         )
    596         .unwrap();
    597         let store =
    598             NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone())
    599                 .await
    600                 .unwrap();
    601         let binding = store
    602             .authenticate(e.input().clone(), e.proof())
    603             .await
    604             .unwrap();
    605         clock.armed.store(true, Ordering::SeqCst);
    606         let result = store
    607             .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    608             .await;
    609         match next {
    610             0 => assert!(matches!(
    611                 result,
    612                 Err(OperationError::Workspace(WorkspaceError::Unavailable))
    613             )),
    614             150 => assert!(matches!(result, Err(OperationError::DeadlineExceeded))),
    615             200 => assert!(matches!(
    616                 result,
    617                 Err(OperationError::Workspace(WorkspaceError::GrantExpired))
    618             )),
    619             _ => unreachable!(),
    620         }
    621         clock.armed.store(false, Ordering::SeqCst);
    622         assert_eq!(
    623             store
    624                 .stock_authority(e.input().clone(), e.proof())
    625                 .await
    626                 .unwrap()
    627                 .inventory_checkpoint()
    628                 .unwrap()
    629                 .revision()
    630                 .get(),
    631             0
    632         );
    633         store.close().await.unwrap();
    634         let mut connection = database(&f).await;
    635         let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_pools")
    636             .fetch_one(&mut connection)
    637             .await
    638             .unwrap();
    639         assert_eq!(count, 0);
    640         connection.close().await.unwrap();
    641     }
    642 }
    643 #[tokio::test]
    644 async fn admitted_inventory_work_survives_observer_and_close_cancellation() {
    645     let f = Fixture::new();
    646     let clock = Arc::new(PausedClock {
    647         state: std::sync::Mutex::new((false, false, false)),
    648         changed: std::sync::Condvar::new(),
    649     });
    650     let e = StockEnrollment::prepare(
    651         SellerStockConfig::new(
    652             key(),
    653             key(),
    654             "inventory-owner",
    655             UnixSeconds::new(200).unwrap(),
    656         )
    657         .unwrap(),
    658         clock.as_ref(),
    659     )
    660     .unwrap();
    661     let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone())
    662         .await
    663         .unwrap();
    664     let binding = store
    665         .authenticate(e.input().clone(), e.proof())
    666         .await
    667         .unwrap();
    668     let original = request(&binding, 1, 2, "Carrots");
    669     let digest = original.command().digest();
    670     clock.arm();
    671     let mut future = store.execute_inventory(original, proof(e.proof()));
    672     assert!(futures::poll!(future.as_mut()).is_pending());
    673     clock.entered();
    674     drop(future);
    675     let mut closing = Box::pin(store.close());
    676     assert!(futures::poll!(closing.as_mut()).is_pending());
    677     drop(closing);
    678     assert!(matches!(
    679         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    680             .await,
    681         Err(WorkspaceError::WriterActive)
    682     ));
    683     clock.release();
    684     store.close().await.unwrap();
    685     let store =
    686         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    687             .await
    688             .unwrap();
    689     let receipt = store
    690         .inventory_operation(
    691             binding.clone(),
    692             minimum(&binding),
    693             OperationId::from_bytes([1; 32]),
    694             Some(digest),
    695             proof(e.proof()),
    696         )
    697         .await
    698         .unwrap()
    699         .unwrap();
    700     assert_eq!(receipt.pool().balances().physical().available.get(), 250);
    701     assert_eq!(receipt.checkpoint().revision().get(), 1);
    702     store.close().await.unwrap();
    703 }
    704 
    705 #[tokio::test]
    706 async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revocation() {
    707     let f = Fixture::new();
    708     let (store, e, binding) = create(&f).await;
    709     let receipt = committed(
    710         store
    711             .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    712             .await
    713             .unwrap(),
    714     );
    715     let wrong = || AttachmentProof::from_protected_input(&[0xB7; 32]).unwrap();
    716     assert!(matches!(
    717         store
    718             .execute_inventory(request(&binding, 1, 2, "Carrots"), wrong())
    719             .await,
    720         Err(OperationError::Workspace(WorkspaceError::Unauthorized))
    721     ));
    722     assert!(matches!(
    723         store
    724             .pool(
    725                 binding.clone(),
    726                 receipt.checkpoint(),
    727                 PoolId::from_bytes([2; 32]),
    728                 wrong()
    729             )
    730             .await,
    731         Err(OperationError::Workspace(WorkspaceError::Unauthorized))
    732     ));
    733     assert!(matches!(
    734         store
    735             .inventory_operation(
    736                 binding.clone(),
    737                 receipt.checkpoint(),
    738                 OperationId::from_bytes([1; 32]),
    739                 None,
    740                 wrong()
    741             )
    742             .await,
    743         Err(OperationError::Workspace(WorkspaceError::Unauthorized))
    744     ));
    745     let revoked = store
    746         .revoke_stock_grant(
    747             binding.clone(),
    748             receipt.checkpoint(),
    749             e.proof(),
    750             radroots_domain::TransactionId::from_bytes([0xAE; 32]),
    751             e.input().grant_id(),
    752         )
    753         .await
    754         .unwrap();
    755     assert!(matches!(
    756         revoked,
    757         radroots_storage_sqlite::workspace::StockGrantOutcome::Committed(_)
    758     ));
    759     assert!(matches!(
    760         store
    761             .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof()))
    762             .await,
    763         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    764     ));
    765     assert!(matches!(
    766         store
    767             .execute_inventory(request(&binding, 3, 4, "New"), proof(e.proof()))
    768             .await,
    769         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    770     ));
    771     assert!(matches!(
    772         store
    773             .pool(
    774                 binding.clone(),
    775                 receipt.checkpoint(),
    776                 PoolId::from_bytes([2; 32]),
    777                 proof(e.proof())
    778             )
    779             .await,
    780         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    781     ));
    782     assert!(matches!(
    783         store
    784             .inventory_operation(
    785                 binding,
    786                 receipt.checkpoint(),
    787                 OperationId::from_bytes([1; 32]),
    788                 None,
    789                 proof(e.proof())
    790             )
    791             .await,
    792         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    793     ));
    794     store.close().await.unwrap();
    795     let mut conn = database(&f).await;
    796     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations")
    797         .fetch_one(&mut conn)
    798         .await
    799         .unwrap();
    800     assert_eq!(count, 1);
    801     conn.close().await.unwrap();
    802 }
    803 
    804 #[tokio::test]
    805 async fn simultaneous_inventory_operations_serialize_identity_and_preserve_earlier_checkpoint_ancestry()
    806  {
    807     let f = Fixture::new();
    808     let (store, e, binding) = create(&f).await;
    809     let (left, right) = tokio::join!(
    810         store.execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())),
    811         store.execute_inventory(request(&binding, 3, 2, "Competing"), proof(e.proof()))
    812     );
    813     let first = match (left, right) {
    814         (Ok(value), Err(OperationError::StaleState))
    815         | (Err(OperationError::StaleState), Ok(value)) => committed(value),
    816         other => panic!("one serialized creation must win: {other:?}"),
    817     };
    818     let next = request(&binding, 5, 6, "Parsnips");
    819     let next = InventoryRequest::new(
    820         binding.clone(),
    821         first.checkpoint(),
    822         CapturedPoolCreation::parse(next.command().protected_wire()).unwrap(),
    823     )
    824     .unwrap();
    825     let second = committed(
    826         store
    827             .execute_inventory(next, proof(e.proof()))
    828             .await
    829             .unwrap(),
    830     );
    831     assert_eq!(first.checkpoint().revision().get(), 1);
    832     assert_eq!(second.checkpoint().revision().get(), 2);
    833     assert_ne!(first.checkpoint().head(), second.checkpoint().head());
    834     assert_eq!(
    835         store
    836             .inventory_operation(
    837                 binding.clone(),
    838                 second.checkpoint(),
    839                 first.attempt().operation_id(),
    840                 Some(first.attempt().command_digest()),
    841                 proof(e.proof())
    842             )
    843             .await
    844             .unwrap(),
    845         Some(first.clone())
    846     );
    847     store.close().await.unwrap();
    848     let store =
    849         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    850             .await
    851             .unwrap();
    852     assert_eq!(
    853         store
    854             .pool(
    855                 binding.clone(),
    856                 first.checkpoint(),
    857                 PoolId::from_bytes([6; 32]),
    858                 proof(e.proof())
    859             )
    860             .await
    861             .unwrap()
    862             .unwrap()
    863             .label(),
    864         "Parsnips"
    865     );
    866     let conflicting = InventoryCheckpointRef::from_host_metadata(
    867         binding.input().authority(),
    868         radroots_domain::Sequence::new(1).unwrap(),
    869         second.checkpoint().head(),
    870     )
    871     .unwrap();
    872     assert!(matches!(
    873         store
    874             .pool(
    875                 binding,
    876                 conflicting,
    877                 PoolId::from_bytes([2; 32]),
    878                 proof(e.proof())
    879             )
    880             .await,
    881         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    882     ));
    883     store.close().await.unwrap();
    884     let mut conn = database(&f).await;
    885     assert_eq!(
    886         sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations")
    887             .fetch_one(&mut conn)
    888             .await
    889             .unwrap(),
    890         2
    891     );
    892     assert_eq!(
    893         sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_pools")
    894             .fetch_one(&mut conn)
    895             .await
    896             .unwrap(),
    897         2
    898     );
    899     assert_eq!(
    900         sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_movements")
    901             .fetch_one(&mut conn)
    902             .await
    903             .unwrap(),
    904         2
    905     );
    906     conn.close().await.unwrap();
    907 }
    908 
    909 #[tokio::test]
    910 async fn acknowledged_branch_cannot_be_satisfied_by_unprotected_history_index_fields() {
    911     let f = Fixture::new();
    912     let (store, e, binding) = create(&f).await;
    913     store.close().await.unwrap();
    914     let path = f.path.join("stock_execution_v1.sqlite");
    915     let genesis = std::fs::read(&path).unwrap();
    916     let store =
    917         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    918             .await
    919             .unwrap();
    920     let acknowledged = committed(
    921         store
    922             .execute_inventory(request(&binding, 1, 2, "First branch"), proof(e.proof()))
    923             .await
    924             .unwrap(),
    925     )
    926     .checkpoint();
    927     store.close().await.unwrap();
    928     // Simulate an older complete local backup and its divergent continuation.
    929     std::fs::write(&path, genesis).unwrap();
    930     let store =
    931         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    932             .await
    933             .unwrap();
    934     store
    935         .execute_inventory(request(&binding, 3, 4, "Other branch"), proof(e.proof()))
    936         .await
    937         .unwrap();
    938     store
    939         .execute_inventory(
    940             request(&binding, 5, 6, "Later other branch"),
    941             proof(e.proof()),
    942         )
    943         .await
    944         .unwrap();
    945     store.close().await.unwrap();
    946     let mut conn = database(&f).await;
    947     sqlx::query("UPDATE stock_operations SET chain_head=? WHERE revision=1")
    948         .bind(acknowledged.head().unwrap().as_bytes().as_slice())
    949         .execute(&mut conn)
    950         .await
    951         .unwrap();
    952     conn.close().await.unwrap();
    953     let store =
    954         NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone())
    955             .await
    956             .unwrap();
    957     assert!(matches!(
    958         store
    959             .pool(
    960                 binding,
    961                 acknowledged,
    962                 PoolId::from_bytes([4; 32]),
    963                 proof(e.proof())
    964             )
    965             .await,
    966         Err(OperationError::RecoveryRequired)
    967             | Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    968     ));
    969     store.close().await.unwrap();
    970 }
    971 
    972 #[path = "pool_correction.rs"]
    973 mod correction;
    974 
    975 #[tokio::test]
    976 async fn acknowledged_history_refuses_an_older_individual_pool_projection() {
    977     let f = Fixture::new();
    978     let (store, e, binding) = create(&f).await;
    979     let initial = committed(
    980         store
    981             .execute_inventory(request(&binding, 1, 2, "projection"), proof(e.proof()))
    982             .await
    983             .unwrap(),
    984     );
    985     let mut connection = database(&f).await;
    986     let original: (i64, Vec<u8>) =
    987         sqlx::query_as("SELECT revision,protected FROM stock_pools WHERE pool_id=?")
    988             .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice())
    989             .fetch_one(&mut connection)
    990             .await
    991             .unwrap();
    992     let capture = request(&binding, 3, 2, "projection");
    993     let wire = serde_json::json!({"type":"stock.adjust","context":capture.command().context(),"input":{"pool_id":PoolId::from_bytes([2;32]),"expected_version":"1","direction":"add","amount":"0.125","reason":"projection continuity"}});
    994     let changed = committed(
    995         store
    996             .execute_inventory(
    997                 InventoryRequest::from_protected_wire(
    998                     binding.clone(),
    999                     initial.checkpoint(),
   1000                     &serde_json::to_vec(&wire).unwrap(),
   1001                 )
   1002                 .unwrap(),
   1003                 proof(e.proof()),
   1004             )
   1005             .await
   1006             .unwrap(),
   1007     );
   1008     assert_eq!(changed.pool().balances().physical().available.get(), 375);
   1009     sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=?")
   1010         .bind(original.0)
   1011         .bind(original.1)
   1012         .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice())
   1013         .execute(&mut connection)
   1014         .await
   1015         .unwrap();
   1016     assert_eq!(
   1017         store
   1018             .pool(
   1019                 binding.clone(),
   1020                 changed.checkpoint(),
   1021                 PoolId::from_bytes([2; 32]),
   1022                 proof(e.proof())
   1023             )
   1024             .await,
   1025         Err(OperationError::RecoveryRequired)
   1026     );
   1027     let mut retry = wire;
   1028     retry["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([4; 32]));
   1029     let retry = InventoryRequest::from_protected_wire(
   1030         binding,
   1031         changed.checkpoint(),
   1032         &serde_json::to_vec(&retry).unwrap(),
   1033     )
   1034     .unwrap();
   1035     assert_eq!(
   1036         store.execute_inventory(retry, proof(e.proof())).await,
   1037         Err(OperationError::RecoveryRequired)
   1038     );
   1039     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations")
   1040         .fetch_one(&mut connection)
   1041         .await
   1042         .unwrap();
   1043     assert_eq!(count, 2);
   1044     connection.close().await.unwrap();
   1045     store.close().await.unwrap();
   1046 }
   1047 
   1048 #[tokio::test]
   1049 async fn a_mutable_pool_index_cannot_hide_a_more_recent_protected_pool_effect() {
   1050     let f = Fixture::new();
   1051     let (store, e, binding) = create(&f).await;
   1052     let initial = committed(
   1053         store
   1054             .execute_inventory(request(&binding, 1, 2, "projection"), proof(e.proof()))
   1055             .await
   1056             .unwrap(),
   1057     );
   1058     let mut connection = database(&f).await;
   1059     let original: (i64, Vec<u8>) =
   1060         sqlx::query_as("SELECT revision,protected FROM stock_pools WHERE pool_id=?")
   1061             .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice())
   1062             .fetch_one(&mut connection)
   1063             .await
   1064             .unwrap();
   1065     let capture = request(&binding, 3, 2, "projection");
   1066     let wire = serde_json::json!({"type":"stock.adjust","context":capture.command().context(),"input":{"pool_id":PoolId::from_bytes([2;32]),"expected_version":"1","direction":"add","amount":"0.125","reason":"projection continuity"}});
   1067     committed(
   1068         store
   1069             .execute_inventory(
   1070                 InventoryRequest::from_protected_wire(
   1071                     binding.clone(),
   1072                     initial.checkpoint(),
   1073                     &serde_json::to_vec(&wire).unwrap(),
   1074                 )
   1075                 .unwrap(),
   1076                 proof(e.proof()),
   1077             )
   1078             .await
   1079             .unwrap(),
   1080     );
   1081     let newest = committed(
   1082         store
   1083             .execute_inventory(request(&binding, 4, 5, "other pool"), proof(e.proof()))
   1084             .await
   1085             .unwrap(),
   1086     );
   1087     sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=?")
   1088         .bind(original.0)
   1089         .bind(original.1)
   1090         .bind(PoolId::from_bytes([2; 32]).as_bytes().as_slice())
   1091         .execute(&mut connection)
   1092         .await
   1093         .unwrap();
   1094     sqlx::query("UPDATE stock_operations SET pool_id=? WHERE operation_id=?")
   1095         .bind(PoolId::from_bytes([5; 32]).as_bytes().as_slice())
   1096         .bind(OperationId::from_bytes([3; 32]).as_bytes().as_slice())
   1097         .execute(&mut connection)
   1098         .await
   1099         .unwrap();
   1100     assert_eq!(
   1101         store
   1102             .pool(
   1103                 binding,
   1104                 newest.checkpoint(),
   1105                 PoolId::from_bytes([2; 32]),
   1106                 proof(e.proof())
   1107             )
   1108             .await,
   1109         Err(OperationError::RecoveryRequired)
   1110     );
   1111     connection.close().await.unwrap();
   1112     store.close().await.unwrap();
   1113 }
   1114 
   1115 #[path = "stock_grants.rs"]
   1116 mod grants;
   1117 
   1118 #[path = "option_mapping.rs"]
   1119 mod mapping;
   1120 
   1121 #[path = "stock_source.rs"]
   1122 mod source;