Skip to main content

type_bridge/
remote.rs

1#![deny(missing_docs)]
2//! Proxy connections: generated queries executed by a TypeBridge server, one
3//! authenticated exchange per terminal.
4
5use std::future::Future;
6use std::marker::PhantomData;
7use std::pin::Pin;
8use std::sync::Arc;
9
10use type_bridge_contract::query_remote::RemoteCapabilities;
11use type_bridge_orm::_registry::DescriptorRegistry;
12use type_bridge_orm::query_v2_prepared::QueryAuthority;
13use type_bridge_orm::session::StagedExchangeFn;
14use type_bridge_orm::session::staged::TransactionOptions;
15use type_bridge_orm::{
16    AnswerCancellation, AnswerTransport, InstalledRuntimeProjection, ProxyEndpoint,
17    ProxyHttpTransport, ProxyQueryConnection, QueryExecutionDeadline, QueryExecutionResourceLimits,
18    QueryTarget, QueryTargetError, RemoteModelQueryV2Error, ValidatedMatchRequest,
19    ValidatedMatchResult, lower_remote_query_diagnostic,
20};
21
22use crate::Result;
23use crate::error::Error;
24use crate::query::QuerySession;
25use crate::schema::{Schema, SchemaPackage, Unbound};
26use crate::staged::Transaction;
27
28mod deprecated;
29#[allow(deprecated)]
30pub use deprecated::{
31    RemoteConnectionOptions, RemoteDatabase, RemoteQueryLimits, RemoteQueryTransport,
32};
33
34/// A caller-owned exchange with a TypeBridge server, for hosts that route or
35/// authenticate requests themselves. [`ProxyConnectionPolicy::new`] uses the
36/// built-in HTTP transport instead.
37///
38/// Implementations return the exact `/v2/capabilities` bytes and perform
39/// exactly one `/v2/query` exchange per terminal.
40pub trait ProxyExchange: Send + Sync + 'static {
41    /// Fetch the executor's exact signed capability advertisement.
42    fn capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>>;
43
44    /// Exchange one exact canonical request for one exact signed reply.
45    fn exchange<'a>(
46        &'a self,
47        request: &'a [u8],
48    ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>>;
49
50    /// Fetch the executor's staged (`GET /v3/capabilities`) advertisement.
51    /// The default refuses: an exchange that predates staged transactions
52    /// cannot open one.
53    fn staged_capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>> {
54        Box::pin(async { Err(staged_unsupported()) })
55    }
56
57    /// Exchange one exact staged request (`POST /v3/staged`) for its exact
58    /// signed reply. The default refuses.
59    fn exchange_staged<'a>(
60        &'a self,
61        _request: &'a [u8],
62    ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
63        Box::pin(async { Err(staged_unsupported()) })
64    }
65}
66
67fn staged_unsupported() -> Error {
68    connect_error(
69        type_bridge_contract::sdk_diagnostic::SdkExecutionDiagnostic::provider_failure(
70            type_bridge_contract::sdk_diagnostic::SdkProviderOperation::Connect,
71        ),
72    )
73}
74
75enum ProxyRoute {
76    Endpoint(ProxyEndpoint),
77    Http(ProxyHttpTransport),
78    Exchange(Arc<dyn ProxyExchange>),
79}
80
81/// Configuration of a proxy connection: where requests go, the answer-limit
82/// ceiling every session inherits, and optionally a pinned advertisement.
83///
84/// Both limits start at the proxy defaults
85/// ([`QueryExecutionResourceLimits::default_for`] on
86/// [`AnswerTransport::Proxy`]), the wire ceilings a default server enforces.
87pub struct ProxyConnectionPolicy {
88    scope: Option<String>,
89    semantic_profile: Option<String>,
90    connection_limits: QueryExecutionResourceLimits,
91    answer_limits: QueryExecutionResourceLimits,
92    route: ProxyRoute,
93    advertisement: Option<Vec<u8>>,
94    staged_advertisement: Option<Vec<u8>>,
95}
96
97impl std::fmt::Debug for ProxyConnectionPolicy {
98    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        formatter.write_str("ProxyConnectionPolicy([REDACTED])")
100    }
101}
102
103impl ProxyConnectionPolicy {
104    /// Reach the server at `endpoint` with the built-in HTTP transport.
105    #[must_use]
106    pub fn new(endpoint: ProxyEndpoint) -> Self {
107        Self::with_route(ProxyRoute::Endpoint(endpoint))
108    }
109
110    /// Reach the server through a caller-owned exchange.
111    #[must_use]
112    pub fn with_exchange(exchange: impl ProxyExchange) -> Self {
113        Self::with_route(ProxyRoute::Exchange(Arc::new(exchange)))
114    }
115
116    fn with_route(route: ProxyRoute) -> Self {
117        Self {
118            scope: None,
119            semantic_profile: None,
120            connection_limits: QueryExecutionResourceLimits::default_for(AnswerTransport::Proxy),
121            answer_limits: QueryExecutionResourceLimits::default_for(AnswerTransport::Proxy),
122            route,
123            advertisement: None,
124            staged_advertisement: None,
125        }
126    }
127
128    /// Pin the staged (`GET /v3/capabilities`) advertisement, provisioned
129    /// out of band. It must name the same executor and reply key as the
130    /// connection's advertisement; staged transactions then never fetch it.
131    #[must_use]
132    pub fn staged_advertisement(mut self, staged_advertisement: Vec<u8>) -> Self {
133        self.staged_advertisement = Some(staged_advertisement);
134        self
135    }
136
137    /// Set the deadline for connecting, which fetches the advertisement.
138    #[must_use]
139    pub const fn connection_limits(mut self, limits: QueryExecutionResourceLimits) -> Self {
140        self.connection_limits = limits.effective();
141        self
142    }
143
144    /// Set the ceiling every session of this connection is constrained by.
145    #[must_use]
146    pub const fn answer_limits(mut self, limits: QueryExecutionResourceLimits) -> Self {
147        self.answer_limits = limits.effective();
148        self
149    }
150
151    /// Use these exact advertisement bytes, provisioned out of band, instead
152    /// of fetching them when connecting.
153    #[must_use]
154    pub fn advertisement(mut self, advertisement: Vec<u8>) -> Self {
155        self.advertisement = Some(advertisement);
156        self
157    }
158
159    /// Name the managed scope and semantic profile for a schema package that
160    /// does not embed its authority. A package that embeds them must agree.
161    #[must_use]
162    pub fn authority(
163        mut self,
164        scope: impl Into<String>,
165        semantic_profile: impl Into<String>,
166    ) -> Self {
167        self.scope = Some(scope.into());
168        self.semantic_profile = Some(semantic_profile.into());
169        self
170    }
171}
172
173struct RemoteRuntime {
174    connection: ProxyQueryConnection,
175    // `None` when the built-in route performs the exchange.
176    exchange: Option<Arc<dyn ProxyExchange>>,
177}
178
179/// A proxy connection branded by schema `S`. Each generated query terminal
180/// is one exchange with the server; a staged [`ProxyDatabase::transaction`]
181/// sends its whole stack as one signed `query-remote/v3` exchange at commit.
182pub struct ProxyDatabase<S: Schema = Unbound> {
183    options: Option<ProxyConnectionPolicy>,
184    runtime: Option<Arc<RemoteRuntime>>,
185    installed: Option<Arc<InstalledRuntimeProjection>>,
186    registry: Option<Arc<DescriptorRegistry>>,
187    marker: PhantomData<fn() -> S>,
188}
189
190impl<S: Schema> std::fmt::Debug for ProxyDatabase<S> {
191    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        formatter
193            .debug_struct("ProxyDatabase")
194            .field("schema_bound", &self.installed.is_some())
195            .finish_non_exhaustive()
196    }
197}
198
199impl ProxyDatabase<Unbound> {
200    /// Open the route and fetch the executor's advertisement, unless one is
201    /// pinned, then validate it.
202    pub async fn connect(options: ProxyConnectionPolicy) -> Result<Self> {
203        Self::connect_with_cancellation(options, AnswerCancellation::default()).await
204    }
205
206    /// [`Self::connect`] with a cancellation owner for the advertisement
207    /// fetch.
208    pub async fn connect_with_cancellation(
209        mut options: ProxyConnectionPolicy,
210        cancellation: AnswerCancellation,
211    ) -> Result<Self> {
212        let deadline = QueryExecutionDeadline::for_limits(options.connection_limits);
213        if let ProxyRoute::Endpoint(endpoint) = &options.route {
214            options.route =
215                ProxyRoute::Http(ProxyHttpTransport::open(endpoint).map_err(connect_error)?);
216        }
217        let advertisement = match (options.advertisement.take(), &options.route) {
218            (Some(pinned), _) => pinned,
219            (None, ProxyRoute::Http(http)) => http
220                .capabilities(deadline, &cancellation)
221                .await
222                .map_err(connect_error)?,
223            (None, ProxyRoute::Exchange(exchange)) => {
224                await_proxy(exchange.capabilities(), &cancellation, deadline).await?
225            }
226            (None, ProxyRoute::Endpoint(_)) => unreachable!("the endpoint was opened above"),
227        };
228        RemoteCapabilities::decode(&advertisement).map_err(remote_diagnostic)?;
229        options.advertisement = Some(advertisement);
230        Ok(Self {
231            options: Some(options),
232            runtime: None,
233            installed: None,
234            registry: None,
235            marker: PhantomData,
236        })
237    }
238
239    /// Verify and bind one generated schema package and its remote authority.
240    pub fn with_schema<S: Schema>(mut self, schema: SchemaPackage<S>) -> Result<ProxyDatabase<S>> {
241        let (installed, embedded_authority) = schema.verify_and_install_with_authority()?;
242        let registry = Arc::new(installed.match_registry().map_err(Error::from_orm)?);
243        let options = self.options.take().ok_or_else(|| Error::Other {
244            message: "proxy connection policy is unavailable".into(),
245            source: None,
246        })?;
247        let authority = if let Some(embedded) = embedded_authority {
248            let embedded_scope = embedded.managed_scope().id().as_str();
249            let embedded_profile = embedded.semantic_profile().id().as_str();
250            if options
251                .scope
252                .as_deref()
253                .is_some_and(|scope| scope != embedded_scope)
254                || options
255                    .semantic_profile
256                    .as_deref()
257                    .is_some_and(|profile| profile != embedded_profile)
258            {
259                return Err(Error::SchemaVerification {
260                    message: "proxy policy authority disagrees with the generated schema authority"
261                        .into(),
262                    source: None,
263                });
264            }
265            let declared =
266                type_bridge_contract::schema::encode_declared_schema(embedded.declared_schema())
267                    .map_err(|error| Error::SchemaVerification {
268                        message: "verified generated authority cannot reconstruct its declaration"
269                            .into(),
270                        source: Some(Box::new(error)),
271                    })?;
272            QueryAuthority::from_declared_bytes(&declared, embedded_scope, embedded_profile)
273                .map_err(remote_diagnostic)?
274        } else {
275            let declared =
276                schema
277                    .declared_schema_json()
278                    .ok_or_else(|| Error::SchemaVerification {
279                        message: "generated schema package omits remote declared-schema authority"
280                            .into(),
281                        source: None,
282                    })?;
283            let scope = options
284                .scope
285                .as_deref()
286                .ok_or_else(|| Error::SchemaVerification {
287                    message: "schema package has no embedded managed scope".into(),
288                    source: None,
289                })?;
290            let semantic_profile =
291                options
292                    .semantic_profile
293                    .as_deref()
294                    .ok_or_else(|| Error::SchemaVerification {
295                        message: "schema package has no embedded semantic profile".into(),
296                        source: None,
297                    })?;
298            QueryAuthority::from_declared_bytes(declared.as_bytes(), scope, semantic_profile)
299                .map_err(remote_diagnostic)?
300        };
301        if !authority.matches_semantic_fingerprint(installed.projection().semantic_fingerprint()) {
302            return Err(Error::SchemaVerification {
303                message: "remote declared-schema authority does not match the generated projection"
304                    .into(),
305                source: None,
306            });
307        }
308        let advertisement = options.advertisement.ok_or_else(|| Error::Other {
309            message: "remote capability advertisement is unavailable".into(),
310            source: None,
311        })?;
312        let (http, exchange) = match options.route {
313            ProxyRoute::Http(http) => (Some(http), None),
314            ProxyRoute::Exchange(exchange) => (None, Some(exchange)),
315            ProxyRoute::Endpoint(_) => unreachable!("the endpoint is opened when connecting"),
316        };
317        let connection = ProxyQueryConnection::new(
318            http,
319            advertisement,
320            Arc::new(authority),
321            options.answer_limits,
322        )
323        .map_err(connect_error)?;
324        let connection = match options.staged_advertisement {
325            Some(staged) => connection
326                .with_staged_advertisement(staged)
327                .map_err(connect_error)?,
328            None => connection,
329        };
330        let runtime = Arc::new(RemoteRuntime {
331            connection,
332            exchange,
333        });
334        Ok(ProxyDatabase {
335            options: None,
336            runtime: Some(runtime),
337            installed: Some(installed),
338            registry: Some(registry),
339            marker: PhantomData,
340        })
341    }
342}
343
344impl<S: Schema> ProxyDatabase<S> {
345    /// Open a staged transaction over this proxy.
346    ///
347    /// It has the same API as a direct
348    /// [`Database::transaction`](crate::Database::transaction): `stage`
349    /// queues [`Plan`](crate::plan::Plan)s, and `commit` sends them as one
350    /// signed `query-remote/v3` envelope with a fresh nonce and verifies the
351    /// signed reply. A lost reply is `commit_outcome_unknown`: the stack may
352    /// have applied, and the caller reads the database. The staged advertisement is
353    /// pinned on the policy, or fetched on first use and verified against
354    /// the connection's executor and reply key, then reused; nothing else is
355    /// sent until commit.
356    ///
357    /// # Errors
358    ///
359    /// Returns an error before [`ProxyDatabase::with_schema`], or when the
360    /// staged advertisement cannot be fetched or decoded.
361    pub async fn transaction(&self, options: TransactionOptions) -> Result<Transaction<S>> {
362        let runtime = self.runtime.as_ref().ok_or_else(remote_not_bound)?;
363        let cancellation = AnswerCancellation::default();
364        let Some(exchange) = &runtime.exchange else {
365            return runtime
366                .connection
367                .staged_transaction(options, &cancellation)
368                .await
369                .map(Transaction::new)
370                .map_err(connect_error);
371        };
372        // A fetched staged advertisement is checked against the connection's
373        // executor and reply key before it is trusted, then reused.
374        let advertisement = match runtime.connection.staged_advertisement() {
375            Some(advertisement) => advertisement.to_vec(),
376            None => {
377                let deadline =
378                    QueryExecutionDeadline::for_limits(runtime.connection.answer_limits());
379                await_proxy(exchange.staged_capabilities(), &cancellation, deadline).await?
380            }
381        };
382        let exchange = Arc::clone(exchange);
383        let send: StagedExchangeFn = Arc::new(move |bytes| {
384            let exchange = Arc::clone(&exchange);
385            Box::pin(async move {
386                // Any exchange error leaves the outcome unknown.
387                exchange.exchange_staged(&bytes).await.map_err(|_| {
388                    type_bridge_contract::sdk_diagnostic::SdkExecutionDiagnostic::provider_failure(
389                        type_bridge_contract::sdk_diagnostic::SdkProviderOperation::Write,
390                    )
391                })
392            })
393        });
394        runtime
395            .connection
396            .staged_transaction_with_exchange(&advertisement, send, options)
397            .map(Transaction::new)
398            .map_err(connect_error)
399    }
400
401    /// Start one owner-branded query session over this proxy connection.
402    pub fn query(&self) -> Result<QuerySession<'_, S>> {
403        let runtime = self.runtime.as_ref().ok_or_else(remote_not_bound)?;
404        self.query_with_resources(
405            runtime.connection.answer_limits(),
406            AnswerCancellation::default(),
407        )
408    }
409
410    /// Start one query session whose resources are `resources` constrained
411    /// by this connection's answer-limit ceiling, with a caller-owned
412    /// cancellation signal.
413    pub fn query_with_resources(
414        &self,
415        resources: QueryExecutionResourceLimits,
416        cancellation: AnswerCancellation,
417    ) -> Result<QuerySession<'_, S>> {
418        let installed = self.installed.as_deref().ok_or_else(remote_not_bound)?;
419        let registry = self.registry.as_ref().ok_or_else(remote_not_bound)?;
420        let runtime = self.runtime.as_ref().ok_or_else(remote_not_bound)?;
421        Ok(QuerySession::remote(
422            installed,
423            Arc::clone(registry),
424            self,
425            resources.constrained_by(runtime.connection.answer_limits()),
426            cancellation,
427        ))
428    }
429
430    pub(crate) async fn execute_match(
431        &self,
432        registry: &DescriptorRegistry,
433        validated: ValidatedMatchRequest,
434        resources: QueryExecutionResourceLimits,
435        cancellation: AnswerCancellation,
436        deadline: QueryExecutionDeadline,
437    ) -> Result<(ValidatedMatchRequest, ValidatedMatchResult)> {
438        let runtime = self.runtime.as_ref().ok_or_else(remote_not_bound)?;
439        let Some(exchange) = &runtime.exchange else {
440            return QueryTarget::Proxy(&runtime.connection)
441                .execute(registry, validated, resources, &cancellation, deadline)
442                .await
443                .map_err(target_error);
444        };
445        let pending = runtime
446            .connection
447            .prepare(registry, validated, resources, &cancellation, deadline)
448            .map_err(target_error)?;
449        let response = await_proxy(
450            exchange.exchange(pending.request_bytes()),
451            &cancellation,
452            deadline,
453        )
454        .await?;
455        ProxyQueryConnection::finish(&pending, &response, &cancellation, deadline)
456            .map_err(target_error)
457    }
458}
459
460async fn await_proxy(
461    exchange: impl Future<Output = Result<Vec<u8>>>,
462    cancellation: &AnswerCancellation,
463    deadline: QueryExecutionDeadline,
464) -> Result<Vec<u8>> {
465    check_remote_execution_budget(cancellation, deadline)?;
466    tokio::pin!(exchange);
467    let cancellation_wait = cancellation.cancelled();
468    tokio::pin!(cancellation_wait);
469    let timeout = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline.instant()));
470    tokio::pin!(timeout);
471    let result = tokio::select! {
472        biased;
473        result = &mut exchange => result,
474        () = &mut cancellation_wait => Err(remote_cancelled()),
475        () = &mut timeout => Err(remote_timeout()),
476    };
477    check_remote_execution_budget(cancellation, deadline)?;
478    result
479}
480
481fn check_remote_execution_budget(
482    cancellation: &AnswerCancellation,
483    deadline: QueryExecutionDeadline,
484) -> Result<()> {
485    deadline
486        .check(cancellation)
487        .map_err(|error| Error::from_sdk_execution(error, crate::ModelValidationPhase::Input))
488}
489
490fn remote_cancelled() -> Error {
491    Error::classified(
492        crate::ErrorCategory::Cancelled,
493        None,
494        "provider_cancelled",
495        Vec::new(),
496        "query execution was cancelled",
497        None,
498    )
499}
500
501fn remote_timeout() -> Error {
502    Error::classified(
503        crate::ErrorCategory::ResourceLimit,
504        None,
505        "transaction_deadline_exceeded",
506        Vec::new(),
507        "query execution exceeded its timeout",
508        None,
509    )
510}
511
512fn remote_not_bound() -> Error {
513    Error::ModelValidation {
514        phase: crate::ModelValidationPhase::Input,
515        code: "schema_not_bound".into(),
516        path: vec![],
517        message: "remote database is not schema-bound".into(),
518        source: None,
519    }
520}
521
522/// Lower a terminal failure, keeping the phase it happened in.
523pub(crate) fn target_error(error: QueryTargetError) -> Error {
524    match error {
525        QueryTargetError::Direct(error) => Error::from_orm_hydration(error),
526        QueryTargetError::Prepare(error) => remote_model_input_error(error),
527        QueryTargetError::Reply(error) => remote_model_hydration_error(error),
528        QueryTargetError::Interrupted(error) => {
529            Error::from_sdk_execution(error, crate::ModelValidationPhase::Input)
530        }
531    }
532}
533
534fn connect_error(error: type_bridge_contract::sdk_diagnostic::SdkExecutionDiagnostic) -> Error {
535    Error::from_sdk_execution(error, crate::ModelValidationPhase::Input)
536}
537
538fn remote_diagnostic(error: type_bridge_contract::diagnostic::Diagnostic) -> Error {
539    Error::from_sdk_execution(
540        lower_remote_query_diagnostic(error),
541        crate::ModelValidationPhase::Input,
542    )
543}
544
545fn remote_model_input_error(error: RemoteModelQueryV2Error) -> Error {
546    match error {
547        RemoteModelQueryV2Error::Diagnostic(error) => Error::from_sdk_execution(
548            lower_remote_query_diagnostic(error),
549            crate::ModelValidationPhase::Input,
550        ),
551        RemoteModelQueryV2Error::Match(error) => {
552            Error::from_match(error, crate::ModelValidationPhase::Input)
553        }
554    }
555}
556
557fn remote_model_hydration_error(error: RemoteModelQueryV2Error) -> Error {
558    match error {
559        RemoteModelQueryV2Error::Diagnostic(error) => Error::from_sdk_execution(
560            lower_remote_query_diagnostic(error),
561            crate::ModelValidationPhase::Hydration,
562        ),
563        RemoteModelQueryV2Error::Match(error) => {
564            Error::from_match(error, crate::ModelValidationPhase::Hydration)
565        }
566    }
567}
568
569#[cfg(test)]
570mod tests {
571    #[test]
572    fn a_default_proxy_policy_carries_the_proxy_defaults() {
573        use super::{
574            AnswerTransport, ProxyConnectionPolicy, ProxyEndpoint, QueryExecutionResourceLimits,
575        };
576
577        let policy = ProxyConnectionPolicy::new(ProxyEndpoint::new("http://127.0.0.1:1"));
578        let proxy = QueryExecutionResourceLimits::default_for(AnswerTransport::Proxy);
579        assert_eq!(policy.answer_limits, proxy);
580        assert_eq!(policy.connection_limits, proxy);
581        assert_ne!(
582            proxy,
583            QueryExecutionResourceLimits::default(),
584            "a proxy connection does not inherit the looser direct defaults"
585        );
586    }
587
588    use std::env;
589    use std::fs::{self, OpenOptions};
590    use std::io::Write as _;
591    use std::path::{Path, PathBuf};
592    use std::sync::Mutex;
593    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
594
595    use sha2::{Digest as _, Sha256};
596    use tokio::sync::Notify;
597    use type_bridge_contract::capability::{CapabilityId, CapabilitySet};
598    use type_bridge_contract::codec::to_canonical_json;
599    use type_bridge_contract::diagnostic::{
600        Diagnostic, DiagnosticCategory, DiagnosticCode, DiagnosticPath, DiagnosticPathSegment,
601    };
602    use type_bridge_contract::fingerprint::SemanticProfileId;
603    use type_bridge_contract::managed_scope::ManagedScopeId;
604    use type_bridge_contract::migration_assertion::BindingId;
605    use type_bridge_contract::projection::{BindingTarget, ProjectionConfig};
606    use type_bridge_contract::query_plan::{ModelQueryV2, query_plan_v2_capability_vocabulary};
607    use type_bridge_contract::query_remote::RemoteExecutorBinding;
608    use type_bridge_contract::query_remote_v2::{
609        CAP_QUERY_REMOTE_STATEMENT_LIMIT, HydrationGraphV2, RemoteOutcomeV2, RemoteQueryFailureV2,
610        RemoteQueryRequestV2, RemoteQueryResponseV2, RemoteReducedValueV2, RemoteReductionRowV2,
611        RemoteResultKindV2, query_remote_v2_required_capabilities,
612    };
613    use type_bridge_contract::schema::{DocumentId, encode_declared_schema};
614    use type_bridge_orm::OrmError;
615    use type_bridge_orm::match_request::CapabilitySet as MatchCapabilitySet;
616    use type_bridge_orm::match_request::SessionHandle;
617    use type_bridge_orm::query_v2_remote::RemoteReplySigningKey;
618    use type_bridge_orm::session::backend::{
619        BoxFuture, DriverBackend, QueryResult, TransactionOps, TxType,
620    };
621    use type_bridge_schema::{
622        ManagedDeltaContext, SchemaDocumentSet, build_schema_authority, encode_schema_authority,
623        normalize_documents, project, resolve,
624    };
625    use type_bridge_schema_codegen::RustEmitter;
626
627    use super::*;
628    use crate::__codegen::{
629        self, CompleteModel, EncodedCreate, EntityModel, HydratedRow, HydrationCapability,
630        IntoEncodedCreate, MaterializeModel, Model, ThingModel, ValidationError,
631    };
632    use crate::schema::sealed;
633
634    struct TestSchema;
635    impl sealed::Sealed for TestSchema {}
636    impl Schema for TestSchema {}
637
638    #[derive(Debug)]
639    struct Person;
640    impl sealed::Sealed for Person {}
641    impl Model for Person {
642        type Schema = TestSchema;
643        const TYPE_ID_JSON: &'static str = r#"{"kind":"entity","label":"person"}"#;
644    }
645    impl ThingModel for Person {
646        fn thing_kind() -> __codegen::ThingKind {
647            __codegen::ThingKind::Entity
648        }
649    }
650    impl EntityModel for Person {}
651    impl CompleteModel for Person {
652        type Create = PersonCreate;
653
654        fn iid(&self) -> &str {
655            unreachable!()
656        }
657    }
658    impl MaterializeModel for Person {
659        fn materialize(
660            _: &HydratedRow,
661            _: &HydrationCapability,
662        ) -> std::result::Result<Self, ValidationError> {
663            Ok(Self)
664        }
665    }
666
667    #[derive(Clone)]
668    struct PersonCreate;
669    impl sealed::Sealed for PersonCreate {}
670    impl IntoEncodedCreate for PersonCreate {
671        fn into_encoded_create(self) -> std::result::Result<EncodedCreate, ValidationError> {
672            Ok(EncodedCreate::new(Person::TYPE_ID_JSON, vec![], vec![]))
673        }
674    }
675
676    #[derive(Default)]
677    struct DirectCancellationState {
678        entered: Notify,
679        opens: AtomicUsize,
680        statements: AtomicUsize,
681        closes: AtomicUsize,
682    }
683
684    struct DirectCancellationBackend {
685        state: Arc<DirectCancellationState>,
686    }
687
688    impl DriverBackend for DirectCancellationBackend {
689        fn match_capabilities(&self) -> MatchCapabilitySet {
690            MatchCapabilitySet::all()
691        }
692
693        fn open_transaction(
694            &self,
695            _database: &str,
696            _tx_type: TxType,
697        ) -> BoxFuture<'_, std::result::Result<Box<dyn TransactionOps>, OrmError>> {
698            let state = Arc::clone(&self.state);
699            Box::pin(async move {
700                state.opens.fetch_add(1, AtomicOrdering::SeqCst);
701                Ok(Box::new(DirectCancellationTransaction { state }) as Box<dyn TransactionOps>)
702            })
703        }
704
705        fn is_open(&self) -> bool {
706            true
707        }
708    }
709
710    struct DirectCancellationTransaction {
711        state: Arc<DirectCancellationState>,
712    }
713
714    impl TransactionOps for DirectCancellationTransaction {
715        fn query(
716            &mut self,
717            _typeql: &str,
718        ) -> BoxFuture<'_, std::result::Result<QueryResult, OrmError>> {
719            let state = Arc::clone(&self.state);
720            Box::pin(async move {
721                state.statements.fetch_add(1, AtomicOrdering::SeqCst);
722                state.entered.notify_one();
723                std::future::pending().await
724            })
725        }
726
727        fn commit(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
728            Box::pin(async { Ok(()) })
729        }
730
731        fn rollback(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
732            Box::pin(async { Ok(()) })
733        }
734
735        fn close(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
736            self.state.closes.fetch_add(1, AtomicOrdering::SeqCst);
737            Box::pin(async { Ok(()) })
738        }
739    }
740
741    fn direct_cancellation_database(
742        state: Arc<DirectCancellationState>,
743    ) -> crate::session::Database<TestSchema> {
744        let generated = package();
745        let installed = Arc::into_inner(
746            generated
747                .verify_and_install()
748                .expect("Rust cancellation proof installs the generated package"),
749        )
750        .expect("a fresh installation has one owner");
751        crate::session::Database::from_test_parts(
752            type_bridge_orm::Database::with_backend(
753                Box::new(DirectCancellationBackend { state }),
754                "rust-queries-proof",
755            ),
756            installed,
757        )
758    }
759
760    async fn observe_sdk_queries_direct_cancellation() -> serde_json::Value {
761        let pre_state = Arc::new(DirectCancellationState::default());
762        let pre_database = direct_cancellation_database(Arc::clone(&pre_state));
763        let pre_signal = AnswerCancellation::default();
764        pre_signal.cancel();
765        let mut pre_session = pre_database
766            .query_with_resources(QueryExecutionResourceLimits::default(), pre_signal)
767            .expect("Rust direct cancellation proof opens a generated session");
768        let pre_person = pre_session
769            .exact::<Person>()
770            .expect("Rust direct cancellation proof binds a generated model");
771        let pre_result = pre_session
772            .query(pre_person)
773            .expect("Rust direct cancellation proof authors a generated query")
774            .count()
775            .await;
776        let pre_partial_result = pre_result.is_ok();
777        let pre_error = pre_result.expect_err("pre-cancellation rejects the generated terminal");
778        let pre_provider_calls = pre_state.opens.load(AtomicOrdering::SeqCst)
779            + pre_state.statements.load(AtomicOrdering::SeqCst);
780        assert_eq!(pre_error.category(), crate::ErrorCategory::Cancelled);
781        assert_eq!(pre_error.code(), Some("provider_cancelled"));
782        assert!(!pre_partial_result);
783        assert_eq!(pre_provider_calls, 0);
784
785        let in_flight_state = Arc::new(DirectCancellationState::default());
786        let in_flight_database = direct_cancellation_database(Arc::clone(&in_flight_state));
787        let in_flight_signal = AnswerCancellation::default();
788        let requester_state = Arc::clone(&in_flight_state);
789        let requester_signal = in_flight_signal.clone();
790        let requester = tokio::spawn(async move {
791            tokio::time::timeout(
792                std::time::Duration::from_secs(5),
793                requester_state.entered.notified(),
794            )
795            .await
796            .expect("direct provider await is reached before cancellation");
797            requester_signal.cancel();
798            true
799        });
800        let mut in_flight_session = in_flight_database
801            .query_with_resources(QueryExecutionResourceLimits::default(), in_flight_signal)
802            .expect("Rust in-flight cancellation proof opens a generated session");
803        let in_flight_person = in_flight_session
804            .exact::<Person>()
805            .expect("Rust in-flight cancellation proof binds a generated model");
806        let in_flight_result = tokio::time::timeout(
807            std::time::Duration::from_secs(5),
808            in_flight_session
809                .query(in_flight_person)
810                .expect("Rust in-flight cancellation proof authors a generated query")
811                .count(),
812        )
813        .await
814        .expect("cancellation wakes the pending provider await");
815        let in_flight_partial_result = in_flight_result.is_ok();
816        let in_flight_error =
817            in_flight_result.expect_err("in-flight cancellation rejects the generated terminal");
818        let provider_await_woken = requester
819            .await
820            .expect("direct cancellation requester completes")
821            && in_flight_state.statements.load(AtomicOrdering::SeqCst) == 1;
822        assert_eq!(in_flight_error.category(), crate::ErrorCategory::Cancelled);
823        assert_eq!(in_flight_error.code(), Some("provider_cancelled"));
824        assert!(!in_flight_partial_result);
825        assert!(provider_await_woken);
826        assert_eq!(in_flight_state.opens.load(AtomicOrdering::SeqCst), 1);
827        assert_eq!(in_flight_state.closes.load(AtomicOrdering::SeqCst), 1);
828
829        serde_json::json!({
830            "in_flight": {
831                "category": in_flight_error.category().as_str(),
832                "code": in_flight_error.code().expect("cancelled errors carry a stable code"),
833                "partial_result": in_flight_partial_result,
834                "provider_await_woken": provider_await_woken,
835            },
836            "pre_dispatch": {
837                "category": pre_error.category().as_str(),
838                "code": pre_error.code().expect("cancelled errors carry a stable code"),
839                "partial_result": pre_partial_result,
840                "provider_calls": pre_provider_calls,
841            },
842        })
843    }
844
845    #[test]
846    fn local_and_remote_failures_preserve_classification_codes_and_paths() {
847        let session = SessionHandle::new(Arc::new(DescriptorRegistry::new()));
848        let match_error = match session.exact("missing") {
849            Err(OrmError::Match(error)) => error,
850            Err(other) => panic!("unexpected ORM error: {other:?}"),
851            Ok(_) => panic!("missing descriptor unexpectedly resolved"),
852        };
853        let local = Error::from_orm(OrmError::Match(match_error.clone()));
854        let remote = remote_model_input_error(RemoteModelQueryV2Error::Match(match_error));
855
856        assert_eq!(local.category(), crate::ErrorCategory::QueryAuthoring);
857        assert_eq!(remote.category(), local.category());
858        assert_eq!(remote.code(), Some("unknown_descriptor"));
859        assert_eq!(remote.code(), local.code());
860        assert_eq!(remote.path(), local.path());
861        assert_eq!(
862            remote.model_validation_phase(),
863            local.model_validation_phase()
864        );
865
866        let diagnostic = Diagnostic::new(
867            DiagnosticCategory::UnsupportedCapability,
868            DiagnosticCode::new("missing_remote_capability").unwrap(),
869            "the remote executor does not advertise one required capability",
870        )
871        .at(DiagnosticPathSegment::Field("capabilities".into()))
872        .at(DiagnosticPathSegment::Index(2));
873        let classified = remote_diagnostic(diagnostic);
874
875        assert_eq!(classified.category(), crate::ErrorCategory::Capability);
876        assert_eq!(classified.code(), Some("missing_remote_capability"));
877        assert_eq!(
878            classified.path(),
879            Some(&["capabilities".to_owned(), "[2]".to_owned()][..])
880        );
881        assert_eq!(classified.model_validation_phase(), None);
882    }
883
884    #[test]
885    fn remote_model_resource_limits_use_released_generated_error_codes() {
886        let internal = Diagnostic::new(
887            DiagnosticCategory::ResourceLimit,
888            DiagnosticCode::new("query_v2_model_role_player_limit").unwrap(),
889            "internal model execution detail",
890        );
891        let error = remote_model_hydration_error(RemoteModelQueryV2Error::Diagnostic(internal));
892
893        assert_eq!(error.category(), crate::ErrorCategory::ResourceLimit);
894        assert_eq!(error.code(), Some("hydrated_role_player_limit"));
895        assert_eq!(error.path(), Some(&["provider_evidence".to_owned()][..]));
896        assert_eq!(
897            error.diagnostic_path(),
898            Some(
899                &[crate::ErrorPathSegment::Query(
900                    crate::QueryDiagnosticPathKind::ProviderEvidence,
901                )][..]
902            )
903        );
904        assert_eq!(error.model_validation_phase(), None);
905        assert_eq!(
906            error
907                .details()
908                .and_then(|details| details.get("query_category")),
909            Some(&crate::ErrorDetail::QueryCategory(
910                crate::QueryDiagnosticCategory::ResourceLimit,
911            ))
912        );
913    }
914
915    fn package() -> SchemaPackage<TestSchema> {
916        let documents = SchemaDocumentSet::parse([(
917            DocumentId::new("remote.yaml").unwrap(),
918            "format: typebridge.schema/v2\nattributes:\n  name: { value: string }\nentities:\n  person:\n    owns: { name: { key: true } }\n",
919        )])
920        .unwrap();
921        let declared = normalize_documents(&documents).unwrap();
922        let profile = SemanticProfileId::new("typedb-3.12.1/v1").unwrap();
923        let resolved = resolve(&declared, &profile).unwrap();
924        let authority = build_schema_authority(
925            &declared,
926            declared.required_capabilities(),
927            &ManagedDeltaContext::new(
928                ManagedScopeId::new("rust-client-test").unwrap(),
929                profile,
930                CapabilitySet::new(),
931            ),
932        )
933        .unwrap();
934        let emitter = RustEmitter::new();
935        let projection = project(
936            &resolved,
937            BindingTarget::Rust,
938            &ProjectionConfig::rust(),
939            &emitter.generator_handlers(),
940            &emitter.code_resources().unwrap(),
941        )
942        .unwrap();
943        let leak = |bytes: Vec<u8>| {
944            Box::leak(String::from_utf8(bytes).unwrap().into_boxed_str()) as &'static str
945        };
946        SchemaPackage::new_with_authority(
947            leak(to_canonical_json(projection.semantic_fingerprint()).unwrap()),
948            leak(to_canonical_json(projection.projection_fingerprint()).unwrap()),
949            leak(to_canonical_json(&projection).unwrap()),
950            leak(encode_schema_authority(&authority)),
951            leak(encode_declared_schema(&declared).unwrap()),
952            "rust-client-test",
953            "typedb-3.12.1/v1",
954        )
955    }
956
957    fn released_declared_package() -> SchemaPackage<TestSchema> {
958        let generated = package();
959        SchemaPackage::new_with_declared(
960            generated.semantic_fingerprint_json(),
961            generated.projection_fingerprint_json(),
962            generated.runtime_projection_json(),
963            generated
964                .declared_schema_json()
965                .expect("test package carries a declaration"),
966        )
967    }
968
969    struct UnusedTransport;
970
971    impl ProxyExchange for UnusedTransport {
972        fn capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>> {
973            Box::pin(async { panic!("compatibility test performs no transport I/O") })
974        }
975
976        fn exchange<'a>(
977            &'a self,
978            _request: &'a [u8],
979        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
980            Box::pin(async { panic!("compatibility test performs no transport I/O") })
981        }
982    }
983
984    /// The answer-limit ceiling these tests connect with.
985    fn small_limits() -> QueryExecutionResourceLimits {
986        QueryExecutionResourceLimits {
987            items: 10,
988            bytes: 1 << 20,
989            collection_members: 10,
990            graph_nodes: 100,
991            attribute_values: 100,
992            role_players: 100,
993            ..QueryExecutionResourceLimits::default()
994        }
995    }
996
997    fn unconnected_remote(mut options: ProxyConnectionPolicy) -> ProxyDatabase<Unbound> {
998        options.advertisement = Some(sdk_queries_transport(0x70).0.advertisement);
999        ProxyDatabase {
1000            options: Some(options),
1001            runtime: None,
1002            installed: None,
1003            registry: None,
1004            marker: PhantomData,
1005        }
1006    }
1007
1008    #[test]
1009    fn generated_authority_accepts_matching_legacy_options_and_rejects_overrides() {
1010        let limits = small_limits;
1011        let matching = ProxyConnectionPolicy::with_exchange(UnusedTransport)
1012            .authority("rust-client-test", "typedb-3.12.1/v1")
1013            .answer_limits(limits());
1014        unconnected_remote(matching)
1015            .with_schema(package())
1016            .expect("matching 2.0.1-style options remain compatible");
1017
1018        for mismatched in [
1019            ProxyConnectionPolicy::with_exchange(UnusedTransport)
1020                .authority("other-scope", "typedb-3.12.1/v1")
1021                .answer_limits(limits()),
1022            ProxyConnectionPolicy::with_exchange(UnusedTransport)
1023                .authority("rust-client-test", "typedb-3.11.5/v1")
1024                .answer_limits(limits()),
1025        ] {
1026            let error = unconnected_remote(mismatched)
1027                .with_schema(package())
1028                .expect_err("caller strings cannot override generated authority");
1029            assert!(
1030                error
1031                    .to_string()
1032                    .contains("disagrees with the generated schema authority"),
1033                "{error}"
1034            );
1035        }
1036    }
1037
1038    #[test]
1039    fn released_declared_package_retains_explicit_remote_options_compatibility() {
1040        let limits = small_limits;
1041        let options = ProxyConnectionPolicy::with_exchange(UnusedTransport)
1042            .authority("rust-client-test", "typedb-3.12.1/v1")
1043            .answer_limits(limits());
1044        unconnected_remote(options)
1045            .with_schema(released_declared_package())
1046            .expect("2.0.1 generated package and explicit options remain compatible");
1047
1048        let generated_options =
1049            ProxyConnectionPolicy::with_exchange(UnusedTransport).answer_limits(limits());
1050        let error = unconnected_remote(generated_options)
1051            .with_schema(released_declared_package())
1052            .expect_err("detached 2.0.1 package cannot invent embedded deployment authority");
1053        assert!(error.to_string().contains("no embedded managed scope"));
1054    }
1055
1056    struct Transport {
1057        advertisement_contract: RemoteCapabilities,
1058        advertisement: Vec<u8>,
1059        capabilities: Arc<Mutex<usize>>,
1060        exchanges: Arc<Mutex<Vec<Vec<u8>>>>,
1061        failure: Option<Diagnostic>,
1062        signer: RemoteReplySigningKey,
1063    }
1064
1065    impl ProxyExchange for Transport {
1066        fn capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>> {
1067            *self.capabilities.lock().unwrap() += 1;
1068            let bytes = self.advertisement.clone();
1069            Box::pin(async move { Ok(bytes) })
1070        }
1071
1072        fn exchange<'a>(
1073            &'a self,
1074            request: &'a [u8],
1075        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
1076            self.exchanges.lock().unwrap().push(request.to_vec());
1077            let response = (|| {
1078                let request = RemoteQueryRequestV2::decode(request).map_err(remote_diagnostic)?;
1079                request
1080                    .validate_advertisement(&self.advertisement_contract)
1081                    .map_err(remote_diagnostic)?;
1082                if let Some(diagnostic) = &self.failure {
1083                    return RemoteQueryFailureV2::bound(
1084                        request.nonce(),
1085                        &request.fingerprint().map_err(remote_diagnostic)?,
1086                        diagnostic,
1087                    )
1088                    .and_then(|failure| {
1089                        failure.encode_signed(
1090                            &self.advertisement_contract.fingerprint()?,
1091                            &self.signer,
1092                        )
1093                    })
1094                    .map_err(remote_diagnostic);
1095                }
1096                let plan = request.plan().map_err(remote_diagnostic)?;
1097                let root = BindingId::new(0).map_err(remote_diagnostic)?;
1098                let outcome = match request.result_kind() {
1099                    RemoteResultKindV2::DistinctCount => {
1100                        RemoteOutcomeV2::DistinctCount { root, value: 7 }
1101                    }
1102                    RemoteResultKindV2::DistinctExists => {
1103                        RemoteOutcomeV2::DistinctExists { root, value: true }
1104                    }
1105                    RemoteResultKindV2::HydratedRows => RemoteOutcomeV2::HydratedRows {
1106                        graph: HydrationGraphV2::new(vec![]).map_err(remote_diagnostic)?,
1107                        rows: vec![],
1108                    },
1109                    RemoteResultKindV2::HydratedPage => RemoteOutcomeV2::HydratedPage {
1110                        entries: vec![],
1111                        graph: HydrationGraphV2::new(vec![]).map_err(remote_diagnostic)?,
1112                        limit: 2,
1113                        offset: 0,
1114                        root,
1115                        total: Some(0),
1116                    },
1117                    RemoteResultKindV2::ModelReduction => {
1118                        let Some(ModelQueryV2::Reduction {
1119                            root,
1120                            group,
1121                            reducers,
1122                            ..
1123                        }) = plan
1124                            .v2_compatibility()
1125                            .and_then(|compatibility| compatibility.model_query())
1126                        else {
1127                            return Err(Error::Other {
1128                                message: "test reduction lacks its model contract".into(),
1129                                source: None,
1130                            });
1131                        };
1132                        RemoteOutcomeV2::ModelReduction {
1133                            graph: HydrationGraphV2::new(vec![]).map_err(remote_diagnostic)?,
1134                            root: *root,
1135                            group: group.clone(),
1136                            reducers: reducers.clone(),
1137                            rows: vec![RemoteReductionRowV2::new(
1138                                None,
1139                                vec![RemoteReducedValueV2::Count { value: 7 }],
1140                            )],
1141                        }
1142                    }
1143                    _ => {
1144                        return Err(Error::Other {
1145                            message: "test transport received an unexpected terminal".into(),
1146                            source: None,
1147                        });
1148                    }
1149                };
1150                RemoteQueryResponseV2::new(
1151                    request.nonce(),
1152                    &plan,
1153                    &request.fingerprint().map_err(remote_diagnostic)?,
1154                    request.result_kind(),
1155                    outcome,
1156                )
1157                .and_then(|response| {
1158                    response
1159                        .encode_signed(&self.advertisement_contract.fingerprint()?, &self.signer)
1160                })
1161                .map_err(remote_diagnostic)
1162            })();
1163            Box::pin(async move { response })
1164        }
1165    }
1166
1167    struct CancelBeforeDecodeTransport {
1168        inner: Transport,
1169        cancellation: AnswerCancellation,
1170        response_completed: Arc<AtomicBool>,
1171    }
1172
1173    impl ProxyExchange for CancelBeforeDecodeTransport {
1174        fn capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>> {
1175            self.inner.capabilities()
1176        }
1177
1178        fn exchange<'a>(
1179            &'a self,
1180            request: &'a [u8],
1181        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
1182            Box::pin(async move {
1183                let response = self.inner.exchange(request).await?;
1184                self.response_completed.store(true, AtomicOrdering::SeqCst);
1185                self.cancellation.cancel();
1186                Ok(response)
1187            })
1188        }
1189    }
1190
1191    struct ExchangeDropProbe(Arc<AtomicBool>);
1192
1193    impl Drop for ExchangeDropProbe {
1194        fn drop(&mut self) {
1195            self.0.store(true, AtomicOrdering::SeqCst);
1196        }
1197    }
1198
1199    struct CallerAbortTransport {
1200        advertisement: Vec<u8>,
1201        exchanges: Arc<AtomicUsize>,
1202        entered: Arc<Notify>,
1203        exchange_dropped: Arc<AtomicBool>,
1204    }
1205
1206    impl ProxyExchange for CallerAbortTransport {
1207        fn capabilities(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + '_>> {
1208            let advertisement = self.advertisement.clone();
1209            Box::pin(async move { Ok(advertisement) })
1210        }
1211
1212        fn exchange<'a>(
1213            &'a self,
1214            _request: &'a [u8],
1215        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
1216            self.exchanges.fetch_add(1, AtomicOrdering::SeqCst);
1217            self.entered.notify_one();
1218            let probe = ExchangeDropProbe(Arc::clone(&self.exchange_dropped));
1219            Box::pin(async move {
1220                let _probe = probe;
1221                std::future::pending().await
1222            })
1223        }
1224    }
1225
1226    fn sdk_queries_transport(seed: u8) -> (Transport, Arc<Mutex<Vec<Vec<u8>>>>) {
1227        let signer = RemoteReplySigningKey::from_secret_bytes([seed; 32]);
1228        let mut capabilities = query_plan_v2_capability_vocabulary();
1229        for capability in query_remote_v2_required_capabilities(true) {
1230            capabilities.insert(capability);
1231        }
1232        capabilities.insert(CapabilityId::new(CAP_QUERY_REMOTE_STATEMENT_LIMIT).unwrap());
1233        let advertisement_contract = RemoteCapabilities::new(
1234            capabilities,
1235            RemoteExecutorBinding::new("rust-client-test", "epoch-00000000003").unwrap(),
1236            signer.public_key(),
1237        );
1238        let advertisement = advertisement_contract.encode().unwrap();
1239        let exchanges = Arc::new(Mutex::new(Vec::new()));
1240        (
1241            Transport {
1242                advertisement_contract,
1243                advertisement,
1244                capabilities: Arc::new(Mutex::new(0)),
1245                exchanges: Arc::clone(&exchanges),
1246                failure: None,
1247                signer,
1248            },
1249            exchanges,
1250        )
1251    }
1252
1253    async fn observe_sdk_queries_remote_cancellation() -> serde_json::Value {
1254        let (pre_transport, pre_exchanges) = sdk_queries_transport(0x71);
1255        let remote = ProxyDatabase::connect(
1256            ProxyConnectionPolicy::with_exchange(pre_transport)
1257                .answer_limits(QueryExecutionResourceLimits::default()),
1258        )
1259        .await
1260        .expect("Rust remote cancellation proof connects")
1261        .with_schema(package())
1262        .expect("Rust remote cancellation proof binds generated schema authority");
1263        let pre_signal = AnswerCancellation::default();
1264        pre_signal.cancel();
1265        let mut pre_session = remote
1266            .query_with_resources(QueryExecutionResourceLimits::default(), pre_signal)
1267            .expect("Rust pre-cancelled remote session opens");
1268        let pre_person = pre_session
1269            .exact::<Person>()
1270            .expect("Rust pre-cancelled remote model binds");
1271        let pre_result = pre_session
1272            .query(pre_person)
1273            .expect("Rust pre-cancelled remote query authors")
1274            .count()
1275            .await;
1276        let pre_partial_result = pre_result.is_ok();
1277        let pre_error = pre_result.expect_err("pre-cancellation rejects before remote exchange");
1278        let pre_exchange_count = pre_exchanges.lock().unwrap().len();
1279        assert_eq!(pre_error.category(), crate::ErrorCategory::Cancelled);
1280        assert_eq!(pre_error.code(), Some("provider_cancelled"));
1281        assert_eq!(pre_exchange_count, 0);
1282        assert!(!pre_partial_result);
1283
1284        let decode_signal = AnswerCancellation::default();
1285        let response_completed = Arc::new(AtomicBool::new(false));
1286        let (decode_inner, decode_exchanges) = sdk_queries_transport(0x72);
1287        let decode_remote = ProxyDatabase::connect(ProxyConnectionPolicy::with_exchange(
1288            CancelBeforeDecodeTransport {
1289                inner: decode_inner,
1290                cancellation: decode_signal.clone(),
1291                response_completed: Arc::clone(&response_completed),
1292            },
1293        ))
1294        .await
1295        .expect("Rust decode-cancel remote connects")
1296        .with_schema(package())
1297        .expect("Rust decode-cancel remote binds generated schema authority");
1298        let mut decode_session = decode_remote
1299            .query_with_resources(QueryExecutionResourceLimits::default(), decode_signal)
1300            .expect("Rust decode-cancel session opens");
1301        let decode_person = decode_session
1302            .exact::<Person>()
1303            .expect("Rust decode-cancel model binds");
1304        let decode_result = decode_session
1305            .query(decode_person)
1306            .expect("Rust decode-cancel query authors")
1307            .count()
1308            .await;
1309        let decode_partial_result = decode_result.is_ok();
1310        let decode_error = decode_result.expect_err("cancellation rejects before reply decode");
1311        let decode_exchange_count = decode_exchanges.lock().unwrap().len();
1312        assert_eq!(decode_error.category(), crate::ErrorCategory::Cancelled);
1313        assert_eq!(decode_error.code(), Some("provider_cancelled"));
1314        assert_eq!(decode_exchange_count, 1);
1315        assert!(!decode_partial_result);
1316
1317        let (abort_contract_transport, _) = sdk_queries_transport(0x73);
1318        let abort_exchanges = Arc::new(AtomicUsize::new(0));
1319        let abort_entered = Arc::new(Notify::new());
1320        let abort_dropped = Arc::new(AtomicBool::new(false));
1321        let abort_transport = CallerAbortTransport {
1322            advertisement: abort_contract_transport.advertisement,
1323            exchanges: Arc::clone(&abort_exchanges),
1324            entered: Arc::clone(&abort_entered),
1325            exchange_dropped: Arc::clone(&abort_dropped),
1326        };
1327        let abort_remote = ProxyDatabase::connect(
1328            ProxyConnectionPolicy::with_exchange(abort_transport)
1329                .answer_limits(QueryExecutionResourceLimits::default()),
1330        )
1331        .await
1332        .expect("Rust caller-abort remote connects")
1333        .with_schema(package())
1334        .expect("Rust caller-abort remote binds generated schema authority");
1335        let abort_signal = AnswerCancellation::default();
1336        let requester_signal = abort_signal.clone();
1337        let requester_entered = Arc::clone(&abort_entered);
1338        let requester = tokio::spawn(async move {
1339            tokio::time::timeout(
1340                std::time::Duration::from_secs(5),
1341                requester_entered.notified(),
1342            )
1343            .await
1344            .expect("caller transport exchange starts before cancellation");
1345            requester_signal.cancel();
1346        });
1347        let mut abort_session = abort_remote
1348            .query_with_resources(QueryExecutionResourceLimits::default(), abort_signal)
1349            .expect("Rust caller-abort session opens");
1350        let abort_person = abort_session
1351            .exact::<Person>()
1352            .expect("Rust caller-abort model binds");
1353        let abort_error = tokio::time::timeout(
1354            std::time::Duration::from_secs(5),
1355            abort_session
1356                .query(abort_person)
1357                .expect("Rust caller-abort query authors")
1358                .count(),
1359        )
1360        .await
1361        .expect("caller cancellation wakes the remote exchange")
1362        .expect_err("caller cancellation rejects the remote terminal");
1363        requester
1364            .await
1365            .expect("caller transport cancellation requester completes");
1366        let caller_transport_abort_supported = abort_error.category()
1367            == crate::ErrorCategory::Cancelled
1368            && abort_error.code() == Some("provider_cancelled")
1369            && abort_exchanges.load(AtomicOrdering::SeqCst) == 1
1370            && abort_dropped.load(AtomicOrdering::SeqCst);
1371        assert!(caller_transport_abort_supported);
1372
1373        serde_json::json!({
1374            "before_exchange": {
1375                "category": pre_error.category().as_str(),
1376                "code": pre_error.code().expect("cancelled errors carry a stable code"),
1377                "exchange_count": pre_exchange_count,
1378                "partial_result": pre_partial_result,
1379            },
1380            "during_decode": {
1381                "category": decode_error.category().as_str(),
1382                "code": decode_error.code().expect("cancelled errors carry a stable code"),
1383                "exchange_count": decode_exchange_count,
1384                "partial_result": decode_partial_result,
1385            },
1386            "caller_transport_abort_supported": caller_transport_abort_supported,
1387            "server_exchange_cancelled_after_send": !response_completed.load(AtomicOrdering::SeqCst),
1388        })
1389    }
1390
1391    fn sdk_queries_query_category(error: &crate::Error) -> &'static str {
1392        error
1393            .details()
1394            .and_then(|details| {
1395                details.values().find_map(|detail| match detail {
1396                    crate::ErrorDetail::QueryCategory(
1397                        crate::QueryDiagnosticCategory::ResultDecode,
1398                    ) => Some("result_decode"),
1399                    _ => None,
1400                })
1401            })
1402            .expect("authenticated remote diagnostic carries result_decode")
1403    }
1404
1405    fn sdk_queries_remote_diagnostic_observation(
1406        error: &crate::Error,
1407        claim_consumed: bool,
1408    ) -> serde_json::Value {
1409        let path = error
1410            .diagnostic_path()
1411            .expect("authenticated remote diagnostic carries typed path")
1412            .iter()
1413            .map(|segment| match segment {
1414                crate::ErrorPathSegment::ContractField(value) => {
1415                    serde_json::json!({"kind": "contract_field", "value": value})
1416                }
1417                crate::ErrorPathSegment::Index(value) => {
1418                    serde_json::json!({"kind": "index", "value": value})
1419                }
1420                crate::ErrorPathSegment::ContractIdentity(value) => {
1421                    serde_json::json!({"kind": "contract_identity", "value": value})
1422                }
1423                other => panic!("unexpected authenticated proof path segment: {other:?}"),
1424            })
1425            .collect::<Vec<_>>();
1426        let mut details = serde_json::Map::new();
1427        for (name, detail) in error
1428            .details()
1429            .expect("authenticated remote diagnostic carries typed details")
1430        {
1431            let value = match detail {
1432                crate::ErrorDetail::Long(value) => {
1433                    serde_json::json!({"kind": "signed", "value": value.to_string()})
1434                }
1435                crate::ErrorDetail::Boolean(value) => {
1436                    serde_json::json!({"kind": "boolean", "value": value})
1437                }
1438                crate::ErrorDetail::QueryIdentity(value) => {
1439                    serde_json::json!({"kind": "query_identity", "value": value})
1440                }
1441                crate::ErrorDetail::QueryIdentityList(values) => {
1442                    serde_json::json!({"kind": "query_identity_list", "value": values})
1443                }
1444                crate::ErrorDetail::QueryCategory(_) => continue,
1445                other => panic!("unexpected authenticated proof detail: {other:?}"),
1446            };
1447            assert!(details.insert(name.clone(), value).is_none());
1448        }
1449        let visible = format!("{}{:?}{:?}", error.message(), path, details);
1450        let redacted = !visible.contains("provider-secret") && !visible.contains("must-not-cross");
1451        serde_json::json!({
1452            "category": match (error.category(), sdk_queries_query_category(error)) {
1453                (crate::ErrorCategory::ModelValidation, "result_decode") => "integrity",
1454                (category, _) => category.as_str(),
1455            },
1456            "query_category": sdk_queries_query_category(error),
1457            "code": error.code().expect("authenticated remote diagnostic carries a stable code"),
1458            "message": error.message(),
1459            "path": path,
1460            "details": details,
1461            "redacted": redacted,
1462            "claim_consumed": claim_consumed,
1463        })
1464    }
1465
1466    async fn observe_sdk_queries_remote_structured_diagnostic() -> serde_json::Value {
1467        let signer = RemoteReplySigningKey::from_secret_bytes([0x42; 32]);
1468        let mut capabilities = query_plan_v2_capability_vocabulary();
1469        for capability in query_remote_v2_required_capabilities(true) {
1470            capabilities.insert(capability);
1471        }
1472        let advertisement_contract = RemoteCapabilities::new(
1473            capabilities,
1474            RemoteExecutorBinding::new("rust-generated-acceptance", "epoch-00000000002").unwrap(),
1475            signer.public_key(),
1476        );
1477        let advertisement = advertisement_contract.encode().unwrap();
1478        let exchanges = Arc::new(Mutex::new(Vec::new()));
1479        let failure = Diagnostic::new(
1480            DiagnosticCategory::Integrity,
1481            DiagnosticCode::new("remote_application_failure").unwrap(),
1482            "provider-secret remote query literal and endpoint",
1483        )
1484        .with_path(DiagnosticPath::from_segments([
1485            DiagnosticPathSegment::Field("plan".into()),
1486            DiagnosticPathSegment::Index(2),
1487            DiagnosticPathSegment::Identifier("person".into()),
1488        ]))
1489        .with_detail("attempt", -7_i64)
1490        .with_detail("expected", vec!["person".to_owned(), "employee".to_owned()])
1491        .with_detail("retryable", false)
1492        .with_detail("subject", "person")
1493        .with_detail("provider_secret", "must-not-cross");
1494        let transport = Transport {
1495            advertisement_contract,
1496            advertisement,
1497            capabilities: Arc::new(Mutex::new(0)),
1498            exchanges: Arc::clone(&exchanges),
1499            failure: Some(failure),
1500            signer,
1501        };
1502        let remote = ProxyDatabase::connect(
1503            ProxyConnectionPolicy::with_exchange(transport).answer_limits(small_limits()),
1504        )
1505        .await
1506        .expect("Rust structured-diagnostic proof connects")
1507        .with_schema(package())
1508        .expect("Rust structured-diagnostic proof binds generated schema authority");
1509        let mut session = remote
1510            .query()
1511            .expect("Rust structured-diagnostic proof opens a generated session");
1512        let person = session
1513            .exact::<Person>()
1514            .expect("Rust structured-diagnostic proof binds a generated model");
1515        let query = session
1516            .query(person)
1517            .expect("Rust structured-diagnostic proof authors a generated query");
1518        let error = query
1519            .one()
1520            .await
1521            .expect_err("signed application failure reaches the generated query facade");
1522        let exchange_count = exchanges.lock().unwrap().len();
1523        let claim_consumed = exchange_count == 1
1524            && error.code() == Some("remote_application_failure")
1525            && error.details().is_some();
1526        assert_eq!(exchange_count, 1);
1527        assert!(claim_consumed);
1528        let observation = sdk_queries_remote_diagnostic_observation(&error, claim_consumed);
1529        assert_eq!(observation["redacted"], true);
1530        observation
1531    }
1532
1533    fn sdk_queries_proof_source(root: &Path, relative: &str) -> serde_json::Value {
1534        let path = root.join(relative);
1535        let bytes = fs::read(&path)
1536            .unwrap_or_else(|error| panic!("proof source {} is readable: {error}", path.display()));
1537        serde_json::json!({
1538            "path": relative,
1539            "sha256": format!("{:x}", Sha256::digest(bytes)),
1540        })
1541    }
1542
1543    fn requested_sdk_queries_proof_fragment() -> Option<(PathBuf, String)> {
1544        let destination = env::var_os("TYPE_BRIDGE_SDK_QUERIES_PROOF_FRAGMENT");
1545        let run_nonce = env::var_os("TYPE_BRIDGE_SDK_QUERIES_PROOF_RUN_NONCE");
1546        assert_eq!(
1547            destination.is_some(),
1548            run_nonce.is_some(),
1549            "Rust proof fragment output and run nonce must be configured together",
1550        );
1551        let destination = PathBuf::from(destination?);
1552        assert!(
1553            destination.is_absolute(),
1554            "Rust proof destination must be absolute"
1555        );
1556        let parent = destination
1557            .parent()
1558            .expect("Rust proof destination has a parent");
1559        let parent_metadata =
1560            fs::symlink_metadata(parent).expect("Rust proof destination parent exists");
1561        assert!(
1562            parent_metadata.is_dir() && !parent_metadata.file_type().is_symlink(),
1563            "Rust proof destination parent must be a non-symlink directory"
1564        );
1565        assert!(
1566            matches!(fs::symlink_metadata(&destination), Err(error) if error.kind() == std::io::ErrorKind::NotFound),
1567            "Rust proof destination must not already exist"
1568        );
1569        let run_nonce = run_nonce
1570            .expect("Rust proof run nonce exists")
1571            .into_string()
1572            .expect("Rust proof run nonce must be UTF-8");
1573        assert!(
1574            run_nonce.len() == 64
1575                && run_nonce
1576                    .bytes()
1577                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)),
1578            "Rust proof run nonce must be 64 lowercase hexadecimal digits"
1579        );
1580        Some((destination, run_nonce))
1581    }
1582
1583    fn publish_sdk_queries_rust_proof_fragment(
1584        destination: &Path,
1585        run_nonce: &str,
1586        results: Vec<serde_json::Value>,
1587    ) {
1588        let core = Path::new(env!("CARGO_MANIFEST_DIR"))
1589            .parent()
1590            .and_then(Path::parent)
1591            .expect("Rust crate lives beneath type-bridge-core");
1592        let repository = core
1593            .parent()
1594            .expect("type-bridge-core has a repository parent");
1595        let sources = ["type-bridge-core/crates/rust/src/remote.rs"];
1596        let fragment = serde_json::json!({
1597            "format": "typebridge.sdk-queries-proof-fragment/v1",
1598            "binding": "rust",
1599            "semantic_profile": crate::sdk_profile_matrix::requested("queries").semantic_profile,
1600            "run_nonce": run_nonce,
1601            "contract": {
1602                "allowlist": sdk_queries_proof_source(repository, "tests/contracts/sdk_conformance/queries/proof-fragment-allowlist.json"),
1603                "journey": sdk_queries_proof_source(repository, "tests/contracts/sdk_conformance/queries/journey.json"),
1604                "proof_schema": sdk_queries_proof_source(repository, "tests/contracts/sdk_conformance/queries/proof-fragment-schema.json"),
1605            },
1606            "producer": {
1607                "id": "type-bridge-rust.generated-query-proof",
1608                "sources": sources
1609                    .iter()
1610                    .map(|source| sdk_queries_proof_source(repository, source))
1611                    .collect::<Vec<_>>(),
1612            },
1613            "results": results,
1614        });
1615        let mut bytes =
1616            to_canonical_json(&fragment).expect("Rust queries proof fragment canonicalizes");
1617        bytes.push(b'\n');
1618        assert!(bytes.len() <= 64 * 1024);
1619        let mut output = OpenOptions::new()
1620            .write(true)
1621            .create_new(true)
1622            .open(destination)
1623            .expect("Rust queries proof fragment is created once");
1624        output
1625            .write_all(&bytes)
1626            .expect("Rust queries proof fragment is written completely");
1627        output
1628            .sync_all()
1629            .expect("Rust queries proof fragment is durable");
1630    }
1631
1632    #[tokio::test]
1633    async fn remote_database_fetches_capabilities_once_and_exchanges_once_per_terminal() {
1634        let signer = RemoteReplySigningKey::from_secret_bytes([0x31; 32]);
1635        let mut capabilities = query_plan_v2_capability_vocabulary();
1636        for capability in query_remote_v2_required_capabilities(true) {
1637            capabilities.insert(capability);
1638        }
1639        capabilities.insert(CapabilityId::new(CAP_QUERY_REMOTE_STATEMENT_LIMIT).unwrap());
1640        let advertisement_contract = RemoteCapabilities::new(
1641            capabilities,
1642            RemoteExecutorBinding::new("rust-client-test", "epoch-00000000001").unwrap(),
1643            signer.public_key(),
1644        );
1645        let advertisement = advertisement_contract.encode().unwrap();
1646        let capability_calls = Arc::new(Mutex::new(0));
1647        let exchanges = Arc::new(Mutex::new(Vec::new()));
1648        let transport = Transport {
1649            advertisement_contract,
1650            advertisement,
1651            capabilities: Arc::clone(&capability_calls),
1652            exchanges: Arc::clone(&exchanges),
1653            failure: None,
1654            signer,
1655        };
1656        let connection_resources =
1657            QueryExecutionResourceLimits::tightened(20_000, 10, 1_000_000, 90, 80, 70, 60, 2);
1658        let options =
1659            ProxyConnectionPolicy::with_exchange(transport).answer_limits(connection_resources);
1660        let remote = ProxyDatabase::connect(options)
1661            .await
1662            .unwrap()
1663            .with_schema(package())
1664            .unwrap();
1665        let mut session = remote.query().unwrap();
1666        let person = session.exact::<Person>().unwrap();
1667        let query = session.query(person).unwrap();
1668
1669        assert_eq!(query.count().await.unwrap(), 7);
1670        assert!(query.exists().await.unwrap());
1671        assert!(
1672            query
1673                .rows(crate::RowsOptions::new(2))
1674                .await
1675                .unwrap()
1676                .is_empty()
1677        );
1678        let page = query
1679            .page_by(person, crate::PageOptions::new(2).include_total(true))
1680            .await
1681            .unwrap();
1682        assert!(page.items().is_empty());
1683        assert_eq!(page.total(), Some(0));
1684        let reduction = query
1685            .aggregate((crate::aggregate::count(),))
1686            .await
1687            .expect("typed reductions use the same authenticated exchange");
1688        assert_eq!(reduction, (7,));
1689        assert_eq!(*capability_calls.lock().unwrap(), 1);
1690
1691        let zero_timeout = QueryExecutionResourceLimits {
1692            timeout_milliseconds: 0,
1693            ..QueryExecutionResourceLimits::default()
1694        };
1695        let mut timed_session = remote
1696            .query_with_resources(zero_timeout, AnswerCancellation::default())
1697            .unwrap();
1698        let timed_person = timed_session.exact::<Person>().unwrap();
1699        let timed_error = timed_session
1700            .query(timed_person)
1701            .unwrap()
1702            .count()
1703            .await
1704            .expect_err("zero timeout must reject before caller transport");
1705        assert_eq!(timed_error.category(), crate::ErrorCategory::ResourceLimit);
1706        assert_eq!(timed_error.code(), Some("transaction_deadline_exceeded"));
1707
1708        let cancellation = AnswerCancellation::default();
1709        cancellation.cancel();
1710        let mut cancelled_session = remote
1711            .query_with_resources(QueryExecutionResourceLimits::default(), cancellation)
1712            .unwrap();
1713        let cancelled_person = cancelled_session.exact::<Person>().unwrap();
1714        let cancelled_error = cancelled_session
1715            .query(cancelled_person)
1716            .unwrap()
1717            .count()
1718            .await
1719            .expect_err("pre-cancellation must reject before caller transport");
1720        assert_eq!(cancelled_error.category(), crate::ErrorCategory::Cancelled);
1721        assert_eq!(cancelled_error.code(), Some("provider_cancelled"));
1722
1723        // A session's own query limits bound what it may prepare: a plan
1724        // ceiling of one byte refuses before the caller's transport.
1725        let mut limited_session = remote
1726            .query_with_resources(
1727                QueryExecutionResourceLimits::default(),
1728                AnswerCancellation::default(),
1729            )
1730            .unwrap()
1731            .with_query_limits(
1732                crate::QueryLimits::from_overrides([("canonical_bytes", 1)]).unwrap(),
1733            )
1734            .unwrap();
1735        let limited_person = limited_session.exact::<Person>().unwrap();
1736        let limited_error = limited_session
1737            .query(limited_person)
1738            .unwrap()
1739            .count()
1740            .await
1741            .expect_err("a lowered plan ceiling must reject before caller transport");
1742        assert_eq!(
1743            limited_error.category(),
1744            crate::ErrorCategory::ResourceLimit
1745        );
1746        assert_eq!(limited_error.code(), Some("canonical_json_too_large"));
1747        let Err(after_binding) = limited_session.with_query_limits(crate::QueryLimits::CANONICAL)
1748        else {
1749            panic!("limits cannot change once a binding exists");
1750        };
1751        assert_eq!(after_binding.code(), Some("query_limits_after_binding"));
1752
1753        let terminal_resources =
1754            QueryExecutionResourceLimits::tightened(10_000, 20, 900_000, 100, 70, 80, 50, 1);
1755        let mut tightened_session = remote
1756            .query_with_resources(terminal_resources, AnswerCancellation::default())
1757            .unwrap();
1758        let tightened_person = tightened_session.exact::<Person>().unwrap();
1759        assert_eq!(
1760            tightened_session
1761                .query(tightened_person)
1762                .unwrap()
1763                .count()
1764                .await
1765                .unwrap(),
1766            7,
1767        );
1768
1769        let requests = exchanges.lock().unwrap();
1770        assert_eq!(requests.len(), 6);
1771        assert!(
1772            std::str::from_utf8(&requests[0])
1773                .unwrap()
1774                .contains("\"format\":\"typebridge.query-remote-request/v2\"")
1775        );
1776        let request = RemoteQueryRequestV2::decode(&requests[5]).unwrap();
1777        let limits = request.limits();
1778        assert!(
1779            limits
1780                .deadline_ms
1781                .is_some_and(|deadline| deadline <= 10_000),
1782            "the wire carries the remaining portion of the tighter terminal timeout",
1783        );
1784        assert_eq!(limits.max_items, 10);
1785        assert_eq!(limits.max_bytes, 900_000);
1786        assert_eq!(limits.max_graph_nodes, 90);
1787        assert_eq!(limits.max_attribute_values, 70);
1788        assert_eq!(limits.max_collection_members, 70);
1789        assert_eq!(limits.max_role_players, 50);
1790        assert_eq!(limits.max_statements, 1);
1791    }
1792
1793    #[tokio::test]
1794    async fn generated_remote_query_preserves_complete_authenticated_structured_diagnostic() {
1795        let signer = RemoteReplySigningKey::from_secret_bytes([0x42; 32]);
1796        let mut capabilities = query_plan_v2_capability_vocabulary();
1797        for capability in query_remote_v2_required_capabilities(true) {
1798            capabilities.insert(capability);
1799        }
1800        let advertisement_contract = RemoteCapabilities::new(
1801            capabilities,
1802            RemoteExecutorBinding::new("rust-generated-acceptance", "epoch-00000000002").unwrap(),
1803            signer.public_key(),
1804        );
1805        let advertisement = advertisement_contract.encode().unwrap();
1806        let capability_calls = Arc::new(Mutex::new(0));
1807        let exchanges = Arc::new(Mutex::new(Vec::new()));
1808        let diagnostic = Diagnostic::new(
1809            DiagnosticCategory::Integrity,
1810            DiagnosticCode::new("remote_application_failure").unwrap(),
1811            "the remote application rejected this query",
1812        )
1813        .with_path(DiagnosticPath::from_segments([
1814            DiagnosticPathSegment::Field("plan".into()),
1815            DiagnosticPathSegment::Index(2),
1816            DiagnosticPathSegment::Identifier("person".into()),
1817        ]))
1818        .with_detail("attempt", -7_i64)
1819        .with_detail("expected", vec!["person".to_owned(), "employee".to_owned()])
1820        .with_detail("retryable", false)
1821        .with_detail("subject", "person");
1822        let transport = Transport {
1823            advertisement_contract,
1824            advertisement,
1825            capabilities: Arc::clone(&capability_calls),
1826            exchanges: Arc::clone(&exchanges),
1827            failure: Some(diagnostic),
1828            signer,
1829        };
1830        let options = ProxyConnectionPolicy::with_exchange(transport).answer_limits(small_limits());
1831        let remote = ProxyDatabase::connect(options)
1832            .await
1833            .unwrap()
1834            .with_schema(package())
1835            .unwrap();
1836        let mut session = remote.query().unwrap();
1837        let person = session.exact::<Person>().unwrap();
1838        let error = session
1839            .query(person)
1840            .unwrap()
1841            .one()
1842            .await
1843            .expect_err("generated query must return the authenticated application failure");
1844
1845        assert_eq!(error.category(), crate::ErrorCategory::ModelValidation);
1846        assert_eq!(error.code(), Some("remote_application_failure"));
1847        assert_eq!(
1848            error.message(),
1849            "Typed query evidence does not match the validated request invocation"
1850        );
1851        assert_eq!(
1852            error.path(),
1853            Some(&["plan".to_owned(), "[2]".to_owned(), "person".to_owned()][..])
1854        );
1855        assert_eq!(
1856            error.diagnostic_path(),
1857            Some(
1858                &[
1859                    crate::ErrorPathSegment::ContractField("plan".into()),
1860                    crate::ErrorPathSegment::Index(2),
1861                    crate::ErrorPathSegment::ContractIdentity("person".into()),
1862                ][..]
1863            )
1864        );
1865        let details = error.details().expect("authenticated diagnostic details");
1866        assert_eq!(details.get("attempt"), Some(&crate::ErrorDetail::Long(-7)));
1867        assert_eq!(
1868            details.get("expected"),
1869            Some(&crate::ErrorDetail::QueryIdentityList(vec![
1870                "person".to_owned(),
1871                "employee".to_owned(),
1872            ]))
1873        );
1874        assert_eq!(
1875            details.get("retryable"),
1876            Some(&crate::ErrorDetail::Boolean(false))
1877        );
1878        assert_eq!(
1879            details.get("subject"),
1880            Some(&crate::ErrorDetail::QueryIdentity("person".to_owned()))
1881        );
1882        assert_eq!(
1883            details.get("query_category"),
1884            Some(&crate::ErrorDetail::QueryCategory(
1885                crate::QueryDiagnosticCategory::ResultDecode
1886            ))
1887        );
1888        assert_eq!(*capability_calls.lock().unwrap(), 1);
1889        assert_eq!(exchanges.lock().unwrap().len(), 1);
1890    }
1891
1892    #[tokio::test]
1893    async fn sdk_queries_rust_deterministic_proof_fragment() {
1894        let test_id = "remote::tests::sdk_queries_rust_deterministic_proof_fragment";
1895        let results = vec![
1896            serde_json::json!({
1897                "observation_ref": "cancellation_direct",
1898                "proof_kind": "direct_runtime",
1899                "test_id": test_id,
1900                "outcome": "passed",
1901                "observation": observe_sdk_queries_direct_cancellation().await,
1902            }),
1903            serde_json::json!({
1904                "observation_ref": "cancellation_remote",
1905                "proof_kind": "remote_runtime",
1906                "test_id": test_id,
1907                "outcome": "passed",
1908                "observation": observe_sdk_queries_remote_cancellation().await,
1909            }),
1910            serde_json::json!({
1911                "observation_ref": "remote_structured_diagnostic",
1912                "proof_kind": "diagnostic",
1913                "test_id": test_id,
1914                "outcome": "passed",
1915                "observation": observe_sdk_queries_remote_structured_diagnostic().await,
1916            }),
1917        ];
1918        if let Some((destination, run_nonce)) = requested_sdk_queries_proof_fragment() {
1919            publish_sdk_queries_rust_proof_fragment(&destination, &run_nonce, results);
1920        }
1921    }
1922}