lib

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

workspace_inventory.rs (15831B)


      1 //! Mechanical task ownership with a controlled port, not SQL qualification.
      2 use super::*;
      3 use radroots_execution::{Code, RetryClass, session::tasks::TaskHost};
      4 use radroots_storage::{command::OperationError, inventory::*};
      5 #[path = "workspace_acceptance.rs"]
      6 mod acceptance;
      7 #[path = "workspace_evidence.rs"]
      8 mod evidence;
      9 
     10 #[derive(Default)]
     11 struct Tasks {
     12     queued: Mutex<Vec<HostFuture<'static, ()>>>,
     13     refuse: AtomicBool,
     14 }
     15 impl TaskHost for Tasks {
     16     fn submit(&self, task: HostFuture<'static, ()>) -> radroots_execution::Result<()> {
     17         if self.refuse.load(Ordering::SeqCst) {
     18             return Err(radroots_execution::Error::operation(
     19                 OperationError::UnsupportedOperation,
     20                 radroots_execution::OperationContext::proposed(None),
     21             ));
     22         }
     23         let mut queued = self.queued.lock().unwrap();
     24         assert!(
     25             queued.len() < 2,
     26             "the owner's byte budget must bound admission first"
     27         );
     28         queued.push(task);
     29         Ok(())
     30     }
     31 }
     32 struct Store {
     33     capture: evidence::Control,
     34     model: Shared<Model>,
     35     calls: Mutex<Vec<(OperationId, CommandDigest)>>,
     36     waiting: AtomicBool,
     37     waker: AtomicWaker,
     38 }
     39 impl WorkspaceStore for Store {
     40     fn authenticate(
     41         &self,
     42         input: AttachmentInput,
     43         proof: AttachmentProof,
     44     ) -> radroots_storage::event::BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> {
     45         self.model.authenticate(input, proof)
     46     }
     47     fn close_workspace(
     48         &self,
     49     ) -> radroots_storage::event::BoxFuture<'_, Result<(), WorkspaceError>> {
     50         Box::pin(async { Ok(()) })
     51     }
     52 }
     53 impl InventoryStore for Store {
     54     fn reconcile_stock_evidence<'a>(
     55         &'a self,
     56         request: &'a StockEvidenceRequest,
     57         proof: &'a AttachmentProof,
     58     ) -> radroots_storage::event::BoxFuture<'a, Result<StockEvidenceOutcome, OperationError>> {
     59         self.capture.reconciliations.fetch_add(1, Ordering::SeqCst);
     60         evidence::capture(self, request, proof)
     61     }
     62     fn capture_stock_evidence<'a>(
     63         &'a self,
     64         request: &'a StockEvidenceRequest,
     65         proof: &'a AttachmentProof,
     66     ) -> radroots_storage::event::BoxFuture<'a, Result<StockEvidenceOutcome, OperationError>> {
     67         evidence::capture(self, request, proof)
     68     }
     69     fn prepare_stock_acceptance(
     70         &self,
     71         request: StockAcceptanceRequest,
     72         proof: AttachmentProof,
     73     ) -> radroots_storage::event::BoxFuture<'_, Result<StockAcceptanceOutcome, OperationError>>
     74     {
     75         Box::pin(async move {
     76             assert_eq!(proof.with_secret(|bytes| *bytes), [7; 32]);
     77             assert_eq!(request.binding().input(), &input(5));
     78             assert_eq!(request.minimum_checkpoint().revision().get(), 0);
     79             assert_eq!(request.source_checkpoint().revision().get(), 2);
     80             assert_eq!(request.listing_checkpoint().revision().get(), 3);
     81             self.calls
     82                 .lock()
     83                 .unwrap()
     84                 .push((request.attempt().operation_id(), request.command().digest()));
     85             poll_fn(|cx| {
     86                 self.waker.register(cx.waker());
     87                 if self.waiting.load(Ordering::SeqCst) {
     88                     Poll::Pending
     89                 } else {
     90                     Poll::Ready(())
     91                 }
     92             })
     93             .await;
     94             // Port mechanics only; this reports no actual T0 or SQL effect.
     95             Ok(StockAcceptanceOutcome::Unknown(request.attempt()))
     96         })
     97     }
     98     fn abort_proven_unissued(
     99         &self,
    100         request: StockAbortRequest,
    101         proof: AttachmentProof,
    102     ) -> radroots_storage::event::BoxFuture<'_, Result<StockAbortOutcome, OperationError>> {
    103         Box::pin(async move {
    104             assert_eq!(proof.with_secret(|bytes| *bytes), [7; 32]);
    105             assert_eq!(request.binding().input(), &input(5));
    106             self.calls
    107                 .lock()
    108                 .unwrap()
    109                 .push((request.operation_id(), request.command_digest()));
    110             poll_fn(|cx| {
    111                 self.waker.register(cx.waker());
    112                 if self.waiting.load(Ordering::SeqCst) {
    113                     Poll::Pending
    114                 } else {
    115                     Poll::Ready(())
    116                 }
    117             })
    118             .await;
    119             // A mechanical report only. No absence, release or SQL proof.
    120             Ok(StockAbortOutcome::Unknown(request.attempt()))
    121         })
    122     }
    123     fn stock_preparation_abort(
    124         &self,
    125         _request: StockAbortRequest,
    126         _proof: AttachmentProof,
    127     ) -> radroots_storage::event::BoxFuture<'_, Result<Option<StockAbortReceipt>, OperationError>>
    128     {
    129         Box::pin(async { Err(OperationError::MissingHistory) })
    130     }
    131     fn option_mapping(
    132         &self,
    133         _binding: WorkspaceBinding,
    134         _minimum: InventoryCheckpointRef,
    135         _key: radroots_domain::stock::OptionMappingKey,
    136         _proof: AttachmentProof,
    137     ) -> radroots_storage::event::BoxFuture<
    138         '_,
    139         Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError>,
    140     > {
    141         panic!("unexpected port call")
    142     }
    143     fn execute_inventory(
    144         &self,
    145         _request: InventoryRequest,
    146         _proof: AttachmentProof,
    147     ) -> radroots_storage::event::BoxFuture<'_, Result<InventoryOutcome, OperationError>> {
    148         panic!("unexpected port call")
    149     }
    150     fn inventory_operation(
    151         &self,
    152         _binding: WorkspaceBinding,
    153         _minimum: InventoryCheckpointRef,
    154         _operation: OperationId,
    155         _digest: Option<CommandDigest>,
    156         _proof: AttachmentProof,
    157     ) -> radroots_storage::event::BoxFuture<'_, Result<Option<InventoryReceipt>, OperationError>>
    158     {
    159         panic!("unexpected port call")
    160     }
    161     fn pool(
    162         &self,
    163         _binding: WorkspaceBinding,
    164         _minimum: InventoryCheckpointRef,
    165         _pool: PoolId,
    166         _proof: AttachmentProof,
    167     ) -> radroots_storage::event::BoxFuture<
    168         '_,
    169         Result<Option<radroots_domain::stock::PoolView>, OperationError>,
    170     > {
    171         Box::pin(async move {
    172             self.capture.queries.fetch_add(1, Ordering::SeqCst);
    173             Ok(None)
    174         })
    175     }
    176 }
    177 fn store() -> Shared<Store> {
    178     Shared::new(Store {
    179         capture: evidence::Control::default(),
    180         model: new_model(),
    181         calls: Mutex::new(vec![]),
    182         waiting: AtomicBool::new(false),
    183         waker: AtomicWaker::new(),
    184     })
    185 }
    186 fn minimum(scope: &WorkspaceSession) -> InventoryCheckpointRef {
    187     InventoryCheckpointRef::from_host_metadata(
    188         scope.binding().input().authority(),
    189         Sequence::new(0).unwrap(),
    190         None,
    191     )
    192     .unwrap()
    193 }
    194 fn operation() -> OperationId {
    195     OperationId::from_bytes([80; 32])
    196 }
    197 fn digest() -> CommandDigest {
    198     CommandDigest::from_bytes([81; 32])
    199 }
    200 
    201 #[test]
    202 fn admitted_inventory_work_survives_observer_loss_bounds_bytes_and_blocks_close_until_settled() {
    203     block_on(async {
    204         let store = store();
    205         let tasks = Shared::new(Tasks::default());
    206         let client = ClientSession::new_with_task_host(
    207             Host,
    208             core::num::NonZeroU16::new(8).unwrap(),
    209             tasks.clone(),
    210         );
    211         let scope = client
    212             .attach_workspace(store.clone(), input(5), proof())
    213             .await
    214             .unwrap();
    215         client.start().await.unwrap();
    216         let minimum = minimum(&scope);
    217         drop(client.abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest()));
    218         assert!(tasks.queued.lock().unwrap().is_empty());
    219         let mut first = Box::pin(client.abort_proven_unissued(
    220             store.clone(),
    221             &scope,
    222             minimum,
    223             operation(),
    224             digest(),
    225         ));
    226         let mut second = Box::pin(client.abort_proven_unissued(
    227             store.clone(),
    228             &scope,
    229             minimum,
    230             operation(),
    231             digest(),
    232         ));
    233         assert!(futures::poll!(first.as_mut()).is_pending());
    234         assert!(futures::poll!(second.as_mut()).is_pending());
    235         assert_eq!(tasks.queued.lock().unwrap().len(), 2);
    236         assert!(store.calls.lock().unwrap().is_empty());
    237         assert_eq!(
    238             client
    239                 .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest())
    240                 .await
    241                 .unwrap_err()
    242                 .code(),
    243             Code::CapabilityUnavailable
    244         );
    245         drop(first);
    246         drop(second);
    247         let mut closing = Box::pin(client.close());
    248         assert!(futures::poll!(closing.as_mut()).is_pending());
    249         assert!(
    250             scope
    251                 .command_context(operation(), None, None, UnixSeconds::new(150).unwrap())
    252                 .is_err()
    253         );
    254         let mut jobs = core::mem::take(&mut *tasks.queued.lock().unwrap());
    255         store.waiting.store(true, Ordering::SeqCst);
    256         assert!(futures::poll!(jobs[0].as_mut()).is_pending());
    257         assert!(futures::poll!(closing.as_mut()).is_pending());
    258         store.waiting.store(false, Ordering::SeqCst);
    259         store.waker.wake();
    260         for task in jobs {
    261             task.await;
    262         }
    263         assert_eq!(
    264             *store.calls.lock().unwrap(),
    265             vec![(operation(), digest()); 2]
    266         );
    267         closing.await.unwrap();
    268         assert_eq!(
    269             client
    270                 .abort_proven_unissued(store, &scope, minimum, operation(), digest())
    271                 .await
    272                 .unwrap_err()
    273                 .code(),
    274             Code::CapabilityUnavailable
    275         );
    276     });
    277 }
    278 
    279 #[test]
    280 fn task_refusal_foreign_scope_closed_scope_and_missing_host_dispatch_nothing() {
    281     block_on(async {
    282         let store = store();
    283         let tasks = Shared::new(Tasks::default());
    284         let client = ClientSession::new_with_task_host(
    285             Host,
    286             core::num::NonZeroU16::new(8).unwrap(),
    287             tasks.clone(),
    288         );
    289         let scope = client
    290             .attach_workspace(store.clone(), input(5), proof())
    291             .await
    292             .unwrap();
    293         let foreign = WorkspaceSession::attach(store.clone(), input(5), proof())
    294             .await
    295             .unwrap();
    296         client.start().await.unwrap();
    297         let minimum = minimum(&scope);
    298         assert_eq!(
    299             client
    300                 .abort_proven_unissued(store.clone(), &foreign, minimum, operation(), digest())
    301                 .await
    302                 .unwrap_err()
    303                 .code(),
    304             Code::Unauthorized
    305         );
    306         tasks.refuse.store(true, Ordering::SeqCst);
    307         assert_eq!(
    308             client
    309                 .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest())
    310                 .await
    311                 .unwrap_err()
    312                 .code(),
    313             Code::CapabilityUnavailable
    314         );
    315         tasks.refuse.store(false, Ordering::SeqCst);
    316         let mut observed = Box::pin(client.abort_proven_unissued(
    317             store.clone(),
    318             &scope,
    319             minimum,
    320             operation(),
    321             digest(),
    322         ));
    323         assert!(futures::poll!(observed.as_mut()).is_pending());
    324         let task = tasks.queued.lock().unwrap().pop().unwrap();
    325         task.await;
    326         let StockAbortOutcome::Unknown(anchor) = observed.await.unwrap() else {
    327             panic!("must preserve uncertainty")
    328         };
    329         assert_eq!(anchor.operation_id(), operation());
    330         assert_eq!(anchor.command_digest(), digest());
    331         assert!(anchor.transaction_id().is_none());
    332         let mut query = Box::pin(client.stock_preparation_abort(
    333             store.clone(),
    334             &scope,
    335             minimum,
    336             operation(),
    337             digest(),
    338         ));
    339         assert!(futures::poll!(query.as_mut()).is_pending());
    340         let task = tasks.queued.lock().unwrap().pop().unwrap();
    341         task.await;
    342         let error = query.await.unwrap_err();
    343         assert_eq!(error.code(), Code::MissingHistory);
    344         assert_eq!(error.context().operation_id(), Some(operation()));
    345         assert_eq!(error.retry(), RetryClass::AfterStateRefresh);
    346         scope.close();
    347         assert_eq!(
    348             client
    349                 .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest())
    350                 .await
    351                 .unwrap_err()
    352                 .code(),
    353             Code::CapabilityUnavailable
    354         );
    355         client.close().await.unwrap();
    356         let without_host = ClientSession::new(Host, core::num::NonZeroU16::MIN);
    357         let scope = without_host
    358             .attach_workspace(store.clone(), input(5), proof())
    359             .await
    360             .unwrap();
    361         without_host.start().await.unwrap();
    362         assert_eq!(
    363             without_host
    364                 .abort_proven_unissued(store.clone(), &scope, minimum, operation(), digest())
    365                 .await
    366                 .unwrap_err()
    367                 .code(),
    368             Code::CapabilityUnavailable
    369         );
    370         without_host.close().await.unwrap();
    371         assert_eq!(store.calls.lock().unwrap().len(), 1);
    372         assert!(tasks.queued.lock().unwrap().is_empty());
    373     });
    374 }
    375 
    376 #[test]
    377 fn loss_of_an_accepted_admission_task_never_reports_known_nonadmission() {
    378     block_on(async {
    379         let store = store();
    380         // Port metadata only. This test deliberately drops an accepted host
    381         // task; it does not qualify that host or any native transaction.
    382         *store.model.binding.lock().unwrap() = WorkspaceBinding::from_authenticated_host(
    383             input(5),
    384             radroots_storage::workspace::WorkspaceScope::SellerStockOwner,
    385             ActorRef::new(key(), ActorRole::Seller, None, Some(input(5).grant_id())),
    386             "device",
    387             Sequence::new(1).unwrap(),
    388             UnixSeconds::new(200).unwrap(),
    389             UnixSeconds::new(100).unwrap(),
    390         )
    391         .unwrap();
    392         let tasks = Shared::new(Tasks::default());
    393         let client =
    394             ClientSession::new_with_task_host(Host, core::num::NonZeroU16::MIN, tasks.clone());
    395         let scope = client
    396             .attach_workspace(store.clone(), input(5), proof())
    397             .await
    398             .unwrap();
    399         client.start().await.unwrap();
    400         let input = radroots_protocol::command::CreatePoolInput::new(
    401             PoolId::from_bytes([82; 32]),
    402             "private model stock",
    403             radroots_domain::stock::PoolUnit::new(
    404                 radroots_domain::listing::MeasurementUnit::Each,
    405                 0,
    406             )
    407             .unwrap(),
    408             Quantity::new(
    409                 "1".parse().unwrap(),
    410                 radroots_domain::listing::MeasurementUnit::Each,
    411             )
    412             .unwrap(),
    413         )
    414         .unwrap();
    415         let context = scope
    416             .command_context(operation(), None, None, UnixSeconds::new(150).unwrap())
    417             .unwrap();
    418         let mut observed = Box::pin(client.create_stock_pool(
    419             store.clone(),
    420             &scope,
    421             context,
    422             minimum(&scope),
    423             input,
    424         ));
    425         assert!(futures::poll!(observed.as_mut()).is_pending());
    426         // Simulate a nonconforming host losing its accepted task. Silence
    427         // cannot prove the store never committed, and must not authorize retry.
    428         drop(tasks.queued.lock().unwrap().pop().unwrap());
    429         let error = observed.await.unwrap_err();
    430         assert_eq!(error.code(), Code::CommitUnknown);
    431         assert_eq!(
    432             error.context().admission(),
    433             radroots_execution::Admission::Unknown
    434         );
    435         assert_eq!(error.context().operation_id(), Some(operation()));
    436         assert_eq!(error.retry(), RetryClass::ManualReconciliation);
    437         assert!(store.calls.lock().unwrap().is_empty());
    438         client.close().await.unwrap();
    439     });
    440 }