Skip to main content

riffdb_client_rust/generated/
client.rs

1// @generated by scripts/generate-operation-adapters; DO NOT EDIT.
2
3use std::error::Error;
4use std::fmt;
5use std::time::Duration;
6
7use riffdb_proto::generated::{
8    admin_service_client::AdminServiceClient,
9    application_session_service_client::ApplicationSessionServiceClient,
10    command_service_client::CommandServiceClient, commit_service_client::CommitServiceClient,
11    contract_service_client::ContractServiceClient, event_service_client::EventServiceClient,
12    query_service_client::QueryServiceClient,
13};
14use riffdb_proto::generated_app::application_query_service_client::ApplicationQueryServiceClient;
15use riffdb_proto::{
16    MAX_EXECUTE_REQUEST_BYTES, MAX_EXECUTE_RESPONSE_BYTES, PublicMessage,
17    validate_apply_application_reimport_page_exchange, validate_apply_contract_migration_exchange,
18    validate_cancel_application_export_exchange, validate_cancel_application_reimport_exchange,
19    validate_check_contract_migration_exchange, validate_contract_validation_exchange,
20    validate_create_capability_exchange, validate_create_offline_backup_exchange,
21    validate_discover_command_tools_exchange, validate_discover_resources_exchange,
22    validate_explain_command_exchange, validate_get_application_export_exchange,
23    validate_get_application_export_page_exchange, validate_get_application_installation_exchange,
24    validate_get_application_reimport_exchange, validate_get_contract_migration_operation_exchange,
25    validate_get_contract_version_exchange, validate_get_offline_maintenance_operation_exchange,
26    validate_get_outcome_exchange, validate_get_projection_status_exchange,
27    validate_list_pending_outbox_deliveries_exchange, validate_public_message,
28    validate_query_projection_exchange, validate_restore_archived_backup_exchange, validate_restore_offline_backup_exchange,
29    validate_retire_offline_backup_exchange, validate_scan_commits_exchange,
30    validate_scan_index_exchange, validate_start_application_export_exchange,
31    validate_start_application_installation_exchange, validate_start_application_reimport_exchange,
32    validate_start_offline_storage_scrub_exchange, validate_trace_provenance_exchange,
33};
34use riffdb_proto::{app::v1 as app_v1, v1};
35use riffdb_types::{
36    ApplicationExportOperationId, ApplicationInstallationCampaignId, CommitSequence, RequestId,
37};
38use tonic::transport::{Channel, Endpoint};
39use tonic::{Request, Response, Streaming};
40
41use crate::application::contextualize_command_client_error;
42use crate::command::{RetryDecision, RetryState, apply_overloaded_backoff};
43use crate::generated::{GeneratedCommand, GeneratedCommandError};
44use crate::status::{
45    ClientError, ProtocolFailure, ProtocolFailureKind, checked_application_status, checked_status,
46};
47use crate::{
48    ApplyContractMigration, AttemptBudget, BootstrapCallMetadata,
49    BootstrapCapabilityCreateTemplate, CallMetadata, CheckContractMigration, CreateOfflineBackup,
50    IdempotentCommand, NormalCapabilityCreateTemplate, RestoreArchivedBackup, RestoreOfflineBackup, RetireOfflineBackup,
51    StartApplicationExport, StartApplicationInstallation, StartApplicationReimport,
52    StartOfflineStorageScrub, SystemIdSource,
53};
54
55pub(crate) trait RetryRequestIdSource {
56    fn next_request_id(&mut self) -> Result<RequestId, crate::IdentifierGenerationError>;
57}
58
59impl RetryRequestIdSource for SystemIdSource {
60    fn next_request_id(&mut self) -> Result<RequestId, crate::IdentifierGenerationError> {
61        (*self).request_id()
62    }
63}
64
65pub(crate) trait ExecuteRetryAttempt {
66    async fn submit_execute_attempt(
67        &mut self,
68        request: v1::ExecuteCommandRequest,
69        metadata: &CallMetadata,
70    ) -> Result<v1::ExecuteCommandResponse, ClientError>;
71}
72
73trait NormalCapabilityRetryAttempt {
74    async fn submit_normal_capability_attempt(
75        &mut self,
76        request: v1::CreateCapabilityRequest,
77        metadata: &CallMetadata,
78    ) -> Result<v1::CreateCapabilityResponse, ClientError>;
79}
80
81trait BootstrapCapabilityRetryAttempt {
82    async fn submit_bootstrap_capability_attempt(
83        &mut self,
84        request: v1::CreateCapabilityRequest,
85        metadata: &BootstrapCallMetadata,
86    ) -> Result<v1::CreateCapabilityResponse, ClientError>;
87}
88
89macro_rules! unary {
90    ($name:ident, $client:ident, $rpc:ident, $request:ty, $response:ty) => {
91        #[doc = concat!("Performs the checked `", stringify!($rpc), "` unary RPC.")]
92        pub async fn $name(
93            &mut self,
94            message: $request,
95            metadata: &CallMetadata,
96        ) -> Result<$response, ClientError> {
97            // Walk inventory (five structural validations per unary round-trip):
98            // (1) client validate_outbound — certain local fail-fast classification
99            // (2) client StrictProstEncoder — wire-bound encode
100            // (3) server StrictProstDecoder — wire contract on requests
101            // (4) server StrictProstEncoder — server fail-closed outbound
102            // (5) client StrictProstDecoder — canonical wire on responses
103            // Inbound re-walk after decode is intentionally absent (codec owns it).
104            validate_outbound(&message)?;
105            let mut request = Request::new(message);
106            metadata.apply(&mut request);
107            let response = self
108                .$client
109                .$rpc(request)
110                .await
111                .map_err(checked_status)?
112                .into_inner();
113            Ok(response)
114        }
115    };
116}
117
118macro_rules! unary_exchange {
119    ($name:ident, $client:ident, $rpc:ident, $request:ty, $response:ty, $exchange:path) => {
120        #[doc = concat!("Performs the checked `", stringify!($rpc), "` unary RPC.")]
121        pub async fn $name(
122            &mut self,
123            message: $request,
124            metadata: &CallMetadata,
125        ) -> Result<$response, ClientError> {
126            validate_outbound(&message)?;
127            let exchange_request = message.clone();
128            let mut request = Request::new(message);
129            metadata.apply(&mut request);
130            let response = self
131                .$client
132                .$rpc(request)
133                .await
134                .map_err(checked_status)?
135                .into_inner();
136            // Structural re-walk of the response is omitted: the decoder already
137            // ran decode_public_message. Exchange checks assert request↔response
138            // relations only (they may re-validate structure internally — that
139            // is riffdb-proto ownership, not this client layer).
140            $exchange(&exchange_request, &response).map_err(|_| invalid_inbound())?;
141            Ok(response)
142        }
143    };
144}
145
146macro_rules! unary_application {
147    ($name:ident, $rpc:ident, $request:ty, $response:ty) => {
148        #[doc = concat!(
149                                                            "Performs the checked application `",
150                                                            stringify!($rpc),
151                                                            "` unary RPC."
152                                                        )]
153        pub async fn $name(
154            &mut self,
155            message: $request,
156            metadata: &CallMetadata,
157        ) -> Result<$response, ClientError> {
158            validate_outbound(&message)?;
159            let mut request = Request::new(message);
160            metadata.apply(&mut request);
161            let response = self
162                .application_query
163                .$rpc(request)
164                .await
165                .map_err(checked_application_status)?
166                .into_inner();
167            Ok(response)
168        }
169    };
170}
171
172/// Explicit per-request observed incarnation wins; otherwise use remembered.
173#[must_use]
174pub(crate) const fn merge_observed_history_incarnation(
175    explicit: Option<u64>,
176    remembered: Option<u64>,
177) -> Option<u64> {
178    if explicit.is_some() {
179        explicit
180    } else {
181        remembered
182    }
183}
184
185/// Typed clients for every service in the public `riffdb.v1` API.
186///
187/// Clones share one Tonic channel while retaining independent generated client
188/// readiness state.
189#[derive(Clone)]
190pub struct RiffDbClient {
191    contract: ContractServiceClient<Channel>,
192    command: CommandServiceClient<Channel>,
193    query: QueryServiceClient<Channel>,
194    commit: CommitServiceClient<Channel>,
195    event: EventServiceClient<Channel>,
196    admin: AdminServiceClient<Channel>,
197    application_query: ApplicationQueryServiceClient<Channel>,
198    application_session: ApplicationSessionServiceClient<Channel>,
199    bounded_application_session: Option<crate::session::BoundedApplicationSession>,
200    /// Optional client-remembered history incarnation for commit read surfaces.
201    ///
202    /// When set, [`Self::apply_observed_history_incarnation`] fills request
203    /// fields that are still unset so callers can fence stale history after
204    /// a destructive restore (ADR-0072).
205    observed_history_incarnation: Option<u64>,
206}
207
208impl RiffDbClient {
209    /// Connects all typed service clients over one lazily cloned channel.
210    pub async fn connect(endpoint: Endpoint) -> Result<Self, ClientError> {
211        let channel = endpoint
212            .connect()
213            .await
214            .map_err(|_| ClientError::ConnectionFailure)?;
215        Ok(Self::from_channel(channel))
216    }
217
218    /// Constructs all typed service clients over an existing channel.
219    #[must_use]
220    pub fn from_channel(channel: Channel) -> Self {
221        Self {
222            contract: ContractServiceClient::new(channel.clone()),
223            command: CommandServiceClient::new(channel.clone())
224                .max_encoding_message_size(MAX_EXECUTE_REQUEST_BYTES)
225                .max_decoding_message_size(MAX_EXECUTE_RESPONSE_BYTES),
226            query: QueryServiceClient::new(channel.clone()),
227            commit: CommitServiceClient::new(channel.clone()),
228            event: EventServiceClient::new(channel.clone())
229                .max_encoding_message_size(MAX_EXECUTE_REQUEST_BYTES)
230                .max_decoding_message_size(MAX_EXECUTE_RESPONSE_BYTES),
231            admin: AdminServiceClient::new(channel.clone()),
232            application_query: ApplicationQueryServiceClient::new(channel.clone()),
233            application_session: ApplicationSessionServiceClient::new(channel)
234                .max_encoding_message_size(MAX_EXECUTE_REQUEST_BYTES)
235                .max_decoding_message_size(MAX_EXECUTE_RESPONSE_BYTES),
236            bounded_application_session: None,
237            observed_history_incarnation: None,
238        }
239    }
240
241    pub(crate) async fn enable_bounded_application_session(
242        &mut self,
243        identity: crate::ApplicationSessionIdentity,
244        metadata: CallMetadata,
245    ) -> Result<(), ClientError> {
246        let session =
247            crate::session::BoundedApplicationSession::open(self, identity, metadata).await?;
248        self.bounded_application_session = Some(session);
249        Ok(())
250    }
251
252    pub(crate) const fn bounded_application_session_enabled(&self) -> bool {
253        self.bounded_application_session.is_some()
254    }
255
256    pub(crate) fn disable_bounded_application_session(&mut self) {
257        if let Some(session) = self.bounded_application_session.take() {
258            session.close();
259        }
260    }
261
262    pub(crate) async fn execute_selected_query_transport(
263        &mut self,
264        message: app_v1::ExecuteQueryRequest,
265        metadata: &CallMetadata,
266    ) -> Result<app_v1::ExecuteQueryResponse, ClientError> {
267        if let Some(session) = self.bounded_application_session.as_ref() {
268            if !session.matches_metadata(metadata) {
269                return Err(invalid_outbound());
270            }
271            return session.execute_query(message).await;
272        }
273        self.execute_query(message, metadata).await
274    }
275
276    pub(crate) async fn open_application_session<S>(
277        &mut self,
278        stream: S,
279        metadata: &CallMetadata,
280    ) -> Result<Streaming<v1::ApplicationSessionResponse>, ClientError>
281    where
282        S: futures_util::Stream<Item = v1::ApplicationSessionRequest> + Send + 'static,
283    {
284        let mut request = Request::new(stream);
285        metadata.apply(&mut request);
286        self.application_session
287            .open(request)
288            .await
289            .map_err(checked_application_status)
290            .map(Response::into_inner)
291    }
292
293    /// Remembers an observed history incarnation for subsequent commit reads.
294    ///
295    /// Pass `None` to clear. Explicit per-request values always win.
296    pub fn set_observed_history_incarnation(&mut self, observed: Option<u64>) {
297        self.observed_history_incarnation = observed;
298    }
299
300    /// Returns the client-remembered observed history incarnation, if any.
301    #[must_use]
302    pub const fn observed_history_incarnation(&self) -> Option<u64> {
303        self.observed_history_incarnation
304    }
305
306    /// Fills `observed_history_incarnation` on a get-commit request when unset.
307    #[must_use]
308    pub fn apply_observed_history_incarnation_get(
309        &self,
310        mut request: v1::GetCommitRequest,
311    ) -> v1::GetCommitRequest {
312        request.observed_history_incarnation = merge_observed_history_incarnation(
313            request.observed_history_incarnation,
314            self.observed_history_incarnation,
315        );
316        request
317    }
318
319    /// Fills `observed_history_incarnation` on a scan-commits request when unset.
320    #[must_use]
321    pub fn apply_observed_history_incarnation_scan(
322        &self,
323        mut request: v1::ScanCommitsRequest,
324    ) -> v1::ScanCommitsRequest {
325        request.observed_history_incarnation = merge_observed_history_incarnation(
326            request.observed_history_incarnation,
327            self.observed_history_incarnation,
328        );
329        request
330    }
331
332    /// Fills `observed_history_incarnation` on a subscribe request when unset.
333    #[must_use]
334    pub fn apply_observed_history_incarnation_subscribe(
335        &self,
336        mut request: v1::SubscribeCommitsRequest,
337    ) -> v1::SubscribeCommitsRequest {
338        request.observed_history_incarnation = merge_observed_history_incarnation(
339            request.observed_history_incarnation,
340            self.observed_history_incarnation,
341        );
342        request
343    }
344
345    /// Fills `observed_history_incarnation` on a replay-events request when unset (`0`).
346    #[must_use]
347    pub fn apply_observed_history_incarnation_replay(
348        &self,
349        mut request: v1::ReplayEventsRequest,
350    ) -> v1::ReplayEventsRequest {
351        if request.observed_history_incarnation == 0
352            && let Some(remembered) = self.observed_history_incarnation
353        {
354            request.observed_history_incarnation = remembered;
355        }
356        request
357    }
358
359    /// Fills `observed_history_incarnation` on a tail-events request when unset (`0`).
360    #[must_use]
361    pub fn apply_observed_history_incarnation_tail(
362        &self,
363        mut request: v1::TailEventsRequest,
364    ) -> v1::TailEventsRequest {
365        if request.observed_history_incarnation == 0
366            && let Some(remembered) = self.observed_history_incarnation
367        {
368            request.observed_history_incarnation = remembered;
369        }
370        request
371    }
372
373    /// Remembers the history incarnation reported by a get-commit response.
374    pub fn remember_history_incarnation_from_get(&mut self, response: &v1::GetCommitResponse) {
375        if response.history_incarnation >= 1 {
376            self.observed_history_incarnation = Some(response.history_incarnation);
377        }
378    }
379
380    /// Remembers the history incarnation reported by a commit page.
381    pub fn remember_history_incarnation_from_scan(&mut self, response: &v1::ScanCommitsResponse) {
382        if let Some(page) = response.page.as_ref()
383            && page.history_incarnation >= 1
384        {
385            self.observed_history_incarnation = Some(page.history_incarnation);
386        }
387    }
388
389    /// Remembers the history incarnation reported by an event page.
390    pub fn remember_history_incarnation_from_event_page(&mut self, page: Option<&v1::EventPage>) {
391        if let Some(page) = page
392            && page.history_incarnation >= 1
393        {
394            self.observed_history_incarnation = Some(page.history_incarnation);
395        }
396    }
397
398    unary_application!(
399        describe_contract,
400        describe_contract,
401        app_v1::DescribeContractRequest,
402        app_v1::DescribeContractResponse
403    );
404    unary_application!(
405        get_application_catalog,
406        get_application_catalog,
407        app_v1::GetApplicationCatalogRequest,
408        app_v1::GetApplicationCatalogResponse
409    );
410    unary_application!(
411        check_query,
412        check_query,
413        app_v1::CheckQueryRequest,
414        app_v1::CheckQueryResponse
415    );
416    unary_application!(
417        explain_query,
418        explain_query,
419        app_v1::ExplainQueryRequest,
420        app_v1::ExplainQueryResponse
421    );
422    unary_application!(
423        execute_query,
424        execute_query,
425        app_v1::ExecuteQueryRequest,
426        app_v1::ExecuteQueryResponse
427    );
428    unary_application!(
429        deploy_query_module,
430        deploy_query_module,
431        app_v1::DeployQueryModuleRequest,
432        app_v1::DeployQueryModuleResponse
433    );
434    unary_application!(
435        deploy_reactive_module,
436        deploy_reactive_module,
437        app_v1::DeployReactiveModuleRequest,
438        app_v1::DeployReactiveModuleResponse
439    );
440    unary_application!(
441        get_query_module,
442        get_query_module,
443        app_v1::GetQueryModuleRequest,
444        app_v1::GetQueryModuleResponse
445    );
446    unary_application!(
447        execute_projected_query_raw,
448        execute_projected_query,
449        app_v1::ExecuteProjectedQueryRequest,
450        app_v1::ExecuteProjectedQueryResponse
451    );
452    unary_application!(
453        inspect_vector_state,
454        inspect_vector_state,
455        app_v1::InspectVectorStateRequest,
456        app_v1::InspectVectorStateResponse
457    );
458
459    unary_exchange!(
460        validate_contract,
461        contract,
462        validate_contract,
463        v1::ValidateContractRequest,
464        v1::ValidateContractResponse,
465        validate_contract_validation_exchange
466    );
467    unary_exchange!(
468        explain_command,
469        contract,
470        explain_command,
471        v1::ExplainCommandRequest,
472        v1::ExplainCommandResponse,
473        validate_explain_command_exchange
474    );
475    unary!(
476        deploy_contract,
477        contract,
478        deploy_contract,
479        v1::DeployContractRequest,
480        v1::DeployContractResponse
481    );
482    unary!(
483        get_active_contract,
484        contract,
485        get_active_contract,
486        v1::GetActiveContractRequest,
487        v1::GetActiveContractResponse
488    );
489    unary_exchange!(
490        get_contract_version,
491        contract,
492        get_contract_version,
493        v1::GetContractVersionRequest,
494        v1::GetContractVersionResponse,
495        validate_get_contract_version_exchange
496    );
497    unary_exchange!(
498        discover_command_tools,
499        contract,
500        discover_command_tools,
501        v1::DiscoverCommandToolsRequest,
502        v1::DiscoverCommandToolsResponse,
503        validate_discover_command_tools_exchange
504    );
505    unary_exchange!(
506        discover_resources,
507        contract,
508        discover_resources,
509        v1::DiscoverResourcesRequest,
510        v1::DiscoverResourcesResponse,
511        validate_discover_resources_exchange
512    );
513    unary!(
514        get_reactive_wakeup,
515        contract,
516        get_reactive_wakeup,
517        v1::GetReactiveWakeupRequest,
518        v1::GetReactiveWakeupResponse
519    );
520    unary!(
521        execute,
522        command,
523        execute,
524        v1::ExecuteCommandRequest,
525        v1::ExecuteCommandResponse
526    );
527    unary_exchange!(
528        execute_batch,
529        command,
530        execute_batch,
531        v1::ExecuteCommandBatchRequest,
532        v1::ExecuteCommandBatchResponse,
533        riffdb_proto::validate_execute_command_batch_exchange
534    );
535    unary_exchange!(
536        get_outcome,
537        command,
538        get_outcome,
539        v1::GetOutcomeRequest,
540        v1::GetOutcomeResponse,
541        validate_get_outcome_exchange
542    );
543    unary!(
544        get_entity,
545        query,
546        get_entity,
547        v1::GetEntityRequest,
548        v1::GetEntityResponse
549    );
550    unary_exchange!(
551        scan_index,
552        query,
553        scan_index,
554        v1::ScanIndexRequest,
555        v1::ScanIndexResponse,
556        validate_scan_index_exchange
557    );
558    unary_exchange!(
559        query_projection,
560        query,
561        query_projection,
562        v1::QueryProjectionRequest,
563        v1::QueryProjectionResponse,
564        validate_query_projection_exchange
565    );
566    unary_exchange!(
567        get_projection_status,
568        query,
569        get_projection_status,
570        v1::GetProjectionStatusRequest,
571        v1::GetProjectionStatusResponse,
572        validate_get_projection_status_exchange
573    );
574
575    /// Queries a projection while asking the server to wait for one sequence.
576    ///
577    /// The server owns waiting and frontier correctness. This helper only maps
578    /// the exact `Duration` into the protocol's total-nanosecond field and
579    /// retains every caller-selected query, page, and fresh request ID field.
580    pub async fn wait_for_projection(
581        &mut self,
582        mut message: v1::QueryProjectionRequest,
583        required_sequence: CommitSequence,
584        maximum_wait: Duration,
585        metadata: &CallMetadata,
586    ) -> Result<v1::QueryProjectionResponse, ClientError> {
587        configure_projection_wait(&mut message, required_sequence, maximum_wait)?;
588        self.query_projection(message, metadata).await
589    }
590    /// Performs the checked `get_commit` unary RPC.
591    pub async fn get_commit(
592        &mut self,
593        message: v1::GetCommitRequest,
594        metadata: &CallMetadata,
595    ) -> Result<v1::GetCommitResponse, ClientError> {
596        let message = self.apply_observed_history_incarnation_get(message);
597        validate_outbound(&message)?;
598        let mut request = Request::new(message);
599        metadata.apply(&mut request);
600        let response = self
601            .commit
602            .get_commit(request)
603            .await
604            .map_err(checked_status)?
605            .into_inner();
606        self.remember_history_incarnation_from_get(&response);
607        Ok(response)
608    }
609
610    /// Performs the checked `scan_commits` unary RPC.
611    pub async fn scan_commits(
612        &mut self,
613        message: v1::ScanCommitsRequest,
614        metadata: &CallMetadata,
615    ) -> Result<v1::ScanCommitsResponse, ClientError> {
616        let message = self.apply_observed_history_incarnation_scan(message);
617        validate_outbound(&message)?;
618        let exchange_request = message.clone();
619        let mut request = Request::new(message);
620        metadata.apply(&mut request);
621        let response = self
622            .commit
623            .scan_commits(request)
624            .await
625            .map_err(checked_status)?
626            .into_inner();
627        validate_scan_commits_exchange(&exchange_request, &response)
628            .map_err(|_| invalid_inbound())?;
629        self.remember_history_incarnation_from_scan(&response);
630        Ok(response)
631    }
632
633    unary_exchange!(
634        trace_provenance,
635        commit,
636        trace_provenance,
637        v1::TraceProvenanceRequest,
638        v1::TraceProvenanceResponse,
639        validate_trace_provenance_exchange
640    );
641    unary!(
642        describe_event,
643        event,
644        describe_event,
645        v1::DescribeEventRequest,
646        v1::DescribeEventResponse
647    );
648
649    /// Performs the checked `replay_events` unary RPC.
650    pub async fn replay_events(
651        &mut self,
652        message: v1::ReplayEventsRequest,
653        metadata: &CallMetadata,
654    ) -> Result<v1::ReplayEventsResponse, ClientError> {
655        let message = self.apply_observed_history_incarnation_replay(message);
656        validate_outbound(&message)?;
657        let mut request = Request::new(message);
658        metadata.apply(&mut request);
659        let response = self
660            .event
661            .replay_events(request)
662            .await
663            .map_err(checked_status)?
664            .into_inner();
665        self.remember_history_incarnation_from_event_page(response.page.as_ref());
666        Ok(response)
667    }
668
669    /// Performs the checked `tail_events` unary RPC.
670    pub async fn tail_events(
671        &mut self,
672        message: v1::TailEventsRequest,
673        metadata: &CallMetadata,
674    ) -> Result<v1::TailEventsResponse, ClientError> {
675        let message = self.apply_observed_history_incarnation_tail(message);
676        validate_outbound(&message)?;
677        let mut request = Request::new(message);
678        metadata.apply(&mut request);
679        let response = self
680            .event
681            .tail_events(request)
682            .await
683            .map_err(checked_status)?
684            .into_inner();
685        self.remember_history_incarnation_from_event_page(response.page.as_ref());
686        Ok(response)
687    }
688    unary!(
689        consume_event_stream,
690        event,
691        consume_event_stream,
692        v1::ConsumeEventStreamRequest,
693        v1::ConsumeEventStreamResponse
694    );
695    unary!(
696        acknowledge_event_stream,
697        event,
698        acknowledge_event_stream,
699        v1::AcknowledgeEventStreamRequest,
700        v1::EventConsumerMutationResponse
701    );
702    unary!(
703        negative_acknowledge_event_stream,
704        event,
705        negative_acknowledge_event_stream,
706        v1::NegativeAcknowledgeEventStreamRequest,
707        v1::EventConsumerMutationResponse
708    );
709    unary!(
710        seek_event_stream_consumer,
711        event,
712        seek_event_stream_consumer,
713        v1::SeekEventStreamConsumerRequest,
714        v1::EventConsumerMutationResponse
715    );
716    unary!(
717        retire_event_stream_consumer,
718        event,
719        retire_event_stream_consumer,
720        v1::RetireEventStreamConsumerRequest,
721        v1::EventConsumerMutationResponse
722    );
723    unary!(
724        get_event_stream_consumer_status,
725        event,
726        get_event_stream_consumer_status,
727        v1::GetEventStreamConsumerStatusRequest,
728        v1::GetEventStreamConsumerStatusResponse
729    );
730    unary!(
731        consume_contextual_subscription,
732        event,
733        consume_contextual_subscription,
734        v1::ConsumeContextualSubscriptionRequest,
735        v1::ConsumeContextualSubscriptionResponse
736    );
737    unary!(
738        acknowledge_contextual_subscription,
739        event,
740        acknowledge_contextual_subscription,
741        v1::AcknowledgeContextualSubscriptionRequest,
742        v1::EventConsumerMutationResponse
743    );
744    unary!(
745        negative_acknowledge_contextual_subscription,
746        event,
747        negative_acknowledge_contextual_subscription,
748        v1::NegativeAcknowledgeContextualSubscriptionRequest,
749        v1::EventConsumerMutationResponse
750    );
751    unary!(
752        get_contextual_subscription_status,
753        event,
754        get_contextual_subscription_status,
755        v1::GetContextualSubscriptionStatusRequest,
756        v1::GetEventStreamConsumerStatusResponse
757    );
758    unary!(
759        execute_contextual_reaction,
760        event,
761        execute_contextual_reaction,
762        v1::ExecuteContextualReactionRequest,
763        v1::ExecuteCommandResponse
764    );
765    unary!(register_follower, admin, register_follower, v1::RegisterFollowerRequest, v1::RegisterFollowerResponse);
766    unary_exchange!(promote_follower, admin, promote_follower, v1::PromoteFollowerRequest, v1::PromoteFollowerResponse, riffdb_proto::validate_promote_follower_exchange);
767    unary_exchange!(retire_follower, admin, retire_follower, v1::RetireFollowerRequest, v1::RetireFollowerResponse, riffdb_proto::validate_retire_follower_exchange);
768    unary_exchange!(fence_replication_primary, admin, fence_replication_primary, v1::FenceReplicationPrimaryRequest, v1::FenceReplicationPrimaryResponse, riffdb_proto::validate_fence_replication_primary_exchange);
769    unary!(health, admin, health, v1::HealthRequest, v1::HealthResponse);
770    unary!(stats, admin, stats, v1::StatsRequest, v1::StatsResponse);
771    unary!(
772        revoke_capability,
773        admin,
774        revoke_capability,
775        v1::RevokeCapabilityRequest,
776        v1::RevokeCapabilityResponse
777    );
778    unary_exchange!(
779        list_pending_outbox_deliveries,
780        admin,
781        list_pending_outbox_deliveries,
782        v1::ListPendingOutboxDeliveriesRequest,
783        v1::ListPendingOutboxDeliveriesResponse,
784        validate_list_pending_outbox_deliveries_exchange
785    );
786    unary_exchange!(
787        create_offline_backup,
788        admin,
789        create_offline_backup,
790        v1::CreateOfflineBackupRequest,
791        v1::CreateOfflineBackupResponse,
792        validate_create_offline_backup_exchange
793    );
794    unary_exchange!(
795        restore_offline_backup,
796        admin,
797        restore_offline_backup,
798        v1::RestoreOfflineBackupRequest,
799        v1::RestoreOfflineBackupResponse,
800        validate_restore_offline_backup_exchange
801    );
802    unary_exchange!(
803        restore_archived_backup,
804        admin,
805        restore_archived_backup,
806        v1::RestoreArchivedBackupRequest,
807        v1::RestoreArchivedBackupResponse,
808        validate_restore_archived_backup_exchange
809    );
810    unary_exchange!(
811        retire_offline_backup,
812        admin,
813        retire_offline_backup,
814        v1::RetireOfflineBackupRequest,
815        v1::RetireOfflineBackupResponse,
816        validate_retire_offline_backup_exchange
817    );
818    unary_exchange!(
819        start_offline_storage_scrub,
820        admin,
821        start_offline_storage_scrub,
822        v1::StartOfflineStorageScrubRequest,
823        v1::StartOfflineStorageScrubResponse,
824        validate_start_offline_storage_scrub_exchange
825    );
826    unary_exchange!(
827        get_offline_maintenance_operation,
828        admin,
829        get_offline_maintenance_operation,
830        v1::GetOfflineMaintenanceOperationRequest,
831        v1::GetOfflineMaintenanceOperationResponse,
832        validate_get_offline_maintenance_operation_exchange
833    );
834    unary_exchange!(
835        check_contract_migration,
836        admin,
837        check_contract_migration,
838        v1::CheckContractMigrationRequest,
839        v1::CheckContractMigrationResponse,
840        validate_check_contract_migration_exchange
841    );
842    unary_exchange!(
843        apply_contract_migration,
844        admin,
845        apply_contract_migration,
846        v1::ApplyContractMigrationRequest,
847        v1::ApplyContractMigrationResponse,
848        validate_apply_contract_migration_exchange
849    );
850    unary_exchange!(
851        get_contract_migration_operation,
852        admin,
853        get_contract_migration_operation,
854        v1::GetContractMigrationOperationRequest,
855        v1::GetContractMigrationOperationResponse,
856        validate_get_contract_migration_operation_exchange
857    );
858    unary_exchange!(
859        start_application_installation,
860        admin,
861        start_application_installation,
862        v1::StartApplicationInstallationRequest,
863        v1::StartApplicationInstallationResponse,
864        validate_start_application_installation_exchange
865    );
866    unary_exchange!(
867        get_application_installation,
868        admin,
869        get_application_installation,
870        v1::GetApplicationInstallationRequest,
871        v1::GetApplicationInstallationResponse,
872        validate_get_application_installation_exchange
873    );
874    unary_exchange!(
875        start_application_export,
876        admin,
877        start_application_export,
878        v1::StartApplicationExportRequest,
879        v1::StartApplicationExportResponse,
880        validate_start_application_export_exchange
881    );
882    unary_exchange!(
883        get_application_export_page,
884        admin,
885        get_application_export_page,
886        v1::GetApplicationExportPageRequest,
887        v1::GetApplicationExportPageResponse,
888        validate_get_application_export_page_exchange
889    );
890    unary_exchange!(
891        get_application_export,
892        admin,
893        get_application_export,
894        v1::GetApplicationExportRequest,
895        v1::GetApplicationExportResponse,
896        validate_get_application_export_exchange
897    );
898    unary_exchange!(
899        cancel_application_export,
900        admin,
901        cancel_application_export,
902        v1::CancelApplicationExportRequest,
903        v1::CancelApplicationExportResponse,
904        validate_cancel_application_export_exchange
905    );
906    unary_exchange!(
907        start_application_reimport,
908        admin,
909        start_application_reimport,
910        v1::StartApplicationReimportRequest,
911        v1::StartApplicationReimportResponse,
912        validate_start_application_reimport_exchange
913    );
914    unary_exchange!(
915        apply_application_reimport_page,
916        admin,
917        apply_application_reimport_page,
918        v1::ApplyApplicationReimportPageRequest,
919        v1::ApplyApplicationReimportPageResponse,
920        validate_apply_application_reimport_page_exchange
921    );
922    unary_exchange!(
923        get_application_reimport,
924        admin,
925        get_application_reimport,
926        v1::GetApplicationReimportRequest,
927        v1::GetApplicationReimportResponse,
928        validate_get_application_reimport_exchange
929    );
930    unary_exchange!(
931        cancel_application_reimport,
932        admin,
933        cancel_application_reimport,
934        v1::CancelApplicationReimportRequest,
935        v1::CancelApplicationReimportResponse,
936        validate_cancel_application_reimport_exchange
937    );
938
939    /// Performs normal authenticated capability creation.
940    pub async fn create_capability(
941        &mut self,
942        message: v1::CreateCapabilityRequest,
943        metadata: &CallMetadata,
944    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
945        if message.mode != v1::CapabilityCreateMode::Normal as i32 {
946            return Err(invalid_outbound());
947        }
948        self.create_capability_with(message, metadata, CallMetadata::apply)
949            .await
950    }
951
952    /// Performs the loopback-only bootstrap capability creation call.
953    pub async fn create_bootstrap_capability(
954        &mut self,
955        message: v1::CreateCapabilityRequest,
956        metadata: &BootstrapCallMetadata,
957    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
958        if message.mode != v1::CapabilityCreateMode::Bootstrap as i32 {
959            return Err(invalid_outbound());
960        }
961        self.create_capability_with(message, metadata, BootstrapCallMetadata::apply)
962            .await
963    }
964
965    async fn create_capability_with<M>(
966        &mut self,
967        message: v1::CreateCapabilityRequest,
968        metadata: &M,
969        apply: fn(&M, &mut Request<v1::CreateCapabilityRequest>),
970    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
971        validate_outbound(&message)?;
972        let exchange_request = message.clone();
973        let mut request = Request::new(message);
974        apply(metadata, &mut request);
975        let response = self
976            .admin
977            .create_capability(request)
978            .await
979            .map_err(checked_status)?
980            .into_inner();
981        validate_create_capability_exchange(&exchange_request, &response)
982            .map_err(|_| invalid_inbound())?;
983        Ok(response)
984    }
985
986    /// Starts a checked commit stream.
987    ///
988    /// Items are decoded by the strict codec (`decode_public_message`). This
989    /// stream does not re-walk structure after decode; exchange-style relations
990    /// do not apply to commit notifications.
991    pub async fn subscribe_commits(
992        &mut self,
993        message: v1::SubscribeCommitsRequest,
994        metadata: &CallMetadata,
995    ) -> Result<CommitNotificationStream, ClientError> {
996        let message = self.apply_observed_history_incarnation_subscribe(message);
997        validate_outbound(&message)?;
998        let mut request = Request::new(message);
999        metadata.apply(&mut request);
1000        let inner = self
1001            .commit
1002            .subscribe_commits(request)
1003            .await
1004            .map_err(checked_status)?
1005            .into_inner();
1006        Ok(CommitNotificationStream { inner })
1007    }
1008
1009    /// Starts a checked durable event-consumer response stream.
1010    ///
1011    /// Items are decoded by the strict public codec. Consumer identity,
1012    /// authorization, leasing, and checkpoint semantics remain server-owned.
1013    pub async fn stream_event_consumer(
1014        &mut self,
1015        message: v1::ConsumeEventStreamRequest,
1016        metadata: &CallMetadata,
1017    ) -> Result<EventConsumerResponseStream, ClientError> {
1018        validate_outbound(&message)?;
1019        let mut request = Request::new(message);
1020        metadata.apply(&mut request);
1021        let inner = self
1022            .event
1023            .stream_event_consumer(request)
1024            .await
1025            .map_err(checked_status)?
1026            .into_inner();
1027        Ok(EventConsumerResponseStream { inner })
1028    }
1029
1030    /// Starts a checked exact named-query live stream.
1031    ///
1032    /// The cursor is consistency evidence only; every reconnect is freshly
1033    /// authenticated and authorized by the server.
1034    pub async fn watch_named_query(
1035        &mut self,
1036        message: v1::WatchNamedQueryRequest,
1037        metadata: &CallMetadata,
1038    ) -> Result<LiveQueryUpdateStream, ClientError> {
1039        validate_outbound(&message)?;
1040        let mut request = Request::new(message);
1041        metadata.apply(&mut request);
1042        let inner = self
1043            .query
1044            .watch_named_query(request)
1045            .await
1046            .map_err(checked_status)?
1047            .into_inner();
1048        Ok(LiveQueryUpdateStream { inner })
1049    }
1050
1051    /// Executes one immutable command with an explicit total submission bound.
1052    ///
1053    /// Retryable checked failures are resubmitted immediately with a fresh
1054    /// outer request ID. Overloaded retries apply bounded backoff (command
1055    /// module); other retryables resubmit immediately without inventing a
1056    /// generic retry policy. This method never mutates
1057    /// the command name, selected version, or opaque input.
1058    pub async fn execute_with_retry(
1059        &mut self,
1060        command: &IdempotentCommand,
1061        attempt_budget: AttemptBudget,
1062        metadata: &CallMetadata,
1063    ) -> Result<v1::ExecuteCommandResponse, ClientError> {
1064        let mut request_ids = SystemIdSource::new();
1065        execute_retry_attempts(self, command, attempt_budget, metadata, &mut request_ids).await
1066    }
1067
1068    /// Creates one normal capability with immutable identity and bounded retry.
1069    pub async fn create_capability_with_retry(
1070        &mut self,
1071        create: &NormalCapabilityCreateTemplate,
1072        attempt_budget: AttemptBudget,
1073        metadata: &CallMetadata,
1074    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
1075        let mut request_ids = SystemIdSource::new();
1076        normal_capability_retry_attempts(self, create, attempt_budget, metadata, &mut request_ids)
1077            .await
1078    }
1079
1080    /// Creates one bootstrap capability with immutable identity and bounded retry.
1081    pub async fn create_bootstrap_capability_with_retry(
1082        &mut self,
1083        create: &BootstrapCapabilityCreateTemplate,
1084        attempt_budget: AttemptBudget,
1085        metadata: &BootstrapCallMetadata,
1086    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
1087        let mut request_ids = SystemIdSource::new();
1088        bootstrap_capability_retry_attempts(
1089            self,
1090            create,
1091            attempt_budget,
1092            metadata,
1093            &mut request_ids,
1094        )
1095        .await
1096    }
1097
1098    /// Starts or resolves one immutable backup-create operation with bounded retry.
1099    pub async fn create_offline_backup_with_retry(
1100        &mut self,
1101        create: &CreateOfflineBackup,
1102        attempt_budget: AttemptBudget,
1103        metadata: &CallMetadata,
1104    ) -> Result<v1::CreateOfflineBackupResponse, ClientError> {
1105        let mut request_ids = SystemIdSource::new();
1106        let mut retry = RetryState::new(attempt_budget);
1107        loop {
1108            if !retry.begin_submission() {
1109                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1110            }
1111            let request_id = request_ids
1112                .next_request_id()
1113                .map_err(|error| retry.request_id_failure(error))?;
1114            retry.note_request_id(&request_id);
1115            match self
1116                .create_offline_backup(create.request(request_id), metadata)
1117                .await
1118            {
1119                Ok(response) => return Ok(response),
1120                Err(error) => match retry.handle_failure(error) {
1121                    RetryDecision::Retry => {}
1122                    RetryDecision::RetryAfter(delay) => {
1123                        apply_overloaded_backoff(delay).await;
1124                    }
1125                    RetryDecision::Return(error) => return Err(error),
1126                },
1127            }
1128        }
1129    }
1130
1131    /// Starts or resolves one immutable restore operation with bounded retry.
1132    pub async fn restore_offline_backup_with_retry(
1133        &mut self,
1134        restore: &RestoreOfflineBackup,
1135        attempt_budget: AttemptBudget,
1136        metadata: &CallMetadata,
1137    ) -> Result<v1::RestoreOfflineBackupResponse, ClientError> {
1138        let mut request_ids = SystemIdSource::new();
1139        let mut retry = RetryState::new(attempt_budget);
1140        loop {
1141            if !retry.begin_submission() {
1142                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1143            }
1144            let request_id = request_ids
1145                .next_request_id()
1146                .map_err(|error| retry.request_id_failure(error))?;
1147            retry.note_request_id(&request_id);
1148            match self
1149                .restore_offline_backup(restore.request(request_id), metadata)
1150                .await
1151            {
1152                Ok(response) => return Ok(response),
1153                Err(error) => match retry.handle_failure(error) {
1154                    RetryDecision::Retry => {}
1155                    RetryDecision::RetryAfter(delay) => {
1156                        apply_overloaded_backoff(delay).await;
1157                    }
1158                    RetryDecision::Return(error) => return Err(error),
1159                },
1160            }
1161        }
1162    }
1163
1164    /// Starts or resolves one immutable archive restore operation with bounded retry.
1165    pub async fn restore_archived_backup_with_retry(
1166        &mut self,
1167        restore: &RestoreArchivedBackup,
1168        attempt_budget: AttemptBudget,
1169        metadata: &CallMetadata,
1170    ) -> Result<v1::RestoreArchivedBackupResponse, ClientError> {
1171        let mut request_ids = SystemIdSource::new();
1172        let mut retry = RetryState::new(attempt_budget);
1173        loop {
1174            if !retry.begin_submission() {
1175                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1176            }
1177            let request_id = request_ids
1178                .next_request_id()
1179                .map_err(|error| retry.request_id_failure(error))?;
1180            retry.note_request_id(&request_id);
1181            match self
1182                .restore_archived_backup(restore.request(request_id), metadata)
1183                .await
1184            {
1185                Ok(response) => return Ok(response),
1186                Err(error) => match retry.handle_failure(error) {
1187                    RetryDecision::Retry => {}
1188                    RetryDecision::RetryAfter(delay) => {
1189                        apply_overloaded_backoff(delay).await;
1190                    }
1191                    RetryDecision::Return(error) => return Err(error),
1192                },
1193            }
1194        }
1195    }
1196
1197    /// Starts or resolves one immutable backup-retirement operation with bounded retry.
1198    pub async fn retire_offline_backup_with_retry(
1199        &mut self,
1200        retire: &RetireOfflineBackup,
1201        attempt_budget: AttemptBudget,
1202        metadata: &CallMetadata,
1203    ) -> Result<v1::RetireOfflineBackupResponse, ClientError> {
1204        let mut request_ids = SystemIdSource::new();
1205        let mut retry = RetryState::new(attempt_budget);
1206        loop {
1207            if !retry.begin_submission() {
1208                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1209            }
1210            let request_id = request_ids
1211                .next_request_id()
1212                .map_err(|error| retry.request_id_failure(error))?;
1213            retry.note_request_id(&request_id);
1214            match self
1215                .retire_offline_backup(retire.request(request_id), metadata)
1216                .await
1217            {
1218                Ok(response) => return Ok(response),
1219                Err(error) => match retry.handle_failure(error) {
1220                    RetryDecision::Retry => {}
1221                    RetryDecision::RetryAfter(delay) => {
1222                        apply_overloaded_backoff(delay).await;
1223                    }
1224                    RetryDecision::Return(error) => return Err(error),
1225                },
1226            }
1227        }
1228    }
1229
1230    /// Starts or resolves the selector-free offline storage scrub with bounded retry.
1231    pub async fn start_offline_storage_scrub_with_retry(
1232        &mut self,
1233        scrub: &StartOfflineStorageScrub,
1234        attempt_budget: AttemptBudget,
1235        metadata: &CallMetadata,
1236    ) -> Result<v1::StartOfflineStorageScrubResponse, ClientError> {
1237        let mut request_ids = SystemIdSource::new();
1238        let mut retry = RetryState::new(attempt_budget);
1239        loop {
1240            if !retry.begin_submission() {
1241                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1242            }
1243            let request_id = request_ids
1244                .next_request_id()
1245                .map_err(|error| retry.request_id_failure(error))?;
1246            retry.note_request_id(&request_id);
1247            match self
1248                .start_offline_storage_scrub(scrub.request(request_id), metadata)
1249                .await
1250            {
1251                Ok(response) => return Ok(response),
1252                Err(error) => match retry.handle_failure(error) {
1253                    RetryDecision::Retry => {}
1254                    RetryDecision::RetryAfter(delay) => {
1255                        apply_overloaded_backoff(delay).await;
1256                    }
1257                    RetryDecision::Return(error) => return Err(error),
1258                },
1259            }
1260        }
1261    }
1262
1263    /// Starts or resolves one immutable migration check with bounded retry.
1264    pub async fn check_contract_migration_with_retry(
1265        &mut self,
1266        check: &CheckContractMigration,
1267        attempt_budget: AttemptBudget,
1268        metadata: &CallMetadata,
1269    ) -> Result<v1::CheckContractMigrationResponse, ClientError> {
1270        let mut request_ids = SystemIdSource::new();
1271        let mut retry = RetryState::new(attempt_budget);
1272        loop {
1273            if !retry.begin_submission() {
1274                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1275            }
1276            let request_id = request_ids
1277                .next_request_id()
1278                .map_err(|error| retry.request_id_failure(error))?;
1279            retry.note_request_id(&request_id);
1280            match self
1281                .check_contract_migration(check.request(request_id), metadata)
1282                .await
1283            {
1284                Ok(response) => return Ok(response),
1285                Err(error) => match retry.handle_failure(error) {
1286                    RetryDecision::Retry => {}
1287                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1288                    RetryDecision::Return(error) => return Err(error),
1289                },
1290            }
1291        }
1292    }
1293
1294    /// Starts or resolves one immutable confirmed migration apply with bounded retry.
1295    pub async fn apply_contract_migration_with_retry(
1296        &mut self,
1297        apply: &ApplyContractMigration,
1298        attempt_budget: AttemptBudget,
1299        metadata: &CallMetadata,
1300    ) -> Result<v1::ApplyContractMigrationResponse, ClientError> {
1301        let mut request_ids = SystemIdSource::new();
1302        let mut retry = RetryState::new(attempt_budget);
1303        loop {
1304            if !retry.begin_submission() {
1305                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1306            }
1307            let request_id = request_ids
1308                .next_request_id()
1309                .map_err(|error| retry.request_id_failure(error))?;
1310            retry.note_request_id(&request_id);
1311            match self
1312                .apply_contract_migration(apply.request(request_id), metadata)
1313                .await
1314            {
1315                Ok(response) => return Ok(response),
1316                Err(error) => match retry.handle_failure(error) {
1317                    RetryDecision::Retry => {}
1318                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1319                    RetryDecision::Return(error) => return Err(error),
1320                },
1321            }
1322        }
1323    }
1324
1325    /// Starts or resumes one immutable exact installation campaign with bounded retry.
1326    pub async fn start_application_installation_with_retry(
1327        &mut self,
1328        start: &StartApplicationInstallation,
1329        attempt_budget: AttemptBudget,
1330        metadata: &CallMetadata,
1331    ) -> Result<v1::StartApplicationInstallationResponse, ClientError> {
1332        let mut request_ids = SystemIdSource::new();
1333        let mut retry = RetryState::new(attempt_budget);
1334        loop {
1335            if !retry.begin_submission() {
1336                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1337            }
1338            let request_id = request_ids
1339                .next_request_id()
1340                .map_err(|error| retry.request_id_failure(error))?;
1341            retry.note_request_id(&request_id);
1342            match self
1343                .start_application_installation(start.request(request_id), metadata)
1344                .await
1345            {
1346                Ok(response) => return Ok(response),
1347                Err(error) => match retry.handle_failure(error) {
1348                    RetryDecision::Retry => {}
1349                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1350                    RetryDecision::Return(error) => return Err(error),
1351                },
1352            }
1353        }
1354    }
1355
1356    /// Starts or exactly replays one immutable symbolic export with bounded retry.
1357    pub async fn start_application_export_with_retry(
1358        &mut self,
1359        start: &StartApplicationExport,
1360        attempt_budget: AttemptBudget,
1361        metadata: &CallMetadata,
1362    ) -> Result<v1::StartApplicationExportResponse, ClientError> {
1363        let mut request_ids = SystemIdSource::new();
1364        let mut retry = RetryState::new(attempt_budget);
1365        loop {
1366            if !retry.begin_submission() {
1367                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1368            }
1369            let request_id = request_ids
1370                .next_request_id()
1371                .map_err(|error| retry.request_id_failure(error))?;
1372            retry.note_request_id(&request_id);
1373            match self
1374                .start_application_export(start.request(request_id), metadata)
1375                .await
1376            {
1377                Ok(response) => return Ok(response),
1378                Err(error) => match retry.handle_failure(error) {
1379                    RetryDecision::Retry => {}
1380                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1381                    RetryDecision::Return(error) => return Err(error),
1382                },
1383            }
1384        }
1385    }
1386
1387    /// Releases or exactly replays one snapshot-bound export page with bounded retry.
1388    ///
1389    /// The opaque cursor is reused byte-for-byte across attempts. If the final
1390    /// response remains uncertain, callers may safely invoke this method again
1391    /// with the same cursor while the operation lease remains valid.
1392    pub async fn get_application_export_page_with_retry(
1393        &mut self,
1394        operation_id: ApplicationExportOperationId,
1395        cursor: &[u8],
1396        max_rows: u16,
1397        attempt_budget: AttemptBudget,
1398        metadata: &CallMetadata,
1399    ) -> Result<v1::GetApplicationExportPageResponse, ClientError> {
1400        let mut request_ids = SystemIdSource::new();
1401        let mut retry = RetryState::new(attempt_budget);
1402        loop {
1403            if !retry.begin_submission() {
1404                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1405            }
1406            let request_id = request_ids
1407                .next_request_id()
1408                .map_err(|error| retry.request_id_failure(error))?;
1409            retry.note_request_id(&request_id);
1410            let request = v1::GetApplicationExportPageRequest {
1411                request_id: request_id.into_bytes().to_vec(),
1412                operation_id: operation_id.into_bytes().to_vec(),
1413                cursor: cursor.to_vec(),
1414                max_rows: u32::from(max_rows),
1415            };
1416            match self.get_application_export_page(request, metadata).await {
1417                Ok(response) => return Ok(response),
1418                Err(error) => match retry.handle_failure(error) {
1419                    RetryDecision::Retry => {}
1420                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1421                    RetryDecision::Return(error) => return Err(error),
1422                },
1423            }
1424        }
1425    }
1426
1427    /// Observes one exact durable export checkpoint with a fresh request identity.
1428    pub async fn get_application_export_operation(
1429        &mut self,
1430        operation_id: ApplicationExportOperationId,
1431        metadata: &CallMetadata,
1432    ) -> Result<v1::GetApplicationExportResponse, ClientError> {
1433        let request_id = SystemIdSource::new()
1434            .next_request_id()
1435            .map_err(ClientError::IdentifierGeneration)?;
1436        self.get_application_export(
1437            v1::GetApplicationExportRequest {
1438                request_id: request_id.into_bytes().to_vec(),
1439                operation_id: operation_id.into_bytes().to_vec(),
1440            },
1441            metadata,
1442        )
1443        .await
1444    }
1445
1446    /// Cancels or exactly observes one terminal export with bounded retry.
1447    pub async fn cancel_application_export_with_retry(
1448        &mut self,
1449        operation_id: ApplicationExportOperationId,
1450        attempt_budget: AttemptBudget,
1451        metadata: &CallMetadata,
1452    ) -> Result<v1::CancelApplicationExportResponse, ClientError> {
1453        let mut request_ids = SystemIdSource::new();
1454        let mut retry = RetryState::new(attempt_budget);
1455        loop {
1456            if !retry.begin_submission() {
1457                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1458            }
1459            let request_id = request_ids
1460                .next_request_id()
1461                .map_err(|error| retry.request_id_failure(error))?;
1462            retry.note_request_id(&request_id);
1463            let request = v1::CancelApplicationExportRequest {
1464                request_id: request_id.into_bytes().to_vec(),
1465                operation_id: operation_id.into_bytes().to_vec(),
1466            };
1467            match self.cancel_application_export(request, metadata).await {
1468                Ok(response) => return Ok(response),
1469                Err(error) => match retry.handle_failure(error) {
1470                    RetryDecision::Retry => {}
1471                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1472                    RetryDecision::Return(error) => return Err(error),
1473                },
1474            }
1475        }
1476    }
1477
1478    /// Starts or exactly replays one immutable application reimport campaign.
1479    pub async fn start_application_reimport_with_retry(
1480        &mut self,
1481        start: &StartApplicationReimport,
1482        attempt_budget: AttemptBudget,
1483        metadata: &CallMetadata,
1484    ) -> Result<v1::StartApplicationReimportResponse, ClientError> {
1485        let mut request_ids = SystemIdSource::new();
1486        let mut retry = RetryState::new(attempt_budget);
1487        loop {
1488            if !retry.begin_submission() {
1489                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1490            }
1491            let request_id = request_ids
1492                .next_request_id()
1493                .map_err(|error| retry.request_id_failure(error))?;
1494            retry.note_request_id(&request_id);
1495            match self
1496                .start_application_reimport(start.request(request_id), metadata)
1497                .await
1498            {
1499                Ok(response) => return Ok(response),
1500                Err(error) => match retry.handle_failure(error) {
1501                    RetryDecision::Retry => {}
1502                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1503                    RetryDecision::Return(error) => return Err(error),
1504                },
1505            }
1506        }
1507    }
1508
1509    /// Applies or exactly replays one hash-bearing export page.
1510    pub async fn apply_application_reimport_page_with_retry(
1511        &mut self,
1512        campaign_id: ApplicationInstallationCampaignId,
1513        page: &v1::ApplicationExportPage,
1514        attempt_budget: AttemptBudget,
1515        metadata: &CallMetadata,
1516    ) -> Result<v1::ApplyApplicationReimportPageResponse, ClientError> {
1517        let mut request_ids = SystemIdSource::new();
1518        let mut retry = RetryState::new(attempt_budget);
1519        loop {
1520            if !retry.begin_submission() {
1521                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1522            }
1523            let request_id = request_ids
1524                .next_request_id()
1525                .map_err(|error| retry.request_id_failure(error))?;
1526            retry.note_request_id(&request_id);
1527            let request = v1::ApplyApplicationReimportPageRequest {
1528                request_id: request_id.into_bytes().to_vec(),
1529                campaign_id: campaign_id.into_bytes().to_vec(),
1530                page: Some(page.clone()),
1531            };
1532            match self
1533                .apply_application_reimport_page(request, metadata)
1534                .await
1535            {
1536                Ok(response) => return Ok(response),
1537                Err(error) => match retry.handle_failure(error) {
1538                    RetryDecision::Retry => {}
1539                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1540                    RetryDecision::Return(error) => return Err(error),
1541                },
1542            }
1543        }
1544    }
1545
1546    /// Observes one exact durable reimport checkpoint with a fresh request identity.
1547    pub async fn get_application_reimport_operation(
1548        &mut self,
1549        campaign_id: ApplicationInstallationCampaignId,
1550        metadata: &CallMetadata,
1551    ) -> Result<v1::GetApplicationReimportResponse, ClientError> {
1552        let request_id = SystemIdSource::new()
1553            .next_request_id()
1554            .map_err(ClientError::IdentifierGeneration)?;
1555        self.get_application_reimport(
1556            v1::GetApplicationReimportRequest {
1557                request_id: request_id.into_bytes().to_vec(),
1558                campaign_id: campaign_id.into_bytes().to_vec(),
1559            },
1560            metadata,
1561        )
1562        .await
1563    }
1564
1565    /// Cancels or exactly observes one terminal reimport campaign.
1566    pub async fn cancel_application_reimport_with_retry(
1567        &mut self,
1568        campaign_id: ApplicationInstallationCampaignId,
1569        attempt_budget: AttemptBudget,
1570        metadata: &CallMetadata,
1571    ) -> Result<v1::CancelApplicationReimportResponse, ClientError> {
1572        let mut request_ids = SystemIdSource::new();
1573        let mut retry = RetryState::new(attempt_budget);
1574        loop {
1575            if !retry.begin_submission() {
1576                return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1577            }
1578            let request_id = request_ids
1579                .next_request_id()
1580                .map_err(|error| retry.request_id_failure(error))?;
1581            retry.note_request_id(&request_id);
1582            let request = v1::CancelApplicationReimportRequest {
1583                request_id: request_id.into_bytes().to_vec(),
1584                campaign_id: campaign_id.into_bytes().to_vec(),
1585            };
1586            match self.cancel_application_reimport(request, metadata).await {
1587                Ok(response) => return Ok(response),
1588                Err(error) => match retry.handle_failure(error) {
1589                    RetryDecision::Retry => {}
1590                    RetryDecision::RetryAfter(delay) => apply_overloaded_backoff(delay).await,
1591                    RetryDecision::Return(error) => return Err(error),
1592                },
1593            }
1594        }
1595    }
1596
1597    /// Builds, submits, and decodes one generated command shape.
1598    pub async fn execute_generated<C: GeneratedCommand>(
1599        &mut self,
1600        command: &C,
1601        attempt_budget: AttemptBudget,
1602        metadata: &CallMetadata,
1603    ) -> Result<GeneratedExecution<C::Outcome>, GeneratedExecutionError> {
1604        let generic = command
1605            .idempotent_command()
1606            .map_err(GeneratedExecutionError::CommandShape)?;
1607        let command_name = generic.command_name().to_owned();
1608        let response = self
1609            .execute_with_retry(&generic, attempt_budget, metadata)
1610            .await
1611            .map_err(|error| contextualize_command_client_error(error, &command_name))
1612            .map_err(GeneratedExecutionError::Client)?;
1613        let outcome = command
1614            .decode_outcome(&response)
1615            .map_err(GeneratedExecutionError::CommandShape)?;
1616        Ok(GeneratedExecution { response, outcome })
1617    }
1618
1619    /// Executes a generated command and performs one exact same-key outcome
1620    /// lookup when the bounded submission loop ends in uncertainty.
1621    pub async fn execute_generated_with_recovery<C: GeneratedCommand>(
1622        &mut self,
1623        command: &C,
1624        attempt_budget: AttemptBudget,
1625        metadata: &CallMetadata,
1626    ) -> Result<GeneratedExecution<C::Outcome>, GeneratedExecutionError> {
1627        let generic = command
1628            .idempotent_command()
1629            .map_err(GeneratedExecutionError::CommandShape)?;
1630        let command_name = generic.command_name().to_owned();
1631        let response = match self
1632            .execute_with_retry(&generic, attempt_budget, metadata)
1633            .await
1634        {
1635            Ok(response) => response,
1636            Err(ClientError::OutcomeUnknown(_)) => {
1637                let request_id = crate::generate_request_id().map_err(|_| {
1638                    GeneratedExecutionError::Client(ClientError::OutcomeUnknown(
1639                        crate::OutcomeUnknown,
1640                    ))
1641                })?;
1642                let request = command
1643                    .outcome_request(request_id)
1644                    .map_err(GeneratedExecutionError::CommandShape)?;
1645                let resolved = self.get_outcome(request, metadata).await.map_err(|_| {
1646                    GeneratedExecutionError::Client(ClientError::OutcomeUnknown(
1647                        crate::OutcomeUnknown,
1648                    ))
1649                })?;
1650                match resolved.result {
1651                    Some(v1::get_outcome_response::Result::Found(response)) => response,
1652                    Some(v1::get_outcome_response::Result::NotFound(_)) | None => {
1653                        return Err(GeneratedExecutionError::Client(
1654                            ClientError::OutcomeUnknown(crate::OutcomeUnknown),
1655                        ));
1656                    }
1657                }
1658            }
1659            Err(error) => {
1660                return Err(GeneratedExecutionError::Client(
1661                    contextualize_command_client_error(error, &command_name),
1662                ));
1663            }
1664        };
1665        let outcome = command
1666            .decode_outcome(&response)
1667            .map_err(GeneratedExecutionError::CommandShape)?;
1668        Ok(GeneratedExecution { response, outcome })
1669    }
1670}
1671
1672impl ExecuteRetryAttempt for RiffDbClient {
1673    async fn submit_execute_attempt(
1674        &mut self,
1675        request: v1::ExecuteCommandRequest,
1676        metadata: &CallMetadata,
1677    ) -> Result<v1::ExecuteCommandResponse, ClientError> {
1678        if let Some(session) = self.bounded_application_session.as_ref() {
1679            if !session.matches_metadata(metadata) {
1680                return Err(invalid_outbound());
1681            }
1682            return session.execute_command(request).await;
1683        }
1684        self.execute(request, metadata).await
1685    }
1686}
1687
1688impl NormalCapabilityRetryAttempt for RiffDbClient {
1689    async fn submit_normal_capability_attempt(
1690        &mut self,
1691        request: v1::CreateCapabilityRequest,
1692        metadata: &CallMetadata,
1693    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
1694        self.create_capability(request, metadata).await
1695    }
1696}
1697
1698impl BootstrapCapabilityRetryAttempt for RiffDbClient {
1699    async fn submit_bootstrap_capability_attempt(
1700        &mut self,
1701        request: v1::CreateCapabilityRequest,
1702        metadata: &BootstrapCallMetadata,
1703    ) -> Result<v1::CreateCapabilityResponse, ClientError> {
1704        self.create_bootstrap_capability(request, metadata).await
1705    }
1706}
1707
1708pub(crate) async fn execute_retry_attempts<T: ExecuteRetryAttempt, S: RetryRequestIdSource>(
1709    attempts: &mut T,
1710    command: &IdempotentCommand,
1711    attempt_budget: AttemptBudget,
1712    metadata: &CallMetadata,
1713    request_ids: &mut S,
1714) -> Result<v1::ExecuteCommandResponse, ClientError> {
1715    let mut retry = RetryState::new(attempt_budget);
1716    loop {
1717        let Some(request) = next_retry_request(command, &mut retry, request_ids)? else {
1718            return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1719        };
1720        match attempts.submit_execute_attempt(request, metadata).await {
1721            Ok(response) => return Ok(response),
1722            Err(error) => match retry.handle_failure(error) {
1723                RetryDecision::Retry => {}
1724                RetryDecision::RetryAfter(delay) => {
1725                    apply_overloaded_backoff(delay).await;
1726                }
1727                RetryDecision::Return(error) => return Err(error),
1728            },
1729        }
1730    }
1731}
1732
1733async fn normal_capability_retry_attempts<
1734    T: NormalCapabilityRetryAttempt,
1735    S: RetryRequestIdSource,
1736>(
1737    attempts: &mut T,
1738    create: &NormalCapabilityCreateTemplate,
1739    attempt_budget: AttemptBudget,
1740    metadata: &CallMetadata,
1741    request_ids: &mut S,
1742) -> Result<v1::CreateCapabilityResponse, ClientError> {
1743    let mut retry = RetryState::new(attempt_budget);
1744    loop {
1745        let Some(request) = next_normal_create_request(create, &mut retry, request_ids)? else {
1746            return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1747        };
1748        match attempts
1749            .submit_normal_capability_attempt(request, metadata)
1750            .await
1751        {
1752            Ok(response) => return Ok(response),
1753            Err(error) => match retry.handle_failure(error) {
1754                RetryDecision::Retry => {}
1755                RetryDecision::RetryAfter(delay) => {
1756                    apply_overloaded_backoff(delay).await;
1757                }
1758                RetryDecision::Return(error) => return Err(error),
1759            },
1760        }
1761    }
1762}
1763
1764async fn bootstrap_capability_retry_attempts<
1765    T: BootstrapCapabilityRetryAttempt,
1766    S: RetryRequestIdSource,
1767>(
1768    attempts: &mut T,
1769    create: &BootstrapCapabilityCreateTemplate,
1770    attempt_budget: AttemptBudget,
1771    metadata: &BootstrapCallMetadata,
1772    request_ids: &mut S,
1773) -> Result<v1::CreateCapabilityResponse, ClientError> {
1774    let mut retry = RetryState::new(attempt_budget);
1775    loop {
1776        let Some(request) = next_bootstrap_create_request(create, &mut retry, request_ids)? else {
1777            return Err(ClientError::OutcomeUnknown(crate::OutcomeUnknown));
1778        };
1779        match attempts
1780            .submit_bootstrap_capability_attempt(request, metadata)
1781            .await
1782        {
1783            Ok(response) => return Ok(response),
1784            Err(error) => match retry.handle_failure(error) {
1785                RetryDecision::Retry => {}
1786                RetryDecision::RetryAfter(delay) => {
1787                    apply_overloaded_backoff(delay).await;
1788                }
1789                RetryDecision::Return(error) => return Err(error),
1790            },
1791        }
1792    }
1793}
1794
1795fn next_retry_request<S: RetryRequestIdSource>(
1796    command: &IdempotentCommand,
1797    retry: &mut RetryState,
1798    request_ids: &mut S,
1799) -> Result<Option<v1::ExecuteCommandRequest>, ClientError> {
1800    if !retry.begin_submission() {
1801        return Ok(None);
1802    }
1803    request_ids
1804        .next_request_id()
1805        .map(|request_id| {
1806            retry.note_request_id(&request_id);
1807            Some(command.request(request_id))
1808        })
1809        .map_err(|error| retry.request_id_failure(error))
1810}
1811
1812fn next_normal_create_request<S: RetryRequestIdSource>(
1813    create: &NormalCapabilityCreateTemplate,
1814    retry: &mut RetryState,
1815    request_ids: &mut S,
1816) -> Result<Option<v1::CreateCapabilityRequest>, ClientError> {
1817    if !retry.begin_submission() {
1818        return Ok(None);
1819    }
1820    request_ids
1821        .next_request_id()
1822        .map(|request_id| {
1823            retry.note_request_id(&request_id);
1824            Some(create.request(request_id))
1825        })
1826        .map_err(|error| retry.request_id_failure(error))
1827}
1828
1829fn next_bootstrap_create_request<S: RetryRequestIdSource>(
1830    create: &BootstrapCapabilityCreateTemplate,
1831    retry: &mut RetryState,
1832    request_ids: &mut S,
1833) -> Result<Option<v1::CreateCapabilityRequest>, ClientError> {
1834    if !retry.begin_submission() {
1835        return Ok(None);
1836    }
1837    request_ids
1838        .next_request_id()
1839        .map(|request_id| {
1840            retry.note_request_id(&request_id);
1841            Some(create.request(request_id))
1842        })
1843        .map_err(|error| retry.request_id_failure(error))
1844}
1845
1846/// A commit-notification stream decoded by the strict client codec.
1847pub struct CommitNotificationStream {
1848    inner: Streaming<v1::CommitNotification>,
1849}
1850
1851/// A durable event-consumer stream decoded by the strict client codec.
1852pub struct EventConsumerResponseStream {
1853    inner: Streaming<v1::ConsumeEventStreamResponse>,
1854}
1855
1856/// A live named-query stream decoded by the strict client codec.
1857pub struct LiveQueryUpdateStream {
1858    inner: Streaming<v1::LiveQueryUpdate>,
1859}
1860
1861impl LiveQueryUpdateStream {
1862    /// Receives the next closed live update (structure enforced at decode).
1863    pub async fn message(&mut self) -> Result<Option<v1::LiveQueryUpdate>, ClientError> {
1864        self.inner.message().await.map_err(checked_status)
1865    }
1866}
1867
1868impl EventConsumerResponseStream {
1869    /// Receives the next leased-event response (structure enforced at decode).
1870    pub async fn message(&mut self) -> Result<Option<v1::ConsumeEventStreamResponse>, ClientError> {
1871        self.inner.message().await.map_err(checked_status)
1872    }
1873}
1874
1875impl CommitNotificationStream {
1876    /// Receives the next commit notification (structure enforced at decode).
1877    pub async fn message(&mut self) -> Result<Option<v1::CommitNotification>, ClientError> {
1878        self.inner.message().await.map_err(checked_status)
1879    }
1880}
1881
1882/// A generated outcome together with its complete checked transport response.
1883pub struct GeneratedExecution<T> {
1884    response: v1::ExecuteCommandResponse,
1885    outcome: T,
1886}
1887
1888impl<T> GeneratedExecution<T> {
1889    /// Borrows the generated declared outcome.
1890    #[must_use]
1891    pub const fn outcome(&self) -> &T {
1892        &self.outcome
1893    }
1894
1895    /// Borrows commit, provenance, contract, and durability metadata.
1896    #[must_use]
1897    pub const fn response(&self) -> &v1::ExecuteCommandResponse {
1898        &self.response
1899    }
1900
1901    /// Splits the generated outcome from its checked transport response.
1902    #[must_use]
1903    pub fn into_parts(self) -> (T, v1::ExecuteCommandResponse) {
1904        (self.outcome, self.response)
1905    }
1906}
1907
1908/// A closed failure while executing one generated command shape.
1909#[derive(Debug)]
1910pub enum GeneratedExecutionError {
1911    /// The generic client or peer protocol failed.
1912    Client(ClientError),
1913    /// Generated input or output did not match its frozen contract shape.
1914    CommandShape(GeneratedCommandError),
1915}
1916
1917impl fmt::Display for GeneratedExecutionError {
1918    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1919        match self {
1920            Self::Client(error) => error.fmt(formatter),
1921            Self::CommandShape(error) => error.fmt(formatter),
1922        }
1923    }
1924}
1925
1926impl Error for GeneratedExecutionError {}
1927
1928/// Client-side outbound structural validation (walk 1 of 5 per unary trip).
1929///
1930/// Load-bearing classification, not repeated representation: invalid
1931/// client-built messages become certain, non-retryable
1932/// [`ProtocolFailureKind::InvalidOutboundMessage`]. The encoder (walk 2) still
1933/// validates before wire write, but encoder failures surface through Tonic as
1934/// details-free transport errors and can be misclassified as retryable
1935/// uncertainty. Inbound has no client re-walk after decode (codec owns that).
1936fn validate_outbound<M: PublicMessage>(message: &M) -> Result<(), ClientError> {
1937    validate_public_message(message).map_err(|_| {
1938        ClientError::Protocol(ProtocolFailure::new(
1939            ProtocolFailureKind::InvalidOutboundMessage,
1940        ))
1941    })
1942}
1943
1944fn configure_projection_wait(
1945    message: &mut v1::QueryProjectionRequest,
1946    required_sequence: CommitSequence,
1947    maximum_wait: Duration,
1948) -> Result<(), ClientError> {
1949    message.required_sequence = Some(required_sequence.get());
1950    message.wait_nanos = u64::try_from(maximum_wait.as_nanos()).map_err(|_| invalid_outbound())?;
1951    validate_outbound(message)
1952}
1953
1954const fn invalid_inbound() -> ClientError {
1955    ClientError::Protocol(ProtocolFailure::new(
1956        ProtocolFailureKind::InvalidInboundMessage,
1957    ))
1958}
1959
1960const fn invalid_outbound() -> ClientError {
1961    ClientError::Protocol(ProtocolFailure::new(
1962        ProtocolFailureKind::InvalidOutboundMessage,
1963    ))
1964}
1965
1966#[cfg(test)]
1967mod tests {
1968    use std::collections::VecDeque;
1969    use std::future::Future;
1970    use std::sync::Arc;
1971    use std::sync::atomic::{AtomicUsize, Ordering};
1972    use std::task::{Context, Poll, Waker};
1973
1974    use super::*;
1975    use crate::BootstrapCredential;
1976    use crate::status::DetailsFreeStatus;
1977    use riffdb_errors::{PublicError, PublicErrorKind};
1978    use tonic_prost::prost::Message;
1979
1980    const BOOTSTRAP_TOKEN: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
1981
1982    struct FixedRequestIds {
1983        values: VecDeque<RequestId>,
1984    }
1985
1986    impl RetryRequestIdSource for FixedRequestIds {
1987        fn next_request_id(&mut self) -> Result<RequestId, crate::IdentifierGenerationError> {
1988            self.values
1989                .pop_front()
1990                .ok_or(crate::IdentifierGenerationError::EntropyUnavailable)
1991        }
1992    }
1993
1994    struct ScriptedRequestIds {
1995        results: VecDeque<Result<RequestId, crate::IdentifierGenerationError>>,
1996        calls: usize,
1997    }
1998
1999    impl RetryRequestIdSource for ScriptedRequestIds {
2000        fn next_request_id(&mut self) -> Result<RequestId, crate::IdentifierGenerationError> {
2001            self.calls += 1;
2002            self.results
2003                .pop_front()
2004                .unwrap_or(Err(crate::IdentifierGenerationError::EntropyUnavailable))
2005        }
2006    }
2007
2008    struct ExecuteAttempts {
2009        results: VecDeque<Result<v1::ExecuteCommandResponse, ClientError>>,
2010        requests: Vec<v1::ExecuteCommandRequest>,
2011        pending_once: bool,
2012    }
2013
2014    impl ExecuteAttempts {
2015        fn new(
2016            results: impl IntoIterator<Item = Result<v1::ExecuteCommandResponse, ClientError>>,
2017        ) -> Self {
2018            Self {
2019                results: results.into_iter().collect(),
2020                requests: Vec::new(),
2021                pending_once: false,
2022            }
2023        }
2024
2025        fn with_pending_once(mut self) -> Self {
2026            self.pending_once = true;
2027            self
2028        }
2029    }
2030
2031    impl ExecuteRetryAttempt for ExecuteAttempts {
2032        async fn submit_execute_attempt(
2033            &mut self,
2034            request: v1::ExecuteCommandRequest,
2035            _metadata: &CallMetadata,
2036        ) -> Result<v1::ExecuteCommandResponse, ClientError> {
2037            self.requests.push(request);
2038            if self.pending_once {
2039                let mut first_poll = true;
2040                std::future::poll_fn(|context| {
2041                    if std::mem::take(&mut first_poll) {
2042                        context.waker().wake_by_ref();
2043                        Poll::Pending
2044                    } else {
2045                        Poll::Ready(())
2046                    }
2047                })
2048                .await;
2049                self.pending_once = false;
2050            }
2051            self.results.pop_front().expect("scripted execute result")
2052        }
2053    }
2054
2055    struct NormalCapabilityAttempts {
2056        results: VecDeque<Result<v1::CreateCapabilityResponse, ClientError>>,
2057        requests: Vec<v1::CreateCapabilityRequest>,
2058    }
2059
2060    impl NormalCapabilityAttempts {
2061        fn new(
2062            results: impl IntoIterator<Item = Result<v1::CreateCapabilityResponse, ClientError>>,
2063        ) -> Self {
2064            Self {
2065                results: results.into_iter().collect(),
2066                requests: Vec::new(),
2067            }
2068        }
2069    }
2070
2071    impl NormalCapabilityRetryAttempt for NormalCapabilityAttempts {
2072        async fn submit_normal_capability_attempt(
2073            &mut self,
2074            request: v1::CreateCapabilityRequest,
2075            _metadata: &CallMetadata,
2076        ) -> Result<v1::CreateCapabilityResponse, ClientError> {
2077            self.requests.push(request);
2078            self.results
2079                .pop_front()
2080                .expect("scripted normal-create result")
2081        }
2082    }
2083
2084    struct BootstrapCapabilityAttempts {
2085        results: VecDeque<Result<v1::CreateCapabilityResponse, ClientError>>,
2086        requests: Vec<v1::CreateCapabilityRequest>,
2087        credential_presentations: Vec<Vec<u8>>,
2088    }
2089
2090    impl BootstrapCapabilityAttempts {
2091        fn new(
2092            results: impl IntoIterator<Item = Result<v1::CreateCapabilityResponse, ClientError>>,
2093        ) -> Self {
2094            Self {
2095                results: results.into_iter().collect(),
2096                requests: Vec::new(),
2097                credential_presentations: Vec::new(),
2098            }
2099        }
2100    }
2101
2102    impl BootstrapCapabilityRetryAttempt for BootstrapCapabilityAttempts {
2103        async fn submit_bootstrap_capability_attempt(
2104            &mut self,
2105            request: v1::CreateCapabilityRequest,
2106            metadata: &BootstrapCallMetadata,
2107        ) -> Result<v1::CreateCapabilityResponse, ClientError> {
2108            let mut transport_request = Request::new(());
2109            metadata.apply(&mut transport_request);
2110            let presentation = transport_request
2111                .metadata()
2112                .get_bin("riffdb-bootstrap-token-bin")
2113                .expect("bootstrap credential metadata")
2114                .to_bytes()
2115                .expect("valid binary metadata")
2116                .to_vec();
2117            self.credential_presentations.push(presentation);
2118            self.requests.push(request);
2119            self.results
2120                .pop_front()
2121                .expect("scripted bootstrap-create result")
2122        }
2123    }
2124
2125    fn block_on_ready<T>(future: impl Future<Output = T>) -> T {
2126        let waker = Waker::noop();
2127        let mut context = Context::from_waker(waker);
2128        let mut future = std::pin::pin!(future);
2129        match future.as_mut().poll(&mut context) {
2130            Poll::Ready(output) => output,
2131            Poll::Pending => panic!("deterministic retry schedule unexpectedly yielded"),
2132        }
2133    }
2134
2135    #[derive(Default)]
2136    struct WakeCounter {
2137        wakes: AtomicUsize,
2138    }
2139
2140    impl std::task::Wake for WakeCounter {
2141        fn wake(self: Arc<Self>) {
2142            self.wakes.fetch_add(1, Ordering::SeqCst);
2143        }
2144
2145        fn wake_by_ref(self: &Arc<Self>) {
2146            self.wakes.fetch_add(1, Ordering::SeqCst);
2147        }
2148    }
2149
2150    fn block_on_deterministic_wakes<T>(future: impl Future<Output = T>) -> (T, usize) {
2151        let wake_counter = Arc::new(WakeCounter::default());
2152        let waker = Waker::from(Arc::clone(&wake_counter));
2153        let mut context = Context::from_waker(&waker);
2154        let mut future = std::pin::pin!(future);
2155        let mut pending_polls = 0;
2156        loop {
2157            match future.as_mut().poll(&mut context) {
2158                Poll::Ready(output) => return (output, pending_polls),
2159                Poll::Pending => {
2160                    pending_polls += 1;
2161                    assert!(
2162                        pending_polls <= 1,
2163                        "deterministic schedule exceeded its one pending poll"
2164                    );
2165                    assert_eq!(
2166                        wake_counter.wakes.swap(0, Ordering::SeqCst),
2167                        1,
2168                        "each deterministic pending poll must arrange exactly one wake"
2169                    );
2170                }
2171            }
2172        }
2173    }
2174
2175    fn scripted_ids(
2176        results: impl IntoIterator<Item = Result<RequestId, crate::IdentifierGenerationError>>,
2177    ) -> ScriptedRequestIds {
2178        ScriptedRequestIds {
2179            results: results.into_iter().collect(),
2180            calls: 0,
2181        }
2182    }
2183
2184    fn request_id(ordinal: u8) -> RequestId {
2185        RequestId::from_unix_milliseconds_and_random(u64::from(ordinal), [ordinal; 10])
2186            .expect("request ID")
2187    }
2188
2189    fn successful_execute_response() -> v1::ExecuteCommandResponse {
2190        v1::ExecuteCommandResponse {
2191            status: v1::execute_command_response::CompletionStatus::ExecutedReadOnly as i32,
2192            commit_sequence: 0,
2193            contract_version: 1,
2194            plan_hash: vec![7; 32],
2195            outcome_type: "Observed".to_owned(),
2196            outcome: Some(v1::Value {
2197                kind: Some(v1::value::Kind::RecordValue(v1::ValueRecord {
2198                    fields: Vec::new(),
2199                })),
2200            }),
2201            provenance_uri: String::new(),
2202            durability_mode: String::new(),
2203            outcome_uri: None,
2204            history_incarnation: 1,
2205        }
2206    }
2207
2208    fn normal_token_unavailable_response(capability_id: &[u8]) -> v1::CreateCapabilityResponse {
2209        v1::CreateCapabilityResponse {
2210            result: Some(v1::create_capability_response::Result::Normal(
2211                v1::NormalCreateCapabilityResult {
2212                    result: Some(
2213                        v1::normal_create_capability_result::Result::AlreadyCreatedTokenUnavailable(
2214                            v1::CapabilityIdentity {
2215                                capability_id: capability_id.to_vec(),
2216                                revision: 1,
2217                            },
2218                        ),
2219                    ),
2220                },
2221            )),
2222        }
2223    }
2224
2225    fn bootstrap_replayed_response(capability_id: &[u8]) -> v1::CreateCapabilityResponse {
2226        v1::CreateCapabilityResponse {
2227            result: Some(v1::create_capability_response::Result::Bootstrap(
2228                v1::BootstrapCreateCapabilityResult {
2229                    result: Some(v1::bootstrap_create_capability_result::Result::Replayed(
2230                        v1::CapabilityTransition {
2231                            identity: Some(v1::CapabilityIdentity {
2232                                capability_id: capability_id.to_vec(),
2233                                revision: 1,
2234                            }),
2235                            administration_sequence: 1,
2236                        },
2237                    )),
2238                },
2239            )),
2240        }
2241    }
2242
2243    fn transport_unavailable() -> ClientError {
2244        ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
2245    }
2246
2247    fn retryable_checked_error() -> ClientError {
2248        ClientError::Public(PublicError::concurrency_deadline_exceeded())
2249    }
2250
2251    fn public_outcome_unknown() -> ClientError {
2252        ClientError::Public(PublicError::outcome_unknown())
2253    }
2254
2255    fn terminal_checked_error() -> ClientError {
2256        ClientError::Public(PublicError::authorization_denied())
2257    }
2258
2259    fn assert_only_execute_request_id_changes(
2260        requests: &[v1::ExecuteCommandRequest],
2261        expected_ids: &[RequestId],
2262    ) {
2263        assert_eq!(requests.len(), expected_ids.len());
2264        let mut semantic_bodies = Vec::new();
2265        for (request, expected_id) in requests.iter().zip(expected_ids) {
2266            assert_eq!(request.request_id, expected_id.into_bytes());
2267            let mut semantic_body = request.clone();
2268            semantic_body.request_id.clear();
2269            semantic_bodies.push(semantic_body.encode_to_vec());
2270        }
2271        assert!(semantic_bodies.windows(2).all(|pair| pair[0] == pair[1]));
2272    }
2273
2274    fn assert_only_create_request_id_changes(
2275        requests: &[v1::CreateCapabilityRequest],
2276        expected_ids: &[RequestId],
2277    ) {
2278        assert_eq!(requests.len(), expected_ids.len());
2279        let mut semantic_bodies = Vec::new();
2280        for (request, expected_id) in requests.iter().zip(expected_ids) {
2281            assert_eq!(request.request_id, expected_id.into_bytes());
2282            let mut semantic_body = request.clone();
2283            semantic_body.request_id.clear();
2284            semantic_bodies.push(semantic_body.encode_to_vec());
2285        }
2286        assert!(semantic_bodies.windows(2).all(|pair| pair[0] == pair[1]));
2287    }
2288
2289    fn assert_authorization_denied<T>(result: Result<T, ClientError>) {
2290        assert!(matches!(
2291            result,
2292            Err(ClientError::Public(error))
2293                if error.kind() == PublicErrorKind::AuthorizationDenied
2294        ));
2295    }
2296
2297    fn assert_concurrency_deadline<T>(result: Result<T, ClientError>) {
2298        assert!(matches!(
2299            result,
2300            Err(ClientError::Public(error))
2301                if error.kind() == PublicErrorKind::ConcurrencyDeadlineExceeded
2302        ));
2303    }
2304
2305    fn assert_outcome_unknown<T>(result: Result<T, ClientError>) {
2306        assert!(matches!(result, Err(ClientError::OutcomeUnknown(_))));
2307    }
2308
2309    fn retry_input() -> v1::Value {
2310        v1::Value {
2311            kind: Some(v1::value::Kind::RecordValue(v1::ValueRecord {
2312                fields: vec![v1::ValueField {
2313                    field_id: Some(1),
2314                    name: String::new(),
2315                    value: Some(v1::Value {
2316                        kind: Some(v1::value::Kind::StringValue("same-key".to_owned())),
2317                    }),
2318                }],
2319            })),
2320        }
2321    }
2322
2323    fn create_template_request(mode: v1::CapabilityCreateMode) -> v1::CreateCapabilityRequest {
2324        let permissions = if mode == v1::CapabilityCreateMode::Bootstrap {
2325            vec![v1::CapabilityPermission {
2326                permission: Some(
2327                    v1::capability_permission::Permission::AdministerCapabilities(v1::Unit {}),
2328                ),
2329            }]
2330        } else {
2331            Vec::new()
2332        };
2333        v1::CreateCapabilityRequest {
2334            request_id: Vec::new(),
2335            mode: mode as i32,
2336            capability_id: RequestId::from_unix_milliseconds_and_random(1, [4; 10])
2337                .expect("capability ID")
2338                .into_bytes()
2339                .to_vec(),
2340            principal_id: "operator".to_owned(),
2341            actor_kind: v1::ActorKind::Human as i32,
2342            requested_lifetime_seconds: 60,
2343            audiences: vec!["riffdb-cli".to_owned()],
2344            grant: Some(v1::CapabilityGrant {
2345                tenant_scope: Some(v1::TenantScope {
2346                    scope: Some(v1::tenant_scope::Scope::Global(v1::Unit {})),
2347                }),
2348                partition_scope: Some(v1::PartitionScope {
2349                    scope: Some(v1::partition_scope::Scope::All(v1::Unit {})),
2350                }),
2351                permissions,
2352                field_visibility: Vec::new(),
2353                max_scan_rows: 1,
2354                approval_required: Vec::new(),
2355                row_policy: None,
2356                export: None,
2357                reimport: None,
2358                vector_inspection: None,
2359            }),
2360        }
2361    }
2362
2363    #[test]
2364    fn execute_helper_retries_checked_failure_with_fresh_id_and_stable_body() {
2365        let first_id = request_id(1);
2366        let second_id = request_id(2);
2367        let mut request_ids = scripted_ids([Ok(first_id), Ok(second_id)]);
2368        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2369            .expect("immutable command");
2370        let expected = successful_execute_response();
2371        let mut attempts =
2372            ExecuteAttempts::new([Err(retryable_checked_error()), Ok(expected.clone())]);
2373
2374        let result = block_on_ready(execute_retry_attempts(
2375            &mut attempts,
2376            &command,
2377            AttemptBudget::new(2).expect("budget"),
2378            &CallMetadata::default(),
2379            &mut request_ids,
2380        ));
2381
2382        assert_eq!(result.expect("second attempt succeeds"), expected);
2383        assert_eq!(request_ids.calls, 2);
2384        assert_only_execute_request_id_changes(&attempts.requests, &[first_id, second_id]);
2385        validate_public_message(&attempts.requests[0]).expect("first checked request");
2386        validate_public_message(&attempts.requests[1]).expect("second checked request");
2387    }
2388
2389    #[test]
2390    fn bootstrap_helper_retains_identity_body_and_token_across_retry() {
2391        let first_id = request_id(3);
2392        let second_id = request_id(4);
2393        let mut request_ids = scripted_ids([Ok(first_id), Ok(second_id)]);
2394        let template_request = create_template_request(v1::CapabilityCreateMode::Bootstrap);
2395        let capability_id = template_request.capability_id.clone();
2396        let create =
2397            BootstrapCapabilityCreateTemplate::new(template_request).expect("bootstrap template");
2398        let expected = bootstrap_replayed_response(&capability_id);
2399        let mut attempts = BootstrapCapabilityAttempts::new([
2400            Err(retryable_checked_error()),
2401            Ok(expected.clone()),
2402        ]);
2403        let metadata = BootstrapCallMetadata::new(
2404            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2405        );
2406
2407        let result = block_on_ready(bootstrap_capability_retry_attempts(
2408            &mut attempts,
2409            &create,
2410            AttemptBudget::new(2).expect("budget"),
2411            &metadata,
2412            &mut request_ids,
2413        ));
2414
2415        assert_eq!(result.expect("replayed bootstrap result"), expected);
2416        assert_eq!(request_ids.calls, 2);
2417        assert_only_create_request_id_changes(&attempts.requests, &[first_id, second_id]);
2418        assert!(
2419            attempts
2420                .requests
2421                .iter()
2422                .all(|request| request.capability_id == capability_id)
2423        );
2424        assert_eq!(
2425            attempts.credential_presentations,
2426            vec![BOOTSTRAP_TOKEN.as_bytes().to_vec(); 2]
2427        );
2428        validate_create_capability_exchange(&attempts.requests[1], &expected)
2429            .expect("checked bootstrap exchange");
2430    }
2431
2432    #[test]
2433    fn normal_helper_returns_token_unavailable_after_uncertainty_without_replacement() {
2434        let first_id = request_id(5);
2435        let second_id = request_id(6);
2436        let unused_third_id = request_id(7);
2437        let mut request_ids = scripted_ids([Ok(first_id), Ok(second_id), Ok(unused_third_id)]);
2438        let template_request = create_template_request(v1::CapabilityCreateMode::Normal);
2439        let capability_id = template_request.capability_id.clone();
2440        let create =
2441            NormalCapabilityCreateTemplate::new(template_request).expect("normal template");
2442        let expected = normal_token_unavailable_response(&capability_id);
2443        let mut attempts =
2444            NormalCapabilityAttempts::new([Err(transport_unavailable()), Ok(expected.clone())]);
2445
2446        let result = block_on_ready(normal_capability_retry_attempts(
2447            &mut attempts,
2448            &create,
2449            AttemptBudget::new(3).expect("budget"),
2450            &CallMetadata::default(),
2451            &mut request_ids,
2452        ));
2453
2454        assert_eq!(
2455            result.expect("terminal token-unavailable response"),
2456            expected
2457        );
2458        assert_eq!(request_ids.calls, 2);
2459        assert_eq!(request_ids.results.len(), 1);
2460        assert!(attempts.results.is_empty());
2461        assert_only_create_request_id_changes(&attempts.requests, &[first_id, second_id]);
2462        validate_create_capability_exchange(&attempts.requests[1], &expected)
2463            .expect("checked normal-create exchange");
2464        let Some(v1::create_capability_response::Result::Normal(normal)) = expected.result else {
2465            panic!("normal result family")
2466        };
2467        assert!(matches!(
2468            normal.result,
2469            Some(
2470                v1::normal_create_capability_result::Result::AlreadyCreatedTokenUnavailable(
2471                    v1::CapabilityIdentity {
2472                        capability_id: returned_id,
2473                        revision: 1,
2474                    }
2475                )
2476            ) if returned_id == capability_id
2477        ));
2478    }
2479
2480    #[test]
2481    fn every_helper_resolves_public_outcome_unknown_with_a_valid_terminal_result() {
2482        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2483            .expect("immutable command");
2484        let normal_request = create_template_request(v1::CapabilityCreateMode::Normal);
2485        let normal_capability_id = normal_request.capability_id.clone();
2486        let normal = NormalCapabilityCreateTemplate::new(normal_request).expect("normal template");
2487        let bootstrap_request = create_template_request(v1::CapabilityCreateMode::Bootstrap);
2488        let bootstrap_capability_id = bootstrap_request.capability_id.clone();
2489        let bootstrap =
2490            BootstrapCapabilityCreateTemplate::new(bootstrap_request).expect("bootstrap template");
2491        let bootstrap_metadata = BootstrapCallMetadata::new(
2492            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2493        );
2494        let budget = AttemptBudget::new(2).expect("budget");
2495
2496        let execute_request_ids = [request_id(35), request_id(36)];
2497        let mut execute_ids = scripted_ids(execute_request_ids.map(Ok));
2498        let execute_response = successful_execute_response();
2499        let mut execute =
2500            ExecuteAttempts::new([Err(public_outcome_unknown()), Ok(execute_response.clone())]);
2501        assert_eq!(
2502            block_on_ready(execute_retry_attempts(
2503                &mut execute,
2504                &command,
2505                budget,
2506                &CallMetadata::default(),
2507                &mut execute_ids,
2508            ))
2509            .expect("same-key command resolution"),
2510            execute_response
2511        );
2512        assert_eq!(execute_ids.calls, 2);
2513        assert_only_execute_request_id_changes(&execute.requests, &execute_request_ids);
2514
2515        let normal_request_ids = [request_id(37), request_id(38)];
2516        let mut normal_ids = scripted_ids(normal_request_ids.map(Ok));
2517        let normal_response = normal_token_unavailable_response(&normal_capability_id);
2518        let mut normal_attempts = NormalCapabilityAttempts::new([
2519            Err(public_outcome_unknown()),
2520            Ok(normal_response.clone()),
2521        ]);
2522        assert_eq!(
2523            block_on_ready(normal_capability_retry_attempts(
2524                &mut normal_attempts,
2525                &normal,
2526                budget,
2527                &CallMetadata::default(),
2528                &mut normal_ids,
2529            ))
2530            .expect("normal-create identity resolution"),
2531            normal_response
2532        );
2533        assert_eq!(normal_ids.calls, 2);
2534        assert_only_create_request_id_changes(&normal_attempts.requests, &normal_request_ids);
2535
2536        let bootstrap_request_ids = [request_id(39), request_id(40)];
2537        let mut bootstrap_ids = scripted_ids(bootstrap_request_ids.map(Ok));
2538        let bootstrap_response = bootstrap_replayed_response(&bootstrap_capability_id);
2539        let mut bootstrap_attempts = BootstrapCapabilityAttempts::new([
2540            Err(public_outcome_unknown()),
2541            Ok(bootstrap_response.clone()),
2542        ]);
2543        assert_eq!(
2544            block_on_ready(bootstrap_capability_retry_attempts(
2545                &mut bootstrap_attempts,
2546                &bootstrap,
2547                budget,
2548                &bootstrap_metadata,
2549                &mut bootstrap_ids,
2550            ))
2551            .expect("bootstrap identity resolution"),
2552            bootstrap_response
2553        );
2554        assert_eq!(bootstrap_ids.calls, 2);
2555        assert_only_create_request_id_changes(&bootstrap_attempts.requests, &bootstrap_request_ids);
2556        assert_eq!(
2557            bootstrap_attempts.credential_presentations,
2558            vec![BOOTSTRAP_TOKEN.as_bytes().to_vec(); 2]
2559        );
2560    }
2561
2562    #[test]
2563    fn execute_retry_state_survives_a_deterministic_pending_and_wake() {
2564        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2565            .expect("immutable command");
2566        let request_ids_expected = [request_id(41), request_id(42)];
2567        let mut request_ids = scripted_ids(request_ids_expected.map(Ok));
2568        let expected = successful_execute_response();
2569        let mut attempts =
2570            ExecuteAttempts::new([Err(public_outcome_unknown()), Ok(expected.clone())])
2571                .with_pending_once();
2572
2573        let (result, pending_polls) = block_on_deterministic_wakes(execute_retry_attempts(
2574            &mut attempts,
2575            &command,
2576            AttemptBudget::new(2).expect("budget"),
2577            &CallMetadata::default(),
2578            &mut request_ids,
2579        ));
2580
2581        assert_eq!(pending_polls, 1);
2582        assert_eq!(result.expect("retry after deterministic wake"), expected);
2583        assert_eq!(request_ids.calls, 2);
2584        assert_only_execute_request_id_changes(&attempts.requests, &request_ids_expected);
2585    }
2586
2587    #[test]
2588    fn every_helper_returns_terminal_checked_error_without_retry() {
2589        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2590            .expect("immutable command");
2591        let normal = NormalCapabilityCreateTemplate::new(create_template_request(
2592            v1::CapabilityCreateMode::Normal,
2593        ))
2594        .expect("normal template");
2595        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
2596            v1::CapabilityCreateMode::Bootstrap,
2597        ))
2598        .expect("bootstrap template");
2599        let bootstrap_metadata = BootstrapCallMetadata::new(
2600            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2601        );
2602        let budget = AttemptBudget::new(3).expect("budget");
2603
2604        let mut execute_ids = scripted_ids([Ok(request_id(8)), Ok(request_id(9))]);
2605        let mut execute = ExecuteAttempts::new([Err(terminal_checked_error())]);
2606        assert_authorization_denied(block_on_ready(execute_retry_attempts(
2607            &mut execute,
2608            &command,
2609            budget,
2610            &CallMetadata::default(),
2611            &mut execute_ids,
2612        )));
2613        assert_eq!((execute.requests.len(), execute_ids.calls), (1, 1));
2614
2615        let mut normal_ids = scripted_ids([Ok(request_id(10)), Ok(request_id(11))]);
2616        let mut normal_attempts = NormalCapabilityAttempts::new([Err(terminal_checked_error())]);
2617        assert_authorization_denied(block_on_ready(normal_capability_retry_attempts(
2618            &mut normal_attempts,
2619            &normal,
2620            budget,
2621            &CallMetadata::default(),
2622            &mut normal_ids,
2623        )));
2624        assert_eq!((normal_attempts.requests.len(), normal_ids.calls), (1, 1));
2625
2626        let mut bootstrap_ids = scripted_ids([Ok(request_id(12)), Ok(request_id(13))]);
2627        let mut bootstrap_attempts =
2628            BootstrapCapabilityAttempts::new([Err(terminal_checked_error())]);
2629        assert_authorization_denied(block_on_ready(bootstrap_capability_retry_attempts(
2630            &mut bootstrap_attempts,
2631            &bootstrap,
2632            budget,
2633            &bootstrap_metadata,
2634            &mut bootstrap_ids,
2635        )));
2636        assert_eq!(
2637            (bootstrap_attempts.requests.len(), bootstrap_ids.calls),
2638            (1, 1)
2639        );
2640    }
2641
2642    #[test]
2643    fn every_helper_keeps_uncertainty_when_a_later_error_is_terminal() {
2644        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2645            .expect("immutable command");
2646        let normal = NormalCapabilityCreateTemplate::new(create_template_request(
2647            v1::CapabilityCreateMode::Normal,
2648        ))
2649        .expect("normal template");
2650        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
2651            v1::CapabilityCreateMode::Bootstrap,
2652        ))
2653        .expect("bootstrap template");
2654        let bootstrap_metadata = BootstrapCallMetadata::new(
2655            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2656        );
2657        let budget = AttemptBudget::new(3).expect("budget");
2658
2659        let execute_request_ids = [request_id(29), request_id(30)];
2660        let mut execute_ids = scripted_ids(execute_request_ids.map(Ok));
2661        let mut execute =
2662            ExecuteAttempts::new([Err(public_outcome_unknown()), Err(terminal_checked_error())]);
2663        assert_outcome_unknown(block_on_ready(execute_retry_attempts(
2664            &mut execute,
2665            &command,
2666            budget,
2667            &CallMetadata::default(),
2668            &mut execute_ids,
2669        )));
2670        assert_eq!((execute.requests.len(), execute_ids.calls), (2, 2));
2671        assert_only_execute_request_id_changes(&execute.requests, &execute_request_ids);
2672
2673        let normal_request_ids = [request_id(31), request_id(32)];
2674        let mut normal_ids = scripted_ids(normal_request_ids.map(Ok));
2675        let mut normal_attempts = NormalCapabilityAttempts::new([
2676            Err(public_outcome_unknown()),
2677            Err(terminal_checked_error()),
2678        ]);
2679        assert_outcome_unknown(block_on_ready(normal_capability_retry_attempts(
2680            &mut normal_attempts,
2681            &normal,
2682            budget,
2683            &CallMetadata::default(),
2684            &mut normal_ids,
2685        )));
2686        assert_eq!((normal_attempts.requests.len(), normal_ids.calls), (2, 2));
2687        assert_only_create_request_id_changes(&normal_attempts.requests, &normal_request_ids);
2688
2689        let bootstrap_request_ids = [request_id(33), request_id(34)];
2690        let mut bootstrap_ids = scripted_ids(bootstrap_request_ids.map(Ok));
2691        let mut bootstrap_attempts = BootstrapCapabilityAttempts::new([
2692            Err(public_outcome_unknown()),
2693            Err(terminal_checked_error()),
2694        ]);
2695        assert_outcome_unknown(block_on_ready(bootstrap_capability_retry_attempts(
2696            &mut bootstrap_attempts,
2697            &bootstrap,
2698            budget,
2699            &bootstrap_metadata,
2700            &mut bootstrap_ids,
2701        )));
2702        assert_eq!(
2703            (bootstrap_attempts.requests.len(), bootstrap_ids.calls),
2704            (2, 2)
2705        );
2706        assert_only_create_request_id_changes(&bootstrap_attempts.requests, &bootstrap_request_ids);
2707    }
2708
2709    #[test]
2710    fn every_helper_preserves_checked_retry_error_on_known_exhaustion() {
2711        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2712            .expect("immutable command");
2713        let normal = NormalCapabilityCreateTemplate::new(create_template_request(
2714            v1::CapabilityCreateMode::Normal,
2715        ))
2716        .expect("normal template");
2717        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
2718            v1::CapabilityCreateMode::Bootstrap,
2719        ))
2720        .expect("bootstrap template");
2721        let bootstrap_metadata = BootstrapCallMetadata::new(
2722            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2723        );
2724        let budget = AttemptBudget::new(2).expect("budget");
2725
2726        let execute_request_ids = [request_id(14), request_id(15)];
2727        let mut execute_ids = scripted_ids(execute_request_ids.map(Ok));
2728        let mut execute = ExecuteAttempts::new([
2729            Err(retryable_checked_error()),
2730            Err(retryable_checked_error()),
2731        ]);
2732        assert_concurrency_deadline(block_on_ready(execute_retry_attempts(
2733            &mut execute,
2734            &command,
2735            budget,
2736            &CallMetadata::default(),
2737            &mut execute_ids,
2738        )));
2739        assert_eq!(execute_ids.calls, 2);
2740        assert_only_execute_request_id_changes(&execute.requests, &execute_request_ids);
2741
2742        let normal_request_ids = [request_id(16), request_id(17)];
2743        let mut normal_ids = scripted_ids(normal_request_ids.map(Ok));
2744        let mut normal_attempts = NormalCapabilityAttempts::new([
2745            Err(retryable_checked_error()),
2746            Err(retryable_checked_error()),
2747        ]);
2748        assert_concurrency_deadline(block_on_ready(normal_capability_retry_attempts(
2749            &mut normal_attempts,
2750            &normal,
2751            budget,
2752            &CallMetadata::default(),
2753            &mut normal_ids,
2754        )));
2755        assert_eq!(normal_ids.calls, 2);
2756        assert_only_create_request_id_changes(&normal_attempts.requests, &normal_request_ids);
2757
2758        let bootstrap_request_ids = [request_id(18), request_id(19)];
2759        let mut bootstrap_ids = scripted_ids(bootstrap_request_ids.map(Ok));
2760        let mut bootstrap_attempts = BootstrapCapabilityAttempts::new([
2761            Err(retryable_checked_error()),
2762            Err(retryable_checked_error()),
2763        ]);
2764        assert_concurrency_deadline(block_on_ready(bootstrap_capability_retry_attempts(
2765            &mut bootstrap_attempts,
2766            &bootstrap,
2767            budget,
2768            &bootstrap_metadata,
2769            &mut bootstrap_ids,
2770        )));
2771        assert_eq!(bootstrap_ids.calls, 2);
2772        assert_only_create_request_id_changes(&bootstrap_attempts.requests, &bootstrap_request_ids);
2773    }
2774
2775    #[test]
2776    fn every_helper_reports_unknown_outcome_on_transport_exhaustion() {
2777        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2778            .expect("immutable command");
2779        let normal = NormalCapabilityCreateTemplate::new(create_template_request(
2780            v1::CapabilityCreateMode::Normal,
2781        ))
2782        .expect("normal template");
2783        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
2784            v1::CapabilityCreateMode::Bootstrap,
2785        ))
2786        .expect("bootstrap template");
2787        let bootstrap_metadata = BootstrapCallMetadata::new(
2788            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2789        );
2790        let budget = AttemptBudget::new(2).expect("budget");
2791
2792        let execute_request_ids = [request_id(20), request_id(21)];
2793        let mut execute_ids = scripted_ids(execute_request_ids.map(Ok));
2794        let mut execute =
2795            ExecuteAttempts::new([Err(transport_unavailable()), Err(transport_unavailable())]);
2796        assert_outcome_unknown(block_on_ready(execute_retry_attempts(
2797            &mut execute,
2798            &command,
2799            budget,
2800            &CallMetadata::default(),
2801            &mut execute_ids,
2802        )));
2803        assert_eq!(execute_ids.calls, 2);
2804        assert_only_execute_request_id_changes(&execute.requests, &execute_request_ids);
2805
2806        let normal_request_ids = [request_id(22), request_id(23)];
2807        let mut normal_ids = scripted_ids(normal_request_ids.map(Ok));
2808        let mut normal_attempts = NormalCapabilityAttempts::new([
2809            Err(transport_unavailable()),
2810            Err(transport_unavailable()),
2811        ]);
2812        assert_outcome_unknown(block_on_ready(normal_capability_retry_attempts(
2813            &mut normal_attempts,
2814            &normal,
2815            budget,
2816            &CallMetadata::default(),
2817            &mut normal_ids,
2818        )));
2819        assert_eq!(normal_ids.calls, 2);
2820        assert_only_create_request_id_changes(&normal_attempts.requests, &normal_request_ids);
2821
2822        let bootstrap_request_ids = [request_id(24), request_id(25)];
2823        let mut bootstrap_ids = scripted_ids(bootstrap_request_ids.map(Ok));
2824        let mut bootstrap_attempts = BootstrapCapabilityAttempts::new([
2825            Err(transport_unavailable()),
2826            Err(transport_unavailable()),
2827        ]);
2828        assert_outcome_unknown(block_on_ready(bootstrap_capability_retry_attempts(
2829            &mut bootstrap_attempts,
2830            &bootstrap,
2831            budget,
2832            &bootstrap_metadata,
2833            &mut bootstrap_ids,
2834        )));
2835        assert_eq!(bootstrap_ids.calls, 2);
2836        assert_only_create_request_id_changes(&bootstrap_attempts.requests, &bootstrap_request_ids);
2837    }
2838
2839    #[test]
2840    fn every_helper_closes_request_id_failure_before_and_after_uncertainty() {
2841        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2842            .expect("immutable command");
2843        let normal = NormalCapabilityCreateTemplate::new(create_template_request(
2844            v1::CapabilityCreateMode::Normal,
2845        ))
2846        .expect("normal template");
2847        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
2848            v1::CapabilityCreateMode::Bootstrap,
2849        ))
2850        .expect("bootstrap template");
2851        let bootstrap_metadata = BootstrapCallMetadata::new(
2852            BootstrapCredential::new(BOOTSTRAP_TOKEN).expect("bootstrap credential"),
2853        );
2854        let budget = AttemptBudget::new(2).expect("budget");
2855        let id_failure = crate::IdentifierGenerationError::EntropyUnavailable;
2856
2857        let mut execute_ids = scripted_ids([Err(id_failure)]);
2858        let mut execute = ExecuteAttempts::new([]);
2859        assert!(matches!(
2860            block_on_ready(execute_retry_attempts(
2861                &mut execute,
2862                &command,
2863                budget,
2864                &CallMetadata::default(),
2865                &mut execute_ids,
2866            )),
2867            Err(ClientError::IdentifierGeneration(
2868                crate::IdentifierGenerationError::EntropyUnavailable
2869            ))
2870        ));
2871        assert!(execute.requests.is_empty());
2872        assert_eq!(execute_ids.calls, 1);
2873
2874        let mut normal_ids = scripted_ids([Err(id_failure)]);
2875        let mut normal_attempts = NormalCapabilityAttempts::new([]);
2876        assert!(matches!(
2877            block_on_ready(normal_capability_retry_attempts(
2878                &mut normal_attempts,
2879                &normal,
2880                budget,
2881                &CallMetadata::default(),
2882                &mut normal_ids,
2883            )),
2884            Err(ClientError::IdentifierGeneration(
2885                crate::IdentifierGenerationError::EntropyUnavailable
2886            ))
2887        ));
2888        assert!(normal_attempts.requests.is_empty());
2889        assert_eq!(normal_ids.calls, 1);
2890
2891        let mut bootstrap_ids = scripted_ids([Err(id_failure)]);
2892        let mut bootstrap_attempts = BootstrapCapabilityAttempts::new([]);
2893        assert!(matches!(
2894            block_on_ready(bootstrap_capability_retry_attempts(
2895                &mut bootstrap_attempts,
2896                &bootstrap,
2897                budget,
2898                &bootstrap_metadata,
2899                &mut bootstrap_ids,
2900            )),
2901            Err(ClientError::IdentifierGeneration(
2902                crate::IdentifierGenerationError::EntropyUnavailable
2903            ))
2904        ));
2905        assert!(bootstrap_attempts.requests.is_empty());
2906        assert_eq!(bootstrap_ids.calls, 1);
2907
2908        let mut execute_ids = scripted_ids([Ok(request_id(26)), Err(id_failure)]);
2909        let mut execute = ExecuteAttempts::new([Err(transport_unavailable())]);
2910        assert_outcome_unknown(block_on_ready(execute_retry_attempts(
2911            &mut execute,
2912            &command,
2913            budget,
2914            &CallMetadata::default(),
2915            &mut execute_ids,
2916        )));
2917        assert_eq!((execute.requests.len(), execute_ids.calls), (1, 2));
2918
2919        let mut normal_ids = scripted_ids([Ok(request_id(27)), Err(id_failure)]);
2920        let mut normal_attempts = NormalCapabilityAttempts::new([Err(transport_unavailable())]);
2921        assert_outcome_unknown(block_on_ready(normal_capability_retry_attempts(
2922            &mut normal_attempts,
2923            &normal,
2924            budget,
2925            &CallMetadata::default(),
2926            &mut normal_ids,
2927        )));
2928        assert_eq!((normal_attempts.requests.len(), normal_ids.calls), (1, 2));
2929
2930        let mut bootstrap_ids = scripted_ids([Ok(request_id(28)), Err(id_failure)]);
2931        let mut bootstrap_attempts =
2932            BootstrapCapabilityAttempts::new([Err(transport_unavailable())]);
2933        assert_outcome_unknown(block_on_ready(bootstrap_capability_retry_attempts(
2934            &mut bootstrap_attempts,
2935            &bootstrap,
2936            budget,
2937            &bootstrap_metadata,
2938            &mut bootstrap_ids,
2939        )));
2940        assert_eq!(
2941            (bootstrap_attempts.requests.len(), bootstrap_ids.calls),
2942            (1, 2)
2943        );
2944    }
2945
2946    #[test]
2947    fn adapter_minted_idempotency_survives_driver_retries_with_fresh_transport_ids() {
2948        let first_id = RequestId::from_unix_milliseconds_and_random(1, [1; 10]).expect("first ID");
2949        let second_id =
2950            RequestId::from_unix_milliseconds_and_random(2, [2; 10]).expect("second ID");
2951        let mut request_ids = FixedRequestIds {
2952            values: VecDeque::from([first_id, second_id]),
2953        };
2954        let command = IdempotentCommand::new("CreateBudget", Some(1), retry_input())
2955            .expect("immutable command");
2956        let mut retry = RetryState::new(AttemptBudget::new(2).expect("budget"));
2957
2958        let first = next_retry_request(&command, &mut retry, &mut request_ids)
2959            .expect("first request")
2960            .expect("first submission");
2961        assert!(matches!(
2962            retry.handle_failure(ClientError::DetailsFree(
2963                DetailsFreeStatus::TransportUnavailable
2964            )),
2965            RetryDecision::Retry
2966        ));
2967        let second = next_retry_request(&command, &mut retry, &mut request_ids)
2968            .expect("second request")
2969            .expect("second submission");
2970
2971        assert_eq!(first.request_id, first_id.into_bytes());
2972        assert_eq!(second.request_id, second_id.into_bytes());
2973        assert_ne!(first.request_id, second.request_id);
2974        assert_eq!(first.input, second.input);
2975        assert_eq!(
2976            first.input.as_ref().expect("first input").encode_to_vec(),
2977            second.input.as_ref().expect("second input").encode_to_vec()
2978        );
2979        assert_eq!(first.command_name, second.command_name);
2980        assert_eq!(
2981            first.expected_contract_version,
2982            second.expected_contract_version
2983        );
2984        assert!(request_ids.values.is_empty());
2985        assert!(matches!(
2986            retry.handle_failure(ClientError::DetailsFree(
2987                DetailsFreeStatus::TransportUnavailable
2988            )),
2989            RetryDecision::Return(ClientError::OutcomeUnknown(_))
2990        ));
2991    }
2992
2993    #[test]
2994    fn capability_retry_builders_preserve_body_and_apply_fresh_request_ids() {
2995        let first_id = RequestId::from_unix_milliseconds_and_random(4, [4; 10]).expect("first ID");
2996        let second_id =
2997            RequestId::from_unix_milliseconds_and_random(5, [5; 10]).expect("second ID");
2998        let mut request_ids = FixedRequestIds {
2999            values: VecDeque::from([first_id, second_id]),
3000        };
3001        let create = NormalCapabilityCreateTemplate::new(create_template_request(
3002            v1::CapabilityCreateMode::Normal,
3003        ))
3004        .expect("normal template");
3005        let mut retry = RetryState::new(AttemptBudget::new(2).expect("budget"));
3006
3007        let first = next_normal_create_request(&create, &mut retry, &mut request_ids)
3008            .expect("first request")
3009            .expect("first attempt");
3010        assert!(matches!(
3011            retry.handle_failure(ClientError::DetailsFree(
3012                DetailsFreeStatus::TransportUnavailable
3013            )),
3014            RetryDecision::Retry
3015        ));
3016        let second = next_normal_create_request(&create, &mut retry, &mut request_ids)
3017            .expect("second request")
3018            .expect("second attempt");
3019        assert_eq!(first.request_id, first_id.into_bytes());
3020        assert_eq!(second.request_id, second_id.into_bytes());
3021        let mut first_without_id = first;
3022        let mut second_without_id = second;
3023        first_without_id.request_id.clear();
3024        second_without_id.request_id.clear();
3025        assert_eq!(first_without_id, second_without_id);
3026        assert!(matches!(
3027            retry.handle_failure(ClientError::DetailsFree(
3028                DetailsFreeStatus::TransportUnavailable
3029            )),
3030            RetryDecision::Return(ClientError::OutcomeUnknown(_))
3031        ));
3032
3033        let bootstrap = BootstrapCapabilityCreateTemplate::new(create_template_request(
3034            v1::CapabilityCreateMode::Bootstrap,
3035        ))
3036        .expect("bootstrap template");
3037        let mut bootstrap_ids = FixedRequestIds {
3038            values: VecDeque::from([
3039                RequestId::from_unix_milliseconds_and_random(6, [6; 10]).expect("bootstrap ID")
3040            ]),
3041        };
3042        let mut bootstrap_retry = RetryState::new(AttemptBudget::new(1).expect("budget"));
3043        let request =
3044            next_bootstrap_create_request(&bootstrap, &mut bootstrap_retry, &mut bootstrap_ids)
3045                .expect("bootstrap request")
3046                .expect("bootstrap attempt");
3047        assert_eq!(request.mode, v1::CapabilityCreateMode::Bootstrap as i32);
3048        assert!(!request.request_id.is_empty());
3049    }
3050
3051    #[test]
3052    fn generated_execution_preserves_transport_metadata() {
3053        let response = v1::ExecuteCommandResponse {
3054            status: v1::execute_command_response::CompletionStatus::Committed as i32,
3055            commit_sequence: 9,
3056            contract_version: 1,
3057            plan_hash: vec![1; 32],
3058            outcome_type: "Created".to_owned(),
3059            outcome: Some(v1::Value {
3060                kind: Some(v1::value::Kind::RecordValue(v1::ValueRecord {
3061                    fields: Vec::new(),
3062                })),
3063            }),
3064            provenance_uri: "riffdb://provenance/018f22e2-79b7-7cc3-a85f-250f0f80c78e".to_owned(),
3065            durability_mode: "sync".to_owned(),
3066            outcome_uri: None,
3067            history_incarnation: 1,
3068        };
3069        let execution = GeneratedExecution {
3070            response: response.clone(),
3071            outcome: 17_u32,
3072        };
3073        assert_eq!(execution.outcome(), &17);
3074        assert_eq!(execution.response(), &response);
3075        assert_eq!(execution.into_parts(), (17, response));
3076    }
3077
3078    #[test]
3079    fn projection_wait_maps_exact_total_nanoseconds_without_changing_query_identity() {
3080        let request_id = riffdb_types::RequestId::from_unix_milliseconds_and_random(1, [1; 10])
3081            .expect("request ID")
3082            .into_bytes()
3083            .to_vec();
3084        let contract = v1::ContractSelection {
3085            selection: Some(v1::contract_selection::Selection::Active(v1::Unit {})),
3086        };
3087        let mut request = v1::QueryProjectionRequest {
3088            request_id: request_id.clone(),
3089            contract: Some(contract.clone()),
3090            projection_id: 1,
3091            leading_components: Vec::new(),
3092            required_sequence: None,
3093            wait_nanos: 0,
3094            page: Some(v1::PageRequest {
3095                limit: Some(1),
3096                cursor: None,
3097            }),
3098        };
3099        let sequence = CommitSequence::new(7).expect("sequence");
3100        configure_projection_wait(&mut request, sequence, Duration::new(2, 345_678_901))
3101            .expect("bounded wait");
3102
3103        assert_eq!(request.request_id, request_id);
3104        assert_eq!(request.contract, Some(contract));
3105        assert_eq!(request.projection_id, 1);
3106        assert_eq!(request.required_sequence, Some(7));
3107        assert_eq!(request.wait_nanos, 2_345_678_901);
3108    }
3109
3110    #[test]
3111    fn projection_wait_rejects_the_public_thirty_second_overflow() {
3112        let mut request = v1::QueryProjectionRequest {
3113            request_id: riffdb_types::RequestId::from_unix_milliseconds_and_random(1, [2; 10])
3114                .expect("request ID")
3115                .into_bytes()
3116                .to_vec(),
3117            contract: Some(v1::ContractSelection {
3118                selection: Some(v1::contract_selection::Selection::Active(v1::Unit {})),
3119            }),
3120            projection_id: 1,
3121            leading_components: Vec::new(),
3122            required_sequence: None,
3123            wait_nanos: 0,
3124            page: Some(v1::PageRequest {
3125                limit: Some(1),
3126                cursor: None,
3127            }),
3128        };
3129        let error = configure_projection_wait(
3130            &mut request,
3131            CommitSequence::new(1).expect("sequence"),
3132            Duration::from_nanos(30_000_000_001),
3133        )
3134        .expect_err("over-limit wait");
3135        match error {
3136            ClientError::Protocol(failure) => {
3137                assert_eq!(failure.kind(), ProtocolFailureKind::InvalidOutboundMessage);
3138            }
3139            other => panic!("expected InvalidOutboundMessage, got {other:?}"),
3140        }
3141    }
3142
3143    /// Invalid unary outbound is certain `InvalidOutboundMessage`, never
3144    /// transport-unavailable uncertainty. Re-dropping `validate_outbound`'s
3145    /// `validate_public_message` walk fails this test (transcript).
3146    #[test]
3147    fn invalid_unary_outbound_is_protocol_not_transport_unavailable() {
3148        use crate::status::{carries_uncertainty, is_retryable};
3149
3150        let request = v1::QueryProjectionRequest {
3151            request_id: riffdb_types::RequestId::from_unix_milliseconds_and_random(1, [3; 10])
3152                .expect("request ID")
3153                .into_bytes()
3154                .to_vec(),
3155            contract: Some(v1::ContractSelection {
3156                selection: Some(v1::contract_selection::Selection::Active(v1::Unit {})),
3157            }),
3158            projection_id: 1,
3159            leading_components: Vec::new(),
3160            required_sequence: Some(1),
3161            wait_nanos: 30_000_000_001,
3162            page: Some(v1::PageRequest {
3163                limit: Some(1),
3164                cursor: None,
3165            }),
3166        };
3167        let error =
3168            validate_outbound(&request).expect_err("invalid outbound must fail before any RPC");
3169        match &error {
3170            ClientError::Protocol(failure) => {
3171                assert_eq!(
3172                    failure.kind(),
3173                    ProtocolFailureKind::InvalidOutboundMessage,
3174                    "encoder-only rejection would surface as TransportUnavailable"
3175                );
3176            }
3177            other => panic!("expected Protocol(InvalidOutboundMessage), got {other:?}"),
3178        }
3179        assert!(!is_retryable(&error));
3180        assert!(!carries_uncertainty(&error));
3181    }
3182
3183    /// The command transport admits framing overhead above the unchanged
3184    /// individual canonical-value ceiling.
3185    #[test]
3186    fn max_canonical_value_inside_the_command_frame_validates_locally() {
3187        use riffdb_types::MAX_CANONICAL_DOCUMENT_BYTES;
3188
3189        let payload_len = MAX_CANONICAL_DOCUMENT_BYTES - 32;
3190        let input = v1::Value {
3191            kind: Some(v1::value::Kind::RecordValue(v1::ValueRecord {
3192                fields: vec![v1::ValueField {
3193                    field_id: Some(1),
3194                    name: "b".to_owned(),
3195                    value: Some(v1::Value {
3196                        kind: Some(v1::value::Kind::BytesValue(vec![0x61; payload_len])),
3197                    }),
3198                }],
3199            })),
3200        };
3201        let request_id = riffdb_types::RequestId::from_unix_milliseconds_and_random(1, [4; 10])
3202            .expect("request ID");
3203        let execute = v1::ExecuteCommandRequest {
3204            request_id: request_id.into_bytes().to_vec(),
3205            command_name: "CreateTicket".to_owned(),
3206            expected_contract_version: Some(1),
3207            input: Some(input.clone()),
3208        };
3209        validate_outbound(&execute).expect("bounded command frame");
3210
3211        let command = IdempotentCommand::new("CreateTicket", Some(1), input)
3212            .expect("max-bound input is a legal command document");
3213        let built = command.request(request_id);
3214        validate_outbound(&built).expect("retry path retains the bounded command frame");
3215    }
3216}
3217
3218#[cfg(test)]
3219mod history_incarnation_tests {
3220    use riffdb_proto::v1;
3221    use tonic::transport::Endpoint;
3222
3223    use super::{RiffDbClient, merge_observed_history_incarnation};
3224
3225    // req: REC-002, STO-001, DX-014
3226    #[test]
3227    fn merge_prefers_explicit_over_remembered() {
3228        assert_eq!(merge_observed_history_incarnation(None, Some(7)), Some(7));
3229        assert_eq!(
3230            merge_observed_history_incarnation(Some(3), Some(7)),
3231            Some(3)
3232        );
3233        assert_eq!(merge_observed_history_incarnation(None, None), None);
3234        assert_eq!(merge_observed_history_incarnation(Some(3), None), Some(3));
3235    }
3236
3237    // req: REC-002, STO-001, DX-014
3238    #[test]
3239    fn client_and_mcp_track_observed_history_incarnation_across_commit_and_event_reads() {
3240        let runtime = tokio::runtime::Builder::new_current_thread()
3241            .enable_time()
3242            .build()
3243            .expect("current-thread runtime");
3244        let _guard = runtime.enter();
3245        let mut client =
3246            RiffDbClient::from_channel(Endpoint::from_static("http://[::1]:1").connect_lazy());
3247        assert_eq!(client.observed_history_incarnation(), None);
3248
3249        client.remember_history_incarnation_from_get(&v1::GetCommitResponse {
3250            result: None,
3251            history_incarnation: 4,
3252        });
3253        assert_eq!(client.observed_history_incarnation(), Some(4));
3254
3255        let get_req = client.apply_observed_history_incarnation_get(v1::GetCommitRequest {
3256            request_id: vec![1; 16],
3257            commit_sequence: 1,
3258            observed_history_incarnation: None,
3259        });
3260        assert_eq!(get_req.observed_history_incarnation, Some(4));
3261
3262        let explicit_get = client.apply_observed_history_incarnation_get(v1::GetCommitRequest {
3263            request_id: vec![1; 16],
3264            commit_sequence: 1,
3265            observed_history_incarnation: Some(2),
3266        });
3267        assert_eq!(explicit_get.observed_history_incarnation, Some(2));
3268
3269        client.remember_history_incarnation_from_scan(&v1::ScanCommitsResponse {
3270            page: Some(v1::CommitPage {
3271                items: Vec::new(),
3272                next_cursor: None,
3273                observed_fence: None,
3274                history_incarnation: 5,
3275            }),
3276        });
3277        assert_eq!(client.observed_history_incarnation(), Some(5));
3278
3279        let scan_req = client.apply_observed_history_incarnation_scan(v1::ScanCommitsRequest {
3280            request_id: vec![1; 16],
3281            page: None,
3282            observed_history_incarnation: None,
3283        });
3284        assert_eq!(scan_req.observed_history_incarnation, Some(5));
3285
3286        let sub_req =
3287            client.apply_observed_history_incarnation_subscribe(v1::SubscribeCommitsRequest {
3288                request_id: vec![1; 16],
3289                after_sequence: None,
3290                maximum_lifetime_nanos: 1_000,
3291                observed_history_incarnation: None,
3292            });
3293        assert_eq!(sub_req.observed_history_incarnation, Some(5));
3294
3295        client.remember_history_incarnation_from_event_page(Some(&v1::EventPage {
3296            items: Vec::new(),
3297            next_cursor: Vec::new(),
3298            observed_upper: None,
3299            disposition: 0,
3300            history_incarnation: 9,
3301        }));
3302        assert_eq!(client.observed_history_incarnation(), Some(9));
3303
3304        let replay_req = client.apply_observed_history_incarnation_replay(v1::ReplayEventsRequest {
3305            request_id: vec![1; 16],
3306            selection: None,
3307            after_event_id: None,
3308            page: None,
3309            observed_history_incarnation: 0,
3310        });
3311        assert_eq!(replay_req.observed_history_incarnation, 9);
3312
3313        let explicit_replay =
3314            client.apply_observed_history_incarnation_replay(v1::ReplayEventsRequest {
3315                request_id: vec![1; 16],
3316                selection: None,
3317                after_event_id: None,
3318                page: None,
3319                observed_history_incarnation: 3,
3320            });
3321        assert_eq!(explicit_replay.observed_history_incarnation, 3);
3322
3323        let tail_req = client.apply_observed_history_incarnation_tail(v1::TailEventsRequest {
3324            request_id: vec![1; 16],
3325            selection: None,
3326            after_event_id: None,
3327            page: None,
3328            maximum_wait_nanos: 1_000,
3329            observed_history_incarnation: 0,
3330        });
3331        assert_eq!(tail_req.observed_history_incarnation, 9);
3332    }
3333}