Skip to main content

riffdb_client_rust/
application.rs

1//! Name-addressed application requests that hide the kernel wire model.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt;
5use std::sync::atomic::{AtomicUsize, Ordering};
6use std::sync::{Arc, Mutex, OnceLock};
7use std::time::Duration;
8
9use futures_util::{StreamExt, stream};
10use riffdb_errors::{
11    ApplicationError, ApplicationErrorCode, ApplicationErrorContext, ApplicationOperation,
12    ApplicationRecoveryAction, PublicErrorKind,
13};
14use riffdb_proto::{app::v1 as app_v1, application_error_from_proto, v1};
15use tonic::transport::{Channel, Endpoint};
16
17use crate::{
18    AttemptBudget, CallMetadata, ClientError, DetailsFreeStatus, GeneratedExecutionError,
19    IdempotentCommand, RiffDbClient, generate_request_id,
20    generated::{GeneratedCommand, GeneratedQuery},
21};
22use riffdb_config::TlsClientConfig;
23
24const MAX_GENERATED_TRANSPORT_BATCH_ITEMS: usize = 16;
25/// Maximum independently in-flight items in one generated command batch.
26pub const MAX_GENERATED_BATCH_CONCURRENCY: usize = 384;
27const MAX_STANDBY_CLIENTS: usize = 4;
28const MAX_READ_REPLICA_CLIENTS: usize = 4;
29
30const APPLICATION_CATALOG_SCHEMA_V1: &str = "riffdb.application-catalog/v1";
31
32/// Closed application feature vocabulary returned by symbolic catalog preflight.
33#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
34pub enum ApplicationCatalogFeature {
35    /// Finite compiler-owned optional predicate families.
36    OperationalOptionalPredicates,
37    /// Snapshot-bound stable cursor pages.
38    StableCursorPages,
39    /// Indexed null and existence predicates.
40    NullExistencePredicates,
41    /// Exact binary UTF-8 prefix indexes.
42    BinaryTextPrefix,
43    /// Versioned Unicode-fold prefix indexes.
44    UnicodeFoldTextPrefixV1,
45    /// Bounded exact operational aggregates.
46    ExactAggregates,
47}
48
49/// Availability of one closed application feature.
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum ApplicationCatalogFeatureState {
52    /// The exact selected server surface implements the feature.
53    Available,
54    /// The feature is explicitly unavailable and must not be emulated.
55    Unavailable,
56}
57
58/// One checked symbolic application feature view.
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub struct ApplicationCatalogFeatureView {
61    /// Closed feature identity.
62    pub feature: ApplicationCatalogFeature,
63    /// Checked availability state.
64    pub state: ApplicationCatalogFeatureState,
65}
66
67/// Checked feature-preflight result for one exact application contract.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct ApplicationCatalogPreflight {
70    /// Exact contract lineage returned by the authorized catalog.
71    pub contract_lineage: String,
72    /// Exact contract version returned by the authorized catalog.
73    pub contract_version: u64,
74    /// Exact contract bundle hash returned by the authorized catalog.
75    pub contract_bundle_hash: [u8; 32],
76    /// Active query-module identities in canonical server order.
77    pub query_module_hashes: Vec<[u8; 32]>,
78    /// Complete closed feature registry.
79    pub features: Vec<ApplicationCatalogFeatureView>,
80}
81
82impl ApplicationCatalogPreflight {
83    /// Returns whether the exact selected server surface exposes `feature`.
84    #[must_use]
85    pub fn is_available(&self, feature: ApplicationCatalogFeature) -> bool {
86        self.features.iter().any(|view| {
87            view.feature == feature && view.state == ApplicationCatalogFeatureState::Available
88        })
89    }
90}
91
92/// A local shape failure for one bounded transport batch of ordinary commands.
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94pub enum IdempotentTransportBatchError {
95    /// The transport batch was empty.
96    Empty,
97    /// The transport batch exceeded the public protocol bound of 16 items.
98    TooManyItems,
99}
100
101impl fmt::Display for IdempotentTransportBatchError {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter.write_str(match self {
104            Self::Empty => "command transport batch is empty",
105            Self::TooManyItems => "command transport batch exceeds 16 items",
106        })
107    }
108}
109
110impl std::error::Error for IdempotentTransportBatchError {}
111
112#[derive(Clone, Debug, Eq, PartialEq)]
113struct PinnedContractIdentity {
114    database: String,
115    lineage: String,
116    version: u64,
117    bundle_hash: [u8; 32],
118}
119
120#[derive(Default)]
121struct ScriptedPeer {
122    active_contract: Mutex<Option<v1::GetActiveContractResponse>>,
123    commands: Mutex<std::collections::VecDeque<Result<v1::ExecuteCommandResponse, ClientError>>>,
124    queries: Mutex<std::collections::VecDeque<Result<app_v1::ExecuteQueryResponse, ClientError>>>,
125    recorded_command_inputs: Mutex<Vec<Option<v1::Value>>>,
126    recorded_queries: Mutex<Vec<(String, Option<u64>, bool)>>,
127}
128
129#[derive(Clone)]
130struct PeerClient {
131    inner: RiffDbClient,
132    scripted: Option<Arc<ScriptedPeer>>,
133}
134
135impl PeerClient {
136    async fn verify_active_contract(
137        &mut self,
138        expected: &PinnedContractIdentity,
139        metadata: &CallMetadata,
140    ) -> Result<(), ApplicationClientError> {
141        if expected.database.is_empty() || expected.lineage.is_empty() || expected.version == 0 {
142            return Err(ApplicationClientError::InvalidInput);
143        }
144        let request_id = Vec::from(
145            generate_request_id()
146                .map_err(|_| ApplicationClientError::IdentifierUnavailable)?
147                .into_bytes(),
148        );
149        let response = if let Some(scripted) = &self.scripted {
150            scripted
151                .active_contract
152                .lock()
153                .unwrap_or_else(std::sync::PoisonError::into_inner)
154                .clone()
155                .ok_or(ClientError::ConnectionFailure)?
156        } else {
157            self.inner
158                .get_active_contract(v1::GetActiveContractRequest { request_id }, metadata)
159                .await?
160        };
161        let Some(v1::get_active_contract_response::Result::Present(contract)) = response.result
162        else {
163            return Err(ApplicationClientError::InvalidResponse);
164        };
165        if response.database_alias != expected.database
166            || contract.contract_lineage != expected.lineage
167            || contract.contract_version != expected.version
168            || contract.bundle_hash.as_slice() != expected.bundle_hash
169        {
170            return Err(ApplicationClientError::InvalidResponse);
171        }
172        Ok(())
173    }
174
175    async fn execute_with_retry(
176        &mut self,
177        command: &IdempotentCommand,
178        attempts: AttemptBudget,
179        metadata: &CallMetadata,
180    ) -> Result<v1::ExecuteCommandResponse, ClientError> {
181        if let Some(scripted) = &self.scripted {
182            let request_id = generate_request_id().map_err(ClientError::IdentifierGeneration)?;
183            let request = command.request(request_id);
184            scripted
185                .recorded_command_inputs
186                .lock()
187                .unwrap_or_else(std::sync::PoisonError::into_inner)
188                .push(request.input);
189            return scripted
190                .commands
191                .lock()
192                .unwrap_or_else(std::sync::PoisonError::into_inner)
193                .pop_front()
194                .unwrap_or(Err(ClientError::ConnectionFailure));
195        }
196        self.inner
197            .execute_with_retry(command, attempts, metadata)
198            .await
199    }
200
201    async fn execute_named_application_query_wire(
202        &mut self,
203        query: NamedQuery,
204        metadata: &CallMetadata,
205    ) -> Result<app_v1::ExecuteQueryResponse, ApplicationClientError> {
206        if let Some(scripted) = &self.scripted {
207            scripted
208                .recorded_queries
209                .lock()
210                .unwrap_or_else(std::sync::PoisonError::into_inner)
211                .push((
212                    query.name.clone(),
213                    query.minimum_application_head,
214                    query.admission_head_consistency,
215                ));
216            let response = scripted
217                .queries
218                .lock()
219                .unwrap_or_else(std::sync::PoisonError::into_inner)
220                .pop_front()
221                .unwrap_or(Err(ClientError::ConnectionFailure))?;
222            validate_query_response_identity(
223                &response,
224                &query.contract,
225                &query.name,
226                query.module_hash,
227                query.expected_plan_hash,
228            )?;
229            return Ok(response);
230        }
231        self.inner
232            .execute_named_application_query_wire(query, metadata)
233            .await
234    }
235}
236
237struct TopologyState {
238    promoted_active: Option<PeerClient>,
239    standby: Vec<PeerClient>,
240    pinned_contract: Option<PinnedContractIdentity>,
241}
242
243struct ClientTopology {
244    state: Mutex<TopologyState>,
245    read_replicas: Vec<PeerClient>,
246    next_replica: AtomicUsize,
247}
248
249impl ClientTopology {
250    fn lock_state(&self) -> std::sync::MutexGuard<'_, TopologyState> {
251        self.state
252            .lock()
253            .unwrap_or_else(std::sync::PoisonError::into_inner)
254    }
255}
256
257/// Application-only client facade.
258///
259/// This type deliberately has no accessor for its kernel client. Stable
260/// application code can execute name-addressed commands and exact named
261/// queries, but cannot construct raw entity/index requests through this
262/// surface.
263#[derive(Clone)]
264pub struct StableApplicationClient {
265    pub(crate) inner: RiffDbClient,
266    scripted: Option<Arc<ScriptedPeer>>,
267    pinned_contract: Option<PinnedContractIdentity>,
268    topology: Option<Arc<ClientTopology>>,
269}
270
271fn validate_loopback_cleartext_endpoint(endpoint: &str) -> Result<(), ClientError> {
272    if endpoint.is_empty()
273        || endpoint.len() > 512
274        || !endpoint.is_ascii()
275        || endpoint.bytes().any(|byte| byte.is_ascii_whitespace())
276    {
277        return Err(ClientError::ConnectionFailure);
278    }
279    let authority = endpoint
280        .strip_prefix("http://")
281        .ok_or(ClientError::ConnectionFailure)?;
282    if authority.contains(['/', '?', '#', '@']) {
283        return Err(ClientError::ConnectionFailure);
284    }
285    let (address, port) = if let Some(bracketed) = authority.strip_prefix('[') {
286        let (host, port) = bracketed
287            .split_once("]:")
288            .ok_or(ClientError::ConnectionFailure)?;
289        if host.is_empty() || port.contains(':') {
290            return Err(ClientError::ConnectionFailure);
291        }
292        let address = host
293            .parse::<std::net::Ipv6Addr>()
294            .map(std::net::IpAddr::V6)
295            .map_err(|_| ClientError::ConnectionFailure)?;
296        (address, port)
297    } else {
298        let (host, port) = authority
299            .split_once(':')
300            .ok_or(ClientError::ConnectionFailure)?;
301        if host.is_empty() || port.contains(':') {
302            return Err(ClientError::ConnectionFailure);
303        }
304        let address = host
305            .parse::<std::net::Ipv4Addr>()
306            .map(std::net::IpAddr::V4)
307            .map_err(|_| ClientError::ConnectionFailure)?;
308        (address, port)
309    };
310    if !address.is_loopback()
311        || port.is_empty()
312        || (port.starts_with('0') && port.len() > 1)
313        || !port.bytes().all(|byte| byte.is_ascii_digit())
314        || port.parse::<u16>().ok().filter(|port| *port != 0).is_none()
315    {
316        return Err(ClientError::ConnectionFailure);
317    }
318    Ok(())
319}
320
321fn validate_loopback_cleartext_uri(uri: &tonic::codegen::http::Uri) -> Result<(), ClientError> {
322    if uri.scheme_str() != Some("http") {
323        return Err(ClientError::ConnectionFailure);
324    }
325    if uri
326        .path_and_query()
327        .is_some_and(|path_and_query| path_and_query.as_str() != "/")
328    {
329        return Err(ClientError::ConnectionFailure);
330    }
331    let authority = uri.authority().ok_or(ClientError::ConnectionFailure)?;
332    if authority.as_str().contains('@') {
333        return Err(ClientError::ConnectionFailure);
334    }
335    let host = uri.host().ok_or(ClientError::ConnectionFailure)?;
336    let trimmed_host = host
337        .strip_prefix('[')
338        .and_then(|rest| rest.strip_suffix(']'))
339        .unwrap_or(host);
340    let address = trimmed_host
341        .parse::<std::net::IpAddr>()
342        .map_err(|_| ClientError::ConnectionFailure)?;
343    if !address.is_loopback() || uri.port_u16().filter(|port| *port != 0).is_none() {
344        return Err(ClientError::ConnectionFailure);
345    }
346    Ok(())
347}
348
349impl StableApplicationClient {
350    /// Connects the application-only facade through mandatory explicit TLS
351    /// trust and exact peer-name verification.
352    pub async fn connect_verified_tls(config: &TlsClientConfig) -> Result<Self, ClientError> {
353        Ok(Self {
354            inner: RiffDbClient::connect_verified_tls(config).await?,
355            scripted: None,
356            pinned_contract: None,
357            topology: None,
358        })
359    }
360
361    /// Connects the application facade from one bounded loopback cleartext URI
362    /// without exposing the transport package to application code.
363    ///
364    /// Remote endpoints must connect through [`Self::connect_verified_tls`].
365    pub async fn connect_uri(endpoint: String) -> Result<Self, ClientError> {
366        validate_loopback_cleartext_endpoint(&endpoint)?;
367        let endpoint = Endpoint::from_shared(endpoint)
368            .map_err(|_| ClientError::ConnectionFailure)?
369            .connect_timeout(Duration::from_secs(10))
370            .timeout(Duration::from_secs(30));
371        Self::connect(endpoint).await
372    }
373
374    /// Connects the application facade over one reusable loopback HTTP/2 channel.
375    ///
376    /// Remote endpoints must connect through [`Self::connect_verified_tls`].
377    pub async fn connect(endpoint: Endpoint) -> Result<Self, ClientError> {
378        validate_loopback_cleartext_uri(endpoint.uri())?;
379        Ok(Self {
380            inner: RiffDbClient::connect(endpoint).await?,
381            scripted: None,
382            pinned_contract: None,
383            topology: None,
384        })
385    }
386
387    /// Constructs the application facade over an existing channel.
388    #[must_use]
389    pub fn from_channel(channel: Channel) -> Self {
390        Self {
391            inner: RiffDbClient::from_channel(channel),
392            scripted: None,
393            pinned_contract: None,
394            topology: None,
395        }
396    }
397
398    #[doc(hidden)]
399    #[must_use]
400    pub fn scripted_for_test(active_contract: v1::GetActiveContractResponse) -> Self {
401        let scripted = Arc::new(ScriptedPeer {
402            active_contract: Mutex::new(Some(active_contract)),
403            ..ScriptedPeer::default()
404        });
405        Self {
406            inner: RiffDbClient::from_channel(
407                Endpoint::from_static("http://127.0.0.1:9").connect_lazy(),
408            ),
409            scripted: Some(scripted),
410            pinned_contract: None,
411            topology: None,
412        }
413    }
414
415    #[doc(hidden)]
416    #[must_use]
417    pub fn push_scripted_command(
418        self,
419        result: Result<v1::ExecuteCommandResponse, ClientError>,
420    ) -> Self {
421        if let Some(scripted) = &self.scripted {
422            scripted
423                .commands
424                .lock()
425                .unwrap_or_else(std::sync::PoisonError::into_inner)
426                .push_back(result);
427        }
428        self
429    }
430
431    #[doc(hidden)]
432    #[must_use]
433    pub fn push_scripted_query(
434        self,
435        result: Result<app_v1::ExecuteQueryResponse, ClientError>,
436    ) -> Self {
437        if let Some(scripted) = &self.scripted {
438            scripted
439                .queries
440                .lock()
441                .unwrap_or_else(std::sync::PoisonError::into_inner)
442                .push_back(result);
443        }
444        self
445    }
446
447    #[doc(hidden)]
448    #[must_use]
449    pub fn scripted_command_inputs(&self) -> Vec<Option<v1::Value>> {
450        self.scripted
451            .as_ref()
452            .map(|scripted| {
453                scripted
454                    .recorded_command_inputs
455                    .lock()
456                    .unwrap_or_else(std::sync::PoisonError::into_inner)
457                    .clone()
458            })
459            .unwrap_or_default()
460    }
461
462    #[doc(hidden)]
463    #[must_use]
464    pub fn scripted_queries(&self) -> Vec<(String, Option<u64>, bool)> {
465        self.scripted
466            .as_ref()
467            .map(|scripted| {
468                scripted
469                    .recorded_queries
470                    .lock()
471                    .unwrap_or_else(std::sync::PoisonError::into_inner)
472                    .clone()
473            })
474            .unwrap_or_default()
475    }
476
477    fn peer_client(&self) -> PeerClient {
478        PeerClient {
479            inner: self.inner.clone(),
480            scripted: self.scripted.clone(),
481        }
482    }
483
484    /// Attaches up to 4 standby channels for automatic
485    /// contract-verified failover when the primary is fenced or unreachable.
486    pub fn with_standby_clients(
487        mut self,
488        standby: Vec<Self>,
489    ) -> Result<Self, ApplicationClientError> {
490        if standby.len() > MAX_STANDBY_CLIENTS {
491            return Err(ApplicationClientError::InvalidInput);
492        }
493        let standby_peers: Vec<PeerClient> = standby
494            .into_iter()
495            .map(|client| client.peer_client())
496            .collect();
497        let (promoted_active, read_replicas, pinned_contract) = match self.topology.take() {
498            Some(existing) => {
499                let state = existing.lock_state();
500                (
501                    state.promoted_active.clone(),
502                    existing.read_replicas.clone(),
503                    state
504                        .pinned_contract
505                        .clone()
506                        .or_else(|| self.pinned_contract.clone()),
507                )
508            }
509            None => (None, Vec::new(), self.pinned_contract.clone()),
510        };
511        if standby_peers.is_empty() && read_replicas.is_empty() && promoted_active.is_none() {
512            self.topology = None;
513        } else {
514            self.topology = Some(Arc::new(ClientTopology {
515                state: Mutex::new(TopologyState {
516                    promoted_active,
517                    standby: standby_peers,
518                    pinned_contract,
519                }),
520                read_replicas,
521                next_replica: AtomicUsize::new(0),
522            }));
523        }
524        Ok(self)
525    }
526
527    /// Attaches up to 4 follower read-replica channels
528    /// for eligible read queries with automatic primary fallback.
529    pub fn with_read_replica_clients(
530        mut self,
531        replicas: Vec<Self>,
532    ) -> Result<Self, ApplicationClientError> {
533        if replicas.len() > MAX_READ_REPLICA_CLIENTS {
534            return Err(ApplicationClientError::InvalidInput);
535        }
536        let read_replicas: Vec<PeerClient> = replicas
537            .into_iter()
538            .map(|client| client.peer_client())
539            .collect();
540        let (promoted_active, standby, pinned_contract) = match self.topology.take() {
541            Some(existing) => {
542                let state = existing.lock_state();
543                (
544                    state.promoted_active.clone(),
545                    state.standby.clone(),
546                    state
547                        .pinned_contract
548                        .clone()
549                        .or_else(|| self.pinned_contract.clone()),
550                )
551            }
552            None => (None, Vec::new(), self.pinned_contract.clone()),
553        };
554        if standby.is_empty() && read_replicas.is_empty() && promoted_active.is_none() {
555            self.topology = None;
556        } else {
557            self.topology = Some(Arc::new(ClientTopology {
558                state: Mutex::new(TopologyState {
559                    promoted_active,
560                    standby,
561                    pinned_contract,
562                }),
563                read_replicas,
564                next_replica: AtomicUsize::new(0),
565            }));
566        }
567        Ok(self)
568    }
569
570    /// Returns the number of remaining standby channels configured on this facade.
571    #[must_use]
572    pub fn standby_client_count(&self) -> usize {
573        self.topology
574            .as_ref()
575            .map_or(0, |topology| topology.lock_state().standby.len())
576    }
577
578    /// Returns the number of read-replica channels configured on this facade.
579    #[must_use]
580    pub fn read_replica_client_count(&self) -> usize {
581        self.topology
582            .as_ref()
583            .map_or(0, |topology| topology.read_replicas.len())
584    }
585
586    fn sync_active_from_topology(&mut self) {
587        if let Some(topology) = &self.topology {
588            let state = topology.lock_state();
589            if let Some(promoted) = &state.promoted_active {
590                self.inner = promoted.inner.clone();
591                self.scripted = promoted.scripted.clone();
592            }
593            if self.pinned_contract.is_none() {
594                self.pinned_contract = state.pinned_contract.clone();
595            }
596        }
597    }
598
599    fn standby_candidates(&self) -> (Vec<PeerClient>, Option<PinnedContractIdentity>) {
600        let Some(topology) = &self.topology else {
601            return (Vec::new(), self.pinned_contract.clone());
602        };
603        let state = topology.lock_state();
604        (
605            state.standby.clone(),
606            state
607                .pinned_contract
608                .clone()
609                .or_else(|| self.pinned_contract.clone()),
610        )
611    }
612
613    fn promote_standby_candidate(&mut self, index: usize, promoted: PeerClient) {
614        self.inner = promoted.inner.clone();
615        self.scripted = promoted.scripted.clone();
616        if let Some(topology) = &self.topology {
617            let mut state = topology.lock_state();
618            if index < state.standby.len() {
619                state.standby.remove(index);
620            }
621            state.promoted_active = Some(promoted);
622        }
623    }
624
625    /// Opens the optional bounded multiplexed application transport against
626    /// one exact generated application identity. Unary transport remains the
627    /// default until this explicit operation succeeds.
628    pub async fn open_bounded_session(
629        &mut self,
630        identity: crate::ApplicationSessionIdentity,
631        metadata: &CallMetadata,
632    ) -> Result<(), ApplicationClientError> {
633        self.sync_active_from_topology();
634        self.inner
635            .enable_bounded_application_session(identity, metadata.clone())
636            .await?;
637        Ok(())
638    }
639
640    /// Reports whether this facade explicitly selected the bounded session.
641    #[must_use]
642    pub const fn bounded_session_enabled(&self) -> bool {
643        self.inner.bounded_application_session_enabled()
644    }
645
646    /// Explicitly closes the optional bounded session and returns this facade
647    /// to unary transport. In-flight operations are released under the same
648    /// uncertainty rules as stream loss.
649    pub fn close_bounded_session(&mut self) {
650        self.inner.disable_bounded_application_session();
651    }
652
653    /// Proves that the authenticated remote database currently exposes the
654    /// exact contract identity compiled into the application lock.
655    pub async fn verify_active_contract(
656        &mut self,
657        database: &str,
658        lineage: &str,
659        version: u64,
660        bundle_hash: [u8; 32],
661        metadata: &CallMetadata,
662    ) -> Result<(), ApplicationClientError> {
663        self.sync_active_from_topology();
664        let expected = PinnedContractIdentity {
665            database: database.to_owned(),
666            lineage: lineage.to_owned(),
667            version,
668            bundle_hash,
669        };
670        self.peer_client()
671            .verify_active_contract(&expected, metadata)
672            .await?;
673        self.pinned_contract = Some(expected.clone());
674        if let Some(topology) = &self.topology {
675            topology.lock_state().pinned_contract = Some(expected);
676        }
677        Ok(())
678    }
679
680    /// Reads and validates the symbolic feature catalog for one exact contract.
681    ///
682    /// This application-only view deliberately omits catalog symbols, numeric
683    /// identities, raw IR, and capability details. An unavailable feature is
684    /// explicit and never authorizes a client-side fallback.
685    pub async fn preflight_application_features(
686        &mut self,
687        contract: ApplicationContract,
688        metadata: &CallMetadata,
689    ) -> Result<ApplicationCatalogPreflight, ApplicationClientError> {
690        self.sync_active_from_topology();
691        let expected = contract.clone();
692        let request_id = Vec::from(
693            generate_request_id()
694                .map_err(|_| ApplicationClientError::IdentifierUnavailable)?
695                .into_bytes(),
696        );
697        let response = self
698            .inner
699            .get_application_catalog(
700                app_v1::GetApplicationCatalogRequest {
701                    contract: lower_contract(contract),
702                    limit: 1,
703                    cursor: None,
704                    request_id,
705                },
706                metadata,
707            )
708            .await?;
709        raise_application_catalog_preflight(response, &expected)
710    }
711
712    /// Inspects one compiler-declared production vector field through the
713    /// symbolic, policy-filtered application operation.
714    pub async fn inspect_vector_state(
715        &mut self,
716        request: VectorStateInspection,
717        metadata: &CallMetadata,
718    ) -> Result<VectorStateInspectionResult, ApplicationClientError> {
719        self.sync_active_from_topology();
720        request.validate()?;
721        let request_id = Vec::from(
722            generate_request_id()
723                .map_err(|_| ApplicationClientError::IdentifierUnavailable)?
724                .into_bytes(),
725        );
726        let response = self
727            .inner
728            .inspect_vector_state(
729                app_v1::InspectVectorStateRequest {
730                    contract: lower_contract(request.contract),
731                    entity: request.entity,
732                    field: request.field,
733                    partition: Some(lower_value(request.partition)?),
734                    kind: match request.kind {
735                        VectorStateInspectionKind::Stale => {
736                            app_v1::VectorStateInspectionKind::StaleEntities as i32
737                        }
738                        VectorStateInspectionKind::OutdatedModel => {
739                            app_v1::VectorStateInspectionKind::OutdatedModelEntities as i32
740                        }
741                    },
742                    page: Some(v1::PageRequest {
743                        limit: Some(request.limit),
744                        cursor: request.cursor,
745                    }),
746                    request_id,
747                },
748                metadata,
749            )
750            .await?;
751        VectorStateInspectionResult::try_from(response)
752    }
753
754    /// Executes one exact named module query.
755    pub async fn execute_named_query(
756        &mut self,
757        query: NamedQuery,
758        metadata: &CallMetadata,
759    ) -> Result<NamedQueryResult, ApplicationClientError> {
760        let shared = self.execute_named_query_shared(query, metadata).await?;
761        Ok(Arc::unwrap_or_clone(shared))
762    }
763
764    /// Executes one exact named module query and returns a shared reference-counted
765    /// result without deep-cloning cached result maps.
766    #[doc(hidden)]
767    pub async fn execute_named_query_shared(
768        &mut self,
769        query: NamedQuery,
770        metadata: &CallMetadata,
771    ) -> Result<Arc<NamedQueryResult>, ApplicationClientError> {
772        let response =
773            with_client_wire_carrier(self.execute_named_query_wire(query, metadata)).await?;
774        raise_query_result_shared_from_client_wire(response)
775    }
776
777    /// Executes one named query while retaining its validated negotiated wire
778    /// arm for first-party generated-language adapters.
779    #[doc(hidden)]
780    pub async fn execute_named_query_wire(
781        &mut self,
782        query: NamedQuery,
783        metadata: &CallMetadata,
784    ) -> Result<app_v1::ExecuteQueryResponse, ApplicationClientError> {
785        self.sync_active_from_topology();
786        if self.topology.is_none() {
787            let mut active = self.peer_client();
788            return active
789                .execute_named_application_query_wire(query, metadata)
790                .await;
791        }
792        if !query.admission_head_consistency
793            && let Some(topology) = &self.topology
794            && !topology.read_replicas.is_empty()
795        {
796            let replicas = &topology.read_replicas;
797            let start = topology.next_replica.fetch_add(1, Ordering::Relaxed);
798            let pinned = topology
799                .lock_state()
800                .pinned_contract
801                .clone()
802                .or_else(|| self.pinned_contract.clone());
803            for offset in 0..replicas.len() {
804                let mut replica = replicas[(start + offset) % replicas.len()].clone();
805                match replica
806                    .execute_named_application_query_wire(query.clone(), metadata)
807                    .await
808                {
809                    Ok(response) => {
810                        if let Some(pinned) = &pinned {
811                            validate_pinned_query_response(&response, pinned)?;
812                        }
813                        return Ok(response);
814                    }
815                    Err(error) if application_query_error_allows_replica_fallback(&error) => {}
816                    Err(error) => return Err(error),
817                }
818            }
819        }
820        let mut active = self.peer_client();
821        match active
822            .execute_named_application_query_wire(query.clone(), metadata)
823            .await
824        {
825            Ok(response) => Ok(response),
826            Err(primary_error) => {
827                let (standby, pinned) = self.standby_candidates();
828                if !standby.is_empty()
829                    && matches!(
830                        &primary_error,
831                        ApplicationClientError::Client(error)
832                            if client_error_triggers_standby_failover(error)
833                    )
834                {
835                    for (index, mut candidate) in standby.into_iter().enumerate() {
836                        if let Some(pinned) = &pinned
837                            && candidate
838                                .verify_active_contract(pinned, metadata)
839                                .await
840                                .is_err()
841                        {
842                            continue;
843                        }
844                        match candidate
845                            .execute_named_application_query_wire(query.clone(), metadata)
846                            .await
847                        {
848                            Ok(response) => {
849                                self.promote_standby_candidate(index, candidate);
850                                return Ok(response);
851                            }
852                            Err(ApplicationClientError::Client(ref error))
853                                if client_error_triggers_standby_failover(error) => {}
854                            Err(error) => {
855                                self.promote_standby_candidate(index, candidate);
856                                return Err(error);
857                            }
858                        }
859                    }
860                }
861                Err(primary_error)
862            }
863        }
864    }
865
866    /// Executes and decodes one generated exact named-query shape.
867    pub async fn execute_generated_query<Q: GeneratedQuery>(
868        &mut self,
869        query: Q,
870        options: QueryOptions,
871        metadata: &CallMetadata,
872    ) -> Result<TypedQueryResult<Q::Output>, ApplicationClientError> {
873        let query = query.named_query(options)?;
874        let response = self.execute_named_query_wire(query, metadata).await?;
875        let application_head = response.application_head;
876        let next_cursor = response.next_cursor.clone();
877        let identity = query_response_identity(&response)?;
878        let value = match app_v1::NamedResultEncoding::try_from(response.selected_result_encoding) {
879            Ok(app_v1::NamedResultEncoding::CompactV1) => {
880                if !response.fields.is_empty() {
881                    return Err(ApplicationClientError::InvalidResponse);
882                }
883                Q::decode_compact_result(
884                    response.outcome,
885                    response
886                        .compact_result
887                        .ok_or(ApplicationClientError::InvalidResponse)?,
888                )?
889            }
890            Ok(app_v1::NamedResultEncoding::PackedV1) => {
891                if !response.fields.is_empty() || response.compact_result.is_some() {
892                    return Err(ApplicationClientError::InvalidResponse);
893                }
894                Q::decode_packed_result(
895                    response.outcome,
896                    response
897                        .packed_result
898                        .ok_or(ApplicationClientError::InvalidResponse)?,
899                )?
900            }
901            Ok(app_v1::NamedResultEncoding::LegacyRecords)
902            | Ok(app_v1::NamedResultEncoding::Unspecified) => {
903                Q::decode_result(raise_query_result(response)?)?
904            }
905            Err(_) => return Err(ApplicationClientError::InvalidResponse),
906        };
907        Ok(TypedQueryResult {
908            value,
909            identity,
910            application_head,
911            next_cursor,
912        })
913    }
914
915    /// Opens a bounded multi-page continuation stream over a named query (`ADR-0339`).
916    ///
917    /// Page 1 establishes the pinned snapshot identity and `application_head`;
918    /// every subsequent page is verified to share the exact identity and
919    /// `application_head` before release.
920    #[must_use]
921    pub fn stream_named_query<'a>(
922        &'a mut self,
923        query: NamedQuery,
924        metadata: &'a CallMetadata,
925    ) -> NamedQueryPageStream<'a> {
926        NamedQueryPageStream::new_stable(self, query, metadata)
927    }
928
929    /// Opens a bounded multi-page continuation stream over a generated query (`ADR-0339`).
930    #[must_use]
931    pub fn stream_generated_query<'a, Q: GeneratedQuery + Clone>(
932        &'a mut self,
933        query: Q,
934        options: QueryOptions,
935        metadata: &'a CallMetadata,
936    ) -> GeneratedQueryPageStream<'a, Q> {
937        GeneratedQueryPageStream::new(self, query, options, metadata)
938    }
939
940    /// Executes one exact symbolic command with bounded uncertainty recovery.
941    pub async fn execute_command(
942        &mut self,
943        command: ApplicationCommand,
944        attempts: AttemptBudget,
945        metadata: &CallMetadata,
946    ) -> Result<ApplicationCommandResult, ApplicationClientError> {
947        self.sync_active_from_topology();
948        let command_name = command.name.clone();
949        let idempotent = command.into_idempotent_command()?;
950        let mut active = self.peer_client();
951        match active
952            .execute_with_retry(&idempotent, attempts, metadata)
953            .await
954        {
955            Ok(response) => raise_application_command_result(response),
956            Err(primary_error) => {
957                let (standby, pinned) = self.standby_candidates();
958                if !standby.is_empty() && client_error_triggers_standby_failover(&primary_error) {
959                    for (index, mut candidate) in standby.into_iter().enumerate() {
960                        if let Some(pinned) = &pinned
961                            && candidate
962                                .verify_active_contract(pinned, metadata)
963                                .await
964                                .is_err()
965                        {
966                            continue;
967                        }
968                        match candidate
969                            .execute_with_retry(&idempotent, attempts, metadata)
970                            .await
971                        {
972                            Ok(response) => {
973                                self.promote_standby_candidate(index, candidate);
974                                return raise_application_command_result(response);
975                            }
976                            Err(error) if client_error_triggers_standby_failover(&error) => {}
977                            Err(error) => {
978                                self.promote_standby_candidate(index, candidate);
979                                return Err(ApplicationClientError::Client(
980                                    contextualize_command_client_error(error, &command_name),
981                                ));
982                            }
983                        }
984                    }
985                }
986                Err(ApplicationClientError::Client(
987                    contextualize_command_client_error(primary_error, &command_name),
988                ))
989            }
990        }
991    }
992
993    /// Executes and decodes one generated command, then performs one exact
994    /// same-key outcome lookup if transport uncertainty remains.
995    pub async fn execute_generated_command<C: GeneratedCommand>(
996        &mut self,
997        command: &C,
998        attempts: AttemptBudget,
999        metadata: &CallMetadata,
1000    ) -> Result<TypedCommandResult<C::Outcome>, GeneratedExecutionError> {
1001        self.sync_active_from_topology();
1002        let execution = match self
1003            .inner
1004            .execute_generated_with_recovery(command, attempts, metadata)
1005            .await
1006        {
1007            Ok(execution) => execution,
1008            Err(primary_error) => {
1009                let (standby, pinned) = self.standby_candidates();
1010                let mut promoted_execution = None;
1011                if !standby.is_empty()
1012                    && matches!(
1013                        &primary_error,
1014                        GeneratedExecutionError::Client(error)
1015                            if client_error_triggers_standby_failover(error)
1016                    )
1017                {
1018                    for (index, mut candidate) in standby.into_iter().enumerate() {
1019                        if let Some(pinned) = &pinned
1020                            && candidate
1021                                .verify_active_contract(pinned, metadata)
1022                                .await
1023                                .is_err()
1024                        {
1025                            continue;
1026                        }
1027                        match candidate
1028                            .inner
1029                            .execute_generated_with_recovery(command, attempts, metadata)
1030                            .await
1031                        {
1032                            Ok(execution) => {
1033                                self.promote_standby_candidate(index, candidate);
1034                                promoted_execution = Some(Ok(execution));
1035                                break;
1036                            }
1037                            Err(GeneratedExecutionError::Client(ref error))
1038                                if client_error_triggers_standby_failover(error) => {}
1039                            Err(error) => {
1040                                self.promote_standby_candidate(index, candidate);
1041                                promoted_execution = Some(Err(error));
1042                                break;
1043                            }
1044                        }
1045                    }
1046                }
1047                match promoted_execution {
1048                    Some(result) => result?,
1049                    None => return Err(primary_error),
1050                }
1051            }
1052        };
1053        let (outcome, response) = execution.into_parts();
1054        let workflow_revisions = command
1055            .workflow_successor_revisions(&response)
1056            .map_err(GeneratedExecutionError::CommandShape)?;
1057        Ok(TypedCommandResult {
1058            outcome,
1059            commit_sequence: (response.commit_sequence != 0).then_some(response.commit_sequence),
1060            contract_version: response.contract_version,
1061            plan_hash: response.plan_hash.try_into().map_err(|_| {
1062                GeneratedExecutionError::CommandShape(
1063                    crate::generated::GeneratedCommandError::InvalidOutcomeShape,
1064                )
1065            })?,
1066            replayed: response.status
1067                == v1::execute_command_response::CompletionStatus::Replayed as i32,
1068            outcome_uri: response.outcome_uri,
1069            workflow_revisions,
1070        })
1071    }
1072
1073    /// Executes a bounded collection of ordinary generated commands with
1074    /// backpressure and independently ordered per-item results.
1075    pub async fn execute_generated_command_batch<C>(
1076        &self,
1077        commands: Vec<C>,
1078        options: GeneratedBatchOptions,
1079        attempts: AttemptBudget,
1080        metadata: &CallMetadata,
1081    ) -> Result<GeneratedBatchResult<C::Outcome>, GeneratedBatchError>
1082    where
1083        C: GeneratedCommand + Clone,
1084    {
1085        self.execute_generated_command_batch_with_progress(
1086            commands,
1087            options,
1088            attempts,
1089            metadata,
1090            |_| {},
1091        )
1092        .await
1093    }
1094
1095    /// Executes a bounded generated-command batch and reports completion plus
1096    /// the largest contiguous, safely resumable input checkpoint.
1097    pub async fn execute_generated_command_batch_with_progress<C, F>(
1098        &self,
1099        commands: Vec<C>,
1100        options: GeneratedBatchOptions,
1101        attempts: AttemptBudget,
1102        metadata: &CallMetadata,
1103        mut report_progress: F,
1104    ) -> Result<GeneratedBatchResult<C::Outcome>, GeneratedBatchError>
1105    where
1106        C: GeneratedCommand + Clone,
1107        F: FnMut(GeneratedBatchProgress),
1108    {
1109        options.validate(commands.len())?;
1110        let total = commands.len();
1111        let (transport_batch_size, transport_concurrency) =
1112            generated_transport_batch_policy(options.concurrency);
1113        let mut chunks = Vec::new();
1114        let mut chunk = Vec::with_capacity(transport_batch_size);
1115        for item in commands.into_iter().enumerate().skip(options.checkpoint) {
1116            chunk.push(item);
1117            if chunk.len() == transport_batch_size {
1118                chunks.push(std::mem::replace(
1119                    &mut chunk,
1120                    Vec::with_capacity(transport_batch_size),
1121                ));
1122            }
1123        }
1124        if !chunk.is_empty() {
1125            chunks.push(chunk);
1126        }
1127        let mut pending = stream::iter(chunks.into_iter().map(|chunk| {
1128            let client = self.clone();
1129            let metadata = metadata.clone();
1130            async move {
1131                client
1132                    .execute_generated_transport_batch(chunk, attempts, &metadata)
1133                    .await
1134            }
1135        }))
1136        .buffer_unordered(transport_concurrency);
1137        let mut items = Vec::with_capacity(total - options.checkpoint);
1138        let mut progress_state = BatchCheckpointState::new(options.checkpoint);
1139        while let Some(completed_chunk) = pending.next().await {
1140            for (index, result) in completed_chunk {
1141                record_generated_batch_item_completion(
1142                    index,
1143                    result,
1144                    total,
1145                    &mut progress_state,
1146                    &mut items,
1147                    &mut report_progress,
1148                );
1149            }
1150        }
1151        items.sort_by_key(|item| item.index);
1152        Ok(GeneratedBatchResult {
1153            items,
1154            checkpoint: progress_state.checkpoint,
1155        })
1156    }
1157
1158    async fn execute_generated_transport_batch<C: GeneratedCommand + Clone>(
1159        &self,
1160        commands: Vec<(usize, C)>,
1161        attempts: AttemptBudget,
1162        metadata: &CallMetadata,
1163    ) -> Vec<(
1164        usize,
1165        Result<TypedCommandResult<C::Outcome>, GeneratedExecutionError>,
1166    )> {
1167        let mut requests = Vec::with_capacity(commands.len());
1168        let mut prepared = Vec::with_capacity(commands.len());
1169        let mut completed = Vec::new();
1170        for (index, command) in commands {
1171            let generic = match command.idempotent_command() {
1172                Ok(generic) => generic,
1173                Err(error) => {
1174                    completed.push((index, Err(GeneratedExecutionError::CommandShape(error))));
1175                    continue;
1176                }
1177            };
1178            let request_id = match generate_request_id() {
1179                Ok(request_id) => request_id,
1180                Err(error) => {
1181                    completed.push((
1182                        index,
1183                        Err(GeneratedExecutionError::Client(
1184                            ClientError::IdentifierGeneration(error),
1185                        )),
1186                    ));
1187                    continue;
1188                }
1189            };
1190            requests.push(generic.request(request_id));
1191            prepared.push((index, command));
1192        }
1193        if prepared.is_empty() {
1194            return completed;
1195        }
1196
1197        let mut client = self.inner.clone();
1198        let response = client
1199            .execute_batch(
1200                v1::ExecuteCommandBatchRequest { commands: requests },
1201                metadata,
1202            )
1203            .await;
1204        let Ok(response) = response else {
1205            // Transport-level or whole-RPC failure: re-enter every item through
1206            // the normal same-idempotency-key recovery path.
1207            let recovered: Vec<_> = stream::iter(prepared.into_iter().map(|(index, command)| {
1208                let mut client = self.clone();
1209                let metadata = metadata.clone();
1210                async move {
1211                    let result = client
1212                        .execute_generated_command(&command, attempts, &metadata)
1213                        .await;
1214                    (index, result)
1215                }
1216            }))
1217            .buffer_unordered(MAX_GENERATED_TRANSPORT_BATCH_ITEMS)
1218            .collect()
1219            .await;
1220            completed.extend(recovered);
1221            return completed;
1222        };
1223
1224        // Prefer per-item carriage when present (ADR-0084). Older servers leave
1225        // items empty and only populate legacy success rows.
1226        if !response.items.is_empty() {
1227            let recovered =
1228                complete_batch_items_with_reentry(prepared, response.items, |index, command| {
1229                    let mut client = self.clone();
1230                    let metadata = metadata.clone();
1231                    async move {
1232                        let result = client
1233                            .execute_generated_command(&command, attempts, &metadata)
1234                            .await;
1235                        (index, result)
1236                    }
1237                })
1238                .await;
1239            completed.extend(recovered);
1240            return completed;
1241        }
1242
1243        // Legacy items-absent path: positional zip on success rows.
1244        completed.extend(prepared.into_iter().zip(response.responses).map(
1245            |((index, command), response)| {
1246                let outcome = command
1247                    .decode_outcome(&response)
1248                    .map_err(GeneratedExecutionError::CommandShape);
1249                (
1250                    index,
1251                    outcome.and_then(|outcome| typed_command_result(&command, outcome, response)),
1252                )
1253            },
1254        ));
1255        completed
1256    }
1257}
1258
1259impl RiffDbClient {
1260    /// Executes at most 16 ordinary idempotent commands through one transport
1261    /// batch while preserving independent per-item recovery.
1262    ///
1263    /// This is transport coalescing only: every item remains a separately
1264    /// authorized command with its own idempotency identity, commit decision,
1265    /// provenance, and typed outcome. Whole-RPC uncertainty and retryable item
1266    /// failures re-enter through [`RiffDbClient::execute_with_retry`] with the
1267    /// identical command input and key.
1268    pub async fn execute_idempotent_transport_batch_with_retry(
1269        &self,
1270        commands: Vec<IdempotentCommand>,
1271        attempts: AttemptBudget,
1272        metadata: &CallMetadata,
1273    ) -> Result<Vec<Result<v1::ExecuteCommandResponse, ClientError>>, IdempotentTransportBatchError>
1274    {
1275        validate_idempotent_transport_batch_len(commands.len())?;
1276
1277        let mut requests = Vec::with_capacity(commands.len());
1278        for command in &commands {
1279            let request_id = match generate_request_id() {
1280                Ok(request_id) => request_id,
1281                Err(_) => {
1282                    // Nothing was submitted. Re-enter every immutable command
1283                    // through the ordinary path so request-id uncertainty is
1284                    // classified independently and no item is misattributed.
1285                    return Ok(
1286                        reenter_idempotent_commands(self, commands, attempts, metadata).await,
1287                    );
1288                }
1289            };
1290            requests.push(command.request(request_id));
1291        }
1292
1293        let mut client = self.clone();
1294        let response = client
1295            .execute_batch(
1296                v1::ExecuteCommandBatchRequest { commands: requests },
1297                metadata,
1298            )
1299            .await;
1300        let Ok(response) = response else {
1301            return Ok(reenter_idempotent_commands(self, commands, attempts, metadata).await);
1302        };
1303
1304        if response.items.is_empty() {
1305            return Ok(response.responses.into_iter().map(Ok).collect());
1306        }
1307
1308        let mut resolved = Vec::with_capacity(commands.len());
1309        let mut reenter = Vec::new();
1310        for (index, (command, item)) in commands.into_iter().zip(response.items).enumerate() {
1311            match item.result {
1312                Some(v1::execute_command_batch_item::Result::Response(response)) => {
1313                    resolved.push((index, Ok(response)));
1314                }
1315                Some(v1::execute_command_batch_item::Result::Error(error_wire)) => {
1316                    match application_error_from_proto(&error_wire) {
1317                        Ok(error) if application_error_requires_reentry(&error) => {
1318                            reenter.push((index, command));
1319                        }
1320                        Ok(error) => {
1321                            resolved.push((index, Err(ClientError::Application(Box::new(error)))));
1322                        }
1323                        Err(_) => reenter.push((index, command)),
1324                    }
1325                }
1326                None => reenter.push((index, command)),
1327            }
1328        }
1329
1330        if !reenter.is_empty() {
1331            let recovered: Vec<_> = stream::iter(reenter.into_iter().map(|(index, command)| {
1332                let mut client = self.clone();
1333                let metadata = metadata.clone();
1334                async move {
1335                    let result = client
1336                        .execute_with_retry(&command, attempts, &metadata)
1337                        .await;
1338                    (index, result)
1339                }
1340            }))
1341            .buffer_unordered(MAX_GENERATED_TRANSPORT_BATCH_ITEMS)
1342            .collect()
1343            .await;
1344            resolved.extend(recovered);
1345        }
1346        resolved.sort_by_key(|(index, _)| *index);
1347        Ok(resolved.into_iter().map(|(_, result)| result).collect())
1348    }
1349}
1350
1351const fn validate_idempotent_transport_batch_len(
1352    item_count: usize,
1353) -> Result<(), IdempotentTransportBatchError> {
1354    if item_count == 0 {
1355        return Err(IdempotentTransportBatchError::Empty);
1356    }
1357    if item_count > MAX_GENERATED_TRANSPORT_BATCH_ITEMS {
1358        return Err(IdempotentTransportBatchError::TooManyItems);
1359    }
1360    Ok(())
1361}
1362
1363async fn reenter_idempotent_commands(
1364    client: &RiffDbClient,
1365    commands: Vec<IdempotentCommand>,
1366    attempts: AttemptBudget,
1367    metadata: &CallMetadata,
1368) -> Vec<Result<v1::ExecuteCommandResponse, ClientError>> {
1369    stream::iter(commands.into_iter().map(|command| {
1370        let mut client = client.clone();
1371        let metadata = metadata.clone();
1372        async move {
1373            client
1374                .execute_with_retry(&command, attempts, &metadata)
1375                .await
1376        }
1377    }))
1378    .buffered(MAX_GENERATED_TRANSPORT_BATCH_ITEMS)
1379    .collect()
1380    .await
1381}
1382
1383type ResolvedBatchItem<T> = (
1384    usize,
1385    Result<TypedCommandResult<T>, GeneratedExecutionError>,
1386);
1387
1388/// One batch item scheduled for same-key re-entry.
1389struct ReenterCandidate<C> {
1390    index: usize,
1391    command: C,
1392    /// Defense-in-depth original protocol failure. Production wire validation
1393    /// rejects unset/undecodable item arms before this path runs; when re-entry
1394    /// is exhausted, this is surfaced instead of the generic re-entry error.
1395    protocol_failure: Option<crate::ProtocolFailure>,
1396}
1397
1398type BatchItemResolution<C> = (
1399    Vec<ResolvedBatchItem<<C as GeneratedCommand>::Outcome>>,
1400    Vec<ReenterCandidate<C>>,
1401);
1402
1403/// Contiguous-progress counters for a generated command batch.
1404struct BatchCheckpointState {
1405    completed: usize,
1406    checkpoint: usize,
1407    completed_after_checkpoint: BTreeSet<usize>,
1408}
1409
1410impl BatchCheckpointState {
1411    /// Seeds completed/checkpoint from a retained resume checkpoint.
1412    fn new(checkpoint: usize) -> Self {
1413        Self {
1414            completed: checkpoint,
1415            checkpoint,
1416            completed_after_checkpoint: BTreeSet::new(),
1417        }
1418    }
1419}
1420
1421/// Records one independent batch item result and advances the contiguous checkpoint.
1422///
1423/// Checkpoint advances over every terminal result (Ok or Err). Callers must only
1424/// invoke this after any same-key re-entry for the item has finished.
1425fn record_generated_batch_item_completion<T, F>(
1426    index: usize,
1427    result: Result<TypedCommandResult<T>, GeneratedExecutionError>,
1428    total: usize,
1429    state: &mut BatchCheckpointState,
1430    items: &mut Vec<GeneratedBatchItem<T>>,
1431    report_progress: &mut F,
1432) where
1433    F: FnMut(GeneratedBatchProgress),
1434{
1435    state.completed += 1;
1436    state.completed_after_checkpoint.insert(index);
1437    while state.completed_after_checkpoint.remove(&state.checkpoint) {
1438        state.checkpoint += 1;
1439    }
1440    items.push(GeneratedBatchItem { index, result });
1441    report_progress(GeneratedBatchProgress {
1442        completed: state.completed,
1443        total,
1444        checkpoint: state.checkpoint,
1445    });
1446}
1447
1448/// Classifies per-item batch carriage into terminal results and re-entry candidates.
1449///
1450/// Re-entry uses the registry-derived recovery action, not a hand-listed code set:
1451/// [`ApplicationRecoveryAction::Retry`] and
1452/// [`ApplicationRecoveryAction::ResolveWithSameIdempotencyKey`] re-enter
1453/// `execute_generated_command` (same idempotency key; its AttemptBudget and
1454/// Overloaded backoff then apply). Every other recovery action is terminal and
1455/// surfaces directly with zero re-entry.
1456///
1457/// Undecodable error details and unset oneof arms are **defense-in-depth**:
1458/// production clients reject both shapes at the kept client inbound decode
1459/// (`decode_public_message` inside StrictProstDecoder — no separate client
1460/// re-walk after decode) before an `Ok` batch response exists, so those wire
1461/// defects arrive as transport-level protocol failures and take the blanket
1462/// re-entry path. If a decoded response still reaches these arms, same-key
1463/// re-entry is scheduled; when that re-entry is exhausted, the original
1464/// protocol failure is surfaced as the item error.
1465fn resolve_generated_batch_items<C: GeneratedCommand>(
1466    prepared: Vec<(usize, C)>,
1467    items: Vec<v1::ExecuteCommandBatchItem>,
1468) -> BatchItemResolution<C> {
1469    let mut resolved = Vec::with_capacity(prepared.len());
1470    let mut reenter = Vec::new();
1471    for ((index, command), item) in prepared.into_iter().zip(items) {
1472        match item.result {
1473            Some(v1::execute_command_batch_item::Result::Response(item_response)) => {
1474                let outcome = command
1475                    .decode_outcome(&item_response)
1476                    .map_err(GeneratedExecutionError::CommandShape);
1477                resolved.push((
1478                    index,
1479                    outcome
1480                        .and_then(|outcome| typed_command_result(&command, outcome, item_response)),
1481                ));
1482            }
1483            Some(v1::execute_command_batch_item::Result::Error(error_wire)) => {
1484                match application_error_from_proto(&error_wire) {
1485                    Ok(error) if application_error_requires_reentry(&error) => {
1486                        reenter.push(ReenterCandidate {
1487                            index,
1488                            command,
1489                            protocol_failure: None,
1490                        });
1491                    }
1492                    Ok(error) => {
1493                        resolved.push((
1494                            index,
1495                            Err(GeneratedExecutionError::Client(ClientError::Application(
1496                                Box::new(error),
1497                            ))),
1498                        ));
1499                    }
1500                    Err(_) => {
1501                        reenter.push(ReenterCandidate {
1502                            index,
1503                            command,
1504                            protocol_failure: Some(crate::ProtocolFailure::new(
1505                                crate::ProtocolFailureKind::InvalidApplicationErrorDetails,
1506                            )),
1507                        });
1508                    }
1509                }
1510            }
1511            None => {
1512                reenter.push(ReenterCandidate {
1513                    index,
1514                    command,
1515                    protocol_failure: Some(crate::ProtocolFailure::new(
1516                        crate::ProtocolFailureKind::InvalidInboundMessage,
1517                    )),
1518                });
1519            }
1520        }
1521    }
1522    (resolved, reenter)
1523}
1524
1525/// Finishes one transport-batch response: keep terminal arms, re-enter the rest.
1526async fn complete_batch_items_with_reentry<C, F, Fut>(
1527    prepared: Vec<(usize, C)>,
1528    items: Vec<v1::ExecuteCommandBatchItem>,
1529    reenter_one: F,
1530) -> Vec<ResolvedBatchItem<C::Outcome>>
1531where
1532    C: GeneratedCommand + Clone,
1533    F: Fn(usize, C) -> Fut,
1534    Fut: std::future::Future<
1535            Output = (
1536                usize,
1537                Result<TypedCommandResult<C::Outcome>, GeneratedExecutionError>,
1538            ),
1539        >,
1540{
1541    let (mut resolved, reenter) = resolve_generated_batch_items(prepared, items);
1542    if !reenter.is_empty() {
1543        let recovered: Vec<_> = stream::iter(reenter.into_iter().map(|candidate| {
1544            let protocol_failure = candidate.protocol_failure;
1545            let reenter_one = &reenter_one;
1546            async move {
1547                let (index, result) = reenter_one(candidate.index, candidate.command).await;
1548                let result = match (result, protocol_failure) {
1549                    (Err(_), Some(failure)) => Err(GeneratedExecutionError::Client(
1550                        ClientError::Protocol(failure),
1551                    )),
1552                    (other, _) => other,
1553                };
1554                (index, result)
1555            }
1556        }))
1557        .buffer_unordered(MAX_GENERATED_TRANSPORT_BATCH_ITEMS)
1558        .collect()
1559        .await;
1560        resolved.extend(recovered);
1561    }
1562    resolved
1563}
1564
1565const fn application_error_requires_reentry(error: &ApplicationError) -> bool {
1566    matches!(
1567        error.recovery_action(),
1568        ApplicationRecoveryAction::Retry | ApplicationRecoveryAction::ResolveWithSameIdempotencyKey
1569    )
1570}
1571
1572fn generated_transport_batch_policy(item_concurrency: usize) -> (usize, usize) {
1573    let transport_concurrency = item_concurrency.div_ceil(MAX_GENERATED_TRANSPORT_BATCH_ITEMS);
1574    let transport_batch_size = item_concurrency / transport_concurrency;
1575    (transport_batch_size, transport_concurrency)
1576}
1577
1578pub(crate) fn typed_command_result<C: GeneratedCommand<Outcome = T>, T>(
1579    command: &C,
1580    outcome: T,
1581    response: v1::ExecuteCommandResponse,
1582) -> Result<TypedCommandResult<T>, GeneratedExecutionError> {
1583    let workflow_revisions = command
1584        .workflow_successor_revisions(&response)
1585        .map_err(GeneratedExecutionError::CommandShape)?;
1586    let plan_hash = response.plan_hash.try_into().map_err(|_| {
1587        GeneratedExecutionError::CommandShape(
1588            crate::generated::GeneratedCommandError::InvalidOutcomeShape,
1589        )
1590    })?;
1591    Ok(TypedCommandResult {
1592        outcome,
1593        commit_sequence: (response.commit_sequence != 0).then_some(response.commit_sequence),
1594        contract_version: response.contract_version,
1595        plan_hash,
1596        replayed: response.status
1597            == v1::execute_command_response::CompletionStatus::Replayed as i32,
1598        outcome_uri: response.outcome_uri,
1599        workflow_revisions,
1600    })
1601}
1602
1603/// Bounds for generated command batches.
1604#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1605pub struct GeneratedBatchOptions {
1606    /// Maximum simultaneously in-flight ordinary command calls.
1607    pub concurrency: usize,
1608    /// Contiguous input prefix already represented by a retained checkpoint.
1609    pub checkpoint: usize,
1610}
1611
1612impl GeneratedBatchOptions {
1613    /// Constructs a checked batch policy.
1614    pub fn new(concurrency: usize) -> Result<Self, GeneratedBatchError> {
1615        let value = Self {
1616            concurrency,
1617            checkpoint: 0,
1618        };
1619        value.validate(1)?;
1620        Ok(value)
1621    }
1622
1623    /// Resumes after a previously reported contiguous input checkpoint.
1624    #[must_use]
1625    pub const fn with_checkpoint(mut self, checkpoint: usize) -> Self {
1626        self.checkpoint = checkpoint;
1627        self
1628    }
1629
1630    fn validate(self, item_count: usize) -> Result<(), GeneratedBatchError> {
1631        if self.concurrency == 0
1632            || self.concurrency > MAX_GENERATED_BATCH_CONCURRENCY
1633            || item_count == 0
1634            || item_count > 4_096
1635            || self.checkpoint > item_count
1636        {
1637            return Err(GeneratedBatchError::InvalidBounds);
1638        }
1639        Ok(())
1640    }
1641}
1642
1643/// One independently completed generated command at its stable input offset.
1644pub struct GeneratedBatchItem<T> {
1645    /// Zero-based position in the complete input collection.
1646    pub index: usize,
1647    /// Typed command result or its independent public execution failure.
1648    pub result: Result<TypedCommandResult<T>, GeneratedExecutionError>,
1649}
1650
1651/// Bounded progress safe to persist without command inputs or outcomes.
1652#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1653pub struct GeneratedBatchProgress {
1654    /// Number of inputs covered by the initial checkpoint or completed now.
1655    pub completed: usize,
1656    /// Total number of inputs in the bound collection.
1657    pub total: usize,
1658    /// Largest contiguous completed input prefix, safe for exact resume.
1659    pub checkpoint: usize,
1660}
1661
1662/// Stable per-item generated batch result and resumable item checkpoint.
1663pub struct GeneratedBatchResult<T> {
1664    /// Newly executed, input-ordered independent outcomes and original offsets.
1665    pub items: Vec<GeneratedBatchItem<T>>,
1666    /// Largest contiguous completed input prefix.
1667    pub checkpoint: usize,
1668}
1669
1670/// Failure before a generated batch can submit any item.
1671#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1672pub enum GeneratedBatchError {
1673    /// Item count or concurrency exceeded the public bounds.
1674    InvalidBounds,
1675}
1676
1677impl fmt::Display for GeneratedBatchError {
1678    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1679        formatter.write_str("generated command batch bounds are invalid")
1680    }
1681}
1682
1683impl std::error::Error for GeneratedBatchError {}
1684
1685/// Canonical UUID value with lazy display text.
1686///
1687/// Wire raise paths keep the 16-byte form; the 36-char text is formatted only
1688/// when a caller asks for display via [`as_str`](Self::as_str) or
1689/// [`into_string`](Self::into_string). Parameter construction from validated
1690/// text retains the original string so adapters that already hold display form
1691/// do not re-allocate.
1692#[derive(Debug)]
1693pub struct ApplicationUuid {
1694    bytes: [u8; 16],
1695    text: OnceLock<String>,
1696}
1697
1698impl Clone for ApplicationUuid {
1699    fn clone(&self) -> Self {
1700        let text = OnceLock::new();
1701        if let Some(existing) = self.text.get() {
1702            let _ = text.set(existing.clone());
1703        }
1704        Self {
1705            bytes: self.bytes,
1706            text,
1707        }
1708    }
1709}
1710
1711impl ApplicationUuid {
1712    /// Builds from the exact 16-byte public UUID value (raise path).
1713    #[must_use]
1714    pub fn from_bytes(bytes: [u8; 16]) -> Self {
1715        Self {
1716            bytes,
1717            text: OnceLock::new(),
1718        }
1719    }
1720
1721    /// Builds from canonical UUID text (parameter path).
1722    pub fn from_text(text: impl Into<String>) -> Result<Self, ApplicationClientError> {
1723        let text = text.into();
1724        let bytes = parse_uuid(&text)?;
1725        let cell = OnceLock::new();
1726        let _ = cell.set(text);
1727        Ok(Self { bytes, text: cell })
1728    }
1729
1730    /// Exact 16-byte form without a text round-trip.
1731    #[must_use]
1732    pub const fn as_bytes(&self) -> &[u8; 16] {
1733        &self.bytes
1734    }
1735
1736    /// Canonical 36-char text; formatted on first access when raised from bytes.
1737    #[must_use]
1738    pub fn as_str(&self) -> &str {
1739        self.text
1740            .get_or_init(|| format_uuid_text(&self.bytes))
1741            .as_str()
1742    }
1743
1744    /// Consumes into canonical text (formats once if never requested).
1745    #[must_use]
1746    pub fn into_string(self) -> String {
1747        match self.text.into_inner() {
1748            Some(text) => text,
1749            None => format_uuid_text(&self.bytes),
1750        }
1751    }
1752
1753    /// True when display text has already been materialized.
1754    #[must_use]
1755    pub fn text_is_materialized(&self) -> bool {
1756        self.text.get().is_some()
1757    }
1758}
1759
1760impl PartialEq for ApplicationUuid {
1761    fn eq(&self, other: &Self) -> bool {
1762        self.bytes == other.bytes
1763    }
1764}
1765
1766impl Eq for ApplicationUuid {}
1767
1768impl From<[u8; 16]> for ApplicationUuid {
1769    fn from(bytes: [u8; 16]) -> Self {
1770        Self::from_bytes(bytes)
1771    }
1772}
1773
1774/// A bounded application value addressed only by contract names.
1775#[derive(Clone, Debug, Eq, PartialEq)]
1776pub enum ApplicationValue {
1777    /// Explicit null.
1778    Null,
1779    /// Boolean.
1780    Bool(bool),
1781    /// Signed integer.
1782    I64(i64),
1783    /// Unsigned integer.
1784    U64(u64),
1785    /// Exact fixed-scale decimal.
1786    Decimal {
1787        /// Minimal big-endian two's-complement coefficient.
1788        coefficient_twos_complement: Vec<u8>,
1789        /// Fractional scale.
1790        scale: u32,
1791        /// Optional declared precision assertion.
1792        precision: Option<u32>,
1793    },
1794    /// Currency-qualified exact decimal.
1795    Money {
1796        /// Three-letter currency code.
1797        currency: String,
1798        /// Exact amount.
1799        amount: Box<Self>,
1800    },
1801    /// Exact text.
1802    String(String),
1803    /// Canonical UUID (bytes form; display text is lazy).
1804    Uuid(ApplicationUuid),
1805    /// Contract enum variant name lowered without caller-visible numeric IDs.
1806    Enum(String),
1807    /// Compiler-generated stable enum identity. Application code uses the name.
1808    EnumIdentity {
1809        /// Stable enum type identifier pinned by the application lock.
1810        type_id: u32,
1811        /// Stable enum variant identifier pinned by the application lock.
1812        variant_id: u32,
1813        /// Symbolic variant name retained for checked presentation.
1814        name: String,
1815    },
1816    /// Opaque bytes.
1817    Bytes(Vec<u8>),
1818    /// Days since the Unix epoch.
1819    Date(i32),
1820    /// UTC timestamp.
1821    Timestamp {
1822        /// Whole seconds since the Unix epoch.
1823        seconds: i64,
1824        /// Nanosecond fraction.
1825        nanos: u32,
1826    },
1827    /// Canonical finite binary32 vector with a structurally bounded dimension.
1828    Vector(riffdb_types::CanonicalVector),
1829    /// Ordered bounded values.
1830    List(Vec<Self>),
1831    /// Name-addressed record.
1832    Record(BTreeMap<String, Self>),
1833}
1834
1835/// Closed population selected by an authoritative vector-state inspection.
1836#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1837pub enum VectorStateInspectionKind {
1838    /// Source-newer or missing embedding evidence.
1839    Stale,
1840    /// Embeddings produced by a non-current declared model version.
1841    OutdatedModel,
1842}
1843
1844/// One symbolic bounded vector-state inspection request.
1845#[derive(Clone, Debug, Eq, PartialEq)]
1846pub struct VectorStateInspection {
1847    contract: ApplicationContract,
1848    entity: String,
1849    field: String,
1850    partition: ApplicationValue,
1851    kind: VectorStateInspectionKind,
1852    limit: u32,
1853    cursor: Option<Vec<u8>>,
1854}
1855
1856impl VectorStateInspection {
1857    /// Creates one initial bounded inspection page.
1858    #[must_use]
1859    pub fn new(
1860        contract: ApplicationContract,
1861        entity: impl Into<String>,
1862        field: impl Into<String>,
1863        partition: ApplicationValue,
1864        kind: VectorStateInspectionKind,
1865        limit: u32,
1866    ) -> Self {
1867        Self {
1868            contract,
1869            entity: entity.into(),
1870            field: field.into(),
1871            partition,
1872            kind,
1873            limit,
1874            cursor: None,
1875        }
1876    }
1877
1878    /// Continues from one opaque server-issued cursor.
1879    #[must_use]
1880    pub fn after(mut self, cursor: Vec<u8>) -> Self {
1881        self.cursor = Some(cursor);
1882        self
1883    }
1884
1885    fn validate(&self) -> Result<(), ApplicationClientError> {
1886        validate_contract(&self.contract)?;
1887        if self.entity.is_empty()
1888            || self.entity.len() > 256
1889            || self.field.is_empty()
1890            || self.field.len() > 256
1891            || self.limit == 0
1892            || self.limit > 500
1893            || self
1894                .cursor
1895                .as_ref()
1896                .is_some_and(|cursor| cursor.len() != 16)
1897        {
1898            return Err(ApplicationClientError::InvalidInput);
1899        }
1900        Ok(())
1901    }
1902}
1903
1904/// Whole-partition staleness summary, returned only when policy permits counts.
1905#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1906pub struct VectorStalenessSummary {
1907    /// Total live entities covered by the authoritative observation.
1908    pub total_entities: u64,
1909    /// Source-stale live entities.
1910    pub stale_count: u64,
1911    /// Strict declared count threshold.
1912    pub stale_entity_count_threshold: u64,
1913    /// Whether `stale_count` strictly exceeds the threshold.
1914    pub slo_breached: bool,
1915}
1916
1917/// Whole-partition model-version summary, returned only when policy permits counts.
1918#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1919pub struct VectorModelVersionSummary {
1920    /// Embeddings carrying the current declared model identity and version.
1921    pub current_count: u64,
1922    /// Embeddings carrying another retained model identity or version.
1923    pub outdated_count: u64,
1924}
1925
1926/// One policy-visible stale entity observation.
1927#[derive(Clone, Eq, PartialEq)]
1928pub struct VectorStalenessItem {
1929    /// Opaque canonical entity key bytes.
1930    pub entity_key: Vec<u8>,
1931    /// Newest declared source-field write.
1932    pub newest_source_write: u64,
1933    /// Last embedding write, or absence when no embedding exists.
1934    pub embedding_write: Option<u64>,
1935}
1936
1937impl fmt::Debug for VectorStalenessItem {
1938    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1939        formatter
1940            .debug_struct("VectorStalenessItem")
1941            .field("entity_key", &"[REDACTED]")
1942            .field("newest_source_write", &self.newest_source_write)
1943            .field("embedding_write", &self.embedding_write)
1944            .finish()
1945    }
1946}
1947
1948/// One policy-visible outdated model observation.
1949#[derive(Clone, Eq, PartialEq)]
1950pub struct VectorModelVersionItem {
1951    /// Opaque canonical entity key bytes.
1952    pub entity_key: Vec<u8>,
1953    /// Bounded model identity.
1954    pub model: String,
1955    /// Bounded model version.
1956    pub model_version: String,
1957    /// Authoritative embedding write sequence.
1958    pub embedding_write: u64,
1959}
1960
1961impl fmt::Debug for VectorModelVersionItem {
1962    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1963        formatter
1964            .debug_struct("VectorModelVersionItem")
1965            .field("entity_key", &"[REDACTED]")
1966            .field("model", &"[REDACTED]")
1967            .field("model_version", &"[REDACTED]")
1968            .field("embedding_write", &self.embedding_write)
1969            .finish()
1970    }
1971}
1972
1973/// One bounded policy-filtered vector-state page.
1974#[derive(Clone, Debug, Eq, PartialEq)]
1975pub struct VectorInspectionPage<T> {
1976    /// Visible canonical items.
1977    pub items: Vec<T>,
1978    /// Opaque continuation cursor.
1979    pub next_cursor: Option<Vec<u8>>,
1980    /// Authoritative observation frontier, when one exists.
1981    pub observed_frontier: Option<u64>,
1982}
1983
1984/// Closed response shape. Count summaries and row-policy-filtered pages cannot
1985/// be confused or silently substituted.
1986#[derive(Clone, Debug, Eq, PartialEq)]
1987pub enum VectorStateInspectionResult {
1988    /// Whole-partition staleness counts.
1989    StalenessSummary(VectorStalenessSummary),
1990    /// Policy-filtered stale entities.
1991    StaleEntities(VectorInspectionPage<VectorStalenessItem>),
1992    /// Whole-partition model-version counts.
1993    ModelVersionSummary(VectorModelVersionSummary),
1994    /// Policy-filtered outdated embeddings.
1995    OutdatedModelEntities(VectorInspectionPage<VectorModelVersionItem>),
1996}
1997
1998impl TryFrom<app_v1::InspectVectorStateResponse> for VectorStateInspectionResult {
1999    type Error = ApplicationClientError;
2000
2001    fn try_from(response: app_v1::InspectVectorStateResponse) -> Result<Self, Self::Error> {
2002        use app_v1::inspect_vector_state_response::Result;
2003        Ok(
2004            match response
2005                .result
2006                .ok_or(ApplicationClientError::InvalidResponse)?
2007            {
2008                Result::StalenessSummary(report) => {
2009                    Self::StalenessSummary(VectorStalenessSummary {
2010                        total_entities: report.total_entities,
2011                        stale_count: report.stale_count,
2012                        stale_entity_count_threshold: report.stale_entity_count_threshold,
2013                        slo_breached: report.slo_breached,
2014                    })
2015                }
2016                Result::StaleEntities(page) => Self::StaleEntities(VectorInspectionPage {
2017                    items: page
2018                        .items
2019                        .into_iter()
2020                        .map(|item| VectorStalenessItem {
2021                            entity_key: item.entity_key,
2022                            newest_source_write: item.newest_source_write,
2023                            embedding_write: item.embedding_write,
2024                        })
2025                        .collect(),
2026                    next_cursor: page.next_cursor,
2027                    observed_frontier: page.observed_frontier,
2028                }),
2029                Result::ModelVersionSummary(report) => {
2030                    Self::ModelVersionSummary(VectorModelVersionSummary {
2031                        current_count: report.current_count,
2032                        outdated_count: report.outdated_count,
2033                    })
2034                }
2035                Result::OutdatedModelEntities(page) => {
2036                    Self::OutdatedModelEntities(VectorInspectionPage {
2037                        items: page
2038                            .items
2039                            .into_iter()
2040                            .map(|item| VectorModelVersionItem {
2041                                entity_key: item.entity_key,
2042                                model: item.model,
2043                                model_version: item.model_version,
2044                                embedding_write: item.embedding_write,
2045                            })
2046                            .collect(),
2047                        next_cursor: page.next_cursor,
2048                        observed_frontier: page.observed_frontier,
2049                    })
2050                }
2051            },
2052        )
2053    }
2054}
2055
2056/// Active or exact symbolic contract selection.
2057#[derive(Clone, Debug, Eq, PartialEq)]
2058pub enum ApplicationContract {
2059    /// Resolve the current active contract.
2060    Active,
2061    /// Resolve one exact retained contract.
2062    Exact {
2063        /// Contract lineage.
2064        lineage: String,
2065        /// Positive contract version.
2066        version: u64,
2067        /// Optional exact bundle hash.
2068        bundle_hash: Option<[u8; 32]>,
2069    },
2070}
2071
2072/// One named query invocation pinned optionally to an immutable module hash.
2073#[derive(Clone, Debug, Eq, PartialEq)]
2074pub struct NamedQuery {
2075    contract: ApplicationContract,
2076    name: String,
2077    module_hash: Option<[u8; 32]>,
2078    expected_plan_hash: Option<[u8; 32]>,
2079    parameters: BTreeMap<String, ApplicationValue>,
2080    cursor: Option<String>,
2081    minimum_application_head: Option<u64>,
2082    admission_head_consistency: bool,
2083    accept_packed_result_v1: bool,
2084}
2085
2086impl NamedQuery {
2087    /// Builds a name-addressed query call.
2088    pub fn new(
2089        contract: ApplicationContract,
2090        name: impl Into<String>,
2091        module_hash: Option<[u8; 32]>,
2092        parameters: BTreeMap<String, ApplicationValue>,
2093        cursor: Option<String>,
2094    ) -> Result<Self, ApplicationClientError> {
2095        let name = name.into();
2096        if name.is_empty() || name.len() > 256 || parameters.len() > 4_096 {
2097            return Err(ApplicationClientError::InvalidInput);
2098        }
2099        validate_contract(&contract)?;
2100        if parameters
2101            .iter()
2102            .any(|(name, _)| name.is_empty() || name.len() > 256)
2103        {
2104            return Err(ApplicationClientError::InvalidInput);
2105        }
2106        Ok(Self {
2107            contract,
2108            name,
2109            module_hash,
2110            expected_plan_hash: None,
2111            parameters,
2112            cursor,
2113            minimum_application_head: None,
2114            admission_head_consistency: false,
2115            accept_packed_result_v1: false,
2116        })
2117    }
2118
2119    /// Requires the server to return this exact compiler-owned query plan.
2120    #[must_use]
2121    pub const fn expect_plan_hash(mut self, plan_hash: [u8; 32]) -> Self {
2122        self.expected_plan_hash = Some(plan_hash);
2123        self
2124    }
2125
2126    /// Advertises the packed result arm for a compiler-covered generated query.
2127    #[doc(hidden)]
2128    #[must_use]
2129    pub const fn accept_packed_result_v1(mut self) -> Self {
2130        self.accept_packed_result_v1 = true;
2131        self
2132    }
2133
2134    /// Applies generated pagination and read-after-commit options.
2135    pub fn with_options(mut self, options: QueryOptions) -> Result<Self, ApplicationClientError> {
2136        if options.read_after_commit == Some(0) {
2137            return Err(ApplicationClientError::InvalidInput);
2138        }
2139        self.cursor = options.cursor;
2140        self.minimum_application_head = options.read_after_commit;
2141        self.admission_head_consistency = options.admission_head;
2142        Ok(self)
2143    }
2144}
2145
2146/// Typed execution options shared by every generated named query.
2147#[derive(Clone, Debug, Default, Eq, PartialEq)]
2148pub struct QueryOptions {
2149    cursor: Option<String>,
2150    read_after_commit: Option<u64>,
2151    admission_head: bool,
2152}
2153
2154impl QueryOptions {
2155    /// Creates default query options.
2156    #[must_use]
2157    pub const fn new() -> Self {
2158        Self {
2159            cursor: None,
2160            read_after_commit: None,
2161            admission_head: false,
2162        }
2163    }
2164
2165    /// Continues from one opaque application cursor.
2166    #[must_use]
2167    pub fn after(mut self, cursor: impl Into<String>) -> Self {
2168        self.cursor = Some(cursor.into());
2169        self
2170    }
2171
2172    /// Routes one compiler-typed generated cursor without overriding a low-level option.
2173    #[doc(hidden)]
2174    pub fn with_generated_cursor(
2175        mut self,
2176        cursor: Option<String>,
2177    ) -> Result<Self, ApplicationClientError> {
2178        if self.cursor.is_some() && cursor.is_some() {
2179            return Err(ApplicationClientError::InvalidInput);
2180        }
2181        if cursor.is_some() {
2182            self.cursor = cursor;
2183        }
2184        Ok(self)
2185    }
2186
2187    /// Requires a snapshot at or after one observed application commit.
2188    #[must_use]
2189    pub const fn read_after_commit(mut self, commit_sequence: u64) -> Self {
2190        self.read_after_commit = Some(commit_sequence);
2191        self
2192    }
2193
2194    /// Requires a snapshot or provider epoch at least as recent as the
2195    /// authoritative application head observed after server admission.
2196    #[must_use]
2197    pub const fn at_least_admission_head(mut self) -> Self {
2198        self.admission_head = true;
2199        self
2200    }
2201}
2202
2203/// Typed generated result with its snapshot and pagination metadata.
2204#[derive(Clone, Debug, Eq, PartialEq)]
2205pub struct TypedQueryResult<T> {
2206    /// Generated declared-result value.
2207    pub value: T,
2208    /// Exact returned identity, verified against the generated request.
2209    pub identity: QueryResponseIdentity,
2210    /// Authoritative application head observed by the one-snapshot read.
2211    pub application_head: u64,
2212    /// Opaque continuation cursor, when another bounded page exists.
2213    pub next_cursor: Option<String>,
2214}
2215
2216/// Typed generated command result without kernel protocol exposure.
2217#[derive(Clone, Debug, Eq, PartialEq)]
2218pub struct TypedCommandResult<T> {
2219    /// Generated declared business outcome.
2220    pub outcome: T,
2221    /// Durable application commit sequence.
2222    pub commit_sequence: Option<u64>,
2223    /// Exact contract version used by execution.
2224    pub contract_version: u64,
2225    /// Exact compiler-owned command plan used by execution.
2226    pub plan_hash: [u8; 32],
2227    /// Whether the invocation replayed an already durable result.
2228    pub replayed: bool,
2229    /// Durable opaque outcome locator, when available.
2230    pub outcome_uri: Option<String>,
2231    /// Compiler-derived successor revisions for successful checked workflow
2232    /// mutations, keyed by source binding rather than numeric entity IDs.
2233    pub workflow_revisions: Vec<crate::generated::WorkflowSuccessorRevision>,
2234}
2235
2236/// One symbolic command invocation with only name-addressed input.
2237#[derive(Clone, Debug, Eq, PartialEq)]
2238pub struct ApplicationCommand {
2239    name: String,
2240    expected_contract_version: Option<u64>,
2241    input: BTreeMap<String, ApplicationValue>,
2242}
2243
2244impl ApplicationCommand {
2245    /// Builds a command invocation.
2246    pub fn new(
2247        name: impl Into<String>,
2248        expected_contract_version: Option<u64>,
2249        input: BTreeMap<String, ApplicationValue>,
2250    ) -> Result<Self, ApplicationClientError> {
2251        let name = name.into();
2252        if name.is_empty()
2253            || name.len() > 256
2254            || expected_contract_version == Some(0)
2255            || input.is_empty()
2256            || input.len() > 4_096
2257            || input
2258                .keys()
2259                .any(|field| field.is_empty() || field.len() > 256)
2260        {
2261            return Err(ApplicationClientError::InvalidInput);
2262        }
2263        Ok(Self {
2264            name,
2265            expected_contract_version,
2266            input,
2267        })
2268    }
2269
2270    pub(crate) fn into_idempotent_command(
2271        self,
2272    ) -> Result<IdempotentCommand, ApplicationClientError> {
2273        let input = lower_value(ApplicationValue::Record(self.input))?;
2274        IdempotentCommand::new(self.name, self.expected_contract_version, input)
2275            .map_err(|_| ApplicationClientError::InvalidInput)
2276    }
2277}
2278
2279/// Query result cardinality declared in RiffQL.
2280#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2281pub enum ApplicationCardinality {
2282    /// Exactly one record.
2283    One,
2284    /// Zero or one record.
2285    Maybe,
2286    /// Bounded records.
2287    Many,
2288}
2289
2290/// One name-addressed returned record.
2291#[derive(Clone, Debug, Eq, PartialEq)]
2292pub struct ApplicationRecord {
2293    /// Optional entity symbol.
2294    pub entity: String,
2295    /// Fields by contract symbol.
2296    pub fields: BTreeMap<String, ApplicationValue>,
2297}
2298
2299/// One top-level query result field.
2300#[derive(Clone, Debug, Eq, PartialEq)]
2301pub struct ApplicationResultField {
2302    /// Declared cardinality.
2303    pub cardinality: ApplicationCardinality,
2304    /// Returned records.
2305    pub records: Vec<ApplicationRecord>,
2306}
2307
2308/// Complete one-snapshot named query result.
2309#[derive(Clone, Debug, Eq, PartialEq)]
2310pub struct NamedQueryResult {
2311    /// Exact query outcome name.
2312    pub outcome: String,
2313    /// Authoritative snapshot head.
2314    pub application_head: u64,
2315    /// Result fields by declared name.
2316    pub fields: BTreeMap<String, ApplicationResultField>,
2317    /// Opaque continuation cursor.
2318    pub next_cursor: Option<String>,
2319    /// Exact symbolic identity used by named execution.
2320    pub identity: QueryResponseIdentity,
2321}
2322
2323/// Exact server-returned identity for one named query execution.
2324#[derive(Clone, Debug, Eq, PartialEq)]
2325pub struct QueryResponseIdentity {
2326    /// Exact contract lineage.
2327    pub contract_lineage: String,
2328    /// Exact contract version.
2329    pub contract_version: u64,
2330    /// Exact contract bundle hash.
2331    pub contract_bundle_hash: [u8; 32],
2332    /// Exact deployed query module hash.
2333    pub module_hash: [u8; 32],
2334    /// Exact query operation name.
2335    pub query_name: String,
2336    /// Exact compiler-owned query plan hash.
2337    pub plan_hash: [u8; 32],
2338}
2339
2340/// Hard upper bound on streamed continuation pages per cursor stream (`ADR-0339`).
2341pub const MAX_STREAMED_QUERY_PAGES: u32 = 1_024;
2342
2343enum NamedQueryStreamClient<'a> {
2344    Stable(&'a mut StableApplicationClient),
2345    Direct(&'a mut RiffDbClient),
2346}
2347
2348/// Bounded multi-page continuation stream over a named query (`ADR-0339`).
2349pub struct NamedQueryPageStream<'a> {
2350    client: NamedQueryStreamClient<'a>,
2351    base_query: NamedQuery,
2352    metadata: &'a CallMetadata,
2353    pinned_identity: Option<QueryResponseIdentity>,
2354    pinned_head: Option<u64>,
2355    next_cursor: Option<String>,
2356    pages_emitted: u32,
2357    max_pages: u32,
2358    exhausted: bool,
2359}
2360
2361impl<'a> NamedQueryPageStream<'a> {
2362    fn new_stable(
2363        client: &'a mut StableApplicationClient,
2364        query: NamedQuery,
2365        metadata: &'a CallMetadata,
2366    ) -> Self {
2367        let initial_cursor = query.cursor.clone();
2368        Self {
2369            client: NamedQueryStreamClient::Stable(client),
2370            base_query: query,
2371            metadata,
2372            pinned_identity: None,
2373            pinned_head: None,
2374            next_cursor: initial_cursor,
2375            pages_emitted: 0,
2376            max_pages: MAX_STREAMED_QUERY_PAGES,
2377            exhausted: false,
2378        }
2379    }
2380
2381    fn new_direct(
2382        client: &'a mut RiffDbClient,
2383        query: NamedQuery,
2384        metadata: &'a CallMetadata,
2385    ) -> Self {
2386        let initial_cursor = query.cursor.clone();
2387        Self {
2388            client: NamedQueryStreamClient::Direct(client),
2389            base_query: query,
2390            metadata,
2391            pinned_identity: None,
2392            pinned_head: None,
2393            next_cursor: initial_cursor,
2394            pages_emitted: 0,
2395            max_pages: MAX_STREAMED_QUERY_PAGES,
2396            exhausted: false,
2397        }
2398    }
2399
2400    /// Bounds the maximum number of pages this stream will yield (clamped to `1..=MAX_STREAMED_QUERY_PAGES`).
2401    #[must_use]
2402    pub fn with_max_pages(mut self, max_pages: u32) -> Self {
2403        self.max_pages = max_pages.clamp(1, MAX_STREAMED_QUERY_PAGES);
2404        self
2405    }
2406
2407    /// Number of pages yielded so far.
2408    #[must_use]
2409    pub const fn pages_emitted(&self) -> u32 {
2410        self.pages_emitted
2411    }
2412
2413    /// Pinned snapshot `application_head` established by the first page.
2414    #[must_use]
2415    pub const fn pinned_application_head(&self) -> Option<u64> {
2416        self.pinned_head
2417    }
2418
2419    /// Fetches the next bounded page in the cursor chain, or `Ok(None)` when complete.
2420    pub async fn next_page(&mut self) -> Result<Option<NamedQueryResult>, ApplicationClientError> {
2421        if self.exhausted {
2422            return Ok(None);
2423        }
2424        if self.pages_emitted >= self.max_pages {
2425            self.exhausted = true;
2426            return Err(ApplicationClientError::InvalidInput);
2427        }
2428        let mut request = self.base_query.clone();
2429        if self.pages_emitted > 0 {
2430            request.cursor = self.next_cursor.clone();
2431            if let Some(pinned_head) = self.pinned_head {
2432                request.minimum_application_head = Some(
2433                    request
2434                        .minimum_application_head
2435                        .map_or(pinned_head, |min| min.max(pinned_head)),
2436                );
2437            }
2438        }
2439        let page = match &mut self.client {
2440            NamedQueryStreamClient::Stable(client) => {
2441                client.execute_named_query(request, self.metadata).await?
2442            }
2443            NamedQueryStreamClient::Direct(client) => {
2444                client
2445                    .execute_named_application_query(request, self.metadata)
2446                    .await?
2447            }
2448        };
2449        if let Some(expected_identity) = &self.pinned_identity {
2450            if &page.identity != expected_identity
2451                || self.pinned_head != Some(page.application_head)
2452            {
2453                self.exhausted = true;
2454                return Err(ApplicationClientError::InvalidResponse);
2455            }
2456        } else {
2457            self.pinned_identity = Some(page.identity.clone());
2458            self.pinned_head = Some(page.application_head);
2459        }
2460        self.pages_emitted = self.pages_emitted.saturating_add(1);
2461        match page.next_cursor.clone() {
2462            Some(cursor) => {
2463                self.next_cursor = Some(cursor);
2464            }
2465            None => {
2466                self.next_cursor = None;
2467                self.exhausted = true;
2468            }
2469        }
2470        Ok(Some(page))
2471    }
2472
2473    /// Collects all remaining pages up to the configured page bound.
2474    pub async fn collect_pages(mut self) -> Result<Vec<NamedQueryResult>, ApplicationClientError> {
2475        let mut pages = Vec::new();
2476        while let Some(page) = self.next_page().await? {
2477            pages.push(page);
2478        }
2479        Ok(pages)
2480    }
2481}
2482
2483/// Bounded multi-page continuation stream over a generated query (`ADR-0339`).
2484pub struct GeneratedQueryPageStream<'a, Q> {
2485    client: &'a mut StableApplicationClient,
2486    query: Q,
2487    options: QueryOptions,
2488    metadata: &'a CallMetadata,
2489    pinned_identity: Option<QueryResponseIdentity>,
2490    pinned_head: Option<u64>,
2491    next_cursor: Option<String>,
2492    pages_emitted: u32,
2493    max_pages: u32,
2494    exhausted: bool,
2495}
2496
2497impl<'a, Q: GeneratedQuery + Clone> GeneratedQueryPageStream<'a, Q> {
2498    fn new(
2499        client: &'a mut StableApplicationClient,
2500        query: Q,
2501        options: QueryOptions,
2502        metadata: &'a CallMetadata,
2503    ) -> Self {
2504        let initial_cursor = options.cursor.clone();
2505        Self {
2506            client,
2507            query,
2508            options,
2509            metadata,
2510            pinned_identity: None,
2511            pinned_head: None,
2512            next_cursor: initial_cursor,
2513            pages_emitted: 0,
2514            max_pages: MAX_STREAMED_QUERY_PAGES,
2515            exhausted: false,
2516        }
2517    }
2518
2519    /// Bounds the maximum number of pages this stream will yield (clamped to `1..=MAX_STREAMED_QUERY_PAGES`).
2520    #[must_use]
2521    pub fn with_max_pages(mut self, max_pages: u32) -> Self {
2522        self.max_pages = max_pages.clamp(1, MAX_STREAMED_QUERY_PAGES);
2523        self
2524    }
2525
2526    /// Number of pages yielded so far.
2527    #[must_use]
2528    pub const fn pages_emitted(&self) -> u32 {
2529        self.pages_emitted
2530    }
2531
2532    /// Pinned snapshot `application_head` established by the first page.
2533    #[must_use]
2534    pub const fn pinned_application_head(&self) -> Option<u64> {
2535        self.pinned_head
2536    }
2537
2538    /// Fetches the next bounded typed page in the cursor chain, or `Ok(None)` when complete.
2539    pub async fn next_page(
2540        &mut self,
2541    ) -> Result<Option<TypedQueryResult<Q::Output>>, ApplicationClientError> {
2542        if self.exhausted {
2543            return Ok(None);
2544        }
2545        if self.pages_emitted >= self.max_pages {
2546            self.exhausted = true;
2547            return Err(ApplicationClientError::InvalidInput);
2548        }
2549        let mut page_options = self.options.clone();
2550        if self.pages_emitted > 0 {
2551            page_options.cursor = self.next_cursor.clone();
2552        }
2553        let page = self
2554            .client
2555            .execute_generated_query(self.query.clone(), page_options, self.metadata)
2556            .await?;
2557        if let Some(expected_identity) = &self.pinned_identity {
2558            if &page.identity != expected_identity
2559                || self.pinned_head != Some(page.application_head)
2560            {
2561                self.exhausted = true;
2562                return Err(ApplicationClientError::InvalidResponse);
2563            }
2564        } else {
2565            self.pinned_identity = Some(page.identity.clone());
2566            self.pinned_head = Some(page.application_head);
2567        }
2568        self.pages_emitted = self.pages_emitted.saturating_add(1);
2569        match page.next_cursor.clone() {
2570            Some(cursor) => {
2571                self.next_cursor = Some(cursor);
2572            }
2573            None => {
2574                self.next_cursor = None;
2575                self.exhausted = true;
2576            }
2577        }
2578        Ok(Some(page))
2579    }
2580
2581    /// Collects all remaining typed pages up to the configured page bound.
2582    pub async fn collect_pages(
2583        mut self,
2584    ) -> Result<Vec<TypedQueryResult<Q::Output>>, ApplicationClientError> {
2585        let mut pages = Vec::new();
2586        while let Some(page) = self.next_page().await? {
2587            pages.push(page);
2588        }
2589        Ok(pages)
2590    }
2591}
2592
2593/// Successful command completion without kernel protocol details.
2594#[derive(Clone, Debug, Eq, PartialEq)]
2595pub struct ApplicationCommandResult {
2596    /// Declared business outcome name when present.
2597    pub outcome: Option<String>,
2598    /// Complete name-addressed declared outcome payload.
2599    pub outcome_value: Option<ApplicationValue>,
2600    /// Application commit sequence; absent for unjournaled read-only commands.
2601    pub commit_sequence: Option<u64>,
2602    /// Exact contract version used by the command.
2603    pub contract_version: u64,
2604    /// Exact command plan hash used by the command.
2605    pub plan_hash: [u8; 32],
2606    /// Whether this invocation replayed an already durable result.
2607    pub replayed: bool,
2608    /// Durable outcome locator when present.
2609    pub outcome_uri: Option<String>,
2610}
2611
2612pub(crate) fn raise_application_command_result(
2613    response: v1::ExecuteCommandResponse,
2614) -> Result<ApplicationCommandResult, ApplicationClientError> {
2615    Ok(ApplicationCommandResult {
2616        outcome: (!response.outcome_type.is_empty()).then_some(response.outcome_type),
2617        outcome_value: response.outcome.map(raise_value).transpose()?,
2618        commit_sequence: (response.commit_sequence != 0).then_some(response.commit_sequence),
2619        contract_version: response.contract_version,
2620        plan_hash: response
2621            .plan_hash
2622            .try_into()
2623            .map_err(|_| ApplicationClientError::InvalidResponse)?,
2624        replayed: response.status
2625            == v1::execute_command_response::CompletionStatus::Replayed as i32,
2626        outcome_uri: response.outcome_uri,
2627    })
2628}
2629
2630/// Closed application-client failure.
2631#[derive(Debug)]
2632pub enum ApplicationClientError {
2633    /// Submitted name-addressed shape is invalid.
2634    InvalidInput,
2635    /// Server returned an invalid or low-level-shaped application response.
2636    InvalidResponse,
2637    /// Request identity generation failed.
2638    IdentifierUnavailable,
2639    /// Checked public transport failure.
2640    Client(ClientError),
2641}
2642
2643impl fmt::Display for ApplicationClientError {
2644    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2645        match self {
2646            Self::InvalidInput => formatter.write_str("application input is invalid"),
2647            Self::InvalidResponse => formatter.write_str("application response is invalid"),
2648            Self::IdentifierUnavailable => formatter.write_str("request identity is unavailable"),
2649            Self::Client(error) => error.fmt(formatter),
2650        }
2651    }
2652}
2653
2654impl std::error::Error for ApplicationClientError {
2655    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2656        match self {
2657            Self::Client(error) => Some(error),
2658            Self::InvalidInput | Self::InvalidResponse | Self::IdentifierUnavailable => None,
2659        }
2660    }
2661}
2662
2663impl ApplicationClientError {
2664    /// Returns the checked semantic application failure, when supplied by RiffDB.
2665    #[must_use]
2666    pub const fn semantic_error(&self) -> Option<&riffdb_errors::ApplicationError> {
2667        match self {
2668            Self::Client(error) => error.application_error(),
2669            Self::InvalidInput | Self::InvalidResponse | Self::IdentifierUnavailable => None,
2670        }
2671    }
2672}
2673
2674impl From<ClientError> for ApplicationClientError {
2675    fn from(error: ClientError) -> Self {
2676        Self::Client(error)
2677    }
2678}
2679
2680impl From<GeneratedExecutionError> for ApplicationClientError {
2681    fn from(error: GeneratedExecutionError) -> Self {
2682        match error {
2683            GeneratedExecutionError::Client(error) => Self::Client(error),
2684            // An input the caller built wrongly and an outcome the server sent
2685            // wrongly are different faults with different fixes. Reporting the
2686            // first as `InvalidResponse` sends callers to audit the decoder for
2687            // a mistake that is in their own request.
2688            GeneratedExecutionError::CommandShape(
2689                crate::generated::GeneratedCommandError::InvalidInputShape
2690                | crate::generated::GeneratedCommandError::InputBudget(_),
2691            ) => Self::InvalidInput,
2692            GeneratedExecutionError::CommandShape(
2693                crate::generated::GeneratedCommandError::InvalidOutcomeShape,
2694            ) => Self::InvalidResponse,
2695        }
2696    }
2697}
2698
2699impl RiffDbClient {
2700    /// Executes one named module query through one public application RPC.
2701    pub async fn execute_named_application_query(
2702        &mut self,
2703        query: NamedQuery,
2704        metadata: &CallMetadata,
2705    ) -> Result<NamedQueryResult, ApplicationClientError> {
2706        let response =
2707            with_client_wire_carrier(self.execute_named_application_query_wire(query, metadata))
2708                .await?;
2709        raise_query_result_from_client_wire(response)
2710    }
2711
2712    /// Opens a bounded multi-page continuation stream over a named query (`ADR-0339`).
2713    #[must_use]
2714    pub fn stream_named_application_query<'a>(
2715        &'a mut self,
2716        query: NamedQuery,
2717        metadata: &'a CallMetadata,
2718    ) -> NamedQueryPageStream<'a> {
2719        NamedQueryPageStream::new_direct(self, query, metadata)
2720    }
2721
2722    async fn execute_named_application_query_wire(
2723        &mut self,
2724        query: NamedQuery,
2725        metadata: &CallMetadata,
2726    ) -> Result<app_v1::ExecuteQueryResponse, ApplicationClientError> {
2727        let expected_contract = query.contract.clone();
2728        let expected_name = query.name.clone();
2729        let expected_module_hash = query.module_hash;
2730        let expected_plan_hash = query.expected_plan_hash;
2731        let request_id = Vec::from(
2732            generate_request_id()
2733                .map_err(|_| ApplicationClientError::IdentifierUnavailable)?
2734                .into_bytes(),
2735        );
2736        // Move owned parameter names once; avoid intermediate (name, value) copies.
2737        let mut parameters = Vec::with_capacity(query.parameters.len());
2738        for (name, value) in query.parameters {
2739            parameters.push(app_v1::Parameter {
2740                name,
2741                value: Some(lower_value(value)?),
2742            });
2743        }
2744        let response = self
2745            .execute_selected_query_transport(
2746                app_v1::ExecuteQueryRequest {
2747                    contract: lower_contract(query.contract),
2748                    query: Some(app_v1::execute_query_request::Query::QueryName(query.name)),
2749                    module_hash: query.module_hash.map(|hash| hash.to_vec()),
2750                    parameters,
2751                    cursor: query.cursor,
2752                    minimum_application_head: query.minimum_application_head,
2753                    accepted_result_encodings: if query.accept_packed_result_v1 {
2754                        vec![
2755                            app_v1::NamedResultEncoding::LegacyRecords as i32,
2756                            app_v1::NamedResultEncoding::CompactV1 as i32,
2757                            app_v1::NamedResultEncoding::PackedV1 as i32,
2758                        ]
2759                    } else {
2760                        vec![
2761                            app_v1::NamedResultEncoding::LegacyRecords as i32,
2762                            app_v1::NamedResultEncoding::CompactV1 as i32,
2763                        ]
2764                    },
2765                    consistency: if query.admission_head_consistency {
2766                        app_v1::QueryConsistency::AdmissionHead as i32
2767                    } else {
2768                        app_v1::QueryConsistency::Unspecified as i32
2769                    },
2770                    request_id,
2771                },
2772                metadata,
2773            )
2774            .await?;
2775        validate_query_response_identity(
2776            &response,
2777            &expected_contract,
2778            &expected_name,
2779            expected_module_hash,
2780            expected_plan_hash,
2781        )?;
2782        Ok(response)
2783    }
2784
2785    /// Executes one symbolic command with bounded retry and no kernel-shaped caller input.
2786    pub async fn execute_application_command(
2787        &mut self,
2788        command: ApplicationCommand,
2789        attempts: AttemptBudget,
2790        metadata: &CallMetadata,
2791    ) -> Result<ApplicationCommandResult, ApplicationClientError> {
2792        let command_name = command.name.clone();
2793        let command = command.into_idempotent_command()?;
2794        let response = self
2795            .execute_with_retry(&command, attempts, metadata)
2796            .await
2797            .map_err(|error| contextualize_command_client_error(error, &command_name))?;
2798        raise_application_command_result(response)
2799    }
2800}
2801
2802pub(crate) fn contextualize_command_client_error(
2803    error: ClientError,
2804    command_name: &str,
2805) -> ClientError {
2806    let ClientError::Public(public) = error else {
2807        return error;
2808    };
2809    let context = ApplicationErrorContext::empty()
2810        .with_operation_symbol(command_name.to_owned())
2811        .unwrap_or_else(|_| ApplicationErrorContext::empty());
2812    ClientError::Application(Box::new(ApplicationError::from_public_error(
2813        &public,
2814        ApplicationOperation::ExecuteCommand,
2815        context,
2816    )))
2817}
2818
2819fn validate_pinned_query_response(
2820    response: &app_v1::ExecuteQueryResponse,
2821    pinned: &PinnedContractIdentity,
2822) -> Result<(), ApplicationClientError> {
2823    let identity = response
2824        .identity
2825        .as_ref()
2826        .ok_or(ApplicationClientError::InvalidResponse)?;
2827    if identity.contract_lineage != pinned.lineage
2828        || identity.contract_version != pinned.version
2829        || identity.contract_bundle_hash.as_slice() != pinned.bundle_hash
2830    {
2831        return Err(ApplicationClientError::InvalidResponse);
2832    }
2833    Ok(())
2834}
2835
2836const fn client_error_triggers_standby_failover(error: &ClientError) -> bool {
2837    match error {
2838        ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
2839        | ClientError::ConnectionFailure
2840        | ClientError::OutcomeUnknown(_) => true,
2841        ClientError::Public(public) => matches!(
2842            public.kind(),
2843            PublicErrorKind::PrimaryFenced
2844                | PublicErrorKind::FollowerMode
2845                | PublicErrorKind::StorageUnavailable
2846        ),
2847        ClientError::Application(application) => matches!(
2848            application.code(),
2849            ApplicationErrorCode::PrimaryFenced
2850                | ApplicationErrorCode::FollowerMode
2851                | ApplicationErrorCode::StorageUnavailable
2852                | ApplicationErrorCode::OutcomeUnknown
2853        ),
2854        ClientError::Protocol(_)
2855        | ClientError::IdentifierGeneration(_)
2856        | ClientError::Tls(_)
2857        | ClientError::DetailsFree(_) => false,
2858    }
2859}
2860
2861const fn application_query_error_allows_replica_fallback(error: &ApplicationClientError) -> bool {
2862    match error {
2863        ApplicationClientError::Client(client) => match client {
2864            ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
2865            | ClientError::ConnectionFailure
2866            | ClientError::OutcomeUnknown(_) => true,
2867            ClientError::Public(public) => matches!(
2868                public.kind(),
2869                PublicErrorKind::FollowerMode
2870                    | PublicErrorKind::PrimaryFenced
2871                    | PublicErrorKind::StorageUnavailable
2872                    | PublicErrorKind::Overloaded
2873            ),
2874            ClientError::Application(application) => matches!(
2875                application.code(),
2876                ApplicationErrorCode::FreshnessUnsatisfied
2877                    | ApplicationErrorCode::SnapshotRetired
2878                    | ApplicationErrorCode::ProjectionDiverged
2879                    | ApplicationErrorCode::FollowerMode
2880                    | ApplicationErrorCode::PrimaryFenced
2881                    | ApplicationErrorCode::StorageUnavailable
2882                    | ApplicationErrorCode::Overloaded
2883            ),
2884            ClientError::Protocol(_)
2885            | ClientError::IdentifierGeneration(_)
2886            | ClientError::Tls(_)
2887            | ClientError::DetailsFree(_) => false,
2888        },
2889        ApplicationClientError::InvalidInput
2890        | ApplicationClientError::InvalidResponse
2891        | ApplicationClientError::IdentifierUnavailable => false,
2892    }
2893}
2894
2895fn validate_query_response_identity(
2896    response: &app_v1::ExecuteQueryResponse,
2897    contract: &ApplicationContract,
2898    query_name: &str,
2899    module_hash: Option<[u8; 32]>,
2900    plan_hash: Option<[u8; 32]>,
2901) -> Result<(), ApplicationClientError> {
2902    let identity = response
2903        .identity
2904        .as_ref()
2905        .ok_or(ApplicationClientError::InvalidResponse)?;
2906    if identity.query_name.as_deref() != Some(query_name)
2907        || module_hash
2908            .is_some_and(|expected| identity.module_hash.as_deref() != Some(expected.as_slice()))
2909        || plan_hash.is_some_and(|expected| identity.plan_hash.as_slice() != expected.as_slice())
2910    {
2911        return Err(ApplicationClientError::InvalidResponse);
2912    }
2913    if let ApplicationContract::Exact {
2914        lineage,
2915        version,
2916        bundle_hash,
2917    } = contract
2918        && (identity.contract_lineage != *lineage
2919            || identity.contract_version != *version
2920            || bundle_hash.is_some_and(|expected| {
2921                identity.contract_bundle_hash.as_slice() != expected.as_slice()
2922            }))
2923    {
2924        return Err(ApplicationClientError::InvalidResponse);
2925    }
2926    Ok(())
2927}
2928
2929fn raise_application_catalog_preflight(
2930    response: app_v1::GetApplicationCatalogResponse,
2931    contract: &ApplicationContract,
2932) -> Result<ApplicationCatalogPreflight, ApplicationClientError> {
2933    if response.schema != APPLICATION_CATALOG_SCHEMA_V1
2934        || response.contract_lineage.is_empty()
2935        || response.contract_version == 0
2936    {
2937        return Err(ApplicationClientError::InvalidResponse);
2938    }
2939    let contract_bundle_hash: [u8; 32] = response
2940        .contract_bundle_hash
2941        .try_into()
2942        .map_err(|_| ApplicationClientError::InvalidResponse)?;
2943    if let ApplicationContract::Exact {
2944        lineage,
2945        version,
2946        bundle_hash,
2947    } = contract
2948        && (response.contract_lineage != *lineage
2949            || response.contract_version != *version
2950            || bundle_hash.is_some_and(|expected| expected != contract_bundle_hash))
2951    {
2952        return Err(ApplicationClientError::InvalidResponse);
2953    }
2954
2955    let mut query_module_hashes = Vec::with_capacity(response.query_module_hashes.len());
2956    for hash in response.query_module_hashes {
2957        query_module_hashes.push(
2958            hash.try_into()
2959                .map_err(|_| ApplicationClientError::InvalidResponse)?,
2960        );
2961    }
2962    if query_module_hashes
2963        .windows(2)
2964        .any(|pair| pair[0] >= pair[1])
2965    {
2966        return Err(ApplicationClientError::InvalidResponse);
2967    }
2968
2969    let mut features = Vec::with_capacity(response.features.len());
2970    for view in response.features {
2971        let feature = match app_v1::ApplicationCatalogFeature::try_from(view.feature) {
2972            Ok(app_v1::ApplicationCatalogFeature::OperationalOptionalPredicates) => {
2973                ApplicationCatalogFeature::OperationalOptionalPredicates
2974            }
2975            Ok(app_v1::ApplicationCatalogFeature::StableCursorPages) => {
2976                ApplicationCatalogFeature::StableCursorPages
2977            }
2978            Ok(app_v1::ApplicationCatalogFeature::NullExistencePredicates) => {
2979                ApplicationCatalogFeature::NullExistencePredicates
2980            }
2981            Ok(app_v1::ApplicationCatalogFeature::BinaryTextPrefix) => {
2982                ApplicationCatalogFeature::BinaryTextPrefix
2983            }
2984            Ok(app_v1::ApplicationCatalogFeature::UnicodeFoldTextPrefixV1) => {
2985                ApplicationCatalogFeature::UnicodeFoldTextPrefixV1
2986            }
2987            Ok(app_v1::ApplicationCatalogFeature::ExactAggregates) => {
2988                ApplicationCatalogFeature::ExactAggregates
2989            }
2990            Ok(app_v1::ApplicationCatalogFeature::Unspecified) | Err(_) => {
2991                return Err(ApplicationClientError::InvalidResponse);
2992            }
2993        };
2994        let state = match app_v1::ApplicationCatalogFeatureState::try_from(view.state) {
2995            Ok(app_v1::ApplicationCatalogFeatureState::Available) => {
2996                ApplicationCatalogFeatureState::Available
2997            }
2998            Ok(app_v1::ApplicationCatalogFeatureState::Unavailable) => {
2999                ApplicationCatalogFeatureState::Unavailable
3000            }
3001            Ok(app_v1::ApplicationCatalogFeatureState::Unspecified) | Err(_) => {
3002                return Err(ApplicationClientError::InvalidResponse);
3003            }
3004        };
3005        features.push(ApplicationCatalogFeatureView { feature, state });
3006    }
3007    if features.len() != 6
3008        || features
3009            .windows(2)
3010            .any(|pair| pair[0].feature >= pair[1].feature)
3011    {
3012        return Err(ApplicationClientError::InvalidResponse);
3013    }
3014
3015    Ok(ApplicationCatalogPreflight {
3016        contract_lineage: response.contract_lineage,
3017        contract_version: response.contract_version,
3018        contract_bundle_hash,
3019        query_module_hashes,
3020        features,
3021    })
3022}
3023
3024pub(crate) fn validate_contract(
3025    contract: &ApplicationContract,
3026) -> Result<(), ApplicationClientError> {
3027    if let ApplicationContract::Exact {
3028        lineage, version, ..
3029    } = contract
3030        && (lineage.is_empty() || lineage.len() > 256 || *version == 0)
3031    {
3032        return Err(ApplicationClientError::InvalidInput);
3033    }
3034    Ok(())
3035}
3036
3037fn lower_contract(contract: ApplicationContract) -> Option<app_v1::ContractSelector> {
3038    match contract {
3039        ApplicationContract::Active => None,
3040        ApplicationContract::Exact {
3041            lineage,
3042            version,
3043            bundle_hash,
3044        } => Some(app_v1::ContractSelector {
3045            lineage,
3046            version,
3047            bundle_hash: bundle_hash.map_or_else(Vec::new, |hash| hash.to_vec()),
3048        }),
3049    }
3050}
3051
3052pub(crate) fn lower_value(value: ApplicationValue) -> Result<v1::Value, ApplicationClientError> {
3053    use v1::value::Kind;
3054    let kind = match value {
3055        ApplicationValue::Null => Kind::NullValue(v1::NullValue::NullValue as i32),
3056        ApplicationValue::Bool(value) => Kind::BoolValue(value),
3057        ApplicationValue::I64(value) => Kind::I64Value(value),
3058        ApplicationValue::U64(value) => Kind::U64Value(value),
3059        ApplicationValue::Decimal {
3060            coefficient_twos_complement,
3061            scale,
3062            precision,
3063        } => Kind::DecimalValue(v1::Decimal {
3064            coefficient_twos_complement,
3065            scale,
3066            precision,
3067        }),
3068        ApplicationValue::Money { currency, amount } => {
3069            let Kind::DecimalValue(amount) = lower_value(*amount)?
3070                .kind
3071                .ok_or(ApplicationClientError::InvalidInput)?
3072            else {
3073                return Err(ApplicationClientError::InvalidInput);
3074            };
3075            Kind::MoneyValue(v1::Money {
3076                currency,
3077                amount: Some(amount),
3078            })
3079        }
3080        ApplicationValue::String(value) => Kind::StringValue(value),
3081        ApplicationValue::Uuid(value) => Kind::UuidValue(value.as_bytes().to_vec()),
3082        ApplicationValue::Enum(name) if !name.is_empty() && name.len() <= 256 => {
3083            Kind::EnumValue(v1::EnumValue {
3084                type_id: 0,
3085                variant_id: 0,
3086                name,
3087            })
3088        }
3089        ApplicationValue::Enum(_) => return Err(ApplicationClientError::InvalidInput),
3090        ApplicationValue::EnumIdentity {
3091            type_id,
3092            variant_id,
3093            name,
3094        } if type_id != 0 && variant_id != 0 && !name.is_empty() && name.len() <= 256 => {
3095            Kind::EnumValue(v1::EnumValue {
3096                type_id,
3097                variant_id,
3098                name,
3099            })
3100        }
3101        ApplicationValue::EnumIdentity { .. } => {
3102            return Err(ApplicationClientError::InvalidInput);
3103        }
3104        ApplicationValue::Bytes(value) => Kind::BytesValue(value),
3105        ApplicationValue::Date(days_since_unix_epoch) => Kind::DateValue(v1::Date {
3106            days_since_unix_epoch,
3107        }),
3108        ApplicationValue::Timestamp { seconds, nanos } if nanos < 1_000_000_000 => {
3109            Kind::TimestampValue(v1::Timestamp { seconds, nanos })
3110        }
3111        ApplicationValue::Timestamp { .. } => {
3112            return Err(ApplicationClientError::InvalidInput);
3113        }
3114        ApplicationValue::Vector(value) => Kind::VectorValue(v1::VectorValue {
3115            components: value.into_components(),
3116        }),
3117        ApplicationValue::List(values) => Kind::ListValue(v1::ValueList {
3118            values: values
3119                .into_iter()
3120                .map(lower_value)
3121                .collect::<Result<Vec<_>, _>>()?,
3122        }),
3123        ApplicationValue::Record(fields) => Kind::RecordValue(v1::ValueRecord {
3124            fields: fields
3125                .into_iter()
3126                .map(|(name, value)| {
3127                    Ok(v1::ValueField {
3128                        field_id: None,
3129                        name,
3130                        value: Some(lower_value(value)?),
3131                    })
3132                })
3133                .collect::<Result<Vec<_>, ApplicationClientError>>()?,
3134        }),
3135    };
3136    Ok(v1::Value { kind: Some(kind) })
3137}
3138
3139const LOCAL_RAISED_QUERY_CACHE_CAP: usize = 256;
3140const LOCAL_RAISED_QUERY_HASH_SLOTS: usize = 512;
3141const SHARED_RAISED_QUERY_SHARDS: usize = 16;
3142const SHARED_RAISED_QUERY_SHARD_CAP: usize = 64;
3143
3144#[derive(Clone)]
3145struct CachedRaisedQueryResult {
3146    wire_cache_id: u32,
3147    result: Arc<NamedQueryResult>,
3148}
3149
3150struct LocalRaisedQueryCache {
3151    entries: Vec<CachedRaisedQueryResult>,
3152    next_slot: usize,
3153    by_wire_id: [u16; LOCAL_RAISED_QUERY_HASH_SLOTS],
3154}
3155
3156impl Default for LocalRaisedQueryCache {
3157    fn default() -> Self {
3158        Self {
3159            entries: Vec::new(),
3160            next_slot: 0,
3161            by_wire_id: [0; LOCAL_RAISED_QUERY_HASH_SLOTS],
3162        }
3163    }
3164}
3165
3166impl LocalRaisedQueryCache {
3167    fn bucket(wire_cache_id: u32) -> usize {
3168        (wire_cache_id as usize) & (LOCAL_RAISED_QUERY_HASH_SLOTS - 1)
3169    }
3170
3171    fn lookup(&self, wire_cache_id: u32) -> Option<&Arc<NamedQueryResult>> {
3172        let bucket = Self::bucket(wire_cache_id);
3173        let idx1 = self.by_wire_id[bucket] as usize;
3174        if idx1 != 0
3175            && let Some(entry) = self.entries.get(idx1 - 1)
3176            && entry.wire_cache_id == wire_cache_id
3177        {
3178            return Some(&entry.result);
3179        }
3180        self.entries
3181            .iter()
3182            .find(|entry| entry.wire_cache_id == wire_cache_id)
3183            .map(|entry| &entry.result)
3184    }
3185
3186    fn insert(&mut self, wire_cache_id: u32, result: Arc<NamedQueryResult>) {
3187        let bucket = Self::bucket(wire_cache_id);
3188        let entry = CachedRaisedQueryResult {
3189            wire_cache_id,
3190            result,
3191        };
3192        let slot = if self.entries.len() < LOCAL_RAISED_QUERY_CACHE_CAP {
3193            let slot = self.entries.len();
3194            self.entries.push(entry);
3195            slot
3196        } else {
3197            let slot = self.next_slot;
3198            self.entries[slot] = entry;
3199            self.next_slot = (slot + 1) % LOCAL_RAISED_QUERY_CACHE_CAP;
3200            slot
3201        };
3202        self.by_wire_id[bucket] = (slot + 1) as u16;
3203    }
3204}
3205
3206#[derive(Default)]
3207struct SharedRaisedQueryShard {
3208    entries: Vec<CachedRaisedQueryResult>,
3209    next_slot: usize,
3210}
3211
3212static SHARED_RAISED_QUERY_CACHE: OnceLock<
3213    [std::sync::RwLock<SharedRaisedQueryShard>; SHARED_RAISED_QUERY_SHARDS],
3214> = OnceLock::new();
3215
3216fn shared_raised_query_cache()
3217-> &'static [std::sync::RwLock<SharedRaisedQueryShard>; SHARED_RAISED_QUERY_SHARDS] {
3218    SHARED_RAISED_QUERY_CACHE.get_or_init(|| {
3219        std::array::from_fn(|_| std::sync::RwLock::new(SharedRaisedQueryShard::default()))
3220    })
3221}
3222
3223std::thread_local! {
3224    static LOCAL_RAISED_QUERY_CACHE: std::cell::RefCell<LocalRaisedQueryCache> =
3225        std::cell::RefCell::new(LocalRaisedQueryCache::default());
3226}
3227
3228fn lookup_shared_raised_query_result(wire_cache_id: u32) -> Option<Arc<NamedQueryResult>> {
3229    let shard_idx = (wire_cache_id as usize) & (SHARED_RAISED_QUERY_SHARDS - 1);
3230    let guard = shared_raised_query_cache()[shard_idx].read().ok()?;
3231    guard
3232        .entries
3233        .iter()
3234        .find(|entry| entry.wire_cache_id == wire_cache_id)
3235        .map(|entry| Arc::clone(&entry.result))
3236}
3237
3238fn insert_shared_raised_query_result(wire_cache_id: u32, result: Arc<NamedQueryResult>) {
3239    let shard_idx = (wire_cache_id as usize) & (SHARED_RAISED_QUERY_SHARDS - 1);
3240    let Ok(mut guard) = shared_raised_query_cache()[shard_idx].write() else {
3241        return;
3242    };
3243    if guard
3244        .entries
3245        .iter()
3246        .any(|entry| entry.wire_cache_id == wire_cache_id)
3247    {
3248        return;
3249    }
3250    let entry = CachedRaisedQueryResult {
3251        wire_cache_id,
3252        result,
3253    };
3254    if guard.entries.len() < SHARED_RAISED_QUERY_SHARD_CAP {
3255        guard.entries.push(entry);
3256    } else {
3257        let slot = guard.next_slot;
3258        guard.entries[slot] = entry;
3259        guard.next_slot = (slot + 1) % SHARED_RAISED_QUERY_SHARD_CAP;
3260    }
3261}
3262
3263async fn with_client_wire_carrier<F: std::future::Future>(future: F) -> F::Output {
3264    let mut pinned = std::pin::pin!(future);
3265    std::future::poll_fn(|cx| {
3266        let _guard = riffdb_proto::enter_client_query_wire_carrier_scope();
3267        pinned.as_mut().poll(cx)
3268    })
3269    .await
3270}
3271
3272fn raise_query_result_from_client_wire(
3273    response: app_v1::ExecuteQueryResponse,
3274) -> Result<NamedQueryResult, ApplicationClientError> {
3275    raise_query_result_shared_from_client_wire(response).map(Arc::unwrap_or_clone)
3276}
3277
3278fn raise_query_result_shared_from_client_wire(
3279    response: app_v1::ExecuteQueryResponse,
3280) -> Result<Arc<NamedQueryResult>, ApplicationClientError> {
3281    if response.selected_result_encoding < 0
3282        && response.fields.is_empty()
3283        && response.compact_result.is_none()
3284        && response.packed_result.is_none()
3285    {
3286        let wire_cache_id = response.selected_result_encoding.unsigned_abs();
3287        if wire_cache_id >= riffdb_proto::CLIENT_WIRE_CARRIER_ID_BASE {
3288            if let Some(cached) = LOCAL_RAISED_QUERY_CACHE.with(|cell| {
3289                let guard = cell.try_borrow().ok()?;
3290                guard.lookup(wire_cache_id).cloned()
3291            }) {
3292                return Ok(cached);
3293            }
3294            if let Some(shared) = lookup_shared_raised_query_result(wire_cache_id) {
3295                LOCAL_RAISED_QUERY_CACHE.with(|cell| {
3296                    if let Ok(mut guard) = cell.try_borrow_mut() {
3297                        guard.insert(wire_cache_id, Arc::clone(&shared));
3298                    }
3299                });
3300                return Ok(shared);
3301            }
3302            if let Some(full_response) =
3303                riffdb_proto::lookup_client_query_wire_response(wire_cache_id)
3304            {
3305                let raised = Arc::new(raise_query_result((*full_response).clone())?);
3306                insert_shared_raised_query_result(wire_cache_id, Arc::clone(&raised));
3307                LOCAL_RAISED_QUERY_CACHE.with(|cell| {
3308                    if let Ok(mut guard) = cell.try_borrow_mut() {
3309                        guard.insert(wire_cache_id, Arc::clone(&raised));
3310                    }
3311                });
3312                return Ok(raised);
3313            }
3314        }
3315    }
3316    raise_query_result(response).map(Arc::new)
3317}
3318
3319#[doc(hidden)]
3320pub fn raise_query_result(
3321    response: app_v1::ExecuteQueryResponse,
3322) -> Result<NamedQueryResult, ApplicationClientError> {
3323    let identity = query_response_identity(&response)?;
3324    let selected_encoding =
3325        app_v1::NamedResultEncoding::try_from(response.selected_result_encoding)
3326            .map_err(|_| ApplicationClientError::InvalidResponse)?;
3327    let fields = match selected_encoding {
3328        app_v1::NamedResultEncoding::Unspecified | app_v1::NamedResultEncoding::LegacyRecords => {
3329            if response.compact_result.is_some() || response.packed_result.is_some() {
3330                return Err(ApplicationClientError::InvalidResponse);
3331            }
3332            raise_legacy_query_fields(response.fields)?
3333        }
3334        app_v1::NamedResultEncoding::CompactV1 => {
3335            if !response.fields.is_empty() || response.packed_result.is_some() {
3336                return Err(ApplicationClientError::InvalidResponse);
3337            }
3338            raise_compact_query_field(
3339                response
3340                    .compact_result
3341                    .ok_or(ApplicationClientError::InvalidResponse)?,
3342            )?
3343        }
3344        app_v1::NamedResultEncoding::PackedV1 => {
3345            return Err(ApplicationClientError::InvalidResponse);
3346        }
3347    };
3348    Ok(NamedQueryResult {
3349        outcome: response.outcome,
3350        application_head: response.application_head,
3351        fields,
3352        next_cursor: response.next_cursor,
3353        identity,
3354    })
3355}
3356
3357fn query_response_identity(
3358    response: &app_v1::ExecuteQueryResponse,
3359) -> Result<QueryResponseIdentity, ApplicationClientError> {
3360    let identity = response
3361        .identity
3362        .as_ref()
3363        .ok_or(ApplicationClientError::InvalidResponse)?;
3364    Ok(QueryResponseIdentity {
3365        contract_lineage: identity.contract_lineage.clone(),
3366        contract_version: identity.contract_version,
3367        contract_bundle_hash: identity
3368            .contract_bundle_hash
3369            .as_slice()
3370            .try_into()
3371            .map_err(|_| ApplicationClientError::InvalidResponse)?,
3372        module_hash: identity
3373            .module_hash
3374            .as_deref()
3375            .ok_or(ApplicationClientError::InvalidResponse)?
3376            .try_into()
3377            .map_err(|_| ApplicationClientError::InvalidResponse)?,
3378        query_name: identity
3379            .query_name
3380            .clone()
3381            .ok_or(ApplicationClientError::InvalidResponse)?,
3382        plan_hash: identity
3383            .plan_hash
3384            .as_slice()
3385            .try_into()
3386            .map_err(|_| ApplicationClientError::InvalidResponse)?,
3387    })
3388}
3389
3390fn raise_legacy_query_fields(
3391    wire_fields: Vec<app_v1::ResultField>,
3392) -> Result<BTreeMap<String, ApplicationResultField>, ApplicationClientError> {
3393    let mut fields = BTreeMap::new();
3394    for field in wire_fields {
3395        let cardinality = match app_v1::ResultCardinality::try_from(field.cardinality) {
3396            Ok(app_v1::ResultCardinality::One) => ApplicationCardinality::One,
3397            Ok(app_v1::ResultCardinality::Maybe) => ApplicationCardinality::Maybe,
3398            Ok(app_v1::ResultCardinality::Many) => ApplicationCardinality::Many,
3399            Ok(app_v1::ResultCardinality::Unspecified) | Err(_) => {
3400                return Err(ApplicationClientError::InvalidResponse);
3401            }
3402        };
3403        let records = field
3404            .records
3405            .into_iter()
3406            .map(|record| {
3407                let mut fields = BTreeMap::new();
3408                for field in record.fields {
3409                    if fields
3410                        .insert(
3411                            field.name,
3412                            raise_value(
3413                                field.value.ok_or(ApplicationClientError::InvalidResponse)?,
3414                            )?,
3415                        )
3416                        .is_some()
3417                    {
3418                        return Err(ApplicationClientError::InvalidResponse);
3419                    }
3420                }
3421                Ok(ApplicationRecord {
3422                    entity: record.entity,
3423                    fields,
3424                })
3425            })
3426            .collect::<Result<Vec<_>, ApplicationClientError>>()?;
3427        if fields
3428            .insert(
3429                field.name,
3430                ApplicationResultField {
3431                    cardinality,
3432                    records,
3433                },
3434            )
3435            .is_some()
3436        {
3437            return Err(ApplicationClientError::InvalidResponse);
3438        }
3439    }
3440    Ok(fields)
3441}
3442
3443fn raise_compact_query_field(
3444    field: app_v1::CompactResultField,
3445) -> Result<BTreeMap<String, ApplicationResultField>, ApplicationClientError> {
3446    if field.name.is_empty() || field.entity.is_empty() || field.fields.is_empty() {
3447        return Err(ApplicationClientError::InvalidResponse);
3448    }
3449    let cardinality = match app_v1::ResultCardinality::try_from(field.cardinality) {
3450        Ok(app_v1::ResultCardinality::Many) => ApplicationCardinality::Many,
3451        _ => return Err(ApplicationClientError::InvalidResponse),
3452    };
3453    let mut names = BTreeSet::new();
3454    for name in &field.fields {
3455        if name.is_empty() || !names.insert(name.as_str()) {
3456            return Err(ApplicationClientError::InvalidResponse);
3457        }
3458    }
3459    let width = field.fields.len();
3460    let records = field
3461        .rows
3462        .into_iter()
3463        .map(|row| {
3464            if row.values.len() != width {
3465                return Err(ApplicationClientError::InvalidResponse);
3466            }
3467            let fields = field
3468                .fields
3469                .iter()
3470                .cloned()
3471                .zip(row.values)
3472                .map(|(name, value)| Ok((name, raise_value(value)?)))
3473                .collect::<Result<BTreeMap<_, _>, ApplicationClientError>>()?;
3474            Ok(ApplicationRecord {
3475                entity: field.entity.clone(),
3476                fields,
3477            })
3478        })
3479        .collect::<Result<Vec<_>, ApplicationClientError>>()?;
3480    Ok(BTreeMap::from([(
3481        field.name,
3482        ApplicationResultField {
3483            cardinality,
3484            records,
3485        },
3486    )]))
3487}
3488
3489#[doc(hidden)]
3490pub fn raise_value(value: v1::Value) -> Result<ApplicationValue, ApplicationClientError> {
3491    use v1::value::Kind;
3492    match value.kind.ok_or(ApplicationClientError::InvalidResponse)? {
3493        Kind::NullValue(_) => Ok(ApplicationValue::Null),
3494        Kind::BoolValue(value) => Ok(ApplicationValue::Bool(value)),
3495        Kind::I64Value(value) => Ok(ApplicationValue::I64(value)),
3496        Kind::U64Value(value) => Ok(ApplicationValue::U64(value)),
3497        Kind::DecimalValue(value) => Ok(ApplicationValue::Decimal {
3498            coefficient_twos_complement: value.coefficient_twos_complement,
3499            scale: value.scale,
3500            precision: value.precision,
3501        }),
3502        Kind::MoneyValue(value) => {
3503            let amount = value
3504                .amount
3505                .ok_or(ApplicationClientError::InvalidResponse)?;
3506            Ok(ApplicationValue::Money {
3507                currency: value.currency,
3508                amount: Box::new(ApplicationValue::Decimal {
3509                    coefficient_twos_complement: amount.coefficient_twos_complement,
3510                    scale: amount.scale,
3511                    precision: amount.precision,
3512                }),
3513            })
3514        }
3515        Kind::StringValue(value) => Ok(ApplicationValue::String(value)),
3516        Kind::BytesValue(value) => Ok(ApplicationValue::Bytes(value)),
3517        Kind::UuidValue(value) => {
3518            let bytes: [u8; 16] = value
3519                .as_slice()
3520                .try_into()
3521                .map_err(|_| ApplicationClientError::InvalidResponse)?;
3522            Ok(ApplicationValue::Uuid(ApplicationUuid::from_bytes(bytes)))
3523        }
3524        Kind::EnumValue(value) if !value.name.is_empty() => Ok(ApplicationValue::Enum(value.name)),
3525        Kind::ListValue(values) => Ok(ApplicationValue::List(
3526            values
3527                .values
3528                .into_iter()
3529                .map(raise_value)
3530                .collect::<Result<Vec<_>, _>>()?,
3531        )),
3532        Kind::RecordValue(record) => {
3533            let mut fields = BTreeMap::new();
3534            for field in record.fields {
3535                if field.name.is_empty()
3536                    || fields
3537                        .insert(
3538                            field.name,
3539                            raise_value(
3540                                field.value.ok_or(ApplicationClientError::InvalidResponse)?,
3541                            )?,
3542                        )
3543                        .is_some()
3544                {
3545                    return Err(ApplicationClientError::InvalidResponse);
3546                }
3547            }
3548            Ok(ApplicationValue::Record(fields))
3549        }
3550        Kind::DateValue(value) => Ok(ApplicationValue::Date(value.days_since_unix_epoch)),
3551        Kind::TimestampValue(value) if value.nanos < 1_000_000_000 => {
3552            Ok(ApplicationValue::Timestamp {
3553                seconds: value.seconds,
3554                nanos: value.nanos,
3555            })
3556        }
3557        Kind::VectorValue(value) => riffdb_types::CanonicalVector::new(value.components)
3558            .map(ApplicationValue::Vector)
3559            .map_err(|_| ApplicationClientError::InvalidResponse),
3560        Kind::TimestampValue(_) | Kind::EnumValue(_) => {
3561            Err(ApplicationClientError::InvalidResponse)
3562        }
3563    }
3564}
3565
3566fn format_uuid_text(bytes: &[u8; 16]) -> String {
3567    const HEX: &[u8; 16] = b"0123456789abcdef";
3568    let mut output = String::with_capacity(36);
3569    for (index, byte) in bytes.iter().copied().enumerate() {
3570        if matches!(index, 4 | 6 | 8 | 10) {
3571            output.push('-');
3572        }
3573        output.push(char::from(HEX[usize::from(byte >> 4)]));
3574        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
3575    }
3576    output
3577}
3578
3579fn parse_uuid(value: &str) -> Result<[u8; 16], ApplicationClientError> {
3580    if value.len() != 36 {
3581        return Err(ApplicationClientError::InvalidInput);
3582    }
3583    let bytes = value.as_bytes();
3584    if [8, 13, 18, 23]
3585        .into_iter()
3586        .any(|index| bytes[index] != b'-')
3587    {
3588        return Err(ApplicationClientError::InvalidInput);
3589    }
3590    let mut output = [0_u8; 16];
3591    let mut encoded = bytes.iter().copied().filter(|byte| *byte != b'-');
3592    for byte in &mut output {
3593        let high = encoded
3594            .next()
3595            .and_then(hex_nibble)
3596            .ok_or(ApplicationClientError::InvalidInput)?;
3597        let low = encoded
3598            .next()
3599            .and_then(hex_nibble)
3600            .ok_or(ApplicationClientError::InvalidInput)?;
3601        *byte = (high << 4) | low;
3602    }
3603    encoded
3604        .next()
3605        .is_none()
3606        .then_some(output)
3607        .ok_or(ApplicationClientError::InvalidInput)
3608}
3609
3610const fn hex_nibble(byte: u8) -> Option<u8> {
3611    match byte {
3612        b'0'..=b'9' => Some(byte - b'0'),
3613        b'a'..=b'f' => Some(byte - b'a' + 10),
3614        _ => None,
3615    }
3616}
3617
3618#[cfg(test)]
3619mod tests {
3620    use super::*;
3621    use riffdb_errors::ApplicationErrorCode;
3622
3623    #[test]
3624    fn exact_tonic_endpoint_defaults_tcp_nodelay_on() {
3625        // tonic is exact-pinned at 0.14.6 by the workspace. This executable
3626        // assertion accompanies WP-632's source receipt so a dependency
3627        // change cannot silently reintroduce Nagle delay into the diagnosis.
3628        let endpoint = Endpoint::from_static("http://127.0.0.1:7443");
3629        assert!(endpoint.get_tcp_nodelay());
3630    }
3631
3632    #[test]
3633    fn named_query_builder_is_name_addressed_and_module_pinned() {
3634        let mut parameters = BTreeMap::new();
3635        parameters.insert(
3636            "organization_id".to_owned(),
3637            ApplicationValue::String("01900000-0000-7000-8000-000000000001".to_owned()),
3638        );
3639        let query = NamedQuery::new(
3640            ApplicationContract::Exact {
3641                lineage: "TicketDesk".to_owned(),
3642                version: 1,
3643                bundle_hash: None,
3644            },
3645            "TicketPage",
3646            Some([7; 32]),
3647            parameters,
3648            None,
3649        )
3650        .expect("query");
3651        assert_eq!(query.name, "TicketPage");
3652        assert_eq!(query.module_hash, Some([7; 32]));
3653    }
3654
3655    #[test]
3656    fn generated_query_options_preserve_cursor_and_read_fence() {
3657        let query = NamedQuery::new(
3658            ApplicationContract::Exact {
3659                lineage: "TicketDesk".to_owned(),
3660                version: 1,
3661                bundle_hash: Some([9; 32]),
3662            },
3663            "TicketPage",
3664            Some([7; 32]),
3665            BTreeMap::new(),
3666            None,
3667        )
3668        .expect("query")
3669        .with_options(
3670            QueryOptions::new()
3671                .after("opaque-cursor")
3672                .read_after_commit(41)
3673                .at_least_admission_head(),
3674        )
3675        .expect("options");
3676        assert_eq!(query.cursor.as_deref(), Some("opaque-cursor"));
3677        assert_eq!(query.minimum_application_head, Some(41));
3678        assert!(query.admission_head_consistency);
3679        assert!(
3680            NamedQuery::new(
3681                ApplicationContract::Active,
3682                "TicketPage",
3683                Some([7; 32]),
3684                BTreeMap::new(),
3685                None,
3686            )
3687            .expect("query")
3688            .with_options(QueryOptions::new().read_after_commit(0))
3689            .is_err()
3690        );
3691    }
3692
3693    // req: OQ-031
3694    #[test]
3695    fn generated_cursor_routing_preserves_low_level_options_and_rejects_collision() {
3696        let routed = QueryOptions::new()
3697            .read_after_commit(41)
3698            .at_least_admission_head()
3699            .with_generated_cursor(Some("generated-cursor".to_owned()))
3700            .expect("generated cursor");
3701        assert_eq!(routed.cursor.as_deref(), Some("generated-cursor"));
3702        assert_eq!(routed.read_after_commit, Some(41));
3703        assert!(routed.admission_head);
3704
3705        let first_page = QueryOptions::new()
3706            .read_after_commit(42)
3707            .with_generated_cursor(None)
3708            .expect("first page");
3709        assert_eq!(first_page.cursor, None);
3710        assert_eq!(first_page.read_after_commit, Some(42));
3711
3712        assert!(matches!(
3713            QueryOptions::new()
3714                .after("low-level-cursor")
3715                .with_generated_cursor(Some("generated-cursor".to_owned())),
3716            Err(ApplicationClientError::InvalidInput)
3717        ));
3718    }
3719
3720    #[test]
3721    fn query_response_raises_only_names_and_typed_values() {
3722        let response = app_v1::ExecuteQueryResponse {
3723            identity: Some(app_v1::QueryIdentity {
3724                contract_lineage: "TicketDesk".to_owned(),
3725                contract_version: 1,
3726                contract_bundle_hash: vec![1; 32],
3727                query_name: Some("TicketPage".to_owned()),
3728                plan_hash: vec![2; 32],
3729                module_hash: Some(vec![3; 32]),
3730            }),
3731            outcome: "Found".to_owned(),
3732            application_head: 4,
3733            fields: vec![app_v1::ResultField {
3734                name: "ticket".to_owned(),
3735                cardinality: app_v1::ResultCardinality::One as i32,
3736                records: vec![app_v1::ResultRecord {
3737                    fields: vec![app_v1::Parameter {
3738                        name: "title".to_owned(),
3739                        value: Some(v1::Value {
3740                            kind: Some(v1::value::Kind::StringValue("Hello".to_owned())),
3741                        }),
3742                    }],
3743                    entity: "Ticket".to_owned(),
3744                }],
3745            }],
3746            next_cursor: None,
3747            selected_result_encoding: app_v1::NamedResultEncoding::LegacyRecords as i32,
3748            compact_result: None,
3749            packed_result: None,
3750        };
3751        let result = raise_query_result(response).expect("result");
3752        assert_eq!(result.outcome, "Found");
3753        assert_eq!(result.identity.contract_lineage, "TicketDesk");
3754        assert_eq!(result.identity.contract_version, 1);
3755        assert_eq!(result.identity.contract_bundle_hash, [1; 32]);
3756        assert_eq!(result.identity.module_hash, [3; 32]);
3757        assert_eq!(result.identity.query_name, "TicketPage");
3758        assert_eq!(result.identity.plan_hash, [2; 32]);
3759        assert_eq!(
3760            result.fields["ticket"].records[0].fields["title"],
3761            ApplicationValue::String("Hello".to_owned())
3762        );
3763    }
3764
3765    #[test]
3766    fn generated_identity_expectations_reject_contract_module_and_name_drift() {
3767        let response = app_v1::ExecuteQueryResponse {
3768            identity: Some(app_v1::QueryIdentity {
3769                contract_lineage: "TicketDesk".to_owned(),
3770                contract_version: 1,
3771                contract_bundle_hash: vec![1; 32],
3772                query_name: Some("TicketPage".to_owned()),
3773                plan_hash: vec![2; 32],
3774                module_hash: Some(vec![3; 32]),
3775            }),
3776            ..Default::default()
3777        };
3778        let contract = ApplicationContract::Exact {
3779            lineage: "TicketDesk".to_owned(),
3780            version: 1,
3781            bundle_hash: Some([1; 32]),
3782        };
3783        validate_query_response_identity(
3784            &response,
3785            &contract,
3786            "TicketPage",
3787            Some([3; 32]),
3788            Some([2; 32]),
3789        )
3790        .expect("exact identity");
3791        assert!(matches!(
3792            validate_query_response_identity(
3793                &response,
3794                &contract,
3795                "Other",
3796                Some([3; 32]),
3797                Some([2; 32])
3798            ),
3799            Err(ApplicationClientError::InvalidResponse)
3800        ));
3801        assert!(matches!(
3802            validate_query_response_identity(
3803                &response,
3804                &contract,
3805                "TicketPage",
3806                Some([4; 32]),
3807                Some([2; 32])
3808            ),
3809            Err(ApplicationClientError::InvalidResponse)
3810        ));
3811        assert!(matches!(
3812            validate_query_response_identity(
3813                &response,
3814                &contract,
3815                "TicketPage",
3816                Some([3; 32]),
3817                Some([4; 32])
3818            ),
3819            Err(ApplicationClientError::InvalidResponse)
3820        ));
3821        let changed_contract = ApplicationContract::Exact {
3822            lineage: "TicketDesk".to_owned(),
3823            version: 1,
3824            bundle_hash: Some([9; 32]),
3825        };
3826        assert!(matches!(
3827            validate_query_response_identity(
3828                &response,
3829                &changed_contract,
3830                "TicketPage",
3831                Some([3; 32]),
3832                Some([2; 32])
3833            ),
3834            Err(ApplicationClientError::InvalidResponse)
3835        ));
3836    }
3837
3838    #[test]
3839    fn application_catalog_preflight_is_exact_closed_and_name_only() {
3840        let contract = ApplicationContract::Exact {
3841            lineage: "TicketDesk".to_owned(),
3842            version: 3,
3843            bundle_hash: Some([7; 32]),
3844        };
3845        let response = app_v1::GetApplicationCatalogResponse {
3846            schema: APPLICATION_CATALOG_SCHEMA_V1.to_owned(),
3847            contract_lineage: "TicketDesk".to_owned(),
3848            contract_version: 3,
3849            contract_bundle_hash: vec![7; 32],
3850            query_module_hashes: vec![vec![3; 32], vec![5; 32]],
3851            features: [
3852                app_v1::ApplicationCatalogFeature::OperationalOptionalPredicates,
3853                app_v1::ApplicationCatalogFeature::StableCursorPages,
3854                app_v1::ApplicationCatalogFeature::NullExistencePredicates,
3855                app_v1::ApplicationCatalogFeature::BinaryTextPrefix,
3856                app_v1::ApplicationCatalogFeature::UnicodeFoldTextPrefixV1,
3857                app_v1::ApplicationCatalogFeature::ExactAggregates,
3858            ]
3859            .into_iter()
3860            .map(|feature| app_v1::ApplicationCatalogFeatureView {
3861                feature: feature as i32,
3862                state: if feature == app_v1::ApplicationCatalogFeature::UnicodeFoldTextPrefixV1 {
3863                    app_v1::ApplicationCatalogFeatureState::Unavailable as i32
3864                } else {
3865                    app_v1::ApplicationCatalogFeatureState::Available as i32
3866                },
3867            })
3868            .collect(),
3869            ..Default::default()
3870        };
3871
3872        let preflight =
3873            raise_application_catalog_preflight(response, &contract).expect("preflight");
3874        assert_eq!(preflight.contract_lineage, "TicketDesk");
3875        assert_eq!(preflight.contract_version, 3);
3876        assert_eq!(preflight.contract_bundle_hash, [7; 32]);
3877        assert_eq!(preflight.query_module_hashes, vec![[3; 32], [5; 32]]);
3878        assert!(preflight.is_available(ApplicationCatalogFeature::BinaryTextPrefix));
3879        assert!(!preflight.is_available(ApplicationCatalogFeature::UnicodeFoldTextPrefixV1));
3880    }
3881
3882    #[test]
3883    fn application_catalog_preflight_rejects_identity_and_registry_drift() {
3884        let contract = ApplicationContract::Exact {
3885            lineage: "TicketDesk".to_owned(),
3886            version: 3,
3887            bundle_hash: Some([7; 32]),
3888        };
3889        let response = app_v1::GetApplicationCatalogResponse {
3890            schema: APPLICATION_CATALOG_SCHEMA_V1.to_owned(),
3891            contract_lineage: "TicketDesk".to_owned(),
3892            contract_version: 4,
3893            contract_bundle_hash: vec![7; 32],
3894            ..Default::default()
3895        };
3896        assert!(matches!(
3897            raise_application_catalog_preflight(response, &contract),
3898            Err(ApplicationClientError::InvalidResponse)
3899        ));
3900
3901        let response = app_v1::GetApplicationCatalogResponse {
3902            schema: APPLICATION_CATALOG_SCHEMA_V1.to_owned(),
3903            contract_lineage: "TicketDesk".to_owned(),
3904            contract_version: 3,
3905            contract_bundle_hash: vec![7; 32],
3906            query_module_hashes: vec![vec![5; 32], vec![3; 32]],
3907            ..Default::default()
3908        };
3909        assert!(matches!(
3910            raise_application_catalog_preflight(response, &contract),
3911            Err(ApplicationClientError::InvalidResponse)
3912        ));
3913    }
3914
3915    #[test]
3916    fn generated_batch_bounds_and_resume_checkpoint_are_closed() {
3917        let options = GeneratedBatchOptions::new(MAX_GENERATED_BATCH_CONCURRENCY)
3918            .expect("maximum concurrency")
3919            .with_checkpoint(4_096);
3920        options.validate(4_096).expect("complete checkpoint");
3921        assert_eq!(options.checkpoint, 4_096);
3922
3923        assert_eq!(
3924            GeneratedBatchOptions::new(0),
3925            Err(GeneratedBatchError::InvalidBounds)
3926        );
3927        assert_eq!(
3928            GeneratedBatchOptions::new(MAX_GENERATED_BATCH_CONCURRENCY + 1),
3929            Err(GeneratedBatchError::InvalidBounds)
3930        );
3931        assert_eq!(
3932            GeneratedBatchOptions::new(1)
3933                .expect("options")
3934                .with_checkpoint(2)
3935                .validate(1),
3936            Err(GeneratedBatchError::InvalidBounds)
3937        );
3938        assert_eq!(
3939            GeneratedBatchOptions::new(1)
3940                .expect("options")
3941                .validate(4_097),
3942            Err(GeneratedBatchError::InvalidBounds)
3943        );
3944    }
3945
3946    #[test]
3947    fn generated_transport_batches_never_exceed_the_item_concurrency_bound() {
3948        for item_concurrency in 1..=MAX_GENERATED_BATCH_CONCURRENCY {
3949            let (batch_size, transport_concurrency) =
3950                generated_transport_batch_policy(item_concurrency);
3951            assert!((1..=MAX_GENERATED_TRANSPORT_BATCH_ITEMS).contains(&batch_size));
3952            assert!(transport_concurrency > 0);
3953            assert!(batch_size * transport_concurrency <= item_concurrency);
3954        }
3955        assert_eq!(generated_transport_batch_policy(64), (16, 4));
3956        assert_eq!(generated_transport_batch_policy(128), (16, 8));
3957        assert_eq!(generated_transport_batch_policy(384), (16, 24));
3958        assert_eq!(generated_transport_batch_policy(17), (8, 2));
3959    }
3960
3961    #[test]
3962    fn ordinary_transport_batch_bound_is_closed_before_submission() {
3963        assert_eq!(
3964            validate_idempotent_transport_batch_len(0),
3965            Err(IdempotentTransportBatchError::Empty)
3966        );
3967        assert_eq!(validate_idempotent_transport_batch_len(1), Ok(()));
3968        assert_eq!(
3969            validate_idempotent_transport_batch_len(MAX_GENERATED_TRANSPORT_BATCH_ITEMS),
3970            Ok(())
3971        );
3972        assert_eq!(
3973            validate_idempotent_transport_batch_len(MAX_GENERATED_TRANSPORT_BATCH_ITEMS + 1),
3974            Err(IdempotentTransportBatchError::TooManyItems)
3975        );
3976    }
3977
3978    #[derive(Clone)]
3979    struct StubBatchCommand {
3980        outcome: &'static str,
3981        key: &'static str,
3982    }
3983
3984    impl GeneratedCommand for StubBatchCommand {
3985        type Outcome = String;
3986
3987        fn idempotent_command(
3988            &self,
3989        ) -> Result<crate::IdempotentCommand, crate::generated::GeneratedCommandError> {
3990            crate::IdempotentCommand::new(
3991                "OkCommand",
3992                Some(1),
3993                v1::Value {
3994                    kind: Some(v1::value::Kind::RecordValue(v1::ValueRecord {
3995                        fields: vec![v1::ValueField {
3996                            field_id: Some(1),
3997                            name: String::new(),
3998                            value: Some(v1::Value {
3999                                kind: Some(v1::value::Kind::StringValue(self.key.to_owned())),
4000                            }),
4001                        }],
4002                    })),
4003                },
4004            )
4005            .map_err(|_| crate::generated::GeneratedCommandError::InvalidInputShape)
4006        }
4007
4008        fn outcome_request(
4009            &self,
4010            request_id: riffdb_types::RequestId,
4011        ) -> Result<v1::GetOutcomeRequest, crate::generated::GeneratedCommandError> {
4012            Ok(v1::GetOutcomeRequest {
4013                request_id: request_id.into_bytes().to_vec(),
4014                contract_lineage: "lineage".to_owned(),
4015                command_name: "OkCommand".to_owned(),
4016                idempotency_key: self.key.to_owned(),
4017                outcome_uri: None,
4018            })
4019        }
4020
4021        fn decode_outcome(
4022            &self,
4023            response: &v1::ExecuteCommandResponse,
4024        ) -> Result<Self::Outcome, crate::generated::GeneratedCommandError> {
4025            if response.outcome_type == self.outcome {
4026                Ok(self.outcome.to_owned())
4027            } else {
4028                Err(crate::generated::GeneratedCommandError::InvalidOutcomeShape)
4029            }
4030        }
4031
4032        fn workflow_successor_revisions(
4033            &self,
4034            response: &v1::ExecuteCommandResponse,
4035        ) -> Result<
4036            Vec<crate::generated::WorkflowSuccessorRevision>,
4037            crate::generated::GeneratedCommandError,
4038        > {
4039            if response.outcome_type == "Workflow" {
4040                Ok(vec![
4041                    crate::generated::WorkflowSuccessorRevision::generated("work", 8),
4042                ])
4043            } else {
4044                Ok(Vec::new())
4045            }
4046        }
4047    }
4048
4049    fn stub_command(outcome: &'static str, key: &'static str) -> StubBatchCommand {
4050        StubBatchCommand { outcome, key }
4051    }
4052
4053    fn stub_response(outcome: &str) -> v1::ExecuteCommandResponse {
4054        v1::ExecuteCommandResponse {
4055            status: v1::execute_command_response::CompletionStatus::ExecutedReadOnly as i32,
4056            commit_sequence: 0,
4057            contract_version: 1,
4058            plan_hash: vec![0x44; 32],
4059            outcome_type: outcome.to_owned(),
4060            outcome: Some(v1::Value {
4061                kind: Some(v1::value::Kind::NullValue(v1::NullValue::NullValue as i32)),
4062            }),
4063            provenance_uri: String::new(),
4064            durability_mode: String::new(),
4065            outcome_uri: None,
4066            history_incarnation: 1,
4067        }
4068    }
4069
4070    #[test]
4071    fn typed_command_results_preserve_generated_workflow_revision_evidence() {
4072        let command = stub_command("Workflow", "workflow-key");
4073        let response = stub_response("Workflow");
4074        let outcome = command.decode_outcome(&response).expect("outcome");
4075        let result = typed_command_result(&command, outcome, response).expect("typed result");
4076
4077        assert_eq!(result.workflow_revisions.len(), 1);
4078        assert_eq!(result.workflow_revisions[0].binding(), "work");
4079        assert_eq!(result.workflow_revisions[0].revision(), 8);
4080    }
4081
4082    fn stub_error_item(code: ApplicationErrorCode) -> v1::ExecuteCommandBatchItem {
4083        v1::ExecuteCommandBatchItem {
4084            result: Some(v1::execute_command_batch_item::Result::Error(
4085                riffdb_proto::application_error_to_proto(&ApplicationError::new(
4086                    code,
4087                    ApplicationOperation::BatchCommand,
4088                    ApplicationErrorContext::empty(),
4089                    None,
4090                )),
4091            )),
4092        }
4093    }
4094
4095    fn application_overloaded() -> ClientError {
4096        ClientError::Application(Box::new(ApplicationError::new(
4097            ApplicationErrorCode::Overloaded,
4098            ApplicationOperation::BatchCommand,
4099            ApplicationErrorContext::empty(),
4100            None,
4101        )))
4102    }
4103
4104    fn block_on_with_time<T>(future: impl std::future::Future<Output = T>) -> T {
4105        tokio::runtime::Builder::new_current_thread()
4106            .enable_time()
4107            .build()
4108            .expect("test runtime")
4109            .block_on(future)
4110    }
4111
4112    /// Scripted ExecuteRetryAttempt mirror of client.rs tests::ExecuteAttempts.
4113    struct ScriptedExecuteAttempts {
4114        results: std::collections::VecDeque<Result<v1::ExecuteCommandResponse, ClientError>>,
4115        requests: Vec<v1::ExecuteCommandRequest>,
4116    }
4117
4118    impl ScriptedExecuteAttempts {
4119        fn new(
4120            results: impl IntoIterator<Item = Result<v1::ExecuteCommandResponse, ClientError>>,
4121        ) -> Self {
4122            Self {
4123                results: results.into_iter().collect(),
4124                requests: Vec::new(),
4125            }
4126        }
4127    }
4128
4129    impl crate::client::ExecuteRetryAttempt for ScriptedExecuteAttempts {
4130        async fn submit_execute_attempt(
4131            &mut self,
4132            request: v1::ExecuteCommandRequest,
4133            _metadata: &CallMetadata,
4134        ) -> Result<v1::ExecuteCommandResponse, ClientError> {
4135            self.requests.push(request);
4136            self.results.pop_front().expect("scripted execute result")
4137        }
4138    }
4139
4140    struct FixedRequestIds {
4141        values: std::collections::VecDeque<riffdb_types::RequestId>,
4142    }
4143
4144    impl crate::client::RetryRequestIdSource for FixedRequestIds {
4145        fn next_request_id(
4146            &mut self,
4147        ) -> Result<riffdb_types::RequestId, crate::IdentifierGenerationError> {
4148            self.values
4149                .pop_front()
4150                .ok_or(crate::IdentifierGenerationError::EntropyUnavailable)
4151        }
4152    }
4153
4154    fn request_id(ordinal: u8) -> riffdb_types::RequestId {
4155        riffdb_types::RequestId::from_unix_milliseconds_and_random(
4156            u64::from(ordinal),
4157            [ordinal; 10],
4158        )
4159        .expect("request id")
4160    }
4161
4162    #[test]
4163    fn batch_items_non_retryable_errors_surface_without_reentry_candidates() {
4164        let prepared = vec![
4165            (0, stub_command("Ok", "k0")),
4166            (1, stub_command("Ok", "k1")),
4167            (2, stub_command("Ok", "k2")),
4168        ];
4169        let items = vec![
4170            v1::ExecuteCommandBatchItem {
4171                result: Some(v1::execute_command_batch_item::Result::Response(
4172                    stub_response("Ok"),
4173                )),
4174            },
4175            stub_error_item(ApplicationErrorCode::InputInvalid),
4176            stub_error_item(ApplicationErrorCode::AuthorizationDenied),
4177        ];
4178        let (resolved, reenter) = resolve_generated_batch_items(prepared, items);
4179        assert!(reenter.is_empty(), "non-retryable errors must not re-enter");
4180        assert_eq!(resolved.len(), 3);
4181        assert!(resolved[0].1.is_ok());
4182        assert!(matches!(
4183            &resolved[1].1,
4184            Err(GeneratedExecutionError::Client(ClientError::Application(error)))
4185                if error.code() == ApplicationErrorCode::InputInvalid
4186        ));
4187        assert!(matches!(
4188            &resolved[2].1,
4189            Err(GeneratedExecutionError::Client(ClientError::Application(error)))
4190                if error.code() == ApplicationErrorCode::AuthorizationDenied
4191        ));
4192        assert_eq!(
4193            resolved.iter().map(|(index, _)| *index).collect::<Vec<_>>(),
4194            vec![0, 1, 2]
4195        );
4196    }
4197
4198    #[test]
4199    fn batch_items_registry_retryable_errors_are_reentry_candidates() {
4200        let prepared = vec![
4201            (0, stub_command("A", "k0")),
4202            (1, stub_command("B", "k1")),
4203            (2, stub_command("C", "k2")),
4204            (3, stub_command("D", "k3")),
4205        ];
4206        let items = vec![
4207            v1::ExecuteCommandBatchItem {
4208                result: Some(v1::execute_command_batch_item::Result::Response(
4209                    stub_response("A"),
4210                )),
4211            },
4212            stub_error_item(ApplicationErrorCode::OutcomeUnknown),
4213            stub_error_item(ApplicationErrorCode::Overloaded),
4214            stub_error_item(ApplicationErrorCode::StorageUnavailable),
4215        ];
4216        let (resolved, reenter) = resolve_generated_batch_items(prepared, items);
4217        assert_eq!(resolved.len(), 1);
4218        assert!(resolved[0].1.is_ok());
4219        assert_eq!(
4220            reenter
4221                .iter()
4222                .map(|candidate| candidate.index)
4223                .collect::<Vec<_>>(),
4224            vec![1, 2, 3],
4225            "Retry and ResolveWithSameIdempotencyKey must re-enter"
4226        );
4227        assert!(reenter.iter().all(|c| c.protocol_failure.is_none()));
4228        assert_eq!(
4229            ApplicationErrorCode::Overloaded.recovery_action(),
4230            ApplicationRecoveryAction::Retry
4231        );
4232        assert_eq!(
4233            ApplicationErrorCode::OutcomeUnknown.recovery_action(),
4234            ApplicationRecoveryAction::ResolveWithSameIdempotencyKey
4235        );
4236    }
4237
4238    #[test]
4239    fn batch_items_corrupt_or_unset_error_arms_reenter() {
4240        let prepared = vec![
4241            (0, stub_command("A", "k0")),
4242            (1, stub_command("B", "k1")),
4243            (2, stub_command("C", "k2")),
4244        ];
4245        let corrupt = v1::ExecuteCommandBatchItem {
4246            result: Some(v1::execute_command_batch_item::Result::Error(
4247                app_v1::ApplicationError {
4248                    envelope_version: 0,
4249                    code: 0,
4250                    category: 0,
4251                    recovery_action: 0,
4252                    operation: 0,
4253                    ..Default::default()
4254                },
4255            )),
4256        };
4257        let items = vec![
4258            v1::ExecuteCommandBatchItem {
4259                result: Some(v1::execute_command_batch_item::Result::Response(
4260                    stub_response("A"),
4261                )),
4262            },
4263            corrupt,
4264            v1::ExecuteCommandBatchItem { result: None },
4265        ];
4266        let (resolved, reenter) = resolve_generated_batch_items(prepared, items);
4267        assert_eq!(resolved.len(), 1);
4268        assert_eq!(
4269            reenter
4270                .iter()
4271                .map(|candidate| candidate.index)
4272                .collect::<Vec<_>>(),
4273            vec![1, 2]
4274        );
4275        assert_eq!(
4276            reenter[0].protocol_failure.map(|f| f.kind()),
4277            Some(crate::ProtocolFailureKind::InvalidApplicationErrorDetails)
4278        );
4279        assert_eq!(
4280            reenter[1].protocol_failure.map(|f| f.kind()),
4281            Some(crate::ProtocolFailureKind::InvalidInboundMessage)
4282        );
4283    }
4284
4285    #[test]
4286    fn complete_batch_items_retries_all_overloaded_through_real_budget_and_succeeds() {
4287        use std::collections::HashMap;
4288        use std::sync::{Arc, Mutex};
4289
4290        let prepared = vec![
4291            (0, stub_command("Ok", "k0")),
4292            (1, stub_command("Ok", "k1")),
4293            (2, stub_command("Ok", "k2")),
4294        ];
4295        let items = vec![
4296            stub_error_item(ApplicationErrorCode::Overloaded),
4297            stub_error_item(ApplicationErrorCode::Overloaded),
4298            stub_error_item(ApplicationErrorCode::Overloaded),
4299        ];
4300        let attempt_counts: Arc<Mutex<HashMap<usize, usize>>> =
4301            Arc::new(Mutex::new(HashMap::new()));
4302        let recovered = block_on_with_time(complete_batch_items_with_reentry(
4303            prepared,
4304            items,
4305            |index, command| {
4306                let attempt_counts = Arc::clone(&attempt_counts);
4307                async move {
4308                    let generic = command.idempotent_command().expect("stub command shape");
4309                    let success = stub_response(command.outcome);
4310                    let mut attempts = ScriptedExecuteAttempts::new([
4311                        Err(application_overloaded()),
4312                        Ok(success.clone()),
4313                    ]);
4314                    let mut ids = FixedRequestIds {
4315                        values: [request_id(10 + index as u8), request_id(40 + index as u8)]
4316                            .into_iter()
4317                            .collect(),
4318                    };
4319                    let response = crate::client::execute_retry_attempts(
4320                        &mut attempts,
4321                        &generic,
4322                        AttemptBudget::new(3).expect("budget"),
4323                        &CallMetadata::default(),
4324                        &mut ids,
4325                    )
4326                    .await
4327                    .expect("capacity frees on second attempt");
4328                    attempt_counts
4329                        .lock()
4330                        .expect("counts")
4331                        .insert(index, attempts.requests.len());
4332                    let outcome = command
4333                        .decode_outcome(&response)
4334                        .map_err(GeneratedExecutionError::CommandShape)
4335                        .and_then(|outcome| typed_command_result(&command, outcome, response));
4336                    (index, outcome)
4337                }
4338            },
4339        ));
4340        assert_eq!(recovered.len(), 3);
4341        assert!(recovered.iter().all(|(_, result)| result.is_ok()));
4342        let counts = attempt_counts.lock().expect("counts");
4343        assert_eq!(counts.len(), 3);
4344        assert!(
4345            counts.values().all(|count| *count > 1),
4346            "mock must record multi-attempt real RetryState path: {counts:?}"
4347        );
4348    }
4349
4350    #[test]
4351    fn complete_batch_items_real_budget_exhaustion_surfaces_err_while_siblings_succeed() {
4352        use std::sync::Arc;
4353        use std::sync::atomic::{AtomicUsize, Ordering};
4354
4355        let prepared = vec![
4356            (0, stub_command("Ok", "k0")),
4357            (1, stub_command("Fail", "k1")),
4358            (2, stub_command("Ok", "k2")),
4359        ];
4360        let items = vec![
4361            v1::ExecuteCommandBatchItem {
4362                result: Some(v1::execute_command_batch_item::Result::Response(
4363                    stub_response("Ok"),
4364                )),
4365            },
4366            stub_error_item(ApplicationErrorCode::Overloaded),
4367            v1::ExecuteCommandBatchItem {
4368                result: Some(v1::execute_command_batch_item::Result::Response(
4369                    stub_response("Ok"),
4370                )),
4371            },
4372        ];
4373        let reenter_attempts = Arc::new(AtomicUsize::new(0));
4374        let mut recovered = block_on_with_time(complete_batch_items_with_reentry(
4375            prepared,
4376            items,
4377            |index, command| {
4378                let reenter_attempts = Arc::clone(&reenter_attempts);
4379                async move {
4380                    let generic = command.idempotent_command().expect("stub command shape");
4381                    // Budget of 2: both submissions fail Overloaded → Return after
4382                    // exactly two real execute_retry_attempts submissions.
4383                    let mut attempts = ScriptedExecuteAttempts::new([
4384                        Err(application_overloaded()),
4385                        Err(application_overloaded()),
4386                    ]);
4387                    let mut ids = FixedRequestIds {
4388                        values: [request_id(20), request_id(21)].into_iter().collect(),
4389                    };
4390                    let budget = AttemptBudget::new(2).expect("budget");
4391                    let error = crate::client::execute_retry_attempts(
4392                        &mut attempts,
4393                        &generic,
4394                        budget,
4395                        &CallMetadata::default(),
4396                        &mut ids,
4397                    )
4398                    .await
4399                    .expect_err("budget exhausted");
4400                    reenter_attempts.store(attempts.requests.len(), Ordering::SeqCst);
4401                    assert_eq!(
4402                        attempts.requests.len(),
4403                        budget.maximum_submissions() as usize
4404                    );
4405                    (index, Err(GeneratedExecutionError::Client(error)))
4406                }
4407            },
4408        ));
4409        recovered.sort_by_key(|(index, _)| *index);
4410        assert_eq!(reenter_attempts.load(Ordering::SeqCst), 2);
4411        assert!(recovered[0].1.is_ok());
4412        assert!(matches!(
4413            &recovered[1].1,
4414            Err(GeneratedExecutionError::Client(ClientError::Application(error)))
4415                if error.code() == ApplicationErrorCode::Overloaded
4416        ));
4417        assert!(recovered[2].1.is_ok());
4418    }
4419
4420    #[test]
4421    fn complete_batch_items_corrupt_error_arm_reenters_and_can_succeed() {
4422        let prepared = vec![
4423            (0, stub_command("Ok", "k0")),
4424            (1, stub_command("Replay", "k1")),
4425        ];
4426        let items = vec![
4427            v1::ExecuteCommandBatchItem {
4428                result: Some(v1::execute_command_batch_item::Result::Response(
4429                    stub_response("Ok"),
4430                )),
4431            },
4432            v1::ExecuteCommandBatchItem {
4433                result: Some(v1::execute_command_batch_item::Result::Error(
4434                    app_v1::ApplicationError {
4435                        envelope_version: 0,
4436                        code: 0,
4437                        category: 0,
4438                        recovery_action: 0,
4439                        operation: 0,
4440                        ..Default::default()
4441                    },
4442                )),
4443            },
4444        ];
4445        let mut recovered = block_on_with_time(complete_batch_items_with_reentry(
4446            prepared,
4447            items,
4448            |index, command| async move {
4449                (
4450                    index,
4451                    Ok(TypedCommandResult {
4452                        outcome: command.outcome.to_owned(),
4453                        commit_sequence: None,
4454                        contract_version: 1,
4455                        plan_hash: [0x55; 32],
4456                        replayed: true,
4457                        outcome_uri: None,
4458                        workflow_revisions: Vec::new(),
4459                    }),
4460                )
4461            },
4462        ));
4463        recovered.sort_by_key(|(index, _)| *index);
4464        assert_eq!(recovered.len(), 2);
4465        assert!(recovered[0].1.is_ok());
4466        assert_eq!(recovered[1].1.as_ref().expect("replayed").outcome, "Replay");
4467    }
4468
4469    #[test]
4470    fn complete_batch_items_corrupt_error_arm_surfaces_protocol_failure_on_reentry_exhaustion() {
4471        let prepared = vec![(0, stub_command("Replay", "k0"))];
4472        let items = vec![v1::ExecuteCommandBatchItem {
4473            result: Some(v1::execute_command_batch_item::Result::Error(
4474                app_v1::ApplicationError {
4475                    envelope_version: 0,
4476                    code: 0,
4477                    category: 0,
4478                    recovery_action: 0,
4479                    operation: 0,
4480                    ..Default::default()
4481                },
4482            )),
4483        }];
4484        let recovered = block_on_with_time(complete_batch_items_with_reentry(
4485            prepared,
4486            items,
4487            |index, _command| async move {
4488                // Re-entry itself fails (budget exhausted / still unknown).
4489                (
4490                    index,
4491                    Err(GeneratedExecutionError::Client(ClientError::Application(
4492                        Box::new(ApplicationError::new(
4493                            ApplicationErrorCode::Overloaded,
4494                            ApplicationOperation::BatchCommand,
4495                            ApplicationErrorContext::empty(),
4496                            None,
4497                        )),
4498                    ))),
4499                )
4500            },
4501        ));
4502        assert_eq!(recovered.len(), 1);
4503        assert!(matches!(
4504            &recovered[0].1,
4505            Err(GeneratedExecutionError::Client(ClientError::Protocol(failure)))
4506                if failure.kind() == crate::ProtocolFailureKind::InvalidApplicationErrorDetails
4507        ));
4508    }
4509
4510    #[test]
4511    fn record_generated_batch_item_completion_advances_checkpoint_in_production_order() {
4512        // Drive the production completion recorder (used by
4513        // execute_generated_command_batch_with_progress) with mixed Ok/Err and
4514        // out-of-order arrivals.
4515        let mut items = Vec::new();
4516        let mut state = BatchCheckpointState::new(0);
4517        let mut progress = Vec::new();
4518        let total = 3usize;
4519
4520        let ok = |label: &str| {
4521            Ok(TypedCommandResult {
4522                outcome: label.to_owned(),
4523                commit_sequence: None,
4524                contract_version: 1,
4525                plan_hash: [0x11; 32],
4526                replayed: false,
4527                outcome_uri: None,
4528                workflow_revisions: Vec::new(),
4529            })
4530        };
4531        let err = Err(GeneratedExecutionError::Client(ClientError::Application(
4532            Box::new(ApplicationError::new(
4533                ApplicationErrorCode::InputInvalid,
4534                ApplicationOperation::BatchCommand,
4535                ApplicationErrorContext::empty(),
4536                None,
4537            )),
4538        )));
4539
4540        // Out of order: 2, then 0, then 1(Err). Checkpoint stays 0 until 0 lands,
4541        // then 1, then 3 once the Err at 1 closes the prefix.
4542        record_generated_batch_item_completion(
4543            2,
4544            ok("two"),
4545            total,
4546            &mut state,
4547            &mut items,
4548            &mut |p| progress.push(p.checkpoint),
4549        );
4550        assert_eq!(state.checkpoint, 0);
4551        record_generated_batch_item_completion(
4552            0,
4553            ok("zero"),
4554            total,
4555            &mut state,
4556            &mut items,
4557            &mut |p| progress.push(p.checkpoint),
4558        );
4559        assert_eq!(state.checkpoint, 1);
4560        record_generated_batch_item_completion(1, err, total, &mut state, &mut items, &mut |p| {
4561            progress.push(p.checkpoint)
4562        });
4563        assert_eq!(state.checkpoint, 3);
4564        assert_eq!(progress, vec![0, 1, 3]);
4565        assert_eq!(items.len(), 3);
4566        assert!(
4567            items
4568                .iter()
4569                .any(|item| item.index == 1 && item.result.is_err())
4570        );
4571    }
4572
4573    #[test]
4574    fn record_generated_batch_item_completion_respects_resumed_checkpoint_seed() {
4575        let mut items = Vec::new();
4576        // Production seeds both completed and checkpoint from options.checkpoint.
4577        let mut state = BatchCheckpointState::new(2);
4578        let mut progress = Vec::new();
4579        let total = 4usize;
4580        let ok = |label: &str| {
4581            Ok(TypedCommandResult {
4582                outcome: label.to_owned(),
4583                commit_sequence: None,
4584                contract_version: 1,
4585                plan_hash: [0x22; 32],
4586                replayed: false,
4587                outcome_uri: None,
4588                workflow_revisions: Vec::new(),
4589            })
4590        };
4591        record_generated_batch_item_completion(
4592            2,
4593            ok("two"),
4594            total,
4595            &mut state,
4596            &mut items,
4597            &mut |p| progress.push((p.completed, p.checkpoint)),
4598        );
4599        record_generated_batch_item_completion(
4600            3,
4601            ok("three"),
4602            total,
4603            &mut state,
4604            &mut items,
4605            &mut |p| progress.push((p.completed, p.checkpoint)),
4606        );
4607        assert_eq!(state.checkpoint, 4);
4608        assert_eq!(state.completed, 4);
4609        assert_eq!(progress, vec![(3, 3), (4, 4)]);
4610    }
4611
4612    /// R3d: raised UUID bytes equal the text path after parse, without forcing
4613    /// text materialization on raise.
4614    #[test]
4615    fn raised_uuid_bytes_match_parsed_text_and_text_is_lazy() {
4616        let bytes = [
4617            0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab,
4618            0xcd, 0xef,
4619        ];
4620        let raised = raise_value(v1::Value {
4621            kind: Some(v1::value::Kind::UuidValue(bytes.to_vec())),
4622        })
4623        .expect("raise uuid");
4624        let ApplicationValue::Uuid(uuid) = raised else {
4625            panic!("expected uuid value");
4626        };
4627        assert!(!uuid.text_is_materialized(), "raise must not allocate text");
4628        assert_eq!(uuid.as_bytes(), &bytes);
4629        let text = uuid.as_str().to_owned();
4630        assert!(uuid.text_is_materialized());
4631        let from_text = ApplicationUuid::from_text(text.clone()).expect("parse text");
4632        assert_eq!(from_text.as_bytes(), &bytes);
4633        assert_eq!(from_text.into_string(), text);
4634        // Adapter-equivalence: bytes path and re-parsed text path agree.
4635        let re_lowered = lower_value(ApplicationValue::Uuid(ApplicationUuid::from_bytes(bytes)))
4636            .expect("lower bytes");
4637        let text_lowered = lower_value(ApplicationValue::Uuid(
4638            ApplicationUuid::from_text(text).expect("text"),
4639        ))
4640        .expect("lower text");
4641        assert_eq!(re_lowered, text_lowered);
4642    }
4643
4644    #[test]
4645    fn canonical_vector_values_round_trip_without_punning() {
4646        let vector =
4647            riffdb_types::CanonicalVector::new(vec![-0.0, 1.5, -2.25]).expect("canonical vector");
4648        let lowered = lower_value(ApplicationValue::Vector(vector.clone())).expect("lower");
4649        let Some(v1::value::Kind::VectorValue(wire)) = lowered.kind.as_ref() else {
4650            panic!("expected the dedicated vector wire arm");
4651        };
4652        assert_eq!(wire.components, vector.components());
4653        assert_eq!(
4654            raise_value(lowered).expect("raise"),
4655            ApplicationValue::Vector(vector)
4656        );
4657    }
4658
4659    #[test]
4660    fn non_finite_vector_response_is_rejected() {
4661        let result = raise_value(v1::Value {
4662            kind: Some(v1::value::Kind::VectorValue(v1::VectorValue {
4663                components: vec![f32::NAN],
4664            })),
4665        });
4666        assert!(matches!(
4667            result,
4668            Err(ApplicationClientError::InvalidResponse)
4669        ));
4670    }
4671
4672    // req: REP-004, REP-005, DRV-001, DRV-005
4673    #[test]
4674    fn driver_pool_and_application_client_failover_to_standby_and_route_replica_reads() {
4675        let runtime = tokio::runtime::Builder::new_current_thread()
4676            .enable_all()
4677            .build()
4678            .expect("current-thread runtime");
4679        runtime.block_on(async {
4680            let active_contract = |bundle_hash: [u8; 32]| v1::GetActiveContractResponse {
4681                result: Some(v1::get_active_contract_response::Result::Present(
4682                    v1::ContractDescriptor {
4683                        contract_lineage: "TicketDesk".to_owned(),
4684                        contract_version: 1,
4685                        bundle_hash: bundle_hash.to_vec(),
4686                        ..v1::ContractDescriptor::default()
4687                    },
4688                )),
4689                database_alias: "default".to_owned(),
4690            };
4691
4692            let primary = StableApplicationClient::scripted_for_test(active_contract([7; 32]))
4693                .push_scripted_command(Err(ClientError::Public(
4694                    riffdb_errors::PublicError::primary_fenced(),
4695                )));
4696            let standby_mismatched =
4697                StableApplicationClient::scripted_for_test(active_contract([9; 32]))
4698                    .push_scripted_command(Ok(stub_response("WrongStandby")));
4699            let query_response = |head: u64, outcome: &str| app_v1::ExecuteQueryResponse {
4700                identity: Some(app_v1::QueryIdentity {
4701                    contract_lineage: "TicketDesk".to_owned(),
4702                    contract_version: 1,
4703                    contract_bundle_hash: vec![7; 32],
4704                    query_name: Some("TicketPage".to_owned()),
4705                    plan_hash: vec![2; 32],
4706                    module_hash: Some(vec![3; 32]),
4707                }),
4708                outcome: outcome.to_owned(),
4709                application_head: head,
4710                fields: Vec::new(),
4711                next_cursor: None,
4712                selected_result_encoding: app_v1::NamedResultEncoding::LegacyRecords as i32,
4713                compact_result: None,
4714                packed_result: None,
4715            };
4716            let standby_promoted =
4717                StableApplicationClient::scripted_for_test(active_contract([7; 32]))
4718                    .push_scripted_command(Ok(v1::ExecuteCommandResponse {
4719                        status: v1::execute_command_response::CompletionStatus::Committed as i32,
4720                        commit_sequence: 19,
4721                        contract_version: 1,
4722                        plan_hash: vec![0x44; 32],
4723                        outcome_type: "Created".to_owned(),
4724                        outcome: Some(v1::Value {
4725                            kind: Some(v1::value::Kind::NullValue(
4726                                v1::NullValue::NullValue as i32,
4727                            )),
4728                        }),
4729                        provenance_uri: String::new(),
4730                        durability_mode: String::new(),
4731                        outcome_uri: Some("riffdb://outcomes/19".to_owned()),
4732                        history_incarnation: 2,
4733                    }))
4734                    .push_scripted_query(Ok(query_response(50, "PrimaryCaughtUp")));
4735            let replica = StableApplicationClient::scripted_for_test(active_contract([7; 32]))
4736                .push_scripted_query(Ok(query_response(18, "ReplicaAvailable")))
4737                .push_scripted_query(Err(ClientError::Application(Box::new(
4738                    ApplicationError::new(
4739                        ApplicationErrorCode::FreshnessUnsatisfied,
4740                        ApplicationOperation::ExecuteQuery,
4741                        ApplicationErrorContext::empty(),
4742                        None,
4743                    ),
4744                ))));
4745
4746            assert!(matches!(
4747                primary.clone().with_standby_clients(vec![
4748                    standby_promoted.clone(),
4749                    standby_promoted.clone(),
4750                    standby_promoted.clone(),
4751                    standby_promoted.clone(),
4752                    standby_promoted.clone(),
4753                ]),
4754                Err(ApplicationClientError::InvalidInput)
4755            ));
4756            assert!(matches!(
4757                primary.clone().with_read_replica_clients(vec![
4758                    replica.clone(),
4759                    replica.clone(),
4760                    replica.clone(),
4761                    replica.clone(),
4762                    replica.clone(),
4763                ]),
4764                Err(ApplicationClientError::InvalidInput)
4765            ));
4766
4767            let mut client = primary
4768                .clone()
4769                .with_standby_clients(vec![standby_mismatched.clone(), standby_promoted.clone()])
4770                .expect("bounded standbys")
4771                .with_read_replica_clients(vec![replica.clone()])
4772                .expect("bounded replicas");
4773            assert_eq!(client.standby_client_count(), 2);
4774            assert_eq!(client.read_replica_client_count(), 1);
4775
4776            let metadata = CallMetadata::default();
4777            client
4778                .verify_active_contract("default", "TicketDesk", 1, [7; 32], &metadata)
4779                .await
4780                .expect("verify primary active contract");
4781
4782            let command = ApplicationCommand::new(
4783                "CreateTicket",
4784                Some(1),
4785                BTreeMap::from([(
4786                    "title".to_owned(),
4787                    ApplicationValue::String("Failover ticket".to_owned()),
4788                )]),
4789            )
4790            .expect("command");
4791            let result = client
4792                .execute_command(
4793                    command,
4794                    AttemptBudget::new(2).expect("attempt budget"),
4795                    &metadata,
4796                )
4797                .await
4798                .expect("failover command execution");
4799            assert_eq!(result.outcome.as_deref(), Some("Created"));
4800            assert_eq!(result.commit_sequence, Some(19));
4801            assert_eq!(standby_mismatched.scripted_command_inputs().len(), 0);
4802            assert_eq!(primary.scripted_command_inputs().len(), 1);
4803            assert_eq!(
4804                primary.scripted_command_inputs(),
4805                standby_promoted.scripted_command_inputs(),
4806                "standby retry must preserve the exact command input and idempotency key from the fenced primary attempt"
4807            );
4808
4809            let base_query = NamedQuery::new(
4810                ApplicationContract::Exact {
4811                    lineage: "TicketDesk".to_owned(),
4812                    version: 1,
4813                    bundle_hash: Some([7; 32]),
4814                },
4815                "TicketPage",
4816                Some([3; 32]),
4817                BTreeMap::new(),
4818                None,
4819            )
4820            .expect("query")
4821            .expect_plan_hash([2; 32]);
4822
4823            let replica_result = client
4824                .execute_named_query(base_query.clone(), &metadata)
4825                .await
4826                .expect("replica query");
4827            assert_eq!(replica_result.outcome, "ReplicaAvailable");
4828            assert_eq!(replica.scripted_queries().len(), 1);
4829            assert_eq!(standby_promoted.scripted_queries().len(), 0);
4830
4831            let causal_query = base_query
4832                .with_options(QueryOptions::new().read_after_commit(50))
4833                .expect("causal query");
4834            let fallback_result = client
4835                .execute_named_query(causal_query, &metadata)
4836                .await
4837                .expect("fallback to promoted primary on replica lag");
4838            assert_eq!(fallback_result.outcome, "PrimaryCaughtUp");
4839            assert_eq!(replica.scripted_queries().len(), 2);
4840            assert_eq!(standby_promoted.scripted_queries().len(), 1);
4841        });
4842    }
4843
4844    // req: QRY-001, QRY-002, QRY-004, DRV-001
4845    #[test]
4846    fn named_query_page_stream_follows_cursors_and_verifies_pinned_snapshot() {
4847        let runtime = tokio::runtime::Builder::new_current_thread()
4848            .enable_all()
4849            .build()
4850            .expect("current-thread runtime");
4851        runtime.block_on(async {
4852            let active_contract = v1::GetActiveContractResponse {
4853                result: Some(v1::get_active_contract_response::Result::Present(
4854                    v1::ContractDescriptor {
4855                        contract_lineage: "TicketDesk".to_owned(),
4856                        contract_version: 1,
4857                        bundle_hash: vec![7; 32],
4858                        ..v1::ContractDescriptor::default()
4859                    },
4860                )),
4861                database_alias: "default".to_owned(),
4862            };
4863            let page_response =
4864                |head: u64, next_cursor: Option<&str>| app_v1::ExecuteQueryResponse {
4865                    identity: Some(app_v1::QueryIdentity {
4866                        contract_lineage: "TicketDesk".to_owned(),
4867                        contract_version: 1,
4868                        contract_bundle_hash: vec![7; 32],
4869                        query_name: Some("TicketPage".to_owned()),
4870                        plan_hash: vec![2; 32],
4871                        module_hash: Some(vec![3; 32]),
4872                    }),
4873                    outcome: "Found".to_owned(),
4874                    application_head: head,
4875                    fields: Vec::new(),
4876                    next_cursor: next_cursor.map(str::to_owned),
4877                    selected_result_encoding: app_v1::NamedResultEncoding::LegacyRecords as i32,
4878                    compact_result: None,
4879                    packed_result: None,
4880                };
4881
4882            let mut client = StableApplicationClient::scripted_for_test(active_contract.clone())
4883                .push_scripted_query(Ok(page_response(77, Some("cursor-page-2"))))
4884                .push_scripted_query(Ok(page_response(77, Some("cursor-page-3"))))
4885                .push_scripted_query(Ok(page_response(77, None)));
4886            let base_query = NamedQuery::new(
4887                ApplicationContract::Exact {
4888                    lineage: "TicketDesk".to_owned(),
4889                    version: 1,
4890                    bundle_hash: Some([7; 32]),
4891                },
4892                "TicketPage",
4893                Some([3; 32]),
4894                BTreeMap::new(),
4895                None,
4896            )
4897            .expect("query")
4898            .expect_plan_hash([2; 32]);
4899            let metadata = CallMetadata::default();
4900
4901            let pages = client
4902                .stream_named_query(base_query.clone(), &metadata)
4903                .collect_pages()
4904                .await
4905                .expect("stream all 3 pages");
4906            assert_eq!(pages.len(), 3);
4907            assert!(pages.iter().all(|p| p.application_head == 77));
4908            let scripted = client.scripted_queries();
4909            assert_eq!(scripted.len(), 3);
4910            assert_eq!(scripted[0], ("TicketPage".to_owned(), None, false));
4911            assert_eq!(scripted[1], ("TicketPage".to_owned(), Some(77), false));
4912            assert_eq!(scripted[2], ("TicketPage".to_owned(), Some(77), false));
4913
4914            // Snapshot head drift on page 2 is rejected with InvalidResponse
4915            let mut drifted_client = StableApplicationClient::scripted_for_test(active_contract)
4916                .push_scripted_query(Ok(page_response(77, Some("cursor-page-2"))))
4917                .push_scripted_query(Ok(page_response(78, None)));
4918            let err = drifted_client
4919                .stream_named_query(base_query, &metadata)
4920                .collect_pages()
4921                .await
4922                .expect_err("snapshot drift must fail closed");
4923            assert!(matches!(err, ApplicationClientError::InvalidResponse));
4924        });
4925    }
4926
4927    #[test]
4928    fn connect_uri_and_connect_reject_remote_cleartext_and_non_loopback_endpoints() {
4929        assert!(validate_loopback_cleartext_endpoint("http://127.0.0.1:7443").is_ok());
4930        assert!(validate_loopback_cleartext_endpoint("http://[::1]:7443").is_ok());
4931        for rejected in [
4932            "http://198.51.100.10:7443",
4933            "http://[2001:db8::1]:7443",
4934            "http://example.com:7443",
4935            "http://localhost:7443",
4936            "https://198.51.100.10:7443",
4937            "http://127.0.0.1:0",
4938            "http://127.0.0.1:07443",
4939            "http://127.0.0.1:7443/path",
4940            "http://user@127.0.0.1:7443",
4941        ] {
4942            assert!(
4943                validate_loopback_cleartext_endpoint(rejected).is_err(),
4944                "expected {rejected} to be rejected"
4945            );
4946        }
4947
4948        let runtime = tokio::runtime::Builder::new_current_thread()
4949            .enable_all()
4950            .build()
4951            .expect("tokio runtime");
4952        runtime.block_on(async {
4953            assert!(
4954                StableApplicationClient::connect_uri("http://198.51.100.10:7443".to_owned())
4955                    .await
4956                    .is_err()
4957            );
4958            assert!(
4959                StableApplicationClient::connect(Endpoint::from_static(
4960                    "http://198.51.100.10:7443"
4961                ))
4962                .await
4963                .is_err()
4964            );
4965        });
4966    }
4967}