Skip to main content

type_bridge_typedb_runtime/
lib.rs

1//! Shared TypeDB driver runtime.
2//!
3//! This crate owns all direct TypeDB driver interaction so higher-level crates
4//! can share version gating, gRPC fallback, database lifecycle, transactions,
5//! and JSON conversion without depending on each other.
6
7#![deny(missing_docs)]
8
9#[cfg(not(any(feature = "band8", feature = "band9")))]
10compile_error!(
11    "type-bridge-typedb-runtime requires at least one band feature; enable `band8` and/or `band9` (both are default)"
12);
13
14use std::future::Future;
15use std::path::PathBuf;
16use std::pin::Pin;
17use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering as AtomicOrdering};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, Instant};
20
21use futures::TryStreamExt;
22use serde::{Deserialize, Serialize};
23use tokio::sync::watch;
24use tracing::Instrument;
25use type_bridge_core_lib::version as core_version;
26use type_bridge_core_lib::version::DEFAULT_HTTP_PORT;
27
28#[cfg(feature = "band8")]
29use type_bridge_typedb_driver_b8 as driver_b8;
30#[cfg(feature = "band8")]
31use type_bridge_typedb_driver_b8::answer::QueryAnswer as B8QueryAnswer;
32#[cfg(feature = "band8")]
33use type_bridge_typedb_driver_b8::{
34    Addresses, Credentials as B8Credentials, DriverOptions, DriverTlsConfig,
35    TransactionOptions as B8TransactionOptions, TransactionType as B8TransactionType,
36    TypeDBDriver as B8Driver,
37};
38
39#[cfg(feature = "band9")]
40use typedb_driver as driver_b9;
41#[cfg(feature = "band9")]
42use typedb_driver::answer::QueryAnswer as B9QueryAnswer;
43#[cfg(feature = "band9")]
44use typedb_driver::{
45    Addresses as B9Addresses, Credentials as B9Credentials, DriverOptions as B9DriverOptions,
46    DriverTlsConfig as B9DriverTlsConfig, TransactionOptions as B9TransactionOptions,
47    TransactionType as B9TransactionType, TypeDBDriver as B9Driver,
48};
49
50/// Typed provider failure classification and redaction.
51pub mod failure;
52use failure::{Failure, redact_provider_error, redacted_failure};
53
54/// Boxed future returned by async runtime methods.
55pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
56
57// Pipeline stage spans. A driver round trip (open, query, rollback, close)
58// is `tb.runtime.execute`, a commit `tb.commit`, and converting one answer
59// to JSON `tb.decode`. They carry no fields, so no query text or value is
60// recorded.
61fn execute_span() -> tracing::Span {
62    tracing::info_span!("tb.runtime.execute")
63}
64
65fn commit_span() -> tracing::Span {
66    tracing::info_span!("tb.commit")
67}
68
69fn decode_span() -> tracing::Span {
70    tracing::info_span!("tb.decode")
71}
72
73/// How confidently a failed commit can be classified without observing server state.
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub enum CommitFailureCertainty {
76    /// A known pre-commit rejection proves that the transaction did not commit.
77    DefinitelyAborted,
78    /// The client cannot determine whether the transaction committed.
79    Unknown,
80}
81
82/// Runtime error type for direct TypeDB driver operations.
83#[derive(Debug, thiserror::Error)]
84pub enum RuntimeError {
85    /// The detected TypeDB server version is below the admitted floor or
86    /// its protocol band is not compiled into this runtime.
87    #[error("Unsupported version: {0}")]
88    UnsupportedVersion(#[from] core_version::VersionError),
89
90    /// Connection to TypeDB failed.
91    #[error("Connection error: {0}")]
92    Connection(String),
93
94    /// Query execution failed.
95    #[error("Query execution error: {0}")]
96    QueryExecution(String),
97
98    /// Transaction lifecycle failed.
99    #[error("Transaction error: {0}")]
100    Transaction(String),
101
102    /// A bounded answer ceiling was exceeded while reading the driver stream.
103    #[error("Resource limit [{code}]: {message}")]
104    ResourceLimit {
105        /// Stable resource code.
106        code: &'static str,
107        /// Human-readable diagnostic.
108        message: &'static str,
109    },
110
111    /// The higher-level answer decoder rejected one streamed item.
112    #[error("Answer consumer rejected a streamed provider item")]
113    AnswerConsumer,
114}
115
116/// A classified result available to recovery-aware internal commit callers.
117///
118/// [`RuntimeTransaction::commit`] retains the released [`RuntimeError`]
119/// surface. Callers that need durability certainty can opt into
120/// [`RuntimeTransaction::commit_classified`] without adding a variant to that
121/// released, exhaustively matchable enum.
122#[derive(Debug, thiserror::Error)]
123pub enum RuntimeCommitError {
124    /// A transaction lifecycle error before the driver attempted a commit.
125    #[error(transparent)]
126    Runtime(#[from] RuntimeError),
127    /// A driver commit failure with explicit durability certainty.
128    #[error("Transaction error: Commit failed: {message}")]
129    Driver {
130        /// Whether the failed response proves that the commit was aborted.
131        certainty: CommitFailureCertainty,
132        /// Value-free code and fixed provider failure description.
133        message: String,
134    },
135}
136
137impl RuntimeError {
138    /// Recover a typed failure from runtime-owned redacted provider descriptions.
139    #[must_use]
140    pub fn failure(&self) -> Option<Failure> {
141        match self {
142            Self::QueryExecution(message) | Self::Transaction(message) => {
143                failure::failure_from_message(message)
144            }
145            _ => None,
146        }
147    }
148}
149
150impl RuntimeCommitError {
151    /// Value-free outcome. Released string carriers have no staged operation index.
152    #[must_use]
153    pub fn failure(&self) -> Failure {
154        match self {
155            Self::Runtime(error) => error
156                .failure()
157                .unwrap_or(Failure::Indeterminate { code: None }),
158            Self::Driver { message, .. } => failure::failure_from_message(message)
159                .unwrap_or(Failure::Indeterminate { code: None }),
160        }
161    }
162
163    /// Convert to the released transaction-error surface.
164    ///
165    /// This discards certainty while retaining the value-free description. A transaction
166    /// error alone never proves that retrying the write is safe.
167    #[must_use]
168    pub fn into_runtime_error(self) -> RuntimeError {
169        match self {
170            Self::Runtime(error) => error,
171            Self::Driver { message, .. } => {
172                RuntimeError::Transaction(format!("Commit failed: {message}"))
173            }
174        }
175    }
176}
177
178fn commit_failure(
179    certainty: CommitFailureCertainty,
180    message: impl Into<String>,
181) -> RuntimeCommitError {
182    RuntimeCommitError::Driver {
183        certainty,
184        message: message.into(),
185    }
186}
187
188// Concept finalise and validation errors occur before the snapshot commit.
189// Exact spellings keep new server codes conservative until their phase is known.
190const DEFINITE_COMMIT_REJECTION_CODES: &[&str] = &[
191    "STC2", "STC4", "TSV2", "DCT1", "DCT2", "DCT3", "SCT1", "SCT2", "COW1", "COW2", "COW3", "COW4",
192    "COW5", "COW6", "COW7", "COW8", "COW9", "COW10", "COW11", "COW12", "CNT1", "CNT2", "CNT3",
193    "CNT4", "CNT5", "CNT6", "CNT7", "CNT8", "CNT9", "CNT10", "DVL1", "DVL2", "DVL3", "DVL4",
194    "DVL5", "DVL6", "DVL7", "DVL8", "DVL9", "DVL10", "DVL11", "DVL12", "DVL13", "DVL14", "DVL15",
195    "DVL16", "DVL17", "DVL18", "DVL19", "DVL20", "DVL21", "DVL22", "SVL1", "SVL2", "SVL3", "SVL4",
196    "SVL5", "SVL6", "SVL7", "SVL8", "SVL9", "SVL10", "SVL11", "SVL12", "SVL13", "SVL14", "SVL15",
197    "SVL16", "SVL17", "SVL18", "SVL19", "SVL20", "SVL21", "SVL22", "SVL23", "SVL24", "SVL25",
198    "SVL26", "SVL27", "SVL28", "SVL29", "SVL30", "SVL31", "SVL32", "SVL33", "SVL34", "SVL35",
199    "SVL36", "SVL37", "SVL38", "SVL39", "SVL40", "SVL41", "SVL42", "SVL43", "SVL44", "SVL45",
200    "SVL46", "SVL47", "SVL48", "SVL49", "SVL50", "SVL51", "SVL52", "SVL53", "SVL54", "SVL55",
201    "SVL56", "SVL57", "SVL58", "SVL59", "SVL60", "SVL61",
202];
203
204fn server_commit_certainty(code: &str) -> CommitFailureCertainty {
205    if DEFINITE_COMMIT_REJECTION_CODES.contains(&code) {
206        CommitFailureCertainty::DefinitelyAborted
207    } else {
208        CommitFailureCertainty::Unknown
209    }
210}
211
212#[cfg(feature = "band8")]
213fn band8_commit_failure(error: driver_b8::Error) -> RuntimeCommitError {
214    let failure = failure::classify_commit(
215        &error.code(),
216        &error.to_string(),
217        matches!(&error, driver_b8::Error::Server(_)),
218    );
219    let certainty = if failure.retry_safe() {
220        CommitFailureCertainty::DefinitelyAborted
221    } else {
222        CommitFailureCertainty::Unknown
223    };
224    commit_failure(
225        certainty,
226        failure::redacted_commit_failure(&failure, &error),
227    )
228}
229
230#[cfg(feature = "band8")]
231fn band8_query_error(error: driver_b8::Error) -> RuntimeError {
232    band8_query_error_with_operation(error, "Query failed")
233}
234
235#[cfg(feature = "band8")]
236fn band8_query_error_with_operation(
237    error: driver_b8::Error,
238    operation: &'static str,
239) -> RuntimeError {
240    let message = failure::classify_query(
241        &error.code(),
242        &error.to_string(),
243        matches!(&error, driver_b8::Error::Server(_)),
244    )
245    .map(|failure| format!("{operation}: {}", redacted_failure(&failure)))
246    .unwrap_or_else(|| redact_provider_error(&error, operation));
247    RuntimeError::QueryExecution(message)
248}
249
250#[cfg(feature = "band9")]
251fn band9_commit_failure(error: driver_b9::Error) -> RuntimeCommitError {
252    let failure = failure::classify_commit(
253        &error.code(),
254        &error.to_string(),
255        matches!(&error, driver_b9::Error::Server(_)),
256    );
257    let certainty = if failure.retry_safe() {
258        CommitFailureCertainty::DefinitelyAborted
259    } else {
260        CommitFailureCertainty::Unknown
261    };
262    commit_failure(
263        certainty,
264        failure::redacted_commit_failure(&failure, &error),
265    )
266}
267
268#[cfg(feature = "band9")]
269fn band9_query_error(error: driver_b9::Error) -> RuntimeError {
270    band9_query_error_with_operation(error, "Query failed")
271}
272
273#[cfg(feature = "band9")]
274fn band9_query_error_with_operation(
275    error: driver_b9::Error,
276    operation: &'static str,
277) -> RuntimeError {
278    let message = failure::classify_query(
279        &error.code(),
280        &error.to_string(),
281        matches!(&error, driver_b9::Error::Server(_)),
282    )
283    .map(|failure| format!("{operation}: {}", redacted_failure(&failure)))
284    .unwrap_or_else(|| redact_provider_error(&error, operation));
285    RuntimeError::QueryExecution(message)
286}
287
288#[cfg(test)]
289mod commit_failure_tests {
290    use super::*;
291
292    fn fixture_status(code: &str, message: &str) -> tonic::Status {
293        use tonic_types::{ErrorDetails, StatusExt};
294        let mut details = ErrorDetails::new();
295        details.set_error_info(code, "typedb", std::collections::HashMap::new());
296        details.set_debug_info(
297            message
298                .trim_start()
299                .split("\nCaused: ")
300                .map(str::to_owned)
301                .collect::<Vec<_>>(),
302            "",
303        );
304        tonic::Status::with_error_details(tonic::Code::Internal, "", details)
305    }
306
307    #[test]
308    fn live_error_fixtures_use_structural_root_codes_and_redact_display() {
309        for fixture in [
310            include_str!("../tests/fixtures/commit-errors-3.12.3.json"),
311            include_str!("../tests/fixtures/commit-errors-3.13.6.json"),
312        ] {
313            let messages: std::collections::BTreeMap<String, String> =
314                serde_json::from_str(fixture).unwrap();
315            for (case, code) in [("stc2", "STC2"), ("cnt5", "CNT5")] {
316                macro_rules! check_band {
317                    ($driver:ident, $classify:ident) => {{
318                        let error = $driver::Error::from(fixture_status(code, &messages[case]));
319                        assert_eq!(error.code(), code);
320                        assert_eq!(error.to_string(), messages[case]);
321                        let failure = $classify(error);
322                        assert!(matches!(
323                            &failure,
324                            RuntimeCommitError::Driver {
325                                certainty: CommitFailureCertainty::DefinitelyAborted,
326                                ..
327                            }
328                        ));
329                        assert!(failure.failure().retry_safe());
330                        let rendered = format!("{failure} {failure:?}");
331                        assert!(!rendered.contains("tb_w226"));
332                        assert!(!rendered.contains("Instance ["));
333                        assert!(failure.into_runtime_error().to_string().contains(code));
334                    }};
335                }
336                #[cfg(feature = "band8")]
337                check_band!(driver_b8, band8_commit_failure);
338                #[cfg(feature = "band9")]
339                check_band!(driver_b9, band9_commit_failure);
340            }
341            // CNT9 was raised during query execution, not commit. Only its
342            // structural root code is under test here.
343            #[cfg(feature = "band9")]
344            assert_eq!(
345                driver_b9::Error::from(fixture_status("CNT9", &messages["cnt9_query"])).code(),
346                "CNT9"
347            );
348            assert!(messages["paused"].starts_with("[CXN06]"));
349            assert_eq!(
350                server_commit_certainty("CXN06"),
351                CommitFailureCertainty::Unknown
352            );
353        }
354    }
355
356    #[test]
357    fn unknown_or_post_commit_codes_remain_unknown() {
358        for code in [
359            "STC1", "STC3", "STC5", "STC6", "DUC1", "DUC2", "DUC3", "DCT5", "SCT3", "SCT4", "SCT5",
360            "SCT6", "SCT7", "NEW999", "CNT11", "DVL23", "SVL62", "COW13", "STC02", "",
361        ] {
362            assert_eq!(
363                server_commit_certainty(code),
364                CommitFailureCertainty::Unknown,
365                "{code}"
366            );
367        }
368        // A known rejection in Display cannot override the structural code.
369        #[cfg(feature = "band9")]
370        assert!(matches!(
371            band9_commit_failure(driver_b9::Error::from(fixture_status(
372                "NEW999",
373                "[STC2] value"
374            ))),
375            RuntimeCommitError::Driver {
376                certainty: CommitFailureCertainty::Unknown,
377                ..
378            }
379        ));
380    }
381
382    #[test]
383    fn pre_commit_and_validation_roots_are_definite_rejections() {
384        for code in [
385            "STC2", "STC4", "TSV2", "DCT1", "DCT2", "DCT3", "SCT1", "SCT2", "COW1", "COW12",
386            "CNT4", "CNT9", "DVL1", "DVL22", "SVL1", "SVL61",
387        ] {
388            assert_eq!(
389                server_commit_certainty(code),
390                CommitFailureCertainty::DefinitelyAborted,
391                "{code}"
392            );
393        }
394    }
395
396    #[test]
397    fn non_server_driver_errors_remain_unknown_even_with_a_rejection_token() {
398        #[cfg(feature = "band8")]
399        assert!(matches!(
400            band8_commit_failure(driver_b8::Error::Other("[STC2] untrusted text".into())),
401            RuntimeCommitError::Driver {
402                certainty: CommitFailureCertainty::Unknown,
403                ..
404            }
405        ));
406        #[cfg(feature = "band9")]
407        assert!(matches!(
408            band9_commit_failure(driver_b9::Error::Other("[STC2] untrusted text".into())),
409            RuntimeCommitError::Driver {
410                certainty: CommitFailureCertainty::Unknown,
411                ..
412            }
413        ));
414    }
415
416    #[test]
417    fn typed_commit_failure_preserves_the_legacy_display() {
418        for certainty in [
419            CommitFailureCertainty::DefinitelyAborted,
420            CommitFailureCertainty::Unknown,
421        ] {
422            let error = commit_failure(certainty, "driver response");
423            assert_eq!(
424                error.to_string(),
425                "Transaction error: Commit failed: driver response"
426            );
427            assert!(matches!(
428                &error,
429                RuntimeCommitError::Driver {
430                    certainty: actual,
431                    ..
432                } if *actual == certainty
433            ));
434            assert!(matches!(
435                error.into_runtime_error(),
436                RuntimeError::Transaction(message)
437                    if message == "Commit failed: driver response"
438            ));
439        }
440    }
441
442    #[cfg(feature = "band8")]
443    #[test]
444    fn band8_opaque_commit_failure_is_unknown() {
445        let error = band8_commit_failure(driver_b8::Error::Other("transport".into()));
446        assert!(matches!(
447            error,
448            RuntimeCommitError::Driver {
449                certainty: CommitFailureCertainty::Unknown,
450                ..
451            }
452        ));
453    }
454
455    #[cfg(feature = "band9")]
456    #[test]
457    fn band9_opaque_commit_failure_is_unknown() {
458        let error = band9_commit_failure(driver_b9::Error::Other("transport".into()));
459        assert!(matches!(
460            error,
461            RuntimeCommitError::Driver {
462                certainty: CommitFailureCertainty::Unknown,
463                ..
464            }
465        ));
466    }
467}
468
469/// Convenience result alias for runtime operations.
470pub type Result<T> = std::result::Result<T, RuntimeError>;
471
472/// Result of a query execution after conversion from TypeDB stream types.
473#[derive(Debug, Clone, Serialize, Deserialize)]
474pub enum QueryResult {
475    /// No data returned.
476    Ok,
477    /// Document results from a fetch clause.
478    Documents(Vec<serde_json::Value>),
479    /// Row results from a match/reduce/concept query.
480    Rows(Vec<serde_json::Value>),
481}
482
483/// One item read from a TypeDB concept answer stream.
484#[derive(Debug, Clone, PartialEq)]
485pub enum RuntimeAnswerItem {
486    /// Concept row converted to JSON.
487    Row(serde_json::Value),
488    /// Concept document converted to JSON.
489    Document(serde_json::Value),
490}
491
492/// Provider answer kind, retained even for an empty stream.
493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
494pub enum RuntimeAnswerKind {
495    /// Statement returned no data stream.
496    Ok,
497    /// Concept-row stream.
498    Rows,
499    /// Concept-document stream.
500    Documents,
501}
502
503/// Whether the answer consumer needs another driver item.
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
505pub enum RuntimeAnswerControl {
506    /// Continue reading.
507    Continue,
508    /// Stop before polling the stream again.
509    Stop,
510}
511
512/// Cooperative cancellation shared with the ORM answer policy.
513#[derive(Debug, Clone)]
514pub struct RuntimeAnswerCancellation {
515    cancelled: watch::Sender<bool>,
516}
517
518impl Default for RuntimeAnswerCancellation {
519    fn default() -> Self {
520        let (cancelled, _) = watch::channel(false);
521        Self { cancelled }
522    }
523}
524
525impl RuntimeAnswerCancellation {
526    /// Construct from a shared wakeable cancellation state.
527    pub fn from_shared(cancelled: watch::Sender<bool>) -> Self {
528        Self { cancelled }
529    }
530
531    /// Request cancellation.
532    pub fn cancel(&self) {
533        self.cancelled.send_replace(true);
534    }
535
536    /// Return whether cancellation was requested.
537    pub fn is_cancelled(&self) -> bool {
538        *self.cancelled.borrow()
539    }
540
541    async fn cancelled(&self) {
542        let mut receiver = self.cancelled.subscribe();
543        if *receiver.borrow_and_update() {
544            return;
545        }
546        while receiver.changed().await.is_ok() {
547            if *receiver.borrow_and_update() {
548                return;
549            }
550        }
551    }
552}
553
554/// Dependency-neutral limits and interruption state for one secure connection.
555///
556/// This type is doc-hidden because binding-neutral policy construction belongs
557/// to the ORM. The runtime receives only the applicable connection dimensions:
558/// admitted items, retained nonsecret version bytes, provider/probe dispatch
559/// statements, one absolute deadline, and one wakeable cancellation owner.
560#[doc(hidden)]
561#[derive(Debug, Clone)]
562pub struct RuntimeConnectionControl {
563    max_items: u64,
564    max_bytes: u64,
565    max_statements: u32,
566    deadline: Instant,
567    cancellation: RuntimeAnswerCancellation,
568}
569
570impl RuntimeConnectionControl {
571    /// Construct one connection control from already-tightened common limits.
572    #[doc(hidden)]
573    #[must_use]
574    pub const fn new(
575        max_items: u64,
576        max_bytes: u64,
577        max_statements: u32,
578        deadline: Instant,
579        cancellation: RuntimeAnswerCancellation,
580    ) -> Self {
581        Self {
582            max_items,
583            max_bytes,
584            max_statements,
585            deadline,
586            cancellation,
587        }
588    }
589}
590
591/// Answers the server may stream ahead of a bounded consumer per batch.
592///
593/// Keep this at two or more. When a transaction closes while a query stream
594/// is paused, TypeDB 3.11/3.12 interrupts the query worker, re-arms one batch
595/// of `prefetch_size` messages, then waits for the worker to exit. The
596/// worker's queue to that batch holds `prefetch_size` messages, and after
597/// the interrupt it may still owe one in-flight answer plus a final status
598/// message. With a prefetch of one, the second of those blocks forever
599/// whenever the client's latency estimate rounds to 0 ms (the batch then
600/// ends without a latency window): the close never completes, the read
601/// transaction never times out, and the database stays "in use" until the
602/// server restarts. Two leaves room for both trailing messages.
603const BOUNDED_QUERY_PREFETCH_SIZE: u64 = 2;
604const _: () = assert!(BOUNDED_QUERY_PREFETCH_SIZE >= 2);
605
606/// Hard limits checked while polling a real driver answer stream.
607#[derive(Debug, Clone)]
608pub struct RuntimeAnswerLimits {
609    /// Maximum processed rows/documents.
610    pub max_items: u64,
611    /// Maximum encoded JSON response bytes.
612    pub max_bytes: u64,
613    /// Optional transaction deadline.
614    pub deadline: Option<Instant>,
615    /// Cooperative cancellation signal.
616    pub cancellation: RuntimeAnswerCancellation,
617}
618
619impl RuntimeAnswerLimits {
620    fn unbounded() -> Self {
621        Self {
622            max_items: u64::MAX,
623            max_bytes: u64::MAX,
624            deadline: None,
625            cancellation: RuntimeAnswerCancellation::default(),
626        }
627    }
628
629    fn is_unbounded(&self) -> bool {
630        self.max_items == u64::MAX && self.max_bytes == u64::MAX && self.deadline.is_none()
631    }
632}
633
634/// V2-only runtime limits layered over the released answer-limit shape.
635///
636/// The wrapper keeps [`RuntimeAnswerLimits`] exhaustively constructible by
637/// released 1.5.x callers while carrying the additive document-list budget.
638#[derive(Debug, Clone)]
639pub struct QueryV2RuntimeAnswerLimits {
640    /// Released item, byte, deadline, and cancellation limits.
641    pub answer: RuntimeAnswerLimits,
642    /// Maximum aggregate list members converted across fetched documents.
643    pub max_collection_members: u64,
644}
645
646impl Default for QueryV2RuntimeAnswerLimits {
647    fn default() -> Self {
648        Self {
649            answer: RuntimeAnswerLimits {
650                max_items: 100_000,
651                max_bytes: 64 * 1024 * 1024,
652                deadline: None,
653                cancellation: RuntimeAnswerCancellation::default(),
654            },
655            max_collection_members: 65_536,
656        }
657    }
658}
659
660/// Bounded stream counters returned without materializing all items.
661#[derive(Debug, Clone, Copy, PartialEq, Eq)]
662pub struct RuntimeAnswerStats {
663    /// Answer kind, including empty streams.
664    pub kind: RuntimeAnswerKind,
665    /// Items processed.
666    pub processed_items: u64,
667    /// Encoded response bytes processed.
668    pub response_bytes: u64,
669    /// Whether the consumer stopped early.
670    pub stopped_early: bool,
671}
672
673impl RuntimeAnswerStats {
674    fn new(kind: RuntimeAnswerKind) -> Self {
675        Self {
676            kind,
677            processed_items: 0,
678            response_bytes: 0,
679            stopped_early: false,
680        }
681    }
682}
683
684/// Transaction type for TypeDB operations.
685#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
686pub enum TxType {
687    /// Read-only transaction.
688    Read,
689    /// Read-write transaction.
690    Write,
691    /// Schema transaction.
692    Schema,
693}
694
695/// Server-side transaction lifetime and schema-lock acquisition bounds.
696///
697/// ```
698/// use std::time::Duration;
699/// use type_bridge_typedb_runtime::TransactionOptions;
700/// let options = TransactionOptions::new()
701///     .with_transaction_timeout(Duration::from_secs(30))
702///     .with_schema_lock_acquire_timeout(Duration::from_secs(2));
703/// assert_eq!(options.transaction_timeout, Some(Duration::from_secs(30)));
704/// assert_eq!(options.schema_lock_acquire_timeout, Some(Duration::from_secs(2)));
705/// ```
706#[derive(Debug, Clone, Copy, Default)]
707#[non_exhaustive]
708pub struct TransactionOptions {
709    /// Maximum transaction lifetime enforced by TypeDB.
710    pub transaction_timeout: Option<Duration>,
711    /// Maximum wait to acquire the schema lock while opening.
712    pub schema_lock_acquire_timeout: Option<Duration>,
713}
714
715impl TransactionOptions {
716    /// Use the driver's default transaction and lock timeouts.
717    pub const fn new() -> Self {
718        Self {
719            transaction_timeout: None,
720            schema_lock_acquire_timeout: None,
721        }
722    }
723
724    /// Bound the transaction's server-side lifetime.
725    pub const fn with_transaction_timeout(mut self, timeout: Duration) -> Self {
726        self.transaction_timeout = Some(timeout);
727        self
728    }
729
730    /// Bound the wait for a schema lock when opening.
731    pub const fn with_schema_lock_acquire_timeout(mut self, timeout: Duration) -> Self {
732        self.schema_lock_acquire_timeout = Some(timeout);
733        self
734    }
735
736    #[cfg(feature = "band8")]
737    fn band8(self) -> B8TransactionOptions {
738        let mut options = B8TransactionOptions::new();
739        if let Some(timeout) = self.transaction_timeout {
740            options = options.transaction_timeout(timeout);
741        }
742        if let Some(timeout) = self.schema_lock_acquire_timeout {
743            options = options.schema_lock_acquire_timeout(timeout);
744        }
745        options
746    }
747
748    #[cfg(feature = "band9")]
749    fn band9(self) -> B9TransactionOptions {
750        let mut options = B9TransactionOptions::new();
751        if let Some(timeout) = self.transaction_timeout {
752            options = options.transaction_timeout(timeout);
753        }
754        if let Some(timeout) = self.schema_lock_acquire_timeout {
755            options = options.schema_lock_acquire_timeout(timeout);
756        }
757        options
758    }
759}
760
761/// A single value bound to a `given` variable, band-agnostic and serializable.
762///
763/// Released temporal variants retain their ISO-8601 text representation.
764/// Additive V2 variants carry exact components when text alone would erase
765/// provider semantics.
766#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
767pub enum GivenValue {
768    /// Explicit absence for an optional `given` cell.
769    Empty,
770    /// TypeQL `boolean`.
771    Boolean(bool),
772    /// TypeQL `integer`.
773    Integer(i64),
774    /// TypeQL `double`.
775    Double(f64),
776    /// TypeQL `string`.
777    String(String),
778    /// TypeQL `date`, ISO-8601 (`YYYY-MM-DD`).
779    Date(String),
780    /// TypeQL `datetime`, ISO-8601 without offset.
781    Datetime(String),
782    /// TypeQL `datetime-tz`, with a fixed offset.
783    DatetimeTz(String),
784    /// Exact V2 TypeQL `datetime-tz`, retaining an optional authored IANA zone
785    /// and its already-validated effective offset.
786    DatetimeTzExact {
787        /// Canonical local datetime.
788        local: String,
789        /// Authored IANA name, or `None` for UTC/fixed-offset values.
790        named_zone: Option<String>,
791        /// Effective offset selected for this local value.
792        effective_offset_seconds: i32,
793    },
794    /// TypeQL fixed-point `decimal`.
795    Decimal(String),
796    /// Exact non-negative TypeDB duration components.
797    Duration {
798        /// Calendar months.
799        months: u32,
800        /// Calendar days.
801        days: u32,
802        /// Absolute nanoseconds.
803        nanos: u64,
804    },
805}
806
807/// Input rows for a `given`-stage query: a variable header plus value rows.
808///
809/// Every row must have exactly one entry per header variable, in header
810/// order. Rows travel through the driver API, never the query string.
811#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
812pub struct GivenRowsSpec {
813    /// Variable names, without the `$` sigil, in column order.
814    pub variables: Vec<String>,
815    /// Value rows; each inner vec is one input row in header order.
816    pub rows: Vec<Vec<GivenValue>>,
817}
818
819/// The compile-pinned band-8 driver fork version resolved in `Cargo.lock`.
820///
821/// This constant records the exact driver version this runtime crate was built
822/// against.  It is the factual counterpart to the policy window declared in
823/// `type_bridge_core_lib::version`: the window says which versions are allowed;
824/// this constant says which version is currently in use.
825///
826/// When `type-bridge-typedb-driver-b8` is refreshed, update this constant to
827/// match the new `Cargo.lock` entry — the `tests::cargo_lock_pin`
828/// test will catch any divergence.
829pub const PINNED_DRIVER_VERSION: &str = "3.11.5";
830
831/// The compile-pinned version of the upstream band-9 `typedb-driver` crate
832/// this runtime crate was built against.
833///
834/// Mirrors [`PINNED_DRIVER_VERSION`] for the band-8 driver fork.  When
835/// the band-9 dependency is refreshed, update this constant to match the new
836/// `Cargo.lock` entry — the `tests::cargo_lock_pin_b9` test will
837/// catch any divergence.
838///
839/// The upstream driver line may run ahead of the support window: driver 3.13
840/// speaks the same band-9 wire protocol that TypeDB 3.12 servers accept.
841pub const PINNED_DRIVER_VERSION_B9: &str = "3.14.0";
842
843/// Protocol bands this build embeds a driver for, derived from the compiled-in
844/// band features.  This is the `embedded_bands` argument to
845/// [`core_version::check_server_supported`] — the embedded-runtime gate accepts
846/// any in-window server whose band is in this set.
847///
848/// Each element is individually cfg-gated so the set reflects exactly the bands
849/// the build can construct; there is no hardcoded band-set literal (master-plan
850/// I6).  The default build compiles both retained bands, so the set is `{8, 9}`.
851const EMBEDDED_BANDS: &[u8] = &[
852    #[cfg(feature = "band8")]
853    8,
854    #[cfg(feature = "band9")]
855    9,
856];
857
858/// Return the driver versions compiled into this build, keyed by protocol band.
859///
860/// Each entry is `(band, version_string)` and is individually cfg-gated so only
861/// compiled-in bands appear in the slice (master-plan I6 — no hardcoded
862/// band-set literal).  The default build embeds both retained bands and returns
863/// `[(8, "3.11.5"), (9, "3.14.0")]`.
864///
865/// This is the Rust-side source of truth for the Python `embedded_driver_versions()`
866/// binding — `crates/python/src/version.rs` wraps this function and exposes it
867/// as a Python dict `{int: str}`.
868pub fn embedded_driver_versions() -> &'static [(u8, &'static str)] {
869    &[
870        #[cfg(feature = "band8")]
871        (8, PINNED_DRIVER_VERSION),
872        #[cfg(feature = "band9")]
873        (9, PINNED_DRIVER_VERSION_B9),
874    ]
875}
876
877/// Connection-time options for the version-gated TypeDB runtime.
878///
879/// Callers that accept the defaults can pass `ConnectOptions::default()`.
880#[derive(Debug, Clone, Copy)]
881pub struct ConnectOptions {
882    /// Port of the TypeDB HTTP API used for the connect-time version probe.
883    pub http_port: u16,
884    /// Whether to use TLS for the HTTP version probe.
885    pub tls: bool,
886    /// Exact server version supplied by the caller.
887    ///
888    /// When set, the connect gate validates this version and skips the HTTP
889    /// `/v1/version` probe. This is the supported path for gRPC-only TypeDB
890    /// deployments where the HTTP API is disabled or unreachable.
891    pub server_version: Option<core_version::Version>,
892}
893
894impl Default for ConnectOptions {
895    fn default() -> Self {
896        Self {
897            http_port: DEFAULT_HTTP_PORT,
898            tls: false,
899            server_version: None,
900        }
901    }
902}
903
904/// Canonical TLS policy for secure TypeDB connections.
905///
906/// The released [`ConnectOptions::tls`] Boolean is retained as a compatibility
907/// adapter.  New callers use this type so a custom root can never be confused
908/// with either plaintext or native-root TLS.
909#[derive(Debug, Clone, PartialEq, Eq, Default)]
910pub enum TlsMode {
911    /// Connect over plaintext HTTP and gRPC.
912    #[default]
913    Disabled,
914    /// Connect over TLS using the operating system's native trust roots.
915    NativeRoots,
916    /// Connect over TLS using only the PEM certificate bundle at this path.
917    CustomRootCa(PathBuf),
918}
919
920impl TlsMode {
921    /// Return whether this mode requires TLS on every transport.
922    #[must_use]
923    pub const fn is_enabled(&self) -> bool {
924        !matches!(self, Self::Disabled)
925    }
926}
927
928/// Connection options for the typed TLS transport surface.
929#[derive(Debug, Clone, PartialEq, Eq)]
930pub struct SecureConnectOptions {
931    /// Port of the TypeDB HTTP API used for the connect-time version probe.
932    pub http_port: u16,
933    /// TLS policy shared by the HTTP probe and every gRPC driver attempt.
934    pub tls_mode: TlsMode,
935    /// Exact server version supplied by the caller.
936    ///
937    /// When set, the HTTP probe is skipped, but `tls_mode` still applies to
938    /// the selected gRPC driver.
939    pub server_version: Option<core_version::Version>,
940}
941
942impl Default for SecureConnectOptions {
943    fn default() -> Self {
944        Self {
945            http_port: DEFAULT_HTTP_PORT,
946            tls_mode: TlsMode::Disabled,
947            server_version: None,
948        }
949    }
950}
951
952impl SecureConnectOptions {
953    /// Validate and lower this transport policy without constructing a host.
954    ///
955    /// This runs the exact shared custom-root and compiled-driver-band
956    /// validation used by every secure connect/lifecycle entry point, then
957    /// discards the provider options. It performs no HTTP request, gRPC host
958    /// construction, credential use, or database operation, so orchestration
959    /// layers can fail malformed trust material before resolving secrets.
960    pub fn validate_transport(&self) -> SecureResult<()> {
961        self.prepare_transport().map(|_| ())
962    }
963
964    /// Resolve and retain this transport policy for several lifecycle calls.
965    ///
966    /// This hidden additive seam exists for orchestrators that must finish all
967    /// trust-material I/O before resolving credentials. Clones share the same
968    /// captured custom-root snapshot and already-lowered band configurations;
969    /// they never reopen [`TlsMode::CustomRootCa`]'s configured path.
970    #[doc(hidden)]
971    pub fn prepare_transport(&self) -> SecureResult<PreparedSecureConnectOptions> {
972        Ok(PreparedSecureConnectOptions {
973            http_port: self.http_port,
974            server_version: self.server_version,
975            required_server_version: None,
976            resolved_tls: ResolvedTlsMode::from_configured_path(self.tls_mode.clone())?,
977            connection_control: None,
978        })
979    }
980
981    /// Prepare a path that already carries workspace/server confinement
982    /// provenance without following any component alias.
983    ///
984    /// Only confinement authorities may use this hidden entry point. Ordinary
985    /// callers must use [`Self::prepare_transport`], which accepts normal OS
986    /// path aliases before capturing the physical file.
987    #[doc(hidden)]
988    pub fn prepare_transport_from_validated_physical_path(
989        &self,
990    ) -> SecureResult<PreparedSecureConnectOptions> {
991        Ok(PreparedSecureConnectOptions {
992            http_port: self.http_port,
993            server_version: self.server_version,
994            required_server_version: None,
995            resolved_tls: ResolvedTlsMode::from_validated_physical_path(self.tls_mode.clone())?,
996            connection_control: None,
997        })
998    }
999
1000    /// Prepare custom-root bytes already captured through a configuration
1001    /// authority without reopening the diagnostic [`TlsMode`] path.
1002    ///
1003    /// Only confinement authorities may use this hidden entry point. The
1004    /// captured bytes are still parsed and lowered by the shared TLS engine,
1005    /// and every driver band receives the resulting private snapshot.
1006    #[doc(hidden)]
1007    pub fn prepare_transport_from_captured_custom_root(
1008        &self,
1009        bytes: Arc<[u8]>,
1010    ) -> SecureResult<PreparedSecureConnectOptions> {
1011        Ok(PreparedSecureConnectOptions {
1012            http_port: self.http_port,
1013            server_version: self.server_version,
1014            required_server_version: None,
1015            resolved_tls: ResolvedTlsMode::from_captured_custom_root(self.tls_mode.clone(), bytes)?,
1016            connection_control: None,
1017        })
1018    }
1019}
1020
1021impl From<ConnectOptions> for SecureConnectOptions {
1022    fn from(value: ConnectOptions) -> Self {
1023        Self {
1024            http_port: value.http_port,
1025            tls_mode: if value.tls {
1026                TlsMode::NativeRoots
1027            } else {
1028                TlsMode::Disabled
1029            },
1030            server_version: value.server_version,
1031        }
1032    }
1033}
1034
1035/// Error returned by typed secure connection and lifecycle entry points.
1036///
1037/// This additive type keeps TLS configuration failures matchable without
1038/// adding a variant to the released, exhaustively matchable [`RuntimeError`].
1039#[derive(Debug, thiserror::Error)]
1040#[non_exhaustive]
1041pub enum SecureConnectError {
1042    /// Custom or native trust material failed validation before network I/O.
1043    #[error(transparent)]
1044    TlsConfiguration(#[from] core_version::TlsConfigurationError),
1045    /// A driver band could not lower the already validated TLS policy.
1046    #[error(
1047        "TLS configuration error [tls_driver_lowering_failed]: TypeDB driver band {band} rejected the TLS policy"
1048    )]
1049    DriverTlsConfiguration {
1050        /// Driver protocol band that rejected the configuration.
1051        band: u8,
1052    },
1053    /// The connection reached the ordinary version gate or driver runtime.
1054    #[error(transparent)]
1055    Runtime(#[from] RuntimeError),
1056}
1057
1058impl SecureConnectError {
1059    /// Return the stable TLS configuration code, or `None` for an ordinary
1060    /// version/connection/runtime failure.
1061    #[must_use]
1062    pub fn configuration_code(&self) -> Option<&'static str> {
1063        match self {
1064            Self::TlsConfiguration(error) => Some(error.code()),
1065            Self::DriverTlsConfiguration { .. } => Some("tls_driver_lowering_failed"),
1066            Self::Runtime(_) => None,
1067        }
1068    }
1069
1070    /// Return a diagnostic that is safe to expose after credentials have
1071    /// been resolved.
1072    ///
1073    /// TLS diagnostics are reconstructed from typed codes without retaining
1074    /// configured paths. Version diagnostics are retained only for variants
1075    /// whose fields are closed version/band data. Exact runtime-owned
1076    /// redacted transport/discovery messages are also retained. Other legacy
1077    /// strings may contain provider values and therefore return `None`.
1078    #[must_use]
1079    pub fn credential_safe_diagnostic(&self) -> Option<String> {
1080        match self {
1081            Self::Runtime(RuntimeError::Connection(message))
1082                if failure::is_redacted_provider_message(message) =>
1083            {
1084                Some(self.to_string())
1085            }
1086            Self::Runtime(RuntimeError::UnsupportedVersion(core_version::VersionError::Probe(
1087                message,
1088            ))) if is_redacted_discovery_failure(message) => Some(self.to_string()),
1089            Self::TlsConfiguration(error) => Some(format!(
1090                "TLS policy preparation failed [{}]; inspect the configured trust material",
1091                error.code()
1092            )),
1093            Self::DriverTlsConfiguration { band } => Some(format!(
1094                "TLS policy lowering failed [tls_driver_lowering_failed] for TypeDB driver band {band}"
1095            )),
1096            Self::Runtime(RuntimeError::UnsupportedVersion(
1097                error @ (core_version::VersionError::Unsupported { .. }
1098                | core_version::VersionError::BandMismatch { .. }
1099                | core_version::VersionError::EmbeddedUnavailable { .. }
1100                | core_version::VersionError::FeatureUnsupported { .. }),
1101            )) => Some(format!("Unsupported version: {error}")),
1102            Self::Runtime(
1103                RuntimeError::UnsupportedVersion(
1104                    core_version::VersionError::Probe(_) | core_version::VersionError::Parse(_),
1105                )
1106                | RuntimeError::Connection(_)
1107                | RuntimeError::QueryExecution(_)
1108                | RuntimeError::Transaction(_)
1109                | RuntimeError::ResourceLimit { .. }
1110                | RuntimeError::AnswerConsumer,
1111            ) => None,
1112        }
1113    }
1114
1115    /// Collapse an additive secure error onto the released runtime surface.
1116    #[must_use]
1117    pub fn into_runtime_error(self) -> RuntimeError {
1118        match self {
1119            Self::Runtime(error) => error,
1120            other => RuntimeError::Connection(other.to_string()),
1121        }
1122    }
1123}
1124
1125const TRACE_CODE_DRIVER_DROP_CLOSE_FAILED: &str = "typedb_runtime_driver_drop_close_failed";
1126const TRACE_CODE_VERSION_GATE_PASSED: &str = "typedb_runtime_version_gate_passed";
1127#[cfg(all(feature = "band8", feature = "band9"))]
1128const TRACE_CODE_BAND9_UPGRADE_SUCCEEDED: &str = "typedb_runtime_band9_upgrade_succeeded";
1129#[cfg(all(feature = "band8", feature = "band9"))]
1130const TRACE_CODE_BAND9_UPGRADE_FAILED: &str = "typedb_runtime_band9_upgrade_failed";
1131#[cfg(feature = "band8")]
1132const TRACE_CODE_BAND8_FALLBACK_CONNECTED: &str = "typedb_runtime_band8_fallback_connected";
1133const TRACE_CODE_CONNECTED: &str = "typedb_runtime_connected";
1134const TRACE_CODE_UNMEASURED_SERVER: &str = "typedb_runtime_unmeasured_server";
1135
1136fn runtime_trace_failure_code(error: &RuntimeError) -> &'static str {
1137    match error {
1138        RuntimeError::UnsupportedVersion(_) => "typedb_runtime_unsupported_version",
1139        RuntimeError::Connection(_) => "typedb_runtime_connection_failed",
1140        RuntimeError::QueryExecution(_) => "typedb_runtime_query_failed",
1141        RuntimeError::Transaction(_) => "typedb_runtime_transaction_failed",
1142        RuntimeError::ResourceLimit { .. } => "typedb_runtime_resource_limit",
1143        RuntimeError::AnswerConsumer => "typedb_runtime_answer_consumer_failed",
1144    }
1145}
1146
1147#[cfg(all(feature = "band8", feature = "band9"))]
1148fn secure_trace_failure_code(error: &SecureConnectError) -> &'static str {
1149    match error {
1150        SecureConnectError::TlsConfiguration(error) => error.code(),
1151        SecureConnectError::DriverTlsConfiguration { .. } => "tls_driver_lowering_failed",
1152        SecureConnectError::Runtime(error) => runtime_trace_failure_code(error),
1153    }
1154}
1155
1156fn trace_driver_drop_close_failure(error: &RuntimeError) {
1157    tracing::warn!(
1158        code = TRACE_CODE_DRIVER_DROP_CLOSE_FAILED,
1159        failure_code = runtime_trace_failure_code(error),
1160        "TypeDB driver cleanup failed during final runtime drop"
1161    );
1162}
1163
1164fn trace_version_gate_passed(_address: &str, band: u8, server_version: core_version::Version) {
1165    tracing::debug!(
1166        code = TRACE_CODE_VERSION_GATE_PASSED,
1167        driver_band = band,
1168        %server_version,
1169        "TypeDB runtime version gate passed"
1170    );
1171}
1172
1173#[cfg(all(feature = "band8", feature = "band9"))]
1174fn trace_band9_upgrade_succeeded(_address: &str, server_version: core_version::Version) {
1175    tracing::debug!(
1176        code = TRACE_CODE_BAND9_UPGRADE_SUCCEEDED,
1177        driver_band = 9_u8,
1178        %server_version,
1179        "TypeDB runtime upgraded its validated fallback connection"
1180    );
1181}
1182
1183#[cfg(all(feature = "band8", feature = "band9"))]
1184fn trace_band9_upgrade_failed(
1185    _address: &str,
1186    server_version: core_version::Version,
1187    error: &SecureConnectError,
1188) {
1189    tracing::warn!(
1190        code = TRACE_CODE_BAND9_UPGRADE_FAILED,
1191        failure_code = secure_trace_failure_code(error),
1192        driver_band = 9_u8,
1193        %server_version,
1194        "TypeDB runtime could not upgrade its validated fallback connection"
1195    );
1196}
1197
1198#[cfg(feature = "band8")]
1199fn trace_band8_fallback_connected(_address: &str, server_version: core_version::Version) {
1200    tracing::debug!(
1201        code = TRACE_CODE_BAND8_FALLBACK_CONNECTED,
1202        driver_band = 8_u8,
1203        %server_version,
1204        "TypeDB runtime retained its validated fallback connection"
1205    );
1206}
1207
1208fn trace_runtime_connected(
1209    _address: &str,
1210    driver_band: u8,
1211    server_version: Option<core_version::Version>,
1212) {
1213    match server_version {
1214        Some(server_version) => {
1215            if core_version::newer_than_measured(&server_version) {
1216                let (major, minor) = core_version::MAX_SUPPORTED_LINE;
1217                let newest_measured_line = format!("{major}.{minor}");
1218                let semantic_profile = core_version::semantic_profile_id(&server_version)
1219                    .expect("newer admitted servers have a measured fallback profile");
1220                tracing::warn!(
1221                    code = TRACE_CODE_UNMEASURED_SERVER,
1222                    %server_version,
1223                    %newest_measured_line,
1224                    semantic_profile,
1225                    "TypeDB server is not tested or supported by this TypeBridge release; using the newest measured semantic profile and protocol assumptions"
1226                );
1227            }
1228            tracing::info!(
1229                code = TRACE_CODE_CONNECTED,
1230                driver_band,
1231                server_version_known = true,
1232                %server_version,
1233                "TypeDB runtime connected"
1234            );
1235        }
1236        None => tracing::info!(
1237            code = TRACE_CODE_CONNECTED,
1238            driver_band,
1239            server_version_known = false,
1240            "TypeDB runtime connected"
1241        ),
1242    }
1243}
1244
1245/// Result alias for typed secure connection and lifecycle operations.
1246pub type SecureResult<T> = std::result::Result<T, SecureConnectError>;
1247
1248/// TLS policy lowered eagerly for every compiled TypeDB driver band.
1249///
1250/// Constructing this value reads and validates a custom root exactly once
1251/// before the HTTP probe or any gRPC host is created. Every band is then
1252/// lowered from the retained file material, and HTTP receives the captured
1253/// bytes rather than the caller-controlled path. Every fallback receives this
1254/// same value, so an enabled request has no plaintext reconstruction path.
1255#[derive(Clone, Debug)]
1256struct ResolvedTlsMode {
1257    probe_mode: ResolvedTlsProbeMode,
1258    #[cfg(feature = "band8")]
1259    band8: DriverTlsConfig,
1260    #[cfg(feature = "band9")]
1261    band9: B9DriverTlsConfig,
1262}
1263
1264#[derive(Clone, Debug)]
1265enum ResolvedTlsProbeMode {
1266    Disabled,
1267    NativeRoots,
1268    CustomRootCa(core_version::RetainedCustomRootCa),
1269}
1270
1271/// A reusable, fully resolved secure transport policy.
1272///
1273/// This type is doc-hidden because ordinary callers should keep using
1274/// [`SecureConnectOptions`]. It is public only so orchestration crates can
1275/// prepare transport material once before credential resolution and reuse the
1276/// same immutable snapshot across database lifecycle and connection calls.
1277#[doc(hidden)]
1278#[derive(Clone, Debug)]
1279pub struct PreparedSecureConnectOptions {
1280    http_port: u16,
1281    server_version: Option<core_version::Version>,
1282    required_server_version: Option<core_version::GeneratedPackageRelease>,
1283    resolved_tls: ResolvedTlsMode,
1284    connection_control: Option<RuntimeConnectionControl>,
1285}
1286
1287impl PreparedSecureConnectOptions {
1288    /// Attach one invocation's common control after trust preparation.
1289    ///
1290    /// Cloning the returned value shares cancellation and the exact absolute
1291    /// deadline, but each connection invocation owns independent counters.
1292    #[doc(hidden)]
1293    #[must_use]
1294    pub fn with_connection_control(mut self, control: RuntimeConnectionControl) -> Self {
1295        self.connection_control = Some(control);
1296        self
1297    }
1298
1299    /// Require a patch floor on one of the minor lines owned by a generated
1300    /// package's semantic profile.
1301    ///
1302    /// This is deliberately not an arbitrary version-taking lane: the release
1303    /// comes only from the closed [`core_version::GeneratedPackageRelease`]
1304    /// map. It clears the released caller-version shortcut so the
1305    /// authoritative HTTP probe always runs before any driver or credential
1306    /// construction.
1307    #[doc(hidden)]
1308    #[must_use]
1309    pub fn with_generated_package_requirement(
1310        mut self,
1311        release: core_version::GeneratedPackageRelease,
1312    ) -> Self {
1313        self.server_version = None;
1314        self.required_server_version = Some(release);
1315        self
1316    }
1317}
1318
1319#[derive(Debug)]
1320struct ConnectionMeter {
1321    control: Option<RuntimeConnectionControl>,
1322    statements: u32,
1323    response_bytes: u64,
1324    admitted_items: u64,
1325}
1326
1327impl ConnectionMeter {
1328    fn new(control: RuntimeConnectionControl) -> Self {
1329        Self {
1330            control: Some(control),
1331            statements: 0,
1332            response_bytes: 0,
1333            admitted_items: 0,
1334        }
1335    }
1336
1337    fn legacy() -> Self {
1338        Self {
1339            control: None,
1340            statements: 0,
1341            response_bytes: 0,
1342            admitted_items: 0,
1343        }
1344    }
1345
1346    fn control(&self) -> Option<&RuntimeConnectionControl> {
1347        self.control.as_ref()
1348    }
1349
1350    fn check_interruption(&self) -> Result<()> {
1351        let Some(control) = &self.control else {
1352            return Ok(());
1353        };
1354        if control.cancellation.is_cancelled() {
1355            return Err(RuntimeError::ResourceLimit {
1356                code: "provider_cancelled",
1357                message: "provider connection was cancelled",
1358            });
1359        }
1360        if tokio::time::Instant::now() >= tokio::time::Instant::from_std(control.deadline) {
1361            return Err(RuntimeError::ResourceLimit {
1362                code: "transaction_deadline_exceeded",
1363                message: "provider connection deadline expired",
1364            });
1365        }
1366        Ok(())
1367    }
1368
1369    fn require_possible_success(&self) -> Result<()> {
1370        self.check_interruption()?;
1371        if self
1372            .control
1373            .as_ref()
1374            .is_some_and(|control| control.max_items == 0)
1375        {
1376            return Err(RuntimeError::ResourceLimit {
1377                code: "processed_item_limit",
1378                message: "provider connection item limit exceeded",
1379            });
1380        }
1381        Ok(())
1382    }
1383
1384    fn charge_statement(&mut self) -> Result<()> {
1385        self.check_interruption()?;
1386        let Some(control) = &self.control else {
1387            return Ok(());
1388        };
1389        let next = self
1390            .statements
1391            .checked_add(1)
1392            .ok_or(RuntimeError::ResourceLimit {
1393                code: "provider_statement_counter_overflow",
1394                message: "provider connection statement counter overflowed",
1395            })?;
1396        if next > control.max_statements {
1397            return Err(RuntimeError::ResourceLimit {
1398                code: "provider_statement_limit",
1399                message: "provider connection statement limit exceeded",
1400            });
1401        }
1402        self.statements = next;
1403        Ok(())
1404    }
1405
1406    fn charge_version_evidence(&mut self, version: core_version::Version) -> Result<()> {
1407        let Some(control) = &self.control else {
1408            return Ok(());
1409        };
1410        // Only the canonical version retained by TypeDBRuntime is public
1411        // connection evidence. Provider errors, raw response framing, hosts,
1412        // credentials, and trust material are deliberately never measured or
1413        // reflected into a diagnostic.
1414        let bytes =
1415            u64::try_from(version.to_string().len()).map_err(|_| RuntimeError::ResourceLimit {
1416                code: "response_byte_counter_overflow",
1417                message: "provider connection response byte counter overflowed",
1418            })?;
1419        let next = self
1420            .response_bytes
1421            .checked_add(bytes)
1422            .ok_or(RuntimeError::ResourceLimit {
1423                code: "response_byte_counter_overflow",
1424                message: "provider connection response byte counter overflowed",
1425            })?;
1426        if next > control.max_bytes {
1427            return Err(RuntimeError::ResourceLimit {
1428                code: "response_byte_limit",
1429                message: "provider connection response byte limit exceeded",
1430            });
1431        }
1432        self.response_bytes = next;
1433        Ok(())
1434    }
1435
1436    fn admit_connection(&mut self) -> Result<()> {
1437        let Some(control) = &self.control else {
1438            return Ok(());
1439        };
1440        let next = self
1441            .admitted_items
1442            .checked_add(1)
1443            .ok_or(RuntimeError::ResourceLimit {
1444                code: "processed_item_counter_overflow",
1445                message: "provider connection item counter overflowed",
1446            })?;
1447        if next > control.max_items {
1448            return Err(RuntimeError::ResourceLimit {
1449                code: "processed_item_limit",
1450                message: "provider connection item limit exceeded",
1451            });
1452        }
1453        self.admitted_items = next;
1454        Ok(())
1455    }
1456}
1457
1458async fn await_connection_work<T>(
1459    future: impl Future<Output = T>,
1460    control: Option<&RuntimeConnectionControl>,
1461) -> Result<T> {
1462    let Some(control) = control else {
1463        return Ok(future.await);
1464    };
1465    tokio::pin!(future);
1466    let cancellation = control.cancellation.cancelled();
1467    tokio::pin!(cancellation);
1468    let deadline = tokio::time::sleep_until(tokio::time::Instant::from_std(control.deadline));
1469    tokio::pin!(deadline);
1470
1471    tokio::select! {
1472        biased;
1473        output = &mut future => Ok(output),
1474        () = &mut cancellation => Err(RuntimeError::ResourceLimit {
1475            code: "provider_cancelled",
1476            message: "provider connection was cancelled",
1477        }),
1478        () = &mut deadline => Err(RuntimeError::ResourceLimit {
1479            code: "transaction_deadline_exceeded",
1480            message: "provider connection deadline expired",
1481        }),
1482    }
1483}
1484
1485fn is_redacted_discovery_failure(message: &str) -> bool {
1486    let Some(rest) = message.strip_prefix(
1487        "HTTP version probe and gRPC fallback both failed: HTTP version probe failed: ",
1488    ) else {
1489        return false;
1490    };
1491    let Some((http, grpc)) = rest.split_once("; ") else {
1492        return false;
1493    };
1494    if core_version::VersionError::Probe(http.to_owned()).redacted_probe_description() != http {
1495        return false;
1496    }
1497    grpc.strip_prefix("band-8 gRPC attempt failed: Connection error: ")
1498        .or_else(|| grpc.strip_prefix("band-8 gRPC version validation failed: "))
1499        .is_some_and(failure::is_redacted_provider_message)
1500        || grpc == "band-8 gRPC attempt skipped: band8 feature is not compiled in"
1501}
1502
1503fn controlled_connection_error(error: SecureConnectError) -> SecureConnectError {
1504    match error {
1505        SecureConnectError::Runtime(RuntimeError::Connection(ref message))
1506            if failure::is_redacted_provider_message(message) =>
1507        {
1508            error
1509        }
1510        SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
1511            core_version::VersionError::Probe(ref message),
1512        )) if is_redacted_discovery_failure(message) => error,
1513        SecureConnectError::TlsConfiguration(
1514            core_version::TlsConfigurationError::CustomRootCaNotFile { .. }
1515            | core_version::TlsConfigurationError::CustomRootCaUnreadable { .. }
1516            | core_version::TlsConfigurationError::CustomRootCaTooLarge { .. }
1517            | core_version::TlsConfigurationError::CustomRootCaInvalidPem { .. },
1518        ) => SecureConnectError::TlsConfiguration(
1519            core_version::TlsConfigurationError::ClientConfiguration,
1520        ),
1521        SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
1522            core_version::VersionError::Probe(_) | core_version::VersionError::Parse(_),
1523        )) => SecureConnectError::Runtime(RuntimeError::Connection(
1524            "TypeDB version discovery failed".to_owned(),
1525        )),
1526        SecureConnectError::Runtime(RuntimeError::Connection(_)) => SecureConnectError::Runtime(
1527            RuntimeError::Connection("TypeDB connection failed".to_owned()),
1528        ),
1529        SecureConnectError::Runtime(RuntimeError::QueryExecution(_)) => {
1530            SecureConnectError::Runtime(RuntimeError::QueryExecution(
1531                "TypeDB connection query failed".to_owned(),
1532            ))
1533        }
1534        SecureConnectError::Runtime(RuntimeError::Transaction(_)) => SecureConnectError::Runtime(
1535            RuntimeError::Transaction("TypeDB connection transaction failed".to_owned()),
1536        ),
1537        other => other,
1538    }
1539}
1540
1541#[cfg(feature = "band8")]
1542fn is_connection_control_error(error: &SecureConnectError) -> bool {
1543    matches!(
1544        error,
1545        SecureConnectError::Runtime(RuntimeError::ResourceLimit { .. })
1546    )
1547}
1548
1549fn close_driver_preserving(driver: &DriverHandle, error: SecureConnectError) -> SecureConnectError {
1550    if let Err(close_error) = driver.force_close() {
1551        trace_driver_drop_close_failure(&close_error);
1552    }
1553    error
1554}
1555
1556impl ResolvedTlsProbeMode {
1557    #[cfg(test)]
1558    const fn is_enabled(&self) -> bool {
1559        !matches!(self, Self::Disabled)
1560    }
1561}
1562
1563impl ResolvedTlsMode {
1564    fn from_captured_custom_root(mode: TlsMode, bytes: Arc<[u8]>) -> SecureResult<Self> {
1565        let material = match &mode {
1566            TlsMode::CustomRootCa(path) => {
1567                core_version::RetainedCustomRootCa::load_captured_bytes(path, bytes)?
1568            }
1569            TlsMode::Disabled | TlsMode::NativeRoots => {
1570                return Err(core_version::TlsConfigurationError::ClientConfiguration.into());
1571            }
1572        };
1573        Self::lower(mode, ResolvedTlsProbeMode::CustomRootCa(material))
1574    }
1575
1576    fn from_validated_physical_path(mode: TlsMode) -> SecureResult<Self> {
1577        let probe_mode = match &mode {
1578            TlsMode::Disabled => ResolvedTlsProbeMode::Disabled,
1579            TlsMode::NativeRoots => ResolvedTlsProbeMode::NativeRoots,
1580            TlsMode::CustomRootCa(path) => {
1581                ResolvedTlsProbeMode::CustomRootCa(core_version::RetainedCustomRootCa::load(path)?)
1582            }
1583        };
1584        Self::lower(mode, probe_mode)
1585    }
1586
1587    fn from_configured_path(mode: TlsMode) -> SecureResult<Self> {
1588        let probe_mode = match &mode {
1589            TlsMode::Disabled => ResolvedTlsProbeMode::Disabled,
1590            TlsMode::NativeRoots => ResolvedTlsProbeMode::NativeRoots,
1591            TlsMode::CustomRootCa(path) => ResolvedTlsProbeMode::CustomRootCa(
1592                core_version::RetainedCustomRootCa::load_configured_alias(path)?,
1593            ),
1594        };
1595        Self::lower(mode, probe_mode)
1596    }
1597
1598    fn lower(mode: TlsMode, probe_mode: ResolvedTlsProbeMode) -> SecureResult<Self> {
1599        let custom_root = match &probe_mode {
1600            ResolvedTlsProbeMode::CustomRootCa(material) => Some(material),
1601            ResolvedTlsProbeMode::Disabled | ResolvedTlsProbeMode::NativeRoots => None,
1602        };
1603
1604        if matches!(mode, TlsMode::CustomRootCa(_)) != custom_root.is_some() {
1605            return Err(core_version::TlsConfigurationError::ClientConfiguration.into());
1606        }
1607
1608        #[cfg(feature = "band8")]
1609        let band8 = match &mode {
1610            TlsMode::Disabled => DriverTlsConfig::disabled(),
1611            TlsMode::NativeRoots => DriverTlsConfig::enabled_with_native_root_ca(),
1612            TlsMode::CustomRootCa(_) => custom_root
1613                .ok_or(core_version::TlsConfigurationError::ClientConfiguration)?
1614                .with_driver_root_path(DriverTlsConfig::enabled_with_root_ca)?
1615                .map_err(|_| SecureConnectError::DriverTlsConfiguration { band: 8 })?,
1616        };
1617
1618        #[cfg(feature = "band9")]
1619        let band9 = match &mode {
1620            TlsMode::Disabled => B9DriverTlsConfig::disabled(),
1621            TlsMode::NativeRoots => B9DriverTlsConfig::enabled_with_native_root_ca(),
1622            TlsMode::CustomRootCa(_) => custom_root
1623                .ok_or(core_version::TlsConfigurationError::ClientConfiguration)?
1624                .with_driver_root_path(B9DriverTlsConfig::enabled_with_root_ca)?
1625                .map_err(|_| SecureConnectError::DriverTlsConfiguration { band: 9 })?,
1626        };
1627
1628        Ok(Self {
1629            probe_mode,
1630            #[cfg(feature = "band8")]
1631            band8,
1632            #[cfg(feature = "band9")]
1633            band9,
1634        })
1635    }
1636}
1637
1638/// Band-tagged driver state. Crate-private; no driver type escapes the crate.
1639enum DriverHandleInner {
1640    #[cfg(feature = "band8")]
1641    B8(B8Driver),
1642    #[cfg(feature = "band9")]
1643    B9(B9Driver),
1644}
1645
1646fn contain_driver_shutdown(shutdown: impl FnOnce() -> Result<()>) -> Result<()> {
1647    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(shutdown)) {
1648        Ok(result) => result,
1649        Err(_) => Err(RuntimeError::Connection(
1650            "Driver close failed: upstream driver panicked during shutdown".to_owned(),
1651        )),
1652    }
1653}
1654
1655#[cfg(test)]
1656fn run_driver_shutdown(
1657    state: &AtomicU8,
1658    close_lock: &Mutex<()>,
1659    shutdown: impl FnOnce() -> Result<()>,
1660) -> Result<()> {
1661    // Serialize explicit binding close, cleanup retries, and final-lease drop.
1662    // Recovering a poisoned guard is preferable to leaking the driver's
1663    // background runtime if an unrelated close caller previously panicked.
1664    let _close_guard = match close_lock.lock() {
1665        Ok(close_guard) => close_guard,
1666        Err(poisoned) => poisoned.into_inner(),
1667    };
1668
1669    run_driver_shutdown_locked(state, shutdown)
1670}
1671
1672fn run_driver_shutdown_locked(
1673    state: &AtomicU8,
1674    shutdown: impl FnOnce() -> Result<()>,
1675) -> Result<()> {
1676    match state.load(AtomicOrdering::Acquire) {
1677        DRIVER_CLOSED => return Ok(()),
1678        DRIVER_OPEN => {
1679            // Publish the monotonic transition before invoking upstream
1680            // shutdown. New operations now fail immediately; active
1681            // operations are cancelled rather than drained, because waiting
1682            // for them can recreate the terminal-close liveness defect
1683            // tracked by #196.
1684            state.store(DRIVER_CLOSING, AtomicOrdering::Release);
1685        }
1686        DRIVER_CLOSING => {
1687            // A prior shutdown attempt failed or panicked. Keep admission
1688            // terminal, but retry cleanup: the upstream 3.12 line can return before
1689            // closing its background runtime when server cleanup fails.
1690        }
1691        _ => unreachable!("driver shutdown state is internal and validated"),
1692    }
1693
1694    let result = contain_driver_shutdown(shutdown);
1695    if result.is_ok() {
1696        state.store(DRIVER_CLOSED, AtomicOrdering::Release);
1697    }
1698    result
1699}
1700
1701fn retain_driver_transaction(
1702    state: &AtomicU8,
1703    active_transactions: &AtomicUsize,
1704    close_lock: &Mutex<()>,
1705) -> Result<()> {
1706    let _close_guard = match close_lock.lock() {
1707        Ok(close_guard) => close_guard,
1708        Err(poisoned) => poisoned.into_inner(),
1709    };
1710    if state.load(AtomicOrdering::Acquire) != DRIVER_OPEN {
1711        return Err(RuntimeError::Connection(
1712            "TypeDB driver connection is closed".to_owned(),
1713        ));
1714    }
1715    active_transactions.fetch_add(1, AtomicOrdering::AcqRel);
1716    Ok(())
1717}
1718
1719/// Shared driver lifetime retained by every open transaction.
1720///
1721/// Automatic shutdown happens only when the final runtime/transaction lease is
1722/// released. Explicit connection close rejects while a transaction is active,
1723/// preserving child usability and making parent/child close order observable.
1724pub(crate) struct DriverHandle {
1725    inner: DriverHandleInner,
1726    state: AtomicU8,
1727    active_transactions: AtomicUsize,
1728    close_lock: Mutex<()>,
1729}
1730
1731const DRIVER_OPEN: u8 = 0;
1732const DRIVER_CLOSING: u8 = 1;
1733const DRIVER_CLOSED: u8 = 2;
1734
1735impl DriverHandle {
1736    #[cfg(feature = "band8")]
1737    fn band8(driver: B8Driver) -> Self {
1738        Self {
1739            inner: DriverHandleInner::B8(driver),
1740            state: AtomicU8::new(DRIVER_OPEN),
1741            active_transactions: AtomicUsize::new(0),
1742            close_lock: Mutex::new(()),
1743        }
1744    }
1745
1746    #[cfg(feature = "band9")]
1747    fn band9(driver: B9Driver) -> Self {
1748        Self {
1749            inner: DriverHandleInner::B9(driver),
1750            state: AtomicU8::new(DRIVER_OPEN),
1751            active_transactions: AtomicUsize::new(0),
1752            close_lock: Mutex::new(()),
1753        }
1754    }
1755
1756    fn inner(&self) -> &DriverHandleInner {
1757        &self.inner
1758    }
1759
1760    fn band(&self) -> u8 {
1761        match &self.inner {
1762            #[cfg(feature = "band8")]
1763            DriverHandleInner::B8(_) => 8,
1764            #[cfg(feature = "band9")]
1765            DriverHandleInner::B9(_) => 9,
1766        }
1767    }
1768
1769    fn ensure_open(&self) -> Result<()> {
1770        if self.state.load(AtomicOrdering::Acquire) == DRIVER_OPEN {
1771            Ok(())
1772        } else {
1773            Err(RuntimeError::Connection(
1774                "TypeDB driver connection is closed".to_owned(),
1775            ))
1776        }
1777    }
1778
1779    fn shutdown_started(&self) -> bool {
1780        self.state.load(AtomicOrdering::Acquire) != DRIVER_OPEN
1781    }
1782
1783    /// Make the selected driver terminal and dispatch upstream shutdown.
1784    ///
1785    /// A failed attempt leaves admission closed and permits a later cleanup
1786    /// retry; after successful dispatch, subsequent calls are no-ops. The
1787    /// upstream callback worker is joined only when the final driver lease is
1788    /// dropped.
1789    fn force_close(&self) -> Result<()> {
1790        let _close_guard = match self.close_lock.lock() {
1791            Ok(close_guard) => close_guard,
1792            Err(poisoned) => poisoned.into_inner(),
1793        };
1794        if self.active_transactions.load(AtomicOrdering::Acquire) != 0 {
1795            return Err(RuntimeError::ResourceLimit {
1796                code: "resource_in_use",
1797                message: "connection cannot close while a transaction is active",
1798            });
1799        }
1800        run_driver_shutdown_locked(&self.state, || match &self.inner {
1801            #[cfg(feature = "band8")]
1802            DriverHandleInner::B8(driver) => driver.force_close().map_err(|error| {
1803                RuntimeError::Connection(redact_provider_error(&error, "force close failed"))
1804            }),
1805            #[cfg(feature = "band9")]
1806            DriverHandleInner::B9(driver) => driver.force_close().map_err(|error| {
1807                RuntimeError::Connection(redact_provider_error(&error, "force close failed"))
1808            }),
1809        })
1810    }
1811}
1812
1813impl Drop for DriverHandle {
1814    fn drop(&mut self) {
1815        // Temporary downstream lifecycle workaround and removal gate:
1816        // https://github.com/ds1sqe/type-bridge/issues/196
1817        //
1818        // The official driver exposes explicit shutdown because ordinary field
1819        // drop can leave background transaction workers alive long enough to
1820        // poison later driver lifecycles. The final shared lease closes while
1821        // every driver field is intact, without invalidating a transaction that
1822        // outlives its originating database handle.
1823        if let Err(error) = self.force_close() {
1824            trace_driver_drop_close_failure(&error);
1825        }
1826    }
1827}
1828
1829/// Real TypeDB backend wrapping an internal band-tagged driver handle.
1830pub struct TypeDBRuntime {
1831    driver: Arc<DriverHandle>,
1832    /// The server version the connect gate detected, when it could.
1833    ///
1834    /// `Some` whenever the exact-version, HTTP-probe, or gRPC path produced an
1835    /// authoritative identity. When it is `None`, the negotiated driver band
1836    /// remains the authority for legacy-fallback classification.
1837    server_version: Option<core_version::Version>,
1838}
1839
1840impl TypeDBRuntime {
1841    /// Make the selected driver terminal and dispatch upstream shutdown.
1842    ///
1843    /// Bindings call this at their public connection-close boundary instead of
1844    /// relying on field drop ordering. While any transaction handle is retained,
1845    /// close returns `resource_in_use` and leaves the connection available.
1846    /// After those handles are released, the first call prevents new operations,
1847    /// invalidates in-flight work through upstream shutdown, and
1848    /// leaves the runtime permanently unavailable even if shutdown reports an
1849    /// error. A later call retries incomplete upstream dispatch without
1850    /// reopening the connection; calls after successful dispatch are harmless.
1851    /// Final callback-worker release remains lease-aware and occurs when the
1852    /// last driver handle drops.
1853    pub fn force_close(&self) -> Result<()> {
1854        self.driver.force_close()
1855    }
1856}
1857
1858/// Released Boolean-adapter gate with an injectable probe.
1859#[cfg(test)]
1860pub(crate) async fn gated_driver_with_probe<F>(
1861    address: &str,
1862    username: &str,
1863    password: &str,
1864    options: ConnectOptions,
1865    probe: F,
1866) -> Result<(DriverHandle, Option<core_version::Version>)>
1867where
1868    F: FnOnce(
1869            &str,
1870            u16,
1871            bool,
1872        ) -> std::result::Result<core_version::Version, core_version::VersionError>
1873        + Send
1874        + 'static,
1875{
1876    gated_driver_secure_with_probe(
1877        address,
1878        username,
1879        password,
1880        options.into(),
1881        move |probe_address, http_port, tls_mode| {
1882            probe(probe_address, http_port, tls_mode.is_enabled())
1883                .map_err(core_version::VersionProbeError::Probe)
1884        },
1885    )
1886    .await
1887    .map_err(SecureConnectError::into_runtime_error)
1888}
1889
1890/// Version-gated secure driver constructor with an injectable typed probe.
1891///
1892/// Custom roots and all compiled driver TLS configurations are validated
1893/// before the exact-version fast path, HTTP probe, or any gRPC construction.
1894/// If the HTTP request itself fails, the same [`ResolvedTlsMode`] is retained
1895/// by every fallback and upgrade attempt.  TLS configuration failures are
1896/// terminal and never trigger a transport fallback.
1897async fn gated_driver_secure_with_probe<F>(
1898    address: &str,
1899    username: &str,
1900    password: &str,
1901    options: SecureConnectOptions,
1902    probe: F,
1903) -> SecureResult<(DriverHandle, Option<core_version::Version>)>
1904where
1905    F: FnOnce(
1906            &str,
1907            u16,
1908            &ResolvedTlsProbeMode,
1909        )
1910            -> std::result::Result<core_version::Version, core_version::VersionProbeError>
1911        + Send
1912        + 'static,
1913{
1914    let prepared = options.prepare_transport()?;
1915    gated_driver_prepared_with_probe(address, username, password, prepared, probe).await
1916}
1917
1918async fn gated_driver_prepared_with_probe<F>(
1919    address: &str,
1920    username: &str,
1921    password: &str,
1922    options: PreparedSecureConnectOptions,
1923    probe: F,
1924) -> SecureResult<(DriverHandle, Option<core_version::Version>)>
1925where
1926    F: FnOnce(
1927            &str,
1928            u16,
1929            &ResolvedTlsProbeMode,
1930        )
1931            -> std::result::Result<core_version::Version, core_version::VersionProbeError>
1932        + Send
1933        + 'static,
1934{
1935    let controlled = options.connection_control.is_some();
1936    let result = async {
1937        let PreparedSecureConnectOptions {
1938            http_port,
1939            server_version,
1940            required_server_version,
1941            resolved_tls,
1942            connection_control,
1943        } = options;
1944        let mut meter = connection_control
1945            .map(ConnectionMeter::new)
1946            .unwrap_or_else(ConnectionMeter::legacy);
1947        // A zero item ceiling cannot admit the only public connection result.
1948        // Reject it before a probe, address parse, credential construction, or
1949        // driver host is attempted.
1950        meter.require_possible_success()?;
1951
1952        let connected = if let Some(server_version) = server_version {
1953            let driver = driver_for_server_version(
1954                address,
1955                username,
1956                password,
1957                server_version,
1958                &resolved_tls,
1959                &mut meter,
1960            )
1961            .await?;
1962            (driver, Some(server_version))
1963        } else {
1964            // The HTTP client is blocking, so dispatch it on the blocking pool
1965            // and race its join handle against the same wakeable invocation
1966            // control used for asynchronous driver construction.
1967            meter.charge_statement()?;
1968            let address_owned = address.to_string();
1969            let probe_mode = resolved_tls.probe_mode.clone();
1970            let probe_task =
1971                tokio::task::spawn_blocking(move || probe(&address_owned, http_port, &probe_mode));
1972            let probe_result = await_connection_work(probe_task, meter.control())
1973                .await?
1974                .map_err(|_error| {
1975                    RuntimeError::Connection("Version probe task failed".to_owned())
1976                })?;
1977
1978            match probe_result {
1979                Ok(server_version) => {
1980                    meter.charge_version_evidence(server_version)?;
1981                    require_generated_server_version(server_version, required_server_version)?;
1982                    let driver = driver_for_server_version(
1983                        address,
1984                        username,
1985                        password,
1986                        server_version,
1987                        &resolved_tls,
1988                        &mut meter,
1989                    )
1990                    .await?;
1991                    (driver, Some(server_version))
1992                }
1993                Err(core_version::VersionProbeError::Probe(http_error)) => {
1994                    grpc_fallback_driver(
1995                        address,
1996                        username,
1997                        password,
1998                        http_error,
1999                        &resolved_tls,
2000                        &mut meter,
2001                        required_server_version,
2002                    )
2003                    .await?
2004                }
2005                Err(core_version::VersionProbeError::TlsConfiguration(error)) => {
2006                    return Err(SecureConnectError::TlsConfiguration(error));
2007                }
2008            }
2009        };
2010
2011        if let Err(error) = meter.admit_connection() {
2012            return Err(close_driver_preserving(&connected.0, error.into()));
2013        }
2014        Ok(connected)
2015    }
2016    .await;
2017
2018    if controlled {
2019        result.map_err(controlled_connection_error)
2020    } else {
2021        result
2022    }
2023}
2024
2025fn require_generated_server_version(
2026    observed: core_version::Version,
2027    required: Option<core_version::GeneratedPackageRelease>,
2028) -> Result<()> {
2029    let Some(release) = required else {
2030        return Ok(());
2031    };
2032    if release.admits(&observed) {
2033        return Ok(());
2034    }
2035    Err(RuntimeError::UnsupportedVersion(
2036        release.unsupported_version(observed),
2037    ))
2038}
2039
2040fn validate_server_band(server_version: &core_version::Version) -> Result<u8> {
2041    // Embedded-runtime gate: accept the server when it is in-window and any
2042    // band it accepts is one this build embedded.  Unlike the installed-driver
2043    // gate (check_supported), the embedded runtime carries every compiled-in
2044    // band. A confirmed 3.12 server normally negotiates native band 9; its
2045    // band-8 acceptance remains
2046    // available to discovery/fallback paths. After this passes, negotiation
2047    // over EMBEDDED_BANDS is guaranteed to yield a band.
2048    core_version::check_server_supported(server_version, EMBEDDED_BANDS)
2049        .map_err(RuntimeError::UnsupportedVersion)?;
2050
2051    Ok(
2052        core_version::negotiate_server_band(server_version, EMBEDDED_BANDS)
2053            .expect("check_server_supported accepted a server with no negotiable band"),
2054    )
2055}
2056
2057async fn driver_for_server_version(
2058    address: &str,
2059    username: &str,
2060    password: &str,
2061    server_version: core_version::Version,
2062    tls: &ResolvedTlsMode,
2063    meter: &mut ConnectionMeter,
2064) -> SecureResult<DriverHandle> {
2065    let band = validate_server_band(&server_version)?;
2066
2067    trace_version_gate_passed(address, band, server_version);
2068
2069    #[cfg(feature = "band8")]
2070    if band == 8 {
2071        return connect_band8_driver(address, username, password, tls, meter)
2072            .await
2073            .map(DriverHandle::band8);
2074    }
2075
2076    #[cfg(feature = "band9")]
2077    if band == 9 {
2078        return connect_band9_driver(address, username, password, tls, meter)
2079            .await
2080            .map(DriverHandle::band9);
2081    }
2082
2083    // Unreachable by invariant: the gate already rejected any server whose
2084    // accepted-band set does not intersect EMBEDDED_BANDS, and negotiation
2085    // only yields embedded bands, each of which returned above.  The arm
2086    // exists only to keep the tail total; it is never entered.
2087    Err(RuntimeError::Connection(format!(
2088        "No compiled driver band supports the negotiated server band ({band})"
2089    ))
2090    .into())
2091}
2092
2093#[cfg(feature = "band8")]
2094async fn connect_band8_driver(
2095    address: &str,
2096    username: &str,
2097    password: &str,
2098    tls: &ResolvedTlsMode,
2099    meter: &mut ConnectionMeter,
2100) -> SecureResult<B8Driver> {
2101    let addresses = Addresses::try_from_address_str(address)
2102        .map_err(|e| RuntimeError::Connection(failure::redact_address_error(&e)))?;
2103    meter.charge_statement()?;
2104    let result = await_connection_work(
2105        B8Driver::new(
2106            addresses,
2107            B8Credentials::new(username, password),
2108            DriverOptions::new(tls.band8.clone()),
2109        ),
2110        meter.control(),
2111    )
2112    .await?;
2113    result.map_err(|e| {
2114        RuntimeError::Connection(redact_provider_error(&e, "Failed to connect")).into()
2115    })
2116}
2117
2118#[cfg(feature = "band9")]
2119async fn connect_band9_driver(
2120    address: &str,
2121    username: &str,
2122    password: &str,
2123    tls: &ResolvedTlsMode,
2124    meter: &mut ConnectionMeter,
2125) -> SecureResult<B9Driver> {
2126    let addresses = B9Addresses::try_from_address_str(address)
2127        .map_err(|e| RuntimeError::Connection(failure::redact_address_error(&e)))?;
2128    meter.charge_statement()?;
2129    let result = await_connection_work(
2130        B9Driver::new(
2131            addresses,
2132            B9Credentials::new(username, password),
2133            B9DriverOptions::new(tls.band9.clone()),
2134        ),
2135        meter.control(),
2136    )
2137    .await?;
2138    result.map_err(|e| {
2139        RuntimeError::Connection(redact_provider_error(&e, "Failed to connect")).into()
2140    })
2141}
2142
2143async fn grpc_fallback_driver(
2144    address: &str,
2145    username: &str,
2146    password: &str,
2147    http_error: core_version::VersionError,
2148    tls: &ResolvedTlsMode,
2149    meter: &mut ConnectionMeter,
2150    required_server_version: Option<core_version::GeneratedPackageRelease>,
2151) -> SecureResult<(DriverHandle, Option<core_version::Version>)> {
2152    #[cfg(not(feature = "band8"))]
2153    let _ = (
2154        address,
2155        username,
2156        password,
2157        tls,
2158        meter,
2159        required_server_version,
2160    );
2161    let mut failures = vec![format!(
2162        "HTTP version probe failed: {}",
2163        http_error.redacted_probe_description()
2164    )];
2165
2166    // Band 9 is deliberately NOT probed blindly: a band-9 connection attempt
2167    // against a 3.11 server crashes the server outright (measured live on
2168    // 3.11.5).  The fallback therefore discovers the server through band 8 —
2169    // usable for version discovery on servers that accept band 8 — and only upgrades
2170    // to band 9 once the reported version proves the server accepts it.
2171    #[cfg(feature = "band8")]
2172    {
2173        match connect_band8_driver(address, username, password, tls, meter).await {
2174            Ok(driver) => {
2175                // Wrap the discovery candidate immediately so every error,
2176                // retry, and native-band upgrade path deterministically closes
2177                // it rather than relying on the upstream field-drop path.
2178                let driver = DriverHandle::band8(driver);
2179                let reported = match driver.inner() {
2180                    DriverHandleInner::B8(driver) => {
2181                        meter.charge_statement()?;
2182                        await_connection_work(driver.server_version(), meter.control())
2183                            .await?
2184                            .map(|reported| reported.version().to_owned())
2185                            .map_err(|error| {
2186                                redact_provider_error(&error, "gRPC server version failed")
2187                            })
2188                    }
2189                    #[cfg(feature = "band9")]
2190                    _ => {
2191                        return Err(RuntimeError::Connection(
2192                            "Internal TypeDB driver-band mismatch".to_owned(),
2193                        )
2194                        .into());
2195                    }
2196                };
2197                let classification = match classify_band8_grpc_version(address, reported) {
2198                    Ok(classification) => classification,
2199                    Err(error) => {
2200                        driver.force_close().map_err(SecureConnectError::Runtime)?;
2201                        return Err(SecureConnectError::Runtime(error));
2202                    }
2203                };
2204                match classification {
2205                    Band8GrpcVersion::Validated(server_version) => {
2206                        if let Err(error) = meter.charge_version_evidence(server_version) {
2207                            return Err(close_driver_preserving(&driver, error.into()));
2208                        }
2209                        if let Err(error) = require_generated_server_version(
2210                            server_version,
2211                            required_server_version,
2212                        ) {
2213                            return Err(close_driver_preserving(&driver, error.into()));
2214                        }
2215                        // Prefer the server's native band when this build embeds
2216                        // it. The authoritative band-8 version round trip makes a
2217                        // band-9 attempt safe; probing band 9 before this point can
2218                        // crash a 3.11 server.
2219                        #[cfg(feature = "band9")]
2220                        if core_version::negotiate_server_band(&server_version, EMBEDDED_BANDS)
2221                            == Some(9)
2222                        {
2223                            // The frozen common statement maximum is three.
2224                            // HTTP failure, band-8 construction, and band-8
2225                            // version discovery consume those three charges;
2226                            // a controlled band-9 upgrade is therefore a real
2227                            // fourth dispatch and fails closed at the meter.
2228                            // The legacy path has no attached meter and keeps
2229                            // its released upgrade behavior unchanged.
2230                            match connect_band9_driver(address, username, password, tls, meter)
2231                                .await
2232                            {
2233                                Ok(b9_driver) => {
2234                                    let b9_driver = DriverHandle::band9(b9_driver);
2235                                    driver.force_close().map_err(SecureConnectError::Runtime)?;
2236                                    trace_band9_upgrade_succeeded(address, server_version);
2237                                    return Ok((b9_driver, Some(server_version)));
2238                                }
2239                                Err(error) => {
2240                                    if is_connection_control_error(&error) {
2241                                        return Err(close_driver_preserving(&driver, error));
2242                                    }
2243                                    trace_band9_upgrade_failed(address, server_version, &error);
2244                                    if !core_version::server_accepted_bands(&server_version)
2245                                        .contains(&8)
2246                                    {
2247                                        return Err(close_driver_preserving(&driver, error));
2248                                    }
2249                                }
2250                            }
2251                        }
2252                        trace_band8_fallback_connected(address, server_version);
2253                        return Ok((driver, Some(server_version)));
2254                    }
2255                    Band8GrpcVersion::RetryableFailure(failure) => {
2256                        driver.force_close().map_err(SecureConnectError::Runtime)?;
2257                        failures.push(failure);
2258                    }
2259                }
2260            }
2261            Err(error) if is_connection_control_error(&error) => return Err(error),
2262            Err(error) => failures.push(format!("band-8 gRPC attempt failed: {error}")),
2263        }
2264    }
2265
2266    #[cfg(not(feature = "band8"))]
2267    failures.push("band-8 gRPC attempt skipped: band8 feature is not compiled in".to_string());
2268
2269    Err(
2270        RuntimeError::UnsupportedVersion(core_version::VersionError::Probe(format!(
2271            "HTTP version probe and gRPC fallback both failed: {}",
2272            failures.join("; ")
2273        )))
2274        .into(),
2275    )
2276}
2277
2278#[cfg(feature = "band8")]
2279#[derive(Debug)]
2280enum Band8GrpcVersion {
2281    Validated(core_version::Version),
2282    RetryableFailure(String),
2283}
2284
2285#[cfg(feature = "band8")]
2286fn classify_band8_grpc_version(
2287    _address: &str,
2288    reported: std::result::Result<String, String>,
2289) -> Result<Band8GrpcVersion> {
2290    let reported = match reported {
2291        Ok(reported) => reported,
2292        Err(error) => {
2293            // TypeDB's band-8 Driver::new is lazy, so it can return Ok before
2294            // server_version performs the first protocol round trip. Preserve
2295            // that failure as fallback evidence without accepting an
2296            // unvalidated connection.
2297            return Ok(Band8GrpcVersion::RetryableFailure(format!(
2298                "band-8 gRPC version validation failed: {error}"
2299            )));
2300        }
2301    };
2302
2303    // Once the server has authoritatively reported a version, parse and gate
2304    // failures are terminal. Falling through to band 7 here could silently
2305    // accept an unsupported server and discard the exact rejection evidence.
2306    let server_version = reported
2307        .parse::<core_version::Version>()
2308        .map_err(RuntimeError::UnsupportedVersion)?;
2309    validate_server_band(&server_version)?;
2310
2311    Ok(Band8GrpcVersion::Validated(server_version))
2312}
2313
2314fn probe_server_version_for_tls_mode(
2315    address: &str,
2316    http_port: u16,
2317    tls_mode: &ResolvedTlsProbeMode,
2318) -> std::result::Result<core_version::Version, core_version::VersionProbeError> {
2319    match tls_mode {
2320        ResolvedTlsProbeMode::Disabled => {
2321            core_version::server_version_plaintext(address, http_port)
2322        }
2323        ResolvedTlsProbeMode::NativeRoots => {
2324            core_version::server_version_native_roots(address, http_port)
2325        }
2326        ResolvedTlsProbeMode::CustomRootCa(material) => {
2327            core_version::server_version_retained_custom_root_ca(address, http_port, material)
2328        }
2329    }
2330}
2331
2332/// Version-gated released [`ConnectOptions`] adapter.
2333async fn gated_driver(
2334    address: &str,
2335    username: &str,
2336    password: &str,
2337    options: ConnectOptions,
2338) -> Result<(DriverHandle, Option<core_version::Version>)> {
2339    gated_driver_secure(address, username, password, options.into())
2340        .await
2341        .map_err(SecureConnectError::into_runtime_error)
2342}
2343
2344/// Version-gated typed TLS constructor.
2345async fn gated_driver_secure(
2346    address: &str,
2347    username: &str,
2348    password: &str,
2349    options: SecureConnectOptions,
2350) -> SecureResult<(DriverHandle, Option<core_version::Version>)> {
2351    gated_driver_secure_with_probe(
2352        address,
2353        username,
2354        password,
2355        options,
2356        probe_server_version_for_tls_mode,
2357    )
2358    .await
2359}
2360
2361async fn gated_driver_prepared_secure(
2362    address: &str,
2363    username: &str,
2364    password: &str,
2365    options: PreparedSecureConnectOptions,
2366) -> SecureResult<(DriverHandle, Option<core_version::Version>)> {
2367    gated_driver_prepared_with_probe(
2368        address,
2369        username,
2370        password,
2371        options,
2372        probe_server_version_for_tls_mode,
2373    )
2374    .await
2375}
2376
2377impl TypeDBRuntime {
2378    /// Connect to a TypeDB server.
2379    ///
2380    /// Validates the supplied server version, or probes via HTTP before opening
2381    /// any gRPC connection when no version is supplied. If HTTP discovery fails,
2382    /// band 8 discovers the version before upgrading to band 9 when supported.
2383    /// A server that requires band 9 fails closed if the upgrade fails.
2384    /// Versions below the admission floor or without a compiled protocol band
2385    /// return [`RuntimeError::UnsupportedVersion`]. Newer lines are admitted with
2386    /// one warning: not tested or supported by this TypeBridge release.
2387    pub async fn connect(
2388        address: &str,
2389        username: &str,
2390        password: &str,
2391        options: ConnectOptions,
2392    ) -> Result<Self> {
2393        let (driver, server_version) = gated_driver(address, username, password, options).await?;
2394        trace_runtime_connected(address, driver.band(), server_version);
2395        Ok(Self {
2396            driver: Arc::new(driver),
2397            server_version,
2398        })
2399    }
2400
2401    /// Connect using an explicit typed TLS policy.
2402    ///
2403    /// Custom trust material is validated before the HTTP version probe or
2404    /// any gRPC host is constructed.  An enabled mode remains enabled through
2405    /// HTTP failure, driver-band discovery, and native-band upgrade.
2406    pub async fn connect_secure(
2407        address: &str,
2408        username: &str,
2409        password: &str,
2410        options: SecureConnectOptions,
2411    ) -> SecureResult<Self> {
2412        let (driver, server_version) =
2413            gated_driver_secure(address, username, password, options).await?;
2414        trace_runtime_connected(address, driver.band(), server_version);
2415        Ok(Self {
2416            driver: Arc::new(driver),
2417            server_version,
2418        })
2419    }
2420
2421    /// Connect with a transport policy that was already fully resolved.
2422    ///
2423    /// This hidden orchestration seam performs no trust-material path I/O;
2424    /// clones of `options` share the exact prepared custom-root snapshot.
2425    #[doc(hidden)]
2426    pub async fn connect_prepared_secure(
2427        address: &str,
2428        username: &str,
2429        password: &str,
2430        options: PreparedSecureConnectOptions,
2431    ) -> SecureResult<Self> {
2432        let (driver, server_version) =
2433            gated_driver_prepared_secure(address, username, password, options).await?;
2434        trace_runtime_connected(address, driver.band(), server_version);
2435        Ok(Self {
2436            driver: Arc::new(driver),
2437            server_version,
2438        })
2439    }
2440
2441    /// The server version detected by the connect gate, when known.
2442    ///
2443    /// When this is `None`, callers must use the negotiated driver band rather
2444    /// than inferring a server version from a failed HTTP probe.
2445    pub fn server_version(&self) -> Option<core_version::Version> {
2446        self.server_version
2447    }
2448
2449    /// Return whether the connection actually negotiated a driver that can
2450    /// transport `given` input rows.
2451    ///
2452    /// This is deliberately separate from the reported server version. A
2453    /// 3.12 server may accept the band-8 discovery connection when a later
2454    /// band-9 upgrade fails; advertising `given` in that state would select an
2455    /// execution path the active driver cannot carry.
2456    pub fn supports_given_rows(&self) -> bool {
2457        match self.driver.inner() {
2458            #[cfg(feature = "band8")]
2459            DriverHandleInner::B8(_) => false,
2460            #[cfg(feature = "band9")]
2461            DriverHandleInner::B9(_) => true,
2462        }
2463    }
2464}
2465
2466fn runtime_error_diagnostic(error: RuntimeError) -> String {
2467    match error {
2468        RuntimeError::Connection(message) => message,
2469        other => other.to_string(),
2470    }
2471}
2472
2473fn finish_one_shot_database_operation<T>(operation: Result<T>, close: Result<()>) -> Result<T> {
2474    match (operation, close) {
2475        (Ok(value), Ok(())) => Ok(value),
2476        (Ok(_), Err(close_error)) => Err(close_error),
2477        (Err(operation_error), Ok(())) => Err(operation_error),
2478        (Err(operation_error), Err(close_error)) => Err(RuntimeError::Connection(format!(
2479            "{}; additionally, TypeDB driver cleanup failed: {}",
2480            runtime_error_diagnostic(operation_error),
2481            runtime_error_diagnostic(close_error),
2482        ))),
2483    }
2484}
2485
2486/// Ensure a TypeDB database exists, creating it if absent.
2487///
2488/// Validates the supplied server version, or probes via HTTP before opening any
2489/// gRPC connection when no version is supplied.
2490/// Returns [`RuntimeError::UnsupportedVersion`] when the server is outside the
2491/// supported window or on a different protocol band than the driver.
2492///
2493/// On all other TypeDB failures (including unreachable server) the error is
2494/// returned so callers can treat it as a hard failure rather than silently
2495/// skipping.
2496pub async fn ensure_database_exists(
2497    address: &str,
2498    database: &str,
2499    username: &str,
2500    password: &str,
2501    options: ConnectOptions,
2502) -> Result<()> {
2503    ensure_database_exists_secure(address, database, username, password, options.into())
2504        .await
2505        .map_err(SecureConnectError::into_runtime_error)
2506}
2507
2508/// Ensure a TypeDB database exists using an explicit typed TLS policy.
2509///
2510/// The same resolved policy is used for version discovery, gRPC fallback, and
2511/// the database lookup/create operations on the resulting driver.
2512pub async fn ensure_database_exists_secure(
2513    address: &str,
2514    database: &str,
2515    username: &str,
2516    password: &str,
2517    options: SecureConnectOptions,
2518) -> SecureResult<()> {
2519    ensure_database_exists_prepared_secure(
2520        address,
2521        database,
2522        username,
2523        password,
2524        options.prepare_transport()?,
2525    )
2526    .await
2527}
2528
2529/// Ensure a database exists using an already resolved transport snapshot.
2530#[doc(hidden)]
2531pub async fn ensure_database_exists_prepared_secure(
2532    address: &str,
2533    database: &str,
2534    username: &str,
2535    password: &str,
2536    options: PreparedSecureConnectOptions,
2537) -> SecureResult<()> {
2538    let (driver, server_version) =
2539        gated_driver_prepared_secure(address, username, password, options).await?;
2540    let runtime = TypeDBRuntime {
2541        driver: Arc::new(driver),
2542        server_version,
2543    };
2544    let operation = async {
2545        if !runtime.database_exists(database).await? {
2546            runtime.create_database(database).await?;
2547        }
2548        Ok(())
2549    }
2550    .await;
2551    let close = runtime.force_close();
2552    finish_one_shot_database_operation(operation, close).map_err(SecureConnectError::Runtime)
2553}
2554
2555/// Check whether a TypeDB database exists without creating it.
2556///
2557/// Same version gating as [`ensure_database_exists`]; the lookup itself is
2558/// read-only and never mutates server state.
2559pub async fn database_exists(
2560    address: &str,
2561    database: &str,
2562    username: &str,
2563    password: &str,
2564    options: ConnectOptions,
2565) -> Result<bool> {
2566    database_exists_secure(address, database, username, password, options.into())
2567        .await
2568        .map_err(SecureConnectError::into_runtime_error)
2569}
2570
2571/// Check whether a TypeDB database exists using an explicit typed TLS policy.
2572pub async fn database_exists_secure(
2573    address: &str,
2574    database: &str,
2575    username: &str,
2576    password: &str,
2577    options: SecureConnectOptions,
2578) -> SecureResult<bool> {
2579    database_exists_prepared_secure(
2580        address,
2581        database,
2582        username,
2583        password,
2584        options.prepare_transport()?,
2585    )
2586    .await
2587}
2588
2589/// Check for a database using an already resolved transport snapshot.
2590#[doc(hidden)]
2591pub async fn database_exists_prepared_secure(
2592    address: &str,
2593    database: &str,
2594    username: &str,
2595    password: &str,
2596    options: PreparedSecureConnectOptions,
2597) -> SecureResult<bool> {
2598    let (driver, server_version) =
2599        gated_driver_prepared_secure(address, username, password, options).await?;
2600    let runtime = TypeDBRuntime {
2601        driver: Arc::new(driver),
2602        server_version,
2603    };
2604    let operation = runtime.database_exists(database).await;
2605    let close = runtime.force_close();
2606    finish_one_shot_database_operation(operation, close).map_err(SecureConnectError::Runtime)
2607}
2608
2609/// Connect securely and delete a TypeDB database.
2610///
2611/// This lifecycle entry point exists for callers that do not otherwise need
2612/// to retain a [`TypeDBRuntime`].  Deleting through an already connected
2613/// runtime remains available as [`TypeDBRuntime::delete_database`].
2614pub async fn delete_database_secure(
2615    address: &str,
2616    database: &str,
2617    username: &str,
2618    password: &str,
2619    options: SecureConnectOptions,
2620) -> SecureResult<()> {
2621    delete_database_prepared_secure(
2622        address,
2623        database,
2624        username,
2625        password,
2626        options.prepare_transport()?,
2627    )
2628    .await
2629}
2630
2631/// Delete a database using an already resolved transport snapshot.
2632#[doc(hidden)]
2633pub async fn delete_database_prepared_secure(
2634    address: &str,
2635    database: &str,
2636    username: &str,
2637    password: &str,
2638    options: PreparedSecureConnectOptions,
2639) -> SecureResult<()> {
2640    let runtime =
2641        TypeDBRuntime::connect_prepared_secure(address, username, password, options).await?;
2642    let operation = async {
2643        if runtime.database_exists(database).await? {
2644            runtime.delete_database(database).await?;
2645        }
2646        Ok(())
2647    }
2648    .await;
2649    let close = runtime.force_close();
2650    finish_one_shot_database_operation(operation, close).map_err(SecureConnectError::Runtime)
2651}
2652
2653impl TypeDBRuntime {
2654    /// Open a TypeDB transaction against `database`.
2655    pub fn open_transaction(
2656        &self,
2657        database: &str,
2658        tx_type: TxType,
2659    ) -> BoxFuture<'_, Result<RuntimeTransaction>> {
2660        self.open_transaction_with_options(database, tx_type, &TransactionOptions::default())
2661    }
2662
2663    /// Open a TypeDB transaction with an explicit server-side lifetime bound.
2664    ///
2665    /// Higher layers use this for transactions that hold schema exclusion: a
2666    /// lost client must not leave the server-side fence unbounded while the
2667    /// transport is still detecting terminal closure.
2668    pub fn open_transaction_with_timeout(
2669        &self,
2670        database: &str,
2671        tx_type: TxType,
2672        timeout: Duration,
2673    ) -> BoxFuture<'_, Result<RuntimeTransaction>> {
2674        self.open_transaction_with_options(
2675            database,
2676            tx_type,
2677            &TransactionOptions {
2678                transaction_timeout: Some(timeout),
2679                schema_lock_acquire_timeout: Some(timeout),
2680            },
2681        )
2682    }
2683
2684    /// Open a transaction with independently configured server-side bounds.
2685    pub fn open_transaction_with_options(
2686        &self,
2687        database: &str,
2688        tx_type: TxType,
2689        options: &TransactionOptions,
2690    ) -> BoxFuture<'_, Result<RuntimeTransaction>> {
2691        let db = database.to_string();
2692        let options = *options;
2693        let driver_lease = Arc::clone(&self.driver);
2694        let work = async move {
2695            driver_lease.ensure_open()?;
2696            match driver_lease.inner() {
2697                #[cfg(feature = "band8")]
2698                DriverHandleInner::B8(d) => {
2699                    let typedb_tx_type = match tx_type {
2700                        TxType::Read => B8TransactionType::Read,
2701                        TxType::Write => B8TransactionType::Write,
2702                        TxType::Schema => B8TransactionType::Schema,
2703                    };
2704                    let options = options.band8();
2705                    let transaction = d
2706                        .transaction_with_options(&db, typedb_tx_type, options)
2707                        .await
2708                        .map_err(|e| {
2709                            RuntimeError::Transaction(redact_provider_error(
2710                                &e,
2711                                "Failed to open transaction",
2712                            ))
2713                        })?;
2714                    retain_driver_transaction(
2715                        &driver_lease.state,
2716                        &driver_lease.active_transactions,
2717                        &driver_lease.close_lock,
2718                    )?;
2719                    Ok(RuntimeTransaction {
2720                        inner: RuntimeTransactionInner::B8(Some(transaction)),
2721                        driver_lease: Some(driver_lease),
2722                    })
2723                }
2724                #[cfg(feature = "band9")]
2725                DriverHandleInner::B9(d) => {
2726                    let typedb_tx_type = match tx_type {
2727                        TxType::Read => B9TransactionType::Read,
2728                        TxType::Write => B9TransactionType::Write,
2729                        TxType::Schema => B9TransactionType::Schema,
2730                    };
2731                    let options = options.band9();
2732                    let transaction = d
2733                        .transaction_with_options(&db, typedb_tx_type, options)
2734                        .await
2735                        .map_err(|e| {
2736                            RuntimeError::Transaction(redact_provider_error(
2737                                &e,
2738                                "Failed to open transaction",
2739                            ))
2740                        })?;
2741                    retain_driver_transaction(
2742                        &driver_lease.state,
2743                        &driver_lease.active_transactions,
2744                        &driver_lease.close_lock,
2745                    )?;
2746                    Ok(RuntimeTransaction {
2747                        inner: RuntimeTransactionInner::B9(Some(transaction)),
2748                        driver_lease: Some(driver_lease),
2749                    })
2750                }
2751            }
2752        };
2753        Box::pin(work.instrument(execute_span()))
2754    }
2755
2756    /// Check whether the underlying driver is open.
2757    pub fn is_open(&self) -> bool {
2758        if self.driver.shutdown_started() {
2759            return false;
2760        }
2761        match self.driver.inner() {
2762            #[cfg(feature = "band8")]
2763            DriverHandleInner::B8(d) => d.is_open(),
2764            #[cfg(feature = "band9")]
2765            DriverHandleInner::B9(d) => d.is_open(),
2766        }
2767    }
2768
2769    /// Check whether a database exists.
2770    pub fn database_exists(&self, database: &str) -> BoxFuture<'_, Result<bool>> {
2771        let database = database.to_string();
2772        Box::pin(async move {
2773            self.driver.ensure_open()?;
2774            match self.driver.inner() {
2775                #[cfg(feature = "band8")]
2776                DriverHandleInner::B8(d) => d.databases().contains(database).await.map_err(|e| {
2777                    RuntimeError::Connection(redact_provider_error(&e, "Database lookup failed"))
2778                }),
2779                #[cfg(feature = "band9")]
2780                DriverHandleInner::B9(d) => d.databases().contains(database).await.map_err(|e| {
2781                    RuntimeError::Connection(redact_provider_error(&e, "Database lookup failed"))
2782                }),
2783            }
2784        })
2785    }
2786
2787    /// Create a database.
2788    pub fn create_database(&self, database: &str) -> BoxFuture<'_, Result<()>> {
2789        let database = database.to_string();
2790        Box::pin(async move {
2791            self.driver.ensure_open()?;
2792            match self.driver.inner() {
2793                #[cfg(feature = "band8")]
2794                DriverHandleInner::B8(d) => d.databases().create(database).await.map_err(|e| {
2795                    RuntimeError::Connection(redact_provider_error(&e, "Database create failed"))
2796                }),
2797                #[cfg(feature = "band9")]
2798                DriverHandleInner::B9(d) => d.databases().create(database).await.map_err(|e| {
2799                    RuntimeError::Connection(redact_provider_error(&e, "Database create failed"))
2800                }),
2801            }
2802        })
2803    }
2804
2805    /// Delete a database.
2806    pub fn delete_database(&self, database: &str) -> BoxFuture<'_, Result<()>> {
2807        let database = database.to_string();
2808        Box::pin(async move {
2809            self.driver.ensure_open()?;
2810            match self.driver.inner() {
2811                #[cfg(feature = "band8")]
2812                DriverHandleInner::B8(d) => {
2813                    let db = d.databases().get(database).await.map_err(|e| {
2814                        RuntimeError::Connection(redact_provider_error(
2815                            &e,
2816                            "Database lookup failed",
2817                        ))
2818                    })?;
2819                    db.delete().await.map_err(|e| {
2820                        RuntimeError::Connection(redact_provider_error(
2821                            &e,
2822                            "Database delete failed",
2823                        ))
2824                    })
2825                }
2826                #[cfg(feature = "band9")]
2827                DriverHandleInner::B9(d) => {
2828                    let db = d.databases().get(database).await.map_err(|e| {
2829                        RuntimeError::Connection(redact_provider_error(
2830                            &e,
2831                            "Database lookup failed",
2832                        ))
2833                    })?;
2834                    db.delete().await.map_err(|e| {
2835                        RuntimeError::Connection(redact_provider_error(
2836                            &e,
2837                            "Database delete failed",
2838                        ))
2839                    })
2840                }
2841            }
2842        })
2843    }
2844
2845    /// Export a database schema as TypeQL text.
2846    pub fn schema_text(&self, database: &str) -> BoxFuture<'_, Result<String>> {
2847        let database = database.to_string();
2848        Box::pin(async move {
2849            self.driver.ensure_open()?;
2850            match self.driver.inner() {
2851                #[cfg(feature = "band8")]
2852                DriverHandleInner::B8(d) => {
2853                    let db = d.databases().get(&database).await.map_err(|e| {
2854                        RuntimeError::Connection(redact_provider_error(
2855                            &e,
2856                            "Database lookup failed",
2857                        ))
2858                    })?;
2859                    db.schema().await.map_err(|e| {
2860                        RuntimeError::Connection(redact_provider_error(&e, "Schema export failed"))
2861                    })
2862                }
2863                #[cfg(feature = "band9")]
2864                DriverHandleInner::B9(d) => {
2865                    let db = d.databases().get(&database).await.map_err(|e| {
2866                        RuntimeError::Connection(redact_provider_error(
2867                            &e,
2868                            "Database lookup failed",
2869                        ))
2870                    })?;
2871                    db.schema().await.map_err(|e| {
2872                        RuntimeError::Connection(redact_provider_error(&e, "Schema export failed"))
2873                    })
2874                }
2875            }
2876        })
2877    }
2878}
2879
2880/// Band-tagged transaction inner state.
2881///
2882/// The `Option` wrapper lets commit/close take ownership by value
2883/// (`.take()`) while the outer `&mut RuntimeTransaction` satisfies the trait's
2884/// `&mut self`.  A `None` after `.take()` marks the transaction as consumed.
2885enum RuntimeTransactionInner {
2886    #[cfg(feature = "band8")]
2887    B8(Option<type_bridge_typedb_driver_b8::Transaction>),
2888    #[cfg(feature = "band9")]
2889    B9(Option<typedb_driver::Transaction>),
2890}
2891
2892/// Open TypeDB transaction owned by the shared runtime.
2893pub struct RuntimeTransaction {
2894    inner: RuntimeTransactionInner,
2895    // Keep the selected driver alive until this transaction is released. Test
2896    // doubles use `None` because they contain no live upstream transaction.
2897    driver_lease: Option<Arc<DriverHandle>>,
2898}
2899
2900impl Drop for RuntimeTransaction {
2901    fn drop(&mut self) {
2902        if let Some(driver) = &self.driver_lease {
2903            let previous = driver
2904                .active_transactions
2905                .fetch_sub(1, AtomicOrdering::AcqRel);
2906            debug_assert!(previous != 0, "runtime transaction lease count underflow");
2907        }
2908    }
2909}
2910
2911fn runtime_cancelled_error() -> RuntimeError {
2912    RuntimeError::ResourceLimit {
2913        code: "provider_cancelled",
2914        message: "provider answer processing was cancelled",
2915    }
2916}
2917
2918fn runtime_deadline_error() -> RuntimeError {
2919    RuntimeError::ResourceLimit {
2920        code: "transaction_deadline_exceeded",
2921        message: "provider transaction deadline expired",
2922    }
2923}
2924
2925fn runtime_check(limits: &RuntimeAnswerLimits) -> Result<()> {
2926    if limits.cancellation.is_cancelled() {
2927        return Err(runtime_cancelled_error());
2928    }
2929    if limits.deadline.is_some_and(|deadline| {
2930        tokio::time::Instant::now() >= tokio::time::Instant::from_std(deadline)
2931    }) {
2932        return Err(runtime_deadline_error());
2933    }
2934    Ok(())
2935}
2936
2937async fn runtime_await<T>(
2938    future: impl Future<Output = Result<T>>,
2939    limits: &RuntimeAnswerLimits,
2940) -> Result<T> {
2941    runtime_check(limits)?;
2942    tokio::pin!(future);
2943    let cancellation = limits.cancellation.cancelled();
2944    tokio::pin!(cancellation);
2945
2946    if let Some(deadline) = limits.deadline {
2947        let deadline = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
2948        tokio::pin!(deadline);
2949        tokio::select! {
2950            biased;
2951            result = &mut future => result,
2952            () = &mut cancellation => Err(runtime_cancelled_error()),
2953            () = &mut deadline => Err(runtime_deadline_error()),
2954        }
2955    } else {
2956        tokio::select! {
2957            biased;
2958            result = &mut future => result,
2959            () = &mut cancellation => Err(runtime_cancelled_error()),
2960        }
2961    }
2962}
2963
2964fn runtime_accept(
2965    limits: &RuntimeAnswerLimits,
2966    stats: &mut RuntimeAnswerStats,
2967    item: RuntimeAnswerItem,
2968    consumer: &mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
2969) -> Result<RuntimeAnswerControl> {
2970    runtime_check(limits)?;
2971    let next_items = stats
2972        .processed_items
2973        .checked_add(1)
2974        .ok_or(RuntimeError::ResourceLimit {
2975            code: "processed_item_counter_overflow",
2976            message: "processed provider item counter overflowed",
2977        })?;
2978    if next_items > limits.max_items {
2979        return Err(RuntimeError::ResourceLimit {
2980            code: "processed_item_limit",
2981            message: "provider answer exceeded the processed-item ceiling",
2982        });
2983    }
2984    let value = match &item {
2985        RuntimeAnswerItem::Row(value) | RuntimeAnswerItem::Document(value) => value,
2986    };
2987    let encoded = u64::try_from(
2988        serde_json::to_vec(value)
2989            .map_err(|error| RuntimeError::QueryExecution(format!("Answer encode: {error}")))?
2990            .len(),
2991    )
2992    .map_err(|_| RuntimeError::ResourceLimit {
2993        code: "answer_byte_counter_overflow",
2994        message: "encoded provider answer length exceeds the counter range",
2995    })?;
2996    let next_bytes =
2997        stats
2998            .response_bytes
2999            .checked_add(encoded)
3000            .ok_or(RuntimeError::ResourceLimit {
3001                code: "answer_byte_counter_overflow",
3002                message: "provider answer byte counter overflowed",
3003            })?;
3004    if next_bytes > limits.max_bytes {
3005        return Err(RuntimeError::ResourceLimit {
3006            code: "response_byte_limit",
3007            message: "provider answer exceeded the response-byte ceiling",
3008        });
3009    }
3010    stats.processed_items = next_items;
3011    stats.response_bytes = next_bytes;
3012    let control = consumer(item);
3013    runtime_check(limits)?;
3014    let control = control?;
3015    if control == RuntimeAnswerControl::Stop {
3016        stats.stopped_early = true;
3017    }
3018    Ok(control)
3019}
3020
3021#[cfg(any(feature = "band9", test))]
3022async fn runtime_consume_stream<S>(
3023    mut stream: S,
3024    kind: RuntimeAnswerKind,
3025    limits: &RuntimeAnswerLimits,
3026    consumer: &mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3027) -> Result<RuntimeAnswerStats>
3028where
3029    S: futures::TryStream<Ok = RuntimeAnswerItem, Error = RuntimeError> + Send + Unpin,
3030{
3031    let mut stats = RuntimeAnswerStats::new(kind);
3032    while let Some(item) = runtime_await(async { stream.try_next().await }, limits).await? {
3033        if runtime_accept(limits, &mut stats, item, consumer)? == RuntimeAnswerControl::Stop {
3034            break;
3035        }
3036    }
3037    Ok(stats)
3038}
3039
3040fn materialize_runtime_answer(
3041    stats: RuntimeAnswerStats,
3042    items: Vec<RuntimeAnswerItem>,
3043) -> QueryResult {
3044    match stats.kind {
3045        RuntimeAnswerKind::Ok => QueryResult::Ok,
3046        RuntimeAnswerKind::Rows => QueryResult::Rows(
3047            items
3048                .into_iter()
3049                .filter_map(|item| match item {
3050                    RuntimeAnswerItem::Row(value) => Some(value),
3051                    RuntimeAnswerItem::Document(_) => None,
3052                })
3053                .collect(),
3054        ),
3055        RuntimeAnswerKind::Documents => QueryResult::Documents(
3056            items
3057                .into_iter()
3058                .filter_map(|item| match item {
3059                    RuntimeAnswerItem::Document(value) => Some(value),
3060                    RuntimeAnswerItem::Row(_) => None,
3061                })
3062                .collect(),
3063        ),
3064    }
3065}
3066
3067impl RuntimeTransaction {
3068    fn ensure_driver_open(&self) -> Result<()> {
3069        match &self.driver_lease {
3070            Some(driver) => driver.ensure_open(),
3071            None => Ok(()),
3072        }
3073    }
3074
3075    fn driver_shutdown_started(driver_lease: &Option<Arc<DriverHandle>>) -> bool {
3076        driver_lease
3077            .as_ref()
3078            .is_some_and(|driver| driver.shutdown_started())
3079    }
3080
3081    /// Return whether this transaction's negotiated driver can transport
3082    /// `given` input rows.
3083    pub fn supports_given_rows(&self) -> bool {
3084        match &self.inner {
3085            #[cfg(feature = "band8")]
3086            RuntimeTransactionInner::B8(_) => false,
3087            #[cfg(feature = "band9")]
3088            RuntimeTransactionInner::B9(_) => true,
3089        }
3090    }
3091
3092    /// Execute TypeQL within this transaction, materializing for legacy callers.
3093    ///
3094    /// New match executors use [`Self::query_bounded`] directly.
3095    pub fn query(&mut self, typeql: &str) -> BoxFuture<'_, Result<QueryResult>> {
3096        let typeql = typeql.to_owned();
3097        Box::pin(async move {
3098            let mut items = Vec::new();
3099            let mut collect = |item| {
3100                items.push(item);
3101                Ok(RuntimeAnswerControl::Continue)
3102            };
3103            let stats = self
3104                .query_bounded(&typeql, RuntimeAnswerLimits::unbounded(), &mut collect)
3105                .await?;
3106            Ok(materialize_runtime_answer(stats, items))
3107        })
3108    }
3109
3110    /// Execute TypeQL and enforce bounds while polling the driver stream.
3111    pub fn query_bounded<'a>(
3112        &'a mut self,
3113        typeql: &'a str,
3114        limits: RuntimeAnswerLimits,
3115        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3116    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3117        self.query_bounded_with_scalar_encoding(
3118            typeql,
3119            QueryV2RuntimeAnswerLimits {
3120                answer: limits,
3121                max_collection_members: u64::MAX,
3122            },
3123            ScalarJsonEncoding::DriverDisplay,
3124            consumer,
3125        )
3126    }
3127
3128    /// Execute V2 TypeQL with an additive document collection-member limit.
3129    pub fn query_v2_bounded<'a>(
3130        &'a mut self,
3131        typeql: &'a str,
3132        limits: QueryV2RuntimeAnswerLimits,
3133        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3134    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3135        self.query_bounded_with_scalar_encoding(
3136            typeql,
3137            limits,
3138            ScalarJsonEncoding::CanonicalV2,
3139            consumer,
3140        )
3141    }
3142
3143    /// Execute V2 with canonical scalar spelling and retain the answer kind.
3144    #[doc(hidden)]
3145    pub async fn query_v2_materialized(
3146        &mut self,
3147        typeql: &str,
3148        limits: QueryV2RuntimeAnswerLimits,
3149    ) -> Result<QueryResult> {
3150        let mut items = Vec::new();
3151        let mut consumer = |item: RuntimeAnswerItem| {
3152            items.push(item);
3153            Ok(RuntimeAnswerControl::Continue)
3154        };
3155        let stats = self.query_v2_bounded(typeql, limits, &mut consumer).await?;
3156        Ok(materialize_runtime_answer(stats, items))
3157    }
3158
3159    /// Materialize a bounded legacy or canonical answer, preserving empty kinds.
3160    #[doc(hidden)]
3161    pub async fn query_materialized_bounded(
3162        &mut self,
3163        typeql: &str,
3164        rows: Option<GivenRowsSpec>,
3165        limits: RuntimeAnswerLimits,
3166        canonical: bool,
3167    ) -> Result<QueryResult> {
3168        let mut items = Vec::new();
3169        let mut consumer = |item| {
3170            items.push(item);
3171            Ok(RuntimeAnswerControl::Continue)
3172        };
3173        let stats = match (rows, canonical) {
3174            (None, false) => self.query_bounded(typeql, limits, &mut consumer).await?,
3175            (Some(rows), false) => {
3176                self.query_with_rows_bounded(typeql, rows, limits, &mut consumer)
3177                    .await?
3178            }
3179            (None, true) => {
3180                self.query_v2_bounded(
3181                    typeql,
3182                    QueryV2RuntimeAnswerLimits {
3183                        answer: limits,
3184                        max_collection_members: u64::MAX,
3185                    },
3186                    &mut consumer,
3187                )
3188                .await?
3189            }
3190            (Some(rows), true) => {
3191                self.query_v2_with_rows_bounded(
3192                    typeql,
3193                    rows,
3194                    QueryV2RuntimeAnswerLimits {
3195                        answer: limits,
3196                        max_collection_members: u64::MAX,
3197                    },
3198                    &mut consumer,
3199                )
3200                .await?
3201            }
3202        };
3203        Ok(materialize_runtime_answer(stats, items))
3204    }
3205
3206    fn query_bounded_with_scalar_encoding<'a>(
3207        &'a mut self,
3208        typeql: &'a str,
3209        limits: QueryV2RuntimeAnswerLimits,
3210        scalar_encoding: ScalarJsonEncoding,
3211        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3212    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3213        let QueryV2RuntimeAnswerLimits {
3214            answer: limits,
3215            max_collection_members,
3216        } = limits;
3217        let tql = typeql.to_string();
3218        let work = async move {
3219            self.ensure_driver_open()?;
3220            runtime_check(&limits)?;
3221            match &self.inner {
3222                #[cfg(feature = "band8")]
3223                RuntimeTransactionInner::B8(opt) => {
3224                    let tx = opt.as_ref().ok_or_else(|| {
3225                        RuntimeError::Transaction("Transaction already consumed".into())
3226                    })?;
3227                    let answer = runtime_await(
3228                        async {
3229                            let options = if limits.is_unbounded() {
3230                                driver_b8::QueryOptions::new()
3231                            } else {
3232                                driver_b8::QueryOptions::new()
3233                                    .prefetch_size(BOUNDED_QUERY_PREFETCH_SIZE)
3234                            };
3235                            tx.query_with_options(&tql, options)
3236                                .await
3237                                .map_err(band8_query_error)
3238                        },
3239                        &limits,
3240                    )
3241                    .await?;
3242                    match answer {
3243                        B8QueryAnswer::Ok(_) => Ok(RuntimeAnswerStats::new(RuntimeAnswerKind::Ok)),
3244                        B8QueryAnswer::ConceptRowStream(_, mut stream) => {
3245                            let mut stats = RuntimeAnswerStats::new(RuntimeAnswerKind::Rows);
3246                            while let Some(row) = runtime_await(
3247                                async {
3248                                    stream.try_next().await.map_err(|error| {
3249                                        band8_query_error_with_operation(error, "Row stream failed")
3250                                    })
3251                                },
3252                                &limits,
3253                            )
3254                            .await?
3255                            {
3256                                let decode = decode_span().entered();
3257                                let mut object = serde_json::Map::new();
3258                                for (index, column) in row.get_column_names().iter().enumerate() {
3259                                    let value = row
3260                                        .row
3261                                        .get(index)
3262                                        .and_then(|concept| concept.as_ref())
3263                                        .map(|concept| concept_to_json_b8(concept, scalar_encoding))
3264                                        .transpose()?
3265                                        .unwrap_or(serde_json::Value::Null);
3266                                    object.insert(column.clone(), value);
3267                                }
3268                                drop(decode);
3269                                if runtime_accept(
3270                                    &limits,
3271                                    &mut stats,
3272                                    RuntimeAnswerItem::Row(serde_json::Value::Object(object)),
3273                                    consumer,
3274                                )? == RuntimeAnswerControl::Stop
3275                                {
3276                                    break;
3277                                }
3278                            }
3279                            Ok(stats)
3280                        }
3281                        B8QueryAnswer::ConceptDocumentStream(_, mut stream) => {
3282                            let mut stats = RuntimeAnswerStats::new(RuntimeAnswerKind::Documents);
3283                            let mut collection_members = 0_u64;
3284                            while let Some(document) = runtime_await(
3285                                async {
3286                                    stream.try_next().await.map_err(|error| {
3287                                        band8_query_error_with_operation(
3288                                            error,
3289                                            "Document stream failed",
3290                                        )
3291                                    })
3292                                },
3293                                &limits,
3294                            )
3295                            .await?
3296                            {
3297                                let decode = decode_span().entered();
3298                                let value = document_to_json_b8(
3299                                    &document,
3300                                    &mut collection_members,
3301                                    max_collection_members,
3302                                    scalar_encoding,
3303                                );
3304                                drop(decode);
3305                                let value = value?;
3306                                if runtime_accept(
3307                                    &limits,
3308                                    &mut stats,
3309                                    RuntimeAnswerItem::Document(value),
3310                                    consumer,
3311                                )? == RuntimeAnswerControl::Stop
3312                                {
3313                                    break;
3314                                }
3315                            }
3316                            Ok(stats)
3317                        }
3318                    }
3319                }
3320                #[cfg(feature = "band9")]
3321                RuntimeTransactionInner::B9(opt) => {
3322                    let tx = opt.as_ref().ok_or_else(|| {
3323                        RuntimeError::Transaction("Transaction already consumed".into())
3324                    })?;
3325                    let answer = runtime_await(
3326                        async {
3327                            let options = if limits.is_unbounded() {
3328                                driver_b9::QueryOptions::new()
3329                            } else {
3330                                driver_b9::QueryOptions::new()
3331                                    .prefetch_size(BOUNDED_QUERY_PREFETCH_SIZE)
3332                            };
3333                            tx.query_with_options(&tql, options)
3334                                .await
3335                                .map_err(band9_query_error)
3336                        },
3337                        &limits,
3338                    )
3339                    .await?;
3340                    consume_answer_b9(
3341                        answer,
3342                        &limits,
3343                        max_collection_members,
3344                        scalar_encoding,
3345                        consumer,
3346                    )
3347                    .await
3348                }
3349            }
3350        };
3351        Box::pin(work.instrument(execute_span()))
3352    }
3353
3354    /// Execute TypeQL with `given`-stage input rows within this transaction.
3355    ///
3356    /// Rows travel through the driver API, not the query string, so this
3357    /// path is only available on the band-9 (TypeDB 3.12+) driver. On a
3358    /// band-8 connection this returns an actionable error —
3359    /// callers that can fall back to per-row queries should consult the
3360    /// detected server version before choosing this path.
3361    pub fn query_with_rows(
3362        &mut self,
3363        typeql: &str,
3364        rows: GivenRowsSpec,
3365    ) -> BoxFuture<'_, Result<QueryResult>> {
3366        let typeql = typeql.to_owned();
3367        Box::pin(async move {
3368            let mut items = Vec::new();
3369            let mut collect = |item| {
3370                items.push(item);
3371                Ok(RuntimeAnswerControl::Continue)
3372            };
3373            let stats = self
3374                .query_with_rows_bounded(
3375                    &typeql,
3376                    rows,
3377                    RuntimeAnswerLimits::unbounded(),
3378                    &mut collect,
3379                )
3380                .await?;
3381            Ok(materialize_runtime_answer(stats, items))
3382        })
3383    }
3384
3385    /// Execute TypeQL with `given` rows and enforce bounds while polling the
3386    /// driver answer stream.
3387    pub fn query_with_rows_bounded<'a>(
3388        &'a mut self,
3389        typeql: &'a str,
3390        rows: GivenRowsSpec,
3391        limits: RuntimeAnswerLimits,
3392        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3393    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3394        self.query_with_rows_bounded_with_scalar_encoding(
3395            typeql,
3396            rows,
3397            QueryV2RuntimeAnswerLimits {
3398                answer: limits,
3399                max_collection_members: u64::MAX,
3400            },
3401            ScalarJsonEncoding::DriverDisplay,
3402            consumer,
3403        )
3404    }
3405
3406    /// Execute a V2 `given` query with an additive collection-member limit.
3407    pub fn query_v2_with_rows_bounded<'a>(
3408        &'a mut self,
3409        typeql: &'a str,
3410        rows: GivenRowsSpec,
3411        limits: QueryV2RuntimeAnswerLimits,
3412        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3413    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3414        self.query_with_rows_bounded_with_scalar_encoding(
3415            typeql,
3416            rows,
3417            limits,
3418            ScalarJsonEncoding::CanonicalV2,
3419            consumer,
3420        )
3421    }
3422
3423    fn query_with_rows_bounded_with_scalar_encoding<'a>(
3424        &'a mut self,
3425        typeql: &'a str,
3426        rows: GivenRowsSpec,
3427        limits: QueryV2RuntimeAnswerLimits,
3428        scalar_encoding: ScalarJsonEncoding,
3429        consumer: &'a mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
3430    ) -> BoxFuture<'a, Result<RuntimeAnswerStats>> {
3431        let QueryV2RuntimeAnswerLimits {
3432            answer: limits,
3433            max_collection_members,
3434        } = limits;
3435        let tql = typeql.to_owned();
3436        #[cfg(not(feature = "band9"))]
3437        let _ = (
3438            &tql,
3439            &rows,
3440            max_collection_members,
3441            scalar_encoding,
3442            &consumer,
3443        );
3444        let work = async move {
3445            self.ensure_driver_open()?;
3446            runtime_check(&limits)?;
3447            match &self.inner {
3448                #[cfg(feature = "band8")]
3449                RuntimeTransactionInner::B8(_) => Err(RuntimeError::QueryExecution(
3450                    "given-stage parameterized queries require the band-9 driver \
3451                     (TypeDB 3.12+); this connection negotiated band 8"
3452                        .into(),
3453                )),
3454                #[cfg(feature = "band9")]
3455                RuntimeTransactionInner::B9(opt) => {
3456                    let tx = opt.as_ref().ok_or_else(|| {
3457                        RuntimeError::Transaction("Transaction already consumed".into())
3458                    })?;
3459                    let given_rows = given_rows_b9(rows)?;
3460                    let answer = runtime_await(
3461                        async {
3462                            let options = if limits.is_unbounded() {
3463                                driver_b9::QueryOptions::new()
3464                            } else {
3465                                driver_b9::QueryOptions::new()
3466                                    .prefetch_size(BOUNDED_QUERY_PREFETCH_SIZE)
3467                            };
3468                            tx.query_with_options_and_rows(&tql, options, Some(given_rows))
3469                                .await
3470                                .map_err(band9_query_error)
3471                        },
3472                        &limits,
3473                    )
3474                    .await?;
3475                    consume_answer_b9(
3476                        answer,
3477                        &limits,
3478                        max_collection_members,
3479                        scalar_encoding,
3480                        consumer,
3481                    )
3482                    .await
3483                }
3484            }
3485        };
3486        Box::pin(work.instrument(execute_span()))
3487    }
3488
3489    /// Commit this transaction.
3490    pub fn commit(&mut self) -> BoxFuture<'_, Result<()>> {
3491        let commit = self.commit_classified();
3492        Box::pin(async move { commit.await.map_err(RuntimeCommitError::into_runtime_error) })
3493    }
3494
3495    /// Commit this transaction while retaining driver durability certainty.
3496    pub fn commit_classified(
3497        &mut self,
3498    ) -> BoxFuture<'_, std::result::Result<(), RuntimeCommitError>> {
3499        // Take ownership out of the Option so the async block can move the
3500        // transaction by value into commit(self) — both bands consume self.
3501        let driver_lease = self.driver_lease.clone();
3502        match &mut self.inner {
3503            #[cfg(feature = "band8")]
3504            RuntimeTransactionInner::B8(opt) => {
3505                let tx = opt.take();
3506                let work = async move {
3507                    if let Some(driver) = &driver_lease {
3508                        driver.ensure_open().map_err(RuntimeCommitError::Runtime)?;
3509                    }
3510                    let t = tx.ok_or_else(|| {
3511                        RuntimeCommitError::Runtime(RuntimeError::Transaction(
3512                            "Transaction already consumed".into(),
3513                        ))
3514                    })?;
3515                    t.commit().await.map_err(band8_commit_failure)
3516                };
3517                Box::pin(work.instrument(commit_span()))
3518            }
3519            #[cfg(feature = "band9")]
3520            RuntimeTransactionInner::B9(opt) => {
3521                let tx = opt.take();
3522                let work = async move {
3523                    if let Some(driver) = &driver_lease {
3524                        driver.ensure_open().map_err(RuntimeCommitError::Runtime)?;
3525                    }
3526                    let t = tx.ok_or_else(|| {
3527                        RuntimeCommitError::Runtime(RuntimeError::Transaction(
3528                            "Transaction already consumed".into(),
3529                        ))
3530                    })?;
3531                    t.commit().await.map_err(band9_commit_failure)
3532                };
3533                Box::pin(work.instrument(commit_span()))
3534            }
3535        }
3536    }
3537
3538    /// Roll back pending changes, keeping this transaction open for further work.
3539    pub fn rollback(&mut self) -> BoxFuture<'_, Result<()>> {
3540        let driver_lease = self.driver_lease.clone();
3541        match &mut self.inner {
3542            #[cfg(feature = "band8")]
3543            RuntimeTransactionInner::B8(opt) => {
3544                let tx = opt.as_ref();
3545                let work = async move {
3546                    if let Some(driver) = &driver_lease {
3547                        driver.ensure_open()?;
3548                    }
3549                    let t = tx.ok_or_else(|| {
3550                        RuntimeError::Transaction("Transaction already consumed".into())
3551                    })?;
3552                    if !t.is_open() {
3553                        return Ok(());
3554                    }
3555                    t.rollback().await.map_err(|e| {
3556                        RuntimeError::Transaction(redact_provider_error(&e, "Rollback failed"))
3557                    })
3558                };
3559                Box::pin(work.instrument(execute_span()))
3560            }
3561            #[cfg(feature = "band9")]
3562            RuntimeTransactionInner::B9(opt) => {
3563                let tx = opt.as_ref();
3564                let work = async move {
3565                    if let Some(driver) = &driver_lease {
3566                        driver.ensure_open()?;
3567                    }
3568                    let t = tx.ok_or_else(|| {
3569                        RuntimeError::Transaction("Transaction already consumed".into())
3570                    })?;
3571                    if !t.is_open() {
3572                        return Ok(());
3573                    }
3574                    t.rollback().await.map_err(|e| {
3575                        RuntimeError::Transaction(redact_provider_error(&e, "Rollback failed"))
3576                    })
3577                };
3578                Box::pin(work.instrument(execute_span()))
3579            }
3580        }
3581    }
3582
3583    /// Close this transaction without committing.
3584    pub fn close(&mut self) -> BoxFuture<'_, Result<()>> {
3585        let driver_lease = self.driver_lease.clone();
3586        match &mut self.inner {
3587            #[cfg(feature = "band8")]
3588            RuntimeTransactionInner::B8(opt) => {
3589                let tx = opt.take();
3590                let work = async move {
3591                    let Some(t) = tx else {
3592                        return Ok(());
3593                    };
3594                    if Self::driver_shutdown_started(&driver_lease) {
3595                        drop(t);
3596                        return Ok(());
3597                    }
3598                    t.close().await.map_err(|e| {
3599                        RuntimeError::Transaction(redact_provider_error(&e, "Close failed"))
3600                    })
3601                };
3602                Box::pin(work.instrument(execute_span()))
3603            }
3604            #[cfg(feature = "band9")]
3605            RuntimeTransactionInner::B9(opt) => {
3606                let tx = opt.take();
3607                let work = async move {
3608                    let Some(t) = tx else {
3609                        return Ok(());
3610                    };
3611                    if Self::driver_shutdown_started(&driver_lease) {
3612                        drop(t);
3613                        return Ok(());
3614                    }
3615                    t.close().await.map_err(|e| {
3616                        RuntimeError::Transaction(redact_provider_error(&e, "Close failed"))
3617                    })
3618                };
3619                Box::pin(work.instrument(execute_span()))
3620            }
3621        }
3622    }
3623}
3624
3625fn document_type_to_json(kind: &str, label: &str) -> serde_json::Value {
3626    serde_json::Value::Object(serde_json::Map::from_iter([
3627        (
3628            "kind".to_owned(),
3629            serde_json::Value::String(kind.to_owned()),
3630        ),
3631        (
3632            "label".to_owned(),
3633            serde_json::Value::String(label.to_owned()),
3634        ),
3635    ]))
3636}
3637
3638fn document_attribute_type_to_json(label: &str, value_type: Option<&str>) -> serde_json::Value {
3639    serde_json::Value::Object(serde_json::Map::from_iter([
3640        (
3641            "kind".to_owned(),
3642            serde_json::Value::String("attribute".to_owned()),
3643        ),
3644        (
3645            "label".to_owned(),
3646            serde_json::Value::String(label.to_owned()),
3647        ),
3648        (
3649            "valueType".to_owned(),
3650            serde_json::Value::String(value_type.unwrap_or("none").to_owned()),
3651        ),
3652    ]))
3653}
3654
3655fn runtime_document_member_error(message: &'static str) -> RuntimeError {
3656    RuntimeError::ResourceLimit {
3657        code: "query_v2_document_member_limit",
3658        message,
3659    }
3660}
3661
3662#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3663enum ScalarJsonEncoding {
3664    DriverDisplay,
3665    CanonicalV2,
3666}
3667
3668fn canonical_decimal_text(display: String) -> Result<String> {
3669    type_bridge_core_lib::decimal::parse_decimal(&display)
3670        .map(|decimal| decimal.canonical_string())
3671        .ok_or_else(|| {
3672            RuntimeError::QueryExecution("provider returned an unparseable decimal".to_owned())
3673        })
3674}
3675
3676fn checked_datetime_tz_local<Tz>(
3677    value: &chrono::DateTime<Tz>,
3678) -> Result<(chrono::NaiveDateTime, i32)>
3679where
3680    Tz: chrono::TimeZone,
3681    Tz::Offset: chrono::Offset,
3682{
3683    use chrono::Offset as _;
3684
3685    let offset_seconds = value.offset().fix().local_minus_utc();
3686    let local = value
3687        .naive_utc()
3688        .checked_add_signed(chrono::TimeDelta::seconds(i64::from(offset_seconds)))
3689        .ok_or_else(|| {
3690            RuntimeError::QueryExecution(
3691                "provider datetime-tz local value is outside the supported range".to_owned(),
3692            )
3693        })?;
3694    Ok((local, offset_seconds))
3695}
3696
3697fn append_exact_offset(rendered: &mut String, offset_seconds: i64) {
3698    use std::fmt::Write as _;
3699
3700    if offset_seconds == 0 {
3701        rendered.push('Z');
3702        return;
3703    }
3704    let sign = if offset_seconds < 0 { '-' } else { '+' };
3705    let absolute = offset_seconds.unsigned_abs();
3706    let hours = absolute / 3_600;
3707    let minutes = (absolute % 3_600) / 60;
3708    let seconds = absolute % 60;
3709    write!(rendered, "{sign}{hours:02}:{minutes:02}")
3710        .expect("writing an offset to String cannot fail");
3711    if seconds != 0 {
3712        write!(rendered, ":{seconds:02}").expect("writing an offset to String cannot fail");
3713    }
3714}
3715
3716fn exact_naive_datetime(value: &chrono::NaiveDateTime) -> String {
3717    use std::fmt::Write as _;
3718
3719    use chrono::{Datelike as _, Timelike as _};
3720
3721    let mut rendered = String::new();
3722    let year = value.year();
3723    match year {
3724        0..=9999 => write!(rendered, "{year:04}"),
3725        10_000.. => write!(rendered, "+{year}"),
3726        -9999..=-1 => write!(rendered, "-{:04}", -year),
3727        _ => write!(rendered, "{year}"),
3728    }
3729    .expect("writing a year to String cannot fail");
3730    write!(
3731        rendered,
3732        "-{:02}-{:02}T{:02}:{:02}:{:02}",
3733        value.month(),
3734        value.day(),
3735        value.hour(),
3736        value.minute(),
3737        value.second(),
3738    )
3739    .expect("writing datetime components to String cannot fail");
3740    let nanosecond = value.nanosecond();
3741    if nanosecond != 0 {
3742        let fraction = format!("{nanosecond:09}");
3743        write!(rendered, ".{}", fraction.trim_end_matches('0'))
3744            .expect("writing a datetime fraction to String cannot fail");
3745    }
3746    rendered
3747}
3748
3749fn exact_duration(months: u32, days: u32, nanos: u64) -> String {
3750    use std::fmt::Write as _;
3751
3752    let seconds = nanos / 1_000_000_000;
3753    let nanosecond = nanos % 1_000_000_000;
3754    let mut rendered = String::from("P");
3755    if months != 0 {
3756        write!(rendered, "{months}M").expect("writing duration months to String cannot fail");
3757    }
3758    if days != 0 {
3759        write!(rendered, "{days}D").expect("writing duration days to String cannot fail");
3760    }
3761    if seconds != 0 || nanosecond != 0 || (months == 0 && days == 0) {
3762        write!(rendered, "T{seconds}").expect("writing duration seconds to String cannot fail");
3763        if nanosecond != 0 {
3764            let fraction = format!("{nanosecond:09}");
3765            write!(rendered, ".{}", fraction.trim_end_matches('0'))
3766                .expect("writing a duration fraction to String cannot fail");
3767        }
3768        rendered.push('S');
3769    }
3770    rendered
3771}
3772
3773macro_rules! define_driver_json_conversion {
3774    (
3775        $feature:literal,
3776        $driver:ident,
3777        $document_fn:ident,
3778        $node_fn:ident,
3779        $leaf_fn:ident,
3780        $value_fn:ident
3781    ) => {
3782        #[cfg(feature = $feature)]
3783        fn $document_fn(
3784            document: &$driver::answer::ConceptDocument,
3785            collection_members: &mut u64,
3786            max_collection_members: u64,
3787            scalar_encoding: ScalarJsonEncoding,
3788        ) -> Result<serde_json::Value> {
3789            document
3790                .root
3791                .as_ref()
3792                .map(|node| {
3793                    $node_fn(
3794                        node,
3795                        collection_members,
3796                        max_collection_members,
3797                        scalar_encoding,
3798                    )
3799                })
3800                .transpose()
3801                .map(|value| value.unwrap_or(serde_json::Value::Null))
3802        }
3803
3804        #[cfg(feature = $feature)]
3805        fn $node_fn(
3806            node: &$driver::answer::concept_document::Node,
3807            collection_members: &mut u64,
3808            max_collection_members: u64,
3809            scalar_encoding: ScalarJsonEncoding,
3810        ) -> Result<serde_json::Value> {
3811            use $driver::answer::concept_document::Node;
3812
3813            match node {
3814                Node::Map(map) => map
3815                    .iter()
3816                    .map(|(name, node)| {
3817                        $node_fn(
3818                            node,
3819                            collection_members,
3820                            max_collection_members,
3821                            scalar_encoding,
3822                        )
3823                        .map(|value| (name.clone(), value))
3824                    })
3825                    .collect::<Result<serde_json::Map<String, serde_json::Value>>>()
3826                    .map(serde_json::Value::Object),
3827                Node::List(list) => {
3828                    let members = u64::try_from(list.len()).map_err(|_| {
3829                        runtime_document_member_error(
3830                            "document list member count exceeds the supported counter range",
3831                        )
3832                    })?;
3833                    let next = collection_members.checked_add(members).ok_or_else(|| {
3834                        runtime_document_member_error("document list member counter overflowed")
3835                    })?;
3836                    if next > max_collection_members {
3837                        return Err(runtime_document_member_error(
3838                            "document lists exceed the aggregate member ceiling",
3839                        ));
3840                    }
3841                    *collection_members = next;
3842                    list.iter()
3843                        .map(|node| {
3844                            $node_fn(
3845                                node,
3846                                collection_members,
3847                                max_collection_members,
3848                                scalar_encoding,
3849                            )
3850                        })
3851                        .collect::<Result<Vec<_>>>()
3852                        .map(serde_json::Value::Array)
3853                }
3854                Node::Leaf(Some(leaf)) => $leaf_fn(leaf, scalar_encoding),
3855                Node::Leaf(None) => Ok(serde_json::Value::Null),
3856            }
3857        }
3858
3859        #[cfg(feature = $feature)]
3860        fn $leaf_fn(
3861            leaf: &$driver::answer::concept_document::Leaf,
3862            scalar_encoding: ScalarJsonEncoding,
3863        ) -> Result<serde_json::Value> {
3864            use $driver::answer::concept_document::Leaf;
3865            use $driver::concept::Concept;
3866
3867            match leaf {
3868                Leaf::Empty => Ok(serde_json::Value::Null),
3869                Leaf::Concept(concept) => match concept {
3870                    Concept::EntityType(_) => {
3871                        Ok(document_type_to_json("entity", concept.get_label()))
3872                    }
3873                    Concept::RelationType(_) => {
3874                        Ok(document_type_to_json("relation", concept.get_label()))
3875                    }
3876                    Concept::RoleType(_) => {
3877                        Ok(document_type_to_json("relation:role", concept.get_label()))
3878                    }
3879                    Concept::AttributeType(_) => {
3880                        let value_type = concept.try_get_value_type();
3881                        Ok(document_attribute_type_to_json(
3882                            concept.get_label(),
3883                            value_type.as_ref().map(|value_type| value_type.name()),
3884                        ))
3885                    }
3886                    Concept::Attribute(_) | Concept::Value(_) => {
3887                        let value = concept.try_get_value().ok_or_else(|| {
3888                            RuntimeError::QueryExecution(
3889                                "document value concept did not carry a value".to_owned(),
3890                            )
3891                        })?;
3892                        $value_fn(value, scalar_encoding)
3893                    }
3894                    Concept::Entity(_) | Concept::Relation(_) => Err(RuntimeError::QueryExecution(
3895                        "document response carried an unsupported thing instance".to_owned(),
3896                    )),
3897                },
3898                Leaf::ValueType(value_type) => {
3899                    Ok(serde_json::Value::String(value_type.name().to_owned()))
3900                }
3901                Leaf::Kind(kind) => Ok(serde_json::Value::String(kind.name().to_owned())),
3902            }
3903        }
3904
3905        #[cfg(feature = $feature)]
3906        fn $value_fn(
3907            value: &$driver::concept::Value,
3908            scalar_encoding: ScalarJsonEncoding,
3909        ) -> Result<serde_json::Value> {
3910            use $driver::concept::Value;
3911
3912            let converted = match value {
3913                Value::Boolean(value) => serde_json::Value::Bool(*value),
3914                Value::Integer(value) => serde_json::Value::from(*value),
3915                Value::Double(value) => serde_json::Value::from(*value),
3916                Value::String(value) => serde_json::Value::String(value.clone()),
3917                Value::Decimal(decimal) => {
3918                    let rendered = match scalar_encoding {
3919                        ScalarJsonEncoding::DriverDisplay => decimal.to_string(),
3920                        ScalarJsonEncoding::CanonicalV2 => {
3921                            canonical_decimal_text(decimal.to_string())?
3922                        }
3923                    };
3924                    serde_json::Value::String(rendered)
3925                }
3926                Value::Date(_) => serde_json::Value::String(value.to_string()),
3927                Value::Datetime(datetime) => {
3928                    let rendered = match scalar_encoding {
3929                        ScalarJsonEncoding::DriverDisplay => value.to_string(),
3930                        ScalarJsonEncoding::CanonicalV2 => exact_naive_datetime(datetime),
3931                    };
3932                    serde_json::Value::String(rendered)
3933                }
3934                Value::Duration(duration) => {
3935                    let rendered = match scalar_encoding {
3936                        ScalarJsonEncoding::DriverDisplay => value.to_string(),
3937                        ScalarJsonEncoding::CanonicalV2 => {
3938                            exact_duration(duration.months, duration.days, duration.nanos)
3939                        }
3940                    };
3941                    serde_json::Value::String(rendered)
3942                }
3943                Value::DatetimeTZ(datetime_tz) => {
3944                    let (local, offset_seconds) = checked_datetime_tz_local(datetime_tz)?;
3945                    let rendered = match scalar_encoding {
3946                        ScalarJsonEncoding::DriverDisplay => value.to_string(),
3947                        ScalarJsonEncoding::CanonicalV2 => {
3948                            let mut rendered = exact_naive_datetime(&local);
3949                            append_exact_offset(&mut rendered, i64::from(offset_seconds));
3950                            if let $driver::concept::value::TimeZone::IANA(timezone) =
3951                                datetime_tz.timezone()
3952                            {
3953                                use std::fmt::Write as _;
3954                                write!(rendered, "[{}]", timezone.name())
3955                                    .expect("writing a timezone name to String cannot fail");
3956                            }
3957                            rendered
3958                        }
3959                    };
3960                    serde_json::Value::String(rendered)
3961                }
3962                Value::Struct(value, name) => {
3963                    let fields = value
3964                        .fields()
3965                        .iter()
3966                        .map(|(field, value)| -> Result<_> {
3967                            Ok((
3968                                field.clone(),
3969                                value
3970                                    .as_ref()
3971                                    .map(|value| $value_fn(value, scalar_encoding))
3972                                    .transpose()?
3973                                    .unwrap_or(serde_json::Value::Null),
3974                            ))
3975                        })
3976                        .collect::<Result<_>>()?;
3977                    serde_json::Value::Object(serde_json::Map::from_iter([(
3978                        name.clone(),
3979                        serde_json::Value::Object(fields),
3980                    )]))
3981                }
3982            };
3983            Ok(converted)
3984        }
3985    };
3986}
3987
3988define_driver_json_conversion!(
3989    "band8",
3990    driver_b8,
3991    document_to_json_b8,
3992    document_node_to_json_b8,
3993    document_leaf_to_json_b8,
3994    value_to_json_b8
3995);
3996define_driver_json_conversion!(
3997    "band9",
3998    driver_b9,
3999    document_to_json_b9,
4000    document_node_to_json_b9,
4001    document_leaf_to_json_b9,
4002    value_to_json_b9
4003);
4004
4005/// Convert a band-8 TypeDB concept to a JSON value.
4006#[cfg(feature = "band8")]
4007fn concept_to_json_b8(
4008    concept: &type_bridge_typedb_driver_b8::concept::Concept,
4009    scalar_encoding: ScalarJsonEncoding,
4010) -> Result<serde_json::Value> {
4011    let mut obj = serde_json::Map::new();
4012    obj.insert(
4013        "category".into(),
4014        serde_json::Value::String(concept.get_category().name().into()),
4015    );
4016    obj.insert(
4017        "label".into(),
4018        serde_json::Value::String(concept.get_label().into()),
4019    );
4020    if let Some(iid) = concept.try_get_iid() {
4021        obj.insert("iid".into(), serde_json::Value::String(iid.to_string()));
4022    }
4023    if let Some(value) = concept.try_get_value() {
4024        obj.insert("value".into(), value_to_json_b8(value, scalar_encoding)?);
4025    }
4026    if let Some(vt) = concept.try_get_value_type() {
4027        obj.insert(
4028            "value_type".into(),
4029            serde_json::Value::String(vt.name().into()),
4030        );
4031    }
4032    Ok(serde_json::Value::Object(obj))
4033}
4034
4035/// Lower a portable [`GivenRowsSpec`] onto the band-9 driver's `GivenRows`.
4036///
4037/// Fails when a row's width does not match the header or a temporal string
4038/// does not parse — both are caller mistakes reported before any wire I/O.
4039#[cfg(feature = "band9")]
4040fn given_rows_b9(spec: GivenRowsSpec) -> Result<typedb_driver::given::GivenRows> {
4041    use typedb_driver::given::GivenRows;
4042
4043    let mut given = GivenRows::new(spec.variables.clone(), spec.rows.len());
4044    for row in spec.rows {
4045        if row.len() != spec.variables.len() {
4046            return Err(RuntimeError::QueryExecution(
4047                "Invalid given row: width does not match the column header".into(),
4048            ));
4049        }
4050        let entries = spec
4051            .variables
4052            .iter()
4053            .zip(row)
4054            .map(|(column, value)| given_entry_b9(column, value))
4055            .collect::<Result<Vec<_>>>()?;
4056        given.push_row(entries).map_err(|_| {
4057            RuntimeError::QueryExecution(
4058                "Invalid given row: the driver rejected the input row shape".into(),
4059            )
4060        })?;
4061    }
4062    Ok(given)
4063}
4064
4065#[cfg(feature = "band9")]
4066fn invalid_given_value(column: &str, value_type: &'static str) -> RuntimeError {
4067    RuntimeError::QueryExecution(format!("Invalid given {value_type} in column {column:?}"))
4068}
4069
4070/// Convert one portable [`GivenValue`] to a band-9 driver row entry.
4071#[cfg(feature = "band9")]
4072fn given_entry_b9(column: &str, value: GivenValue) -> Result<typedb_driver::given::GivenRowEntry> {
4073    use chrono::{NaiveDate, NaiveDateTime};
4074    use typedb_driver::concept::value::TimeZone as B9TimeZone;
4075    use typedb_driver::concept::value::{Decimal, Duration};
4076    use typedb_driver::given::GivenRowEntry;
4077
4078    Ok(match value {
4079        GivenValue::Empty => GivenRowEntry::Empty,
4080        GivenValue::Boolean(b) => GivenRowEntry::from(b),
4081        GivenValue::Integer(i) => GivenRowEntry::from(i),
4082        GivenValue::Double(d) => GivenRowEntry::from(d),
4083        GivenValue::String(s) => GivenRowEntry::from(s),
4084        GivenValue::Date(s) => {
4085            let date = s
4086                .parse::<NaiveDate>()
4087                .map_err(|_| invalid_given_value(column, "date"))?;
4088            GivenRowEntry::from(date)
4089        }
4090        GivenValue::Datetime(s) => {
4091            let dt = s
4092                .parse::<NaiveDateTime>()
4093                .map_err(|_| invalid_given_value(column, "datetime"))?;
4094            GivenRowEntry::from(dt)
4095        }
4096        GivenValue::DatetimeTz(s) => {
4097            let dt = parse_given_datetime_tz(&s)
4098                .map_err(|_| invalid_given_value(column, "datetime-tz"))?;
4099            let offset = *dt.offset();
4100            GivenRowEntry::from(dt.with_timezone(&B9TimeZone::Fixed(offset)))
4101        }
4102        GivenValue::DatetimeTzExact {
4103            local,
4104            named_zone,
4105            effective_offset_seconds,
4106        } => GivenRowEntry::from(
4107            exact_given_datetime_tz_b9(&local, named_zone.as_deref(), effective_offset_seconds)
4108                .map_err(|_| invalid_given_value(column, "datetime-tz"))?,
4109        ),
4110        GivenValue::Decimal(s) => {
4111            // The upstream parser parses the unsigned magnitude into `i64`,
4112            // so the otherwise-valid decimal minimum cannot pass through it.
4113            // Preserve that one boundary explicitly; every other canonical
4114            // decimal spelling is accepted by the driver parser.
4115            let decimal = if s == "-9223372036854775808" {
4116                Decimal::MIN
4117            } else {
4118                s.parse::<Decimal>()
4119                    .map_err(|_| invalid_given_value(column, "decimal"))?
4120            };
4121            GivenRowEntry::from(decimal)
4122        }
4123        GivenValue::Duration {
4124            months,
4125            days,
4126            nanos,
4127        } => GivenRowEntry::from(Duration::new(months, days, nanos)),
4128    })
4129}
4130
4131#[cfg(feature = "band9")]
4132fn exact_given_datetime_tz_b9(
4133    local: &str,
4134    named_zone: Option<&str>,
4135    effective_offset_seconds: i32,
4136) -> Result<chrono::DateTime<typedb_driver::concept::value::TimeZone>> {
4137    use chrono::{FixedOffset, LocalResult, NaiveDateTime, TimeZone as _};
4138    use typedb_driver::concept::value::TimeZone as B9TimeZone;
4139
4140    let local = local.parse::<NaiveDateTime>().map_err(|_| {
4141        RuntimeError::QueryExecution("Invalid given exact datetime-tz local".to_owned())
4142    })?;
4143    let matches_offset = |value: &chrono::DateTime<B9TimeZone>| {
4144        value
4145            .naive_local()
4146            .signed_duration_since(value.naive_utc())
4147            .num_seconds()
4148            == i64::from(effective_offset_seconds)
4149    };
4150    if let Some(name) = named_zone {
4151        let timezone = chrono_tz::Tz::from_str_insensitive(name)
4152            .map(B9TimeZone::IANA)
4153            .map_err(|_| {
4154                RuntimeError::QueryExecution(
4155                    "Invalid given exact datetime-tz named zone".to_owned(),
4156                )
4157            })?;
4158        let selected = match timezone.from_local_datetime(&local) {
4159            LocalResult::Single(value) if matches_offset(&value) => Some(value),
4160            LocalResult::Ambiguous(earlier, later) => [earlier, later]
4161                .into_iter()
4162                .find(|value| matches_offset(value)),
4163            LocalResult::Single(_) | LocalResult::None => None,
4164        };
4165        return selected.ok_or_else(|| {
4166            RuntimeError::QueryExecution(
4167                "Invalid given exact datetime-tz named-zone resolution".to_owned(),
4168            )
4169        });
4170    }
4171
4172    let offset = FixedOffset::east_opt(effective_offset_seconds).ok_or_else(|| {
4173        RuntimeError::QueryExecution("Invalid given exact datetime-tz fixed offset".to_owned())
4174    })?;
4175    B9TimeZone::Fixed(offset)
4176        .from_local_datetime(&local)
4177        .single()
4178        .ok_or_else(|| {
4179            RuntimeError::QueryExecution(
4180                "Invalid given exact datetime-tz fixed resolution".to_owned(),
4181            )
4182        })
4183}
4184
4185/// Parse the fixed-offset spelling used by the portable V2 contract.
4186///
4187/// Chrono's RFC-3339 parser deliberately accepts only four-digit years and
4188/// minute-resolution offsets. TypeDB's scalar domain is wider, so parse the
4189/// canonical local datetime and an optional seconds component separately.
4190#[cfg(feature = "band9")]
4191fn parse_given_datetime_tz(
4192    value: &str,
4193) -> std::result::Result<chrono::DateTime<chrono::FixedOffset>, &'static str> {
4194    use chrono::{FixedOffset, NaiveDateTime, TimeZone as _};
4195
4196    let (local, offset_seconds) = if let Some(local) = value.strip_suffix('Z') {
4197        (local, 0)
4198    } else {
4199        let (local, offset) = [9_usize, 6]
4200            .into_iter()
4201            .find_map(|width| {
4202                let split = value.len().checked_sub(width)?;
4203                if !value.is_char_boundary(split) {
4204                    return None;
4205                }
4206                let (local, offset) = (&value[..split], &value[split..]);
4207                parse_fixed_offset(offset).map(|seconds| (local, seconds))
4208            })
4209            .ok_or("expected a Z or signed fixed offset")?;
4210        (local, offset)
4211    };
4212    let local = local
4213        .parse::<NaiveDateTime>()
4214        .map_err(|_| "invalid local datetime")?;
4215    let offset = FixedOffset::east_opt(offset_seconds).ok_or("fixed offset is out of range")?;
4216    offset
4217        .from_local_datetime(&local)
4218        .single()
4219        .ok_or("local datetime is out of range")
4220}
4221
4222#[cfg(feature = "band9")]
4223fn parse_fixed_offset(value: &str) -> Option<i32> {
4224    let bytes = value.as_bytes();
4225    if !matches!(
4226        bytes,
4227        [b'+' | b'-', _, _, b':', _, _] | [b'+' | b'-', _, _, b':', _, _, b':', _, _]
4228    ) || !bytes
4229        .iter()
4230        .enumerate()
4231        .filter(|(index, _)| !matches!(index, 0 | 3 | 6))
4232        .all(|(_, byte)| byte.is_ascii_digit())
4233    {
4234        return None;
4235    }
4236    let component = |left: usize, right: usize| {
4237        std::str::from_utf8(&bytes[left..right])
4238            .ok()?
4239            .parse::<i32>()
4240            .ok()
4241    };
4242    let hours = component(1, 3)?;
4243    let minutes = component(4, 6)?;
4244    let seconds = if bytes.len() == 9 {
4245        component(7, 9)?
4246    } else {
4247        0
4248    };
4249    if hours > 23 || minutes > 59 || seconds > 59 {
4250        return None;
4251    }
4252    let magnitude = hours * 3_600 + minutes * 60 + seconds;
4253    Some(if bytes[0] == b'-' {
4254        -magnitude
4255    } else {
4256        magnitude
4257    })
4258}
4259
4260/// Convert and consume a band-9 answer without materializing its stream.
4261#[cfg(feature = "band9")]
4262async fn consume_answer_b9(
4263    answer: B9QueryAnswer,
4264    limits: &RuntimeAnswerLimits,
4265    max_collection_members: u64,
4266    scalar_encoding: ScalarJsonEncoding,
4267    consumer: &mut (dyn FnMut(RuntimeAnswerItem) -> Result<RuntimeAnswerControl> + Send),
4268) -> Result<RuntimeAnswerStats> {
4269    match answer {
4270        B9QueryAnswer::Ok(_) => Ok(RuntimeAnswerStats::new(RuntimeAnswerKind::Ok)),
4271        B9QueryAnswer::ConceptRowStream(_, stream) => {
4272            let stream = stream
4273                .map_err(|error| band9_query_error_with_operation(error, "Row stream failed"))
4274                .and_then(move |row| {
4275                    let _stage = decode_span().entered();
4276                    let result = (|| -> Result<RuntimeAnswerItem> {
4277                        let mut obj = serde_json::Map::new();
4278                        for (i, col) in row.get_column_names().iter().enumerate() {
4279                            let value = row
4280                                .row
4281                                .get(i)
4282                                .and_then(|c| c.as_ref())
4283                                .map(|concept| concept_to_json_b9(concept, scalar_encoding))
4284                                .transpose()?
4285                                .unwrap_or(serde_json::Value::Null);
4286                            obj.insert(col.clone(), value);
4287                        }
4288                        Ok(RuntimeAnswerItem::Row(serde_json::Value::Object(obj)))
4289                    })();
4290                    futures::future::ready(result)
4291                });
4292            runtime_consume_stream(stream, RuntimeAnswerKind::Rows, limits, consumer).await
4293        }
4294        B9QueryAnswer::ConceptDocumentStream(_, stream) => {
4295            let mut collection_members = 0_u64;
4296            let stream = stream
4297                .map_err(|error| band9_query_error_with_operation(error, "Document stream failed"))
4298                .and_then(move |document| {
4299                    let _stage = decode_span().entered();
4300                    let result = document_to_json_b9(
4301                        &document,
4302                        &mut collection_members,
4303                        max_collection_members,
4304                        scalar_encoding,
4305                    )
4306                    .map(RuntimeAnswerItem::Document);
4307                    futures::future::ready(result)
4308                });
4309            runtime_consume_stream(stream, RuntimeAnswerKind::Documents, limits, consumer).await
4310        }
4311    }
4312}
4313
4314/// Convert a band-9 TypeDB concept to a JSON value.
4315///
4316/// Output shape is identical to [`concept_to_json_b8`] for all common concepts.
4317#[cfg(feature = "band9")]
4318fn concept_to_json_b9(
4319    concept: &typedb_driver::concept::Concept,
4320    scalar_encoding: ScalarJsonEncoding,
4321) -> Result<serde_json::Value> {
4322    let mut obj = serde_json::Map::new();
4323    obj.insert(
4324        "category".into(),
4325        serde_json::Value::String(concept.get_category().name().into()),
4326    );
4327    obj.insert(
4328        "label".into(),
4329        serde_json::Value::String(concept.get_label().into()),
4330    );
4331    if let Some(iid) = concept.try_get_iid() {
4332        obj.insert("iid".into(), serde_json::Value::String(iid.to_string()));
4333    }
4334    if let Some(value) = concept.try_get_value() {
4335        obj.insert("value".into(), value_to_json_b9(value, scalar_encoding)?);
4336    }
4337    if let Some(vt) = concept.try_get_value_type() {
4338        obj.insert(
4339            "value_type".into(),
4340            serde_json::Value::String(vt.name().into()),
4341        );
4342    }
4343    Ok(serde_json::Value::Object(obj))
4344}
4345
4346#[cfg(test)]
4347mod tests {
4348    use super::*;
4349    use std::io;
4350    use std::sync::atomic::{AtomicUsize, Ordering};
4351    use std::sync::{Arc, Mutex};
4352
4353    #[test]
4354    fn transaction_options_forward_independent_driver_deadlines() {
4355        for options in [
4356            TransactionOptions::default(),
4357            TransactionOptions {
4358                transaction_timeout: Some(Duration::from_secs(1)),
4359                ..Default::default()
4360            },
4361            TransactionOptions {
4362                schema_lock_acquire_timeout: Some(Duration::from_secs(2)),
4363                ..Default::default()
4364            },
4365            TransactionOptions {
4366                transaction_timeout: Some(Duration::from_secs(3)),
4367                schema_lock_acquire_timeout: Some(Duration::from_secs(4)),
4368            },
4369        ] {
4370            #[cfg(feature = "band8")]
4371            {
4372                let driver = options.band8();
4373                assert_eq!(driver.transaction_timeout, options.transaction_timeout);
4374                assert_eq!(
4375                    driver.schema_lock_acquire_timeout,
4376                    options.schema_lock_acquire_timeout
4377                );
4378            }
4379            #[cfg(feature = "band9")]
4380            {
4381                let driver = options.band9();
4382                assert_eq!(driver.transaction_timeout, options.transaction_timeout);
4383                assert_eq!(
4384                    driver.schema_lock_acquire_timeout,
4385                    options.schema_lock_acquire_timeout
4386                );
4387            }
4388        }
4389    }
4390
4391    static NEXT_TLS_MATERIAL_TEST_ID: AtomicUsize = AtomicUsize::new(0);
4392    static TRACE_CAPTURE_LOCK: Mutex<()> = Mutex::new(());
4393
4394    #[derive(Clone, Default)]
4395    struct TraceCapture {
4396        bytes: Arc<Mutex<Vec<u8>>>,
4397    }
4398
4399    struct TraceCaptureWriter {
4400        bytes: Arc<Mutex<Vec<u8>>>,
4401    }
4402
4403    impl io::Write for TraceCaptureWriter {
4404        fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
4405            self.bytes
4406                .lock()
4407                .expect("trace capture lock")
4408                .extend_from_slice(buffer);
4409            Ok(buffer.len())
4410        }
4411
4412        fn flush(&mut self) -> io::Result<()> {
4413            Ok(())
4414        }
4415    }
4416
4417    impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for TraceCapture {
4418        type Writer = TraceCaptureWriter;
4419
4420        fn make_writer(&'writer self) -> Self::Writer {
4421            TraceCaptureWriter {
4422                bytes: Arc::clone(&self.bytes),
4423            }
4424        }
4425    }
4426
4427    fn capture_traces(emit: impl FnOnce()) -> String {
4428        let _capture_guard = TRACE_CAPTURE_LOCK.lock().expect("trace capture suite lock");
4429        let capture = TraceCapture::default();
4430        let subscriber = tracing_subscriber::fmt()
4431            .without_time()
4432            .with_ansi(false)
4433            .with_target(false)
4434            .with_max_level(tracing::Level::TRACE)
4435            .with_writer(capture.clone())
4436            .finish();
4437        tracing::subscriber::with_default(subscriber, || {
4438            // Another test thread may have cached a callsite as uninteresting
4439            // while no subscriber was set; re-evaluate before emitting.
4440            tracing::callsite::rebuild_interest_cache();
4441            emit();
4442        });
4443        let bytes = capture.bytes.lock().expect("trace capture lock").clone();
4444        String::from_utf8(bytes).expect("tracing formatter emits UTF-8")
4445    }
4446
4447    #[test]
4448    fn driver_drop_close_warning_drops_hostile_provider_text() {
4449        const PROVIDER_SENTINEL: &str = "TB_DROP_CLOSE_PROVIDER_SECRET";
4450        let error = RuntimeError::Connection(PROVIDER_SENTINEL.to_owned());
4451        let output = capture_traces(|| trace_driver_drop_close_failure(&error));
4452
4453        assert!(
4454            output.contains(TRACE_CODE_DRIVER_DROP_CLOSE_FAILED),
4455            "{output}"
4456        );
4457        assert!(
4458            output.contains("typedb_runtime_connection_failed"),
4459            "{output}"
4460        );
4461        assert!(!output.contains(PROVIDER_SENTINEL), "{output}");
4462    }
4463
4464    #[cfg(all(feature = "band8", feature = "band9"))]
4465    #[test]
4466    fn band9_upgrade_failure_warning_drops_hostile_provider_and_address_text() {
4467        const ADDRESS_SENTINEL: &str = "TB_BAND9_UPGRADE_ADDRESS_SECRET";
4468        const PROVIDER_SENTINEL: &str = "TB_BAND9_UPGRADE_PROVIDER_SECRET";
4469        let error =
4470            SecureConnectError::Runtime(RuntimeError::Connection(PROVIDER_SENTINEL.to_owned()));
4471        let output = capture_traces(|| {
4472            trace_band9_upgrade_failed(
4473                ADDRESS_SENTINEL,
4474                core_version::Version::new(3, 12, 1),
4475                &error,
4476            );
4477        });
4478
4479        assert!(output.contains(TRACE_CODE_BAND9_UPGRADE_FAILED), "{output}");
4480        assert!(
4481            output.contains("typedb_runtime_connection_failed"),
4482            "{output}"
4483        );
4484        assert!(output.contains("3.12.1"), "{output}");
4485        assert!(!output.contains(ADDRESS_SENTINEL), "{output}");
4486        assert!(!output.contains(PROVIDER_SENTINEL), "{output}");
4487    }
4488
4489    #[test]
4490    fn post_credential_connection_traces_drop_raw_address_identity() {
4491        const ADDRESS_SENTINEL: &str = "TB_POST_CREDENTIAL_ADDRESS_SECRET";
4492        let server_version = core_version::Version::new(3, 12, 1);
4493        let output = capture_traces(|| {
4494            trace_version_gate_passed(ADDRESS_SENTINEL, 9, server_version);
4495            #[cfg(all(feature = "band8", feature = "band9"))]
4496            trace_band9_upgrade_succeeded(ADDRESS_SENTINEL, server_version);
4497            #[cfg(feature = "band8")]
4498            trace_band8_fallback_connected(ADDRESS_SENTINEL, server_version);
4499            trace_runtime_connected(ADDRESS_SENTINEL, 9, Some(server_version));
4500        });
4501
4502        assert!(!output.contains(ADDRESS_SENTINEL), "{output}");
4503        assert!(output.contains(TRACE_CODE_VERSION_GATE_PASSED), "{output}");
4504        assert!(output.contains(TRACE_CODE_CONNECTED), "{output}");
4505        assert!(output.contains("3.12.1"), "{output}");
4506        #[cfg(all(feature = "band8", feature = "band9"))]
4507        assert!(
4508            output.contains(TRACE_CODE_BAND9_UPGRADE_SUCCEEDED),
4509            "{output}"
4510        );
4511        #[cfg(feature = "band8")]
4512        assert!(
4513            output.contains(TRACE_CODE_BAND8_FALLBACK_CONNECTED),
4514            "{output}"
4515        );
4516    }
4517
4518    #[test]
4519    fn retained_server_trace_is_warning_free() {
4520        for (driver_band, server_version) in [
4521            (8, Some(core_version::Version::new(3, 11, 5))),
4522            (9, Some(core_version::Version::new(3, 12, 1))),
4523            // A 3.12 server may retain the validated band-8 fallback after
4524            // discovery. Classification keys on the known server line, not
4525            // the negotiated driver band.
4526            (8, Some(core_version::Version::new(3, 12, 1))),
4527            (9, Some(core_version::Version::new(3, 14, 1))),
4528            (8, None),
4529            (9, None),
4530        ] {
4531            let output =
4532                capture_traces(|| trace_runtime_connected("redacted", driver_band, server_version));
4533            assert!(output.contains(TRACE_CODE_CONNECTED), "{output}");
4534            assert!(!output.contains("WARN"), "{output}");
4535            assert!(!output.contains("deprecated"), "{output}");
4536        }
4537    }
4538
4539    #[test]
4540    fn newer_server_connection_warns_once_with_measured_fallback_and_no_address() {
4541        for version in [
4542            core_version::Version::new(3, 15, 0),
4543            core_version::Version::new(4, 0, 0),
4544        ] {
4545            let output =
4546                capture_traces(|| trace_runtime_connected("PRIVATE_ENDPOINT", 9, Some(version)));
4547            assert_eq!(
4548                output.matches(TRACE_CODE_UNMEASURED_SERVER).count(),
4549                1,
4550                "{output}"
4551            );
4552            assert_eq!(output.matches("WARN").count(), 1, "{output}");
4553            assert!(output.contains(&version.to_string()), "{output}");
4554            assert!(output.contains("newest_measured_line=3.14"), "{output}");
4555            assert!(
4556                output.contains(core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID),
4557                "{output}"
4558            );
4559            assert!(
4560                output.contains("not tested or supported by this TypeBridge release"),
4561                "{output}"
4562            );
4563            assert!(!output.contains("PRIVATE_ENDPOINT"), "{output}");
4564        }
4565    }
4566
4567    #[test]
4568    fn credential_safe_secure_diagnostics_drop_provider_controlled_text() {
4569        const SENTINEL: &str = "TB_POST_CREDENTIAL_PROVIDER_SECRET";
4570        for error in [
4571            SecureConnectError::Runtime(RuntimeError::Connection(SENTINEL.to_owned())),
4572            SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
4573                core_version::VersionError::Probe(SENTINEL.to_owned()),
4574            )),
4575            SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
4576                core_version::VersionError::Parse(SENTINEL.to_owned()),
4577            )),
4578        ] {
4579            assert_eq!(error.credential_safe_diagnostic(), None);
4580        }
4581
4582        let tls = SecureConnectError::TlsConfiguration(
4583            core_version::TlsConfigurationError::CustomRootCaUnreadable {
4584                path: std::path::PathBuf::from(SENTINEL),
4585            },
4586        )
4587        .credential_safe_diagnostic()
4588        .expect("typed TLS codes remain safe");
4589        assert!(tls.contains("tls_custom_root_ca_unreadable"), "{tls}");
4590        assert!(!tls.contains(SENTINEL), "{tls}");
4591    }
4592
4593    #[test]
4594    fn credential_safe_secure_diagnostics_preserve_closed_version_data() {
4595        let error = SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
4596            core_version::VersionError::Unsupported {
4597                component: "server",
4598                found: core_version::Version::new(3, 10, 4),
4599            },
4600        ));
4601        let diagnostic = error
4602            .credential_safe_diagnostic()
4603            .expect("closed version diagnostics remain actionable");
4604        assert!(diagnostic.contains("server version 3.10.4"), "{diagnostic}");
4605        assert!(diagnostic.contains("3.11.0 or newer"), "{diagnostic}");
4606    }
4607
4608    #[test]
4609    fn driver_shutdown_panics_are_contained_as_connection_errors() {
4610        let error = contain_driver_shutdown(|| panic!("simulated upstream shutdown panic"))
4611            .expect_err("shutdown panic must not cross the runtime boundary");
4612
4613        assert!(matches!(
4614            error,
4615            RuntimeError::Connection(message)
4616                if message == "Driver close failed: upstream driver panicked during shutdown"
4617        ));
4618    }
4619
4620    #[test]
4621    fn failed_driver_shutdown_is_retried_without_reopening_admission() {
4622        let state = AtomicU8::new(DRIVER_OPEN);
4623        let close_lock = Mutex::new(());
4624
4625        for _ in 0..2 {
4626            let error = run_driver_shutdown(&state, &close_lock, || {
4627                Err(RuntimeError::Connection(
4628                    "Driver close failed: simulated incomplete cleanup".to_owned(),
4629                ))
4630            })
4631            .expect_err("incomplete cleanup must remain observable");
4632            assert_eq!(
4633                error.to_string(),
4634                "Connection error: Driver close failed: simulated incomplete cleanup"
4635            );
4636            assert_eq!(state.load(AtomicOrdering::Acquire), DRIVER_CLOSING);
4637        }
4638
4639        run_driver_shutdown(&state, &close_lock, || Ok(()))
4640            .expect("a later close retries and completes cleanup");
4641        assert_eq!(state.load(AtomicOrdering::Acquire), DRIVER_CLOSED);
4642
4643        run_driver_shutdown(&state, &close_lock, || {
4644            panic!("successful cleanup must make later close calls no-ops")
4645        })
4646        .expect("close remains idempotent after cleanup succeeds");
4647    }
4648
4649    #[test]
4650    fn transaction_retention_and_shutdown_share_one_admission_lock() {
4651        let state = AtomicU8::new(DRIVER_OPEN);
4652        let active_transactions = AtomicUsize::new(0);
4653        let close_lock = Mutex::new(());
4654
4655        retain_driver_transaction(&state, &active_transactions, &close_lock)
4656            .expect("an open driver admits a transaction lease");
4657        assert_eq!(active_transactions.load(AtomicOrdering::Acquire), 1);
4658
4659        let _close_guard = close_lock.lock().expect("admission lock remains usable");
4660        state.store(DRIVER_CLOSING, AtomicOrdering::Release);
4661        drop(_close_guard);
4662
4663        let error = retain_driver_transaction(&state, &active_transactions, &close_lock)
4664            .expect_err("shutdown must make later transaction retention terminal");
4665        assert!(matches!(error, RuntimeError::Connection(_)));
4666        assert_eq!(active_transactions.load(AtomicOrdering::Acquire), 1);
4667    }
4668
4669    #[test]
4670    fn one_shot_database_operation_propagates_close_failure_after_success() {
4671        assert_eq!(
4672            finish_one_shot_database_operation(Ok(17_u8), Ok(())).unwrap(),
4673            17
4674        );
4675
4676        let error = finish_one_shot_database_operation(
4677            Ok(17_u8),
4678            Err(RuntimeError::Connection("close diagnosis".to_owned())),
4679        )
4680        .expect_err("a successful operation must still report driver-close failure");
4681        assert!(matches!(
4682            error,
4683            RuntimeError::Connection(message) if message == "close diagnosis"
4684        ));
4685    }
4686
4687    #[test]
4688    fn one_shot_database_operation_preserves_primary_failure_and_combines_close_failure() {
4689        let primary_only = finish_one_shot_database_operation::<()>(
4690            Err(RuntimeError::Connection("primary diagnosis".to_owned())),
4691            Ok(()),
4692        )
4693        .expect_err("the primary database-operation failure must be returned");
4694        assert!(matches!(
4695            primary_only,
4696            RuntimeError::Connection(message) if message == "primary diagnosis"
4697        ));
4698
4699        let combined = finish_one_shot_database_operation::<()>(
4700            Err(RuntimeError::Connection("primary diagnosis".to_owned())),
4701            Err(RuntimeError::Connection("close diagnosis".to_owned())),
4702        )
4703        .expect_err("both failures must produce one deterministic diagnostic");
4704        assert!(matches!(
4705            combined,
4706            RuntimeError::Connection(message)
4707                if message
4708                    == "primary diagnosis; additionally, TypeDB driver cleanup failed: close diagnosis"
4709        ));
4710    }
4711
4712    macro_rules! row_and_document_scalar_regression {
4713        ($feature:literal, $name:ident, $driver:ident, $concept_fn:ident, $node_fn:ident, $decimal:expr) => {
4714            #[cfg(feature = $feature)]
4715            #[test]
4716            fn $name() {
4717                use $driver::answer::concept_document::{Leaf, Node};
4718                use $driver::concept::{Concept, Value};
4719
4720                const LARGE_INTEGER: i64 = 9_007_199_254_740_993;
4721                let integer = Node::Leaf(Some(Leaf::Concept(Concept::Value(Value::Integer(
4722                    LARGE_INTEGER,
4723                )))));
4724                let mut collection_members = 0;
4725                assert_eq!(
4726                    $node_fn(
4727                        &integer,
4728                        &mut collection_members,
4729                        u64::MAX,
4730                        ScalarJsonEncoding::CanonicalV2,
4731                    )
4732                    .unwrap(),
4733                    serde_json::Value::from(LARGE_INTEGER),
4734                    "concept-document integers must not cross an f64 boundary"
4735                );
4736
4737                let decimal = $decimal;
4738                let scalar_text = |value: serde_json::Value| {
4739                    value
4740                        .get("value")
4741                        .and_then(serde_json::Value::as_str)
4742                        .or_else(|| value.as_str())
4743                        .map(str::to_owned)
4744                        .expect("decimal conversion must expose scalar text")
4745                };
4746                let legacy_expected = decimal.to_string();
4747                let expected = "1234.56";
4748                let decimal =
4749                    Node::Leaf(Some(Leaf::Concept(Concept::Value(Value::Decimal(decimal)))));
4750                let row_decimal = Concept::Value(Value::Decimal($decimal));
4751                assert_eq!(
4752                    scalar_text(
4753                        $node_fn(
4754                            &decimal,
4755                            &mut collection_members,
4756                            u64::MAX,
4757                            ScalarJsonEncoding::CanonicalV2,
4758                        )
4759                        .unwrap()
4760                    ),
4761                    expected,
4762                    "concept-document decimals must use canonical strings"
4763                );
4764                assert_eq!(
4765                    scalar_text(
4766                        $concept_fn(&row_decimal, ScalarJsonEncoding::CanonicalV2).unwrap()
4767                    ),
4768                    expected
4769                );
4770                assert_eq!(
4771                    scalar_text(
4772                        $concept_fn(&row_decimal, ScalarJsonEncoding::DriverDisplay).unwrap()
4773                    ),
4774                    legacy_expected.clone()
4775                );
4776                let legacy_decimal = Node::Leaf(Some(Leaf::Concept(Concept::Value(
4777                    Value::Decimal($decimal),
4778                ))));
4779                assert_eq!(
4780                    scalar_text(
4781                        $node_fn(
4782                            &legacy_decimal,
4783                            &mut collection_members,
4784                            u64::MAX,
4785                            ScalarJsonEncoding::DriverDisplay,
4786                        )
4787                        .unwrap()
4788                    ),
4789                    legacy_expected,
4790                    "legacy document decimals must retain driver spelling"
4791                );
4792            }
4793        };
4794    }
4795
4796    row_and_document_scalar_regression!(
4797        "band8",
4798        band8_rows_and_documents_preserve_lossless_scalars,
4799        driver_b8,
4800        concept_to_json_b8,
4801        document_node_to_json_b8,
4802        driver_b8::concept::value::Decimal::new(1234, 5_600_000_000_000_000_000)
4803    );
4804    row_and_document_scalar_regression!(
4805        "band9",
4806        band9_rows_and_documents_preserve_lossless_scalars,
4807        driver_b9,
4808        concept_to_json_b9,
4809        document_node_to_json_b9,
4810        driver_b9::concept::value::Decimal::from_parts(1234, 5_600_000_000_000_000_000)
4811    );
4812
4813    macro_rules! datetime_tz_evidence_regression {
4814        ($feature:literal, $name:ident, $driver:ident, $concept_fn:ident, $leaf_fn:ident) => {
4815            #[cfg(feature = $feature)]
4816            #[test]
4817            fn $name() {
4818                use chrono::{NaiveDateTime, TimeZone as _};
4819                use $driver::answer::concept_document::Leaf;
4820                use $driver::concept::value::TimeZone;
4821                use $driver::concept::{Concept, Value};
4822
4823                let london = TimeZone::IANA(
4824                    "Europe/London"
4825                        .parse()
4826                        .expect("driver timezone database contains London"),
4827                );
4828                let overlap_utc = "2024-10-27T00:30:00"
4829                    .parse::<NaiveDateTime>()
4830                    .expect("UTC datetime");
4831                let named = Value::DatetimeTZ(london.from_utc_datetime(&overlap_utc));
4832                assert_eq!(
4833                    $concept_fn(
4834                        &Concept::Value(named.clone()),
4835                        ScalarJsonEncoding::CanonicalV2,
4836                    )
4837                    .expect("row concept")["value"],
4838                    serde_json::json!("2024-10-27T01:30:00+01:00[Europe/London]"),
4839                    "row evidence preserves both the IANA identity and overlap side",
4840                );
4841                assert_eq!(
4842                    $leaf_fn(
4843                        &Leaf::Concept(Concept::Value(named.clone())),
4844                        ScalarJsonEncoding::CanonicalV2,
4845                    )
4846                    .expect("document leaf"),
4847                    serde_json::json!("2024-10-27T01:30:00+01:00[Europe/London]"),
4848                    "document evidence uses the same exact datetime-tz bridge",
4849                );
4850                assert_eq!(
4851                    $concept_fn(&Concept::Value(named), ScalarJsonEncoding::DriverDisplay,)
4852                        .expect("row concept")["value"],
4853                    serde_json::json!("2024-10-27T01:30:00.000000000 Europe/London"),
4854                    "released conversion retains the upstream driver display",
4855                );
4856
4857                let fixed = TimeZone::Fixed(
4858                    chrono::FixedOffset::east_opt(1_172).expect("second-resolution offset"),
4859                );
4860                let fixed_utc = "1900-01-01T11:40:28"
4861                    .parse::<NaiveDateTime>()
4862                    .expect("UTC datetime");
4863                let fixed = Value::DatetimeTZ(fixed.from_utc_datetime(&fixed_utc));
4864                assert_eq!(
4865                    $concept_fn(
4866                        &Concept::Value(fixed.clone()),
4867                        ScalarJsonEncoding::CanonicalV2,
4868                    )
4869                    .expect("row concept")["value"],
4870                    serde_json::json!("1900-01-01T12:00:00+00:19:32"),
4871                    "row evidence preserves fixed offset seconds",
4872                );
4873                assert_eq!(
4874                    $leaf_fn(
4875                        &Leaf::Concept(Concept::Value(fixed)),
4876                        ScalarJsonEncoding::CanonicalV2,
4877                    )
4878                    .expect("document leaf"),
4879                    serde_json::json!("1900-01-01T12:00:00+00:19:32"),
4880                    "document evidence preserves fixed offset seconds",
4881                );
4882            }
4883        };
4884    }
4885
4886    datetime_tz_evidence_regression!(
4887        "band8",
4888        band8_rows_and_documents_preserve_exact_datetime_tz_evidence,
4889        driver_b8,
4890        concept_to_json_b8,
4891        document_leaf_to_json_b8
4892    );
4893    datetime_tz_evidence_regression!(
4894        "band9",
4895        band9_rows_and_documents_preserve_exact_datetime_tz_evidence,
4896        driver_b9,
4897        concept_to_json_b9,
4898        document_leaf_to_json_b9
4899    );
4900
4901    macro_rules! datetime_tz_local_range_regression {
4902        ($feature:literal, $name:ident, $driver:ident, $concept_fn:ident, $leaf_fn:ident) => {
4903            #[cfg(feature = $feature)]
4904            #[test]
4905            fn $name() {
4906                use chrono::{FixedOffset, NaiveDateTime, TimeZone as _};
4907                use $driver::answer::concept_document::Leaf;
4908                use $driver::concept::value::TimeZone;
4909                use $driver::concept::{Concept, Value};
4910
4911                let assert_range_error = |error: RuntimeError| {
4912                    assert!(matches!(
4913                        error,
4914                        RuntimeError::QueryExecution(message)
4915                            if message
4916                                == "provider datetime-tz local value is outside the supported range"
4917                    ));
4918                };
4919                let invalid = [
4920                    (
4921                        FixedOffset::east_opt(1).expect("positive offset"),
4922                        NaiveDateTime::MAX,
4923                    ),
4924                    (
4925                        FixedOffset::west_opt(1).expect("negative offset"),
4926                        NaiveDateTime::MIN,
4927                    ),
4928                ];
4929                for (offset, utc) in invalid {
4930                    let timezone = TimeZone::Fixed(offset);
4931                    let value = Value::DatetimeTZ(timezone.from_utc_datetime(&utc));
4932                    for encoding in [
4933                        ScalarJsonEncoding::CanonicalV2,
4934                        ScalarJsonEncoding::DriverDisplay,
4935                    ] {
4936                        let row_error =
4937                            $concept_fn(&Concept::Value(value.clone()), encoding).expect_err(
4938                                "an unrepresentable provider local datetime must fail row conversion",
4939                            );
4940                        assert_range_error(row_error);
4941
4942                        let document_error =
4943                            $leaf_fn(&Leaf::Concept(Concept::Value(value.clone())), encoding)
4944                                .expect_err(
4945                                    "an unrepresentable provider local datetime must fail document conversion",
4946                                );
4947                        assert_range_error(document_error);
4948                    }
4949                }
4950
4951                let valid = [
4952                    (
4953                        FixedOffset::west_opt(1).expect("negative offset"),
4954                        NaiveDateTime::MAX,
4955                    ),
4956                    (
4957                        FixedOffset::east_opt(1).expect("positive offset"),
4958                        NaiveDateTime::MIN,
4959                    ),
4960                ];
4961                for (offset, utc) in valid {
4962                    let timezone = TimeZone::Fixed(offset);
4963                    let value = Value::DatetimeTZ(timezone.from_utc_datetime(&utc));
4964                    for encoding in [
4965                        ScalarJsonEncoding::CanonicalV2,
4966                        ScalarJsonEncoding::DriverDisplay,
4967                    ] {
4968                        let row = $concept_fn(&Concept::Value(value.clone()), encoding)
4969                            .expect("an inward offset must remain representable");
4970                        assert!(row["value"].is_string());
4971
4972                        let document =
4973                            $leaf_fn(&Leaf::Concept(Concept::Value(value.clone())), encoding)
4974                                .expect("document conversion accepts an inward offset");
4975                        assert!(document.is_string());
4976                    }
4977                }
4978            }
4979        };
4980    }
4981
4982    datetime_tz_local_range_regression!(
4983        "band8",
4984        band8_datetime_tz_local_range_errors_are_propagated,
4985        driver_b8,
4986        concept_to_json_b8,
4987        document_leaf_to_json_b8
4988    );
4989    datetime_tz_local_range_regression!(
4990        "band9",
4991        band9_datetime_tz_local_range_errors_are_propagated,
4992        driver_b9,
4993        concept_to_json_b9,
4994        document_leaf_to_json_b9
4995    );
4996
4997    macro_rules! exact_temporal_evidence_regression {
4998        ($feature:literal, $name:ident, $driver:ident, $concept_fn:ident, $leaf_fn:ident) => {
4999            #[cfg(feature = $feature)]
5000            #[test]
5001            fn $name() {
5002                use $driver::answer::concept_document::Leaf;
5003                use $driver::concept::value::Duration;
5004                use $driver::concept::{Concept, Value};
5005
5006                let duration_cases = [
5007                    (Duration::new(0, 0, 0), "PT0S"),
5008                    (Duration::new(12, 0, 0), "P12M"),
5009                    (Duration::new(0, 0, 3_660_000_000_000), "PT3660S"),
5010                    (Duration::new(0, 0, 1_500_000_000), "PT1.5S"),
5011                    (
5012                        Duration::new(u32::MAX, u32::MAX, u64::MAX),
5013                        "P4294967295M4294967295DT18446744073.709551615S",
5014                    ),
5015                ];
5016                for (duration, expected) in duration_cases {
5017                    let value = Value::Duration(duration);
5018                    assert_eq!(
5019                        $concept_fn(
5020                            &Concept::Value(value.clone()),
5021                            ScalarJsonEncoding::CanonicalV2,
5022                        )
5023                        .expect("row concept")["value"],
5024                        serde_json::Value::String(expected.to_owned()),
5025                        "row evidence uses the contract's exact duration components",
5026                    );
5027                    assert_eq!(
5028                        $leaf_fn(
5029                            &Leaf::Concept(Concept::Value(value)),
5030                            ScalarJsonEncoding::CanonicalV2,
5031                        )
5032                        .expect("document leaf"),
5033                        serde_json::Value::String(expected.to_owned()),
5034                        "document evidence uses the same exact duration bridge",
5035                    );
5036                }
5037
5038                let year = Value::Duration(Duration::new(12, 0, 0));
5039                assert_eq!(
5040                    $concept_fn(&Concept::Value(year), ScalarJsonEncoding::DriverDisplay,)
5041                        .expect("row concept")["value"],
5042                    serde_json::json!("P1Y"),
5043                    "released conversion retains the upstream duration display",
5044                );
5045
5046                let datetime = chrono::NaiveDate::from_ymd_opt(2024, 1, 2)
5047                    .expect("date")
5048                    .and_hms_nano_opt(3, 4, 5, 500_000_000)
5049                    .expect("datetime");
5050                let datetime = Value::Datetime(datetime);
5051                assert_eq!(
5052                    $concept_fn(
5053                        &Concept::Value(datetime.clone()),
5054                        ScalarJsonEncoding::CanonicalV2,
5055                    )
5056                    .expect("row concept")["value"],
5057                    serde_json::json!("2024-01-02T03:04:05.5"),
5058                    "row evidence trims only insignificant datetime zeroes",
5059                );
5060                assert_eq!(
5061                    $leaf_fn(
5062                        &Leaf::Concept(Concept::Value(datetime.clone())),
5063                        ScalarJsonEncoding::CanonicalV2,
5064                    )
5065                    .expect("document leaf"),
5066                    serde_json::json!("2024-01-02T03:04:05.5"),
5067                    "document evidence uses the same exact datetime bridge",
5068                );
5069                assert_eq!(
5070                    $concept_fn(&Concept::Value(datetime), ScalarJsonEncoding::DriverDisplay,)
5071                        .expect("row concept")["value"],
5072                    serde_json::json!("2024-01-02T03:04:05.500000000"),
5073                    "released conversion retains the upstream datetime display",
5074                );
5075            }
5076        };
5077    }
5078
5079    exact_temporal_evidence_regression!(
5080        "band8",
5081        band8_rows_and_documents_preserve_exact_datetime_and_duration_evidence,
5082        driver_b8,
5083        concept_to_json_b8,
5084        document_leaf_to_json_b8
5085    );
5086    exact_temporal_evidence_regression!(
5087        "band9",
5088        band9_rows_and_documents_preserve_exact_datetime_and_duration_evidence,
5089        driver_b9,
5090        concept_to_json_b9,
5091        document_leaf_to_json_b9
5092    );
5093
5094    #[cfg(feature = "band9")]
5095    #[test]
5096    fn document_list_limit_rejects_before_json_collection() {
5097        use driver_b9::answer::concept_document::{Leaf, Node};
5098        let document = Node::List(vec![Node::Leaf(Some(Leaf::Empty)), Node::Leaf(None)]);
5099        let mut members = 0;
5100        let error =
5101            document_node_to_json_b9(&document, &mut members, 1, ScalarJsonEncoding::CanonicalV2)
5102                .expect_err("the list exceeds its conversion budget");
5103        assert!(matches!(
5104            error,
5105            RuntimeError::ResourceLimit {
5106                code: "query_v2_document_member_limit",
5107                ..
5108            }
5109        ));
5110        assert_eq!(members, 0, "rejected lists are not partially charged");
5111    }
5112
5113    #[cfg(feature = "band9")]
5114    #[test]
5115    fn unexpected_document_thing_is_a_typed_error_not_a_panic() {
5116        use driver_b9::answer::concept_document::{Leaf, Node};
5117        use driver_b9::concept::{Concept, Entity};
5118
5119        let document = Node::Leaf(Some(Leaf::Concept(Concept::Entity(Entity {
5120            iid: vec![1_u8].into(),
5121            type_: None,
5122        }))));
5123        let mut members = 0;
5124        let error = document_node_to_json_b9(
5125            &document,
5126            &mut members,
5127            u64::MAX,
5128            ScalarJsonEncoding::CanonicalV2,
5129        )
5130        .expect_err("thing instances are not valid fetch-document leaves");
5131        assert!(matches!(
5132            error,
5133            RuntimeError::QueryExecution(message)
5134                if message == "document response carried an unsupported thing instance"
5135        ));
5136    }
5137
5138    async fn assert_pending_runtime_await_hits_deadline() {
5139        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5140        let limits = RuntimeAnswerLimits {
5141            max_items: 10,
5142            max_bytes: 4096,
5143            deadline: Some(
5144                (tokio::time::Instant::now() + std::time::Duration::from_secs(5)).into_std(),
5145            ),
5146            cancellation: RuntimeAnswerCancellation::default(),
5147        };
5148        let execution = tokio::spawn(async move {
5149            runtime_await(
5150                async move {
5151                    let _ = started_tx.send(());
5152                    std::future::pending::<Result<()>>().await
5153                },
5154                &limits,
5155            )
5156            .await
5157        });
5158
5159        started_rx.await.unwrap();
5160        tokio::time::advance(std::time::Duration::from_secs(5)).await;
5161        tokio::task::yield_now().await;
5162        assert!(execution.is_finished());
5163        assert!(matches!(
5164            execution.await.unwrap().unwrap_err(),
5165            RuntimeError::ResourceLimit {
5166                code: "transaction_deadline_exceeded",
5167                ..
5168            }
5169        ));
5170    }
5171
5172    #[tokio::test(start_paused = true)]
5173    async fn runtime_deadline_interrupts_pending_query_await() {
5174        assert_pending_runtime_await_hits_deadline().await;
5175    }
5176
5177    #[tokio::test(start_paused = true)]
5178    async fn runtime_deadline_interrupts_pending_stream_poll() {
5179        assert_pending_runtime_await_hits_deadline().await;
5180    }
5181
5182    #[tokio::test]
5183    async fn runtime_cancellation_after_poll_start_interrupts_pending_await() {
5184        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5185        let cancellation = RuntimeAnswerCancellation::default();
5186        let trigger = cancellation.clone();
5187        let limits = RuntimeAnswerLimits {
5188            max_items: 10,
5189            max_bytes: 4096,
5190            deadline: None,
5191            cancellation,
5192        };
5193        let execution = tokio::spawn(async move {
5194            runtime_await(
5195                async move {
5196                    let _ = started_tx.send(());
5197                    std::future::pending::<Result<()>>().await
5198                },
5199                &limits,
5200            )
5201            .await
5202        });
5203
5204        started_rx.await.unwrap();
5205        trigger.cancel();
5206        tokio::task::yield_now().await;
5207        assert!(execution.is_finished());
5208        assert!(matches!(
5209            execution.await.unwrap().unwrap_err(),
5210            RuntimeError::ResourceLimit {
5211                code: "provider_cancelled",
5212                ..
5213            }
5214        ));
5215    }
5216
5217    #[test]
5218    fn bounded_runtime_reader_stops_and_enforces_limits_before_consumer() {
5219        let limits = RuntimeAnswerLimits {
5220            max_items: 1,
5221            max_bytes: 64,
5222            deadline: None,
5223            cancellation: RuntimeAnswerCancellation::default(),
5224        };
5225        let mut stats = RuntimeAnswerStats::new(RuntimeAnswerKind::Rows);
5226        let mut accepted = 0;
5227        let mut stop = |_item| {
5228            accepted += 1;
5229            Ok(RuntimeAnswerControl::Stop)
5230        };
5231        assert_eq!(
5232            runtime_accept(
5233                &limits,
5234                &mut stats,
5235                RuntimeAnswerItem::Row(serde_json::json!({"v": 1})),
5236                &mut stop,
5237            )
5238            .unwrap(),
5239            RuntimeAnswerControl::Stop
5240        );
5241        assert_eq!(accepted, 1);
5242        assert!(stats.stopped_early);
5243
5244        let mut never_called =
5245            |_item| -> Result<RuntimeAnswerControl> { panic!("over-limit item reached consumer") };
5246        let error = runtime_accept(
5247            &limits,
5248            &mut stats,
5249            RuntimeAnswerItem::Row(serde_json::json!({"v": 2})),
5250            &mut never_called,
5251        )
5252        .unwrap_err();
5253        assert!(matches!(
5254            error,
5255            RuntimeError::ResourceLimit {
5256                code: "processed_item_limit",
5257                ..
5258            }
5259        ));
5260    }
5261
5262    #[tokio::test]
5263    async fn bounded_runtime_stream_stops_before_polling_another_item() {
5264        let polls = Arc::new(AtomicUsize::new(0));
5265        let observed_polls = Arc::clone(&polls);
5266        let mut emitted = false;
5267        let stream = futures::stream::poll_fn(move |_context| {
5268            observed_polls.fetch_add(1, Ordering::SeqCst);
5269            assert!(!emitted, "stream was polled after the consumer stopped");
5270            emitted = true;
5271            std::task::Poll::Ready(Some(Ok::<_, RuntimeError>(RuntimeAnswerItem::Row(
5272                serde_json::json!({"v": 1}),
5273            ))))
5274        });
5275        let limits = RuntimeAnswerLimits::unbounded();
5276        let mut consumer = |_item| Ok(RuntimeAnswerControl::Stop);
5277
5278        let stats = runtime_consume_stream(stream, RuntimeAnswerKind::Rows, &limits, &mut consumer)
5279            .await
5280            .unwrap();
5281
5282        assert_eq!(polls.load(Ordering::SeqCst), 1);
5283        assert_eq!(stats.processed_items, 1);
5284        assert!(stats.stopped_early);
5285    }
5286
5287    #[tokio::test]
5288    async fn bounded_runtime_stream_rejects_an_over_limit_item_before_consumer() {
5289        let stream = futures::stream::iter([
5290            Ok(RuntimeAnswerItem::Row(serde_json::json!({"v": 1}))),
5291            Ok(RuntimeAnswerItem::Row(serde_json::json!({"v": 2}))),
5292        ]);
5293        let limits = RuntimeAnswerLimits {
5294            max_items: 1,
5295            max_bytes: u64::MAX,
5296            deadline: None,
5297            cancellation: RuntimeAnswerCancellation::default(),
5298        };
5299        let mut accepted = 0;
5300        let mut consumer = |_item| {
5301            accepted += 1;
5302            Ok(RuntimeAnswerControl::Continue)
5303        };
5304
5305        let error = runtime_consume_stream(stream, RuntimeAnswerKind::Rows, &limits, &mut consumer)
5306            .await
5307            .unwrap_err();
5308
5309        assert_eq!(accepted, 1);
5310        assert!(matches!(
5311            error,
5312            RuntimeError::ResourceLimit {
5313                code: "processed_item_limit",
5314                ..
5315            }
5316        ));
5317    }
5318
5319    #[cfg(feature = "band8")]
5320    fn empty_given_rows() -> GivenRowsSpec {
5321        GivenRowsSpec {
5322            variables: vec!["value".into()],
5323            rows: Vec::new(),
5324        }
5325    }
5326
5327    #[cfg(feature = "band8")]
5328    #[tokio::test]
5329    async fn band8_transaction_rejects_bounded_given_rows_actionably() {
5330        let mut transaction = RuntimeTransaction {
5331            inner: RuntimeTransactionInner::B8(None),
5332            driver_lease: None,
5333        };
5334        let mut consumer = |_item| Ok(RuntimeAnswerControl::Continue);
5335
5336        assert!(!transaction.supports_given_rows());
5337        let error = transaction
5338            .query_with_rows_bounded(
5339                "given $value: string; match $x isa thing;",
5340                empty_given_rows(),
5341                RuntimeAnswerLimits::unbounded(),
5342                &mut consumer,
5343            )
5344            .await
5345            .unwrap_err();
5346
5347        assert!(
5348            matches!(&error, RuntimeError::QueryExecution(message) if message.contains("band-9 driver") && message.contains("band 8")),
5349            "unexpected error: {error}"
5350        );
5351    }
5352
5353    #[cfg(feature = "band9")]
5354    #[test]
5355    fn band9_transaction_reports_given_row_transport_support() {
5356        let transaction = RuntimeTransaction {
5357            inner: RuntimeTransactionInner::B9(None),
5358            driver_lease: None,
5359        };
5360
5361        assert!(transaction.supports_given_rows());
5362    }
5363
5364    #[test]
5365    fn bounded_runtime_reader_rechecks_cancellation_after_consumer_work() {
5366        let cancellation = RuntimeAnswerCancellation::default();
5367        let trigger = cancellation.clone();
5368        let limits = RuntimeAnswerLimits {
5369            max_items: 1,
5370            max_bytes: 64,
5371            deadline: None,
5372            cancellation,
5373        };
5374        let mut stats = RuntimeAnswerStats::new(RuntimeAnswerKind::Rows);
5375        let mut consumer = move |_item| {
5376            trigger.cancel();
5377            Ok(RuntimeAnswerControl::Continue)
5378        };
5379
5380        let error = runtime_accept(
5381            &limits,
5382            &mut stats,
5383            RuntimeAnswerItem::Row(serde_json::json!({"v": 1})),
5384            &mut consumer,
5385        )
5386        .unwrap_err();
5387        assert!(matches!(
5388            error,
5389            RuntimeError::ResourceLimit {
5390                code: "provider_cancelled",
5391                ..
5392            }
5393        ));
5394
5395        let cancellation = RuntimeAnswerCancellation::default();
5396        let trigger = cancellation.clone();
5397        let limits = RuntimeAnswerLimits {
5398            max_items: 1,
5399            max_bytes: 64,
5400            deadline: None,
5401            cancellation,
5402        };
5403        let mut stats = RuntimeAnswerStats::new(RuntimeAnswerKind::Rows);
5404        let mut failing_consumer = move |_item| -> Result<RuntimeAnswerControl> {
5405            trigger.cancel();
5406            Err(RuntimeError::AnswerConsumer)
5407        };
5408        let error = runtime_accept(
5409            &limits,
5410            &mut stats,
5411            RuntimeAnswerItem::Row(serde_json::json!({"v": 1})),
5412            &mut failing_consumer,
5413        )
5414        .unwrap_err();
5415        assert!(matches!(
5416            error,
5417            RuntimeError::ResourceLimit {
5418                code: "provider_cancelled",
5419                ..
5420            }
5421        ));
5422    }
5423
5424    #[test]
5425    fn connect_options_default_matches_ssot() {
5426        let options = ConnectOptions::default();
5427        assert_eq!(options.http_port, DEFAULT_HTTP_PORT);
5428        assert!(!options.tls);
5429        assert_eq!(options.server_version, None);
5430    }
5431
5432    fn test_connection_control(
5433        max_items: u64,
5434        max_bytes: u64,
5435        max_statements: u32,
5436        cancellation: RuntimeAnswerCancellation,
5437    ) -> RuntimeConnectionControl {
5438        RuntimeConnectionControl::new(
5439            max_items,
5440            max_bytes,
5441            max_statements,
5442            Instant::now() + Duration::from_secs(5),
5443            cancellation,
5444        )
5445    }
5446
5447    fn prepared_controlled_probe(
5448        control: RuntimeConnectionControl,
5449    ) -> PreparedSecureConnectOptions {
5450        SecureConnectOptions {
5451            http_port: 8123,
5452            tls_mode: TlsMode::Disabled,
5453            server_version: None,
5454        }
5455        .prepare_transport()
5456        .expect("prepare plaintext test transport")
5457        .with_connection_control(control)
5458    }
5459
5460    #[test]
5461    fn controlled_connection_meter_proves_direct_success_and_fallback_fourth_dispatch_failure() {
5462        let version = core_version::Version::new(3, 12, 1);
5463        let version_bytes = u64::try_from(version.to_string().len()).unwrap();
5464
5465        let mut direct = ConnectionMeter::new(test_connection_control(
5466            1,
5467            version_bytes,
5468            3,
5469            RuntimeAnswerCancellation::default(),
5470        ));
5471        direct.charge_statement().unwrap(); // HTTP version probe
5472        direct.charge_version_evidence(version).unwrap();
5473        direct.charge_statement().unwrap(); // authoritative band-9 constructor
5474        direct.admit_connection().unwrap();
5475        assert_eq!(direct.statements, 2);
5476        assert_eq!(direct.response_bytes, version_bytes);
5477        assert_eq!(direct.admitted_items, 1);
5478
5479        let mut fallback = ConnectionMeter::new(test_connection_control(
5480            1,
5481            version_bytes,
5482            3,
5483            RuntimeAnswerCancellation::default(),
5484        ));
5485        fallback.charge_statement().unwrap(); // failed HTTP version probe
5486        fallback.charge_statement().unwrap(); // band-8 constructor
5487        fallback.charge_statement().unwrap(); // band-8 version dispatch
5488        fallback.charge_version_evidence(version).unwrap();
5489        assert!(matches!(
5490            fallback.charge_statement(), // validated band-9 constructor
5491            Err(RuntimeError::ResourceLimit {
5492                code: "provider_statement_limit",
5493                ..
5494            })
5495        ));
5496        assert_eq!(fallback.statements, 3);
5497        assert_eq!(fallback.response_bytes, version_bytes);
5498        assert_eq!(fallback.admitted_items, 0);
5499
5500        let mut bytes = ConnectionMeter::new(test_connection_control(
5501            1,
5502            version_bytes,
5503            3,
5504            RuntimeAnswerCancellation::default(),
5505        ));
5506        bytes.charge_version_evidence(version).unwrap();
5507        assert!(matches!(
5508            bytes.charge_version_evidence(version),
5509            Err(RuntimeError::ResourceLimit {
5510                code: "response_byte_limit",
5511                ..
5512            })
5513        ));
5514
5515        let mut items = ConnectionMeter::new(test_connection_control(
5516            1,
5517            version_bytes,
5518            3,
5519            RuntimeAnswerCancellation::default(),
5520        ));
5521        items.admit_connection().unwrap();
5522        assert!(matches!(
5523            items.admit_connection(),
5524            Err(RuntimeError::ResourceLimit {
5525                code: "processed_item_limit",
5526                ..
5527            })
5528        ));
5529    }
5530
5531    #[test]
5532    fn legacy_connection_meter_is_an_exact_uncontrolled_adapter() {
5533        let mut meter = ConnectionMeter::legacy();
5534        for _ in 0..16 {
5535            meter.charge_statement().unwrap();
5536            meter
5537                .charge_version_evidence(core_version::Version::new(3, 12, 1))
5538                .unwrap();
5539            meter.admit_connection().unwrap();
5540        }
5541        assert_eq!(meter.statements, 0);
5542        assert_eq!(meter.response_bytes, 0);
5543        assert_eq!(meter.admitted_items, 0);
5544    }
5545
5546    #[tokio::test]
5547    async fn controlled_zero_item_and_statement_ceilings_reject_before_probe_dispatch() {
5548        for (control, expected_code) in [
5549            (
5550                test_connection_control(0, 32, 3, RuntimeAnswerCancellation::default()),
5551                "processed_item_limit",
5552            ),
5553            (
5554                test_connection_control(1, 32, 0, RuntimeAnswerCancellation::default()),
5555                "provider_statement_limit",
5556            ),
5557        ] {
5558            let probe_called = Arc::new(Mutex::new(false));
5559            let captured = Arc::clone(&probe_called);
5560            let error = gated_driver_prepared_with_probe(
5561                "endpoint must not be used",
5562                "credential must not be used",
5563                "credential must not be used",
5564                prepared_controlled_probe(control),
5565                move |_address, _port, _mode| {
5566                    *captured.lock().unwrap() = true;
5567                    Ok(core_version::Version::new(3, 12, 1))
5568                },
5569            )
5570            .await
5571            .err()
5572            .expect("zero applicable ceiling must reject before probe dispatch");
5573
5574            assert!(!*probe_called.lock().unwrap());
5575            assert!(matches!(
5576                error,
5577                SecureConnectError::Runtime(RuntimeError::ResourceLimit { code, .. })
5578                    if code == expected_code
5579            ));
5580        }
5581    }
5582
5583    #[tokio::test]
5584    async fn controlled_probe_bytes_are_bounded_before_driver_construction() {
5585        let probe_called = Arc::new(Mutex::new(false));
5586        let captured = Arc::clone(&probe_called);
5587        let error = gated_driver_prepared_with_probe(
5588            "endpoint must not reach a driver",
5589            "credential must not be used",
5590            "credential must not be used",
5591            prepared_controlled_probe(test_connection_control(
5592                1,
5593                5,
5594                2,
5595                RuntimeAnswerCancellation::default(),
5596            )),
5597            move |_address, _port, _mode| {
5598                *captured.lock().unwrap() = true;
5599                Ok(core_version::Version::new(3, 12, 1))
5600            },
5601        )
5602        .await
5603        .err()
5604        .expect("six retained version bytes must cross a five-byte ceiling");
5605
5606        assert!(*probe_called.lock().unwrap());
5607        assert!(matches!(
5608            error,
5609            SecureConnectError::Runtime(RuntimeError::ResourceLimit {
5610                code: "response_byte_limit",
5611                ..
5612            })
5613        ));
5614    }
5615
5616    #[test]
5617    fn generated_patch_floor_gate_uses_core_admission_and_diagnostics() {
5618        for (profile, observed) in [
5619            (
5620                core_version::TYPEDB_3_12_SEMANTIC_PROFILE_ID,
5621                core_version::Version::new(3, 12, 7),
5622            ),
5623            (
5624                core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID,
5625                core_version::Version::new(3, 13, 9),
5626            ),
5627            (
5628                core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID,
5629                core_version::Version::new(3, 14, 1),
5630            ),
5631            (
5632                core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID,
5633                core_version::Version::new(3, 15, 0),
5634            ),
5635            (
5636                core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID,
5637                core_version::Version::new(4, 0, 0),
5638            ),
5639        ] {
5640            let release = core_version::GeneratedPackageRelease::for_profile(profile).unwrap();
5641            require_generated_server_version(observed, Some(release)).unwrap();
5642            let error = require_generated_server_version(
5643                core_version::Version::new(3, 13, 5),
5644                Some(release),
5645            )
5646            .unwrap_err();
5647            assert!(error.to_string().contains(&release.to_string()));
5648            assert!(
5649                SecureConnectError::Runtime(error)
5650                    .credential_safe_diagnostic()
5651                    .unwrap()
5652                    .contains(&release.to_string())
5653            );
5654        }
5655    }
5656
5657    #[tokio::test]
5658    async fn generated_patch_floor_rejects_after_one_probe_before_driver_construction() {
5659        for (profile, observed, expected) in [
5660            (
5661                core_version::TYPEDB_3_12_SEMANTIC_PROFILE_ID,
5662                core_version::Version::new(3, 12, 0),
5663                core_version::Version::new(3, 12, 3),
5664            ),
5665            // The refusal names the profile's newest admitted release.
5666            (
5667                core_version::TYPEDB_3_13_SEMANTIC_PROFILE_ID,
5668                core_version::Version::new(3, 12, 3),
5669                core_version::Version::new(3, 14, 0),
5670            ),
5671        ] {
5672            let release = core_version::GeneratedPackageRelease::for_profile(profile)
5673                .expect("generated profiles map to measured releases");
5674            let probe_calls = Arc::new(AtomicUsize::new(0));
5675            let observed_calls = Arc::clone(&probe_calls);
5676            let result = gated_driver_prepared_with_probe(
5677                "not a provider endpoint and must not reach address parsing",
5678                "credential must not be used",
5679                "credential must not be used",
5680                prepared_controlled_probe(test_connection_control(
5681                    1,
5682                    32,
5683                    2,
5684                    RuntimeAnswerCancellation::default(),
5685                ))
5686                .with_generated_package_requirement(release),
5687                move |_address, _port, _mode| {
5688                    observed_calls.fetch_add(1, Ordering::AcqRel);
5689                    Ok(observed)
5690                },
5691            )
5692            .await;
5693            let error = match result {
5694                Ok(_) => panic!("a generated {profile} package requires TypeDB {release}"),
5695                Err(error) => error,
5696            };
5697
5698            assert_eq!(probe_calls.load(Ordering::Acquire), 1);
5699            assert!(matches!(
5700                error,
5701                SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
5702                    core_version::VersionError::FeatureUnsupported {
5703                        server,
5704                        required,
5705                        ..
5706                    }
5707                )) if server == observed && required == expected
5708            ));
5709        }
5710    }
5711
5712    #[tokio::test]
5713    async fn controlled_probe_cancellation_wakes_while_blocking_work_is_in_flight() {
5714        let cancellation = RuntimeAnswerCancellation::default();
5715        let prepared =
5716            prepared_controlled_probe(test_connection_control(1, 32, 2, cancellation.clone()));
5717        let (started_sender, started_receiver) = std::sync::mpsc::channel();
5718        let (release_sender, release_receiver) = std::sync::mpsc::channel();
5719        let connection = tokio::spawn(async move {
5720            gated_driver_prepared_with_probe(
5721                "pending endpoint",
5722                "credential",
5723                "credential",
5724                prepared,
5725                move |_address, _port, _mode| {
5726                    started_sender.send(()).unwrap();
5727                    release_receiver.recv().unwrap();
5728                    Err(core_version::VersionProbeError::Probe(
5729                        core_version::VersionError::Probe("released probe".to_owned()),
5730                    ))
5731                },
5732            )
5733            .await
5734        });
5735
5736        tokio::task::spawn_blocking(move || started_receiver.recv().unwrap())
5737            .await
5738            .unwrap();
5739        cancellation.cancel();
5740        let error = tokio::time::timeout(Duration::from_secs(1), connection)
5741            .await
5742            .expect("cancellation must wake the pending connection")
5743            .unwrap()
5744            .err()
5745            .expect("cancelled connection must fail");
5746        release_sender.send(()).unwrap();
5747
5748        assert!(matches!(
5749            error,
5750            SecureConnectError::Runtime(RuntimeError::ResourceLimit {
5751                code: "provider_cancelled",
5752                ..
5753            })
5754        ));
5755    }
5756
5757    #[tokio::test]
5758    async fn completed_provider_outcome_wins_an_already_ready_cancellation_branch() {
5759        let cancellation = RuntimeAnswerCancellation::default();
5760        cancellation.cancel();
5761        let control = test_connection_control(1, 32, 1, cancellation);
5762        assert_eq!(
5763            await_connection_work(std::future::ready(17_u8), Some(&control))
5764                .await
5765                .unwrap(),
5766            17
5767        );
5768    }
5769
5770    #[tokio::test(start_paused = true)]
5771    async fn controlled_deadline_wakes_pending_provider_work() {
5772        let control = RuntimeConnectionControl::new(
5773            1,
5774            32,
5775            1,
5776            Instant::now() + Duration::from_secs(1),
5777            RuntimeAnswerCancellation::default(),
5778        );
5779        let pending = tokio::spawn(async move {
5780            await_connection_work(std::future::pending::<()>(), Some(&control)).await
5781        });
5782        tokio::time::advance(Duration::from_secs(2)).await;
5783        let error = pending
5784            .await
5785            .unwrap()
5786            .expect_err("absolute deadline must wake pending provider work");
5787        assert!(matches!(
5788            error,
5789            RuntimeError::ResourceLimit {
5790                code: "transaction_deadline_exceeded",
5791                ..
5792            }
5793        ));
5794    }
5795
5796    #[test]
5797    fn controlled_connection_errors_drop_provider_endpoint_and_parse_text() {
5798        const SENTINEL: &str = "TB_CONTROLLED_CONNECT_SECRET";
5799        for error in [
5800            SecureConnectError::Runtime(RuntimeError::Connection(SENTINEL.to_owned())),
5801            SecureConnectError::Runtime(RuntimeError::UnsupportedVersion(
5802                core_version::VersionError::Parse(SENTINEL.to_owned()),
5803            )),
5804        ] {
5805            let rendered = controlled_connection_error(error).to_string();
5806            assert!(!rendered.contains(SENTINEL), "{rendered}");
5807        }
5808    }
5809
5810    #[test]
5811    fn released_boolean_options_map_to_the_typed_tls_truth_table() {
5812        let disabled = SecureConnectOptions::from(ConnectOptions {
5813            http_port: 8123,
5814            tls: false,
5815            server_version: Some(core_version::Version::new(3, 11, 5)),
5816        });
5817        assert_eq!(disabled.http_port, 8123);
5818        assert_eq!(disabled.tls_mode, TlsMode::Disabled);
5819        assert_eq!(
5820            disabled.server_version,
5821            Some(core_version::Version::new(3, 11, 5))
5822        );
5823
5824        let native = SecureConnectOptions::from(ConnectOptions {
5825            http_port: 8124,
5826            tls: true,
5827            server_version: None,
5828        });
5829        assert_eq!(native.http_port, 8124);
5830        assert_eq!(native.tls_mode, TlsMode::NativeRoots);
5831        assert_eq!(native.server_version, None);
5832    }
5833
5834    #[test]
5835    fn every_enabled_fallback_band_lowers_to_tls_without_plaintext() {
5836        let disabled = ResolvedTlsMode::from_configured_path(TlsMode::Disabled).unwrap();
5837        assert!(!disabled.probe_mode.is_enabled());
5838        #[cfg(feature = "band8")]
5839        assert!(!disabled.band8.is_enabled());
5840        #[cfg(feature = "band9")]
5841        assert!(!disabled.band9.is_enabled());
5842
5843        let native = ResolvedTlsMode::from_configured_path(TlsMode::NativeRoots).unwrap();
5844        assert!(native.probe_mode.is_enabled());
5845        #[cfg(feature = "band8")]
5846        assert!(native.band8.is_enabled());
5847        #[cfg(feature = "band9")]
5848        assert!(native.band9.is_enabled());
5849
5850        let root_ca = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/root-ca.pem");
5851        let custom =
5852            ResolvedTlsMode::from_configured_path(TlsMode::CustomRootCa(root_ca.clone())).unwrap();
5853        assert!(custom.probe_mode.is_enabled());
5854        #[cfg(any(feature = "band8", feature = "band9"))]
5855        let expected_root = std::fs::read(&root_ca).unwrap();
5856        #[cfg(feature = "band8")]
5857        {
5858            assert!(custom.band8.is_enabled());
5859            assert_eq!(
5860                std::fs::read(custom.band8.root_ca_path().unwrap()).unwrap(),
5861                expected_root
5862            );
5863        }
5864        #[cfg(feature = "band9")]
5865        {
5866            assert!(custom.band9.is_enabled());
5867            assert_eq!(
5868                std::fs::read(custom.band9.root_ca_path().unwrap()).unwrap(),
5869                expected_root
5870            );
5871        }
5872    }
5873
5874    #[test]
5875    fn every_band_lowers_from_retained_material_after_path_replacement() {
5876        let sequence = NEXT_TLS_MATERIAL_TEST_ID.fetch_add(1, Ordering::Relaxed);
5877        let directory = std::env::temp_dir().join(format!(
5878            "type-bridge-runtime-root-replacement-{}-{sequence}",
5879            std::process::id()
5880        ));
5881        std::fs::create_dir(&directory).unwrap();
5882        // load() requires an already-physical path; the ambient temp
5883        // directory may sit behind symlinked components (macOS /var).
5884        let directory = directory.canonicalize().unwrap();
5885        let configured = directory.join("root.pem");
5886        let moved = directory.join("loaded-root.pem");
5887        let original = include_bytes!("../tests/fixtures/root-ca.pem");
5888        std::fs::write(&configured, original).unwrap();
5889
5890        let material = core_version::RetainedCustomRootCa::load(&configured).unwrap();
5891        match std::fs::rename(&configured, &moved) {
5892            Ok(()) => {
5893                std::fs::write(&configured, b"replacement is not a certificate\n").unwrap();
5894            }
5895            Err(_) => {
5896                // Windows' retained no-delete handle makes the replacement
5897                // itself fail closed. It must also prevent an in-place write.
5898                assert!(
5899                    std::fs::write(&configured, b"replacement is not a certificate\n").is_err()
5900                );
5901            }
5902        }
5903
5904        let resolved = ResolvedTlsMode::lower(
5905            TlsMode::CustomRootCa(configured),
5906            ResolvedTlsProbeMode::CustomRootCa(material),
5907        )
5908        .expect("all bands must lower the retained original material");
5909
5910        #[cfg(feature = "band8")]
5911        assert_eq!(
5912            std::fs::read(resolved.band8.root_ca_path().unwrap()).unwrap(),
5913            original
5914        );
5915        #[cfg(feature = "band9")]
5916        assert_eq!(
5917            std::fs::read(resolved.band9.root_ca_path().unwrap()).unwrap(),
5918            original
5919        );
5920
5921        drop(resolved);
5922        std::fs::remove_dir_all(directory).unwrap();
5923    }
5924
5925    #[test]
5926    fn every_band_lowers_from_retained_material_after_parent_swap() {
5927        let sequence = NEXT_TLS_MATERIAL_TEST_ID.fetch_add(1, Ordering::Relaxed);
5928        let root = std::env::temp_dir().join(format!(
5929            "type-bridge-runtime-root-parent-swap-{}-{sequence}",
5930            std::process::id()
5931        ));
5932        std::fs::create_dir(&root).unwrap();
5933        // load() requires an already-physical path; the ambient temp
5934        // directory may sit behind symlinked components (macOS /var).
5935        let root = root.canonicalize().unwrap();
5936        let configured_parent = root.join("configured-parent");
5937        let moved_parent = root.join("loaded-parent");
5938        std::fs::create_dir(&configured_parent).unwrap();
5939        let configured = configured_parent.join("root.pem");
5940        let original = include_bytes!("../tests/fixtures/root-ca.pem");
5941        std::fs::write(&configured, original).unwrap();
5942
5943        let material = core_version::RetainedCustomRootCa::load(&configured).unwrap();
5944        match std::fs::rename(&configured_parent, &moved_parent) {
5945            Ok(()) => {
5946                std::fs::create_dir(&configured_parent).unwrap();
5947                std::fs::write(&configured, b"replacement is not a certificate\n").unwrap();
5948            }
5949            Err(_) => {
5950                // Windows retains the parent without delete sharing, so a
5951                // namespace swap is rejected before any driver lowering.
5952                assert_eq!(std::fs::read(&configured).unwrap(), original);
5953            }
5954        }
5955
5956        let resolved = ResolvedTlsMode::lower(
5957            TlsMode::CustomRootCa(configured),
5958            ResolvedTlsProbeMode::CustomRootCa(material),
5959        )
5960        .expect("all bands must lower the retained parent/file material");
5961
5962        #[cfg(feature = "band8")]
5963        assert_eq!(
5964            std::fs::read(resolved.band8.root_ca_path().unwrap()).unwrap(),
5965            original
5966        );
5967        #[cfg(feature = "band9")]
5968        assert_eq!(
5969            std::fs::read(resolved.band9.root_ca_path().unwrap()).unwrap(),
5970            original
5971        );
5972
5973        drop(resolved);
5974        std::fs::remove_dir_all(root).unwrap();
5975    }
5976
5977    #[test]
5978    fn every_band_lowers_from_snapshot_after_in_place_source_overwrite() {
5979        let sequence = NEXT_TLS_MATERIAL_TEST_ID.fetch_add(1, Ordering::Relaxed);
5980        let directory = std::env::temp_dir().join(format!(
5981            "type-bridge-runtime-root-overwrite-{}-{sequence}",
5982            std::process::id()
5983        ));
5984        std::fs::create_dir(&directory).unwrap();
5985        // load() requires an already-physical path; the ambient temp
5986        // directory may sit behind symlinked components (macOS /var).
5987        let directory = directory.canonicalize().unwrap();
5988        let configured = directory.join("root.pem");
5989        let original = include_bytes!("../tests/fixtures/root-ca.pem");
5990        std::fs::write(&configured, original).unwrap();
5991
5992        let material = core_version::RetainedCustomRootCa::load(&configured).unwrap();
5993        match std::fs::write(&configured, b"overwritten source is not a certificate\n") {
5994            Ok(()) => assert_ne!(std::fs::read(&configured).unwrap(), original),
5995            Err(_) => assert_eq!(std::fs::read(&configured).unwrap(), original),
5996        }
5997
5998        let resolved = ResolvedTlsMode::lower(
5999            TlsMode::CustomRootCa(configured),
6000            ResolvedTlsProbeMode::CustomRootCa(material),
6001        )
6002        .expect("all bands must lower the captured-byte snapshot");
6003
6004        #[cfg(feature = "band8")]
6005        assert_eq!(
6006            std::fs::read(resolved.band8.root_ca_path().unwrap()).unwrap(),
6007            original
6008        );
6009        #[cfg(feature = "band9")]
6010        assert_eq!(
6011            std::fs::read(resolved.band9.root_ca_path().unwrap()).unwrap(),
6012            original
6013        );
6014
6015        drop(resolved);
6016        std::fs::remove_dir_all(directory).unwrap();
6017    }
6018
6019    #[tokio::test]
6020    async fn prepared_transport_never_rereads_mutated_custom_root_path() {
6021        let sequence = NEXT_TLS_MATERIAL_TEST_ID.fetch_add(1, Ordering::Relaxed);
6022        let directory = std::env::temp_dir().join(format!(
6023            "type-bridge-runtime-root-prepared-{}-{sequence}",
6024            std::process::id()
6025        ));
6026        std::fs::create_dir(&directory).unwrap();
6027        let configured = directory.join("root.pem");
6028        let original = include_bytes!("../tests/fixtures/root-ca.pem");
6029        std::fs::write(&configured, original).unwrap();
6030
6031        let prepared = SecureConnectOptions {
6032            http_port: 8123,
6033            tls_mode: TlsMode::CustomRootCa(configured.clone()),
6034            server_version: None,
6035        }
6036        .prepare_transport()
6037        .expect("prepare the complete custom-root transport");
6038
6039        match std::fs::write(&configured, b"mutated after preparation\n") {
6040            Ok(()) => assert_ne!(std::fs::read(&configured).unwrap(), original),
6041            Err(_) => assert_eq!(std::fs::read(&configured).unwrap(), original),
6042        }
6043
6044        #[cfg(feature = "band8")]
6045        assert_eq!(
6046            std::fs::read(prepared.resolved_tls.band8.root_ca_path().unwrap()).unwrap(),
6047            original
6048        );
6049        #[cfg(feature = "band9")]
6050        assert_eq!(
6051            std::fs::read(prepared.resolved_tls.band9.root_ca_path().unwrap()).unwrap(),
6052            original
6053        );
6054
6055        let expected = original.to_vec();
6056        let error = gated_driver_prepared_with_probe(
6057            "host must not be constructed",
6058            "credential must not be used",
6059            "credential must not be used",
6060            prepared
6061                .clone()
6062                .with_connection_control(test_connection_control(
6063                    1,
6064                    32,
6065                    1,
6066                    RuntimeAnswerCancellation::default(),
6067                )),
6068            move |_address, port, mode| {
6069                assert_eq!(port, 8123);
6070                let ResolvedTlsProbeMode::CustomRootCa(material) = mode else {
6071                    panic!("prepared probe must retain custom-root mode");
6072                };
6073                let bytes = material
6074                    .with_driver_root_path(|path| std::fs::read(path))
6075                    .unwrap()
6076                    .unwrap();
6077                assert_eq!(bytes, expected);
6078                Err(core_version::VersionProbeError::TlsConfiguration(
6079                    core_version::TlsConfigurationError::NativeRootsUnavailable,
6080                ))
6081            },
6082        )
6083        .await
6084        .err()
6085        .expect("injected terminal probe error prevents host construction");
6086        assert!(matches!(
6087            error,
6088            SecureConnectError::TlsConfiguration(
6089                core_version::TlsConfigurationError::NativeRootsUnavailable
6090            )
6091        ));
6092
6093        drop(prepared);
6094        std::fs::remove_dir_all(directory).unwrap();
6095    }
6096
6097    #[cfg(unix)]
6098    #[test]
6099    fn binding_transport_resolves_a_raw_alias_without_weakening_physical_paths() {
6100        use std::os::unix::fs::symlink;
6101
6102        let sequence = NEXT_TLS_MATERIAL_TEST_ID.fetch_add(1, Ordering::Relaxed);
6103        let directory = std::env::temp_dir().join(format!(
6104            "type-bridge-runtime-binding-alias-{}-{sequence}",
6105            std::process::id()
6106        ));
6107        std::fs::create_dir(&directory).expect("create binding-alias directory");
6108        let physical_parent = directory.join("physical");
6109        let alias_parent = directory.join("alias");
6110        std::fs::create_dir(&physical_parent).expect("create physical CA parent");
6111        std::fs::write(
6112            physical_parent.join("root.pem"),
6113            include_bytes!("../tests/fixtures/root-ca.pem"),
6114        )
6115        .expect("write binding CA");
6116        symlink(&physical_parent, &alias_parent).expect("create caller path alias");
6117        let configured = alias_parent.join("root.pem");
6118        let options = SecureConnectOptions {
6119            http_port: 8123,
6120            tls_mode: TlsMode::CustomRootCa(configured.clone()),
6121            server_version: None,
6122        };
6123
6124        assert!(matches!(
6125            options.prepare_transport_from_validated_physical_path(),
6126            Err(SecureConnectError::TlsConfiguration(
6127                core_version::TlsConfigurationError::CustomRootCaUnreadable { path }
6128            )) if path == configured
6129        ));
6130        options
6131            .prepare_transport()
6132            .expect("raw binding preparation resolves one caller alias");
6133        std::fs::remove_dir_all(directory).expect("remove binding-alias directory");
6134    }
6135
6136    #[test]
6137    fn public_transport_preflight_returns_typed_errors_without_a_host() {
6138        let missing =
6139            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/does-not-exist.pem");
6140        let options = SecureConnectOptions {
6141            http_port: 8123,
6142            tls_mode: TlsMode::CustomRootCa(missing.clone()),
6143            server_version: Some(core_version::Version::new(3, 11, 5)),
6144        };
6145
6146        let error = options
6147            .validate_transport()
6148            .expect_err("preflight must validate trust material synchronously");
6149        assert_eq!(
6150            error.configuration_code(),
6151            Some("tls_custom_root_ca_unreadable")
6152        );
6153        assert!(matches!(
6154            error,
6155            SecureConnectError::TlsConfiguration(
6156                core_version::TlsConfigurationError::CustomRootCaUnreadable { path }
6157            ) if path == missing
6158        ));
6159    }
6160
6161    #[tokio::test]
6162    async fn invalid_custom_root_is_rejected_before_exact_version_or_probe_io() {
6163        let probe_called = Arc::new(Mutex::new(false));
6164        let captured = Arc::clone(&probe_called);
6165        let missing =
6166            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/does-not-exist.pem");
6167
6168        let error = gated_driver_secure_with_probe(
6169            "invalid host that must not be constructed",
6170            "admin",
6171            "password",
6172            SecureConnectOptions {
6173                http_port: 8123,
6174                tls_mode: TlsMode::CustomRootCa(missing.clone()),
6175                server_version: Some(core_version::Version::new(3, 11, 5)),
6176            },
6177            move |_address, _port, _mode| {
6178                *captured.lock().unwrap() = true;
6179                Ok(core_version::Version::new(3, 11, 5))
6180            },
6181        )
6182        .await
6183        .err()
6184        .expect("invalid custom root must fail before connection construction");
6185
6186        assert!(!*probe_called.lock().unwrap());
6187        assert!(matches!(
6188            error,
6189            SecureConnectError::TlsConfiguration(
6190                core_version::TlsConfigurationError::CustomRootCaUnreadable { path }
6191            ) if path == missing
6192        ));
6193    }
6194
6195    #[tokio::test]
6196    async fn enabled_probe_tls_failure_is_terminal_before_grpc_fallback() {
6197        let error = gated_driver_secure_with_probe(
6198            "127.0.0.1:1",
6199            "admin",
6200            "password",
6201            SecureConnectOptions {
6202                http_port: 8123,
6203                tls_mode: TlsMode::NativeRoots,
6204                server_version: None,
6205            },
6206            |_address, _port, mode| {
6207                assert!(matches!(mode, ResolvedTlsProbeMode::NativeRoots));
6208                Err(core_version::VersionProbeError::TlsConfiguration(
6209                    core_version::TlsConfigurationError::NativeRootsUnavailable,
6210                ))
6211            },
6212        )
6213        .await
6214        .err()
6215        .expect("TLS configuration failure must be terminal");
6216
6217        assert!(matches!(
6218            error,
6219            SecureConnectError::TlsConfiguration(
6220                core_version::TlsConfigurationError::NativeRootsUnavailable
6221            )
6222        ));
6223    }
6224
6225    /// The injectable probe must receive the configured port, not a
6226    /// hardcoded 8000.  The probe returns an in-window version so the gate
6227    /// proceeds to the gRPC connection attempt, which fails with a network
6228    /// error (no server) — the assertion is about the recorded port and
6229    /// that the HTTP failure fallback path was not involved.
6230    #[tokio::test]
6231    async fn gated_driver_probe_receives_configured_port() {
6232        let recorded_port: Arc<Mutex<Option<u16>>> = Arc::new(Mutex::new(None));
6233        let captured = Arc::clone(&recorded_port);
6234
6235        let result = gated_driver_with_probe(
6236            "localhost:1729",
6237            "admin",
6238            "password",
6239            ConnectOptions {
6240                http_port: 9123,
6241                tls: false,
6242                server_version: None,
6243            },
6244            move |_addr, port, _tls| {
6245                *captured.lock().unwrap() = Some(port);
6246                Ok(core_version::Version::new(3, 11, 5))
6247            },
6248        )
6249        .await;
6250
6251        let observed = recorded_port.lock().unwrap().expect("probe was not called");
6252        assert_eq!(
6253            observed, 9123,
6254            "probe must receive the configured http_port (9123), got {observed}"
6255        );
6256
6257        if let Err(RuntimeError::UnsupportedVersion(_)) = result {
6258            panic!("expected a connection error (no server), not a version gate rejection")
6259        }
6260    }
6261
6262    /// When HTTP version detection fails, the constructor attempts the safe
6263    /// band-8 discovery path. If it cannot connect, the error should preserve
6264    /// both the discovery failure and the HTTP failure.
6265    #[tokio::test]
6266    async fn gated_driver_http_failure_reports_grpc_fallback_failures() {
6267        let result = gated_driver_with_probe(
6268            "127.0.0.1:1",
6269            "admin",
6270            "password",
6271            ConnectOptions {
6272                http_port: 9123,
6273                tls: false,
6274                server_version: None,
6275            },
6276            move |_addr, _port, _tls| {
6277                Err(core_version::VersionError::Probe(
6278                    "HTTP version request failed: connection refused or unavailable".to_string(),
6279                ))
6280            },
6281        )
6282        .await;
6283
6284        match result {
6285            Err(RuntimeError::UnsupportedVersion(err)) => {
6286                let msg = err.to_string();
6287                assert!(
6288                    msg.contains("HTTP version probe failed: HTTP version request failed: connection refused or unavailable"),
6289                    "{msg}"
6290                );
6291                assert!(!msg.contains("HTTP endpoint unavailable"), "{msg}");
6292                assert!(!msg.contains("127.0.0.1"), "{msg}");
6293                assert!(msg.contains("band-8 gRPC attempt failed"), "{msg}");
6294                assert!(
6295                    msg.contains("TypeDB transport failed: connection refused or unavailable"),
6296                    "{msg}"
6297                );
6298                // Band 9 must never be probed blindly: a band-9 connect
6299                // attempt crashes a 3.11 server (see grpc_fallback_driver).
6300                assert!(!msg.contains("band-9 gRPC attempt"), "{msg}");
6301            }
6302            Err(other) => panic!("expected aggregated version-probe failure, got {other}"),
6303            Ok(_) => panic!("expected aggregated version-probe failure, got successful connection"),
6304        }
6305    }
6306
6307    #[cfg(feature = "band8")]
6308    #[test]
6309    fn band8_lazy_validation_failure_is_retryable() {
6310        let result = classify_band8_grpc_version(
6311            "localhost:1729",
6312            Err(redact_provider_error(
6313                &driver_b8::Error::Other("protocol handshake failed SECRET_SENTINEL".to_owned()),
6314                "gRPC server version failed",
6315            )),
6316        )
6317        .expect("transport validation failure should remain retryable");
6318
6319        match result {
6320            Band8GrpcVersion::RetryableFailure(failure) => {
6321                assert_eq!(
6322                    failure,
6323                    "band-8 gRPC version validation failed: gRPC server version failed: [UNKNOWN] TypeDB transport failed: other transport"
6324                );
6325            }
6326            Band8GrpcVersion::Validated(version) => {
6327                panic!("failed lazy connection unexpectedly validated as {version}")
6328            }
6329        }
6330    }
6331
6332    #[cfg(feature = "band8")]
6333    #[test]
6334    fn band8_reported_versions_are_authoritative() {
6335        let unsupported = classify_band8_grpc_version("localhost:1729", Ok("3.7.3".to_string()))
6336            .expect_err("reported below-window version must be terminal");
6337        assert!(matches!(
6338            unsupported,
6339            RuntimeError::UnsupportedVersion(core_version::VersionError::Unsupported {
6340                component: "server",
6341                found: core_version::Version {
6342                    major: 3,
6343                    minor: 7,
6344                    patch: 3,
6345                },
6346            })
6347        ));
6348
6349        let retired = classify_band8_grpc_version("localhost:1729", Ok("3.10.4".to_string()))
6350            .expect_err("reported retired server version must not silently fall through");
6351        assert!(matches!(
6352            retired,
6353            RuntimeError::UnsupportedVersion(core_version::VersionError::Unsupported {
6354                component: "server",
6355                found: core_version::Version {
6356                    major: 3,
6357                    minor: 10,
6358                    patch: 4,
6359                },
6360            })
6361        ));
6362
6363        let malformed =
6364            classify_band8_grpc_version("localhost:1729", Ok("not-a-version".to_string()))
6365                .expect_err("malformed reported version must be terminal");
6366        assert!(matches!(
6367            malformed,
6368            RuntimeError::UnsupportedVersion(core_version::VersionError::Parse(_))
6369        ));
6370
6371        let validated = classify_band8_grpc_version("localhost:1729", Ok("3.11.5".to_string()))
6372            .expect("reported band-8 version should validate");
6373        assert!(matches!(
6374            validated,
6375            Band8GrpcVersion::Validated(core_version::Version {
6376                major: 3,
6377                minor: 11,
6378                patch: 5,
6379            })
6380        ));
6381
6382        let backward_compatible =
6383            classify_band8_grpc_version("localhost:1729", Ok("3.12.0".to_string()))
6384                .expect("reported band-9 server accepts the discovery band");
6385        assert!(matches!(
6386            backward_compatible,
6387            Band8GrpcVersion::Validated(core_version::Version {
6388                major: 3,
6389                minor: 12,
6390                patch: 0,
6391            })
6392        ));
6393    }
6394
6395    #[cfg(all(feature = "band8", feature = "band9"))]
6396    #[test]
6397    fn band8_discovery_negotiates_the_accepted_embedded_band() {
6398        for (reported, expected_band) in [
6399            ("3.11.5", 8),
6400            ("3.12.3", 9),
6401            ("3.13.6", 9),
6402            ("3.14.0", 9),
6403            ("3.15.0", 9),
6404            ("4.0.0", 9),
6405        ] {
6406            let Band8GrpcVersion::Validated(version) =
6407                classify_band8_grpc_version("localhost:1729", Ok(reported.to_owned()))
6408                    .expect("supported discovery version must validate")
6409            else {
6410                panic!("authoritative version unexpectedly marked retryable");
6411            };
6412            assert_eq!(validate_server_band(&version).unwrap(), expected_band);
6413        }
6414        assert!(matches!(
6415            classify_band8_grpc_version("localhost:1729", Ok("3.10.4".to_owned())),
6416            Err(RuntimeError::UnsupportedVersion(
6417                core_version::VersionError::Unsupported { .. }
6418            ))
6419        ));
6420    }
6421
6422    #[cfg(all(feature = "band8", not(feature = "band9")))]
6423    #[test]
6424    fn band8_discovery_refuses_a_server_requiring_an_unembedded_band() {
6425        assert!(matches!(
6426            classify_band8_grpc_version("localhost:1729", Ok("3.13.6".to_owned())),
6427            Err(RuntimeError::UnsupportedVersion(_))
6428        ));
6429    }
6430
6431    /// A caller-supplied exact server version is the gRPC-only escape hatch: it
6432    /// must bypass the HTTP probe but still flow through the normal embedded
6433    /// runtime gate before driver construction.
6434    #[tokio::test]
6435    async fn gated_driver_pinned_version_skips_probe() {
6436        let probe_called = Arc::new(Mutex::new(false));
6437        let captured = Arc::clone(&probe_called);
6438
6439        let result = gated_driver_with_probe(
6440            "localhost:1729",
6441            "admin",
6442            "password",
6443            ConnectOptions {
6444                http_port: 9123,
6445                tls: false,
6446                server_version: Some(core_version::Version::new(3, 11, 5)),
6447            },
6448            move |_addr, _port, _tls| {
6449                *captured.lock().unwrap() = true;
6450                Ok(core_version::Version::new(3, 11, 5))
6451            },
6452        )
6453        .await;
6454
6455        assert!(
6456            !*probe_called.lock().unwrap(),
6457            "pinned server_version must skip the HTTP probe"
6458        );
6459
6460        if let Err(RuntimeError::UnsupportedVersion(_)) = result {
6461            panic!("expected a connection error (no server), not a version gate rejection")
6462        }
6463    }
6464
6465    /// Pinned versions still use the exact semantic version gate, so a gRPC-only
6466    /// path cannot silently accept an unsupported server.
6467    #[tokio::test]
6468    async fn gated_driver_rejects_unsupported_pinned_version_without_probe() {
6469        let probe_called = Arc::new(Mutex::new(false));
6470        let captured = Arc::clone(&probe_called);
6471
6472        let result = gated_driver_with_probe(
6473            "localhost:1729",
6474            "admin",
6475            "password",
6476            ConnectOptions {
6477                http_port: 9123,
6478                tls: false,
6479                server_version: Some(core_version::Version::new(3, 7, 3)),
6480            },
6481            move |_addr, _port, _tls| {
6482                *captured.lock().unwrap() = true;
6483                Ok(core_version::Version::new(3, 11, 5))
6484            },
6485        )
6486        .await;
6487
6488        assert!(
6489            !*probe_called.lock().unwrap(),
6490            "unsupported pinned server_version must skip the HTTP probe"
6491        );
6492
6493        match result {
6494            Err(RuntimeError::UnsupportedVersion(err)) => {
6495                assert!(
6496                    err.to_string().contains("3.7.3"),
6497                    "error should name rejected version: {err}"
6498                );
6499            }
6500            Err(other) => panic!("expected unsupported-version rejection for 3.7.3, got {other}"),
6501            Ok(_) => panic!(
6502                "expected unsupported-version rejection for 3.7.3, got successful connection"
6503            ),
6504        }
6505    }
6506
6507    #[test]
6508    fn cargo_lock_pin() {
6509        let lock_path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../Cargo.lock");
6510        let lock_contents = std::fs::read_to_string(lock_path)
6511            .expect("Cargo.lock not found relative to crate root");
6512
6513        let lock_version = lock_contents
6514            .split("[[package]]")
6515            .find(|block| block.contains("name = \"type-bridge-typedb-driver-b8\""))
6516            .and_then(|block| {
6517                block
6518                    .lines()
6519                    .find(|line| line.trim_start().starts_with("version = "))
6520            })
6521            .and_then(|line| {
6522                let start = line.find('"')? + 1;
6523                let end = line.rfind('"')?;
6524                Some(&line[start..end])
6525            })
6526            .expect("type-bridge-typedb-driver-b8 entry not found in Cargo.lock");
6527
6528        assert_eq!(
6529            lock_version, PINNED_DRIVER_VERSION,
6530            "Cargo.lock resolves type-bridge-typedb-driver-b8 {lock_version} but \
6531             PINNED_DRIVER_VERSION \
6532             is {PINNED_DRIVER_VERSION}; update the runtime constant"
6533        );
6534
6535        let pinned: core_version::Version = PINNED_DRIVER_VERSION.parse().unwrap();
6536        assert_eq!(
6537            core_version::band(&pinned),
6538            Some(8),
6539            "pinned driver version {PINNED_DRIVER_VERSION} left protocol band 8; \
6540             review the gate expectations before accepting the bump"
6541        );
6542    }
6543
6544    /// Portable given-rows lower onto the band-9 driver structures, including
6545    /// temporal string parsing; malformed rows fail before any wire I/O.
6546    #[cfg(feature = "band9")]
6547    #[test]
6548    fn given_rows_lowering() {
6549        let spec = GivenRowsSpec {
6550            variables: vec!["n".into(), "a".into()],
6551            rows: vec![
6552                vec![GivenValue::String("alice".into()), GivenValue::Integer(28)],
6553                vec![GivenValue::String("bob".into()), GivenValue::Integer(26)],
6554            ],
6555        };
6556        let rows = given_rows_b9(spec).expect("valid spec must lower");
6557        let (header, rows) = rows.into_parts();
6558        assert_eq!(header.width(), 2);
6559        assert_eq!(rows.len(), 2);
6560    }
6561
6562    #[cfg(feature = "band9")]
6563    #[test]
6564    fn given_rows_lowering_rejects_width_mismatch() {
6565        let spec = GivenRowsSpec {
6566            variables: vec!["n".into(), "a".into()],
6567            rows: vec![vec![GivenValue::String("alice".into())]],
6568        };
6569        let err = given_rows_b9(spec).expect_err("short row must be rejected");
6570        assert!(matches!(err, RuntimeError::QueryExecution(_)), "{err}");
6571    }
6572
6573    #[cfg(feature = "band9")]
6574    #[test]
6575    fn given_entry_temporal_parsing() {
6576        for value in [
6577            GivenValue::Empty,
6578            GivenValue::Date("2026-07-13".into()),
6579            GivenValue::Datetime("2026-07-13T10:30:00".into()),
6580            GivenValue::DatetimeTz("2026-07-13T10:30:00+09:00".into()),
6581            GivenValue::DatetimeTz("2026-07-13T10:30:00+00:19:32".into()),
6582            GivenValue::DatetimeTzExact {
6583                local: "2024-10-27T01:30:00".into(),
6584                named_zone: Some("Europe/London".into()),
6585                effective_offset_seconds: 3_600,
6586            },
6587            GivenValue::DatetimeTzExact {
6588                local: "2024-07-01T12:00:00".into(),
6589                named_zone: Some("europe/amsterdam".into()),
6590                effective_offset_seconds: 7_200,
6591            },
6592            GivenValue::DatetimeTzExact {
6593                local: "1900-01-01T12:00:00".into(),
6594                named_zone: None,
6595                effective_offset_seconds: 1_172,
6596            },
6597            GivenValue::Decimal("12.30dec".into()),
6598            GivenValue::Decimal("-9223372036854775808".into()),
6599            GivenValue::Duration {
6600                months: u32::MAX,
6601                days: u32::MAX,
6602                nanos: u64::MAX,
6603            },
6604            GivenValue::Boolean(true),
6605            GivenValue::Double(1.5),
6606        ] {
6607            given_entry_b9("test_input", value.clone())
6608                .unwrap_or_else(|e| panic!("{value:?} must convert: {e}"));
6609        }
6610    }
6611
6612    #[cfg(feature = "band9")]
6613    #[test]
6614    fn exact_given_entries_preserve_named_timezone_and_duration_components() {
6615        use typedb_driver::concept::Value;
6616        use typedb_driver::concept::value::TimeZone;
6617        use typedb_driver::given::GivenRowEntry;
6618
6619        let named = given_entry_b9(
6620            "test_input",
6621            GivenValue::DatetimeTzExact {
6622                local: "2024-10-27T01:30:00".into(),
6623                named_zone: Some("Europe/London".into()),
6624                effective_offset_seconds: 3_600,
6625            },
6626        )
6627        .expect("explicit overlap side");
6628        let GivenRowEntry::Value(Value::DatetimeTZ(named)) = named else {
6629            panic!("datetime-tz given entry")
6630        };
6631        let TimeZone::IANA(timezone) = named.timezone() else {
6632            panic!("authored IANA identity must survive transport")
6633        };
6634        assert_eq!(timezone.name(), "Europe/London");
6635        assert_eq!(named.naive_local().to_string(), "2024-10-27 01:30:00");
6636        assert_eq!(
6637            named
6638                .naive_local()
6639                .signed_duration_since(named.naive_utc())
6640                .num_seconds(),
6641            3_600
6642        );
6643
6644        let lower_case = given_entry_b9(
6645            "test_input",
6646            GivenValue::DatetimeTzExact {
6647                local: "2024-07-01T12:00:00".into(),
6648                named_zone: Some("europe/amsterdam".into()),
6649                effective_offset_seconds: 7_200,
6650            },
6651        )
6652        .expect("case-insensitive names admitted by schema also lower");
6653        let GivenRowEntry::Value(Value::DatetimeTZ(lower_case)) = lower_case else {
6654            panic!("datetime-tz given entry")
6655        };
6656        let TimeZone::IANA(timezone) = lower_case.timezone() else {
6657            panic!("IANA identity must survive transport")
6658        };
6659        assert_eq!(
6660            timezone.name(),
6661            "Europe/Amsterdam",
6662            "the provider canonicalizes accepted authored case"
6663        );
6664
6665        let duration = given_entry_b9(
6666            "test_input",
6667            GivenValue::Duration {
6668                months: u32::MAX,
6669                days: u32::MAX,
6670                nanos: u64::MAX,
6671            },
6672        )
6673        .expect("duration boundary");
6674        let GivenRowEntry::Value(Value::Duration(duration)) = duration else {
6675            panic!("duration given entry")
6676        };
6677        assert_eq!(duration.months, u32::MAX);
6678        assert_eq!(duration.days, u32::MAX);
6679        assert_eq!(duration.nanos, u64::MAX);
6680    }
6681
6682    #[cfg(feature = "band9")]
6683    #[test]
6684    fn given_entry_rejects_malformed_temporal() {
6685        for value in [
6686            GivenValue::Date("not-a-date".into()),
6687            GivenValue::Datetime("2026-13-45T99:00:00".into()),
6688            GivenValue::DatetimeTz("2026-07-13 10:30".into()),
6689            GivenValue::DatetimeTz("2026-07-13T10:30:00+24:00".into()),
6690            GivenValue::DatetimeTzExact {
6691                local: "2024-10-27T01:30:00".into(),
6692                named_zone: Some("Europe/London".into()),
6693                effective_offset_seconds: 7_200,
6694            },
6695            GivenValue::DatetimeTzExact {
6696                local: "2024-03-31T01:30:00".into(),
6697                named_zone: Some("Europe/London".into()),
6698                effective_offset_seconds: 3_600,
6699            },
6700            GivenValue::Decimal("1.00000000000000000000".into()),
6701        ] {
6702            let err = given_entry_b9("test_input", value.clone())
6703                .expect_err("malformed temporal string must be rejected");
6704            assert!(
6705                err.to_string().contains("Invalid given"),
6706                "{value:?}: {err}"
6707            );
6708        }
6709    }
6710
6711    #[cfg(feature = "band9")]
6712    #[test]
6713    fn given_conversion_errors_identify_column_and_type_without_values() {
6714        let secret = "private-input-sentinel";
6715        for (value, kind) in [
6716            (GivenValue::Date(secret.into()), "date"),
6717            (GivenValue::Datetime(secret.into()), "datetime"),
6718            (GivenValue::DatetimeTz(secret.into()), "datetime-tz"),
6719            (GivenValue::Decimal(secret.into()), "decimal"),
6720            (
6721                GivenValue::DatetimeTzExact {
6722                    local: secret.into(),
6723                    named_zone: None,
6724                    effective_offset_seconds: 0,
6725                },
6726                "datetime-tz",
6727            ),
6728            (
6729                GivenValue::DatetimeTzExact {
6730                    local: "2024-07-01T12:00:00".into(),
6731                    named_zone: Some(secret.into()),
6732                    effective_offset_seconds: 0,
6733                },
6734                "datetime-tz",
6735            ),
6736        ] {
6737            let error = given_rows_b9(GivenRowsSpec {
6738                variables: vec!["valid_column".into(), "birth_date".into()],
6739                rows: vec![vec![GivenValue::Integer(1), value]],
6740            })
6741            .expect_err("invalid second column");
6742            assert_eq!(
6743                error.to_string(),
6744                format!("Query execution error: Invalid given {kind} in column \"birth_date\"")
6745            );
6746            assert!(!format!("{error:?}").contains(secret));
6747            assert!(std::error::Error::source(&error).is_none());
6748        }
6749    }
6750
6751    #[cfg(feature = "band9")]
6752    #[test]
6753    fn given_row_width_errors_do_not_expose_or_ignore_extra_values() {
6754        for row in [
6755            vec![],
6756            vec![
6757                GivenValue::Integer(1),
6758                GivenValue::Date("private-input-sentinel".into()),
6759            ],
6760        ] {
6761            let error = given_rows_b9(GivenRowsSpec {
6762                variables: vec!["column".into()],
6763                rows: vec![row],
6764            })
6765            .expect_err("row width must match headers");
6766            assert_eq!(
6767                error.to_string(),
6768                "Query execution error: Invalid given row: width does not match the column header"
6769            );
6770            assert!(!format!("{error:?}").contains("private-input-sentinel"));
6771        }
6772    }
6773
6774    #[test]
6775    fn cargo_lock_pin_b9() {
6776        let lock_path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../Cargo.lock");
6777        let lock_contents = std::fs::read_to_string(lock_path)
6778            .expect("Cargo.lock not found relative to crate root");
6779
6780        let lock_version = lock_contents
6781            .split("[[package]]")
6782            .find(|block| block.contains("name = \"typedb-driver\""))
6783            .and_then(|block| {
6784                block
6785                    .lines()
6786                    .find(|line| line.trim_start().starts_with("version = "))
6787            })
6788            .and_then(|line| {
6789                let start = line.find('"')? + 1;
6790                let end = line.rfind('"')?;
6791                Some(&line[start..end])
6792            })
6793            .expect("typedb-driver entry not found in Cargo.lock");
6794
6795        assert_eq!(
6796            lock_version, PINNED_DRIVER_VERSION_B9,
6797            "Cargo.lock resolves typedb-driver {lock_version} but \
6798             PINNED_DRIVER_VERSION_B9 is {PINNED_DRIVER_VERSION_B9}; update the runtime constant"
6799        );
6800
6801        // The driver line may run ahead of the window (it speaks band 9 to the
6802        // window's newest line) but must never fall behind it.
6803        let pinned: core_version::Version = PINNED_DRIVER_VERSION_B9.parse().unwrap();
6804        let (top_major, top_minor) = core_version::MAX_SUPPORTED_LINE;
6805        assert_eq!(
6806            core_version::band(&core_version::Version::new(top_major, top_minor, 0)),
6807            Some(9),
6808            "the window's newest line no longer negotiates band 9; \
6809             review the band-9 driver pin"
6810        );
6811        assert!(
6812            pinned.major == top_major && pinned.minor >= top_minor,
6813            "pinned band-9 driver version {PINNED_DRIVER_VERSION_B9} is behind the \
6814             window's newest line {top_major}.{top_minor}; review the gate expectations \
6815             before accepting the bump"
6816        );
6817    }
6818
6819    #[test]
6820    fn materialize_runtime_answer_preserves_empty_kinds() {
6821        let stats = |kind| RuntimeAnswerStats {
6822            kind,
6823            processed_items: 0,
6824            response_bytes: 0,
6825            stopped_early: false,
6826        };
6827        assert!(matches!(
6828            super::materialize_runtime_answer(stats(RuntimeAnswerKind::Ok), Vec::new()),
6829            QueryResult::Ok
6830        ));
6831        assert!(matches!(
6832            super::materialize_runtime_answer(stats(RuntimeAnswerKind::Rows), Vec::new()),
6833            QueryResult::Rows(values) if values.is_empty()
6834        ));
6835        assert!(matches!(
6836            super::materialize_runtime_answer(stats(RuntimeAnswerKind::Documents), Vec::new()),
6837            QueryResult::Documents(values) if values.is_empty()
6838        ));
6839    }
6840
6841    #[test]
6842    fn canonical_decimal_text_normalizes_provider_display() {
6843        assert_eq!(
6844            super::canonical_decimal_text("001234.5600dec".into()).unwrap(),
6845            "1234.56"
6846        );
6847        assert_eq!(
6848            super::canonical_decimal_text("-0.000dec".into()).unwrap(),
6849            "0"
6850        );
6851        assert_eq!(
6852            super::canonical_decimal_text("-9223372036854775808dec".into()).unwrap(),
6853            "-9223372036854775808"
6854        );
6855        assert!(matches!(
6856            super::canonical_decimal_text("not-a-decimal".into()),
6857            Err(RuntimeError::QueryExecution(message)) if message == "provider returned an unparseable decimal"
6858        ));
6859    }
6860}
6861
6862#[cfg(test)]
6863mod fixed_transport_control_tests {
6864    use super::*;
6865
6866    #[test]
6867    fn controlled_connections_keep_only_complete_owned_diagnoses() {
6868        let message =
6869            "Failed to connect: [CXN20] TypeDB transport failed: connection refused or unavailable";
6870        let error = controlled_connection_error(SecureConnectError::Runtime(
6871            RuntimeError::Connection(message.to_owned()),
6872        ));
6873        assert_eq!(error.to_string(), format!("Connection error: {message}"));
6874        assert_eq!(error.credential_safe_diagnostic(), Some(error.to_string()));
6875        let aggregate = format!(
6876            "HTTP version probe and gRPC fallback both failed: HTTP version probe failed: HTTP version request failed: TLS/certificate failure; band-8 gRPC attempt failed: Connection error: {message}"
6877        );
6878        let error = controlled_connection_error(SecureConnectError::Runtime(
6879            RuntimeError::UnsupportedVersion(core_version::VersionError::Probe(aggregate.clone())),
6880        ));
6881        assert!(error.to_string().contains(&aggregate));
6882        assert_eq!(error.credential_safe_diagnostic(), Some(error.to_string()));
6883        let forged = format!("{message} SECRET_SENTINEL");
6884        let error = controlled_connection_error(SecureConnectError::Runtime(
6885            RuntimeError::Connection(forged),
6886        ));
6887        assert!(!error.to_string().contains("SECRET_SENTINEL"));
6888    }
6889}