Skip to main content

oraclemcp_driver_cx/
lib.rs

1// Unit-test assertions intentionally panic on invariant violations.
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3
4//! A pure-Rust, thin-mode driver for Oracle Database.
5//!
6//! `oraclemcp-driver-cx` speaks the Oracle TNS/TTC wire protocol directly over
7//! TCP. It
8//! needs no Oracle Instant Client, no OCI libraries, and no C toolchain: add
9//! the crate, point it at a listener, and connect. The driver is a faithful
10//! port of the python-oracledb thin client, so its behavior tracks that
11//! reference implementation.
12//!
13//! # Why thin mode
14//!
15//! A traditional OCI-based client links a large native library and inherits
16//! whatever identity the OS hands it. Because this driver builds every packet
17//! itself, the application controls the full connection envelope, including the
18//! session identity the database records.
19//!
20//! # Caller-set identity (the differentiator)
21//!
22//! Every connection carries a [`ClientIdentity`] the
23//! caller supplies: `program`, `machine`, `osuser`, and `terminal`. The
24//! database stores those exact values in `v$session`. An OCI client reports the
25//! host process and OS user it happens to run as; here the application decides.
26//! This is invaluable for multi-tenant services and connection multiplexers
27//! that need each logical user attributed correctly in the DBA's session views,
28//! audit trail, and resource-manager rules.
29//!
30//! ```no_run
31//! use oraclemcp_driver_cx::{BlockingConnection, ConnectOptions};
32//! use oraclemcp_driver_cx::protocol::ClientIdentity;
33//!
34//! # fn main() -> Result<(), oraclemcp_driver_cx::Error> {
35//! // The identity the database will record for this session.
36//! let identity = ClientIdentity::new(
37//!     "billing-worker", // program
38//!     "edge-pod-7",     // machine
39//!     "tenant-42",      // osuser
40//!     "shard-a",        // terminal
41//!     "rust-oracledb",  // driver name
42//! )?;
43//!
44//! let options = ConnectOptions::new(
45//!     "dbhost:1521/FREEPDB1", // EasyConnect string
46//!     "app_user",
47//!     "app_password",
48//!     identity,
49//! );
50//!
51//! let mut conn = BlockingConnection::connect(options)?;
52//!
53//! // Bind parameters positionally (:1, :2, ...) as a tuple.
54//! let row = BlockingConnection::query_one(
55//!     &mut conn,
56//!     "select :1 + :2 from dual",
57//!     (40, 2),
58//! )?;
59//!
60//! // Typed column access converts the Oracle NUMBER straight into an integer.
61//! let sum: i64 = row.get(0)?;
62//! assert_eq!(sum, 42);
63//!
64//! BlockingConnection::close(conn)?;
65//! # Ok(())
66//! # }
67//! ```
68//!
69//! # Choosing an API surface
70//!
71//! Two equivalent surfaces are exposed:
72//!
73//! - [`BlockingConnection`] runs each operation on a private single-threaded
74//!   runtime and blocks the calling thread. Use it from synchronous code; it is
75//!   the simplest way to use the driver as a library.
76//! - [`Connection`] is the native asynchronous API. Every method takes an
77//!   `&Cx` (the Asupersync request context) so the work participates in
78//!   structured concurrency and cancellation. Use it inside an Asupersync
79//!   runtime.
80//!
81//! `BlockingConnection` is a thin shim over `Connection`: it owns a
82//! [`Connection`] and drives the async methods to completion.
83//!
84//! # Working with values
85//!
86//! Fetched cells are [`QueryValue`](protocol::thin::QueryValue), a sum type
87//! over every Oracle scalar (NUMBER carried as lossless text, VARCHAR2, DATE /
88//! TIMESTAMP, RAW, ROWID, BOOLEAN, BINARY_DOUBLE, VECTOR, JSON, LOB locators,
89//! object images, ...). Convenience accessors
90//! ([`as_i64`](protocol::thin::QueryValue::as_i64),
91//! [`as_text`](protocol::thin::QueryValue::as_text),
92//! [`as_f64`](protocol::thin::QueryValue::as_f64), and friends) and
93//! [`QueryResult::cell`](protocol::thin::QueryResult::cell) cover the common
94//! cases without an explicit `match`.
95//!
96//! Columns that stream their value through a client-side define (`CLOB`,
97//! `BLOB`, `VECTOR`, native `JSON`) come back from a plain
98//! [`Connection::execute_raw`] as describe-only metadata with a `None` cell,
99//! matching the wire protocol. Use
100//! [`Connection::define_and_fetch_rows_with_columns`] after opening the cursor
101//! when you need the first batch materialized explicitly.
102//!
103//! # Optional features
104//!
105//! - `arrow`: fetch result sets directly into Apache Arrow `RecordBatch`es via
106//!   `Connection::fetch_all_record_batch` and
107//!   `Connection::fetch_record_batches`.
108//!
109//! # Connection pooling
110//!
111//! The [`pool`] module provides async [`Pool`](pool::Pool) and
112//! [`BlockingPool`](pool::BlockingPool) facades that mirror python-oracledb's
113//! thin pool: free/busy lists, growth planning, getmode semantics, ping policy,
114//! idle timeout, and max lifetime. The pool is generic over a
115//! [`PoolBackend`](pool::PoolBackend) so the embedder supplies how a pooled
116//! connection is created, pinged, and closed.
117#![forbid(unsafe_code)]
118
119use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
120use std::future::Future;
121use std::num::NonZeroU32;
122use std::process;
123use std::sync::Arc;
124use std::time::Duration;
125
126use asupersync::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
127use asupersync::net::TcpStream;
128use asupersync::runtime::{reactor, Runtime, RuntimeBuilder};
129use asupersync::sync::Mutex as AsyncMutex;
130use asupersync::{time, Cx};
131use oracledb_protocol::thin::aq::{
132    build_aq_array_deq_payload, build_aq_array_enq_payload, build_aq_deq_payload,
133    build_aq_enq_payload, parse_aq_array_response_with_limits, parse_aq_deq_response_with_limits,
134    parse_aq_enq_response_with_limits, AqArrayResult, AqDeqOptions, AqDeqResult, AqEnqOptions,
135    AqMsgProps, AqQueueDesc,
136};
137use oracledb_protocol::thin::{
138    adjust_refetch_metadata, build_auth_phase_one_payload,
139    build_auth_phase_two_payload_with_proxy_with_seq,
140    build_auth_phase_two_token_payload_with_pop_and_proxy, build_begin_pipeline_piggyback,
141    build_change_password_payload_with_seq, build_connect_packet_payload, build_data_types_payload,
142    build_define_fetch_payload_with_seq, build_end_pipeline_payload_with_seq,
143    build_execute_payload_with_bind_rows_and_options_with_seq, build_fast_auth_phase_one_payload,
144    build_fast_auth_token_payload_with_pop_and_proxy, build_fetch_payload_with_seq,
145    build_function_payload_with_seq, build_function_payload_with_seq_and_token,
146    build_lob_create_temp_payload_with_seq, build_lob_free_temp_payload_with_seq,
147    build_lob_read_payload_with_seq, build_lob_trim_payload_with_seq,
148    build_lob_write_payload_with_seq, build_protocol_negotiation_payload,
149    classic_connect_response_is_complete, connect_data_fits_inline, parse_accept_payload,
150    parse_auth_response_with_limits, parse_define_fetch_response_borrowed_with_limits,
151    parse_define_fetch_response_with_context_and_limits,
152    parse_fetch_response_with_context_and_limits, parse_lob_create_temp_response_with_limits,
153    parse_lob_free_temp_response_with_limits, parse_lob_read_response_with_limits,
154    parse_lob_trim_response_with_limits, parse_lob_write_response_with_limits,
155    parse_plain_function_response_with_limits, parse_query_response_borrowed_with_limits,
156    parse_query_response_with_binds_options_columns_and_limits,
157    parse_tpc_txn_switch_response_with_limits, AuthResponse, BindValue, BorrowedFetchResult,
158    ClientCapabilities, ColumnMetadata, CursorValue, ExecuteOptions, LobReadResult, QueryResult,
159    QueryValueRef, SessionlessTxnState, TokenPop, TpcChangeStateResponse, TpcSwitchResponse,
160    TpcXid, TNS_DATA_FLAGS_BEGIN_PIPELINE, TNS_DATA_FLAGS_END_OF_REQUEST, TNS_FUNC_COMMIT,
161    TNS_FUNC_LOGOFF, TNS_FUNC_PING, TNS_FUNC_ROLLBACK, TNS_MSG_TYPE_END_OF_RESPONSE,
162    TNS_MSG_TYPE_FLUSH_OUT_BINDS, TNS_PACKET_FLAG_REDIRECT, TNS_PACKET_TYPE_ACCEPT,
163    TNS_PACKET_TYPE_CONNECT, TNS_PACKET_TYPE_DATA, TNS_PACKET_TYPE_REDIRECT,
164    TNS_PACKET_TYPE_REFUSE, TNS_PACKET_TYPE_RESEND, TNS_PIPELINE_MODE_ABORT_ON_ERROR,
165    TNS_PIPELINE_MODE_CONTINUE_ON_ERROR, TNS_TPC_TXN_ABORT, TNS_TPC_TXN_COMMIT, TNS_TPC_TXN_DETACH,
166    TNS_TPC_TXN_POST_DETACH, TNS_TPC_TXN_PREPARE, TNS_TPC_TXN_START, TNS_TPC_TXN_STATE_ABORTED,
167    TNS_TPC_TXN_STATE_COMMITTED, TNS_TPC_TXN_STATE_FORGOTTEN, TNS_TPC_TXN_STATE_PREPARE,
168    TNS_TPC_TXN_STATE_READ_ONLY, TNS_TPC_TXN_STATE_REQUIRES_COMMIT, TPC_TXN_FLAGS_NEW,
169    TPC_TXN_FLAGS_RESUME, TPC_TXN_FLAGS_SESSIONLESS,
170};
171use oracledb_protocol::thin::{
172    build_notify_payload_with_seq, build_subscribe_payload_with_seq,
173    check_notification_header_with_limits, parse_subscribe_response_with_limits,
174    try_parse_oac_record_with_limits, NotificationRecord, SubscribeResult, TNS_SUBSCR_OP_REGISTER,
175    TNS_SUBSCR_OP_UNREGISTER,
176};
177use oracledb_protocol::thin::{
178    build_sessionless_piggyback, build_tpc_change_state_payload_with_seq_and_version,
179    build_tpc_switch_payload_with_seq_and_version, build_tpc_txn_switch_payload_with_seq,
180    parse_tpc_change_state_response_with_limits, parse_tpc_switch_response_with_limits,
181};
182use oracledb_protocol::thin::{TNS_AQ_ARRAY_DEQ, TNS_AQ_ARRAY_ENQ};
183use oracledb_protocol::wire::{encode_packet, PacketLengthWidth, ProtocolLimits};
184use oracledb_protocol::{
185    net::{
186        connectstring::{
187            Address, AddressList, Description, Descriptor, DEFAULT_SDU as DSN_DEFAULT_SDU,
188        },
189        EasyConnect, Protocol as NetProtocol,
190    },
191    ClientIdentity,
192};
193
194const PYTHON_ORACLEDB_COMPAT_VERSION_NUM: u32 = 0x0400_1000;
195const DEFAULT_SDU: usize = 8192;
196
197/// Upper bound on server-requested CONNECT resends before giving up. A real
198/// server asks once (pre-23ai, long connect data); the bound only guards
199/// against a peer that never stops answering RESEND.
200const MAX_CONNECT_RESEND_ROUNDS: u8 = 8;
201
202/// Upper bound on listener REDIRECT hops before giving up. A real redirect
203/// chain is one hop (shared server / RAC dispatcher); the reference does not
204/// bound the loop, but a pair of misconfigured listeners redirecting to each
205/// other must terminate here instead of spinning forever.
206const MAX_CONNECT_REDIRECT_ROUNDS: u8 = 8;
207
208/// Human name for a TNS network packet type, for connect-phase diagnostics.
209/// These are packet-layer types (header offset 4), not TTC message types.
210fn tns_packet_type_name(packet_type: u8) -> &'static str {
211    match packet_type {
212        1 => "CONNECT",
213        2 => "ACCEPT",
214        3 => "ACK",
215        4 => "REFUSE",
216        5 => "REDIRECT",
217        6 => "DATA",
218        7 => "NULL",
219        9 => "ABORT",
220        11 => "RESEND",
221        12 => "MARKER",
222        13 => "ATTENTION",
223        14 => "CONTROL",
224        _ => "unknown",
225    }
226}
227const TNS_DATA_PACKET_OVERHEAD: usize = 10;
228
229pub use oracledb_protocol as protocol;
230
231/// The version of this driver crate, supplied by Cargo at build time.
232///
233/// Consumers that wrap the driver (for example `oraclemcp-db`'s `doctor`) must
234/// report the *driver's* real version, not their own: `env!("CARGO_PKG_VERSION")`
235/// evaluated inside a wrapping crate resolves to that wrapper's version. This
236/// const is evaluated in the driver crate, so it always reflects the actual
237/// `oracledb` version the wrapper is linked against.
238pub const VERSION: &str = env!("CARGO_PKG_VERSION");
239
240/// Profiling-only read/decode attribution counters for the fetch paging loop.
241///
242/// **This is measurement-only instrumentation, not part of the optimization.**
243/// When the `ORACLEDB_PROFILE_FETCH` environment variable is set (checked once,
244/// lazily), [`fetch_rows_with_columns`](Connection::fetch_rows_with_columns)
245/// accumulates the wall time spent in the socket read (`read_response`) vs the
246/// CPU decode (`parse_fetch_response`) into these atomics. A bench / example can
247/// read the split with [`fetch_profile_read_decode_ns`] to attribute how much of
248/// a paged fetch is socket-bound (overlap candidate) vs CPU-bound. The flag is
249/// off by default, so the production path pays one relaxed atomic load per page
250/// and nothing else.
251mod fetch_profile {
252    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
253    use std::sync::OnceLock;
254
255    static READ_NS: AtomicU64 = AtomicU64::new(0);
256    static DECODE_NS: AtomicU64 = AtomicU64::new(0);
257    static ENABLED: OnceLock<bool> = OnceLock::new();
258    /// Lets a bench arm/disarm attribution without an env var (so a single
259    /// process can measure a clean window).
260    static FORCE: AtomicBool = AtomicBool::new(false);
261
262    #[inline]
263    pub(crate) fn enabled() -> bool {
264        FORCE.load(Ordering::Relaxed)
265            || *ENABLED.get_or_init(|| std::env::var_os("ORACLEDB_PROFILE_FETCH").is_some())
266    }
267
268    #[inline]
269    pub(crate) fn add_read(ns: u64) {
270        READ_NS.fetch_add(ns, Ordering::Relaxed);
271    }
272
273    #[inline]
274    pub(crate) fn add_decode(ns: u64) {
275        DECODE_NS.fetch_add(ns, Ordering::Relaxed);
276    }
277
278    pub(crate) fn snapshot() -> (u64, u64) {
279        (
280            READ_NS.load(Ordering::Relaxed),
281            DECODE_NS.load(Ordering::Relaxed),
282        )
283    }
284
285    pub(crate) fn reset() {
286        READ_NS.store(0, Ordering::Relaxed);
287        DECODE_NS.store(0, Ordering::Relaxed);
288    }
289
290    pub(crate) fn set_force(on: bool) {
291        FORCE.store(on, Ordering::Relaxed);
292    }
293}
294
295/// Profiling-only: snapshot the cumulative `(read_ns, decode_ns)` split that the
296/// fetch paging loop has accumulated since the last [`fetch_profile_reset`].
297///
298/// Only populated when fetch profiling is armed (the `ORACLEDB_PROFILE_FETCH`
299/// env var is set, or [`fetch_profile_arm(true)`](fetch_profile_arm) was called).
300/// This is benchmark/diagnostic instrumentation; it is not part of the normal
301/// data path.
302pub fn fetch_profile_read_decode_ns() -> (u64, u64) {
303    fetch_profile::snapshot()
304}
305
306/// Profiling-only: zero the fetch read/decode attribution counters.
307pub fn fetch_profile_reset() {
308    fetch_profile::reset();
309}
310
311/// Profiling-only: arm or disarm fetch read/decode attribution for this process
312/// without setting an environment variable.
313pub fn fetch_profile_arm(on: bool) {
314    fetch_profile::set_force(on);
315}
316
317#[cfg(feature = "arrow")]
318#[path = "arrow/mod.rs"]
319pub mod arrow;
320/// Executemany batch-chunk bookkeeping. Private module: the user-facing surface
321/// is the three items re-exported at the crate root below, so there is exactly
322/// one public path per item (no `oraclemcp_driver_cx::cursor_logic::…` second path).
323mod cursor_logic;
324mod iam_pop;
325/// Feature-gated observability seam (bead rust-oracledb-lv6). Always compiled so
326/// the `obs_span!` / `obs_record!` macros resolve, but its `tracing`-touching
327/// items are themselves `#[cfg(feature = "tracing")]`, so the off-build pulls in
328/// no `tracing` dependency. See `docs/OBSERVABILITY.md`.
329#[macro_use]
330mod obs;
331/// Lazy, on-demand streaming over LOB locators (bead a4-bbx). The user-facing
332/// types are re-exported at the crate root (the single canonical public path).
333pub(crate) mod lob_stream;
334pub mod pool;
335mod recovery;
336mod request;
337/// Idempotency-gated retry executor over the ORA error taxonomy (bead a4-r9a).
338pub mod retry;
339mod routine;
340/// Owning row-by-row query stream (K10). The user-facing [`OwnedRowStream`] is
341/// re-exported at the crate root (the single canonical public path).
342mod row_stream;
343mod rows;
344/// Cross-connection statement-shape cache with DDL-invalidation self-heal
345/// (bead a4-8pp). The user-facing types are re-exported at the crate root (the
346/// single canonical public path).
347pub(crate) mod shape_cache;
348#[cfg(feature = "soda")]
349pub mod soda;
350mod sql_convert;
351pub(crate) mod tls;
352// The `tls` module itself is crate-private, but the wallet-precedence
353// resolution accessor and its outcome types are part of the public API (a
354// server doctor calls them to report which wallet file wins without re-deriving
355// the driver's precedence). Re-exported flat at the crate root — the single
356// public path for each.
357pub use tls::{resolve_wallet, WalletFile, WalletResolution};
358pub mod transport;
359
360/// L2 version cassettes: live capture + offline replay of the per-version
361/// connect-negotiation wire exchange (bead rust-oracledb-xver-parity-so3w.3).
362/// Test-only, and only with the `cassette` feature (it uses the record/replay
363/// transport seam). Not part of the public API and compiled out of every
364/// shipping build.
365#[cfg(all(test, feature = "cassette"))]
366mod version_cassettes;
367
368/// Re-export of the `tracing` crate for the `obs_span!` / `obs_record!` macros
369/// (`$crate::__tracing::…`). Hidden and feature-gated; not part of the public
370/// API. Only exists when the `tracing` feature is on.
371#[cfg(feature = "tracing")]
372#[doc(hidden)]
373pub use tracing as __tracing;
374
375/// Off-build no-op span guard the `obs_span!` macro yields when the `tracing`
376/// feature is off (hoisted to crate root for `$crate::ObsSpanGuard`).
377#[cfg(not(feature = "tracing"))]
378#[doc(hidden)]
379pub use obs::ObsSpanGuard;
380
381pub use cursor_logic::{
382    bind_rows_need_iterative_plsql, ExecutemanyManager, ExecutemanyManagerError,
383};
384
385pub use request::{Batch, BatchRows, Execute, Query, Registration, Scroll};
386use request::{DeadlineExpiry, QueryDeadline};
387pub use row_stream::OwnedRowStream;
388pub use rows::{
389    BatchError, BatchOutcome, BlockingRows, ExecuteOutcome, OutBinds, RegistrationOutcome,
390    ReturningRows, Row, Rows,
391};
392
393pub use routine::{OutType, RoutineCall, RoutineOutcome};
394
395pub use shape_cache::{ColumnShape, ShapeObservation, StatementShapeCache};
396
397pub use lob_stream::{ClobReader, LobReader, LobWriter};
398
399pub use sql_convert::{
400    check_bind_rows, check_positional_binds, declared_bind_count, BindError, ConversionError,
401    FromRow, FromSql, IntoBinds, Params, QueryResultExt, ToSql, TypedRow,
402};
403
404/// Derive a [`FromRow`] implementation that maps a query row into a struct with
405/// compile-time-checked field types.
406///
407/// Available with the default-on `derive` feature. The derive and the
408/// [`FromRow`] trait share a name, so `use oraclemcp_driver_cx::FromRow;` brings
409/// both into scope.
410///
411/// ```no_run
412/// use oraclemcp_driver_cx::FromRow;
413///
414/// #[derive(FromRow)]
415/// struct Emp {
416///     id: i64,
417///     name: String,
418///     manager_id: Option<i64>,
419/// }
420/// ```
421///
422/// See the [`FromRow`] trait docs for the supported shapes and `#[driver_cx(...)]`
423/// attributes.
424#[cfg(feature = "derive")]
425pub use oracledb_derive::FromRow;
426
427/// The everyday types and traits, for a single glob import.
428///
429/// A typical program needs a connection type, [`ConnectOptions`], the
430/// [`ClientIdentity`] the database records, the value
431/// types it binds and reads back ([`BindValue`] /
432/// [`QueryValue`](protocol::thin::QueryValue)), and the typed-row helpers
433/// ([`FromRow`], [`QueryResultExt`], [`params!`]). Those live across two
434/// namespaces (the driver root and the [`protocol`] re-export), so the prelude
435/// gathers them so callers can write one line:
436///
437/// ```no_run
438/// use oraclemcp_driver_cx::prelude::*;
439///
440/// # fn main() -> oraclemcp_driver_cx::Result<()> {
441/// let identity = ClientIdentity::new("app", "host", "user", "term", "rust-oracledb")?;
442/// let options = ConnectOptions::new("dbhost:1521/FREEPDB1", "app_user", "app_pw", identity);
443/// let mut conn = BlockingConnection::connect(options)?;
444/// let binds = params! { "id" => 42_i64 };
445/// # let _ = (&mut conn, binds);
446/// # BlockingConnection::close(conn)?;
447/// # Ok(())
448/// # }
449/// ```
450///
451/// The prelude is a curated convenience namespace, not a second canonical home:
452/// each item's one obvious path is still its non-prelude path
453/// (`oraclemcp_driver_cx::Connection`,
454/// `oraclemcp_driver_cx::protocol::thin::QueryValue`, ...). Reach
455/// for an explicit `use` when you want exactly one name or a less common type.
456///
457/// It deliberately does **not** re-export [`Result`] or [`Error`]: a 1-argument
458/// `Result` alias and an `Error` type in a glob import shadow
459/// `std::result::Result` / `std::error::Error`, which surprises callers. Name
460/// those explicitly as `oraclemcp_driver_cx::Result` /
461/// `oraclemcp_driver_cx::Error`.
462pub mod prelude {
463    pub use crate::protocol::thin::{BindValue, QueryValue};
464    pub use crate::protocol::ClientIdentity;
465    pub use crate::{
466        params, BlockingConnection, ConnectOptions, Connection, FromRow, Params, QueryResultExt,
467    };
468}
469
470use recovery::{
471    cancel_disposition, classify_recovery_result, decode_server_version_number,
472    observe_cancellation_between_round_trips, post_sync_protocol_error_disposition,
473    protocol_error_is_session_dead, protocol_error_kind, protocol_error_offset,
474    protocol_error_ora_code, run_recovery_without_current_cx,
475    server_version_number_uses_extended_layout, CancelDisposition, PostSyncProtocolDisposition,
476    RecoveryWireAction, SessionRecovery, SessionRecoveryPhase, CONNECTION_LOST_ORA_CODES,
477    SESSION_DEAD_ORA_CODES, TRANSIENT_ORA_CODES,
478};
479
480use transport::{Connector, WireTransport};
481
482type DriverConnector = transport::OracleConnector;
483type DriverTransport = <DriverConnector as Connector>::Transport;
484type SharedWriteHalf<T = DriverTransport> = Arc<AsyncMutex<<T as WireTransport>::Write>>;
485type DriverCore = ConnectionCore<DriverTransport>;
486
487struct TokenAuthentication<'a> {
488    user: &'a str,
489    token: &'a str,
490    driver_name: &'a str,
491    version_num: u32,
492    connect_string: &'a str,
493    edition: Option<&'a str>,
494    /// OCI IAM database-token proof-of-possession (`AUTH_HEADER`/`AUTH_SIGNATURE`).
495    /// `None` for a plain OAuth2 bearer token.
496    pop: Option<TokenPop<'a>>,
497    /// Proxy client name (`PROXY_CLIENT_NAME`); `None` when not proxying.
498    /// Empty base `user` with `Some(proxy)` is the token-auth `[proxy]` form.
499    proxy_user: Option<&'a str>,
500}
501
502#[derive(Debug)]
503struct ConnectionCore<T: WireTransport> {
504    read: Option<T::Read>,
505    write: SharedWriteHalf<T>,
506    recovery: Arc<SessionRecovery>,
507    protocol_limits: ProtocolLimits,
508    /// Optional per-read inactivity deadline (GH#14). `None` = unbounded reads
509    /// (prior behaviour); `Some(d)` fails a stalled post-auth read with
510    /// [`Error::CallTimeout`] after `d`. Set once at connect from
511    /// [`ConnectOptions::inactivity_timeout`].
512    inactivity_timeout: Option<Duration>,
513    /// Whether this session negotiated the *classic* (pre-END_OF_RESPONSE)
514    /// framing, i.e. `!supports_end_of_response`. Set once at connect time from
515    /// the ACCEPT capabilities. The recovery drain reads this to decide the
516    /// trailing-error boundary the way the connected server frames it (bead
517    /// rust-oracledb-99xu); `false` (23ai framing) until the session negotiates.
518    classic_framing: bool,
519}
520
521impl<T: WireTransport> ConnectionCore<T> {
522    fn from_halves(read: T::Read, write: T::Write, write_name: &'static str) -> Self {
523        Self {
524            read: Some(read),
525            write: Arc::new(AsyncMutex::with_name(write_name, write)),
526            recovery: Arc::new(SessionRecovery::new()),
527            protocol_limits: ProtocolLimits::DEFAULT,
528            inactivity_timeout: None,
529            classic_framing: false,
530        }
531    }
532
533    /// Records whether this session uses classic (pre-END_OF_RESPONSE) framing,
534    /// so the recovery drain can decide the trailing-error boundary correctly
535    /// on pre-23ai servers (bead rust-oracledb-99xu).
536    fn set_classic_framing(&mut self, classic: bool) {
537        self.classic_framing = classic;
538    }
539
540    fn set_protocol_limits(&mut self, limits: ProtocolLimits) -> Result<()> {
541        self.protocol_limits = limits.validate()?;
542        Ok(())
543    }
544
545    /// Sets the per-read inactivity deadline for this session (GH#14). `None`
546    /// leaves reads unbounded (prior behaviour).
547    fn set_inactivity_timeout(&mut self, timeout: Option<Duration>) {
548        self.inactivity_timeout = timeout;
549    }
550
551    fn read_mut(&mut self) -> Result<&mut T::Read> {
552        self.read.as_mut().ok_or_else(|| {
553            Error::ConnectionClosed("connection read half unavailable during recovery".into())
554        })
555    }
556
557    fn take_read(&mut self) -> Result<T::Read> {
558        self.read.take().ok_or_else(|| {
559            Error::ConnectionClosed("connection read half unavailable during recovery".into())
560        })
561    }
562
563    fn write_handle(&self) -> SharedWriteHalf<T> {
564        Arc::clone(&self.write)
565    }
566
567    async fn write_all(&self, cx: &Cx, packet: &[u8]) -> Result<()> {
568        write_all_shared(cx, &self.write, packet).await
569    }
570
571    async fn shutdown_write(&self, cx: &Cx) -> Result<()> {
572        shutdown_write_shared(cx, &self.write).await
573    }
574
575    async fn send_data_packet(&self, cx: &Cx, payload: &[u8], sdu: usize) -> Result<()> {
576        send_data_packet_shared(cx, &self.write, payload, sdu).await
577    }
578
579    /// Sends the overflow CONNECT descriptor before the listener has replied
580    /// with ACCEPT. This exchange still uses the legacy 16-bit TNS header;
581    /// normal TTC DATA switches to `Large32` only after ACCEPT.
582    async fn send_connect_data_packet(&self, cx: &Cx, payload: &[u8], sdu: usize) -> Result<()> {
583        send_data_packet_shared_with_width(
584            cx,
585            &self.write,
586            payload,
587            sdu,
588            PacketLengthWidth::Legacy16,
589        )
590        .await
591    }
592
593    async fn send_data_packet_with_flags(
594        &self,
595        cx: &Cx,
596        payload: &[u8],
597        sdu: usize,
598        first_packet_flags: u16,
599        last_packet_flags: u16,
600    ) -> Result<()> {
601        send_data_packet_shared_with_flags(
602            cx,
603            &self.write,
604            payload,
605            sdu,
606            first_packet_flags,
607            last_packet_flags,
608        )
609        .await
610    }
611
612    async fn read_packet(&mut self, width: PacketLengthWidth) -> Result<IncomingPacket> {
613        let limits = self.protocol_limits;
614        let inactivity = self.inactivity_timeout;
615        let result = {
616            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
617            read_packet_with_limits(&mut read, width, limits).await
618        };
619        self.note_post_sync_result(map_inactivity_timeout(result))
620    }
621
622    async fn read_data_response(&mut self, cx: &Cx) -> Result<Vec<u8>> {
623        let write = Arc::clone(&self.write);
624        let limits = self.protocol_limits;
625        let inactivity = self.inactivity_timeout;
626        let result = {
627            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
628            read_data_response_with_limits(&mut read, cx, &write, limits).await
629        };
630        self.note_post_sync_result(map_inactivity_timeout(result))
631    }
632
633    /// Reads one classic (pre-END_OF_RESPONSE) connect-phase response. Servers
634    /// that did not negotiate END_OF_RESPONSE framing never set the
635    /// end-of-response DATA flag, so the flag-driven boundary reader would wait
636    /// forever; completion is decided by the payload's terminal message instead
637    /// (`classic_connect_response_is_complete`).
638    async fn read_classic_data_response(&mut self, cx: &Cx) -> Result<Vec<u8>> {
639        let write = Arc::clone(&self.write);
640        let limits = self.protocol_limits;
641        let inactivity = self.inactivity_timeout;
642        let result = {
643            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
644            read_classic_data_response_with_limits(&mut read, cx, &write, limits).await
645        };
646        self.note_post_sync_result(map_inactivity_timeout(result))
647    }
648
649    /// Authenticates an OCI IAM/OAuth database token over the pre-23ai classic
650    /// connect sequence. The token payload is deliberately never passed to the
651    /// packet trace helper.
652    async fn authenticate_classic_token(
653        &mut self,
654        cx: &Cx,
655        token_auth: TokenAuthentication<'_>,
656        sdu: usize,
657    ) -> Result<(AuthResponse, ClientCapabilities)> {
658        let protocol_limits = self.protocol_limits;
659        // Mirror the password path's classic negotiation, then send the
660        // self-contained token phase-two payload (there is no password
661        // challenge/response).
662        let protocol_payload = build_protocol_negotiation_payload()?;
663        trace_connect_step("send protocol negotiation (classic token)");
664        self.send_data_packet(cx, &protocol_payload, sdu).await?;
665        trace_connect_step("read protocol negotiation");
666        let response = self.read_classic_data_response(cx).await?;
667        trace_connect_bytes("protocol negotiation response", &response);
668        let negotiated = parse_auth_response_with_limits(&response, protocol_limits)?;
669
670        let data_types_payload = build_data_types_payload()?;
671        trace_connect_step("send data types (classic token)");
672        self.send_data_packet(cx, &data_types_payload, sdu).await?;
673        trace_connect_step("read data types");
674        let response = self.read_classic_data_response(cx).await?;
675        trace_connect_bytes("data types response", &response);
676        parse_auth_response_with_limits(&response, protocol_limits)?;
677
678        let auth_payload = build_auth_phase_two_token_payload_with_pop_and_proxy(
679            token_auth.user,
680            token_auth.token,
681            token_auth.driver_name,
682            token_auth.version_num,
683            token_auth.connect_string,
684            token_auth.edition,
685            token_auth.pop,
686            token_auth.proxy_user,
687        )?;
688        trace_connect_step("send AUTH token (classic phase two)");
689        self.send_data_packet(cx, &auth_payload, sdu).await?;
690        trace_connect_step("read AUTH token response");
691        let response = self.read_classic_data_response(cx).await?;
692        trace_connect_bytes("AUTH token response", &response);
693        let auth = parse_auth_response_with_limits(&response, protocol_limits)?;
694        let capabilities = negotiated
695            .capabilities
696            .or(auth.capabilities)
697            .unwrap_or_default();
698        Ok((auth, capabilities))
699    }
700
701    /// Reads one TTC response, deciding completion the way the connected
702    /// server framing requires. With `classic == false` this is exactly
703    /// [`read_data_response`](Self::read_data_response) (END_OF_RESPONSE/EOF
704    /// data-flag framing, 23ai+). With `classic == true` (ACCEPT protocol
705    /// version < 319 — the server never sends those flags) DATA packets are
706    /// accumulated and `probe(&accumulated)` decides completion after each
707    /// packet: the caller probes with the same parser it will run on the
708    /// returned buffer, so the response is complete precisely when that parser
709    /// can consume it without running out of bytes (reference
710    /// messages/base.pyx:249-252, 294-298 — a classic response ends at its
711    /// terminal ERROR/STATUS/FLUSH_OUT_BINDS message).
712    async fn read_data_response_probed(
713        &mut self,
714        cx: &Cx,
715        classic: bool,
716        probe: impl Fn(&[u8]) -> bool,
717    ) -> Result<Vec<u8>> {
718        if !classic {
719            return self.read_data_response(cx).await;
720        }
721        let write = Arc::clone(&self.write);
722        let limits = self.protocol_limits;
723        let inactivity = self.inactivity_timeout;
724        let result = {
725            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
726            read_classic_data_response_probed_with_limits(&mut read, cx, &write, &probe, limits)
727                .await
728        };
729        self.note_post_sync_result(map_inactivity_timeout(result))
730    }
731
732    /// Read the response to the terminal LOGOFF request.
733    ///
734    /// Oracle may finish a usable TCPS session by closing TCP without a TLS
735    /// `close_notify`. That transport signal is acceptable only before the
736    /// first byte of this terminal response: at that point LOGOFF has already
737    /// been written and there is no next application response to protect. Any
738    /// bytes followed by the same signal remain a truncated response error.
739    async fn read_session_close_response(
740        &mut self,
741        cx: &Cx,
742        classic: bool,
743        probe: impl Fn(&[u8]) -> bool,
744    ) -> Result<SessionCloseDisposition> {
745        let write = Arc::clone(&self.write);
746        let limits = self.protocol_limits;
747        let inactivity = self.inactivity_timeout;
748        let result = {
749            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
750            read_session_close_response_with_limits(&mut read, cx, &write, classic, &probe, limits)
751                .await
752        };
753        self.note_post_sync_result(map_inactivity_timeout(result))
754    }
755
756    /// Finishes the wire-level half of a terminal LOGOFF exchange.
757    ///
758    /// A peer hard-close accepted at the empty response boundary has already
759    /// made Asupersync's TLS stream terminal, so attempting the ordinary final
760    /// TNS EOF write would only turn a successful close into `BrokenPipe`.
761    /// Complete responses and response timeouts retain the existing EOF write
762    /// and write-shutdown behavior.
763    async fn finish_session_close(
764        &mut self,
765        cx: &Cx,
766        classic: bool,
767        probe: impl Fn(&[u8]) -> bool,
768    ) -> Result<()> {
769        if let Ok(response) = time::timeout(
770            time::wall_now(),
771            Duration::from_secs(5),
772            self.read_session_close_response(cx, classic, probe),
773        )
774        .await
775        {
776            if response? == SessionCloseDisposition::PeerHardClosed {
777                return Ok(());
778            }
779        }
780        let eof = encode_packet(
781            TNS_PACKET_TYPE_DATA,
782            0,
783            Some(oracledb_protocol::thin::TNS_DATA_FLAGS_EOF),
784            &[],
785            PacketLengthWidth::Large32,
786        )?;
787        self.write_all(cx, &eof).await?;
788        let _ = self.shutdown_write(cx).await;
789        Ok(())
790    }
791
792    /// [`read_data_response_probed`](Self::read_data_response_probed) for the
793    /// bind/execute path, which must answer FLUSH_OUT_BINDS requests. With
794    /// `classic == false` this is exactly
795    /// [`read_data_response_flushing_out_binds`](Self::read_data_response_flushing_out_binds).
796    async fn read_data_response_flushing_out_binds_probed(
797        &mut self,
798        cx: &Cx,
799        sdu: usize,
800        classic: bool,
801        probe: impl Fn(&[u8]) -> bool,
802    ) -> Result<Vec<u8>> {
803        if !classic {
804            return self.read_data_response_flushing_out_binds(cx, sdu).await;
805        }
806        let write = Arc::clone(&self.write);
807        let limits = self.protocol_limits;
808        let inactivity = self.inactivity_timeout;
809        let result = {
810            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
811            read_classic_data_response_flushing_out_binds_probed_with_limits(
812                &mut read, cx, &write, sdu, &probe, limits,
813            )
814            .await
815        };
816        self.note_post_sync_result(map_inactivity_timeout(result))
817    }
818
819    async fn read_data_response_boundary(
820        &mut self,
821        cx: &Cx,
822        in_pipeline: bool,
823    ) -> Result<DataResponse> {
824        let write = Arc::clone(&self.write);
825        let limits = self.protocol_limits;
826        let inactivity = self.inactivity_timeout;
827        let result = {
828            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
829            read_data_response_boundary_with_limits(&mut read, cx, &write, in_pipeline, limits)
830                .await
831        };
832        self.note_post_sync_result(map_inactivity_timeout(result))
833    }
834
835    async fn read_data_response_flushing_out_binds(
836        &mut self,
837        cx: &Cx,
838        sdu: usize,
839    ) -> Result<Vec<u8>> {
840        let write = Arc::clone(&self.write);
841        let limits = self.protocol_limits;
842        let inactivity = self.inactivity_timeout;
843        let result = {
844            let mut read = InactivityRead::new(self.read_mut()?, inactivity);
845            read_data_response_flushing_out_binds_with_limits(&mut read, cx, &write, sdu, limits)
846                .await
847        };
848        self.note_post_sync_result(map_inactivity_timeout(result))
849    }
850
851    fn note_post_sync_result<U>(&self, result: Result<U>) -> Result<U> {
852        if let Err(Error::Protocol(err)) = &result {
853            if post_sync_protocol_error_disposition(err) == PostSyncProtocolDisposition::Dead {
854                self.recovery.mark_dead();
855            }
856        }
857        result
858    }
859
860    fn break_and_drain_wire(&mut self, recovery_timeout: Duration) -> Result<()> {
861        self.run_recovery_drain(RecoveryWireAction::BreakAndDrain, recovery_timeout)
862    }
863
864    fn cancel_and_drain_wire(&mut self, recovery_timeout: Duration) -> Result<()> {
865        self.run_recovery_drain(RecoveryWireAction::BreakAndDrain, recovery_timeout)
866    }
867
868    fn drain_cancel_wire(&mut self, recovery_timeout: Duration) -> Result<()> {
869        self.run_recovery_drain(RecoveryWireAction::DrainCancel, recovery_timeout)
870    }
871
872    fn run_recovery_drain(
873        &mut self,
874        action: RecoveryWireAction,
875        recovery_timeout: Duration,
876    ) -> Result<()> {
877        let read = self.take_read()?;
878        let write = Arc::clone(&self.write);
879        let limits = self.protocol_limits;
880        let classic = self.classic_framing;
881        let thread = std::thread::Builder::new()
882            .name("oracledb-recovery-drain".to_string())
883            .spawn(move || {
884                let mut read = read;
885                let result = run_recovery_without_current_cx(
886                    &mut read,
887                    &write,
888                    action,
889                    recovery_timeout,
890                    limits,
891                    classic,
892                );
893                (read, result)
894            })
895            .map_err(|err| {
896                Error::ConnectionClosed(format!("failed to start recovery drain thread: {err}"))
897            })?;
898
899        match thread.join() {
900            Ok((read, result)) => {
901                self.read = Some(read);
902                result
903            }
904            Err(_) => Err(Error::ConnectionClosed(
905                "recovery drain thread panicked".to_string(),
906            )),
907        }
908    }
909}
910
911/// Render a compiler-style caret diagnostic: the line of `sql` containing the
912/// 1-based character `offset` (the position Oracle reports for a parse error),
913/// with a `^` under that character, beneath `headline`.
914///
915/// Pure and panic-free: `offset` is clamped into range (a 0 or out-of-range
916/// offset points at the start / just past the end). Counts in Unicode scalar
917/// values, so multibyte SQL stays aligned; tabs count as one column.
918///
919/// ```
920/// let d = oraclemcp_driver_cx::render_caret(
921///     "select * from no_such_table",
922///     15,
923///     "ORA-00942: table or view does not exist",
924/// );
925/// assert!(d.contains("no_such_table"));
926/// assert!(d.lines().last().unwrap().trim_end().ends_with('^'));
927/// ```
928pub fn render_caret(sql: &str, offset: usize, headline: &str) -> String {
929    let chars: Vec<char> = sql.chars().collect();
930    let total = chars.len();
931    // 1-based -> 0-based char index, clamped into [0, total].
932    let target = offset.saturating_sub(1).min(total);
933
934    let mut line_start = 0usize;
935    let mut line_no = 1usize;
936    let mut col = 0usize;
937    for (i, &c) in chars.iter().enumerate() {
938        if i == target {
939            break;
940        }
941        if c == '\n' {
942            line_no += 1;
943            line_start = i + 1;
944            col = 0;
945        } else {
946            col += 1;
947        }
948    }
949
950    let mut line_end = line_start;
951    while line_end < total && chars[line_end] != '\n' {
952        line_end += 1;
953    }
954    let line: String = chars[line_start..line_end].iter().collect();
955    let gutter = line_no.to_string();
956    let pad = " ".repeat(gutter.len());
957    let caret_indent = " ".repeat(col);
958    format!("{headline}\n{pad} |\n{gutter} | {line}\n{pad} | {caret_indent}^")
959}
960
961/// Captured `DBMS_OUTPUT`, bounded by the caller's line/char limits. Returned by
962/// [`Connection::read_dbms_output`].
963#[derive(Debug, Clone, Default, PartialEq, Eq)]
964pub struct DbmsOutput {
965    /// The captured lines, in the order `DBMS_OUTPUT.GET_LINE` returned them.
966    lines: Vec<String>,
967    /// Number of lines captured (`== lines.len()`).
968    line_count: usize,
969    /// Total characters (Unicode scalar values) across all captured lines.
970    char_count: usize,
971    /// `true` if capture stopped at a `max_lines`/`max_chars` bound while more
972    /// output was still buffered server-side; `false` if it drained to the end.
973    truncated: bool,
974}
975
976impl DbmsOutput {
977    pub fn new(lines: Vec<String>, truncated: bool) -> Self {
978        let line_count = lines.len();
979        let char_count = lines.iter().map(|line| line.chars().count()).sum();
980        Self {
981            lines,
982            line_count,
983            char_count,
984            truncated,
985        }
986    }
987
988    pub fn lines(&self) -> &[String] {
989        &self.lines
990    }
991
992    pub fn line_count(&self) -> usize {
993        self.line_count
994    }
995
996    pub fn char_count(&self) -> usize {
997        self.char_count
998    }
999
1000    pub fn truncated(&self) -> bool {
1001        self.truncated
1002    }
1003
1004    pub fn into_lines(self) -> Vec<String> {
1005        self.lines
1006    }
1007}
1008
1009/// A scalar attribute of an Oracle ADT/object type (from the data dictionary).
1010#[derive(Debug, Clone, PartialEq, Eq)]
1011pub struct ObjectAttribute {
1012    /// Attribute name, uppercased as Oracle stores it.
1013    pub name: String,
1014    /// Oracle attribute type name (`ALL_TYPE_ATTRS.ATTR_TYPE_NAME`), e.g.
1015    /// `"VARCHAR2"`, `"NUMBER"`, `"DATE"`.
1016    pub type_name: String,
1017    /// `Some(owner)` when the attribute is itself an object/collection type (a
1018    /// nested ADT); `None` for built-in scalar types.
1019    pub type_owner: Option<String>,
1020}
1021
1022/// Element type metadata for an Oracle collection type (VARRAY / nested table),
1023/// from `ALL_COLL_TYPES`.
1024#[derive(Debug, Clone, PartialEq, Eq)]
1025pub struct CollectionElement {
1026    /// Oracle element type name (`ALL_COLL_TYPES.ELEM_TYPE_NAME`), e.g.
1027    /// `"NUMBER"`, `"VARCHAR2"`.
1028    pub type_name: String,
1029    /// `Some(owner)` when the element is itself an object/collection type; `None`
1030    /// for built-in scalar element types.
1031    pub type_owner: Option<String>,
1032}
1033
1034/// Metadata for an Oracle ADT/object type, fetched from the data dictionary by
1035/// [`Connection::describe_object_type`]. A type is either an *object* (carrying
1036/// `attributes`) or a *collection* (carrying `collection_element`).
1037#[derive(Debug, Clone, PartialEq, Eq)]
1038pub struct ObjectType {
1039    /// Owning schema (uppercased).
1040    pub schema: String,
1041    /// Type name (uppercased).
1042    pub name: String,
1043    /// Attributes in declaration order (empty for a collection type).
1044    pub attributes: Vec<ObjectAttribute>,
1045    /// `Some(..)` when this type is a collection (VARRAY / nested table); carries
1046    /// its element metadata. `None` for object types (see `attributes`).
1047    pub collection_element: Option<CollectionElement>,
1048}
1049
1050/// A decoded Oracle ADT value. For an *object* type the scalar attributes are in
1051/// `attributes`; for a *collection* type the elements are in `elements`. Each
1052/// value is decoded with the same rules as a normal column. Returned by
1053/// [`decode_object`].
1054#[derive(Debug, Clone, Default, PartialEq)]
1055pub struct DecodedObject {
1056    /// The object type's schema.
1057    type_schema: String,
1058    /// The object type's name.
1059    type_name: String,
1060    /// `(attribute name, value)` in declaration order; `None` is SQL `NULL`.
1061    /// Empty when the decoded value is a collection (see `elements`).
1062    attributes: Vec<(String, Option<oracledb_protocol::thin::QueryValue>)>,
1063    /// `Some(elements)` when the decoded value is a collection; each entry is one
1064    /// element in order (`None` is a NULL element). `None` for object values.
1065    elements: Option<Vec<Option<oracledb_protocol::thin::QueryValue>>>,
1066}
1067
1068impl DecodedObject {
1069    pub fn object(
1070        type_schema: impl Into<String>,
1071        type_name: impl Into<String>,
1072        attributes: Vec<(String, Option<oracledb_protocol::thin::QueryValue>)>,
1073    ) -> Self {
1074        Self {
1075            type_schema: type_schema.into(),
1076            type_name: type_name.into(),
1077            attributes,
1078            elements: None,
1079        }
1080    }
1081
1082    pub fn collection(
1083        type_schema: impl Into<String>,
1084        type_name: impl Into<String>,
1085        elements: Vec<Option<oracledb_protocol::thin::QueryValue>>,
1086    ) -> Self {
1087        Self {
1088            type_schema: type_schema.into(),
1089            type_name: type_name.into(),
1090            attributes: Vec::new(),
1091            elements: Some(elements),
1092        }
1093    }
1094
1095    pub fn type_schema(&self) -> &str {
1096        &self.type_schema
1097    }
1098
1099    pub fn type_name(&self) -> &str {
1100        &self.type_name
1101    }
1102
1103    pub fn attributes(&self) -> &[(String, Option<oracledb_protocol::thin::QueryValue>)] {
1104        &self.attributes
1105    }
1106
1107    pub fn elements(&self) -> Option<&[Option<oracledb_protocol::thin::QueryValue>]> {
1108        self.elements.as_deref()
1109    }
1110
1111    pub fn is_collection(&self) -> bool {
1112        self.elements.is_some()
1113    }
1114
1115    pub fn into_attributes(self) -> Vec<(String, Option<oracledb_protocol::thin::QueryValue>)> {
1116        self.attributes
1117    }
1118
1119    pub fn into_elements(self) -> Option<Vec<Option<oracledb_protocol::thin::QueryValue>>> {
1120        self.elements
1121    }
1122}
1123
1124/// Decode a returned Oracle ADT object value (the payload of a
1125/// `QueryValue::Object`) into its scalar attributes, using the type metadata
1126/// from [`Connection::describe_object_type`]. Bounded by the object image
1127/// length, so a malformed/huge image cannot cause unbounded work.
1128///
1129/// Scoped to objects with scalar attributes: a nested object/collection
1130/// attribute yields a typed `Error::Protocol(UnsupportedFeature(..))`, so a
1131/// caller can classify "this shape isn't decodable yet" distinctly from a real
1132/// failure. python-oracledb only decodes objects through its thick/DbObject
1133/// machinery; this is the native structured surface.
1134pub fn decode_object(
1135    value: &oracledb_protocol::thin::ObjectValue,
1136    ty: &ObjectType,
1137) -> Result<DecodedObject> {
1138    use oracledb_protocol::thin::DbObjectPackedReader;
1139    use oracledb_protocol::wire::{BoundedReader, ProtocolLimits};
1140    let mut reader = DbObjectPackedReader::new(&value.packed_data);
1141    reader
1142        .limits()
1143        .check_response_bytes(value.packed_data.len())?;
1144    reader.read_header()?;
1145
1146    // Collection type: 1 collection-flags byte, then an element count, then each
1147    // element value (reference impl/thin/dbobject.pyx `_unpack_data_from_buf`).
1148    if let Some(elem) = &ty.collection_element {
1149        if elem.type_owner.is_some() {
1150            return Err(oracledb_protocol::ProtocolError::UnsupportedFeature(
1151                "collection of nested object/collection elements is not decodable yet",
1152            )
1153            .into());
1154        }
1155        let _collection_flags = reader.read_u8()?;
1156        let num_elements = reader.read_length()?;
1157        reader.limits().check_object_elements(num_elements)?;
1158        // Every element consumes at least one byte, so the real count cannot
1159        // exceed the bytes still in the image; cap the pre-allocation against
1160        // `remaining()` so a malformed huge count can't force an unbounded Vec.
1161        // The loop itself is bounded too: `read_value_bytes` errors (truncated)
1162        // once the image is exhausted.
1163        let mut elements: Vec<Option<oracledb_protocol::thin::QueryValue>> =
1164            reader.with_capacity_limited(num_elements, 1, ProtocolLimits::check_object_elements)?;
1165        for _ in 0..num_elements {
1166            let decoded = match reader.read_value_bytes()? {
1167                None => None,
1168                Some(bytes) => Some(decode_object_scalar(&elem.type_name, bytes)?),
1169            };
1170            elements.push(decoded);
1171        }
1172        return Ok(DecodedObject {
1173            type_schema: ty.schema.clone(),
1174            type_name: ty.name.clone(),
1175            attributes: Vec::new(),
1176            elements: Some(elements),
1177        });
1178    }
1179
1180    let mut attributes = Vec::with_capacity(ty.attributes.len());
1181    for attr in &ty.attributes {
1182        if attr.type_owner.is_some() {
1183            return Err(oracledb_protocol::ProtocolError::UnsupportedFeature(
1184                "nested object/collection attribute is not decodable yet",
1185            )
1186            .into());
1187        }
1188        let decoded = match reader.read_value_bytes()? {
1189            None => None,
1190            Some(bytes) => Some(decode_object_scalar(&attr.type_name, bytes)?),
1191        };
1192        attributes.push((attr.name.clone(), decoded));
1193    }
1194    Ok(DecodedObject {
1195        type_schema: ty.schema.clone(),
1196        type_name: ty.name.clone(),
1197        attributes,
1198        elements: None,
1199    })
1200}
1201
1202/// Decode one scalar attribute/element value of an Oracle object/collection,
1203/// using the same codecs as normal column values. Returns a typed
1204/// `UnsupportedFeature` for a type we do not decode yet (so a caller can classify
1205/// the shape distinctly from a real failure).
1206fn decode_object_scalar(
1207    type_name: &str,
1208    bytes: Vec<u8>,
1209) -> Result<oracledb_protocol::thin::QueryValue> {
1210    use oracledb_protocol::thin::{
1211        decode_datetime_value, decode_dbobject_text, decode_number_value, QueryValue,
1212    };
1213    let v = if type_name.starts_with("TIMESTAMP") {
1214        decode_datetime_value(&bytes)?
1215    } else {
1216        match type_name {
1217            "VARCHAR2" | "VARCHAR" | "CHAR" => {
1218                QueryValue::Text(decode_dbobject_text(&bytes, "DB_TYPE_VARCHAR")?)
1219            }
1220            "NVARCHAR2" | "NCHAR" => {
1221                QueryValue::Text(decode_dbobject_text(&bytes, "DB_TYPE_NCHAR")?)
1222            }
1223            "NUMBER" | "FLOAT" | "INTEGER" => decode_number_value(&bytes)?,
1224            "DATE" => decode_datetime_value(&bytes)?,
1225            "RAW" => QueryValue::Raw(bytes),
1226            _ => {
1227                return Err(oracledb_protocol::ProtocolError::UnsupportedFeature(
1228                    "object attribute/element type is not decodable yet",
1229                )
1230                .into())
1231            }
1232        }
1233    };
1234    Ok(v)
1235}
1236
1237/// Stable top-level error bucket for [`Error::kind`].
1238#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1239#[non_exhaustive]
1240pub enum ErrorKind {
1241    Network,
1242    Timeout,
1243    Cancel,
1244    Protocol,
1245    Database,
1246    Conversion,
1247    Pool,
1248    ResourceLimit,
1249    Authentication,
1250}
1251
1252/// Whether the connection that produced an error can be reused.
1253#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1254pub enum ConnectionDisposition {
1255    Reusable,
1256    Dead,
1257}
1258
1259/// Conservative retry guidance for caller-proven idempotent operations.
1260#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1261#[non_exhaustive]
1262pub enum RetryHint {
1263    Never,
1264    RetrySameConnectionIfIdempotent,
1265    ReconnectThenRetryIfIdempotent,
1266}
1267
1268#[derive(Debug, thiserror::Error)]
1269#[non_exhaustive]
1270pub enum Error {
1271    #[error(transparent)]
1272    Protocol(#[from] oracledb_protocol::ProtocolError),
1273    #[error("I/O error: {0}")]
1274    Io(#[from] std::io::Error),
1275    #[error("asupersync runtime error: {0}")]
1276    Runtime(String),
1277    /// The listener redirected the connection to a target whose shape this
1278    /// driver refuses to follow: the redirect address demands a transport
1279    /// protocol CHANGE. Continuing a `tcps` connect over plain `tcp` would be
1280    /// a silent TLS downgrade, and a mid-connect `tcp` -> `tcps` upgrade is
1281    /// not supported; a redirect that keeps the original transport protocol
1282    /// is followed transparently.
1283    #[error(
1284        "listener redirect demands a transport protocol change (e.g. a tcps -> tcp \
1285         downgrade); refusing to follow it"
1286    )]
1287    RedirectUnsupported,
1288    /// The listener answered CONNECT with a REDIRECT packet whose redirect
1289    /// data could not be understood (truncated length prefix, missing the
1290    /// NUL separator between the target address and its connect data, or an
1291    /// unparseable target address). The payload describes the defect; the
1292    /// raw redirect bytes are not echoed verbatim.
1293    #[error("listener redirect data is malformed: {0}")]
1294    InvalidRedirectData(String),
1295    /// The listener kept answering every CONNECT with another REDIRECT. A
1296    /// real redirect chain is one hop (shared server / RAC); the bound only
1297    /// guards against a redirect loop between misconfigured listeners.
1298    #[error("listener kept redirecting the connection ({0} redirects); giving up")]
1299    ConnectRedirectLoop(u8),
1300    #[error("listener refused connection: {0}")]
1301    ListenerRefused(String),
1302    /// Every address in a multi-address connect descriptor (`ADDRESS_LIST` or
1303    /// several `ADDRESS` entries) failed to establish a transport. The payload
1304    /// aggregates the per-address failure reasons in the order they were tried.
1305    /// The connection never reached a listener, so there is nothing to reuse.
1306    #[error("all connect addresses failed: {0}")]
1307    AllAddressesFailed(String),
1308    /// `use_sni=true` was explicitly requested but the Oracle TCPS SNI string
1309    /// (`S{len}.{service}.V3.{version}`) is not a valid rustls DNS name (its
1310    /// trailing all-numeric label is rejected by RFC-strict rustls), so it
1311    /// cannot be transmitted. The driver fails closed here instead of silently
1312    /// connecting without SNI. Reconnect with `use_sni=false` (the default) to
1313    /// rely on the post-handshake Oracle DN match, which secures the connection
1314    /// without SNI.
1315    #[error(
1316        "use_sni=true cannot be honored: the Oracle SNI \"{0}\" is not a valid \
1317         rustls DNS name; reconnect with use_sni=false to secure the connection \
1318         with the post-handshake DN match instead"
1319    )]
1320    UnsupportedSni(String),
1321    #[error(
1322        "unexpected TNS packet type {ty} ({name})",
1323        ty = .0,
1324        name = tns_packet_type_name(*.0)
1325    )]
1326    UnexpectedPacket(u8),
1327    #[error("server kept requesting CONNECT resend ({0} rounds); giving up")]
1328    ConnectResendLoop(u8),
1329    #[error("server did not advertise fast authentication")]
1330    FastAuthRequired,
1331    #[error("server response did not contain {0}")]
1332    MissingSessionField(&'static str),
1333    #[error("call timeout of {0} ms exceeded")]
1334    CallTimeout(u32),
1335    #[error("query returned no rows")]
1336    NoRows,
1337    #[error("query returned more than one row")]
1338    TooManyRows,
1339    /// The in-flight operation was explicitly cancelled by the user (via
1340    /// [`Connection::cancel`] or by dropping a cancellable fetch future), the
1341    /// driver's analog of the server-side `ORA-01013` "user requested cancel of
1342    /// current operation". Like a [`Self::CallTimeout`] (`DPY-4024`), a cancel
1343    /// drains the wire and leaves the session ALIVE and the connection clean and
1344    /// reusable: it is therefore **not** [`Self::is_connection_lost`] and **is**
1345    /// [`Self::is_transient`] (re-run the idempotent call on the same
1346    /// connection). It is distinguished from `CallTimeout` only so callers can
1347    /// tell a deliberate cancel apart from a deadline overrun.
1348    #[error("ORA-01013: user requested cancel of current operation")]
1349    Cancelled,
1350    /// The connection was closed because recovery from a prior failure could
1351    /// not complete: most commonly a **second** timeout while draining the
1352    /// server's response after a [`Self::CallTimeout`] break (mirroring the
1353    /// reference `ERR_CONNECTION_CLOSED` raised when the post-break
1354    /// `_receive_packet` itself times out, protocol.pyx:454-458). Unlike
1355    /// [`Self::CallTimeout`], the wire stream could not be left clean, so the
1356    /// connection is dead and must be discarded — [`Self::is_connection_lost`]
1357    /// is `true` for this variant. The payload is the human-readable reason.
1358    #[error("DPY-4011: the database or network closed the connection: {0}")]
1359    ConnectionClosed(String),
1360    /// A TCPS/TLS transport error (wallet load, handshake, or server-cert /
1361    /// DN-match failure).
1362    #[error("TLS/TCPS error: {0}")]
1363    Tls(String),
1364    /// A wallet-location or wallet-format error. Kept distinct from generic
1365    /// TLS failures so callers can classify unsupported wallet formats and
1366    /// operator setup issues without parsing strings.
1367    #[error("wallet error: {0}")]
1368    Wallet(#[from] oracledb_protocol::tls::wallet::WalletError),
1369    /// Access-token authentication was requested over a non-TLS transport.
1370    /// A database access token must only travel over TCPS so it is not exposed
1371    /// in clear text (reference protocol.pyx `ERR_ACCESS_TOKEN_REQUIRES_TCPS` /
1372    /// DPY-3001). Reconnect with a `tcps://` connect string. The token itself is
1373    /// never included in this error.
1374    #[error("DPY-3001: access token authentication requires a TLS (TCPS) connection")]
1375    AccessTokenRequiresTcps,
1376    /// The OCI IAM database-token proof-of-possession private key could not be
1377    /// used to sign the auth header: it was not a readable PKCS#8 RSA key, or
1378    /// the RSA-PKCS1v15-SHA256 signing operation failed. The key material, the
1379    /// token, and the signed header are never included in this error — only a
1380    /// fixed diagnostic is surfaced.
1381    #[error(
1382        "OCI IAM database-token proof-of-possession signing failed: \
1383         the bound private key is not a usable PKCS#8 RSA key"
1384    )]
1385    IamTokenProofOfPossession,
1386    /// A pluggable [`TokenSource`] failed to produce a database access token.
1387    /// The failure is a redacted [`TokenSourceError`] class; the token and any
1388    /// provider detail never appear in this error.
1389    #[error("{0}")]
1390    TokenSource(TokenSourceError),
1391    /// The caller selected a known authentication mode that this thin build
1392    /// does not implement. The mode is structured so diagnostic tools can
1393    /// distinguish capability gaps from bad credentials, listener failures, or
1394    /// TLS setup errors without parsing the display string.
1395    #[error("{0}")]
1396    UnsupportedAuthMode(UnsupportedAuthMode),
1397    /// A sessionless transaction client-API misuse (reference
1398    /// ERR_SESSIONLESS_* / DPY-3034/3035/3036). The payload is the DPY full
1399    /// code so the shim can raise the matching DatabaseError.
1400    #[error("{0}")]
1401    SessionlessTransaction(SessionlessError),
1402    /// A TPC (two-phase commit) state machine returned an unexpected out state
1403    /// (reference `ERR_UNKNOWN_TRANSACTION_STATE` / DPY-5010). The payload is
1404    /// the unexpected state value.
1405    #[error("DPY-5010: internal error: unknown transaction state {0}")]
1406    UnknownTransactionState(u32),
1407    /// A client-side bind payload was provably incompatible with the SQL text.
1408    #[error("bind validation failed: {0}")]
1409    Bind(#[from] BindError),
1410    /// A typed [`FromSql`] conversion failed: the fetched value did not match
1411    /// the requested Rust type, was out of range, or could not be parsed. The
1412    /// payload describes the mismatch.
1413    #[error("type conversion failed: {0}")]
1414    Conversion(ConversionError),
1415    #[cfg(feature = "arrow")]
1416    #[error(transparent)]
1417    ArrowConversion(#[from] arrow::ArrowConversionError),
1418}
1419
1420pub type Result<T> = std::result::Result<T, Error>;
1421
1422pub(crate) fn duration_to_millis_saturating(duration: Duration) -> u32 {
1423    duration.as_millis().min(u128::from(u32::MAX)) as u32
1424}
1425
1426/// Whether an `io::Error` is Asupersync's own cancellation signal for a
1427/// cancellation-aware read/connect: kind `Interrupted` with the exact payload
1428/// `"cancelled"` (`asupersync::net::tcp::stream` poll paths, pinned `=0.3.9`).
1429/// This marker is set at the instant the runtime observes the cancel, so it is
1430/// a deterministic discriminator from a genuine OS `EINTR` (whose message is the
1431/// OS text, not `"cancelled"`) and is not subject to the interrupt-vs-checkpoint
1432/// visibility race a later `Cx::checkpoint()` on the reading thread can hit.
1433fn is_asupersync_cancellation(io_error: &std::io::Error) -> bool {
1434    io_error.kind() == std::io::ErrorKind::Interrupted && io_error.to_string() == "cancelled"
1435}
1436
1437/// A REF CURSOR handle returned in a row or implicit result set.
1438pub type Cursor = CursorValue;
1439
1440/// Resolve an owned [`Row`] column by index or by case-insensitive column name.
1441///
1442/// This trait is sealed; supported indexes are `usize` and `&str`.
1443pub trait ColumnIndex: column_index_private::Sealed {
1444    #[doc(hidden)]
1445    fn resolve(self, columns: &[ColumnMetadata]) -> std::result::Result<usize, ConversionError>;
1446}
1447
1448mod column_index_private {
1449    pub trait Sealed {}
1450}
1451
1452impl column_index_private::Sealed for usize {}
1453
1454impl ColumnIndex for usize {
1455    fn resolve(self, columns: &[ColumnMetadata]) -> std::result::Result<usize, ConversionError> {
1456        if self < columns.len() {
1457            Ok(self)
1458        } else {
1459            Err(ConversionError::OutOfRange {
1460                expected: "column index",
1461                detail: format!("no column at index {self}"),
1462            })
1463        }
1464    }
1465}
1466
1467impl column_index_private::Sealed for &str {}
1468
1469impl ColumnIndex for &str {
1470    fn resolve(self, columns: &[ColumnMetadata]) -> std::result::Result<usize, ConversionError> {
1471        columns
1472            .iter()
1473            .position(|col| col.name().eq_ignore_ascii_case(self))
1474            .ok_or_else(|| ConversionError::OutOfRange {
1475                expected: "column name",
1476                detail: format!("no column named {self:?}"),
1477            })
1478    }
1479}
1480
1481/// Structured classification of an [`Error`].
1482///
1483/// These accessors promote the driver's *internal* retry knowledge (which ORA
1484/// codes mean "the session died", "the resource was busy", "the cached plan is
1485/// stale") into a public, matchable taxonomy. python-oracledb gives you a bare
1486/// `.code` integer and leaves the classification to you; here the curated lists
1487/// ship with the driver so production retry / circuit-breaker code is trivial:
1488///
1489/// ```no_run
1490/// # use oraclemcp_driver_cx::Error;
1491/// # fn classify(err: &Error) {
1492/// if err.is_connection_lost() {
1493///     // reconnect, then retry
1494/// } else if err.is_retryable() {
1495///     // back off and retry on the same connection
1496/// }
1497/// # }
1498/// ```
1499///
1500/// The classification sources, in priority order:
1501///
1502/// 1. The structured server error code (`ServerErrorInfo.code`) when present.
1503/// 2. Otherwise the `ORA-NNNNN` prefix parsed from the error message.
1504///
1505/// The curated transient and connection-lost code sets are maintained in this
1506/// module and exposed through the stable methods below.
1507impl Error {
1508    /// Stable top-level error category.
1509    pub fn kind(&self) -> ErrorKind {
1510        match self {
1511            Error::Protocol(err) => protocol_error_kind(err),
1512            Error::Io(_)
1513            | Error::ListenerRefused(_)
1514            | Error::AllAddressesFailed(_)
1515            | Error::ConnectionClosed(_)
1516            | Error::Tls(_)
1517            | Error::UnsupportedSni(_)
1518            | Error::Wallet(_) => ErrorKind::Network,
1519            Error::CallTimeout(_) => ErrorKind::Timeout,
1520            Error::Cancelled => ErrorKind::Cancel,
1521            Error::Conversion(_) | Error::Bind(_) => ErrorKind::Conversion,
1522            #[cfg(feature = "arrow")]
1523            Error::ArrowConversion(_) => ErrorKind::Conversion,
1524            Error::AccessTokenRequiresTcps
1525            | Error::UnsupportedAuthMode(_)
1526            | Error::IamTokenProofOfPossession
1527            | Error::TokenSource(_) => ErrorKind::Authentication,
1528            Error::RedirectUnsupported
1529            | Error::InvalidRedirectData(_)
1530            | Error::ConnectRedirectLoop(_)
1531            | Error::Runtime(_)
1532            | Error::FastAuthRequired
1533            | Error::UnexpectedPacket(_)
1534            | Error::ConnectResendLoop(_)
1535            | Error::MissingSessionField(_)
1536            | Error::SessionlessTransaction(_)
1537            | Error::UnknownTransactionState(_) => ErrorKind::Protocol,
1538            Error::NoRows | Error::TooManyRows => ErrorKind::Database,
1539        }
1540    }
1541
1542    /// Structured resource-limit details when this error came from
1543    /// [`oracledb_protocol::wire::ProtocolLimits`].
1544    pub fn resource_limit(&self) -> Option<oracledb_protocol::ResourceLimit> {
1545        match self {
1546            Error::Protocol(err) => err.resource_limit(),
1547            _ => None,
1548        }
1549    }
1550
1551    /// The Oracle error number (`ORA-NNNNN`) this error carries, if any.
1552    ///
1553    /// Returns the structured `ServerErrorInfo.code` when the error came back
1554    /// on the structured path; otherwise it parses the `ORA-` prefix out of the
1555    /// server message. `None` for non-server errors (I/O, timeouts, protocol
1556    /// decode failures) and server messages with no `ORA-` code.
1557    ///
1558    /// The value is an `i32` (rather than `u32`) so it composes directly with
1559    /// the `i32`-typed codes most retry tables and logging layers already use;
1560    /// every real Oracle code fits comfortably.
1561    pub fn ora_code(&self) -> Option<i32> {
1562        match self {
1563            Error::Protocol(err) => protocol_error_ora_code(err).map(|code| code as i32),
1564            // A user cancel is the client-side shape of the server's ORA-01013
1565            // "user requested cancel of current operation".
1566            Error::Cancelled => Some(1013),
1567            _ => None,
1568        }
1569    }
1570
1571    /// Alias for [`Self::ora_code`] using the API-design terminology.
1572    pub fn oracle_code(&self) -> Option<i32> {
1573        self.ora_code()
1574    }
1575
1576    /// The server-reported parse offset / error position for this error, if the
1577    /// server provided one (1-based character offset into the SQL text for a
1578    /// parse error). Only the structured server-error path retains the offset;
1579    /// `None` everywhere else, and `None` when the server reported offset 0.
1580    pub fn offset(&self) -> Option<i32> {
1581        match self {
1582            Error::Protocol(err) => protocol_error_offset(err),
1583            _ => None,
1584        }
1585    }
1586
1587    /// Render a compiler-style caret diagnostic for a parse error, pointing at
1588    /// the exact character in `sql` the server flagged ([`Error::offset`]):
1589    ///
1590    /// ```text
1591    /// ORA-00942: table or view does not exist
1592    ///   |
1593    /// 1 | select * from no_such_table
1594    ///   |               ^
1595    /// ```
1596    ///
1597    /// Returns `None` when the error carries no parse offset (only structured
1598    /// server parse errors do). The headline is this error's first `Display`
1599    /// line (the `ORA-` code + message). python-oracledb hands you a bare offset
1600    /// integer and leaves the rendering to you; this does it.
1601    pub fn caret(&self, sql: &str) -> Option<String> {
1602        let offset = usize::try_from(self.offset()?).ok()?;
1603        let full = self.to_string();
1604        let headline = full.lines().next().unwrap_or(full.as_str());
1605        Some(render_caret(sql, offset, headline))
1606    }
1607
1608    /// Whether the connection that surfaced this error is still reusable. A
1609    /// dead disposition means the session was killed, the socket was reset, or
1610    /// the server reported one of the session-dead Oracle codes; callers should
1611    /// discard the connection before continuing.
1612    ///
1613    /// Raw I/O errors ([`Error::Io`]) and the recovery-failure
1614    /// [`Error::ConnectionClosed`] also count as connection-lost: the transport
1615    /// is no longer usable.
1616    ///
1617    /// A plain [`Error::CallTimeout`] is deliberately **not** connection-lost.
1618    /// On a call timeout the driver sends a BREAK, then drains the server's
1619    /// in-flight response and the RESET handshake, leaving the wire stream
1620    /// clean and the connection reusable — exactly as python-oracledb does for
1621    /// `DPY-4024` (`ERR_CALL_TIMEOUT_EXCEEDED`), which, unlike `DPY-4011`
1622    /// (`ERR_CONNECTION_CLOSED`), does **not** set `is_session_dead`
1623    /// (errors.py:124-125). The connection survives; retry on the same one. Only
1624    /// when that drain itself fails (a *second* timeout) does the driver give up
1625    /// and surface [`Error::ConnectionClosed`], which *is* connection-lost.
1626    pub fn connection_disposition(&self) -> ConnectionDisposition {
1627        match self {
1628            Error::Io(_) | Error::ConnectionClosed(_) => ConnectionDisposition::Dead,
1629            _ if self
1630                .ora_code()
1631                .is_some_and(|code| SESSION_DEAD_ORA_CODES.contains(&(code as u32))) =>
1632            {
1633                ConnectionDisposition::Dead
1634            }
1635            _ => ConnectionDisposition::Reusable,
1636        }
1637    }
1638
1639    pub fn is_connection_lost(&self) -> bool {
1640        match self {
1641            Error::Io(_) | Error::ConnectionClosed(_) => true,
1642            _ => self
1643                .ora_code()
1644                .is_some_and(|code| CONNECTION_LOST_ORA_CODES.contains(&(code as u32))),
1645        }
1646    }
1647
1648    /// Whether this error is *transient*: the operation failed for a reason
1649    /// expected to clear on its own (lock contention, deadlock victim, listener
1650    /// hand-off congestion, resource-manager throttle, or a call timeout), so
1651    /// the same call may be retried on the **same** connection after a short
1652    /// back-off. Does **not** include connection-lost codes (those need a
1653    /// reconnect first — use [`Self::is_connection_lost`]).
1654    ///
1655    /// [`Error::CallTimeout`] is transient: after the driver drains the wire the
1656    /// connection is clean and reusable, so re-running the (idempotent) call on
1657    /// the same connection — e.g. with a longer timeout — is the natural retry.
1658    /// [`Error::Cancelled`] is transient for the same reason: an explicit cancel
1659    /// also drains the wire and leaves the session alive.
1660    pub fn is_transient(&self) -> bool {
1661        matches!(self, Error::CallTimeout(_) | Error::Cancelled)
1662            || self
1663                .ora_code()
1664                .is_some_and(|code| TRANSIENT_ORA_CODES.contains(&(code as u32)))
1665    }
1666
1667    /// Conservative retry guidance. Any returned retry action still requires
1668    /// the caller to know the operation is idempotent; non-idempotent operations
1669    /// must not be replayed automatically.
1670    pub fn retry_hint(&self) -> RetryHint {
1671        if self.is_transient() {
1672            RetryHint::RetrySameConnectionIfIdempotent
1673        } else if self.is_connection_lost() {
1674            RetryHint::ReconnectThenRetryIfIdempotent
1675        } else {
1676            RetryHint::Never
1677        }
1678    }
1679
1680    pub fn is_retryable(&self) -> bool {
1681        !matches!(self.retry_hint(), RetryHint::Never)
1682    }
1683}
1684
1685/// Client-API misuse of the sessionless transaction API, mirroring the
1686/// reference `ERR_SESSIONLESS_*` errors (impl/oracledb/errors.py:338-340).
1687#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1688#[non_exhaustive]
1689pub enum SessionlessError {
1690    /// DPY-3034: suspend/resume was attempted on a transaction started with
1691    /// DBMS_TRANSACTION (or vice versa).
1692    DifferingMethods,
1693    /// DPY-3035: a sessionless transaction is already active on the connection.
1694    AlreadyActive,
1695    /// DPY-3036: no sessionless transaction is active on the connection.
1696    Inactive,
1697}
1698
1699impl SessionlessError {
1700    /// The DPY full code (reference errors.py full codes).
1701    pub fn full_code(self) -> &'static str {
1702        match self {
1703            Self::DifferingMethods => "DPY-3034",
1704            Self::AlreadyActive => "DPY-3035",
1705            Self::Inactive => "DPY-3036",
1706        }
1707    }
1708
1709    /// The reference error message text (errors.py:945-953).
1710    pub fn message(self) -> &'static str {
1711        match self {
1712            Self::DifferingMethods => {
1713                "suspending or resuming a Sessionless Transaction can be done with \
1714                 DBMS_TRANSACTION or with python-oracledb, but not both"
1715            }
1716            Self::AlreadyActive => {
1717                "suspend, commit, or rollback the current active sessionless \
1718                 transaction before beginning or resuming another one"
1719            }
1720            Self::Inactive => "no Sessionless Transaction is active",
1721        }
1722    }
1723}
1724
1725impl std::fmt::Display for SessionlessError {
1726    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1727        write!(f, "{}: {}", self.full_code(), self.message())
1728    }
1729}
1730
1731/// Whether an execute error is the server signalling that the cached
1732/// statement's types no longer match (ORA-00932 inconsistent datatypes /
1733/// ORA-01007 variable not in select list), the two errors the reference
1734/// retries with a full parse (impl/thin/constants.pxi:166-167,
1735/// messages/base.pyx:1199-1213).
1736fn refetch_retry_applies(err: &Error) -> bool {
1737    let message = match err {
1738        Error::Protocol(oracledb_protocol::ProtocolError::ServerError(message)) => message,
1739        Error::Protocol(oracledb_protocol::ProtocolError::ServerErrorWithRowCount {
1740            message,
1741            ..
1742        }) => message,
1743        Error::Protocol(oracledb_protocol::ProtocolError::ServerErrorInfo(details)) => {
1744            // structured error path: match by ORA code directly (ORA-00932
1745            // inconsistent data types / ORA-01007 variable not in select list)
1746            return details.code == 932 || details.code == 1007;
1747        }
1748        _ => return false,
1749    };
1750    message.starts_with("ORA-00932") || message.starts_with("ORA-01007")
1751}
1752
1753/// A database access token used in place of a password — an OCI IAM database
1754/// token or an OAuth2 token. Its [`Debug`] output is redacted so the secret
1755/// never leaks into logs, error messages, or panic output. Set it with
1756/// [`ConnectOptions::with_access_token`].
1757#[derive(Clone)]
1758pub struct AccessToken(String);
1759
1760const REDACTED_SECRET: &str = "***redacted***";
1761
1762impl AccessToken {
1763    /// Wrap a token string. The value is never printed; see the type docs.
1764    pub fn new(token: impl Into<String>) -> Self {
1765        Self(token.into())
1766    }
1767
1768    /// The raw token, for sending on the wire. Crate-internal so callers cannot
1769    /// accidentally route the secret through `Display`/formatting.
1770    pub(crate) fn expose(&self) -> &str {
1771        &self.0
1772    }
1773}
1774
1775impl std::fmt::Debug for AccessToken {
1776    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1777        // Never render the token, regardless of formatter flags.
1778        f.write_str("AccessToken(")?;
1779        f.write_str(REDACTED_SECRET)?;
1780        f.write_str(")")
1781    }
1782}
1783
1784/// The RSA private key (PKCS#8 PEM) an OCI IAM database token is bound to, used
1785/// to sign the proof-of-possession header. Like [`AccessToken`] its [`Debug`]
1786/// is redacted so the key never leaks into logs, errors, or panics. Set it with
1787/// [`ConnectOptions::with_access_token_and_key`] or
1788/// [`ConnectOptions::with_token_source_and_key`].
1789#[derive(Clone)]
1790pub struct TokenPrivateKey(String);
1791
1792impl TokenPrivateKey {
1793    /// Wrap a PKCS#8 private-key PEM. The value is never printed; see the docs.
1794    pub fn new(pem: impl Into<String>) -> Self {
1795        Self(pem.into())
1796    }
1797
1798    /// The raw PEM, for signing only. Crate-internal so callers cannot route the
1799    /// secret through `Display`/formatting.
1800    pub(crate) fn expose(&self) -> &str {
1801        &self.0
1802    }
1803}
1804
1805impl std::fmt::Debug for TokenPrivateKey {
1806    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1807        f.write_str("TokenPrivateKey(")?;
1808        f.write_str(REDACTED_SECRET)?;
1809        f.write_str(")")
1810    }
1811}
1812
1813/// A boxed, `Send` future — the return type of [`TokenSource::get_token`].
1814///
1815/// Defined locally because the driver takes no dependency on the `futures`
1816/// crate; it is the conventional `Pin<Box<dyn Future + Send>>` shape.
1817pub type BoxFuture<'a, T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
1818
1819/// Failure classes a [`TokenSource`] may report.
1820///
1821/// Every variant is **fully redacted**: neither [`Debug`] nor [`std::fmt::Display`]
1822/// reveals any inner detail. The variants carry no payload by construction, so a
1823/// token, a signed assertion, or a raw provider response can never leak through
1824/// a token-source failure into logs, error chains, or panic output. A provider
1825/// maps its underlying error into one of these classes and drops the detail —
1826/// fail-closed.
1827#[derive(Clone, Copy, Eq, PartialEq)]
1828#[non_exhaustive]
1829pub enum TokenSourceError {
1830    /// The provider (command / process / HTTP call) failed to execute or exited
1831    /// unsuccessfully.
1832    Exec,
1833    /// The provider ran but returned something that is not a usable token.
1834    Invalid,
1835    /// The provider did not produce a token within its own deadline.
1836    Timeout,
1837    /// Any other provider failure.
1838    Other,
1839}
1840
1841impl TokenSourceError {
1842    /// A stable, non-secret label for this failure class.
1843    pub fn as_str(&self) -> &'static str {
1844        match self {
1845            Self::Exec => "exec",
1846            Self::Invalid => "invalid",
1847            Self::Timeout => "timeout",
1848            Self::Other => "other",
1849        }
1850    }
1851}
1852
1853impl std::fmt::Display for TokenSourceError {
1854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1855        let msg = match self {
1856            Self::Exec => "token source failed to execute",
1857            Self::Invalid => "token source returned an invalid token",
1858            Self::Timeout => "token source timed out",
1859            Self::Other => "token source failed",
1860        };
1861        f.write_str(msg)
1862    }
1863}
1864
1865impl std::fmt::Debug for TokenSourceError {
1866    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1867        // Only the class name — there is no payload and nothing to leak.
1868        write!(f, "TokenSourceError::{}", {
1869            match self {
1870                Self::Exec => "Exec",
1871                Self::Invalid => "Invalid",
1872                Self::Timeout => "Timeout",
1873                Self::Other => "Other",
1874            }
1875        })
1876    }
1877}
1878
1879impl std::error::Error for TokenSourceError {}
1880
1881/// A pluggable source of OCI IAM / OAuth2 database access tokens.
1882///
1883/// Implement this to obtain a fresh token at connect time (for example by
1884/// shelling out to the OCI CLI, calling an instance-principal endpoint, or
1885/// reading a short-lived token file). The driver calls [`get_token`] **once
1886/// for each physical connection attempt**, before it dials a TCPS endpoint.
1887/// The source owns freshness: this interface returns only a token string, so
1888/// the driver cannot inspect token expiry and does not retry after an
1889/// authentication rejection. Return a current token on every call (or retain
1890/// and refresh it inside the source). The returned token is placed in
1891/// `AUTH_TOKEN` and therefore requires a TCPS transport; a token source on a
1892/// plaintext descriptor is refused with [`Error::AccessTokenRequiresTcps`]
1893/// *before* the source is ever consulted, so a token is never fetched for a
1894/// connection that could not carry it securely.
1895///
1896/// The token itself must never be logged; report failures as the redacted
1897/// [`TokenSourceError`].
1898///
1899/// [`get_token`]: TokenSource::get_token
1900pub trait TokenSource: Send + Sync {
1901    /// Fetch a fresh database access token, or a redacted failure class.
1902    fn get_token(&self) -> BoxFuture<'_, std::result::Result<String, TokenSourceError>>;
1903}
1904
1905/// Stable classifier for the thin driver's authentication modes.
1906#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1907#[non_exhaustive]
1908pub enum AuthModeKind {
1909    Password,
1910    Proxy,
1911    External,
1912    IamToken,
1913    Kerberos,
1914    Radius,
1915}
1916
1917impl std::fmt::Display for AuthModeKind {
1918    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1919        let name = match self {
1920            Self::Password => "password",
1921            Self::Proxy => "proxy",
1922            Self::External => "external",
1923            Self::IamToken => "iam-token",
1924            Self::Kerberos => "kerberos",
1925            Self::Radius => "radius",
1926        };
1927        f.write_str(name)
1928    }
1929}
1930
1931/// Whether a known authentication mode is implemented by this thin driver.
1932#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1933#[non_exhaustive]
1934pub enum AuthModeSupport {
1935    Supported,
1936    UnsupportedInThin,
1937}
1938
1939/// Queryable authentication capability metadata for this build.
1940#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1941#[non_exhaustive]
1942pub struct AuthCapabilities {
1943    pub password: AuthModeSupport,
1944    pub proxy: AuthModeSupport,
1945    pub external: AuthModeSupport,
1946    pub iam_token: AuthModeSupport,
1947    pub kerberos: AuthModeSupport,
1948    pub radius: AuthModeSupport,
1949}
1950
1951impl AuthCapabilities {
1952    /// Capabilities of the current pure-thin implementation.
1953    pub const THIN: Self = Self {
1954        password: AuthModeSupport::Supported,
1955        proxy: AuthModeSupport::Supported,
1956        external: AuthModeSupport::UnsupportedInThin,
1957        iam_token: AuthModeSupport::Supported,
1958        kerberos: AuthModeSupport::UnsupportedInThin,
1959        radius: AuthModeSupport::UnsupportedInThin,
1960    };
1961
1962    #[must_use]
1963    pub fn support(self, mode: AuthModeKind) -> AuthModeSupport {
1964        match mode {
1965            AuthModeKind::Password => self.password,
1966            AuthModeKind::Proxy => self.proxy,
1967            AuthModeKind::External => self.external,
1968            AuthModeKind::IamToken => self.iam_token,
1969            AuthModeKind::Kerberos => self.kerberos,
1970            AuthModeKind::Radius => self.radius,
1971        }
1972    }
1973}
1974
1975/// A known authentication mode selected by the caller.
1976#[derive(Clone, Eq, PartialEq)]
1977#[non_exhaustive]
1978pub enum AuthMode {
1979    Password,
1980    Proxy,
1981    External,
1982    IamToken,
1983    Kerberos {
1984        principal: Option<String>,
1985        keytab: Option<String>,
1986    },
1987    Radius {
1988        challenge: Option<String>,
1989    },
1990}
1991
1992impl AuthMode {
1993    #[must_use]
1994    pub fn kind(&self) -> AuthModeKind {
1995        match self {
1996            Self::Password => AuthModeKind::Password,
1997            Self::Proxy => AuthModeKind::Proxy,
1998            Self::External => AuthModeKind::External,
1999            Self::IamToken => AuthModeKind::IamToken,
2000            Self::Kerberos { .. } => AuthModeKind::Kerberos,
2001            Self::Radius { .. } => AuthModeKind::Radius,
2002        }
2003    }
2004
2005    fn unsupported_in_thin(&self) -> Option<UnsupportedAuthMode> {
2006        let mode = self.kind();
2007        (AuthCapabilities::THIN.support(mode) == AuthModeSupport::UnsupportedInThin)
2008            .then_some(UnsupportedAuthMode { mode })
2009    }
2010}
2011
2012impl std::fmt::Debug for AuthMode {
2013    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2014        fn redacted(value: &Option<String>) -> Option<&'static str> {
2015            value.as_ref().map(|_| REDACTED_SECRET)
2016        }
2017
2018        match self {
2019            Self::Password => f.write_str("Password"),
2020            Self::Proxy => f.write_str("Proxy"),
2021            Self::External => f.write_str("External"),
2022            Self::IamToken => f.write_str("IamToken"),
2023            Self::Kerberos { principal, keytab } => f
2024                .debug_struct("Kerberos")
2025                .field("principal", &redacted(principal))
2026                .field("keytab", &redacted(keytab))
2027                .finish(),
2028            Self::Radius { challenge } => f
2029                .debug_struct("Radius")
2030                .field("challenge", &redacted(challenge))
2031                .finish(),
2032        }
2033    }
2034}
2035
2036/// Structured unsupported-authentication diagnostic.
2037#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
2038#[error("authentication mode {mode} is not supported by this thin build")]
2039pub struct UnsupportedAuthMode {
2040    mode: AuthModeKind,
2041}
2042
2043impl UnsupportedAuthMode {
2044    #[must_use]
2045    pub fn mode(&self) -> AuthModeKind {
2046        self.mode
2047    }
2048}
2049
2050/// Parse a username that may use the reference bracket form.
2051///
2052/// Mirrors python-oracledb `ConnectParamsImpl.parse_user` after upstream
2053/// e861662a75b5: `base[proxy]` splits into base user + proxy; `[proxy]`
2054/// (leading bracket, empty base) is valid for token-auth proxy-only sessions.
2055/// A string that does not end in `]` or has no `[` is returned unchanged with
2056/// no proxy. The closing `]` must be the final character.
2057pub fn parse_user_and_proxy(user: &str) -> (String, Option<String>) {
2058    if let Some(start) = user.find('[') {
2059        if user.ends_with(']') && start < user.len() - 1 {
2060            let base = user[..start].to_string();
2061            let proxy = user[start + 1..user.len() - 1].to_string();
2062            return (base, Some(proxy));
2063        }
2064    }
2065    (user.to_string(), None)
2066}
2067
2068/// Everything needed to open a connection: where to connect, who to
2069/// authenticate as, and the [`ClientIdentity`] the database will record.
2070///
2071/// Build the required fields with [`ConnectOptions::new`], then layer optional
2072/// settings with the `with_*` methods.
2073#[derive(Clone)]
2074pub struct ConnectOptions {
2075    /// EasyConnect descriptor, `host:port/service_name` (the port and service
2076    /// may be omitted to take the listener defaults).
2077    connect_string: String,
2078    /// Database user to authenticate as.
2079    user: String,
2080    /// Password for `user`.
2081    password: String,
2082    /// Session identity reported to the database (`v$session`).
2083    identity: ClientIdentity,
2084    /// Application-context triples `(namespace, key, value)` set on the
2085    /// session at logon (reference `connection.appcontext`).
2086    app_context: Vec<(String, String, String)>,
2087    /// Session Data Unit (negotiated packet size) in bytes.
2088    sdu: u16,
2089    /// Proxy user for `[proxy_user]` style connections, if any.
2090    proxy_user: Option<String>,
2091    /// Authentication mode selected by the caller. Unsupported thin modes fail
2092    /// before network I/O with [`Error::UnsupportedAuthMode`].
2093    auth_mode: AuthMode,
2094    /// When set, `(SERVER=emon)` is injected into the connect descriptor's
2095    /// `CONNECT_DATA`. This routes the connection to the database EMON process
2096    /// used to push CQN notifications (reference `subscr.pyx` rewrites
2097    /// `description.server_type = "emon"` for the background connection).
2098    server_type_emon: bool,
2099    /// TCPS wallet directory (`MY_WALLET_DIRECTORY` / `wallet_location`). The
2100    /// directory should contain `ewallet.pem`, `ewallet.p12` (requires
2101    /// `wallet_password`), or `cwallet.sso`. When `None`, `TNS_ADMIN` is
2102    /// consulted; the special value `SYSTEM` (case-insensitive) forces the
2103    /// system trust store. Only consulted for TCPS connections.
2104    wallet_location: Option<String>,
2105    /// Password for an encrypted wallet (`ewallet.p12`, or an `ewallet.pem`
2106    /// with an encrypted private key). `None` for auto-login or verify-only
2107    /// wallets.
2108    wallet_password: Option<String>,
2109    /// Oracle edition for Edition-Based Redefinition (`AUTH_ORA_EDITION`),
2110    /// applied during authentication before any user SQL. `None` uses the
2111    /// database default edition.
2112    edition: Option<String>,
2113    /// Run the Oracle server-DN match after the TLS handshake
2114    /// (`ssl_server_dn_match`, reference default `true`).
2115    ssl_server_dn_match: bool,
2116    /// Explicit expected server-certificate distinguished name
2117    /// (`ssl_server_cert_dn`). When set, the server's subject DN must equal
2118    /// this exactly; when `None`, the host name is matched against the
2119    /// certificate's SAN DNS names and common names.
2120    ssl_server_cert_dn: Option<String>,
2121    /// Send the Oracle TCPS SNI string (`use_sni`, reference default `false`).
2122    /// See [`tls::TlsParams::use_sni`] for the rustls-name-validity caveat.
2123    use_sni: bool,
2124    /// Authenticate with a database access token (OCI IAM / OAuth2) instead of
2125    /// `password`. When set, the token is sent as `AUTH_TOKEN` and no password
2126    /// verifier is exchanged. Token auth requires a TLS/TCPS transport; see
2127    /// [`ConnectOptions::with_access_token`]. The token is redacted from `Debug`.
2128    access_token: Option<AccessToken>,
2129    /// The RSA private key (PKCS#8 PEM) an OCI IAM **database** token is bound
2130    /// to. When present (with an `access_token`), the driver performs the
2131    /// token's proof-of-possession: it signs the auth header with this key and
2132    /// sends `AUTH_HEADER`/`AUTH_SIGNATURE` so the server can verify possession
2133    /// against the token's embedded public key. Required for OCI IAM database
2134    /// tokens (`oci iam db-token get`); a plain OAuth2 bearer token needs none.
2135    /// Redacted from `Debug`. Set with
2136    /// [`ConnectOptions::with_access_token_and_key`] or
2137    /// [`ConnectOptions::with_token_source_and_key`].
2138    access_token_private_key: Option<TokenPrivateKey>,
2139    /// Pluggable source of database access tokens (OCI IAM / OAuth2). When set
2140    /// and no static [`access_token`](Self::access_token) is present, the driver
2141    /// calls it once for each physical connection attempt. The source owns
2142    /// freshness; the driver does not inspect expiry or retry a rejected token.
2143    /// Like a static token it requires TCPS; a token source on a plaintext
2144    /// descriptor is refused before it is ever consulted. Set with
2145    /// [`ConnectOptions::with_token_source`].
2146    token_source: Option<std::sync::Arc<dyn TokenSource>>,
2147    /// Maximum number of open statements kept in this connection's statement
2148    /// cache. Defaults to 20 (the reference default). `0` disables caching
2149    /// entirely (every statement's cursor is closed after use, never retained),
2150    /// matching python-oracledb's `stmtcachesize=0`. The cache holds at most this
2151    /// many entries, each a small `(sql, cursor_id)` pair, so it is bounded by
2152    /// construction. Set with [`ConnectOptions::with_statement_cache_size`].
2153    statement_cache_size: usize,
2154    /// Resource policy for thin-protocol decoding and packet reassembly.
2155    protocol_limits: ProtocolLimits,
2156    /// Optional read-inactivity deadline applied to every post-auth wire read
2157    /// (GH#14). When `Some(d)`, a single read operation that makes no progress
2158    /// within `d` fails with [`Error::CallTimeout`] rather than hanging forever
2159    /// on a silent or half-open server. `None` (the default) preserves the prior
2160    /// unbounded-read behaviour; operators opt in per connection with
2161    /// [`ConnectOptions::with_inactivity_timeout`]. The CONNECT/ACCEPT phase is
2162    /// bounded separately by the DSN transport-connect timeout, and TCP keepalive
2163    /// is derived from a DSN `EXPIRE_TIME`.
2164    inactivity_timeout: Option<Duration>,
2165    /// Optional cross-connection statement-shape cache (bead a4-8pp). When set,
2166    /// every connection built from these options shares this cache, so a query's
2167    /// described result-column shape is tracked across connections and a
2168    /// concurrent DDL that changes the shape triggers a self-heal (re-describe)
2169    /// on the next execute instead of a stale decode. `None` (default) gives
2170    /// each connection a private cache, preserving the prior per-connection
2171    /// behaviour. Set with
2172    /// [`ConnectOptions::with_shared_statement_shape_cache`].
2173    statement_shape_cache: Option<Arc<StatementShapeCache>>,
2174}
2175
2176impl std::fmt::Debug for ConnectOptions {
2177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2178        let wallet_location = self.wallet_location.as_ref().map(|_| REDACTED_SECRET);
2179        let wallet_password = self.wallet_password.as_ref().map(|_| REDACTED_SECRET);
2180        let server_cert_dn = self.ssl_server_cert_dn.as_ref().map(|_| REDACTED_SECRET);
2181        f.debug_struct("ConnectOptions")
2182            .field("connect_string", &self.connect_string)
2183            .field("user", &self.full_user())
2184            .field("password", &REDACTED_SECRET)
2185            .field("identity", &self.identity)
2186            .field("app_context", &self.app_context)
2187            .field("sdu", &self.sdu)
2188            .field("proxy_user", &self.proxy_user)
2189            .field("auth_mode", &self.auth_mode)
2190            .field("server_type_emon", &self.server_type_emon)
2191            .field("wallet_location", &wallet_location)
2192            .field("wallet_password", &wallet_password)
2193            .field("edition", &self.edition)
2194            .field("ssl_server_dn_match", &self.ssl_server_dn_match)
2195            .field("ssl_server_cert_dn", &server_cert_dn)
2196            .field("use_sni", &self.use_sni)
2197            .field("access_token", &self.access_token)
2198            .field("access_token_private_key", &self.access_token_private_key)
2199            .field(
2200                "token_source",
2201                &self.token_source.as_ref().map(|_| "<token source>"),
2202            )
2203            .field("statement_cache_size", &self.statement_cache_size)
2204            .field("protocol_limits", &self.protocol_limits)
2205            .field("inactivity_timeout", &self.inactivity_timeout)
2206            .field(
2207                "statement_shape_cache",
2208                &self
2209                    .statement_shape_cache
2210                    .as_ref()
2211                    .map(|_| "<shared statement-shape cache>"),
2212            )
2213            .finish()
2214    }
2215}
2216
2217impl ConnectOptions {
2218    /// Create connect options with the required fields. `connect_string` is an
2219    /// EasyConnect descriptor (`host:port/service_name`); `identity` is the
2220    /// session identity the database will record. Optional settings default to
2221    /// an 8 KiB SDU, no application context, and no proxy user.
2222    ///
2223    /// `user` may be a plain username or the reference bracket form
2224    /// `base[proxy]` / `[proxy]` (proxy-only, typically with token auth). See
2225    /// [`parse_user_and_proxy`]. An explicit later [`Self::with_proxy_user`]
2226    /// call overwrites any proxy desugared here.
2227    pub fn new(
2228        connect_string: impl Into<String>,
2229        user: impl Into<String>,
2230        password: impl Into<String>,
2231        identity: ClientIdentity,
2232    ) -> Self {
2233        let raw_user = user.into();
2234        let (user, proxy_user) = parse_user_and_proxy(&raw_user);
2235        let auth_mode = if proxy_user.is_some() {
2236            AuthMode::Proxy
2237        } else {
2238            AuthMode::Password
2239        };
2240        Self {
2241            connect_string: connect_string.into(),
2242            user,
2243            password: password.into(),
2244            identity,
2245            app_context: Vec::new(),
2246            sdu: 8192,
2247            proxy_user,
2248            auth_mode,
2249            server_type_emon: false,
2250            wallet_location: None,
2251            wallet_password: None,
2252            ssl_server_dn_match: true,
2253            ssl_server_cert_dn: None,
2254            use_sni: false,
2255            edition: None,
2256            access_token: None,
2257            access_token_private_key: None,
2258            token_source: None,
2259            statement_cache_size: STATEMENT_CACHE_SIZE,
2260            protocol_limits: ProtocolLimits::DEFAULT,
2261            inactivity_timeout: None,
2262            statement_shape_cache: None,
2263        }
2264    }
2265
2266    /// Create connect options that express passwordless external authentication
2267    /// intent without caller-supplied dummy credentials. This thin build
2268    /// currently reports the mode as [`Error::UnsupportedAuthMode`] before any
2269    /// network I/O; use [`Self::auth_capabilities`] to inspect support.
2270    pub fn external_auth(connect_string: impl Into<String>, identity: ClientIdentity) -> Self {
2271        let mut options = Self::new(connect_string, "", "", identity);
2272        options.auth_mode = AuthMode::External;
2273        options
2274    }
2275
2276    /// Create connect options for Kerberos intent. Real Kerberos/GSSAPI
2277    /// exchange is not implemented in this thin build; principal and keytab are
2278    /// carried only for structured diagnostics and are redacted from `Debug`.
2279    pub fn kerberos_auth(
2280        connect_string: impl Into<String>,
2281        principal: impl Into<String>,
2282        keytab: impl Into<String>,
2283        identity: ClientIdentity,
2284    ) -> Self {
2285        let mut options = Self::new(connect_string, "", "", identity);
2286        options.auth_mode = AuthMode::Kerberos {
2287            principal: Some(principal.into()),
2288            keytab: Some(keytab.into()),
2289        };
2290        options
2291    }
2292
2293    /// Create connect options for RADIUS/native-MFA intent. Real challenge
2294    /// exchange is not implemented in this thin build; the challenge hint is
2295    /// carried only for structured diagnostics and is redacted from `Debug`.
2296    pub fn radius_auth(
2297        connect_string: impl Into<String>,
2298        challenge: impl Into<String>,
2299        identity: ClientIdentity,
2300    ) -> Self {
2301        let mut options = Self::new(connect_string, "", "", identity);
2302        options.auth_mode = AuthMode::Radius {
2303            challenge: Some(challenge.into()),
2304        };
2305        options
2306    }
2307
2308    /// Set the thin-protocol resource limits. Invalid policies are rejected at
2309    /// connect time before any network I/O.
2310    #[must_use]
2311    pub fn with_protocol_limits(mut self, limits: ProtocolLimits) -> Self {
2312        self.protocol_limits = limits;
2313        self
2314    }
2315
2316    /// Set a read-inactivity deadline for every post-auth wire read on this
2317    /// connection (GH#14). A read operation that makes no progress within
2318    /// `timeout` fails with [`Error::CallTimeout`] rather than hanging forever on
2319    /// a silent or half-open peer (a half-open connection whose FIN/RST was lost
2320    /// otherwise wedges the read indefinitely). Unset by default, which keeps the
2321    /// prior unbounded-read behaviour. The CONNECT/ACCEPT phase is bounded by the
2322    /// DSN transport-connect timeout; this governs only established-session reads.
2323    #[must_use]
2324    pub fn with_inactivity_timeout(mut self, timeout: Duration) -> Self {
2325        self.inactivity_timeout = Some(timeout);
2326        self
2327    }
2328
2329    /// Set the statement-cache capacity for this connection (number of open
2330    /// statements retained for reuse). `0` disables caching — every statement's
2331    /// cursor is closed after use rather than cached (python-oracledb
2332    /// `stmtcachesize=0` semantics). The default is 20. The cache is bounded to
2333    /// this many small entries, so a large value cannot cause unbounded growth
2334    /// beyond the count of distinct prepared statements.
2335    #[must_use]
2336    pub fn with_statement_cache_size(mut self, size: usize) -> Self {
2337        self.statement_cache_size = size;
2338        self
2339    }
2340
2341    /// Authenticate with a database access token instead of a password — an OCI
2342    /// IAM database token or an OAuth2 token (python-oracledb's `access_token`).
2343    /// The token is sent as `AUTH_TOKEN` with no password-verifier exchange.
2344    ///
2345    /// Token authentication **requires** a TLS/TCPS connection (the token would
2346    /// otherwise travel in clear text); connecting with a token over plain TCP
2347    /// fails with the typed [`Error::AccessTokenRequiresTcps`]. The token is
2348    /// wrapped in [`AccessToken`], whose `Debug` is redacted, so it never appears
2349    /// in logs or error output.
2350    #[must_use]
2351    pub fn with_access_token(mut self, token: impl Into<String>) -> Self {
2352        self.access_token = Some(AccessToken::new(token));
2353        self.auth_mode = AuthMode::IamToken;
2354        self
2355    }
2356
2357    /// Authenticate with an OCI IAM **database** token and its bound RSA private
2358    /// key (`oci iam db-token get` writes the token and a PKCS#8 `oci_db_key.pem`).
2359    ///
2360    /// Unlike a plain OAuth2 bearer token, an OCI IAM database token is a
2361    /// proof-of-possession credential: the token embeds a public key and the
2362    /// database refuses the bearer token alone with `ORA-01017`. With the private
2363    /// key set, the driver signs the auth header (RSA-PKCS1v15 + SHA-256) and
2364    /// sends `AUTH_HEADER`/`AUTH_SIGNATURE`, which the server verifies against the
2365    /// token's embedded public key. Like [`Self::with_access_token`] this selects
2366    /// token auth and therefore **requires** a TLS/TCPS connection. Both the token
2367    /// and the key are redacted from `Debug`.
2368    #[must_use]
2369    pub fn with_access_token_and_key(
2370        mut self,
2371        token: impl Into<String>,
2372        private_key_pkcs8_pem: impl Into<String>,
2373    ) -> Self {
2374        self.access_token = Some(AccessToken::new(token));
2375        self.access_token_private_key = Some(TokenPrivateKey::new(private_key_pkcs8_pem));
2376        self.auth_mode = AuthMode::IamToken;
2377        self
2378    }
2379
2380    /// Authenticate with an OCI IAM **database** token obtained from a
2381    /// refreshable [`TokenSource`] and its bound RSA private key (PKCS#8 PEM).
2382    ///
2383    /// OCI IAM database tokens are proof-of-possession credentials: each token
2384    /// is bound to the supplied key, which the driver uses to produce
2385    /// `AUTH_HEADER`/`AUTH_SIGNATURE`. The source is consulted once for every
2386    /// physical connection attempt, so it owns freshness; no token is stored in
2387    /// these options. As with [`Self::with_token_source`], the descriptor must
2388    /// use TLS/TCPS or the driver fails with [`Error::AccessTokenRequiresTcps`]
2389    /// before consulting the source. Both the source's token and the key remain
2390    /// redacted from [`Debug`].
2391    ///
2392    /// This method deliberately does not set a static access token. Supplying a
2393    /// static token separately still takes precedence, exactly as documented by
2394    /// [`Self::with_token_source`].
2395    #[must_use]
2396    pub fn with_token_source_and_key(
2397        mut self,
2398        source: std::sync::Arc<dyn TokenSource>,
2399        private_key_pkcs8_pem: impl Into<String>,
2400    ) -> Self {
2401        self.token_source = Some(source);
2402        self.access_token_private_key = Some(TokenPrivateKey::new(private_key_pkcs8_pem));
2403        self.auth_mode = AuthMode::IamToken;
2404        self
2405    }
2406
2407    /// Authenticate with a database access token obtained from a pluggable
2408    /// [`TokenSource`] (OCI IAM / OAuth2). The driver calls the source once for
2409    /// each physical connection attempt. The source owns freshness: this API
2410    /// does not expose token expiry, so the driver neither inspects expiry nor
2411    /// retries after an authentication rejection. Like
2412    /// [`Self::with_access_token`] this selects token auth and therefore
2413    /// **requires** a TLS/TCPS connection: a token source on a plaintext
2414    /// descriptor fails with the typed [`Error::AccessTokenRequiresTcps`]
2415    /// *before* the source is consulted, so a token is never fetched for a
2416    /// transport that could not carry it securely.
2417    ///
2418    /// A static [`Self::with_access_token`] takes precedence if both are set.
2419    #[must_use]
2420    pub fn with_token_source(mut self, source: std::sync::Arc<dyn TokenSource>) -> Self {
2421        self.token_source = Some(source);
2422        self.auth_mode = AuthMode::IamToken;
2423        self
2424    }
2425
2426    /// The configured [`TokenSource`], if any.
2427    pub fn token_source(&self) -> Option<&std::sync::Arc<dyn TokenSource>> {
2428        self.token_source.as_ref()
2429    }
2430
2431    /// Share a [`StatementShapeCache`] across every connection built from these
2432    /// options (bead a4-8pp). With a shared cache, a query's described
2433    /// result-column shape is tracked cross-connection: if a concurrent DDL on
2434    /// one connection changes the shape, the next execute of the same statement
2435    /// on any sharing connection self-heals (re-describes) rather than decoding
2436    /// against the stale shape. Without this, each connection keeps a private
2437    /// cache and behaves exactly as before.
2438    #[must_use]
2439    pub fn with_shared_statement_shape_cache(mut self, cache: Arc<StatementShapeCache>) -> Self {
2440        self.statement_shape_cache = Some(cache);
2441        self
2442    }
2443
2444    /// The shared [`StatementShapeCache`], if one was configured.
2445    pub fn statement_shape_cache(&self) -> Option<&Arc<StatementShapeCache>> {
2446        self.statement_shape_cache.as_ref()
2447    }
2448
2449    /// Select passwordless external authentication intent on an existing
2450    /// options value. This is useful for code that starts from a shared
2451    /// `ConnectOptions::new` builder path; [`Self::external_auth`] avoids
2452    /// requiring credentials in the first place.
2453    #[must_use]
2454    pub fn with_external_auth(mut self) -> Self {
2455        self.auth_mode = AuthMode::External;
2456        self.user.clear();
2457        self.password.clear();
2458        self
2459    }
2460
2461    /// Select Kerberos authentication intent. Principal and keytab values are
2462    /// redacted from every `Debug` representation and are not sent on the wire
2463    /// because this thin build returns [`Error::UnsupportedAuthMode`] for the
2464    /// mode before network I/O.
2465    #[must_use]
2466    pub fn with_kerberos_auth(
2467        mut self,
2468        principal: impl Into<String>,
2469        keytab: impl Into<String>,
2470    ) -> Self {
2471        self.auth_mode = AuthMode::Kerberos {
2472            principal: Some(principal.into()),
2473            keytab: Some(keytab.into()),
2474        };
2475        self.user.clear();
2476        self.password.clear();
2477        self
2478    }
2479
2480    /// Select RADIUS/native-MFA authentication intent. The challenge hint is
2481    /// redacted from `Debug` and is not sent on the wire because this thin
2482    /// build returns [`Error::UnsupportedAuthMode`] for the mode before network
2483    /// I/O.
2484    #[must_use]
2485    pub fn with_radius_auth(mut self, challenge: impl Into<String>) -> Self {
2486        self.auth_mode = AuthMode::Radius {
2487            challenge: Some(challenge.into()),
2488        };
2489        self.user.clear();
2490        self.password.clear();
2491        self
2492    }
2493
2494    /// Select the Oracle edition for this session (Edition-Based Redefinition).
2495    /// Applied via `AUTH_ORA_EDITION` during authentication, *before* any user
2496    /// SQL — deterministic even for pooled/reused sessions. Verify with
2497    /// `SYS_CONTEXT('USERENV','CURRENT_EDITION_NAME')`. An invalid/unauthorized
2498    /// edition surfaces as a typed server error at connect time.
2499    #[must_use]
2500    pub fn with_edition(mut self, edition: impl Into<String>) -> Self {
2501        self.edition = Some(edition.into());
2502        self
2503    }
2504
2505    /// Enable sending the Oracle TCPS SNI string (`use_sni`, default off).
2506    #[must_use]
2507    pub fn with_use_sni(mut self, use_sni: bool) -> Self {
2508        self.use_sni = use_sni;
2509        self
2510    }
2511
2512    /// Set the TCPS wallet directory (`wallet_location` /
2513    /// `MY_WALLET_DIRECTORY`). Only used for TCPS connections.
2514    #[must_use]
2515    pub fn with_wallet_location(mut self, location: impl Into<String>) -> Self {
2516        self.wallet_location = Some(location.into());
2517        self
2518    }
2519
2520    /// Set the wallet password — required for `ewallet.p12` wallets and for an
2521    /// `ewallet.pem` whose private key is encrypted (PKCS#8 `ENCRYPTED PRIVATE
2522    /// KEY`). Not needed for auto-login (`cwallet.sso`) or verify-only wallets.
2523    #[must_use]
2524    pub fn with_wallet_password(mut self, password: impl Into<String>) -> Self {
2525        self.wallet_password = Some(password.into());
2526        self
2527    }
2528
2529    /// Enable or disable the Oracle server-DN match (`ssl_server_dn_match`,
2530    /// default enabled).
2531    #[must_use]
2532    pub fn with_ssl_server_dn_match(mut self, enabled: bool) -> Self {
2533        self.ssl_server_dn_match = enabled;
2534        self
2535    }
2536
2537    /// Set the explicit expected server-certificate DN
2538    /// (`ssl_server_cert_dn`).
2539    #[must_use]
2540    pub fn with_ssl_server_cert_dn(mut self, dn: impl Into<String>) -> Self {
2541        self.ssl_server_cert_dn = Some(dn.into());
2542        self
2543    }
2544
2545    /// Route this connection to the database EMON process by injecting
2546    /// `(SERVER=emon)` into the connect descriptor (used by the CQN background
2547    /// notification connection).
2548    pub fn with_server_type_emon(mut self, emon: bool) -> Self {
2549        self.server_type_emon = emon;
2550        self
2551    }
2552
2553    /// Set the application-context triples applied at logon.
2554    pub fn with_app_context(mut self, app_context: Vec<(String, String, String)>) -> Self {
2555        self.app_context = app_context;
2556        self
2557    }
2558
2559    /// Set the proxy user for `[proxy_user]` style authentication.
2560    ///
2561    /// When `Some`, this **overwrites** any proxy desugared from a bracketed
2562    /// username in [`Self::new`] (explicit API wins). Passing `None` clears the
2563    /// proxy and, if the mode was only Proxy, restores password mode.
2564    pub fn with_proxy_user(mut self, proxy_user: Option<String>) -> Self {
2565        if proxy_user.is_some() {
2566            self.auth_mode = AuthMode::Proxy;
2567        } else if matches!(self.auth_mode, AuthMode::Proxy) {
2568            self.auth_mode = AuthMode::Password;
2569        }
2570        self.proxy_user = proxy_user;
2571        self
2572    }
2573
2574    /// Request a Session Data Unit size, clamped to the protocol-legal range
2575    /// `512..=65535` bytes. The value is a hint; the server negotiates the
2576    /// effective SDU at connect time.
2577    pub fn with_sdu(mut self, sdu: u32) -> Self {
2578        let clamped = sdu.clamp(512, u32::from(u16::MAX));
2579        self.sdu = u16::try_from(clamped).unwrap_or(u16::MAX);
2580        self
2581    }
2582
2583    pub fn connect_string(&self) -> &str {
2584        &self.connect_string
2585    }
2586
2587    pub fn user(&self) -> &str {
2588        &self.user
2589    }
2590
2591    /// Full user display including any proxy, matching the reference
2592    /// `get_full_user` form: `base[proxy]`, or `[proxy]` when the base user is
2593    /// empty (token-auth proxy-only sessions). Never includes the password.
2594    pub fn full_user(&self) -> String {
2595        match (self.user.as_str(), self.proxy_user.as_deref()) {
2596            ("", Some(proxy)) => format!("[{proxy}]"),
2597            (base, Some(proxy)) => format!("{base}[{proxy}]"),
2598            (base, None) => base.to_string(),
2599        }
2600    }
2601
2602    pub fn password(&self) -> &str {
2603        &self.password
2604    }
2605
2606    pub fn identity(&self) -> &ClientIdentity {
2607        &self.identity
2608    }
2609
2610    pub fn app_context(&self) -> &[(String, String, String)] {
2611        &self.app_context
2612    }
2613
2614    pub fn sdu(&self) -> u16 {
2615        self.sdu
2616    }
2617
2618    pub fn proxy_user(&self) -> Option<&str> {
2619        self.proxy_user.as_deref()
2620    }
2621
2622    pub fn auth_mode(&self) -> &AuthMode {
2623        &self.auth_mode
2624    }
2625
2626    pub fn auth_capabilities(&self) -> AuthCapabilities {
2627        AuthCapabilities::THIN
2628    }
2629
2630    pub fn server_type_emon(&self) -> bool {
2631        self.server_type_emon
2632    }
2633
2634    pub fn wallet_location(&self) -> Option<&str> {
2635        self.wallet_location.as_deref()
2636    }
2637
2638    pub fn wallet_password(&self) -> Option<&str> {
2639        self.wallet_password.as_deref()
2640    }
2641
2642    pub fn edition(&self) -> Option<&str> {
2643        self.edition.as_deref()
2644    }
2645
2646    pub fn ssl_server_dn_match(&self) -> bool {
2647        self.ssl_server_dn_match
2648    }
2649
2650    pub fn ssl_server_cert_dn(&self) -> Option<&str> {
2651        self.ssl_server_cert_dn.as_deref()
2652    }
2653
2654    pub fn use_sni(&self) -> bool {
2655        self.use_sni
2656    }
2657
2658    pub fn access_token(&self) -> Option<&AccessToken> {
2659        self.access_token.as_ref()
2660    }
2661
2662    pub fn statement_cache_size(&self) -> usize {
2663        self.statement_cache_size
2664    }
2665
2666    pub fn protocol_limits(&self) -> ProtocolLimits {
2667        self.protocol_limits
2668    }
2669
2670    pub fn inactivity_timeout(&self) -> Option<Duration> {
2671        self.inactivity_timeout
2672    }
2673}
2674
2675/// A live asynchronous connection to an Oracle Database session.
2676///
2677/// Every method takes an `&Cx` and runs on an Asupersync runtime. For
2678/// synchronous code use [`BlockingConnection`], which owns a `Connection` and
2679/// drives these methods to completion on a private runtime.
2680///
2681/// A connection is not `Clone` and is not safe to use from two tasks at once;
2682/// drive one operation to completion before starting the next. To pool
2683/// connections, use the [`pool`] engine.
2684#[derive(Debug)]
2685pub struct Connection {
2686    descriptor: EasyConnect,
2687    identity: ClientIdentity,
2688    /// The private transport core owns packet I/O and cancellation-drain state.
2689    /// Cancellable reads arm its drain flag so the next operation can break and
2690    /// drain before issuing a new request.
2691    core: DriverCore,
2692    protocol_limits: ProtocolLimits,
2693    session_id: u32,
2694    serial_num: u16,
2695    server_version: Option<String>,
2696    server_version_tuple: Option<(u8, u8, u8, u8, u8)>,
2697    /// `SYS_CONTEXT('USERENV','DB_UNIQUE_NAME')` from the AUTH phase-two session
2698    /// data key `AUTH_SC_REAL_DBUNIQUE_NAME` (reference `db_unique_name`,
2699    /// upstream 16a57f1cbd58). `None` when the server did not send the key.
2700    db_unique_name: Option<String>,
2701    capabilities: ClientCapabilities,
2702    ttc_seq_num: u8,
2703    sdu: usize,
2704    /// Negotiated TTC protocol version from the server's ACCEPT
2705    /// (`AcceptInfo.protocol_version`). Surfaced via
2706    /// [`Connection::protocol_version`].
2707    protocol_version: u16,
2708    /// Whether authentication used the combined fast-auth bundle: the server
2709    /// advertised `TNS_ACCEPT_FLAG_FAST_AUTH` (`AcceptInfo.supports_fast_auth`)
2710    /// and the driver took the single-round-trip auth path. Surfaced via
2711    /// [`Connection::supports_fast_auth`].
2712    supports_fast_auth: bool,
2713    supports_end_of_response: bool,
2714    /// Whether the server negotiated out-of-band (urgent-TCP) break support
2715    /// (`protocol_options & TNS_GSO_CAN_RECV_ATTENTION`, reference
2716    /// `Capabilities.supports_oob`). Surfaced via [`Connection::supports_oob`];
2717    /// [`Connection::cancel`] always uses the in-band BREAK marker regardless,
2718    /// because the transport does not expose `MSG_OOB`.
2719    supports_oob: bool,
2720    cursor_columns: BTreeMap<u32, Vec<ColumnMetadata>>,
2721    /// Fetch metadata of the most recent execution keyed by SQL text,
2722    /// mirroring the reference statement cache's per-statement
2723    /// `_fetch_var_impls` retention (impl/thin/statement.pyx:300-310) that
2724    /// drives the re-execute type-change adjustment.
2725    fetch_metadata_by_sql: HashMap<String, Vec<ColumnMetadata>>,
2726    /// Insertion order for [`Self::fetch_metadata_by_sql`] eviction.
2727    fetch_metadata_order: VecDeque<String>,
2728    /// Cross-connection statement-shape cache (bead a4-8pp). Private per
2729    /// connection unless a shared one was supplied via
2730    /// [`ConnectOptions::with_shared_statement_shape_cache`]. Each query execute
2731    /// observes its freshly-described shape here; a cross-connection shape change
2732    /// (concurrent DDL) self-heals by dropping this connection's retained per-SQL
2733    /// fetch metadata so it re-describes instead of serving a stale decode.
2734    shape_cache: Arc<StatementShapeCache>,
2735    dead: bool,
2736    /// Logon user, retained for the change-password call.
2737    user: String,
2738    /// Session combo key from verifier generation, retained for the
2739    /// change-password call (reference keeps `conn_impl._combo_key`).
2740    combo_key: Vec<u8>,
2741    /// LRU statement cache: SQL text -> open server cursor id plus the bind
2742    /// TYPE shape the cursor was last bound with (reference
2743    /// thin/statement_cache.pyx, default size 20). The shape guards against
2744    /// reusing a cursor whose server-side bind metadata no longer matches the
2745    /// new binds (bead rust-oracledb-ilel: ORA-01722 when a text bind rides a
2746    /// cursor parsed with a NUMBER bind).
2747    statement_cache: Vec<CachedStatement>,
2748    /// Capacity of [`Self::statement_cache`] (from
2749    /// [`ConnectOptions::statement_cache_size`]); `0` disables caching.
2750    statement_cache_size: usize,
2751    /// Server cursor ids currently held by a live cursor (reference
2752    /// `Statement._in_use`). A cached cursor whose id is in this set must NOT
2753    /// be reused by a second cursor: `get_statement` returns a fresh
2754    /// (re-parsed) cursor instead, so interleaved fetches on different cursors
2755    /// of the same connection cannot reset each other's server-side fetch
2756    /// position (ORA-01002 fetch out of sequence). Cleared when the owning
2757    /// cursor releases the id (close / re-prepare to a different statement).
2758    in_use_cursors: HashSet<u32>,
2759    /// Cursor ids whose active server define returns LOB locator rows with the
2760    /// extra size/chunk fields. Plain `stream_lobs()` cursors are intentionally
2761    /// absent even when their describe metadata contains CLOB/BLOB columns.
2762    lob_prefetch_cursors: BTreeSet<u32>,
2763    /// Server cursor ids that were parsed as a fresh copy because the cached
2764    /// statement was in use (reference statement with `_return_to_cache =
2765    /// False`). These are never returned to the statement cache; when the
2766    /// owning cursor releases the id it is queued for close instead of being
2767    /// kept open (reference `return_statement` -> `_add_cursor_to_close`).
2768    copied_cursors: HashSet<u32>,
2769    /// Server cursor ids queued for the close-cursors piggyback (reference
2770    /// `_cursors_to_close`).
2771    cursors_to_close: Vec<u32>,
2772    /// State of the active sessionless transaction (reference
2773    /// `BaseThinConnImpl._sessionless_data`); `None` when no sessionless
2774    /// transaction is active on this connection.
2775    sessionless_data: Option<SessionlessData>,
2776    /// Leftover (partially-decoded) bytes from the EMON notification stream.
2777    /// The reference `ReadBuffer` chains pushed packets so a single logical
2778    /// `process()` call decodes records that span packet boundaries; this
2779    /// buffer plays the same role for [`Connection::recv_notification`].
2780    notification_buffer: Vec<u8>,
2781    /// Whether the leading `TNS_MSG_TYPE_OAC` byte of the notification stream
2782    /// has been consumed (the reference reads it once via the outer
2783    /// `process()` loop before delivering any record).
2784    notification_header_consumed: bool,
2785    /// The TPC (two-phase commit) transaction context returned by `tpc_begin`,
2786    /// echoed back on `tpc_end`/`tpc_prepare`/`tpc_commit`/`tpc_rollback`
2787    /// (reference `BaseThinConnImpl._transaction_context`). `None` when no XA
2788    /// transaction context has been captured.
2789    transaction_context: Option<Vec<u8>>,
2790    /// Whether a server-side transaction is in progress, derived from the wire
2791    /// end-of-call status bit `TNS_EOCS_FLAGS_TXN_IN_PROGRESS` on every round
2792    /// trip (reference protocol.pyx `_process_call_status` /
2793    /// `_txn_in_progress`).
2794    txn_in_progress: bool,
2795    /// Secret-free support-capture guard (bead K6). Armed only when
2796    /// `ORACLEDB_CAPTURE` was set at connect time and the `cassette` feature is
2797    /// compiled in; on drop/close it writes a scrubbed, secret-free
2798    /// `.tns-cassette` of the whole session to that path (fail-closed: a
2799    /// surviving secret refuses the write and leaves no file). `None` otherwise,
2800    /// in which case the transport path is byte-identical to a non-capturing
2801    /// session.
2802    ///
2803    /// Held only for its `Drop` side effect (persist-on-session-end), never read.
2804    #[cfg(feature = "cassette")]
2805    #[allow(dead_code)]
2806    capture_guard: Option<transport::CaptureGuard>,
2807}
2808
2809/// Owns the lifecycle of the open query cursor used by
2810/// [`Connection::for_each_row_ref`]. The borrowed-row path deliberately keeps a
2811/// speculative response in flight while it runs the user's callback, so every
2812/// post-execute early return -- including cancellation by dropping the method
2813/// future -- must retire the cursor locally. Wire recovery remains the
2814/// transport's job: the next request drains any stranded response before it
2815/// sends this guard's queued close-cursor piggyback.
2816struct BorrowedStreamCursorGuard<'conn> {
2817    connection: &'conn mut Connection,
2818    cursor_id: u32,
2819}
2820
2821impl<'conn> BorrowedStreamCursorGuard<'conn> {
2822    fn new(connection: &'conn mut Connection, cursor_id: u32) -> Self {
2823        Self {
2824            connection,
2825            cursor_id,
2826        }
2827    }
2828
2829    fn connection(&mut self) -> &mut Connection {
2830        self.connection
2831    }
2832
2833    /// The cursor reached normal end-of-data, so it remains valid for statement
2834    /// cache reuse. Disarm the fail-closed drop path after normal release.
2835    fn release(mut self) {
2836        self.connection.release_cursor(self.cursor_id);
2837        self.cursor_id = 0;
2838    }
2839}
2840
2841impl Drop for BorrowedStreamCursorGuard<'_> {
2842    fn drop(&mut self) {
2843        if self.cursor_id != 0 {
2844            self.connection.close_cursor(self.cursor_id);
2845        }
2846    }
2847}
2848
2849/// Mirrors the reference `_SessionlessData` (impl/thin/connection.pyx): the
2850/// pending or active sessionless transaction tracked on the connection.
2851#[derive(Clone, Debug)]
2852struct SessionlessData {
2853    transaction_id: Vec<u8>,
2854    timeout: u32,
2855    /// One of `TNS_TPC_TXN_START` / `TNS_TPC_TXN_DETACH`, optionally OR'd with
2856    /// `TNS_TPC_TXN_POST_DETACH` once a suspend-on-success is folded in.
2857    operation: u32,
2858    /// `TPC_TXN_FLAGS_NEW` or `TPC_TXN_FLAGS_RESUME` (SESSIONLESS is added when
2859    /// the message is built).
2860    flags: u32,
2861    /// A begin/resume that must ride as a piggyback on the next execute
2862    /// (`defer_round_trip=True`, or a folded-in suspend-on-success).
2863    piggyback_pending: bool,
2864    /// The transaction was started via DBMS_TRANSACTION on the server; the
2865    /// client API may not suspend/resume it (reference `started_on_server`).
2866    started_on_server: bool,
2867}
2868
2869/// Result of one bounded notification packet read.
2870enum PacketRead {
2871    /// A DATA packet's payload was appended to the notification buffer.
2872    Appended,
2873    /// The read timed out (no data within the window); the caller should poll
2874    /// its shutdown flag and may retry.
2875    TimedOut,
2876    /// The emon socket was closed or returned a non-DATA packet; the stream is
2877    /// finished.
2878    Closed,
2879}
2880
2881/// Outcome of [`Connection::recv_notification`].
2882#[derive(Clone, Debug)]
2883#[non_exhaustive]
2884pub enum NotificationOutcome {
2885    /// A decoded notification record to deliver to the callback.
2886    Record(NotificationRecord),
2887    /// No record arrived within the read window; poll the shutdown flag and
2888    /// call again to keep waiting.
2889    TimedOut,
2890    /// The emon socket closed (teardown / STOP_NOTIF); stop the receive loop.
2891    Closed,
2892}
2893
2894const STATEMENT_CACHE_SIZE: usize = 20;
2895
2896/// One operation in a pipelined batch (`Connection::run_pipeline`).
2897#[derive(Clone, Debug)]
2898pub enum PipelineRequest {
2899    #[non_exhaustive]
2900    Execute {
2901        sql: String,
2902        bind_rows: Vec<Vec<BindValue>>,
2903        prefetch_rows: u32,
2904    },
2905    Commit,
2906}
2907
2908impl PipelineRequest {
2909    pub fn execute(
2910        sql: impl Into<String>,
2911        bind_rows: Vec<Vec<BindValue>>,
2912        prefetch_rows: u32,
2913    ) -> Self {
2914        Self::Execute {
2915            sql: sql.into(),
2916            bind_rows,
2917            prefetch_rows,
2918        }
2919    }
2920
2921    pub fn commit() -> Self {
2922        Self::Commit
2923    }
2924
2925    pub fn sql(&self) -> Option<&str> {
2926        match self {
2927            Self::Execute { sql, .. } => Some(sql),
2928            Self::Commit => None,
2929        }
2930    }
2931
2932    pub fn bind_rows(&self) -> Option<&[Vec<BindValue>]> {
2933        match self {
2934            Self::Execute { bind_rows, .. } => Some(bind_rows),
2935            Self::Commit => None,
2936        }
2937    }
2938
2939    pub fn prefetch_rows(&self) -> Option<u32> {
2940        match self {
2941            Self::Execute { prefetch_rows, .. } => Some(*prefetch_rows),
2942            Self::Commit => None,
2943        }
2944    }
2945
2946    pub fn is_commit(&self) -> bool {
2947        matches!(self, Self::Commit)
2948    }
2949}
2950
2951#[derive(Debug)]
2952pub struct CancelHandle {
2953    write: SharedWriteHalf,
2954    recovery: Arc<SessionRecovery>,
2955}
2956
2957impl Connection {
2958    /// Open a connection: resolve the EasyConnect descriptor, complete the TNS
2959    /// handshake and TTC capability negotiation, and authenticate `user` with
2960    /// the supplied [`ClientIdentity`]. On success the database has recorded a
2961    /// session whose `program` / `machine` / `osuser` / `terminal` are exactly
2962    /// the identity fields.
2963    pub async fn connect(cx: &Cx, mut options: ConnectOptions) -> Result<Self> {
2964        observe_cancellation_between_round_trips(cx)?;
2965        let protocol_limits = options.protocol_limits.validate()?;
2966        if let Some(unsupported) = options.auth_mode.unsupported_in_thin() {
2967            return Err(Error::UnsupportedAuthMode(unsupported));
2968        }
2969        let descriptor = EasyConnect::parse(&options.connect_string)?;
2970        // Fail closed BEFORE any network I/O: a database access token (OCI IAM /
2971        // OAuth2) must never be put on the wire in clear text. The reference
2972        // enforces this during the auth exchange (protocol.pyx
2973        // `ERR_ACCESS_TOKEN_REQUIRES_TCPS`); we additionally refuse up front, so
2974        // the token never leaves the process when the descriptor is plaintext
2975        // TCP. The in-auth guard below stays as defense in depth. Uniform typed
2976        // error; the token is never rendered. A pluggable token *source* is held
2977        // to the same rule and — crucially — is refused here BEFORE it is ever
2978        // consulted, so no token is fetched for a transport that could not carry
2979        // it securely.
2980        if (options.access_token.is_some() || options.token_source.is_some())
2981            && !descriptor.protocol.is_tls()
2982        {
2983            return Err(Error::AccessTokenRequiresTcps);
2984        }
2985        // Resolve a pluggable token source into a concrete access token once, at
2986        // connect (the transport is now known to be TCPS). A static access token
2987        // takes precedence. The provider's failure is surfaced as the redacted
2988        // `Error::TokenSource`; its detail (and the token) never leak.
2989        if options.access_token.is_none() {
2990            if let Some(source) = options.token_source.clone() {
2991                let token = source.get_token().await.map_err(Error::TokenSource)?;
2992                options.access_token = Some(AccessToken::new(token));
2993            }
2994        }
2995        let full_descriptor = EasyConnect::parse_descriptor(&options.connect_string)?;
2996        let primary_description = full_descriptor.first_description().clone();
2997        let connect_timeout =
2998            transport_connect_timeout_duration(primary_description.tcp_connect_timeout);
2999        let connect_timeout_ms = duration_to_millis_saturating(connect_timeout);
3000        // GH#14: the opt-in per-read inactivity deadline, and the TCP keepalive
3001        // idle interval derived from a DSN `EXPIRE_TIME` (minutes). Both are Copy
3002        // values captured into the connect block: keepalive is set on the socket
3003        // right after dial (before any TLS wrap), and the inactivity deadline is
3004        // installed on the session core once the transport is established.
3005        let inactivity_timeout = options.inactivity_timeout;
3006        let keepalive_idle = keepalive_idle_from_expire_time(primary_description.expire_time);
3007        let connect_result = time::timeout(time::wall_now(), connect_timeout, async {
3008            // Connect span (feature-gated, zero-cost when off). Carries only the
3009            // server address / port / service — never the password.
3010            let _span = obs_span!(
3011                "oracledb.connect",
3012                db.system = "oracle",
3013                server.address = %descriptor.host,
3014                server.port = descriptor.port as u64,
3015                db.name = %descriptor.service_name,
3016            );
3017            let token_auth = options.access_token.is_some();
3018            let descriptor_ssl_server_dn_match =
3019                effective_ssl_server_dn_match(&primary_description, &options);
3020            let descriptor_ssl_server_cert_dn = options
3021                .ssl_server_cert_dn
3022                .as_deref()
3023                .or(primary_description.security.ssl_server_cert_dn.as_deref());
3024            let identity = options.identity;
3025            // F1 (bead rust-oracledb-clvm): apply the DSN-parsed transport
3026            // parameters that were previously parsed and dropped. The SDU
3027            // advertised in the CONNECT packet honours a DSN `(SDU=...)` (see
3028            // `resolve_effective_sdu`); the wallet directory and the SNI toggle
3029            // fall back to the DSN `SECURITY`/`USE_SNI` when the structured
3030            // builder did not set them.
3031            let advertised_sdu =
3032                u16::try_from(resolve_effective_sdu(options.sdu, &primary_description))
3033                    .unwrap_or(u16::MAX);
3034            let effective_use_sni = options.use_sni || primary_description.use_sni;
3035            let effective_wallet_location = options
3036                .wallet_location
3037                .as_deref()
3038                .or(primary_description.security.wallet_location.as_deref());
3039            // TCPS: TLS parameters (wallet, DN-match, SNI policy) are resolved
3040            // once and reused when a listener REDIRECT re-establishes the
3041            // transport to a new address (the redirected connection keeps the
3042            // original transport protocol, reference `_connect_phase_one`).
3043            let server_type = if options.server_type_emon {
3044                Some("emon")
3045            } else {
3046                None
3047            };
3048            // F-DC2 (security fix): feed the TLS verifier the SAME resolved
3049            // `SSL_SERVER_DN_MATCH` / `SSL_SERVER_CERT_DN` values that
3050            // `descriptor_ssl_server_dn_match` / `descriptor_ssl_server_cert_dn`
3051            // already computed above (options merged over the DSN-parsed
3052            // descriptor) and that drive the outbound listener CONNECT
3053            // descriptor below. Passing the raw, unmerged `options.*` fields
3054            // here (the prior bug) meant a cert DN pinned ONLY in the connect
3055            // string (`(SECURITY=(SSL_SERVER_CERT_DN=...)))`, never touching
3056            // the `with_ssl_server_cert_dn` builder) never reached the
3057            // verifier: `run_dn_match` would silently fall back to the
3058            // hostname/SAN/CN match instead of enforcing the pinned DN, so
3059            // DN pinning configured via the DSN did not actually pin. The
3060            // same gap dropped a DSN-only `SSL_SERVER_DN_MATCH=OFF`, so the
3061            // check stayed enforced even when the descriptor asked to
3062            // disable it. One resolved value now feeds both the verifier and
3063            // the wire descriptor, so they can never diverge.
3064            let prepared_tls = if descriptor.protocol.is_tls() {
3065                let tls_params = tls::resolve_tls_params(
3066                    &descriptor,
3067                    effective_wallet_location,
3068                    options.wallet_password.as_deref(),
3069                    descriptor_ssl_server_dn_match,
3070                    descriptor_ssl_server_cert_dn,
3071                    effective_use_sni,
3072                )?;
3073                // Build the rustls config, validate the wallet key, and decide
3074                // SNI before any address is dialled. These deterministic setup
3075                // failures are returned directly and never enter the transient
3076                // transport-failover loop below.
3077                Some(tls::prepare_tls_handshake(
3078                    &descriptor,
3079                    server_type,
3080                    &tls_params,
3081                )?)
3082            } else {
3083                None
3084            };
3085            let connector = DriverConnector::default();
3086            // Secret-free support capture (bead K6): when `ORACLEDB_CAPTURE` is
3087            // set, a recorder is created here and installed around each dial's
3088            // transport split so the WHOLE session (connect + auth + queries) is
3089            // teed into it. The recorder handle rides on the returned
3090            // `Connection`; on drop/close the auth phase is scrubbed and a
3091            // fail-closed refuse gate persists the cassette to the path (or
3092            // refuses if any secret survives). Off / feature-absent = no
3093            // behaviour change.
3094            #[cfg(feature = "cassette")]
3095            let capture_path = transport::capture_path_from_env();
3096            #[cfg(feature = "cassette")]
3097            let capture_recorder = capture_path
3098                .as_ref()
3099                .map(|_| transport::CassetteRecorder::new());
3100            // Dials one listener endpoint: TCP connect, then — for a TCPS
3101            // original — the TLS handshake on the whole socket before
3102            // splitting and before any TNS bytes are sent (implicit TLS,
3103            // matching python-oracledb thin's _connect_tcp ordering). Used
3104            // for the initial address and for every REDIRECT target.
3105            let dial = |host: String, port: u16| {
3106                let connector = &connector;
3107                let prepared_tls = prepared_tls.as_ref();
3108                #[cfg(feature = "cassette")]
3109                let capture_recorder = capture_recorder.as_ref();
3110                async move {
3111                    trace_connect_step("tcp connect");
3112                    let stream = TcpStream::connect_timeout((host, port), connect_timeout).await?;
3113                    stream.set_nodelay(true)?;
3114                    // GH#14: enable TCP keepalive so a half-open/dead peer is
3115                    // detected instead of wedging a later read forever. The idle
3116                    // interval comes from the DSN `EXPIRE_TIME` (minutes); on a
3117                    // TCPS descriptor it is set on the underlying socket here,
3118                    // before the TLS handshake consumes the stream.
3119                    if let Some(idle) = keepalive_idle {
3120                        stream.set_keepalive(Some(idle))?;
3121                    }
3122                    trace_connect_step("tcp connected");
3123                    let halves = if let Some(prepared_tls) = prepared_tls {
3124                        trace_connect_step("tls handshake");
3125                        // Honor the same configured connect timeout that already
3126                        // bounds the TCP dial above, instead of a hard-coded
3127                        // value: `connect_timeout` is resolved uniformly from
3128                        // the DSN `TRANSPORT_CONNECT_TIMEOUT`/`CONNECT_TIMEOUT`
3129                        // for both easy-connect and full-descriptor DSN forms
3130                        // (bead F-DC4).
3131                        let tls_stream = tls::tls_handshake_prepared(
3132                            prepared_tls,
3133                            stream,
3134                            tls::handshake_timeout_from_connect_timeout(connect_timeout),
3135                        )
3136                        .await?;
3137                        trace_connect_step("tls established");
3138                        // Install the capture recorder around the SYNCHRONOUS
3139                        // split only (no await while held) so the thread-local
3140                        // is observed on the thread performing the split.
3141                        #[cfg(feature = "cassette")]
3142                        let _capture =
3143                            capture_recorder.map(|r| transport::install_recorder_scope(r.clone()));
3144                        connector.tls_split(tls_stream)
3145                    } else {
3146                        #[cfg(feature = "cassette")]
3147                        let _capture =
3148                            capture_recorder.map(|r| transport::install_recorder_scope(r.clone()));
3149                        connector.plain_split(stream)
3150                    };
3151                    Ok::<_, TransportEstablishmentError>(halves)
3152                }
3153            };
3154            // F2 (bead rust-oracledb-clvm): sequential multi-address failover.
3155            // A DESCRIPTION with an ADDRESS_LIST (or several ADDRESS entries)
3156            // is tried in order — honouring LOAD_BALANCE (shuffle) and
3157            // RETRY_COUNT/RETRY_DELAY — until one address establishes a
3158            // transport; if every address fails, the per-address reasons are
3159            // aggregated into `Error::AllAddressesFailed`. Only
3160            // transport-establishment errors (TCP dial / TLS handshake) fail
3161            // over to the next address; a configuration error aborts the whole
3162            // connect. The overall connect deadline (the DSN transport connect
3163            // timeout) still bounds the total, shared across attempts.
3164            let candidates = resolve_connect_addresses(&full_descriptor, descriptor.protocol);
3165            let retry_count = primary_description.retry_count;
3166            let retry_delay = Duration::from_secs(u64::from(primary_description.retry_delay));
3167            let mut attempt_errors: Vec<String> = Vec::new();
3168            let mut connected = None;
3169            'failover: for round in 0..=retry_count {
3170                if round > 0 && !retry_delay.is_zero() {
3171                    trace_connect_step("failover retry delay");
3172                    // Sleep `retry_delay` by timing out a never-ready future
3173                    // (asupersync exposes the deadline primitive, not a bare
3174                    // sleep); the elapsed Err is expected and ignored.
3175                    let _ =
3176                        time::timeout(time::wall_now(), retry_delay, std::future::pending::<()>())
3177                            .await;
3178                }
3179                for candidate in &candidates {
3180                    match dial(candidate.host.clone(), candidate.port).await {
3181                        Ok(halves) => {
3182                            connected = Some((halves, candidate.clone()));
3183                            break 'failover;
3184                        }
3185                        Err(err) => {
3186                            if err.is_terminal() {
3187                                return Err(err.into_driver_error());
3188                            }
3189                            attempt_errors
3190                                .push(format!("{}:{} ({err})", candidate.host, candidate.port));
3191                        }
3192                    }
3193                }
3194            }
3195            let ((read, write), active_address) = match connected {
3196                Some(pair) => pair,
3197                None => {
3198                    return Err(Error::AllAddressesFailed(format!(
3199                        "tried {} address(es): {}",
3200                        attempt_errors.len(),
3201                        attempt_errors.join("; ")
3202                    )));
3203                }
3204            };
3205            // Rebind the working descriptor to the address that actually
3206            // connected so the CONNECT descriptor's ADDRESS clause reflects the
3207            // live endpoint (the TLS params/DN match keep the configured host).
3208            let descriptor = EasyConnect {
3209                host: active_address.host,
3210                port: active_address.port,
3211                service_name: descriptor.service_name.clone(),
3212                protocol: descriptor.protocol,
3213            };
3214            let mut core = ConnectionCore::from_halves(read, write, "oracle_tcp_write");
3215            core.set_protocol_limits(protocol_limits)?;
3216            core.set_inactivity_timeout(inactivity_timeout);
3217
3218            let connect_descriptor = listener_connect_descriptor_with_server(
3219                &descriptor,
3220                &primary_description,
3221                &identity,
3222                options.server_type_emon,
3223                token_auth,
3224                descriptor_ssl_server_dn_match,
3225                descriptor_ssl_server_cert_dn,
3226            );
3227            trace_connect_value("CONNECT descriptor", &connect_descriptor);
3228            // A descriptor longer than TNS_MAX_CONNECT_DATA travels in a DATA
3229            // packet right behind the CONNECT packet, and the server may answer
3230            // with a RESEND packet asking for the whole exchange again before it
3231            // ACCEPTs (reference protocol.pyx `_connect_phase_one`: "this may
3232            // request the message to be resent multiple times"). Pre-23ai
3233            // servers RESEND routinely; a bounded loop guards against a
3234            // misbehaving peer that never stops asking. A REDIRECT answer
3235            // reconnects the transport to the redirected address and resends
3236            // the CONNECT there with the REDIRECT packet flag (and the
3237            // redirect-supplied connect data); RESEND and REDIRECT may
3238            // interleave — a RESEND after a redirect resends the redirected
3239            // CONNECT, flag included.
3240            let mut connect_data = connect_descriptor;
3241            let mut packet_flags = 0u8;
3242            let mut resend_rounds = 0u8;
3243            let mut redirect_rounds = 0u8;
3244            let accept = loop {
3245                let connect_payload = build_connect_packet_payload(&connect_data, advertised_sdu)?;
3246                let packet = encode_packet(
3247                    TNS_PACKET_TYPE_CONNECT,
3248                    packet_flags,
3249                    None,
3250                    &connect_payload,
3251                    PacketLengthWidth::Legacy16,
3252                )?;
3253                trace_connect_bytes("CONNECT packet", &packet);
3254                let split_connect_data = !connect_data_fits_inline(&connect_data);
3255                trace_connect_step("send CONNECT");
3256                core.write_all(cx, &packet).await?;
3257                if split_connect_data {
3258                    trace_connect_step("send CONNECT descriptor (data packet)");
3259                    core.send_connect_data_packet(
3260                        cx,
3261                        connect_data.as_bytes(),
3262                        usize::from(advertised_sdu),
3263                    )
3264                    .await?;
3265                }
3266
3267                trace_connect_step("read ACCEPT");
3268                let reply = core.read_packet(PacketLengthWidth::Legacy16).await?;
3269                trace_connect_value(
3270                    "CONNECT reply",
3271                    &format!(
3272                        "type={} flags=0x{:02x} payload_len={}",
3273                        reply.packet_type,
3274                        reply.packet_flags,
3275                        reply.payload.len()
3276                    ),
3277                );
3278                match reply.packet_type {
3279                    TNS_PACKET_TYPE_ACCEPT => break reply,
3280                    TNS_PACKET_TYPE_RESEND => {
3281                        resend_rounds += 1;
3282                        if resend_rounds > MAX_CONNECT_RESEND_ROUNDS {
3283                            return Err(Error::ConnectResendLoop(resend_rounds));
3284                        }
3285                        trace_connect_step("RESEND requested; resending CONNECT");
3286                        continue;
3287                    }
3288                    TNS_PACKET_TYPE_REDIRECT => {
3289                        redirect_rounds += 1;
3290                        if redirect_rounds > MAX_CONNECT_REDIRECT_ROUNDS {
3291                            return Err(Error::ConnectRedirectLoop(redirect_rounds));
3292                        }
3293                        let redirect_data = read_redirect_data(&mut core, &reply.payload).await?;
3294                        let target = parse_redirect_target(&redirect_data, descriptor.protocol)?;
3295                        trace_connect_value(
3296                            "REDIRECT target",
3297                            &format!("{}:{}", target.host, target.port),
3298                        );
3299                        // Reconnect the transport to the redirected listener
3300                        // (dropping the old connection closes it) and resend
3301                        // the CONNECT there, flagged as a redirect follow-up
3302                        // and carrying the redirect-supplied connect data
3303                        // (reference `_connect_phase_one`).
3304                        let (read, write) = dial(target.host, target.port)
3305                            .await
3306                            .map_err(TransportEstablishmentError::into_driver_error)?;
3307                        core = ConnectionCore::from_halves(read, write, "oracle_tcp_write");
3308                        core.set_protocol_limits(protocol_limits)?;
3309                        core.set_inactivity_timeout(inactivity_timeout);
3310                        connect_data = target.connect_data;
3311                        packet_flags = TNS_PACKET_FLAG_REDIRECT;
3312                        // The redirected listener negotiates from scratch and
3313                        // may itself ask for resends.
3314                        resend_rounds = 0;
3315                        trace_connect_step("REDIRECT: reconnected; resending CONNECT");
3316                        continue;
3317                    }
3318                    TNS_PACKET_TYPE_REFUSE => {
3319                        trace_connect_step("REFUSE received");
3320                        return Err(Error::ListenerRefused(
3321                            String::from_utf8_lossy(&reply.payload).to_string(),
3322                        ));
3323                    }
3324                    other => return Err(Error::UnexpectedPacket(other)),
3325                }
3326            };
3327            let accept_info = parse_accept_payload(&accept.payload)?;
3328            // Surface the negotiated ACCEPT capabilities so a captured trace
3329            // shows *why* the auth path forked: `fast_auth=true` takes the
3330            // combined fast-auth bundle, `fast_auth=false` falls back to the
3331            // classic protocol-negotiation + data-types round trips. This is the
3332            // single most useful line for diagnosing a "missing/failed fast-auth"
3333            // exchange. None of these values are secret (they mirror v$session /
3334            // negotiated SDU).
3335            trace_connect_value(
3336                "ACCEPT",
3337                &format!(
3338                    "sdu={} fast_auth={} end_of_response={} oob={}",
3339                    accept_info.sdu,
3340                    accept_info.supports_fast_auth,
3341                    accept_info.supports_end_of_response,
3342                    accept_info.supports_oob,
3343                ),
3344            );
3345            // Record the framing mode so the recovery drain (which runs on a raw
3346            // read half, without the Connection) decides the trailing-error
3347            // boundary the way this server frames it: pre-23ai (no
3348            // END_OF_RESPONSE) needs message-driven completion (bead
3349            // rust-oracledb-99xu).
3350            core.set_classic_framing(!accept_info.supports_end_of_response);
3351            let sdu = usize::try_from(accept_info.sdu)
3352                .unwrap_or(DEFAULT_SDU)
3353                .max(TNS_DATA_PACKET_OVERHEAD + 1);
3354
3355            let mut ttc_seq_num = 1;
3356            let auth_connect_string = auth_connect_descriptor(
3357                &descriptor,
3358                &primary_description,
3359                token_auth,
3360                descriptor_ssl_server_dn_match,
3361                descriptor_ssl_server_cert_dn,
3362            );
3363
3364            // Authentication has two shapes. Token auth (OCI IAM / OAuth2) carries
3365            // the credential in `AUTH_TOKEN` and skips the password-verifier round
3366            // trip entirely; password auth does the classic phase-one challenge /
3367            // phase-two verifier exchange. Both converge on a parsed auth response
3368            // plus the negotiated capabilities; only password auth yields a combo key
3369            // (used later to verify the server's response and for change-password).
3370            let (auth_two, capabilities, combo_key) = if let Some(token) = &options.access_token {
3371                // A database access token must never travel in clear text: require
3372                // TLS/TCPS, exactly as the reference does
3373                // (protocol.pyx `ERR_ACCESS_TOKEN_REQUIRES_TCPS`).
3374                if !descriptor.protocol.is_tls() {
3375                    return Err(Error::AccessTokenRequiresTcps);
3376                }
3377                // OCI IAM *database* tokens are proof-of-possession: the token is
3378                // bound to an RSA private key and the server refuses the bearer
3379                // token alone with ORA-01017. When the caller supplied the key,
3380                // sign the HTTP-Signatures header now and carry it as
3381                // AUTH_HEADER/AUTH_SIGNATURE on whichever auth path is taken. A
3382                // plain OAuth2 bearer token has no key and skips this. Computed
3383                // once; the borrowed `TokenPop` feeds both fast-auth and classic.
3384                let pop_material = match options.access_token_private_key.as_ref() {
3385                    Some(key) => {
3386                        let header = iam_pop::build_signing_header(
3387                            &descriptor.service_name,
3388                            &descriptor.host,
3389                            descriptor.port,
3390                            std::time::SystemTime::now(),
3391                        );
3392                        let signature = iam_pop::sign_signing_header(key.expose(), &header)?;
3393                        Some((header, signature))
3394                    }
3395                    None => None,
3396                };
3397                let pop = pop_material
3398                    .as_ref()
3399                    .map(|(header, signature)| TokenPop { header, signature });
3400                let (auth, capabilities) = if accept_info.supports_fast_auth {
3401                    // One combined fast-auth bundle carrying a phase-two
3402                    // `AUTH_TOKEN` message; no resend. The payload embeds the
3403                    // token, so it is never passed to `trace_connect_bytes`.
3404                    let auth_payload = build_fast_auth_token_payload_with_pop_and_proxy(
3405                        &options.user,
3406                        token.expose(),
3407                        &identity.driver_name,
3408                        PYTHON_ORACLEDB_COMPAT_VERSION_NUM,
3409                        &auth_connect_string,
3410                        options.edition.as_deref(),
3411                        pop,
3412                        options.proxy_user.as_deref(),
3413                    )?;
3414                    trace_connect_step("send AUTH token (fast-auth phase two)");
3415                    core.send_data_packet(cx, &auth_payload, sdu).await?;
3416                    trace_connect_step("read AUTH token response");
3417                    let response = core.read_data_response(cx).await?;
3418                    trace_connect_bytes("AUTH token response", &response);
3419                    let auth = parse_auth_response_with_limits(&response, protocol_limits)?;
3420                    let capabilities = auth.capabilities.unwrap_or_default();
3421                    (auth, capabilities)
3422                } else {
3423                    core.authenticate_classic_token(
3424                        cx,
3425                        TokenAuthentication {
3426                            user: &options.user,
3427                            token: token.expose(),
3428                            driver_name: &identity.driver_name,
3429                            version_num: PYTHON_ORACLEDB_COMPAT_VERSION_NUM,
3430                            connect_string: &auth_connect_string,
3431                            edition: options.edition.as_deref(),
3432                            pop,
3433                            proxy_user: options.proxy_user.as_deref(),
3434                        },
3435                        sdu,
3436                    )
3437                    .await?
3438                };
3439                // Token auth derives no shared password key: there is no combo key,
3440                // hence no server-response MAC to verify and no change-password.
3441                (auth, capabilities, Vec::new())
3442            } else {
3443                let client_pid = process::id();
3444                // Pre-23ai servers do not understand the combined fast-auth
3445                // bundle: run the classic handshake instead — protocol
3446                // negotiation and data types as their own round trips
3447                // (reference protocol.pyx `_connect_phase_two`), then the same
3448                // two-phase password auth. The standalone payloads are exact
3449                // slices of the fast-auth bundle, so both paths negotiate
3450                // byte-identically.
3451                let negotiated_capabilities = if accept_info.supports_fast_auth {
3452                    None
3453                } else {
3454                    let protocol_payload = build_protocol_negotiation_payload()?;
3455                    trace_connect_step("send protocol negotiation (classic)");
3456                    core.send_data_packet(cx, &protocol_payload, sdu).await?;
3457                    trace_connect_step("read protocol negotiation");
3458                    let response = core.read_classic_data_response(cx).await?;
3459                    trace_connect_bytes("protocol negotiation response", &response);
3460                    let negotiated = parse_auth_response_with_limits(&response, protocol_limits)?;
3461
3462                    let data_types_payload = build_data_types_payload()?;
3463                    trace_connect_step("send data types (classic)");
3464                    core.send_data_packet(cx, &data_types_payload, sdu).await?;
3465                    trace_connect_step("read data types");
3466                    let response = core.read_classic_data_response(cx).await?;
3467                    trace_connect_bytes("data types response", &response);
3468                    parse_auth_response_with_limits(&response, protocol_limits)?;
3469
3470                    Some(negotiated.capabilities.unwrap_or_default())
3471                };
3472                let auth_one = if accept_info.supports_fast_auth {
3473                    build_fast_auth_phase_one_payload(
3474                        &options.user,
3475                        &identity.program,
3476                        &identity.machine,
3477                        &identity.osuser,
3478                        &identity.terminal,
3479                        client_pid,
3480                    )?
3481                } else {
3482                    build_auth_phase_one_payload(
3483                        &options.user,
3484                        &identity.program,
3485                        &identity.machine,
3486                        &identity.osuser,
3487                        &identity.terminal,
3488                        client_pid,
3489                    )?
3490                };
3491                trace_connect_bytes("AUTH phase one payload", &auth_one);
3492                trace_connect_step("send AUTH phase one");
3493                core.send_data_packet(cx, &auth_one, sdu).await?;
3494                trace_connect_step("read AUTH phase one");
3495                let auth_one_response = if accept_info.supports_fast_auth {
3496                    core.read_data_response(cx).await?
3497                } else {
3498                    core.read_classic_data_response(cx).await?
3499                };
3500                trace_connect_bytes("AUTH phase one response", &auth_one_response);
3501                let auth_one =
3502                    parse_auth_response_with_limits(&auth_one_response, protocol_limits)?;
3503                let capabilities = negotiated_capabilities
3504                    .or(auth_one.capabilities)
3505                    .unwrap_or_default();
3506                let verifier_type = auth_one
3507                    .verifier_type
3508                    .ok_or(Error::MissingSessionField("AUTH_VFR_DATA verifier type"))?;
3509                let encrypted = oracledb_protocol::crypto::generate_verifier(
3510                    options.password.as_bytes(),
3511                    &auth_one.session_data,
3512                    verifier_type,
3513                )?;
3514                let auth_two_payload = build_auth_phase_two_payload_with_proxy_with_seq(
3515                    &options.user,
3516                    &encrypted,
3517                    &identity.driver_name,
3518                    PYTHON_ORACLEDB_COMPAT_VERSION_NUM,
3519                    &auth_connect_string,
3520                    next_ttc_sequence(&mut ttc_seq_num),
3521                    &options.app_context,
3522                    options.proxy_user.as_deref(),
3523                    options.edition.as_deref(),
3524                    capabilities.ttc_field_version,
3525                )?;
3526                trace_connect_bytes("AUTH phase two payload", &auth_two_payload);
3527                trace_connect_step("send AUTH phase two");
3528                core.send_data_packet(cx, &auth_two_payload, sdu).await?;
3529                trace_connect_step("read AUTH phase two");
3530                let auth_two_response = if accept_info.supports_fast_auth {
3531                    core.read_data_response(cx).await?
3532                } else {
3533                    core.read_classic_data_response(cx).await?
3534                };
3535                trace_connect_bytes("AUTH phase two response", &auth_two_response);
3536                let auth_two =
3537                    parse_auth_response_with_limits(&auth_two_response, protocol_limits)?;
3538                oracledb_protocol::crypto::verify_server_response(
3539                    &encrypted.combo_key,
3540                    &auth_two.session_data,
3541                )?;
3542                (auth_two, capabilities, encrypted.combo_key)
3543            };
3544
3545            let session_id = parse_session_u32(&auth_two.session_data, "AUTH_SESSION_ID")?;
3546            let serial_num = parse_session_u16(&auth_two.session_data, "AUTH_SERIAL_NUM")?;
3547            // Final handshake milestone: authentication succeeded and the server
3548            // handed back a session. `sid`/`serial` are the v$session identifiers
3549            // (not secret) and let an operator correlate a captured trace with a
3550            // server-side session.
3551            trace_connect_value(
3552                "session established",
3553                &format!("sid={session_id} serial={serial_num}"),
3554            );
3555            let server_version = auth_two.session_data.get("AUTH_VERSION_STRING").cloned();
3556            let db_unique_name = parse_db_unique_name(&auth_two.session_data);
3557            let server_version_tuple = auth_two
3558                .session_data
3559                .get("AUTH_VERSION_NO")
3560                .and_then(|value| value.trim().parse::<u32>().ok())
3561                .map(|num| {
3562                    decode_server_version_number(
3563                        num,
3564                        server_version_number_uses_extended_layout(capabilities.ttc_field_version),
3565                    )
3566                });
3567
3568            // Arm the support-capture guard from the recorder installed at dial
3569            // time (both `Some` iff `ORACLEDB_CAPTURE` was set). On drop/close it
3570            // scrubs + gate-checks + persists the cassette.
3571            #[cfg(feature = "cassette")]
3572            let capture_guard = match (capture_recorder, capture_path) {
3573                (Some(recorder), Some(path)) => Some(transport::CaptureGuard::new(recorder, path)),
3574                _ => None,
3575            };
3576            Ok(Self {
3577                descriptor,
3578                identity,
3579                core,
3580                protocol_limits,
3581                session_id,
3582                serial_num,
3583                server_version,
3584                server_version_tuple,
3585                db_unique_name,
3586                capabilities,
3587                ttc_seq_num,
3588                sdu,
3589                protocol_version: accept_info.protocol_version,
3590                supports_fast_auth: accept_info.supports_fast_auth,
3591                supports_end_of_response: accept_info.supports_end_of_response,
3592                supports_oob: accept_info.supports_oob,
3593                cursor_columns: BTreeMap::new(),
3594                fetch_metadata_by_sql: HashMap::new(),
3595                fetch_metadata_order: VecDeque::new(),
3596                shape_cache: options.statement_shape_cache.clone().unwrap_or_default(),
3597                dead: false,
3598                user: options.user,
3599                combo_key,
3600                statement_cache: Vec::new(),
3601                statement_cache_size: options.statement_cache_size,
3602                in_use_cursors: HashSet::new(),
3603                lob_prefetch_cursors: BTreeSet::new(),
3604                copied_cursors: HashSet::new(),
3605                cursors_to_close: Vec::new(),
3606                sessionless_data: None,
3607                notification_buffer: Vec::new(),
3608                notification_header_consumed: false,
3609                transaction_context: None,
3610                txn_in_progress: false,
3611                #[cfg(feature = "cassette")]
3612                capture_guard,
3613            })
3614        })
3615        .await;
3616        match connect_result {
3617            Ok(result) => result,
3618            Err(_) => Err(Error::CallTimeout(connect_timeout_ms)),
3619        }
3620    }
3621
3622    pub fn descriptor(&self) -> &EasyConnect {
3623        &self.descriptor
3624    }
3625
3626    /// Host of the connected endpoint (reference thin-mode `connection.host`,
3627    /// upstream da4ec2d2526a). This is the address the session actually
3628    /// connected to, as captured in the resolved descriptor.
3629    pub fn host(&self) -> &str {
3630        &self.descriptor.host
3631    }
3632
3633    /// Port of the connected endpoint (reference `connection.port`).
3634    pub fn port(&self) -> u16 {
3635        self.descriptor.port
3636    }
3637
3638    /// Transport protocol (TCP / TCPS) of the connected endpoint (reference
3639    /// `connection.protocol`).
3640    pub fn protocol(&self) -> NetProtocol {
3641        self.descriptor.protocol
3642    }
3643
3644    /// The [`ClientIdentity`] this session was opened with (the values the
3645    /// database recorded in `v$session`).
3646    pub fn identity(&self) -> &ClientIdentity {
3647        &self.identity
3648    }
3649
3650    /// Server-assigned session id (`v$session.sid`).
3651    pub fn session_id(&self) -> u32 {
3652        self.session_id
3653    }
3654
3655    /// Server-assigned session serial number (`v$session.serial#`).
3656    pub fn serial_num(&self) -> u16 {
3657        self.serial_num
3658    }
3659
3660    /// Server version banner, if the server reported one.
3661    pub fn server_version(&self) -> Option<&str> {
3662        self.server_version.as_deref()
3663    }
3664
3665    /// The database unique name (`SYS_CONTEXT('USERENV','DB_UNIQUE_NAME')`),
3666    /// parsed from the AUTH phase-two `AUTH_SC_REAL_DBUNIQUE_NAME` field
3667    /// (reference thin-mode `connection.db_unique_name`, upstream 16a57f1cbd58).
3668    /// Empty when the server did not send it.
3669    pub fn db_unique_name(&self) -> &str {
3670        self.db_unique_name.as_deref().unwrap_or("")
3671    }
3672
3673    /// Database version 5-tuple decoded from `AUTH_VERSION_NO`
3674    /// (reference messages/auth.pyx `_get_version_tuple`).
3675    pub fn server_version_tuple(&self) -> Option<(u8, u8, u8, u8, u8)> {
3676        self.server_version_tuple
3677    }
3678
3679    /// Whether the server supports OSON long field names (server major version
3680    /// >= 23). Mirrors the reference `conn_impl.supports_oson_long_field_names`.
3681    fn supports_oson_long_fnames(&self) -> bool {
3682        self.server_version_tuple
3683            .map(|(major, ..)| major >= 23)
3684            .unwrap_or(false)
3685    }
3686
3687    pub fn sdu(&self) -> usize {
3688        self.sdu
3689    }
3690
3691    /// Whether the server negotiated END_OF_RESPONSE framing at accept time
3692    /// (protocol version >= 319 with TNS_ACCEPT_FLAG_HAS_END_OF_RESPONSE) --
3693    /// the prerequisite for pipelining (impl/thin/capabilities.pyx:126-130).
3694    pub fn supports_pipelining(&self) -> bool {
3695        self.supports_end_of_response
3696    }
3697
3698    /// The negotiated TTC protocol version from the server's ACCEPT packet
3699    /// (`AcceptInfo.protocol_version`, reference connect.pyx). This is the
3700    /// TNS_VERSION_* level the client and server agreed on (e.g. 319 for a
3701    /// 19c+/23ai-era server that supports END_OF_RESPONSE framing).
3702    pub fn protocol_version(&self) -> u16 {
3703        self.protocol_version
3704    }
3705
3706    /// Whether this session authenticated over the combined fast-auth bundle:
3707    /// the server advertised `TNS_ACCEPT_FLAG_FAST_AUTH` at accept time and the
3708    /// driver used the single-round-trip fast-auth path (23ai-era servers). A
3709    /// `false` value means the classic protocol-negotiation + data-types
3710    /// handshake was used instead.
3711    pub fn supports_fast_auth(&self) -> bool {
3712        self.supports_fast_auth
3713    }
3714
3715    pub fn cancel_handle(&self) -> Result<CancelHandle> {
3716        Ok(CancelHandle {
3717            write: self.core.write_handle(),
3718            recovery: Arc::clone(&self.core.recovery),
3719        })
3720    }
3721
3722    /// Whether a session-dead Oracle error (mapped to DPY-4011 by the Python
3723    /// layer) has been observed on this connection.
3724    pub fn is_dead(&self) -> bool {
3725        self.dead || self.core.recovery.is_dead()
3726    }
3727
3728    /// Wrap a protocol parse result, recording session-dead errors.
3729    fn note_parse<T>(
3730        &mut self,
3731        result: std::result::Result<T, oracledb_protocol::ProtocolError>,
3732    ) -> Result<T> {
3733        match result {
3734            Ok(value) => Ok(value),
3735            Err(err) => {
3736                if protocol_error_is_session_dead(&err) {
3737                    self.dead = true;
3738                    self.core.recovery.mark_dead();
3739                }
3740                Err(Error::Protocol(err))
3741            }
3742        }
3743    }
3744
3745    /// Round-trip a lightweight PING to verify the session is alive.
3746    pub async fn ping(&mut self, cx: &Cx) -> Result<()> {
3747        self.send_function(cx, TNS_FUNC_PING).await
3748    }
3749
3750    /// Change the session password via the dedicated auth round trip
3751    /// (reference `ThinConnImpl.change_password`): an AUTH_PHASE_TWO message
3752    /// carrying the combo-key-encrypted old/new passwords. Server errors
3753    /// (ORA-28218, ORA-01017, ...) surface unchanged.
3754    pub async fn change_password(
3755        &mut self,
3756        cx: &Cx,
3757        old_password: &str,
3758        new_password: &str,
3759    ) -> Result<()> {
3760        observe_cancellation_between_round_trips(cx)?;
3761        self.ensure_clean_before_request().await?;
3762        let (encoded_password, encoded_newpassword) =
3763            oracledb_protocol::crypto::encrypt_change_password_pair(
3764                &self.combo_key,
3765                old_password.as_bytes(),
3766                new_password.as_bytes(),
3767            )?;
3768        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
3769        let payload = build_change_password_payload_with_seq(
3770            &self.user,
3771            &encoded_password,
3772            &encoded_newpassword,
3773            seq_num,
3774            self.capabilities.ttc_field_version,
3775        )?;
3776        self.core.send_data_packet(cx, &payload, self.sdu).await?;
3777        // change_password is an auth-shaped round trip, so the classic probe is
3778        // the same terminal-message rule the connect-phase reads use.
3779        let limits = self.protocol_limits;
3780        let response = self
3781            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
3782                classic_connect_response_is_complete(bytes, limits).unwrap_or(true)
3783            })
3784            .await?;
3785        self.note_parse(
3786            parse_auth_response_with_limits(&response, self.protocol_limits).map(|_| ()),
3787        )?;
3788        Ok(())
3789    }
3790
3791    /// Register a CQN subscription (FUNC 125, opcode 1) on this connection.
3792    /// Returns the registration id (`Subscription.id`) and the EMON client id
3793    /// echoed in the subsequent NOTIFY. `public_qos`/`operations` are the public
3794    /// `SUBSCR_QOS_*` / `OPCODE_*` values; the wire derivation lives in the
3795    /// protocol builder. Reference `ThinSubscrImpl.subscribe`.
3796    #[allow(clippy::too_many_arguments)]
3797    pub async fn subscribe_register(
3798        &mut self,
3799        cx: &Cx,
3800        namespace: u32,
3801        name: Option<&str>,
3802        public_qos: u32,
3803        operations: u32,
3804        timeout: u32,
3805        grouping_class: u8,
3806        grouping_value: u32,
3807        grouping_type: u8,
3808    ) -> Result<SubscribeResult> {
3809        observe_cancellation_between_round_trips(cx)?;
3810        self.ensure_clean_before_request().await?;
3811        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
3812        let payload = build_subscribe_payload_with_seq(
3813            seq_num,
3814            TNS_SUBSCR_OP_REGISTER,
3815            Some(&self.user),
3816            None,
3817            namespace,
3818            name,
3819            public_qos,
3820            operations,
3821            timeout,
3822            grouping_class,
3823            grouping_value,
3824            grouping_type,
3825            0,
3826            self.capabilities.ttc_field_version,
3827        )?;
3828        self.core.send_data_packet(cx, &payload, self.sdu).await?;
3829        // Classic-aware read: pre-23ai servers never negotiate END_OF_RESPONSE
3830        // framing, so the flag-driven reader would block forever. The probe
3831        // decides completion by parsing the accumulated payload (bead
3832        // rust-oracledb-eyp7).
3833        let capabilities = self.capabilities;
3834        let limits = self.protocol_limits;
3835        let response = self
3836            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
3837                response_complete(&parse_subscribe_response_with_limits(
3838                    bytes,
3839                    capabilities,
3840                    limits,
3841                ))
3842            })
3843            .await?;
3844        self.note_parse(parse_subscribe_response_with_limits(
3845            &response,
3846            self.capabilities,
3847            self.protocol_limits,
3848        ))
3849    }
3850
3851    /// Unregister a CQN subscription (FUNC 125, opcode 2). The `client_id` is
3852    /// the value returned by [`Self::subscribe_register`] (now non-None so its
3853    /// pointer/bytes are emitted) and `registration_id` rides on the tail.
3854    /// Reference `ThinSubscrImpl.unsubscribe`.
3855    #[allow(clippy::too_many_arguments)]
3856    pub async fn subscribe_unregister(
3857        &mut self,
3858        cx: &Cx,
3859        registration_id: u64,
3860        client_id: &[u8],
3861        namespace: u32,
3862        name: Option<&str>,
3863        public_qos: u32,
3864        operations: u32,
3865        timeout: u32,
3866        grouping_class: u8,
3867        grouping_value: u32,
3868        grouping_type: u8,
3869    ) -> Result<()> {
3870        observe_cancellation_between_round_trips(cx)?;
3871        self.ensure_clean_before_request().await?;
3872        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
3873        // unregister reuses the same `_write_message` path: the name/qos/
3874        // operations/grouping fields mirror the original registration so the
3875        // server can match the subscription (reference passes the same
3876        // `subscr_impl`).
3877        let payload = build_subscribe_payload_with_seq(
3878            seq_num,
3879            TNS_SUBSCR_OP_UNREGISTER,
3880            Some(&self.user),
3881            Some(client_id),
3882            namespace,
3883            name,
3884            public_qos,
3885            operations,
3886            timeout,
3887            grouping_class,
3888            grouping_value,
3889            grouping_type,
3890            registration_id,
3891            self.capabilities.ttc_field_version,
3892        )?;
3893        self.core.send_data_packet(cx, &payload, self.sdu).await?;
3894        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
3895        // rust-oracledb-eyp7.
3896        let capabilities = self.capabilities;
3897        let limits = self.protocol_limits;
3898        let response = self
3899            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
3900                response_complete(&parse_subscribe_response_with_limits(
3901                    bytes,
3902                    capabilities,
3903                    limits,
3904                ))
3905            })
3906            .await?;
3907        self.note_parse(parse_subscribe_response_with_limits(
3908            &response,
3909            self.capabilities,
3910            self.protocol_limits,
3911        ))?;
3912        Ok(())
3913    }
3914
3915    /// Send the single NOTIFY message (FUNC 187) that arms the EMON push stream
3916    /// on this (emon) connection. No response is read here; pushed notification
3917    /// packets are consumed by [`Self::recv_notification`]. Reference
3918    /// `ThinSubscrImpl._bg_task_func` (sends NOTIFY then blocks reading).
3919    pub async fn notify_register(&mut self, cx: &Cx, client_id: &[u8]) -> Result<()> {
3920        observe_cancellation_between_round_trips(cx)?;
3921        self.ensure_clean_before_request().await?;
3922        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
3923        let payload =
3924            build_notify_payload_with_seq(seq_num, client_id, self.capabilities.ttc_field_version)?;
3925        // NOTIFY sets the END_OF_REQUEST data flag on its (single) packet.
3926        self.core
3927            .send_data_packet_with_flags(cx, &payload, self.sdu, 0, TNS_DATA_FLAGS_END_OF_REQUEST)
3928            .await?;
3929        Ok(())
3930    }
3931
3932    /// Wait for the next CQN notification record pushed by the EMON process and
3933    /// decode it. `read_timeout` bounds each underlying socket read so the
3934    /// background receive loop can poll a shutdown flag between reads (the DB
3935    /// never sends an end-of-stream marker; teardown unblocks the loop). The
3936    /// reference blocks forever and is unblocked by a forced socket close; the
3937    /// bounded read achieves the same clean teardown without a cross-thread
3938    /// socket close, and never hangs.
3939    ///
3940    /// Records may span several pushed packets, so this chains packets through
3941    /// `notification_buffer` exactly like the reference `ReadBuffer`.
3942    pub async fn recv_notification(
3943        &mut self,
3944        cx: &Cx,
3945        namespace: u32,
3946        public_qos: u32,
3947        read_timeout: Duration,
3948    ) -> Result<NotificationOutcome> {
3949        observe_cancellation_between_round_trips(cx)?;
3950        let db_name = self.descriptor.service_name.clone();
3951        loop {
3952            observe_cancellation_between_round_trips(cx)?;
3953            // consume the leading OAC message-type byte once
3954            if !self.notification_header_consumed {
3955                if self.notification_buffer.is_empty() {
3956                    match self.read_one_notification_packet(read_timeout).await? {
3957                        PacketRead::Appended => continue,
3958                        PacketRead::TimedOut => return Ok(NotificationOutcome::TimedOut),
3959                        PacketRead::Closed => return Ok(NotificationOutcome::Closed),
3960                    }
3961                }
3962                let consumed = check_notification_header_with_limits(
3963                    &self.notification_buffer,
3964                    self.protocol_limits,
3965                )?;
3966                self.notification_buffer.drain(..consumed);
3967                self.notification_header_consumed = true;
3968            }
3969            // try to decode one full record from the buffered bytes
3970            if !self.notification_buffer.is_empty() {
3971                if let Some((record, consumed)) = try_parse_oac_record_with_limits(
3972                    &self.notification_buffer,
3973                    namespace,
3974                    public_qos,
3975                    Some(&db_name),
3976                    self.protocol_limits,
3977                )? {
3978                    self.notification_buffer.drain(..consumed);
3979                    return Ok(NotificationOutcome::Record(record));
3980                }
3981            }
3982            // need more bytes: read another pushed packet (bounded)
3983            match self.read_one_notification_packet(read_timeout).await? {
3984                PacketRead::Appended => {}
3985                // a timeout mid-record is unusual; surface it so the caller can
3986                // re-check the shutdown flag and resume reading
3987                PacketRead::TimedOut => return Ok(NotificationOutcome::TimedOut),
3988                PacketRead::Closed => return Ok(NotificationOutcome::Closed),
3989            }
3990        }
3991    }
3992
3993    /// Reads one DATA packet from the emon socket (bounded by `read_timeout`)
3994    /// and appends its TTC payload (after the 2-byte data flags) to
3995    /// `notification_buffer`. Reports a timeout (so the caller can poll its
3996    /// shutdown flag) or a closed/errored socket distinctly. Non-DATA packets
3997    /// (markers, disconnect) end the stream.
3998    async fn read_one_notification_packet(&mut self, read_timeout: Duration) -> Result<PacketRead> {
3999        let read = self.core.read_packet(PacketLengthWidth::Large32);
4000        let packet = match time::timeout(time::wall_now(), read_timeout, read).await {
4001            Ok(Ok(packet)) => packet,
4002            // socket closed / errored (incl. force-close on teardown): end the
4003            // stream cleanly, mirroring the reference's swallowed read error
4004            Ok(Err(_)) => return Ok(PacketRead::Closed),
4005            Err(_) => return Ok(PacketRead::TimedOut),
4006        };
4007        if packet.packet_type != TNS_PACKET_TYPE_DATA {
4008            return Ok(PacketRead::Closed);
4009        }
4010        let Some((_data_flags, payload)) = packet.payload.split_at_checked(2) else {
4011            return Ok(PacketRead::Closed);
4012        };
4013        self.notification_buffer.extend_from_slice(payload);
4014        Ok(PacketRead::Appended)
4015    }
4016
4017    /// Ping with an upper bound on the round trip, used by pool health
4018    /// checks (reference pings under `ping_timeout`).
4019    pub async fn ping_with_timeout(&mut self, cx: &Cx, timeout_ms: u32) -> Result<()> {
4020        if timeout_ms == 0 {
4021            return self.ping(cx).await;
4022        }
4023        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
4024        match deadline.run(self.ping(cx)).await {
4025            Ok(result) => result,
4026            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
4027            // Previously this returned bare CallTimeout without even sending a
4028            // BREAK, leaving the half-sent ping round trip on the wire to poison
4029            // the next reuse. Break + drain like every other timeout path.
4030            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
4031        }
4032    }
4033
4034    /// Commit the current transaction. DML on a connection is not durable
4035    /// until committed.
4036    pub async fn commit(&mut self, cx: &Cx) -> Result<()> {
4037        let _span = obs_span!("oracledb.commit");
4038        self.send_function(cx, TNS_FUNC_COMMIT).await?;
4039        // a commit ends any active sessionless transaction on the server
4040        // (reference clears `_sessionless_data` via the SYNC piggyback)
4041        self.sessionless_data = None;
4042        Ok(())
4043    }
4044
4045    /// Roll back the current transaction, discarding uncommitted DML.
4046    pub async fn rollback(&mut self, cx: &Cx) -> Result<()> {
4047        let _span = obs_span!("oracledb.rollback");
4048        self.send_function(cx, TNS_FUNC_ROLLBACK).await?;
4049        self.sessionless_data = None;
4050        Ok(())
4051    }
4052
4053    /// Enable server-side `DBMS_OUTPUT` buffering for this session. `buffer_bytes`
4054    /// caps the server buffer; `None` requests an unbounded buffer
4055    /// (`DBMS_OUTPUT.ENABLE(NULL)`). Call once before running the PL/SQL whose
4056    /// output you want, then [`read_dbms_output`](Self::read_dbms_output).
4057    pub async fn enable_dbms_output(&mut self, cx: &Cx, buffer_bytes: Option<u32>) -> Result<()> {
4058        // `buffer_bytes` is a u32 we own (never untrusted text), so inlining it
4059        // as a numeric literal is injection-safe and avoids an extra IN bind.
4060        let arg = buffer_bytes.map_or_else(|| "null".to_string(), |n| n.to_string());
4061        self.execute_query_with_bind_rows_and_options_core(
4062            cx,
4063            &format!("begin dbms_output.enable({arg}); end;"),
4064            0,
4065            &[],
4066            ExecuteOptions::default(),
4067        )
4068        .await?;
4069        Ok(())
4070    }
4071
4072    /// Read buffered `DBMS_OUTPUT` from this session via the canonical
4073    /// `GET_LINE(:line, :status)` loop, bounded by `max_lines` and `max_chars`.
4074    /// Stops cleanly when the server reports no more lines (`status != 0`) or
4075    /// when a bound is reached (setting [`DbmsOutput::truncated`]). Output is
4076    /// captured from this exact connection/session. python-oracledb leaves this
4077    /// loop to the caller; this centralizes it.
4078    pub async fn read_dbms_output(
4079        &mut self,
4080        cx: &Cx,
4081        max_lines: usize,
4082        max_chars: usize,
4083    ) -> Result<DbmsOutput> {
4084        // ORA_TYPE_SIZE_NUMBER is crate-private upstream; 22 is the NUMBER size.
4085        const NUMBER_SIZE: u32 = 22;
4086        let mut out = DbmsOutput::default();
4087        loop {
4088            observe_cancellation_between_round_trips(cx)?;
4089            let binds = [vec![
4090                BindValue::Output {
4091                    ora_type_num: oracledb_protocol::thin::ORA_TYPE_NUM_VARCHAR,
4092                    csfrm: oracledb_protocol::thin::CS_FORM_IMPLICIT,
4093                    buffer_size: 32767,
4094                },
4095                BindValue::Output {
4096                    ora_type_num: oracledb_protocol::thin::ORA_TYPE_NUM_NUMBER,
4097                    csfrm: 0,
4098                    buffer_size: NUMBER_SIZE,
4099                },
4100            ]];
4101            let res = self
4102                .execute_query_with_bind_rows_and_options_core(
4103                    cx,
4104                    "begin dbms_output.get_line(:1, :2); end;",
4105                    0,
4106                    &binds,
4107                    ExecuteOptions::default(),
4108                )
4109                .await?;
4110            // OUT values come back in bind order: [0] = line, [1] = status.
4111            let status = res
4112                .out_values
4113                .get(1)
4114                .and_then(|(_, v)| v.as_ref())
4115                .and_then(oracledb_protocol::thin::QueryValue::as_i64)
4116                .unwrap_or(1);
4117            if status != 0 {
4118                break; // no more lines buffered
4119            }
4120            let line = res
4121                .out_values
4122                .first()
4123                .and_then(|(_, v)| v.as_ref())
4124                .and_then(oracledb_protocol::thin::QueryValue::as_text)
4125                .unwrap_or("")
4126                .to_string();
4127            let chars = line.chars().count();
4128            // A real line is in hand. If it would cross a bound, stop and report
4129            // truncation: this line is past the bound and is discarded (it is part
4130            // of the acknowledged-truncated remainder). Checking after the read —
4131            // rather than before — keeps `truncated` exact: output that ends right
4132            // at `max_lines` reports `truncated == false`, not a false positive.
4133            if out.lines.len() >= max_lines || out.char_count + chars > max_chars {
4134                out.truncated = true;
4135                break;
4136            }
4137            out.char_count += chars;
4138            out.lines.push(line);
4139            out.line_count += 1;
4140        }
4141        Ok(out)
4142    }
4143
4144    /// Begins (`flags = TPC_TXN_FLAGS_NEW`) or resumes
4145    /// (`flags = TPC_TXN_FLAGS_RESUME`) a sessionless transaction. With
4146    /// `defer_round_trip = false` the request is sent immediately; with `true`
4147    /// it is queued as a piggyback on the next execute (reference
4148    /// impl/thin/connection.pyx `_start_sessionless_transaction`).
4149    async fn start_sessionless_transaction(
4150        &mut self,
4151        cx: &Cx,
4152        transaction_id: &[u8],
4153        timeout: u32,
4154        flags: u32,
4155        defer_round_trip: bool,
4156    ) -> Result<()> {
4157        if self.sessionless_data.is_some() {
4158            return Err(Error::SessionlessTransaction(
4159                SessionlessError::AlreadyActive,
4160            ));
4161        }
4162        let data = SessionlessData {
4163            transaction_id: transaction_id.to_vec(),
4164            timeout,
4165            operation: TNS_TPC_TXN_START,
4166            flags,
4167            piggyback_pending: defer_round_trip,
4168            started_on_server: false,
4169        };
4170        if defer_round_trip {
4171            // queue the begin/resume to ride on the next execute
4172            self.sessionless_data = Some(data);
4173            return Ok(());
4174        }
4175        // send the begin/resume immediately
4176        observe_cancellation_between_round_trips(cx)?;
4177        self.ensure_clean_before_request().await?;
4178        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
4179        let payload = build_tpc_txn_switch_payload_with_seq(
4180            seq_num,
4181            0,
4182            data.operation,
4183            data.flags | TPC_TXN_FLAGS_SESSIONLESS,
4184            data.timeout,
4185            Some(transaction_id),
4186        );
4187        self.core.send_data_packet(cx, &payload, self.sdu).await?;
4188        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
4189        // rust-oracledb-eyp7.
4190        let capabilities = self.capabilities;
4191        let limits = self.protocol_limits;
4192        let response = self
4193            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
4194                response_complete(&parse_tpc_txn_switch_response_with_limits(
4195                    bytes,
4196                    capabilities,
4197                    limits,
4198                ))
4199            })
4200            .await?;
4201        let state = self.note_parse(parse_tpc_txn_switch_response_with_limits(
4202            &response,
4203            self.capabilities,
4204            self.protocol_limits,
4205        ))?;
4206        self.sessionless_data = Some(data);
4207        self.apply_sessionless_state(state);
4208        Ok(())
4209    }
4210
4211    /// Begins a new sessionless transaction (reference
4212    /// `begin_sessionless_transaction`).
4213    pub async fn begin_sessionless_transaction(
4214        &mut self,
4215        cx: &Cx,
4216        transaction_id: &[u8],
4217        timeout: u32,
4218        defer_round_trip: bool,
4219    ) -> Result<()> {
4220        self.start_sessionless_transaction(
4221            cx,
4222            transaction_id,
4223            timeout,
4224            TPC_TXN_FLAGS_NEW,
4225            defer_round_trip,
4226        )
4227        .await
4228    }
4229
4230    /// Resumes an existing sessionless transaction (reference
4231    /// `resume_sessionless_transaction`).
4232    pub async fn resume_sessionless_transaction(
4233        &mut self,
4234        cx: &Cx,
4235        transaction_id: &[u8],
4236        timeout: u32,
4237        defer_round_trip: bool,
4238    ) -> Result<()> {
4239        self.start_sessionless_transaction(
4240            cx,
4241            transaction_id,
4242            timeout,
4243            TPC_TXN_FLAGS_RESUME,
4244            defer_round_trip,
4245        )
4246        .await
4247    }
4248
4249    /// Suspends the active sessionless transaction immediately (reference
4250    /// `suspend_sessionless_transaction`).
4251    pub async fn suspend_sessionless_transaction(&mut self, cx: &Cx) -> Result<()> {
4252        match &self.sessionless_data {
4253            None => return Err(Error::SessionlessTransaction(SessionlessError::Inactive)),
4254            Some(data) if data.started_on_server => {
4255                return Err(Error::SessionlessTransaction(
4256                    SessionlessError::DifferingMethods,
4257                ));
4258            }
4259            Some(_) => {}
4260        }
4261        observe_cancellation_between_round_trips(cx)?;
4262        self.ensure_clean_before_request().await?;
4263        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
4264        let payload = build_tpc_txn_switch_payload_with_seq(
4265            seq_num,
4266            0,
4267            TNS_TPC_TXN_DETACH,
4268            TPC_TXN_FLAGS_SESSIONLESS,
4269            0,
4270            None,
4271        );
4272        self.core.send_data_packet(cx, &payload, self.sdu).await?;
4273        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
4274        // rust-oracledb-eyp7.
4275        let capabilities = self.capabilities;
4276        let limits = self.protocol_limits;
4277        let response = self
4278            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
4279                response_complete(&parse_tpc_txn_switch_response_with_limits(
4280                    bytes,
4281                    capabilities,
4282                    limits,
4283                ))
4284            })
4285            .await?;
4286        let state = self.note_parse(parse_tpc_txn_switch_response_with_limits(
4287            &response,
4288            self.capabilities,
4289            self.protocol_limits,
4290        ))?;
4291        // a suspend always clears the active transaction locally; the server's
4292        // SYNC piggyback confirms it (reference clears `_sessionless_data`)
4293        self.sessionless_data = None;
4294        self.apply_sessionless_state(state);
4295        Ok(())
4296    }
4297
4298    /// Run a TPC transaction-switch (func 103) round trip and capture its
4299    /// response. Shared by `tpc_begin` (START) and `tpc_end` (DETACH).
4300    async fn tpc_switch_round_trip(
4301        &mut self,
4302        cx: &Cx,
4303        operation: u32,
4304        flags: u32,
4305        timeout: u32,
4306        xid: Option<&TpcXid<'_>>,
4307        context: Option<&[u8]>,
4308    ) -> Result<TpcSwitchResponse> {
4309        observe_cancellation_between_round_trips(cx)?;
4310        self.ensure_clean_before_request().await?;
4311        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
4312        let payload = build_tpc_switch_payload_with_seq_and_version(
4313            seq_num,
4314            operation,
4315            flags,
4316            timeout,
4317            xid,
4318            context,
4319            self.capabilities.ttc_field_version,
4320        );
4321        self.core.send_data_packet(cx, &payload, self.sdu).await?;
4322        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
4323        // rust-oracledb-eyp7.
4324        let capabilities = self.capabilities;
4325        let limits = self.protocol_limits;
4326        let response = self
4327            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
4328                response_complete(&parse_tpc_switch_response_with_limits(
4329                    bytes,
4330                    capabilities,
4331                    limits,
4332                ))
4333            })
4334            .await?;
4335        self.note_parse(parse_tpc_switch_response_with_limits(
4336            &response,
4337            self.capabilities,
4338            self.protocol_limits,
4339        ))
4340    }
4341
4342    /// Run a TPC change-state (func 104) round trip and capture its response.
4343    /// Shared by `tpc_prepare` (PREPARE), `tpc_commit` (COMMIT) and
4344    /// `tpc_rollback` (ABORT).
4345    async fn tpc_change_state_round_trip(
4346        &mut self,
4347        cx: &Cx,
4348        operation: u32,
4349        requested_state: u32,
4350        xid: Option<&TpcXid<'_>>,
4351        context: Option<&[u8]>,
4352    ) -> Result<TpcChangeStateResponse> {
4353        observe_cancellation_between_round_trips(cx)?;
4354        self.ensure_clean_before_request().await?;
4355        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
4356        let payload = build_tpc_change_state_payload_with_seq_and_version(
4357            seq_num,
4358            operation,
4359            requested_state,
4360            0,
4361            xid,
4362            context,
4363            self.capabilities.ttc_field_version,
4364        );
4365        self.core.send_data_packet(cx, &payload, self.sdu).await?;
4366        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
4367        // rust-oracledb-eyp7.
4368        let capabilities = self.capabilities;
4369        let limits = self.protocol_limits;
4370        let response = self
4371            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
4372                response_complete(&parse_tpc_change_state_response_with_limits(
4373                    bytes,
4374                    capabilities,
4375                    limits,
4376                ))
4377            })
4378            .await?;
4379        self.note_parse(parse_tpc_change_state_response_with_limits(
4380            &response,
4381            self.capabilities,
4382            self.protocol_limits,
4383        ))
4384    }
4385
4386    /// Begin (or resume/promote, via `flags`) an XA global transaction
4387    /// (reference impl/thin/connection.pyx `tpc_begin`). The server returns a
4388    /// transaction context which is captured for the subsequent
4389    /// end/prepare/commit/rollback round trips.
4390    pub async fn tpc_begin(
4391        &mut self,
4392        cx: &Cx,
4393        format_id: u32,
4394        global_transaction_id: &[u8],
4395        branch_qualifier: &[u8],
4396        flags: u32,
4397        timeout: u32,
4398    ) -> Result<()> {
4399        let xid = TpcXid {
4400            format_id,
4401            global_transaction_id,
4402            branch_qualifier,
4403        };
4404        let response = self
4405            .tpc_switch_round_trip(cx, TNS_TPC_TXN_START, flags, timeout, Some(&xid), None)
4406            .await?;
4407        self.transaction_context = Some(response.context);
4408        self.txn_in_progress = response.txn_in_progress;
4409        Ok(())
4410    }
4411
4412    /// End (detach) an XA global transaction branch (reference `tpc_end`). The
4413    /// retained transaction context is echoed back; `xid` is `None` to detach
4414    /// the implicit current transaction. The context is cleared afterwards.
4415    pub async fn tpc_end(
4416        &mut self,
4417        cx: &Cx,
4418        xid: Option<(u32, &[u8], &[u8])>,
4419        flags: u32,
4420    ) -> Result<()> {
4421        let xid = xid.map(|(format_id, gtid, bqual)| TpcXid {
4422            format_id,
4423            global_transaction_id: gtid,
4424            branch_qualifier: bqual,
4425        });
4426        let context = self.transaction_context.clone();
4427        let response = self
4428            .tpc_switch_round_trip(
4429                cx,
4430                TNS_TPC_TXN_DETACH,
4431                flags,
4432                0,
4433                xid.as_ref(),
4434                context.as_deref(),
4435            )
4436            .await?;
4437        self.txn_in_progress = response.txn_in_progress;
4438        self.transaction_context = None;
4439        Ok(())
4440    }
4441
4442    /// Prepare an XA global transaction for commit (reference `tpc_prepare`).
4443    /// Returns `true` when the transaction requires a commit, `false` when it
4444    /// is read-only; an unexpected out state raises DPY-5010.
4445    pub async fn tpc_prepare(&mut self, cx: &Cx, xid: Option<(u32, &[u8], &[u8])>) -> Result<bool> {
4446        let xid = xid.map(|(format_id, gtid, bqual)| TpcXid {
4447            format_id,
4448            global_transaction_id: gtid,
4449            branch_qualifier: bqual,
4450        });
4451        let context = self.transaction_context.clone();
4452        let response = self
4453            .tpc_change_state_round_trip(
4454                cx,
4455                TNS_TPC_TXN_PREPARE,
4456                TNS_TPC_TXN_STATE_PREPARE,
4457                xid.as_ref(),
4458                context.as_deref(),
4459            )
4460            .await?;
4461        self.txn_in_progress = response.txn_in_progress;
4462        match response.state {
4463            TNS_TPC_TXN_STATE_REQUIRES_COMMIT => Ok(true),
4464            TNS_TPC_TXN_STATE_READ_ONLY => Ok(false),
4465            other => Err(Error::UnknownTransactionState(other)),
4466        }
4467    }
4468
4469    /// Commit an XA global transaction (reference `tpc_commit`). `one_phase`
4470    /// requests a single-phase (read-only) commit; two-phase requests a
4471    /// committed state and expects the server to return FORGOTTEN. The retained
4472    /// context is sent and cleared. An unexpected out state raises DPY-5010.
4473    pub async fn tpc_commit(
4474        &mut self,
4475        cx: &Cx,
4476        xid: Option<(u32, &[u8], &[u8])>,
4477        one_phase: bool,
4478    ) -> Result<()> {
4479        let xid = xid.map(|(format_id, gtid, bqual)| TpcXid {
4480            format_id,
4481            global_transaction_id: gtid,
4482            branch_qualifier: bqual,
4483        });
4484        let requested_state = if one_phase {
4485            TNS_TPC_TXN_STATE_READ_ONLY
4486        } else {
4487            TNS_TPC_TXN_STATE_COMMITTED
4488        };
4489        let context = self.transaction_context.clone();
4490        let response = self
4491            .tpc_change_state_round_trip(
4492                cx,
4493                TNS_TPC_TXN_COMMIT,
4494                requested_state,
4495                xid.as_ref(),
4496                context.as_deref(),
4497            )
4498            .await?;
4499        self.txn_in_progress = response.txn_in_progress;
4500        // reference `_check_tpc_commit_state`: one-phase must be READ_ONLY or
4501        // COMMITTED; two-phase must be FORGOTTEN.
4502        let state = response.state;
4503        let ok = if one_phase {
4504            state == TNS_TPC_TXN_STATE_READ_ONLY || state == TNS_TPC_TXN_STATE_COMMITTED
4505        } else {
4506            state == TNS_TPC_TXN_STATE_FORGOTTEN
4507        };
4508        if !ok {
4509            return Err(Error::UnknownTransactionState(state));
4510        }
4511        self.transaction_context = None;
4512        Ok(())
4513    }
4514
4515    /// Roll back an XA global transaction (reference `tpc_rollback`). The
4516    /// retained context is sent; the server is expected to return ABORTED. An
4517    /// unexpected out state raises DPY-5010.
4518    pub async fn tpc_rollback(&mut self, cx: &Cx, xid: Option<(u32, &[u8], &[u8])>) -> Result<()> {
4519        let xid = xid.map(|(format_id, gtid, bqual)| TpcXid {
4520            format_id,
4521            global_transaction_id: gtid,
4522            branch_qualifier: bqual,
4523        });
4524        let context = self.transaction_context.clone();
4525        let response = self
4526            .tpc_change_state_round_trip(
4527                cx,
4528                TNS_TPC_TXN_ABORT,
4529                TNS_TPC_TXN_STATE_ABORTED,
4530                xid.as_ref(),
4531                context.as_deref(),
4532            )
4533            .await?;
4534        self.txn_in_progress = response.txn_in_progress;
4535        if response.state != TNS_TPC_TXN_STATE_ABORTED {
4536            return Err(Error::UnknownTransactionState(response.state));
4537        }
4538        Ok(())
4539    }
4540
4541    /// Whether a server-side transaction is in progress (reference
4542    /// `get_transaction_in_progress` -> `_txn_in_progress`).
4543    pub fn transaction_in_progress(&self) -> bool {
4544        self.txn_in_progress
4545    }
4546
4547    /// Validate that a `suspend_on_success` request is legal and fold the
4548    /// post-detach into the pending sessionless piggyback (reference
4549    /// execute.pyx `_handle_sessionless_suspend`). Called by the cursor execute
4550    /// path before building the execute message.
4551    pub fn prepare_sessionless_suspend_on_success(&mut self) -> Result<()> {
4552        match &mut self.sessionless_data {
4553            None => Err(Error::SessionlessTransaction(SessionlessError::Inactive)),
4554            Some(data) if data.started_on_server => Err(Error::SessionlessTransaction(
4555                SessionlessError::DifferingMethods,
4556            )),
4557            Some(data) => {
4558                if data.piggyback_pending {
4559                    data.operation |= TNS_TPC_TXN_POST_DETACH;
4560                } else {
4561                    data.operation = TNS_TPC_TXN_POST_DETACH;
4562                    data.flags = TPC_TXN_FLAGS_SESSIONLESS;
4563                    data.piggyback_pending = true;
4564                }
4565                Ok(())
4566            }
4567        }
4568    }
4569
4570    /// Take the pending sessionless piggyback bytes (if any) to prepend to the
4571    /// next execute payload, mirroring the close-cursors piggyback flow. The
4572    /// piggyback's sequence number is consumed from the connection counter so
4573    /// it precedes the execute's own sequence number.
4574    fn take_sessionless_piggyback(&mut self) -> Option<Vec<u8>> {
4575        let data = self.sessionless_data.as_mut()?;
4576        if !data.piggyback_pending {
4577            return None;
4578        }
4579        data.piggyback_pending = false;
4580        let xid = if data.operation & TNS_TPC_TXN_START != 0 {
4581            Some(data.transaction_id.clone())
4582        } else {
4583            None
4584        };
4585        let flags = data.flags | TPC_TXN_FLAGS_SESSIONLESS;
4586        let operation = data.operation;
4587        let timeout = data.timeout;
4588        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
4589        Some(build_sessionless_piggyback(
4590            seq_num,
4591            0,
4592            operation,
4593            flags,
4594            timeout,
4595            xid.as_deref(),
4596        ))
4597    }
4598
4599    /// Apply a sessionless state update reported by the server (via the SYNC
4600    /// piggyback) to the connection's tracked state (reference
4601    /// `_update_sessionless_txn_state`).
4602    fn apply_sessionless_state(&mut self, state: Option<SessionlessTxnState>) {
4603        match state {
4604            // transaction ended/suspended on the server (reference clears
4605            // `_sessionless_data` and sets `_txn_in_progress = False`,
4606            // base.pyx:152/161)
4607            Some(SessionlessTxnState::Unset) => {
4608                self.sessionless_data = None;
4609                self.txn_in_progress = false;
4610            }
4611            // transaction started/resumed (reference replaces `_sessionless_data`
4612            // with a fresh `_SessionlessData`). This also covers a transaction
4613            // started via DBMS_TRANSACTION on the server, where no client-side
4614            // data existed yet: the server SET carries `started_on_server` so a
4615            // later client suspend/resume correctly raises DPY-3034.
4616            Some(SessionlessTxnState::Set { started_on_server }) => {
4617                self.txn_in_progress = true;
4618                match self.sessionless_data.as_mut() {
4619                    Some(data) => {
4620                        data.started_on_server = started_on_server;
4621                        data.piggyback_pending = false;
4622                    }
4623                    None => {
4624                        self.sessionless_data = Some(SessionlessData {
4625                            transaction_id: Vec::new(),
4626                            timeout: 0,
4627                            operation: TNS_TPC_TXN_START,
4628                            flags: 0,
4629                            piggyback_pending: false,
4630                            started_on_server,
4631                        });
4632                    }
4633                }
4634            }
4635            None => {}
4636        }
4637    }
4638
4639    #[allow(dead_code)]
4640    async fn execute_query_collect_core(
4641        &mut self,
4642        cx: &Cx,
4643        sql: &str,
4644        prefetch_rows: u32,
4645    ) -> Result<QueryResult> {
4646        let mut result = self
4647            .execute_query_with_bind_rows_and_options_core(
4648                cx,
4649                sql,
4650                prefetch_rows,
4651                &[],
4652                ExecuteOptions::default(),
4653            )
4654            .await?;
4655        if !columns_require_define(&result.columns) || result.cursor_id == 0 {
4656            return Ok(result);
4657        }
4658        // When the open server cursor already streamed rows inline (an active
4659        // define on a re-execute), those rows are authoritative; keep them.
4660        if !result.rows.is_empty() {
4661            return Ok(result);
4662        }
4663        let cursor_id = result.cursor_id;
4664        let columns = result.columns.clone();
4665        let fetched_result = self
4666            .define_and_fetch_rows_with_columns(cx, cursor_id, prefetch_rows.max(1), &columns, None)
4667            .await;
4668        let fetched = self.close_cursor_on_error(cursor_id, fetched_result)?;
4669        result.rows = fetched.rows;
4670        result.more_rows = fetched.more_rows;
4671        if !fetched.columns.is_empty() {
4672            result.columns = fetched.columns;
4673        }
4674        if result.cursor_id == 0 {
4675            result.cursor_id = cursor_id;
4676        }
4677        Ok(result)
4678    }
4679
4680    /// True when `sql` already has an open server cursor in the statement cache.
4681    /// The Arrow fetch entry points use this to tell a COLD query (freshly
4682    /// parsed cursor, no server-side define yet) from a WARM one (a cached cursor
4683    /// whose client-side define was established by an earlier fetch and persists
4684    /// server-side) — see [`Self::establish_cold_define`].
4685    #[cfg(feature = "arrow")]
4686    pub(crate) fn statement_has_cached_cursor(&self, sql: &str) -> bool {
4687        self.statement_cache
4688            .iter()
4689            .any(|entry| entry.sql == sql && entry.cursor_id != 0)
4690    }
4691
4692    /// Establishes the client-side define for a COLD define-requiring query
4693    /// (`VECTOR` / native `JSON` / `CLOB` / `BLOB`) so the first fetch on the
4694    /// freshly parsed cursor carries the define. Such columns come back from the
4695    /// execute as describe-only metadata (an empty first page); the server only
4696    /// streams their values once a define-fetch has told it the client's buffer
4697    /// shape. The row query paths ([`Self::query_with`],
4698    /// [`Self::execute_query_collect_core`]) already do this; the Arrow fetch
4699    /// paths ran a plain fetch instead and desynced ("invalid ub8 length") on a
4700    /// cold `VECTOR` (bead a4-0mk).
4701    ///
4702    /// `warm` (from [`Self::statement_has_cached_cursor`], captured BEFORE the
4703    /// execute) skips this: a warm cursor already carries the server-side define
4704    /// from an earlier fetch, so a plain fetch is correct — this keeps the
4705    /// already-working warm Arrow path byte-identical. Non-define-requiring
4706    /// queries (the scalar columnar fast path) and executes that streamed rows
4707    /// inline are also no-ops.
4708    #[cfg(feature = "arrow")]
4709    pub(crate) async fn establish_cold_define(
4710        &mut self,
4711        cx: &Cx,
4712        warm: bool,
4713        result: &mut QueryResult,
4714        prefetch_rows: u32,
4715    ) -> Result<()> {
4716        if warm
4717            || result.cursor_id == 0
4718            || !result.rows.is_empty()
4719            || !columns_require_define(&result.columns)
4720        {
4721            return Ok(());
4722        }
4723        let cursor_id = result.cursor_id;
4724        let columns = result.columns.clone();
4725        let fetched_result = self
4726            .define_and_fetch_rows_with_columns(cx, cursor_id, prefetch_rows.max(1), &columns, None)
4727            .await;
4728        let fetched = self.close_cursor_on_error(cursor_id, fetched_result)?;
4729        result.rows = fetched.rows;
4730        result.more_rows = fetched.more_rows;
4731        if !fetched.columns.is_empty() {
4732            result.columns = fetched.columns;
4733        }
4734        if result.cursor_id == 0 {
4735            result.cursor_id = cursor_id;
4736        }
4737        Ok(())
4738    }
4739
4740    /// Ergonomic query: bind typed Rust values positionally and return a lazy
4741    /// [`Rows`] facade. `params` is anything that converts into [`Params`]: a tuple
4742    /// `(40, "alice")`, a homogeneous array `[1, 2, 3]`, a raw
4743    /// `Vec<BindValue>`, or the named [`params!`](crate::params) form:
4744    ///
4745    /// ```no_run
4746    /// # use oraclemcp_driver_cx::Connection;
4747    /// # use asupersync::Cx;
4748    /// # async fn demo(conn: &mut Connection, cx: &Cx) -> Result<(), oraclemcp_driver_cx::Error> {
4749    /// let positional = conn.query(cx, "select :1 + :2 from dual", (40, 2)).await?
4750    ///     .collect(cx)
4751    ///     .await?;
4752    /// let named = conn
4753    ///     .query(cx, "select :a + :b from dual", oraclemcp_driver_cx::params!{ ":a" => 40, ":b" => 2 })
4754    ///     .await?
4755    ///     .collect(cx)
4756    ///     .await?;
4757    /// # let _ = (positional, named); Ok(()) }
4758    /// ```
4759    ///
4760    /// This is sugar over [`Self::query_with`]; the arraysize defaults to 100
4761    /// rows and define-requiring cells are materialized by default.
4762    pub async fn query<'p>(
4763        &mut self,
4764        cx: &Cx,
4765        sql: &str,
4766        params: impl Into<crate::Params<'p>>,
4767    ) -> Result<Rows<'_>> {
4768        self.query_with(cx, Query::owned_sql(sql.to_string()).bind(params))
4769            .await
4770    }
4771
4772    /// Run a query that must return exactly one row.
4773    pub async fn query_one<'p>(
4774        &mut self,
4775        cx: &Cx,
4776        sql: &str,
4777        params: impl Into<crate::Params<'p>>,
4778    ) -> Result<Row> {
4779        let mut rows = self
4780            .query_with(
4781                cx,
4782                Query::owned_sql(sql.to_string())
4783                    .bind(params)
4784                    .arraysize(NonZeroU32::new(2).expect("two is non-zero"))
4785                    .prefetch(2),
4786            )
4787            .await?;
4788        rows.materialize_for_cardinality(cx).await?;
4789        rows.one()
4790    }
4791
4792    /// Run a query that may return zero or one row.
4793    pub async fn query_opt<'p>(
4794        &mut self,
4795        cx: &Cx,
4796        sql: &str,
4797        params: impl Into<crate::Params<'p>>,
4798    ) -> Result<Option<Row>> {
4799        let mut rows = self
4800            .query_with(
4801                cx,
4802                Query::owned_sql(sql.to_string())
4803                    .bind(params)
4804                    .arraysize(NonZeroU32::new(2).expect("two is non-zero"))
4805                    .prefetch(2),
4806            )
4807            .await?;
4808        rows.materialize_for_cardinality(cx).await?;
4809        rows.opt()
4810    }
4811
4812    /// Run a query and eagerly drain every fetch batch.
4813    pub async fn query_all<'p>(
4814        &mut self,
4815        cx: &Cx,
4816        sql: &str,
4817        params: impl Into<crate::Params<'p>>,
4818    ) -> Result<Vec<Row>> {
4819        self.query(cx, sql, params).await?.collect(cx).await
4820    }
4821
4822    /// Run a query described by a [`Query`] builder and return a lazy row
4823    /// facade for the first batch plus continuation fetches.
4824    pub async fn query_with<'conn, 'q>(
4825        &'conn mut self,
4826        cx: &Cx,
4827        query: Query<'q>,
4828    ) -> Result<Rows<'conn>> {
4829        let Query {
4830            sql,
4831            params,
4832            arraysize,
4833            prefetch,
4834            prefetch_set: _,
4835            materialize_lobs,
4836            scrollable,
4837            timeout,
4838        } = query;
4839        let sql_owned = sql.into_owned();
4840        let binds = crate::sql_convert::resolve_params(&sql_owned, params)?;
4841        let bind_rows = if binds.is_empty() {
4842            Vec::new()
4843        } else {
4844            vec![binds]
4845        };
4846        let exec_options = ExecuteOptions::default().with_scrollable(scrollable);
4847        let deadline = QueryDeadline::new(cx, timeout);
4848        let mut result = match deadline
4849            .run(self.execute_query_with_bind_rows_and_options_core(
4850                cx,
4851                &sql_owned,
4852                prefetch,
4853                &bind_rows,
4854                exec_options,
4855            ))
4856            .await
4857        {
4858            Ok(result) => result?,
4859            Err(DeadlineExpiry::BeforeStart) => {
4860                return self.reject_before_operation_start(cx, deadline.timeout_ms());
4861            }
4862            Err(DeadlineExpiry::InFlight) => {
4863                return self
4864                    .recover_from_call_timeout(cx, deadline.timeout_ms())
4865                    .await
4866            }
4867        };
4868        if materialize_lobs
4869            && columns_require_define(&result.columns)
4870            && result.cursor_id != 0
4871            && result.rows.is_empty()
4872        {
4873            let cursor_id = result.cursor_id;
4874            let columns = result.columns.clone();
4875            let fetched = match deadline
4876                .run(self.define_and_fetch_rows_with_columns(
4877                    cx,
4878                    cursor_id,
4879                    prefetch.max(1),
4880                    &columns,
4881                    None,
4882                ))
4883                .await
4884            {
4885                Ok(result) => self.close_cursor_on_error(cursor_id, result)?,
4886                Err(DeadlineExpiry::BeforeStart) => {
4887                    self.release_cursor(cursor_id);
4888                    return self.reject_before_operation_start(cx, deadline.timeout_ms());
4889                }
4890                Err(DeadlineExpiry::InFlight) => {
4891                    let recovered = self
4892                        .recover_from_call_timeout(cx, deadline.timeout_ms())
4893                        .await;
4894                    self.close_cursor(cursor_id);
4895                    return recovered;
4896                }
4897            };
4898            result.rows = fetched.rows;
4899            result.more_rows = fetched.more_rows;
4900            if !fetched.columns.is_empty() {
4901                result.columns = fetched.columns;
4902            }
4903            if result.cursor_id == 0 {
4904                result.cursor_id = cursor_id;
4905            }
4906        }
4907        Ok(Rows::from_result(
4908            self, sql_owned, arraysize, deadline, scrollable, result,
4909        ))
4910    }
4911
4912    /// Execute DML, DDL, or PL/SQL with a single bind row.
4913    pub async fn execute<'p>(
4914        &mut self,
4915        cx: &Cx,
4916        sql: &str,
4917        params: impl Into<crate::Params<'p>>,
4918    ) -> Result<ExecuteOutcome> {
4919        self.execute_with(cx, Execute::owned_sql(sql.to_string()).bind(params))
4920            .await
4921    }
4922
4923    /// Execute DML, DDL, or PL/SQL described by an [`Execute`] builder.
4924    pub async fn execute_with<'e>(
4925        &mut self,
4926        cx: &Cx,
4927        execute: Execute<'e>,
4928    ) -> Result<ExecuteOutcome> {
4929        let deadline = QueryDeadline::new(cx, execute.timeout_duration());
4930        self.execute_with_deadline(cx, execute, deadline).await
4931    }
4932
4933    async fn execute_with_deadline<'e>(
4934        &mut self,
4935        cx: &Cx,
4936        execute: Execute<'e>,
4937        deadline: QueryDeadline,
4938    ) -> Result<ExecuteOutcome> {
4939        let Execute {
4940            sql,
4941            params,
4942            timeout: _,
4943            options,
4944        } = execute;
4945        let sql_owned = sql.into_owned();
4946        let binds = crate::sql_convert::resolve_params(&sql_owned, params)?;
4947        let bind_rows = if binds.is_empty() {
4948            Vec::new()
4949        } else {
4950            vec![binds]
4951        };
4952        let result = match deadline
4953            .run(self.execute_query_with_bind_rows_and_options_core(
4954                cx, &sql_owned, 0, &bind_rows, options,
4955            ))
4956            .await
4957        {
4958            Ok(result) => result?,
4959            Err(DeadlineExpiry::BeforeStart) => {
4960                return self.reject_before_operation_start(cx, deadline.timeout_ms());
4961            }
4962            Err(DeadlineExpiry::InFlight) => {
4963                return self
4964                    .recover_from_call_timeout(cx, deadline.timeout_ms())
4965                    .await
4966            }
4967        };
4968        Ok(ExecuteOutcome::from_query_result(result))
4969    }
4970
4971    /// Execute `sql` once for each bind row in a single array-DML operation.
4972    pub async fn execute_many<'b>(
4973        &mut self,
4974        cx: &Cx,
4975        sql: &str,
4976        rows: impl Into<crate::BatchRows<'b>>,
4977    ) -> Result<BatchOutcome> {
4978        self.execute_many_with(cx, Batch::owned_sql(sql.to_string(), rows))
4979            .await
4980    }
4981
4982    /// Execute array DML described by a [`Batch`] builder.
4983    pub async fn execute_many_with<'b>(
4984        &mut self,
4985        cx: &Cx,
4986        batch: Batch<'b>,
4987    ) -> Result<BatchOutcome> {
4988        let Batch {
4989            sql,
4990            rows,
4991            timeout,
4992            options,
4993        } = batch;
4994        rows.validate_rectangular()?;
4995        if rows.is_empty() {
4996            return Ok(BatchOutcome::empty(options.arraydmlrowcounts()));
4997        }
4998        let sql_owned = sql.into_owned();
4999        let deadline = QueryDeadline::new(cx, timeout);
5000        let result = match deadline
5001            .run(self.execute_query_with_bind_rows_and_options_core(
5002                cx,
5003                &sql_owned,
5004                0,
5005                rows.as_slice(),
5006                options,
5007            ))
5008            .await
5009        {
5010            Ok(result) => result?,
5011            Err(DeadlineExpiry::BeforeStart) => {
5012                return self.reject_before_operation_start(cx, deadline.timeout_ms());
5013            }
5014            Err(DeadlineExpiry::InFlight) => {
5015                return self
5016                    .recover_from_call_timeout(cx, deadline.timeout_ms())
5017                    .await
5018            }
5019        };
5020        Ok(BatchOutcome::from_query_result(result))
5021    }
5022
5023    /// Register a query against an existing CQN subscription.
5024    pub async fn register_query<'r>(
5025        &mut self,
5026        cx: &Cx,
5027        registration: Registration<'r>,
5028    ) -> Result<RegistrationOutcome> {
5029        let Registration {
5030            sql,
5031            params,
5032            registration_id,
5033            timeout,
5034        } = registration;
5035        let sql_owned = sql.into_owned();
5036        let binds = crate::sql_convert::resolve_params(&sql_owned, params)?;
5037        let bind_rows = if binds.is_empty() {
5038            Vec::new()
5039        } else {
5040            vec![binds]
5041        };
5042        let exec_options = ExecuteOptions::default().with_registration_id(registration_id);
5043        let deadline = QueryDeadline::new(cx, timeout);
5044        let result = match deadline
5045            .run(self.execute_query_with_bind_rows_and_options_core(
5046                cx,
5047                &sql_owned,
5048                0,
5049                &bind_rows,
5050                exec_options,
5051            ))
5052            .await
5053        {
5054            Ok(result) => result?,
5055            Err(DeadlineExpiry::BeforeStart) => {
5056                return self.reject_before_operation_start(cx, deadline.timeout_ms());
5057            }
5058            Err(DeadlineExpiry::InFlight) => {
5059                return self
5060                    .recover_from_call_timeout(cx, deadline.timeout_ms())
5061                    .await
5062            }
5063        };
5064        Ok(RegistrationOutcome::from_query_result(result))
5065    }
5066
5067    pub(crate) async fn execute_query_with_binds_core(
5068        &mut self,
5069        cx: &Cx,
5070        sql: &str,
5071        prefetch_rows: u32,
5072        binds: &[BindValue],
5073    ) -> Result<QueryResult> {
5074        let bind_rows = if binds.is_empty() {
5075            Vec::new()
5076        } else {
5077            vec![binds.to_vec()]
5078        };
5079        self.execute_query_with_bind_rows_and_options_core(
5080            cx,
5081            sql,
5082            prefetch_rows,
5083            &bind_rows,
5084            ExecuteOptions::default(),
5085        )
5086        .await
5087    }
5088
5089    pub(crate) async fn execute_query_with_bind_rows_and_options_core(
5090        &mut self,
5091        cx: &Cx,
5092        sql: &str,
5093        prefetch_rows: u32,
5094        bind_rows: &[Vec<BindValue>],
5095        exec_options: ExecuteOptions,
5096    ) -> Result<QueryResult> {
5097        match self
5098            .execute_query_with_bind_rows_options_adjusted(
5099                cx,
5100                sql,
5101                prefetch_rows,
5102                bind_rows,
5103                exec_options,
5104            )
5105            .await
5106        {
5107            // a query re-executed against an open server cursor whose select
5108            // list changed since it was parsed reports ORA-00932 (inconsistent
5109            // data types) or ORA-01007 (variable not in select list); the
5110            // reference clears the cursor and retries once with a full parse
5111            // (impl/thin/messages/base.pyx:1199-1213). The failing adjusted
5112            // call has already evicted the stale cursor from the statement
5113            // cache, so the retry re-parses from scratch.
5114            Err(err) if refetch_retry_applies(&err) && statement_is_query(sql) => {
5115                observe_cancellation_between_round_trips(cx)?;
5116                // also drop any retained by-SQL fetch metadata used by the
5117                // older refetch path so the retry rebuilds it
5118                self.forget_fetch_metadata(sql);
5119                self.execute_query_with_bind_rows_options_adjusted(
5120                    cx,
5121                    sql,
5122                    prefetch_rows,
5123                    bind_rows,
5124                    exec_options,
5125                )
5126                .await
5127            }
5128            other => other,
5129        }
5130    }
5131
5132    async fn execute_query_with_bind_rows_options_adjusted(
5133        &mut self,
5134        cx: &Cx,
5135        sql: &str,
5136        prefetch_rows: u32,
5137        bind_rows: &[Vec<BindValue>],
5138        exec_options: ExecuteOptions,
5139    ) -> Result<QueryResult> {
5140        // Bind/execute round-trip span (feature-gated, zero-cost when off).
5141        // Carries the SQL digest, the bind count (binds per row — NEVER any bind
5142        // value), and the executemany row count; `db.rows_fetched` is filled
5143        // after the response.
5144        let _span = obs_span!(
5145            "oracledb.execute",
5146            db.statement = %crate::obs::sql_digest(sql),
5147            db.bind_count = bind_rows.first().map_or(0, Vec::len) as u64,
5148            db.bind_rows = bind_rows.len() as u64,
5149            db.rows_fetched = tracing::field::Empty,
5150        );
5151        observe_cancellation_between_round_trips(cx)?;
5152        // A parse-only describe carries no binds (the wire bind count is zero),
5153        // and a scroll continuation re-uses an already-bound cursor; neither
5154        // should be shape-validated. The raw validator only rejects ragged
5155        // array-DML rows — see `validate_bind_rows_shape`.
5156        if !exec_options.scroll_operation() && !exec_options.parse_only() {
5157            crate::sql_convert::validate_bind_rows_shape(sql, bind_rows)?;
5158            // First-execute type validation: array DML binds one type per column,
5159            // so a batch row whose value type disagrees with the type the first
5160            // typed row established would be silently coerced by the server into a
5161            // cryptic ORA error. Reject it up front with a precise typed error
5162            // (reference DPY-2006). A single-row execute always passes.
5163            crate::sql_convert::validate_bind_rows_types(bind_rows)?;
5164        }
5165        // If a prior cancellable round trip was dropped mid-read, break + drain
5166        // the stranded call before issuing this execute (Scope cancel-on-drop).
5167        self.ensure_clean_before_request().await?;
5168        let mut exec_options = exec_options.with_max_string_size(self.capabilities.max_string_size);
5169        // a `suspend_on_success` execute folds a post-detach into the pending
5170        // sessionless piggyback; validate (DPY-3034/3036) before any wire work
5171        // (reference execute.pyx `_handle_sessionless_suspend`)
5172        if exec_options.suspend_on_success() {
5173            self.prepare_sessionless_suspend_on_success()?;
5174        }
5175        let use_cache = exec_options.cache_statement() && !exec_options.parse_only();
5176        // Whether the cursor produced by this execute may be returned to the
5177        // statement cache (reference `Statement._return_to_cache`). A statement
5178        // that had to be copied because the cached cursor was in use is NOT
5179        // returnable: returning it would evict the still-live original from the
5180        // cache and reset its fetch position (ORA-01002).
5181        let mut is_copy = false;
5182        // Bind TYPE shape of this execute: a cached cursor is only reused when
5183        // the shape it was parsed/bound with is still compatible, otherwise it
5184        // is dropped and this execute re-parses with the new bind metadata
5185        // (bead rust-oracledb-ilel: ORA-01722 on a NUMBER->TEXT rebind).
5186        let bind_shape = bind_type_shape(bind_rows);
5187        if exec_options.cursor_id() == 0 && !exec_options.parse_only() {
5188            if use_cache {
5189                if self.statement_is_in_use(sql) {
5190                    // cached cursor busy: this execute parses a fresh (copy)
5191                    // cursor that must not be returned to the cache
5192                    is_copy = true;
5193                } else if let Some(cursor_id) = self.statement_cache_get(sql, &bind_shape) {
5194                    exec_options = exec_options.with_cursor_id(cursor_id);
5195                }
5196            } else if let Some(cursor_id) = self.statement_cache_take(sql, &bind_shape) {
5197                // reference pops the statement from the cache even when
5198                // cache_statement=False, reusing its open cursor once
5199                exec_options = exec_options.with_cursor_id(cursor_id);
5200            }
5201        }
5202        // Re-executing an open cursor whose columns require a client-side define
5203        // (VECTOR) must suppress server-side prefetch (reference
5204        // `stmt._no_prefetch`, set once during describe in messages/base.pyx
5205        // 1159-1164 and persisted on the cached statement). Otherwise the
5206        // re-execute prefetches the row inline and exhausts the cursor before
5207        // the define-fetch runs, raising ORA-01002 on the next fetch.
5208        if exec_options.cursor_id() != 0 && statement_is_query(sql) {
5209            if let Some(columns) = self.cursor_columns.get(&exec_options.cursor_id()) {
5210                if columns.iter().any(|column| {
5211                    column.ora_type_num() == oracledb_protocol::thin::ORA_TYPE_NUM_VECTOR
5212                }) {
5213                    exec_options = exec_options.with_no_prefetch(true);
5214                }
5215            }
5216        }
5217        let piggyback = self.take_close_cursors_piggyback();
5218        if piggyback.is_none() {
5219            let has_ref_cursor_output = bind_rows.iter().any(|row| {
5220                row.iter().any(|value| {
5221                    matches!(
5222                        value,
5223                        BindValue::Output {
5224                            ora_type_num: oracledb_protocol::thin::ORA_TYPE_NUM_CURSOR,
5225                            ..
5226                        }
5227                    )
5228                })
5229            });
5230            if has_ref_cursor_output {
5231                // python-oracledb reserves this sequence slot for a
5232                // close-cursor piggyback.
5233                let _ = next_ttc_sequence(&mut self.ttc_seq_num);
5234            }
5235        }
5236        // a deferred begin/resume or a folded-in suspend-on-success rides as a
5237        // sessionless piggyback prepended to this execute (reference
5238        // messages/base.pyx `_write_sessionless_piggyback`); its sequence number
5239        // is consumed before the execute's, after the close-cursors piggyback's.
5240        self.protocol_limits.check_batch_rows(bind_rows.len())?;
5241        if let Some(first_row) = bind_rows.first() {
5242            self.protocol_limits.check_binds(first_row.len())?;
5243        }
5244        let sessionless_piggyback = self.take_sessionless_piggyback();
5245        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
5246        let mut payload = build_execute_payload_with_bind_rows_and_options_with_seq(
5247            sql,
5248            prefetch_rows,
5249            seq_num,
5250            statement_is_query(sql),
5251            bind_rows,
5252            exec_options,
5253            self.capabilities.ttc_field_version,
5254        )?;
5255        if let Some(piggyback_bytes) = sessionless_piggyback {
5256            let mut combined = piggyback_bytes;
5257            combined.extend_from_slice(&payload);
5258            payload = combined;
5259        }
5260        if let Some(mut piggyback_bytes) = piggyback {
5261            piggyback_bytes.extend_from_slice(&payload);
5262            payload = piggyback_bytes;
5263        }
5264        trace_query_bytes("EXECUTE query payload", &payload);
5265        self.core.send_data_packet(cx, &payload, self.sdu).await?;
5266        let known_columns = if exec_options.cursor_id() != 0 {
5267            self.cursor_columns
5268                .get(&exec_options.cursor_id())
5269                .cloned()
5270                .unwrap_or_default()
5271        } else {
5272            Vec::new()
5273        };
5274        // Read under a cancel-on-drop guard: a dropped execute future arms the
5275        // next operation's break + drain. The classic probe is the same parse
5276        // this site runs below, with its result discarded.
5277        let capabilities = self.capabilities;
5278        let limits = self.protocol_limits;
5279        let first_bind_row = bind_rows.first().map(Vec::as_slice).unwrap_or(&[]);
5280        let classic = !self.supports_end_of_response;
5281        let response = self
5282            .read_flushing_out_binds_cancellable(cx, classic, |bytes| {
5283                response_complete(&parse_query_response_with_binds_options_columns_and_limits(
5284                    bytes,
5285                    capabilities,
5286                    first_bind_row,
5287                    exec_options,
5288                    &known_columns,
5289                    limits,
5290                ))
5291            })
5292            .await?;
5293        trace_query_bytes("EXECUTE query response", &response);
5294        let parsed = parse_query_response_with_binds_options_columns_and_limits(
5295            &response,
5296            self.capabilities,
5297            bind_rows.first().map(Vec::as_slice).unwrap_or(&[]),
5298            exec_options,
5299            &known_columns,
5300            self.protocol_limits,
5301        );
5302        match self.note_parse(parsed) {
5303            Ok(result) => {
5304                if result.cursor_id != 0
5305                    && !result.rows.is_empty()
5306                    && columns_have_lob_prefetch_fields(&result.columns)
5307                {
5308                    self.lob_prefetch_cursors.insert(result.cursor_id);
5309                }
5310                // a deferred begin/resume or a suspend-on-success reports its
5311                // outcome through the response's SYNC piggyback
5312                self.apply_sessionless_state(result.sessionless_txn_state);
5313                // refresh the transaction-in-progress flag from the wire
5314                // end-of-call status (reference protocol.pyx
5315                // `_process_call_status`); leave unchanged if the response
5316                // carried no STATUS message.
5317                if let Some(txn_in_progress) = result.txn_in_progress {
5318                    self.txn_in_progress = txn_in_progress;
5319                }
5320                if is_copy {
5321                    // a copied cursor is never returned to the statement cache;
5322                    // it is closed when its owning cursor releases it (reference
5323                    // `_return_to_cache = False` -> `_add_cursor_to_close`).
5324                    if result.cursor_id != 0 {
5325                        self.copied_cursors.insert(result.cursor_id);
5326                    }
5327                } else if use_cache {
5328                    self.statement_cache_put(sql, result.cursor_id, bind_shape);
5329                }
5330                // Mark the open query cursor as in use so a concurrent execute
5331                // of the same SQL on another cursor of this connection does not
5332                // reuse it (and reset its server-side fetch position). Released
5333                // by `release_cursor` when the owning cursor closes or
5334                // re-prepares (reference `Statement._in_use`). Only query
5335                // cursors hold a fetch position vulnerable to ORA-01002.
5336                if result.cursor_id != 0 && statement_is_query(sql) && !exec_options.parse_only() {
5337                    self.in_use_cursors.insert(result.cursor_id);
5338                }
5339                // A cursor passed as an IN REF CURSOR bind may be closed
5340                // server-side by the called PL/SQL (e.g. `close a_cursor`); its
5341                // cached cursor_id is then invalid. Drop any statement-cache
5342                // entry pointing at a bound cursor_id so the next execute on
5343                // that cursor re-parses with a fresh one instead of reusing the
5344                // closed one (ORA-01001). Test 1315 / 5815.
5345                self.invalidate_bound_ref_cursors(bind_rows);
5346                self.remember_cursor_columns(&result);
5347                obs_record!(_span, db.rows_fetched = result.rows.len() as u64);
5348                if exec_options.parse_only() {
5349                    return Ok(result);
5350                }
5351                self.apply_refetch_metadata(cx, sql, result, prefetch_rows.max(2))
5352                    .await
5353            }
5354            Err(err) => {
5355                // drop the cached cursor so the next execute re-parses
5356                // (reference base.pyx:1186-1189 clear_cursor on errors)
5357                if use_cache {
5358                    self.statement_cache_invalidate(sql, exec_options.cursor_id());
5359                }
5360                Err(err)
5361            }
5362        }
5363    }
5364
5365    /// Low-level raw execute: run `sql` once per bind row with explicit
5366    /// [`ExecuteOptions`] and an optional per-call timeout, returning the first
5367    /// fetch batch as a raw [`QueryResult`] (columns, `cursor_id`, `more_rows`,
5368    /// `rows`, OUT/RETURNING binds, batch errors, array DML row counts).
5369    ///
5370    /// This is the execute-side counterpart to the retained low-level fetch
5371    /// primitives ([`Self::fetch_rows`],
5372    /// [`Self::define_and_fetch_rows_with_columns`], [`Self::scroll_cursor`],
5373    /// [`Self::fetch_cursor`]): the four operation families
5374    /// ([`Self::query`]/[`Self::execute`]/[`Self::execute_many`]) are the
5375    /// ergonomic surface built *over* this, and project the `QueryResult` into
5376    /// the curated [`Rows`]/[`ExecuteOutcome`]/[`BatchOutcome`] outcomes. Use
5377    /// `execute_raw` only when you need the unprojected wire result — for
5378    /// example a statement-type-agnostic caller that decides query-vs-DML from
5379    /// `result.columns`, a parse-only describe (`exec_options.with_parse_only`),
5380    /// or per-bind-row OUT/RETURNING aggregation. Prefer the families for
5381    /// ordinary application code.
5382    ///
5383    /// `bind_rows` is positional array DML: each inner `Vec<BindValue>` is one
5384    /// bind row applied in a single round trip (an empty slice runs `sql` once
5385    /// with no binds). `prefetch_rows` is the requested first-batch size; rows
5386    /// beyond the first batch (when [`QueryResult::more_rows`] is set) are
5387    /// fetched with the cursor primitives above. `timeout_ms` of `Some(n)` with
5388    /// `n > 0` bounds the round trip with a BREAK→drain→[`Error::CallTimeout`]
5389    /// recovery that leaves the session usable; `None`/`Some(0)` runs untimed.
5390    pub async fn execute_raw(
5391        &mut self,
5392        cx: &Cx,
5393        sql: &str,
5394        prefetch_rows: u32,
5395        bind_rows: &[Vec<BindValue>],
5396        exec_options: ExecuteOptions,
5397        timeout_ms: Option<u32>,
5398    ) -> Result<QueryResult> {
5399        self.execute_query_with_bind_rows_options_call_timeout(
5400            cx,
5401            sql,
5402            prefetch_rows,
5403            bind_rows,
5404            exec_options,
5405            timeout_ms,
5406        )
5407        .await
5408    }
5409
5410    pub(crate) async fn execute_query_with_bind_rows_options_call_timeout(
5411        &mut self,
5412        cx: &Cx,
5413        sql: &str,
5414        prefetch_rows: u32,
5415        bind_rows: &[Vec<BindValue>],
5416        exec_options: ExecuteOptions,
5417        timeout_ms: Option<u32>,
5418    ) -> Result<QueryResult> {
5419        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
5420            return self
5421                .execute_query_with_bind_rows_and_options_core(
5422                    cx,
5423                    sql,
5424                    prefetch_rows,
5425                    bind_rows,
5426                    exec_options,
5427                )
5428                .await;
5429        };
5430        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
5431        match deadline
5432            .run(self.execute_query_with_bind_rows_and_options_core(
5433                cx,
5434                sql,
5435                prefetch_rows,
5436                bind_rows,
5437                exec_options,
5438            ))
5439            .await
5440        {
5441            Ok(result) => result,
5442            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
5443            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
5444        }
5445    }
5446
5447    /// If a previous cancellable fetch future was dropped mid-read (its
5448    /// `CancelDrainGuard` moved the recovery phase to `BreakSent`), break +
5449    /// drain the stranded server call now — before this round trip sends its own
5450    /// request — so the leftover bytes / still-running call cannot poison this
5451    /// response. A failed drain marks the connection dead and surfaces
5452    /// [`Error::ConnectionClosed`].
5453    ///
5454    /// A bare [`fetch_rows_request`](Self::fetch_rows_request) whose paired
5455    /// `fetch_rows_ref_response` is never consumed (the caller abandons the
5456    /// speculative page without dropping a response future to fire the guard)
5457    /// leaves the phase `InFlight` with a stranded response on the wire. Treat
5458    /// that the same as a dropped fetch: move it to `BreakSent` so the drain
5459    /// below reclaims the wire instead of wedging the connection on every
5460    /// subsequent operation. This is only ever reached from the *start* of the
5461    /// next operation — `fetch_rows_ref_response`, the one path that legitimately
5462    /// reads its own `InFlight` response, never calls this.
5463    async fn ensure_clean_before_request(&mut self) -> Result<()> {
5464        if self.core.recovery.phase() == SessionRecoveryPhase::InFlight {
5465            self.core.recovery.mark_break_required();
5466        }
5467        if !self.core.recovery.begin_pending_drain()? {
5468            return Ok(());
5469        }
5470        match self
5471            .core
5472            .cancel_and_drain_wire(BREAK_DRAIN_RECOVERY_TIMEOUT)
5473        {
5474            Ok(()) => {
5475                self.core.recovery.finish_drain_ready();
5476                Ok(())
5477            }
5478            Err(err) => {
5479                self.core.recovery.mark_dead();
5480                self.dead = true;
5481                Err(err)
5482            }
5483        }
5484    }
5485
5486    /// Convert Asupersync's transport-level signal for a context cancelled
5487    /// while a socket read was pending into the driver's public cancellation
5488    /// error. The [`CancelDrainGuard`] deliberately remains armed on this path:
5489    /// the request is already on the wire, so the next connection owner must
5490    /// break and drain it before reusing the session.
5491    ///
5492    /// A real OS `Interrupted` error is left untouched. Asupersync uses that
5493    /// same `io::ErrorKind` for cancellation-aware TCP reads, but marks its own
5494    /// cancellation with the exact payload `"cancelled"`
5495    /// (`asupersync::net::tcp::stream` poll paths). That marker is set at the
5496    /// instant asupersync observes the cancel, so it is the DETERMINISTIC signal:
5497    /// keying off it (or an already-observable `cx.checkpoint()`) instead of the
5498    /// checkpoint alone closes the interrupt-vs-checkpoint race where the read
5499    /// future resolves before the cancel flag is visible to a *later*
5500    /// `checkpoint()` on this thread — which otherwise mistyped a real
5501    /// cancellation as a raw `Io(Interrupted)`. A genuine OS `EINTR` (a different
5502    /// message, no pending cancel) is still left untouched.
5503    fn in_flight_read_cancellation_error(&mut self, cx: &Cx, err: &Error) -> Option<Error> {
5504        let Error::Io(io_error) = err else {
5505            return None;
5506        };
5507        if io_error.kind() != std::io::ErrorKind::Interrupted
5508            || !(is_asupersync_cancellation(io_error) || cx.checkpoint().is_err())
5509        {
5510            return None;
5511        }
5512
5513        let timeout_ms = cx
5514            .budget()
5515            .remaining_time(time::wall_now())
5516            .map(duration_to_millis_saturating)
5517            .unwrap_or(0);
5518        let disposition = cancel_disposition(cx.cancel_reason());
5519        if disposition == CancelDisposition::Close {
5520            // Shutdown/resource-loss cancellation is not reusable even though
5521            // the guard would otherwise schedule a deferred drain.
5522            self.core.recovery.mark_dead();
5523            self.dead = true;
5524        }
5525        Some(disposition.into_error(timeout_ms))
5526    }
5527
5528    /// Read one TTC response under a `CancelDrainGuard`: if THIS read future is
5529    /// dropped mid-flight (the fetch was cancelled / raced), the guard moves the
5530    /// recovery phase to `BreakSent` so the next operation breaks + drains the
5531    /// stranded call. A normal completion disarms the guard, so the uncancelled
5532    /// path costs nothing beyond an `Arc::clone`.
5533    async fn read_response_cancellable(
5534        &mut self,
5535        cx: &Cx,
5536        classic: bool,
5537        probe: impl Fn(&[u8]) -> bool,
5538    ) -> Result<Vec<u8>> {
5539        // Clone the Arc so the guard owns a handle independent of the `&mut self`
5540        // read borrow (the two touch disjoint state but the borrow checker can't
5541        // prove it across the guard's lifetime).
5542        let recovery = Arc::clone(&self.core.recovery);
5543        let mut guard = CancelDrainGuard::arm(recovery)?;
5544        let response = match self
5545            .core
5546            .read_data_response_probed(cx, classic, probe)
5547            .await
5548        {
5549            Ok(response) => response,
5550            Err(err) => {
5551                if let Some(cancelled) = self.in_flight_read_cancellation_error(cx, &err) {
5552                    return Err(cancelled);
5553                }
5554                return Err(err);
5555            }
5556        };
5557        guard.disarm();
5558        Ok(response)
5559    }
5560
5561    /// Read one END_OF_RESPONSE-delimited pipeline response with the same
5562    /// cancel-on-drop bookkeeping as every ordinary request response. Pipeline
5563    /// writes are followed by multiple response boundaries; a stalled boundary
5564    /// must therefore arm recovery before the inactivity timeout reaches the
5565    /// caller, or the next request could consume a stranded pipeline response.
5566    async fn read_pipeline_response_cancellable(&mut self, cx: &Cx) -> Result<DataResponse> {
5567        let recovery = Arc::clone(&self.core.recovery);
5568        let mut guard = CancelDrainGuard::arm(recovery)?;
5569        let response = match self.core.read_data_response_boundary(cx, true).await {
5570            Ok(response) => response,
5571            Err(err) => {
5572                if let Some(cancelled) = self.in_flight_read_cancellation_error(cx, &err) {
5573                    return Err(cancelled);
5574                }
5575                return Err(err);
5576            }
5577        };
5578        guard.disarm();
5579        Ok(response)
5580    }
5581
5582    /// [`Self::read_response_cancellable`] for the bind/execute path, which reads
5583    /// via [`read_data_response_flushing_out_binds`] (it answers FLUSH_OUT_BINDS
5584    /// requests). Same cancel-on-drop semantics: a dropped execute future arms
5585    /// the next operation's break + drain.
5586    async fn read_flushing_out_binds_cancellable(
5587        &mut self,
5588        cx: &Cx,
5589        classic: bool,
5590        probe: impl Fn(&[u8]) -> bool,
5591    ) -> Result<Vec<u8>> {
5592        let recovery = Arc::clone(&self.core.recovery);
5593        let mut guard = CancelDrainGuard::arm(recovery)?;
5594        let response = match self
5595            .core
5596            .read_data_response_flushing_out_binds_probed(cx, self.sdu, classic, probe)
5597            .await
5598        {
5599            Ok(response) => response,
5600            Err(err) => {
5601                if let Some(cancelled) = self.in_flight_read_cancellation_error(cx, &err) {
5602                    return Err(cancelled);
5603                }
5604                return Err(err);
5605            }
5606        };
5607        guard.disarm();
5608        Ok(response)
5609    }
5610
5611    pub async fn fetch_rows(
5612        &mut self,
5613        cx: &Cx,
5614        cursor_id: u32,
5615        arraysize: u32,
5616        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
5617    ) -> Result<QueryResult> {
5618        self.fetch_rows_with_columns(cx, cursor_id, arraysize, &[], previous_row)
5619            .await
5620    }
5621
5622    pub async fn fetch_rows_with_columns(
5623        &mut self,
5624        cx: &Cx,
5625        cursor_id: u32,
5626        arraysize: u32,
5627        known_columns: &[ColumnMetadata],
5628        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
5629    ) -> Result<QueryResult> {
5630        // Fetch round-trip span (feature-gated, zero-cost when off). Carries the
5631        // cursor id and the requested arraysize; `db.rows_fetched` is filled
5632        // after the response.
5633        let _span = obs_span!(
5634            "oracledb.fetch",
5635            db.cursor_id = cursor_id as u64,
5636            db.arraysize = arraysize as u64,
5637            db.rows_fetched = tracing::field::Empty,
5638        );
5639        observe_cancellation_between_round_trips(cx)?;
5640        // If a prior fetch future was cancelled mid-read, break + drain the
5641        // stranded call before issuing this fetch (Scope-based cancel-on-drop).
5642        self.ensure_clean_before_request().await?;
5643        let columns = self
5644            .cursor_columns
5645            .get(&cursor_id)
5646            .cloned()
5647            .unwrap_or_else(|| known_columns.to_vec());
5648        let lob_prefetch = self.lob_prefetch_cursors.contains(&cursor_id);
5649        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
5650        let payload = if lob_prefetch {
5651            build_define_fetch_payload_with_seq(
5652                cursor_id,
5653                arraysize,
5654                seq_num,
5655                &columns,
5656                self.capabilities.ttc_field_version,
5657            )?
5658        } else {
5659            build_fetch_payload_with_seq(
5660                cursor_id,
5661                arraysize,
5662                seq_num,
5663                self.capabilities.ttc_field_version,
5664            )
5665        };
5666        trace_query_bytes("FETCH payload", &payload);
5667        self.core.send_data_packet(cx, &payload, self.sdu).await?;
5668        // Read under a cancel-on-drop guard: if THIS fetch future is dropped
5669        // mid-read, the next operation will break + drain the stranded call.
5670        // The classic probe is the same parse this site runs below, with its
5671        // result discarded.
5672        let capabilities = self.capabilities;
5673        let limits = self.protocol_limits;
5674        let classic = !self.supports_end_of_response;
5675        let profile = fetch_profile::enabled();
5676        let read_start = profile.then(time::wall_now);
5677        let response = self
5678            .read_response_cancellable(cx, classic, |bytes| {
5679                response_complete(&if lob_prefetch {
5680                    parse_define_fetch_response_with_context_and_limits(
5681                        bytes,
5682                        capabilities,
5683                        &columns,
5684                        previous_row,
5685                        limits,
5686                    )
5687                } else {
5688                    parse_fetch_response_with_context_and_limits(
5689                        bytes,
5690                        capabilities,
5691                        &columns,
5692                        previous_row,
5693                        limits,
5694                    )
5695                })
5696            })
5697            .await?;
5698        if let Some(start) = read_start {
5699            fetch_profile::add_read(time::wall_now().duration_since(start));
5700        }
5701        trace_query_bytes("FETCH response", &response);
5702        let decode_start = profile.then(time::wall_now);
5703        let parsed = if lob_prefetch {
5704            parse_define_fetch_response_with_context_and_limits(
5705                &response,
5706                self.capabilities,
5707                &columns,
5708                previous_row,
5709                self.protocol_limits,
5710            )
5711        } else {
5712            parse_fetch_response_with_context_and_limits(
5713                &response,
5714                self.capabilities,
5715                &columns,
5716                previous_row,
5717                self.protocol_limits,
5718            )
5719        };
5720        if let Some(start) = decode_start {
5721            fetch_profile::add_decode(time::wall_now().duration_since(start));
5722        }
5723        let result = self.note_parse(parsed)?;
5724        obs_record!(_span, db.rows_fetched = result.rows.len() as u64);
5725        self.remember_cursor_columns(&result);
5726        Ok(result)
5727    }
5728
5729    /// Zero-copy companion to [`fetch_rows`](Self::fetch_rows): fetch one batch
5730    /// of rows from an open server cursor and return a
5731    /// [`BorrowedFetchResult`]
5732    /// whose rows borrow the response buffer (no per-cell allocation for the
5733    /// common scalar case). Iterate the rows with
5734    /// [`BorrowedRowBatch::for_each_row_ref`](oracledb_protocol::thin::BorrowedRowBatch::for_each_row_ref).
5735    ///
5736    /// This is additive: the owned [`fetch_rows`](Self::fetch_rows) path is
5737    /// unchanged. Prefer [`for_each_row_ref`](Self::for_each_row_ref) for the
5738    /// common "execute and drain" case; this lower-level method exists for
5739    /// callers that page manually.
5740    pub async fn fetch_rows_ref(
5741        &mut self,
5742        cx: &Cx,
5743        cursor_id: u32,
5744        arraysize: u32,
5745        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
5746    ) -> Result<BorrowedFetchResult> {
5747        observe_cancellation_between_round_trips(cx)?;
5748        self.ensure_clean_before_request().await?;
5749        let columns = self
5750            .cursor_columns
5751            .get(&cursor_id)
5752            .cloned()
5753            .unwrap_or_default();
5754        let lob_prefetch = self.lob_prefetch_cursors.contains(&cursor_id);
5755        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
5756        let payload = if lob_prefetch {
5757            build_define_fetch_payload_with_seq(
5758                cursor_id,
5759                arraysize,
5760                seq_num,
5761                &columns,
5762                self.capabilities.ttc_field_version,
5763            )?
5764        } else {
5765            build_fetch_payload_with_seq(
5766                cursor_id,
5767                arraysize,
5768                seq_num,
5769                self.capabilities.ttc_field_version,
5770            )
5771        };
5772        trace_query_bytes("FETCH payload", &payload);
5773        self.core.send_data_packet(cx, &payload, self.sdu).await?;
5774        // The classic probe runs the same borrowed parsers this site uses
5775        // below; the borrowed result is dropped inside the closure, so no
5776        // borrow of the probe bytes escapes.
5777        let capabilities = self.capabilities;
5778        let limits = self.protocol_limits;
5779        let classic = !self.supports_end_of_response;
5780        let profile = fetch_profile::enabled();
5781        let read_start = profile.then(time::wall_now);
5782        let response = self
5783            .read_response_cancellable(cx, classic, |bytes| {
5784                if lob_prefetch {
5785                    response_complete(&parse_define_fetch_response_borrowed_with_limits(
5786                        bytes,
5787                        capabilities,
5788                        &columns,
5789                        previous_row,
5790                        limits,
5791                    ))
5792                } else {
5793                    response_complete(&parse_query_response_borrowed_with_limits(
5794                        bytes,
5795                        capabilities,
5796                        &columns,
5797                        previous_row,
5798                        limits,
5799                    ))
5800                }
5801            })
5802            .await?;
5803        if let Some(start) = read_start {
5804            fetch_profile::add_read(time::wall_now().duration_since(start));
5805        }
5806        trace_query_bytes("FETCH response", &response);
5807        let decode_start = profile.then(time::wall_now);
5808        let parsed = if lob_prefetch {
5809            parse_define_fetch_response_borrowed_with_limits(
5810                &response,
5811                self.capabilities,
5812                &columns,
5813                previous_row,
5814                self.protocol_limits,
5815            )
5816        } else {
5817            parse_query_response_borrowed_with_limits(
5818                &response,
5819                self.capabilities,
5820                &columns,
5821                previous_row,
5822                self.protocol_limits,
5823            )
5824        };
5825        if let Some(start) = decode_start {
5826            fetch_profile::add_decode(time::wall_now().duration_since(start));
5827        }
5828        let result = self.note_parse(parsed)?;
5829        // Mirror the owned `fetch_rows` path: if the server re-described the
5830        // cursor mid-paging (the type-change refetch path emits DESCRIBE_INFO),
5831        // persist the adjusted column list under this cursor id so subsequent
5832        // pages decode with the new schema. Keyed on the known `cursor_id`
5833        // (the response's own cursor_id is 0 on an ordinary fetch).
5834        if cursor_id != 0 && !result.batch.columns().is_empty() {
5835            self.cursor_columns
5836                .insert(cursor_id, result.batch.columns().to_vec());
5837        }
5838        Ok(result)
5839    }
5840
5841    /// Send a FETCH request for the next page on an open cursor **without**
5842    /// reading its response — the *request* half of the speculative next-page
5843    /// prefetch that overlaps page K+1's wire round trip with page K's decode
5844    /// (bead rust-oracledb-xad / 3oi). Pair it with
5845    /// [`fetch_rows_ref_response`](Self::fetch_rows_ref_response), which reads +
5846    /// decodes the outstanding page.
5847    ///
5848    /// ## Cancellation safety
5849    ///
5850    /// Issuing this request leaves a server response in flight on the wire. So
5851    /// it moves the recovery phase to `InFlight` for the entire window until
5852    /// that response is consumed: if the owning future is dropped while the
5853    /// response is in flight — whether during the prior page's decode (no read
5854    /// yet) or during the response read itself — the next operation breaks +
5855    /// drains the stranded page before issuing its own request (the same
5856    /// machinery that protects a dropped fetch, see `CancelDrainGuard`). A
5857    /// request can only be issued from a clean wire boundary, so it first drains
5858    /// any *previously* stranded call.
5859    pub async fn fetch_rows_request(
5860        &mut self,
5861        cx: &Cx,
5862        cursor_id: u32,
5863        arraysize: u32,
5864    ) -> Result<()> {
5865        observe_cancellation_between_round_trips(cx)?;
5866        // A request must start from a clean boundary: if a prior cancelled op
5867        // left a drain pending, break + drain it first.
5868        self.ensure_clean_before_request().await?;
5869        let columns = self
5870            .cursor_columns
5871            .get(&cursor_id)
5872            .cloned()
5873            .unwrap_or_default();
5874        let lob_prefetch = self.lob_prefetch_cursors.contains(&cursor_id);
5875        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
5876        let payload = if lob_prefetch {
5877            build_define_fetch_payload_with_seq(
5878                cursor_id,
5879                arraysize,
5880                seq_num,
5881                &columns,
5882                self.capabilities.ttc_field_version,
5883            )?
5884        } else {
5885            build_fetch_payload_with_seq(
5886                cursor_id,
5887                arraysize,
5888                seq_num,
5889                self.capabilities.ttc_field_version,
5890            )
5891        };
5892        trace_query_bytes("FETCH payload (prefetch)", &payload);
5893        self.core.recovery.begin_operation()?;
5894        match self.core.send_data_packet(cx, &payload, self.sdu).await {
5895            Ok(()) => Ok(()),
5896            Err(err) => {
5897                self.core.recovery.mark_dead();
5898                self.dead = true;
5899                Err(err)
5900            }
5901        }?;
5902        // A speculative response is now outstanding: the recovery phase remains
5903        // InFlight for the WHOLE window until it is consumed by
5904        // `fetch_rows_ref_response`, so a drop anywhere in {decode prior page,
5905        // read this response} cleans it up before the next op runs.
5906        Ok(())
5907    }
5908
5909    /// Read + decode the response to a FETCH request previously issued by
5910    /// [`fetch_rows_request`](Self::fetch_rows_request) — the *response* half of
5911    /// the speculative next-page prefetch. Returns the same
5912    /// [`BorrowedFetchResult`] as [`fetch_rows_ref`](Self::fetch_rows_ref).
5913    ///
5914    /// Must be called exactly once per `fetch_rows_request`, with the request's
5915    /// `cursor_id` and the `previous_row` seed for duplicate-column decoding
5916    /// (the last row of the prior page — known by now because the prior page is
5917    /// fully decoded). The read runs under a `CancelDrainGuard` (a mid-read
5918    /// drop re-arms the pending drain); a clean read disarms the
5919    /// `fetch_rows_request` arming, leaving no stranded page.
5920    pub async fn fetch_rows_ref_response(
5921        &mut self,
5922        cx: &Cx,
5923        cursor_id: u32,
5924        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
5925    ) -> Result<BorrowedFetchResult> {
5926        observe_cancellation_between_round_trips(cx)?;
5927        // Read under the cancel-on-drop guard. NOTE: do NOT
5928        // `ensure_clean_before_request` here — the InFlight phase is set by our
5929        // own `fetch_rows_request` and marks the response we are about to read
5930        // legitimately, not a stranded call to discard.
5931        let columns = self
5932            .cursor_columns
5933            .get(&cursor_id)
5934            .cloned()
5935            .unwrap_or_default();
5936        let lob_prefetch = self.lob_prefetch_cursors.contains(&cursor_id);
5937        // The classic probe runs the same borrowed parsers this site uses
5938        // below; the borrowed result is dropped inside the closure.
5939        let capabilities = self.capabilities;
5940        let limits = self.protocol_limits;
5941        let classic = !self.supports_end_of_response;
5942        let profile = fetch_profile::enabled();
5943        let read_start = profile.then(time::wall_now);
5944        let response = self
5945            .read_response_cancellable(cx, classic, |bytes| {
5946                if lob_prefetch {
5947                    response_complete(&parse_define_fetch_response_borrowed_with_limits(
5948                        bytes,
5949                        capabilities,
5950                        &columns,
5951                        previous_row,
5952                        limits,
5953                    ))
5954                } else {
5955                    response_complete(&parse_query_response_borrowed_with_limits(
5956                        bytes,
5957                        capabilities,
5958                        &columns,
5959                        previous_row,
5960                        limits,
5961                    ))
5962                }
5963            })
5964            .await?;
5965        if let Some(start) = read_start {
5966            fetch_profile::add_read(time::wall_now().duration_since(start));
5967        }
5968        trace_query_bytes("FETCH response (prefetch)", &response);
5969        let decode_start = profile.then(time::wall_now);
5970        let parsed = if lob_prefetch {
5971            parse_define_fetch_response_borrowed_with_limits(
5972                &response,
5973                self.capabilities,
5974                &columns,
5975                previous_row,
5976                self.protocol_limits,
5977            )
5978        } else {
5979            parse_query_response_borrowed_with_limits(
5980                &response,
5981                self.capabilities,
5982                &columns,
5983                previous_row,
5984                self.protocol_limits,
5985            )
5986        };
5987        if let Some(start) = decode_start {
5988            fetch_profile::add_decode(time::wall_now().duration_since(start));
5989        }
5990        let result = self.note_parse(parsed)?;
5991        if cursor_id != 0 && !result.batch.columns().is_empty() {
5992            self.cursor_columns
5993                .insert(cursor_id, result.batch.columns().to_vec());
5994        }
5995        Ok(result)
5996    }
5997
5998    /// Execute `sql` and drive every fetched row through `callback` as a slice
5999    /// of borrowed [`QueryValueRef`] —
6000    /// the zero-copy fetch fast path. Scalar cells (Text / Number / Raw /
6001    /// Boolean / Interval / DateTime) borrow the fetch buffer directly, so a
6002    /// Rust consumer iterating a wide many-row result pays ~0 allocations per
6003    /// cell, in contrast to the owned [`execute_raw`](Self::execute_raw) +
6004    /// [`fetch_rows`](Self::fetch_rows) path which materializes a `String` /
6005    /// `Vec<u8>` per scalar cell of every row.
6006    ///
6007    /// The `&[Option<QueryValueRef>]` row slice is valid only for the duration
6008    /// of each `callback` call — it borrows the batch buffer and cannot escape.
6009    /// Use [`QueryValueRef::to_owned_value`](oracledb_protocol::thin::QueryValueRef::to_owned_value)
6010    /// to keep a value past the call. Cold cells (LOB / Cursor / Object / Vector
6011    /// / JSON / non-UTF-8 / ROWID) surface as `QueryValueRef::Owned`.
6012    ///
6013    /// Pages through the cursor with the given `arraysize` until the server
6014    /// reports no more rows, releasing the server cursor back to the statement
6015    /// cache when done. The owned fetch path is untouched.
6016    pub async fn for_each_row_ref<F>(
6017        &mut self,
6018        cx: &Cx,
6019        sql: &str,
6020        arraysize: u32,
6021        mut callback: F,
6022    ) -> Result<()>
6023    where
6024        F: FnMut(&[Option<QueryValueRef<'_>>]) -> Result<()>,
6025    {
6026        // Streaming-query span (feature-gated, zero-cost when off). Carries the
6027        // SQL digest and the arraysize (the prefetch fill target); filled after
6028        // the loop with the total rows streamed, the number of paged fetch round
6029        // trips, and the max prefetch look-ahead depth. This path keeps a single
6030        // page in flight, so the look-ahead (queue) depth is 0 or 1 — the
6031        // backpressure signal; rows/sec is the operator's db.rows_streamed over
6032        // the span duration. NEVER row data.
6033        let _stream_span = obs_span!(
6034            "oracledb.stream",
6035            db.statement = %crate::obs::sql_digest(sql),
6036            db.arraysize = arraysize as u64,
6037            db.rows_streamed = tracing::field::Empty,
6038            db.pages_fetched = tracing::field::Empty,
6039            db.prefetch_inflight_max = tracing::field::Empty,
6040        );
6041        #[cfg(feature = "tracing")]
6042        let mut rows_streamed: u64 = 0;
6043        #[cfg(feature = "tracing")]
6044        let mut pages_fetched: u64 = 0;
6045        #[cfg(feature = "tracing")]
6046        let mut prefetch_inflight_max: u64 = 0;
6047
6048        // First round trip: EXECUTE + first fetch batch (owned), to obtain the
6049        // open cursor id and column metadata. The first batch's rows are decoded
6050        // borrowed by re-parsing nothing — instead we capture them from the
6051        // owned result below. To keep the borrowed guarantee for the first batch
6052        // too, we re-fetch borrowed pages from the cursor.
6053        let first = self
6054            .execute_query_with_bind_rows_and_options_core(
6055                cx,
6056                sql,
6057                arraysize,
6058                &[],
6059                ExecuteOptions::default(),
6060            )
6061            .await?;
6062        let cursor_id = first.cursor_id;
6063        let mut cursor = BorrowedStreamCursorGuard::new(self, cursor_id);
6064        if cursor_id != 0 && columns_have_lob_prefetch_fields(&first.columns) {
6065            cursor.connection().lob_prefetch_cursors.insert(cursor_id);
6066        }
6067
6068        // Emit the first (owned) batch's rows as borrowed refs over owned values.
6069        // The first execute round trip already materialized them; surfacing them
6070        // through QueryValueRef::Owned keeps the callback's type uniform without
6071        // a second round trip for batch one.
6072        for row in &first.rows {
6073            let refs: Vec<Option<QueryValueRef<'_>>> = row
6074                .iter()
6075                .map(|cell| cell.as_ref().map(QueryValueRef::Owned))
6076                .collect();
6077            callback(&refs)?;
6078        }
6079        #[cfg(feature = "tracing")]
6080        {
6081            rows_streamed += first.rows.len() as u64;
6082        }
6083
6084        let mut more_rows = first.more_rows;
6085        let mut previous_row: Option<Vec<Option<oracledb_protocol::thin::QueryValue>>> =
6086            first.rows.last().cloned();
6087
6088        // Speculative next-page prefetch (bead xad / 3oi): overlap the wire round
6089        // trip of page K+1 with the CPU decode of page K. The trick is that a
6090        // FETCH *request* needs only the cursor id + arraysize (not page K's
6091        // rows), while `previous_row` — page K's last row, the duplicate-column
6092        // seed — is needed only when *decoding* K+1, by which point K is done.
6093        //
6094        // So the loop keeps one page of look-ahead outstanding on the wire:
6095        //   1. request page K+1   (just the send; arms the prefetch drain guard)
6096        //   2. read+decode page K (callback) — overlaps with K+1 in flight
6097        //   3. read+decode page K+1 next iteration, immediately request K+2, ...
6098        //
6099        // Cancellation: `fetch_rows_request` leaves the recovery phase InFlight
6100        // until the response is consumed, so a drop anywhere in this loop
6101        // (including inside the callback, with a page in flight) leaves the
6102        // stranded page to be broken + drained by the next op on this
6103        // connection. Decode stays on this task, so the borrowed batch buffer
6104        // never crosses a thread/await boundary that outlives it — the
6105        // borrowed-fetch guarantee is preserved and `#![forbid(unsafe_code)]`
6106        // holds.
6107
6108        // Prime the pipeline: request the first paged batch ahead of decoding.
6109        if more_rows && cursor_id != 0 {
6110            cursor
6111                .connection()
6112                .fetch_rows_request(cx, cursor_id, arraysize)
6113                .await?;
6114            #[cfg(feature = "tracing")]
6115            {
6116                // One page is now outstanding on the wire (look-ahead depth 1).
6117                prefetch_inflight_max = 1;
6118            }
6119        }
6120
6121        while more_rows && cursor_id != 0 {
6122            // Read + decode the page whose request is already in flight.
6123            let result = cursor
6124                .connection()
6125                .fetch_rows_ref_response(cx, cursor_id, previous_row.as_deref())
6126                .await?;
6127            let next_more = result.more_rows;
6128
6129            // Speculatively request the NEXT page BEFORE running the callback, so
6130            // its round trip overlaps this page's decode + the callback's work.
6131            // The request needs no data from `result`, so `result`'s buffer stays
6132            // alive and untouched across this send.
6133            if next_more {
6134                cursor
6135                    .connection()
6136                    .fetch_rows_request(cx, cursor_id, arraysize)
6137                    .await?;
6138            }
6139
6140            // Snapshot ONLY the last row of the page as the next page's
6141            // duplicate-column seed; materializing every row to owned (the old
6142            // behaviour) would defeat the zero-copy fast path. `row_count()` is
6143            // the `for_each_row_ref` iteration count (both are `row_starts.len()`),
6144            // so this captures exactly the row the old "overwrite every iteration"
6145            // logic left in `last_owned`. Seed correctness is covered by the
6146            // duplicate-CLOB compression regression in `live_borrowed_fetch`.
6147            let row_count = result.batch.row_count();
6148            #[cfg(feature = "tracing")]
6149            {
6150                pages_fetched += 1;
6151                rows_streamed += row_count as u64;
6152                if next_more {
6153                    prefetch_inflight_max = prefetch_inflight_max.max(1);
6154                }
6155            }
6156            let mut last_owned: Option<Vec<Option<oracledb_protocol::thin::QueryValue>>> = None;
6157            let mut row_idx = 0usize;
6158            result.batch.for_each_row_ref(|row| {
6159                if row_idx + 1 == row_count {
6160                    last_owned = Some(
6161                        row.iter()
6162                            .map(|cell| cell.map(|v| v.to_owned_value()))
6163                            .collect(),
6164                    );
6165                }
6166                row_idx += 1;
6167                callback(row)
6168            })?;
6169            if let Some(last) = last_owned {
6170                previous_row = Some(last);
6171            }
6172            more_rows = next_more;
6173        }
6174
6175        obs_record!(_stream_span, db.rows_streamed = rows_streamed);
6176        obs_record!(_stream_span, db.pages_fetched = pages_fetched);
6177        obs_record!(
6178            _stream_span,
6179            db.prefetch_inflight_max = prefetch_inflight_max
6180        );
6181        cursor.release();
6182        Ok(())
6183    }
6184
6185    pub async fn define_and_fetch_rows_with_columns(
6186        &mut self,
6187        cx: &Cx,
6188        cursor_id: u32,
6189        arraysize: u32,
6190        define_columns: &[ColumnMetadata],
6191        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
6192    ) -> Result<QueryResult> {
6193        observe_cancellation_between_round_trips(cx)?;
6194        self.ensure_clean_before_request().await?;
6195        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6196        let payload = build_define_fetch_payload_with_seq(
6197            cursor_id,
6198            arraysize,
6199            seq_num,
6200            define_columns,
6201            self.capabilities.ttc_field_version,
6202        )?;
6203        trace_query_bytes("DEFINE FETCH payload", &payload);
6204        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6205        let capabilities = self.capabilities;
6206        let limits = self.protocol_limits;
6207        let response = self
6208            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6209                response_complete(&parse_define_fetch_response_with_context_and_limits(
6210                    bytes,
6211                    capabilities,
6212                    define_columns,
6213                    previous_row,
6214                    limits,
6215                ))
6216            })
6217            .await?;
6218        trace_query_bytes("DEFINE FETCH response", &response);
6219        let result = parse_define_fetch_response_with_context_and_limits(
6220            &response,
6221            self.capabilities,
6222            define_columns,
6223            previous_row,
6224            self.protocol_limits,
6225        )
6226        .map_err(Error::from)?;
6227        if columns_have_lob_prefetch_fields(define_columns) {
6228            self.lob_prefetch_cursors.insert(cursor_id);
6229            if result.cursor_id != 0 {
6230                self.lob_prefetch_cursors.insert(result.cursor_id);
6231            }
6232        } else {
6233            self.lob_prefetch_cursors.remove(&cursor_id);
6234            if result.cursor_id != 0 {
6235                self.lob_prefetch_cursors.remove(&result.cursor_id);
6236            }
6237        }
6238        self.cursor_columns
6239            .insert(cursor_id, define_columns.to_vec());
6240        self.remember_cursor_columns(&result);
6241        Ok(result)
6242    }
6243
6244    /// Fetch up to `max_rows` rows from a returned REF CURSOR — a
6245    /// `QueryValue::Cursor` OUT value, or an entry of
6246    /// [`QueryResult::implicit_resultsets`]. A returned cursor is
6247    /// self-describing (its column metadata travels with it as
6248    /// `CursorValue::columns`), so no manual cursor-id handling is required.
6249    /// The child result set's column metadata is on the returned
6250    /// [`QueryResult::columns`]; fetching is bounded by `max_rows`. Like the
6251    /// reference, the nested cursor's id is not independently closed — the
6252    /// server owns its lifecycle as part of the parent statement (reference
6253    /// `_add_cursor_to_close` skips nested cursors). python-oracledb makes you
6254    /// drive the cursor lifecycle by hand; this does it.
6255    pub async fn fetch_cursor(
6256        &mut self,
6257        cx: &Cx,
6258        cursor: &oracledb_protocol::thin::CursorValue,
6259        max_rows: usize,
6260    ) -> Result<QueryResult> {
6261        // Cap the per-fetch array size, but never ask the server for more rows
6262        // than the caller wants: a small `max_rows` must not drag a full batch
6263        // off the wire. (`.max(1)` keeps the degenerate `max_rows == 0` define
6264        // fetch valid; the result is still truncated to 0 below.)
6265        const ARRAYSIZE: usize = 100;
6266        let fetch_size =
6267            |fetched: usize| -> u32 { max_rows.saturating_sub(fetched).clamp(1, ARRAYSIZE) as u32 };
6268        let mut rows: Vec<Vec<Option<oracledb_protocol::thin::QueryValue>>> = Vec::new();
6269        // First fetch is a DEFINE-FETCH: it establishes the column buffers for
6270        // the cursor and returns the first batch.
6271        let mut batch = self
6272            .define_and_fetch_rows_with_columns(
6273                cx,
6274                cursor.cursor_id,
6275                fetch_size(0),
6276                &cursor.columns,
6277                None,
6278            )
6279            .await?;
6280        let mut more = batch.more_rows;
6281        let mut cid = if batch.cursor_id != 0 {
6282            batch.cursor_id
6283        } else {
6284            cursor.cursor_id
6285        };
6286        rows.append(&mut batch.rows);
6287        // Continuation fetches until the cursor drains or the bound is reached.
6288        while more && cid != 0 && rows.len() < max_rows {
6289            observe_cancellation_between_round_trips(cx)?;
6290            let previous_row = rows.last().cloned();
6291            let mut next = self
6292                .fetch_rows_with_columns(
6293                    cx,
6294                    cid,
6295                    fetch_size(rows.len()),
6296                    &cursor.columns,
6297                    previous_row.as_deref(),
6298                )
6299                .await?;
6300            more = next.more_rows;
6301            if next.cursor_id != 0 {
6302                cid = next.cursor_id;
6303            }
6304            rows.append(&mut next.rows);
6305        }
6306        rows.truncate(max_rows);
6307        self.release_cursor(cid);
6308        Ok(QueryResult {
6309            columns: cursor.columns.clone(),
6310            rows,
6311            ..Default::default()
6312        })
6313    }
6314
6315    /// Fetch the metadata for an Oracle ADT type from the data dictionary. For an
6316    /// *object* type, returns its attributes in declaration order (`ALL_TYPE_ATTRS`),
6317    /// each with its Oracle type name and whether it is itself a nested object
6318    /// type. For a *collection* type (VARRAY / nested table), returns its element
6319    /// metadata in `collection_element` (`ALL_COLL_TYPES`). Pair with
6320    /// [`decode_object`] to turn a returned `QueryValue::Object` into structured
6321    /// values. `schema`/`type_name` are matched case-insensitively.
6322    pub async fn describe_object_type(
6323        &mut self,
6324        cx: &Cx,
6325        schema: &str,
6326        type_name: &str,
6327    ) -> Result<ObjectType> {
6328        let schema = schema.to_ascii_uppercase();
6329        let name = type_name.to_ascii_uppercase();
6330        let binds = || {
6331            vec![
6332                oracledb_protocol::thin::BindValue::Text(schema.clone()),
6333                oracledb_protocol::thin::BindValue::Text(name.clone()),
6334            ]
6335        };
6336        let row_text =
6337            |row: &[Option<oracledb_protocol::thin::QueryValue>], i: usize| -> Option<String> {
6338                match row.get(i) {
6339                    Some(Some(v)) => {
6340                        oracledb_protocol::thin::QueryValue::as_text(v).map(str::to_string)
6341                    }
6342                    _ => None,
6343                }
6344            };
6345
6346        // A collection type (VARRAY / nested table) is described by its element
6347        // type, not by attributes — check ALL_COLL_TYPES first.
6348        let coll = self
6349            .execute_query_with_binds_core(
6350                cx,
6351                "select elem_type_name, elem_type_owner from all_coll_types \
6352                 where owner = :1 and type_name = :2",
6353                10,
6354                &binds(),
6355            )
6356            .await?;
6357        if let Some(row) = coll.rows.first() {
6358            return Ok(ObjectType {
6359                schema,
6360                name,
6361                attributes: Vec::new(),
6362                collection_element: Some(CollectionElement {
6363                    type_name: row_text(row, 0).unwrap_or_default(),
6364                    type_owner: row_text(row, 1),
6365                }),
6366            });
6367        }
6368
6369        // High prefetch so every attribute row arrives in one batch. Oracle caps
6370        // a type at 1000 attributes, so this never truncates the metadata.
6371        let res = self
6372            .execute_query_with_binds_core(
6373                cx,
6374                "select attr_name, attr_type_name, attr_type_owner from all_type_attrs \
6375                 where owner = :1 and type_name = :2 order by attr_no",
6376                1000,
6377                &binds(),
6378            )
6379            .await?;
6380        let attributes: Vec<ObjectAttribute> = res
6381            .rows
6382            .iter()
6383            .map(|row| ObjectAttribute {
6384                name: row_text(row, 0).unwrap_or_default(),
6385                type_name: row_text(row, 1).unwrap_or_default(),
6386                type_owner: row_text(row, 2),
6387            })
6388            .collect();
6389        if attributes.is_empty() {
6390            return Err(Error::Protocol(
6391                oracledb_protocol::ProtocolError::UnsupportedFeature(
6392                    "object type not found or has no attributes",
6393                ),
6394            ));
6395        }
6396        Ok(ObjectType {
6397            schema,
6398            name,
6399            attributes,
6400            collection_element: None,
6401        })
6402    }
6403
6404    /// Sends a scroll request on an open scrollable cursor and returns the
6405    /// repositioned buffer (reference `_create_scroll_message` +
6406    /// `_post_process_scroll`). The caller computes the orientation/position;
6407    /// `arraysize` is the prefetch/iteration count used for the fetch.
6408    pub async fn scroll_cursor(
6409        &mut self,
6410        cx: &Cx,
6411        sql: &str,
6412        cursor_id: u32,
6413        arraysize: u32,
6414        fetch_orientation: u32,
6415        fetch_pos: u32,
6416    ) -> Result<QueryResult> {
6417        observe_cancellation_between_round_trips(cx)?;
6418        self.ensure_clean_before_request().await?;
6419        let exec_options = ExecuteOptions::default()
6420            .with_max_string_size(self.capabilities.max_string_size)
6421            .with_cursor_id(cursor_id)
6422            .with_scrollable(true)
6423            .with_scroll_operation(true)
6424            .with_fetch_orientation(fetch_orientation)
6425            .with_fetch_pos(fetch_pos)
6426            .with_cache_statement(false);
6427        let piggyback = self.take_close_cursors_piggyback();
6428        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6429        let mut payload = build_execute_payload_with_bind_rows_and_options_with_seq(
6430            sql,
6431            arraysize,
6432            seq_num,
6433            true,
6434            &[],
6435            exec_options,
6436            self.capabilities.ttc_field_version,
6437        )?;
6438        if let Some(mut piggyback_bytes) = piggyback {
6439            piggyback_bytes.extend_from_slice(&payload);
6440            payload = piggyback_bytes;
6441        }
6442        trace_query_bytes("SCROLL payload", &payload);
6443        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6444        let known_columns = self
6445            .cursor_columns
6446            .get(&cursor_id)
6447            .cloned()
6448            .unwrap_or_default();
6449        // The classic probe is the same parse this site runs below, with its
6450        // result discarded (a scroll is an execute-shaped round trip).
6451        let capabilities = self.capabilities;
6452        let limits = self.protocol_limits;
6453        let response = self
6454            .read_flushing_out_binds_cancellable(cx, !self.supports_end_of_response, |bytes| {
6455                response_complete(&parse_query_response_with_binds_options_columns_and_limits(
6456                    bytes,
6457                    capabilities,
6458                    &[],
6459                    exec_options,
6460                    &known_columns,
6461                    limits,
6462                ))
6463            })
6464            .await?;
6465        trace_query_bytes("SCROLL response", &response);
6466        let parsed = parse_query_response_with_binds_options_columns_and_limits(
6467            &response,
6468            self.capabilities,
6469            &[],
6470            exec_options,
6471            &known_columns,
6472            self.protocol_limits,
6473        );
6474        let result = self.note_parse(parsed)?;
6475        self.remember_cursor_columns(&result);
6476        Ok(result)
6477    }
6478
6479    /// Read up to `amount` units from the LOB identified by `locator`,
6480    /// starting at 1-based `offset`. The `locator` comes from a
6481    /// [`QueryValue::Lob`](protocol::thin::QueryValue::Lob) cell. The returned
6482    /// bytes are the raw LOB content in the column's character-set form; decode
6483    /// CLOB/NCLOB text with
6484    /// [`decode_lob_text`](protocol::thin::decode_lob_text).
6485    pub async fn read_lob(
6486        &mut self,
6487        cx: &Cx,
6488        locator: &[u8],
6489        offset: u64,
6490        amount: u64,
6491    ) -> Result<LobReadResult> {
6492        // LOB read span (feature-gated, zero-cost when off). Carries the offset
6493        // and requested amount — never the locator bytes or the LOB data.
6494        let _span = obs_span!(
6495            "oracledb.lob",
6496            db.operation = "read",
6497            db.lob_offset = offset,
6498            db.lob_amount = amount,
6499        );
6500        observe_cancellation_between_round_trips(cx)?;
6501        self.ensure_clean_before_request().await?;
6502        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6503        let payload = build_lob_read_payload_with_seq(
6504            locator,
6505            offset,
6506            amount,
6507            seq_num,
6508            self.capabilities.ttc_field_version,
6509        )?;
6510        trace_query_bytes("LOB READ payload", &payload);
6511        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6512        let capabilities = self.capabilities;
6513        let limits = self.protocol_limits;
6514        let response = self
6515            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6516                response_complete(&parse_lob_read_response_with_limits(
6517                    bytes,
6518                    capabilities,
6519                    locator,
6520                    limits,
6521                ))
6522            })
6523            .await?;
6524        trace_query_bytes("LOB READ response", &response);
6525        self.note_parse(parse_lob_read_response_with_limits(
6526            &response,
6527            self.capabilities,
6528            locator,
6529            self.protocol_limits,
6530        ))
6531    }
6532
6533    pub async fn read_lob_with_timeout(
6534        &mut self,
6535        cx: &Cx,
6536        locator: &[u8],
6537        offset: u64,
6538        amount: u64,
6539        timeout_ms: Option<u32>,
6540    ) -> Result<LobReadResult> {
6541        self.read_lob_call_timeout(cx, locator, offset, amount, timeout_ms)
6542            .await
6543    }
6544
6545    /// Enqueues a single AQ message (FUNC 121), returning the assigned 16-byte
6546    /// message id. The TTC round-trip mirrors `read_lob`.
6547    pub async fn aq_enq_one(
6548        &mut self,
6549        cx: &Cx,
6550        queue: &AqQueueDesc,
6551        props: &AqMsgProps,
6552        enq_options: &AqEnqOptions,
6553    ) -> Result<Option<Vec<u8>>> {
6554        observe_cancellation_between_round_trips(cx)?;
6555        self.ensure_clean_before_request().await?;
6556        self.protocol_limits.check_frame_bytes(queue.name.len())?;
6557        self.protocol_limits
6558            .check_frame_bytes(queue.payload_toid.len())?;
6559        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6560        let payload = build_aq_enq_payload(
6561            queue,
6562            props,
6563            enq_options,
6564            seq_num,
6565            self.capabilities.ttc_field_version,
6566            self.supports_oson_long_fnames(),
6567        )?;
6568        trace_query_bytes("AQ ENQ payload", &payload);
6569        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6570        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
6571        // rust-oracledb-eyp7.
6572        let capabilities = self.capabilities;
6573        let limits = self.protocol_limits;
6574        let response = self
6575            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6576                response_complete(&parse_aq_enq_response_with_limits(
6577                    bytes,
6578                    capabilities,
6579                    limits,
6580                ))
6581            })
6582            .await?;
6583        trace_query_bytes("AQ ENQ response", &response);
6584        self.note_parse(parse_aq_enq_response_with_limits(
6585            &response,
6586            self.capabilities,
6587            self.protocol_limits,
6588        ))
6589    }
6590
6591    /// Dequeues a single AQ message (FUNC 122). Returns `None` when the queue is
6592    /// empty (ORA-25228 cleared server-side).
6593    pub async fn aq_deq_one(
6594        &mut self,
6595        cx: &Cx,
6596        queue: &AqQueueDesc,
6597        deq_options: &AqDeqOptions,
6598    ) -> Result<AqDeqResult> {
6599        observe_cancellation_between_round_trips(cx)?;
6600        self.ensure_clean_before_request().await?;
6601        self.protocol_limits.check_frame_bytes(queue.name.len())?;
6602        self.protocol_limits
6603            .check_frame_bytes(queue.payload_toid.len())?;
6604        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6605        let payload = build_aq_deq_payload(
6606            queue,
6607            deq_options,
6608            seq_num,
6609            self.capabilities.ttc_field_version,
6610        )?;
6611        trace_query_bytes("AQ DEQ payload", &payload);
6612        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6613        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
6614        // rust-oracledb-eyp7.
6615        let capabilities = self.capabilities;
6616        let limits = self.protocol_limits;
6617        let response = self
6618            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6619                response_complete(&parse_aq_deq_response_with_limits(
6620                    bytes,
6621                    capabilities,
6622                    &queue.kind,
6623                    limits,
6624                ))
6625            })
6626            .await?;
6627        trace_query_bytes("AQ DEQ response", &response);
6628        self.note_parse(parse_aq_deq_response_with_limits(
6629            &response,
6630            self.capabilities,
6631            &queue.kind,
6632            self.protocol_limits,
6633        ))
6634    }
6635
6636    /// Enqueues many AQ messages in one array round-trip (FUNC 145, op=ENQ),
6637    /// returning the assigned msgid per input message in order.
6638    pub async fn aq_enq_many(
6639        &mut self,
6640        cx: &Cx,
6641        queue: &AqQueueDesc,
6642        props_list: &[AqMsgProps],
6643        enq_options: &AqEnqOptions,
6644    ) -> Result<Vec<Vec<u8>>> {
6645        observe_cancellation_between_round_trips(cx)?;
6646        self.ensure_clean_before_request().await?;
6647        self.protocol_limits.check_batch_rows(props_list.len())?;
6648        self.protocol_limits.check_frame_bytes(queue.name.len())?;
6649        self.protocol_limits
6650            .check_frame_bytes(queue.payload_toid.len())?;
6651        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6652        let payload = build_aq_array_enq_payload(
6653            queue,
6654            props_list,
6655            enq_options,
6656            seq_num,
6657            self.capabilities.ttc_field_version,
6658            self.supports_oson_long_fnames(),
6659        )?;
6660        trace_query_bytes("AQ ARRAY ENQ payload", &payload);
6661        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6662        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
6663        // rust-oracledb-eyp7.
6664        let capabilities = self.capabilities;
6665        let limits = self.protocol_limits;
6666        let response = self
6667            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6668                response_complete(&parse_aq_array_response_with_limits(
6669                    bytes,
6670                    capabilities,
6671                    TNS_AQ_ARRAY_ENQ,
6672                    props_list.len() as u32,
6673                    &queue.kind,
6674                    limits,
6675                ))
6676            })
6677            .await?;
6678        trace_query_bytes("AQ ARRAY ENQ response", &response);
6679        let result: AqArrayResult = self.note_parse(parse_aq_array_response_with_limits(
6680            &response,
6681            self.capabilities,
6682            TNS_AQ_ARRAY_ENQ,
6683            props_list.len() as u32,
6684            &queue.kind,
6685            self.protocol_limits,
6686        ))?;
6687        Ok(result.enq_msgids)
6688    }
6689
6690    /// Dequeues up to `max_num_messages` AQ messages in one array round-trip
6691    /// (FUNC 145, op=DEQ). Returns the dequeued messages (empty when none).
6692    pub async fn aq_deq_many(
6693        &mut self,
6694        cx: &Cx,
6695        queue: &AqQueueDesc,
6696        deq_options: &AqDeqOptions,
6697        max_num_messages: u32,
6698    ) -> Result<Vec<oracledb_protocol::thin::aq::AqDeqMessage>> {
6699        observe_cancellation_between_round_trips(cx)?;
6700        self.ensure_clean_before_request().await?;
6701        self.protocol_limits
6702            .check_batch_rows(max_num_messages as usize)?;
6703        self.protocol_limits.check_frame_bytes(queue.name.len())?;
6704        self.protocol_limits
6705            .check_frame_bytes(queue.payload_toid.len())?;
6706        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6707        let payload = build_aq_array_deq_payload(
6708            queue,
6709            deq_options,
6710            max_num_messages,
6711            seq_num,
6712            self.capabilities.ttc_field_version,
6713        )?;
6714        trace_query_bytes("AQ ARRAY DEQ payload", &payload);
6715        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6716        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
6717        // rust-oracledb-eyp7.
6718        let capabilities = self.capabilities;
6719        let limits = self.protocol_limits;
6720        let response = self
6721            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6722                response_complete(&parse_aq_array_response_with_limits(
6723                    bytes,
6724                    capabilities,
6725                    TNS_AQ_ARRAY_DEQ,
6726                    max_num_messages,
6727                    &queue.kind,
6728                    limits,
6729                ))
6730            })
6731            .await?;
6732        trace_query_bytes("AQ ARRAY DEQ response", &response);
6733        let result: AqArrayResult = self.note_parse(parse_aq_array_response_with_limits(
6734            &response,
6735            self.capabilities,
6736            TNS_AQ_ARRAY_DEQ,
6737            max_num_messages,
6738            &queue.kind,
6739            self.protocol_limits,
6740        ))?;
6741        Ok(result.deq_messages)
6742    }
6743
6744    pub async fn create_temp_lob(
6745        &mut self,
6746        cx: &Cx,
6747        ora_type_num: u8,
6748        csfrm: u8,
6749    ) -> Result<LobReadResult> {
6750        observe_cancellation_between_round_trips(cx)?;
6751        self.ensure_clean_before_request().await?;
6752        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6753        let payload = build_lob_create_temp_payload_with_seq(
6754            ora_type_num,
6755            csfrm,
6756            seq_num,
6757            self.capabilities.ttc_field_version,
6758        )?;
6759        trace_query_bytes("LOB CREATE TEMP payload", &payload);
6760        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6761        let capabilities = self.capabilities;
6762        let limits = self.protocol_limits;
6763        let response = self
6764            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6765                response_complete(&parse_lob_create_temp_response_with_limits(
6766                    bytes,
6767                    capabilities,
6768                    limits,
6769                ))
6770            })
6771            .await?;
6772        trace_query_bytes("LOB CREATE TEMP response", &response);
6773        self.note_parse(parse_lob_create_temp_response_with_limits(
6774            &response,
6775            self.capabilities,
6776            self.protocol_limits,
6777        ))
6778    }
6779
6780    pub async fn write_lob(
6781        &mut self,
6782        cx: &Cx,
6783        locator: &[u8],
6784        offset: u64,
6785        data: &[u8],
6786    ) -> Result<LobReadResult> {
6787        // LOB write span (feature-gated, zero-cost when off). Carries the offset
6788        // and the byte count written — never the locator bytes or the LOB data.
6789        let _span = obs_span!(
6790            "oracledb.lob",
6791            db.operation = "write",
6792            db.lob_offset = offset,
6793            db.lob_bytes = data.len() as u64,
6794        );
6795        observe_cancellation_between_round_trips(cx)?;
6796        self.ensure_clean_before_request().await?;
6797        self.protocol_limits.check_frame_bytes(locator.len())?;
6798        self.protocol_limits.check_frame_bytes(data.len())?;
6799        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6800        let payload = build_lob_write_payload_with_seq(
6801            locator,
6802            offset,
6803            data,
6804            seq_num,
6805            self.capabilities.ttc_field_version,
6806        )?;
6807        trace_query_bytes("LOB WRITE payload", &payload);
6808        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6809        let capabilities = self.capabilities;
6810        let limits = self.protocol_limits;
6811        let response = self
6812            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6813                response_complete(&parse_lob_write_response_with_limits(
6814                    bytes,
6815                    capabilities,
6816                    locator,
6817                    limits,
6818                ))
6819            })
6820            .await?;
6821        trace_query_bytes("LOB WRITE response", &response);
6822        self.note_parse(parse_lob_write_response_with_limits(
6823            &response,
6824            self.capabilities,
6825            locator,
6826            self.protocol_limits,
6827        ))
6828    }
6829
6830    pub async fn write_lob_with_timeout(
6831        &mut self,
6832        cx: &Cx,
6833        locator: &[u8],
6834        offset: u64,
6835        data: &[u8],
6836        timeout_ms: Option<u32>,
6837    ) -> Result<LobReadResult> {
6838        self.write_lob_call_timeout(cx, locator, offset, data, timeout_ms)
6839            .await
6840    }
6841
6842    pub async fn trim_lob(
6843        &mut self,
6844        cx: &Cx,
6845        locator: &[u8],
6846        new_size: u64,
6847    ) -> Result<LobReadResult> {
6848        observe_cancellation_between_round_trips(cx)?;
6849        self.ensure_clean_before_request().await?;
6850        self.protocol_limits.check_frame_bytes(locator.len())?;
6851        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6852        let payload = build_lob_trim_payload_with_seq(
6853            locator,
6854            new_size,
6855            seq_num,
6856            self.capabilities.ttc_field_version,
6857        )?;
6858        trace_query_bytes("LOB TRIM payload", &payload);
6859        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6860        let capabilities = self.capabilities;
6861        let limits = self.protocol_limits;
6862        let response = self
6863            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6864                response_complete(&parse_lob_trim_response_with_limits(
6865                    bytes,
6866                    capabilities,
6867                    locator,
6868                    limits,
6869                ))
6870            })
6871            .await?;
6872        trace_query_bytes("LOB TRIM response", &response);
6873        self.note_parse(parse_lob_trim_response_with_limits(
6874            &response,
6875            self.capabilities,
6876            locator,
6877            self.protocol_limits,
6878        ))
6879    }
6880
6881    pub async fn trim_lob_with_timeout(
6882        &mut self,
6883        cx: &Cx,
6884        locator: &[u8],
6885        new_size: u64,
6886        timeout_ms: Option<u32>,
6887    ) -> Result<LobReadResult> {
6888        self.trim_lob_call_timeout(cx, locator, new_size, timeout_ms)
6889            .await
6890    }
6891
6892    pub async fn free_temp_lobs(&mut self, cx: &Cx, locators: &[Vec<u8>]) -> Result<()> {
6893        observe_cancellation_between_round_trips(cx)?;
6894        if locators.is_empty() {
6895            return Ok(());
6896        }
6897        self.ensure_clean_before_request().await?;
6898        self.protocol_limits.check_lob_chunks(locators.len())?;
6899        let returned_parameter_len = locators.iter().try_fold(0usize, |total, locator| {
6900            self.protocol_limits.check_frame_bytes(locator.len())?;
6901            total.checked_add(locator.len()).ok_or(
6902                oracledb_protocol::ProtocolError::ResourceLimit {
6903                    limit: "frame_bytes",
6904                    observed: usize::MAX,
6905                    maximum: self.protocol_limits.max_frame_bytes,
6906                },
6907            )
6908        })?;
6909        self.protocol_limits
6910            .check_frame_bytes(returned_parameter_len)?;
6911        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
6912        let payload = build_lob_free_temp_payload_with_seq(
6913            locators,
6914            seq_num,
6915            self.capabilities.ttc_field_version,
6916        )?;
6917        trace_query_bytes("LOB FREE TEMP payload", &payload);
6918        self.core.send_data_packet(cx, &payload, self.sdu).await?;
6919        let capabilities = self.capabilities;
6920        let limits = self.protocol_limits;
6921        let response = self
6922            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
6923                response_complete(&parse_lob_free_temp_response_with_limits(
6924                    bytes,
6925                    capabilities,
6926                    returned_parameter_len,
6927                    limits,
6928                ))
6929            })
6930            .await?;
6931        trace_query_bytes("LOB FREE TEMP response", &response);
6932        self.note_parse(parse_lob_free_temp_response_with_limits(
6933            &response,
6934            self.capabilities,
6935            returned_parameter_len,
6936            self.protocol_limits,
6937        ))
6938    }
6939
6940    pub async fn free_temp_lobs_with_timeout(
6941        &mut self,
6942        cx: &Cx,
6943        locators: &[Vec<u8>],
6944        timeout_ms: Option<u32>,
6945    ) -> Result<()> {
6946        self.free_temp_lobs_call_timeout(cx, locators, timeout_ms)
6947            .await
6948    }
6949
6950    #[allow(dead_code)]
6951    async fn execute_query_call_timeout(
6952        &mut self,
6953        cx: &Cx,
6954        sql: &str,
6955        prefetch_rows: u32,
6956        timeout_ms: Option<u32>,
6957    ) -> Result<QueryResult> {
6958        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
6959            return self
6960                .execute_query_with_bind_rows_and_options_core(
6961                    cx,
6962                    sql,
6963                    prefetch_rows,
6964                    &[],
6965                    ExecuteOptions::default(),
6966                )
6967                .await;
6968        };
6969        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
6970        match deadline
6971            .run(self.execute_query_with_bind_rows_and_options_core(
6972                cx,
6973                sql,
6974                prefetch_rows,
6975                &[],
6976                ExecuteOptions::default(),
6977            ))
6978            .await
6979        {
6980            Ok(result) => result,
6981            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
6982            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
6983        }
6984    }
6985
6986    async fn execute_query_with_binds_call_timeout(
6987        &mut self,
6988        cx: &Cx,
6989        sql: &str,
6990        prefetch_rows: u32,
6991        binds: &[BindValue],
6992        timeout_ms: Option<u32>,
6993    ) -> Result<QueryResult> {
6994        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
6995            return self
6996                .execute_query_with_binds_core(cx, sql, prefetch_rows, binds)
6997                .await;
6998        };
6999        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7000        match deadline
7001            .run(self.execute_query_with_binds_core(cx, sql, prefetch_rows, binds))
7002            .await
7003        {
7004            Ok(result) => result,
7005            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7006            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7007        }
7008    }
7009
7010    #[allow(dead_code)]
7011    async fn execute_query_with_bind_rows_call_timeout(
7012        &mut self,
7013        cx: &Cx,
7014        sql: &str,
7015        prefetch_rows: u32,
7016        bind_rows: &[Vec<BindValue>],
7017        timeout_ms: Option<u32>,
7018    ) -> Result<QueryResult> {
7019        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
7020            return self
7021                .execute_query_with_bind_rows_and_options_core(
7022                    cx,
7023                    sql,
7024                    prefetch_rows,
7025                    bind_rows,
7026                    ExecuteOptions::default(),
7027                )
7028                .await;
7029        };
7030        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7031        match deadline
7032            .run(self.execute_query_with_bind_rows_and_options_core(
7033                cx,
7034                sql,
7035                prefetch_rows,
7036                bind_rows,
7037                ExecuteOptions::default(),
7038            ))
7039            .await
7040        {
7041            Ok(result) => result,
7042            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7043            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7044        }
7045    }
7046
7047    async fn read_lob_call_timeout(
7048        &mut self,
7049        cx: &Cx,
7050        locator: &[u8],
7051        offset: u64,
7052        amount: u64,
7053        timeout_ms: Option<u32>,
7054    ) -> Result<LobReadResult> {
7055        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
7056            return self.read_lob(cx, locator, offset, amount).await;
7057        };
7058        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7059        match deadline
7060            .run(self.read_lob(cx, locator, offset, amount))
7061            .await
7062        {
7063            Ok(result) => result,
7064            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7065            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7066        }
7067    }
7068
7069    async fn write_lob_call_timeout(
7070        &mut self,
7071        cx: &Cx,
7072        locator: &[u8],
7073        offset: u64,
7074        data: &[u8],
7075        timeout_ms: Option<u32>,
7076    ) -> Result<LobReadResult> {
7077        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
7078            return self.write_lob(cx, locator, offset, data).await;
7079        };
7080        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7081        match deadline
7082            .run(self.write_lob(cx, locator, offset, data))
7083            .await
7084        {
7085            Ok(result) => result,
7086            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7087            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7088        }
7089    }
7090
7091    async fn trim_lob_call_timeout(
7092        &mut self,
7093        cx: &Cx,
7094        locator: &[u8],
7095        new_size: u64,
7096        timeout_ms: Option<u32>,
7097    ) -> Result<LobReadResult> {
7098        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
7099            return self.trim_lob(cx, locator, new_size).await;
7100        };
7101        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7102        match deadline.run(self.trim_lob(cx, locator, new_size)).await {
7103            Ok(result) => result,
7104            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7105            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7106        }
7107    }
7108
7109    async fn free_temp_lobs_call_timeout(
7110        &mut self,
7111        cx: &Cx,
7112        locators: &[Vec<u8>],
7113        timeout_ms: Option<u32>,
7114    ) -> Result<()> {
7115        let Some(timeout_ms) = timeout_ms.filter(|value| *value > 0) else {
7116            return self.free_temp_lobs(cx, locators).await;
7117        };
7118        let deadline = QueryDeadline::from_timeout(Duration::from_millis(u64::from(timeout_ms)));
7119        match deadline.run(self.free_temp_lobs(cx, locators)).await {
7120            Ok(result) => result,
7121            Err(DeadlineExpiry::BeforeStart) => self.reject_before_operation_start(cx, timeout_ms),
7122            Err(DeadlineExpiry::InFlight) => self.recover_from_call_timeout(cx, timeout_ms).await,
7123        }
7124    }
7125
7126    /// Sends a direct path prepare (TTC function 128) for the given table and
7127    /// returns the server column metadata plus the direct path cursor id.
7128    pub async fn direct_path_prepare(
7129        &mut self,
7130        cx: &Cx,
7131        schema_name: &str,
7132        table_name: &str,
7133        column_names: &[String],
7134    ) -> Result<oracledb_protocol::dpl::DirectPathPrepareResult> {
7135        observe_cancellation_between_round_trips(cx)?;
7136        self.ensure_clean_before_request().await?;
7137        self.protocol_limits.check_columns(column_names.len())?;
7138        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7139        let payload = oracledb_protocol::dpl::build_direct_path_prepare_payload_with_version(
7140            schema_name,
7141            table_name,
7142            column_names,
7143            seq_num,
7144            self.capabilities.ttc_field_version,
7145        )?;
7146        trace_query_bytes("DIRECT PATH PREPARE payload", &payload);
7147        self.core.send_data_packet(cx, &payload, self.sdu).await?;
7148        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
7149        // rust-oracledb-eyp7.
7150        let capabilities = self.capabilities;
7151        let limits = self.protocol_limits;
7152        let response = self
7153            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
7154                response_complete(
7155                    &oracledb_protocol::dpl::parse_direct_path_prepare_response_with_limits(
7156                        bytes,
7157                        capabilities,
7158                        limits,
7159                    ),
7160                )
7161            })
7162            .await?;
7163        trace_query_bytes("DIRECT PATH PREPARE response", &response);
7164        oracledb_protocol::dpl::parse_direct_path_prepare_response_with_limits(
7165            &response,
7166            self.capabilities,
7167            self.protocol_limits,
7168        )
7169        .map_err(Error::from)
7170    }
7171
7172    /// Sends one direct path load stream message (TTC function 129).
7173    pub async fn direct_path_load_stream(
7174        &mut self,
7175        cx: &Cx,
7176        cursor_id: u16,
7177        stream: &oracledb_protocol::dpl::DirectPathStream,
7178    ) -> Result<()> {
7179        observe_cancellation_between_round_trips(cx)?;
7180        self.ensure_clean_before_request().await?;
7181        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7182        let payload = oracledb_protocol::dpl::build_direct_path_load_stream_payload_with_version(
7183            cursor_id,
7184            stream,
7185            seq_num,
7186            self.capabilities.ttc_field_version,
7187        )?;
7188        trace_query_bytes("DIRECT PATH LOAD STREAM payload", &payload);
7189        self.core.send_data_packet(cx, &payload, self.sdu).await?;
7190        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
7191        // rust-oracledb-eyp7.
7192        let capabilities = self.capabilities;
7193        let limits = self.protocol_limits;
7194        let response = self
7195            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
7196                response_complete(
7197                    &oracledb_protocol::dpl::parse_direct_path_simple_response_with_limits(
7198                        bytes,
7199                        capabilities,
7200                        limits,
7201                    ),
7202                )
7203            })
7204            .await?;
7205        trace_query_bytes("DIRECT PATH LOAD STREAM response", &response);
7206        oracledb_protocol::dpl::parse_direct_path_simple_response_with_limits(
7207            &response,
7208            self.capabilities,
7209            self.protocol_limits,
7210        )
7211        .map_err(Error::from)
7212    }
7213
7214    /// Sends a direct path op message (TTC function 130).
7215    /// [`oracledb_protocol::dpl::TNS_DP_OP_FINISH`] commits the load
7216    /// server-side; [`oracledb_protocol::dpl::TNS_DP_OP_ABORT`] discards it.
7217    pub async fn direct_path_op(&mut self, cx: &Cx, cursor_id: u16, op_code: u32) -> Result<()> {
7218        observe_cancellation_between_round_trips(cx)?;
7219        self.ensure_clean_before_request().await?;
7220        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7221        let payload = oracledb_protocol::dpl::build_direct_path_op_payload_with_version(
7222            cursor_id,
7223            op_code,
7224            seq_num,
7225            self.capabilities.ttc_field_version,
7226        );
7227        trace_query_bytes("DIRECT PATH OP payload", &payload);
7228        self.core.send_data_packet(cx, &payload, self.sdu).await?;
7229        // Classic-aware read (pre-23ai has no END_OF_RESPONSE framing); bead
7230        // rust-oracledb-eyp7.
7231        let capabilities = self.capabilities;
7232        let limits = self.protocol_limits;
7233        let response = self
7234            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
7235                response_complete(
7236                    &oracledb_protocol::dpl::parse_direct_path_simple_response_with_limits(
7237                        bytes,
7238                        capabilities,
7239                        limits,
7240                    ),
7241                )
7242            })
7243            .await?;
7244        trace_query_bytes("DIRECT PATH OP response", &response);
7245        oracledb_protocol::dpl::parse_direct_path_simple_response_with_limits(
7246            &response,
7247            self.capabilities,
7248            self.protocol_limits,
7249        )
7250        .map_err(Error::from)
7251    }
7252
7253    /// Loads `rows` into `schema_name.table_name` via the direct path load
7254    /// interface, mirroring the reference driver loop
7255    /// (impl/thin/connection.pyx `direct_path_load`): prepare, stream batches
7256    /// of `batch_size` rows, then FINISH (which commits) or ABORT on error.
7257    /// The op message is always sent, even when streaming fails, so the
7258    /// session is never left wedged.
7259    pub async fn direct_path_load(
7260        &mut self,
7261        cx: &Cx,
7262        schema_name: &str,
7263        table_name: &str,
7264        column_names: &[String],
7265        rows: &[Vec<oracledb_protocol::dpl::DirectPathColumnValue>],
7266        batch_size: u32,
7267    ) -> Result<()> {
7268        let prepare = self
7269            .direct_path_prepare(cx, schema_name, table_name, column_names)
7270            .await?;
7271        let load_result = self
7272            .direct_path_load_batches(cx, &prepare, rows, batch_size)
7273            .await;
7274        let op_code = if load_result.is_ok() {
7275            oracledb_protocol::dpl::TNS_DP_OP_FINISH
7276        } else {
7277            oracledb_protocol::dpl::TNS_DP_OP_ABORT
7278        };
7279        let op_result = self.direct_path_op(cx, prepare.cursor_id, op_code).await;
7280        load_result?;
7281        op_result
7282    }
7283
7284    /// Loads pre-converted rows against an already-prepared direct path cursor,
7285    /// then sends the FINISH (or ABORT on failure) op. Lets a caller convert its
7286    /// data using the prepared `column_metadata` without a second PREPARE round
7287    /// trip (so the reference round-trip count holds).
7288    pub async fn direct_path_load_prepared(
7289        &mut self,
7290        cx: &Cx,
7291        prepare: &oracledb_protocol::dpl::DirectPathPrepareResult,
7292        rows: &[Vec<oracledb_protocol::dpl::DirectPathColumnValue>],
7293        batch_size: u32,
7294    ) -> Result<()> {
7295        let load_result = self
7296            .direct_path_load_batches(cx, prepare, rows, batch_size)
7297            .await;
7298        let op_code = if load_result.is_ok() {
7299            oracledb_protocol::dpl::TNS_DP_OP_FINISH
7300        } else {
7301            oracledb_protocol::dpl::TNS_DP_OP_ABORT
7302        };
7303        let op_result = self.direct_path_op(cx, prepare.cursor_id, op_code).await;
7304        load_result?;
7305        op_result
7306    }
7307
7308    async fn direct_path_load_batches(
7309        &mut self,
7310        cx: &Cx,
7311        prepare: &oracledb_protocol::dpl::DirectPathPrepareResult,
7312        rows: &[Vec<oracledb_protocol::dpl::DirectPathColumnValue>],
7313        batch_size: u32,
7314    ) -> Result<()> {
7315        // Verify all row widths match the column metadata before sending
7316        // anything (reference `_verify_metadata` rejects a width mismatch before
7317        // the first stream message). `batch_size` is a chunking *upper bound*,
7318        // not a row count: `BatchLoadState` clamps it to the data length per
7319        // batch (`calculate_num_rows_in_batch`), and the reference imposes no
7320        // cap on `batch_size` (its default is the `2**32 - 1` "all rows"
7321        // sentinel; oversized data is piece-streamed). So it must NOT be
7322        // limit-checked here — doing so spuriously raised "protocol resource
7323        // limit exceeded" for the default sentinel. The genuine per-execute row
7324        // caps remain on the array-DML / object paths, which pass real counts.
7325        for row in rows {
7326            if row.len() != prepare.column_metadata.len() {
7327                return Err(oracledb_protocol::ProtocolError::TtcDecode(
7328                    "direct path row width does not match column metadata",
7329                )
7330                .into());
7331            }
7332        }
7333        let mut state =
7334            oracledb_protocol::dpl::BatchLoadState::for_rows(rows.len() as u64, batch_size)?;
7335        // 1-based running row counter across batches for error messages
7336        let mut row_num: u64 = 1;
7337        while !state.is_done() {
7338            observe_cancellation_between_round_trips(cx)?;
7339            let start = usize::try_from(state.offset()).map_err(|_| {
7340                oracledb_protocol::ProtocolError::TtcDecode("direct path offset overflow")
7341            })?;
7342            let end = start + state.num_rows() as usize;
7343            let stream = oracledb_protocol::dpl::encode_direct_path_rows(
7344                &prepare.column_metadata,
7345                &rows[start..end],
7346                row_num,
7347            )?;
7348            row_num += (end - start) as u64;
7349            self.direct_path_load_stream(cx, prepare.cursor_id, &stream)
7350                .await?;
7351            state.next_batch();
7352        }
7353        Ok(())
7354    }
7355
7356    /// On a call timeout, send a BREAK and drain the server's in-flight
7357    /// response so the wire stream is left clean and the connection stays
7358    /// reusable — the parity-faithful recovery python-oracledb performs before
7359    /// raising `DPY-4024` (`_break_external` + `_receive_packet`/`_reset`,
7360    /// protocol.pyx:449-451). Delegates to [`break_and_drain_wire`].
7361    ///
7362    /// `Ok(())` means the drain succeeded and the connection is usable; the
7363    /// caller then returns [`Error::CallTimeout`]. If the drain fails (a second
7364    /// timeout or a wire error), the connection is marked [`Self::dead`] and the
7365    /// returned [`Error::ConnectionClosed`] is propagated instead — mirroring
7366    /// the reference's disconnect-on-second-timeout (protocol.pyx:454-458).
7367    async fn break_and_drain(&mut self) -> Result<()> {
7368        self.core.recovery.begin_drain_after_break()?;
7369        match self.core.break_and_drain_wire(BREAK_DRAIN_RECOVERY_TIMEOUT) {
7370            Ok(()) => {
7371                self.core.recovery.finish_drain_ready();
7372                Ok(())
7373            }
7374            Err(err) => {
7375                // Recovery failed: the stream is poisoned, the connection is
7376                // dead. Pools must discard it (see `is_dead` / `is_connection_lost`).
7377                self.core.recovery.mark_dead();
7378                self.dead = true;
7379                Err(err)
7380            }
7381        }
7382    }
7383
7384    /// Reject an operation whose deadline elapsed before its future was ever
7385    /// polled. No request bytes can exist, so sending BREAK here would corrupt
7386    /// an idle session; structured context cancellation still determines the
7387    /// public error and whether the connection remains reusable.
7388    pub(crate) fn reject_before_operation_start<T>(
7389        &mut self,
7390        cx: &Cx,
7391        timeout_ms: u32,
7392    ) -> Result<T> {
7393        let disposition = cx
7394            .cancel_reason()
7395            .map(|reason| CancelDisposition::from_kind(reason.kind))
7396            .unwrap_or(CancelDisposition::Timeout);
7397        if disposition == CancelDisposition::Close {
7398            self.core.recovery.mark_dead();
7399            self.dead = true;
7400        }
7401        Err(disposition.into_error(timeout_ms))
7402    }
7403
7404    /// Common tail for every `*_call_timeout` arm: the in-flight operation hit
7405    /// its deadline (the user's `call_timeout`) or the caller's `Cx` was
7406    /// cancelled, so break + drain the wire and then surface the right error.
7407    ///
7408    /// The drain is unconditional — whatever the reason, the cancelled call's
7409    /// in-flight bytes must be cleared off the socket before the connection can
7410    /// be reused or discarded cleanly. After a clean drain we branch on the
7411    /// asupersync [`CancelKind`] (via [`CancelDisposition`]) to flatten to the
7412    /// right public error:
7413    ///
7414    /// * **No `Cx` cancel recorded** (a pure `call_timeout` deadline): the
7415    ///   classic [`Error::CallTimeout`] (`DPY-4024`) — the session survives and
7416    ///   the error is connection-reusable + retryable.
7417    /// * **Timeout/deadline/quota cancel**: same — [`Error::CallTimeout`].
7418    /// * **Shutdown / resource-loss cancel** ([`CancelDisposition::Close`]):
7419    ///   even though the drain succeeded, the runtime is going away, so the
7420    ///   connection is marked **dead** and [`Error::ConnectionClosed`] is
7421    ///   surfaced — the caller must discard it.
7422    /// * **Explicit / topological cancel** ([`CancelDisposition::Cancel`]): the
7423    ///   distinct [`Error::Cancelled`] (`ORA-01013`), connection-reusable.
7424    ///
7425    /// On a **failed** drain the connection is already dead and
7426    /// [`Error::ConnectionClosed`] (`DPY-4011`) is propagated regardless of the
7427    /// cancel kind. Always returns `Err`, so it composes as the `Err(_)` branch
7428    /// of the timeout `match`.
7429    pub(crate) async fn recover_from_call_timeout<T>(
7430        &mut self,
7431        cx: &Cx,
7432        timeout_ms: u32,
7433    ) -> Result<T> {
7434        match self.break_and_drain().await {
7435            Ok(()) => {
7436                // This arm is reached because a deadline elapsed. If the `Cx`
7437                // also carries a structured cancel, its kind drives the
7438                // disposition; otherwise (no recorded cancel) it is a pure
7439                // `call_timeout` deadline, which is the `Timeout` disposition —
7440                // NOT the generic `Cancel` fallback used at the between-round-
7441                // trip checkpoint boundary.
7442                let disposition = cx
7443                    .cancel_reason()
7444                    .map(|reason| CancelDisposition::from_kind(reason.kind))
7445                    .unwrap_or(CancelDisposition::Timeout);
7446                if disposition == CancelDisposition::Close {
7447                    // Drain left the wire clean, but a runtime shutdown means the
7448                    // connection must not be handed back to the pool.
7449                    self.core.recovery.mark_dead();
7450                    self.dead = true;
7451                }
7452                Err(disposition.into_error(timeout_ms))
7453            }
7454            Err(closed) => Err(closed),
7455        }
7456    }
7457
7458    /// Cleans the wire after a two-thread cancel: a [`CancelHandle`] on another
7459    /// thread already sent the BREAK while this thread was blocked in a query, so
7460    /// the socket now holds the full multi-stage cancel response. Drains it with
7461    /// the SAME machinery the call-timeout path uses ([`drain_cancel_wire`] ->
7462    /// [`drain_break_response_recovery`]) — the cancelled call's in-flight DATA
7463    /// response, the break-ack MARKER, the RESET handshake, and the trailing
7464    /// ORA-01013 — leaving the connection clean and reusable.
7465    ///
7466    /// Before this used the proper drain it ran a single `read_data_response`
7467    /// that stopped at the in-flight response's end-of-response boundary, leaking
7468    /// the MARKER + ORA-01013 into the socket where the NEXT operation misread
7469    /// them (bead rust-oracledb-wnz). A failed drain marks the connection dead
7470    /// and surfaces [`Error::ConnectionClosed`].
7471    async fn drain_cancel_response(&mut self) -> Result<()> {
7472        self.core.recovery.begin_drain_after_break()?;
7473        match self.core.drain_cancel_wire(BREAK_DRAIN_RECOVERY_TIMEOUT) {
7474            Ok(()) => {
7475                self.core.recovery.finish_drain_ready();
7476                Ok(())
7477            }
7478            Err(err) => {
7479                self.core.recovery.mark_dead();
7480                self.dead = true;
7481                Err(err)
7482            }
7483        }
7484    }
7485
7486    /// Explicitly cancel the in-flight operation on this connection and leave the
7487    /// connection in a clean, reusable state.
7488    ///
7489    /// This sends a BREAK to the server and then **drains** the entire cancel
7490    /// response (any in-flight DATA response of the cancelled call, the break-ack
7491    /// MARKER, the RESET handshake, and the trailing `ORA-01013`) so the wire is
7492    /// left at a clean message boundary — exactly the recovery python-oracledb
7493    /// performs in `Connection.cancel()` (`_break_external()` + `_reset()`,
7494    /// protocol.pyx:533-557). The reference would send an out-of-band urgent-TCP
7495    /// break when `supports_oob` is negotiated and fall back to this in-band
7496    /// BREAK marker otherwise (protocol.pyx:56-69); asupersync's transport does
7497    /// not expose `MSG_OOB`, so the portable in-band path is always taken (the
7498    /// server handles it identically — see [`Self::supports_oob`]).
7499    ///
7500    /// On success the connection is **usable for the next operation** (the cancel
7501    /// mirrors `DPY-4024` semantics: the session is alive, the wire is clean).
7502    /// `Ok(())` means the cancel completed and the connection survives. If the
7503    /// drain fails (a second timeout or a wire error) the connection is marked
7504    /// dead and [`Error::ConnectionClosed`] is returned instead.
7505    ///
7506    /// Unlike [`Self::cancel_handle`] (which only fires a bare BREAK from another
7507    /// thread, leaving the owner-side drain to private recovery machinery), this
7508    /// is the single-call, self-contained cancel: break **and** drain in one
7509    /// place.
7510    pub async fn cancel(&mut self, _cx: &Cx) -> Result<()> {
7511        self.core.recovery.begin_drain_after_break()?;
7512        match self
7513            .core
7514            .cancel_and_drain_wire(BREAK_DRAIN_RECOVERY_TIMEOUT)
7515        {
7516            Ok(()) => {
7517                self.core.recovery.finish_drain_ready();
7518                Ok(())
7519            }
7520            Err(err) => {
7521                self.core.recovery.mark_dead();
7522                self.dead = true;
7523                Err(err)
7524            }
7525        }
7526    }
7527
7528    /// Whether the server negotiated out-of-band (urgent-TCP) break support at
7529    /// accept time (`protocol_options & TNS_GSO_CAN_RECV_ATTENTION`, the
7530    /// reference `Capabilities.supports_oob`, capabilities.pyx:120). This driver
7531    /// always uses the in-band BREAK marker for [`Self::cancel`] regardless,
7532    /// because asupersync's `TcpStream` does not expose `send(MSG_OOB)`; the bit
7533    /// is surfaced for diagnostics and parity with the reference capability
7534    /// negotiation. The server accepts the in-band break on every connection.
7535    pub fn supports_oob(&self) -> bool {
7536        self.supports_oob
7537    }
7538
7539    fn remember_cursor_columns(&mut self, result: &QueryResult) {
7540        if result.cursor_id != 0 && !result.columns.is_empty() {
7541            // On a statement-cache hit the same cursor re-executes with identical
7542            // columns, so the map already holds an equal value. Cloning the
7543            // `Vec<ColumnMetadata>` (and each column's `name`/object/domain
7544            // `String`) every call would be pure waste on that hot path. Skip the
7545            // clone when the cached value already matches; the map ends with the
7546            // same content either way (behavior-preserving). The equality check is
7547            // a cheap field compare versus the String allocations a clone makes.
7548            if self.cursor_columns.get(&result.cursor_id) == Some(&result.columns) {
7549                return;
7550            }
7551            self.cursor_columns
7552                .insert(result.cursor_id, result.columns.clone());
7553        }
7554    }
7555
7556    /// Retains the fetch metadata of the most recent execution of `sql`,
7557    /// evicting the oldest entry beyond the cap (reference retains this on
7558    /// the cached Statement object, impl/thin/statement.pyx:300-310).
7559    fn remember_fetch_metadata(&mut self, sql: &str, columns: &[ColumnMetadata]) {
7560        const FETCH_METADATA_RETENTION_CAP: usize = 100;
7561        if !self.fetch_metadata_by_sql.contains_key(sql) {
7562            if self.fetch_metadata_order.len() >= FETCH_METADATA_RETENTION_CAP {
7563                if let Some(oldest) = self.fetch_metadata_order.pop_front() {
7564                    self.fetch_metadata_by_sql.remove(&oldest);
7565                }
7566            }
7567            self.fetch_metadata_order.push_back(sql.to_string());
7568        }
7569        self.fetch_metadata_by_sql
7570            .insert(sql.to_string(), columns.to_vec());
7571    }
7572
7573    /// Drops the retained fetch metadata for `sql` (the reference clears the
7574    /// cached statement's cursor before a type-change retry,
7575    /// impl/thin/messages/base.pyx:1206-1213). Returns whether an entry
7576    /// existed.
7577    fn forget_fetch_metadata(&mut self, sql: &str) -> bool {
7578        if self.fetch_metadata_by_sql.remove(sql).is_some() {
7579            self.fetch_metadata_order.retain(|entry| entry != sql);
7580            return true;
7581        }
7582        false
7583    }
7584
7585    /// Applies the re-execute type-change rule: when the retained fetch
7586    /// metadata for this SQL says a column previously fetched as char/raw is
7587    /// now described as CLOB/BLOB, re-define the cursor so the data streams
7588    /// as LONG/LONG RAW (reference _adjust_metadata + _requires_define,
7589    /// impl/thin/messages/base.pyx:820-845, 1148-1158).
7590    async fn apply_refetch_metadata(
7591        &mut self,
7592        cx: &Cx,
7593        sql: &str,
7594        mut result: QueryResult,
7595        arraysize: u32,
7596    ) -> Result<QueryResult> {
7597        if result.columns.is_empty() {
7598            return Ok(result);
7599        }
7600        // Cross-connection statement-shape observation (bead a4-8pp): record the
7601        // freshly-described shape in the shared cache. If another connection
7602        // changed the shape since it was last seen (a concurrent DDL), self-heal
7603        // by dropping THIS connection's retained per-SQL fetch metadata so the
7604        // adjust below cannot re-define the fresh columns toward the now-stale
7605        // shape. The decode itself always uses the live `result.columns`, so it
7606        // is never stale; the cache only forces a re-describe when the shape
7607        // drifted. Self-heal only ever invalidates (heals down), never loosens.
7608        if self.shape_cache.observe(sql, &result.columns).self_healed {
7609            self.forget_fetch_metadata(sql);
7610        }
7611        if let Some(previous_columns) = self.fetch_metadata_by_sql.get(sql) {
7612            let mut adjusted = result.columns.clone();
7613            let mut any_adjusted = false;
7614            for (index, column) in adjusted.iter_mut().enumerate() {
7615                if let Some(previous) = previous_columns.get(index) {
7616                    any_adjusted |= adjust_refetch_metadata(previous, column);
7617                }
7618            }
7619            if any_adjusted && result.cursor_id != 0 {
7620                observe_cancellation_between_round_trips(cx)?;
7621                let cursor_id = result.cursor_id;
7622                let redefined_result = self
7623                    .define_and_fetch_rows_with_columns(
7624                        cx,
7625                        cursor_id,
7626                        arraysize.max(1),
7627                        &adjusted,
7628                        None,
7629                    )
7630                    .await;
7631                let mut redefined = self.close_cursor_on_error(cursor_id, redefined_result)?;
7632                if redefined.columns.is_empty() {
7633                    redefined.columns = adjusted;
7634                }
7635                if redefined.cursor_id == 0 {
7636                    redefined.cursor_id = cursor_id;
7637                }
7638                result = redefined;
7639            }
7640        }
7641        self.remember_fetch_metadata(sql, &result.columns);
7642        Ok(result)
7643    }
7644
7645    /// Looks up an open server cursor for the SQL text, refreshing its LRU
7646    /// position (reference `_statement_cache.get_statement`). A cached cursor
7647    /// that is currently `_in_use` by another live cursor is NOT handed out:
7648    /// the reference makes a `stmt.copy()` (fresh cursor id) in that case, so
7649    /// concurrent cursors over identical SQL each drive their own server
7650    /// cursor and cannot reset each other's fetch position (ORA-01002). We
7651    /// model the copy by returning `None`, which forces a fresh PARSE.
7652    ///
7653    /// A cached cursor whose recorded bind TYPE shape is incompatible with
7654    /// `bind_shape` is dropped (queued for the close-cursors piggyback) and
7655    /// `None` is returned, forcing a fresh PARSE with the new bind metadata:
7656    /// re-executing it would make the server coerce the new values through
7657    /// the stale parsed types (bead rust-oracledb-ilel, ORA-01722).
7658    fn statement_cache_get(&mut self, sql: &str, bind_shape: &[BindShapeSlot]) -> Option<u32> {
7659        let index = self
7660            .statement_cache
7661            .iter()
7662            .position(|entry| entry.sql == sql)?;
7663        let cursor_id = self.statement_cache[index].cursor_id;
7664        if cursor_id != 0 && self.in_use_cursors.contains(&cursor_id) {
7665            return None;
7666        }
7667        if !bind_shape_is_compatible(&self.statement_cache[index].bind_shape, bind_shape) {
7668            self.statement_cache_invalidate(sql, cursor_id);
7669            return None;
7670        }
7671        let entry = self.statement_cache.remove(index);
7672        self.statement_cache.push(entry);
7673        Some(cursor_id)
7674    }
7675
7676    /// Removes and returns the open cursor for the SQL text; used when the
7677    /// caller requested `cache_statement=False` but the statement is still
7678    /// present from an earlier cached execution (reference `_get_statement`
7679    /// pops from the cache unconditionally). A bind-shape mismatch drops the
7680    /// cursor instead of handing it out (same rule as
7681    /// [`Self::statement_cache_get`]).
7682    fn statement_cache_take(&mut self, sql: &str, bind_shape: &[BindShapeSlot]) -> Option<u32> {
7683        let index = self
7684            .statement_cache
7685            .iter()
7686            .position(|entry| entry.sql == sql)?;
7687        if !bind_shape_is_compatible(&self.statement_cache[index].bind_shape, bind_shape) {
7688            let cursor_id = self.statement_cache[index].cursor_id;
7689            self.statement_cache_invalidate(sql, cursor_id);
7690            return None;
7691        }
7692        Some(self.statement_cache.remove(index).cursor_id)
7693    }
7694
7695    /// Stores/updates the open cursor for the SQL text along with the bind
7696    /// TYPE shape it was bound with, evicting the least recently used entry
7697    /// into the close-cursors piggyback queue (reference
7698    /// `_statement_cache.return_statement`).
7699    fn statement_cache_put(&mut self, sql: &str, cursor_id: u32, bind_shape: Vec<BindShapeSlot>) {
7700        let to_close = statement_cache_insert(
7701            &mut self.statement_cache,
7702            self.statement_cache_size,
7703            sql,
7704            cursor_id,
7705            bind_shape,
7706        );
7707        for cursor_id in &to_close {
7708            self.lob_prefetch_cursors.remove(cursor_id);
7709            self.cursor_columns.remove(cursor_id);
7710        }
7711        self.cursors_to_close.extend(to_close);
7712    }
7713
7714    /// Drops any statement-cache entry whose open cursor was passed as an IN
7715    /// REF CURSOR bind in `bind_rows`. The called PL/SQL may have closed the
7716    /// cursor server-side, leaving the cached cursor_id invalid; clearing the
7717    /// entry forces a re-parse on the next execute of that SQL rather than
7718    /// reusing the closed cursor (ORA-01001). Test 1315 / 5815.
7719    fn invalidate_bound_ref_cursors(&mut self, bind_rows: &[Vec<BindValue>]) {
7720        for row in bind_rows {
7721            for value in row {
7722                if let BindValue::Cursor { cursor_id } = value {
7723                    if *cursor_id == 0 {
7724                        continue;
7725                    }
7726                    self.statement_cache
7727                        .retain(|entry| entry.cursor_id != *cursor_id);
7728                    self.cursor_columns.remove(cursor_id);
7729                    self.lob_prefetch_cursors.remove(cursor_id);
7730                }
7731            }
7732        }
7733    }
7734
7735    /// Releases a server cursor id previously marked in use by an executing
7736    /// query cursor (reference `_return_statement` clearing `Statement._in_use`).
7737    /// Called when the owning cursor closes or re-prepares; once released the
7738    /// cached cursor may be reused by the next execute of the same SQL. The
7739    /// cursor id stays in the statement cache (the open server cursor is kept
7740    /// for reuse, mirroring `_return_to_cache`).
7741    pub fn release_cursor(&mut self, cursor_id: u32) {
7742        if cursor_id == 0 {
7743            return;
7744        }
7745        self.in_use_cursors.remove(&cursor_id);
7746        // A copied cursor (parsed because the cached statement was busy) is not
7747        // kept open: queue it for the close-cursors piggyback now that its
7748        // owning cursor is done with it (reference `_add_cursor_to_close`).
7749        if self.copied_cursors.remove(&cursor_id) {
7750            self.cursors_to_close.push(cursor_id);
7751            self.cursor_columns.remove(&cursor_id);
7752            self.lob_prefetch_cursors.remove(&cursor_id);
7753        }
7754    }
7755
7756    /// Apply the fail-closed lifecycle rule for an operation on an already-open
7757    /// cursor: a successful result keeps ownership unchanged, while an error
7758    /// retires the cursor because its server-side validity is no longer proven.
7759    /// Callers that prove an operation never started must use `release_cursor`
7760    /// directly instead, preserving a valid cached cursor for reuse.
7761    pub(crate) fn close_cursor_on_error<T>(
7762        &mut self,
7763        cursor_id: u32,
7764        result: Result<T>,
7765    ) -> Result<T> {
7766        if result.is_err() {
7767            self.close_cursor(cursor_id);
7768        }
7769        result
7770    }
7771
7772    /// Queue an open server cursor to be closed on the next round trip
7773    /// (reference `_add_cursor_to_close`). Unlike [`Self::release_cursor`],
7774    /// which returns a cached cursor to the statement cache for reuse, this
7775    /// drops the cursor entirely: its id is sent in the close-cursors piggyback
7776    /// that rides the next execute, any statement-cache entry pointing at the
7777    /// id is evicted, and its retained describe metadata is forgotten. Use this
7778    /// for a non-cached cursor (for example one opened by [`Self::execute_raw`])
7779    /// once its result is fully consumed, or for any cursor whose validity was
7780    /// lost after a failed operation. A cursor id of `0` is ignored.
7781    pub fn close_cursor(&mut self, cursor_id: u32) {
7782        if cursor_id == 0 {
7783            return;
7784        }
7785        self.statement_cache
7786            .retain(|entry| entry.cursor_id != cursor_id);
7787        self.in_use_cursors.remove(&cursor_id);
7788        self.copied_cursors.remove(&cursor_id);
7789        self.cursor_columns.remove(&cursor_id);
7790        self.lob_prefetch_cursors.remove(&cursor_id);
7791        if !self.cursors_to_close.contains(&cursor_id) {
7792            self.cursors_to_close.push(cursor_id);
7793        }
7794    }
7795
7796    /// Returns true when the SQL text has a cached open cursor that is
7797    /// currently in use by another live cursor (reference `Statement._in_use`
7798    /// checked in `get_statement`).
7799    fn statement_is_in_use(&self, sql: &str) -> bool {
7800        self.statement_cache
7801            .iter()
7802            .find(|entry| entry.sql == sql)
7803            .is_some_and(|entry| {
7804                entry.cursor_id != 0 && self.in_use_cursors.contains(&entry.cursor_id)
7805            })
7806    }
7807
7808    /// Drops the cached cursor for the SQL text after a server error so the
7809    /// next execute re-parses (reference `_statement_cache.clear_cursor`).
7810    fn statement_cache_invalidate(&mut self, sql: &str, cursor_id: u32) {
7811        if let Some(index) = self
7812            .statement_cache
7813            .iter()
7814            .position(|entry| entry.sql == sql)
7815        {
7816            self.statement_cache.remove(index);
7817        }
7818        if cursor_id != 0 {
7819            self.cursors_to_close.push(cursor_id);
7820            self.cursor_columns.remove(&cursor_id);
7821            self.lob_prefetch_cursors.remove(&cursor_id);
7822            self.in_use_cursors.remove(&cursor_id);
7823            self.copied_cursors.remove(&cursor_id);
7824        }
7825    }
7826
7827    /// Builds the close-cursors piggyback bytes for any queued cursor ids;
7828    /// the piggyback consumes its own TTC sequence number.
7829    fn take_close_cursors_piggyback(&mut self) -> Option<Vec<u8>> {
7830        if self.cursors_to_close.is_empty() {
7831            return None;
7832        }
7833        let cursor_ids = std::mem::take(&mut self.cursors_to_close);
7834        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7835        Some(oracledb_protocol::thin::build_close_cursors_piggyback(
7836            &cursor_ids,
7837            seq_num,
7838            self.capabilities.ttc_field_version,
7839        ))
7840    }
7841
7842    /// Log off and close the connection, consuming it. Any uncommitted
7843    /// transaction is rolled back by the server.
7844    pub async fn close(mut self, cx: &Cx) -> Result<()> {
7845        observe_cancellation_between_round_trips(cx)?;
7846        match time::timeout(time::wall_now(), Duration::from_secs(5), self.rollback(cx)).await {
7847            Ok(result) => result?,
7848            Err(_) => {
7849                let eof = encode_packet(
7850                    TNS_PACKET_TYPE_DATA,
7851                    0,
7852                    Some(oracledb_protocol::thin::TNS_DATA_FLAGS_EOF),
7853                    &[],
7854                    PacketLengthWidth::Large32,
7855                )?;
7856                let _ = self.core.write_all(cx, &eof).await;
7857                let _ = self.core.shutdown_write(cx).await;
7858                return Ok(());
7859            }
7860        }
7861        self.ensure_clean_before_request().await?;
7862        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7863        self.core
7864            .send_data_packet(
7865                cx,
7866                &build_function_payload_with_seq(
7867                    TNS_FUNC_LOGOFF,
7868                    seq_num,
7869                    self.capabilities.ttc_field_version,
7870                ),
7871                self.sdu,
7872            )
7873            .await?;
7874        let capabilities = self.capabilities;
7875        let limits = self.protocol_limits;
7876        self.core
7877            .finish_session_close(cx, !self.supports_end_of_response, |bytes| {
7878                response_complete(&parse_plain_function_response_with_limits(
7879                    bytes,
7880                    capabilities,
7881                    limits,
7882                ))
7883            })
7884            .await
7885    }
7886
7887    /// Runs a batch of operations as a true wire pipeline (single round trip):
7888    /// every request is written before anything is read, then the N+1
7889    /// boundary-delimited responses (one per operation plus the end-pipeline
7890    /// response) are returned as raw TTC payloads in token order. Mirrors the
7891    /// reference flow (impl/thin/connection.pyx `run_pipeline_with_pipelining`
7892    /// and protocol.pyx `end_pipeline`):
7893    ///
7894    /// * the first message is prefixed with the begin-pipeline piggyback and
7895    ///   its first packet carries TNS_DATA_FLAGS_BEGIN_PIPELINE,
7896    /// * each operation message carries token 1..N and its final packet
7897    ///   carries TNS_DATA_FLAGS_END_OF_REQUEST,
7898    /// * the end-pipeline message (function 200) closes the batch,
7899    /// * marker packets received while reading pipeline responses are dropped
7900    ///   without sending a reset (packet.pyx:346-370),
7901    /// * responses are read for every operation even after a server error --
7902    ///   the server answers each message in both pipeline modes, so callers
7903    ///   parse per-operation payloads and decide error semantics.
7904    pub async fn run_pipeline(
7905        &mut self,
7906        cx: &Cx,
7907        requests: &[PipelineRequest],
7908        continue_on_error: bool,
7909    ) -> Result<Vec<Vec<u8>>> {
7910        // Pipelining is defined in terms of END_OF_RESPONSE boundary framing
7911        // (impl/thin/capabilities.pyx:126-130); a pre-23ai server that did not
7912        // negotiate it cannot delimit the N+1 pipelined responses, so fail
7913        // closed instead of hanging on the first boundary read.
7914        if !self.supports_end_of_response {
7915            return Err(Error::Protocol(
7916                oracledb_protocol::ProtocolError::UnsupportedFeature(
7917                    "pipelining requires END_OF_RESPONSE framing, which this server \
7918                     did not negotiate (requires Oracle Database 23ai or later)",
7919                ),
7920            ));
7921        }
7922        observe_cancellation_between_round_trips(cx)?;
7923        if requests.is_empty() {
7924            return Ok(Vec::new());
7925        }
7926        self.ensure_clean_before_request().await?;
7927        self.protocol_limits
7928            .check_length_prefixed_elements(requests.len())?;
7929        let pipeline_mode = if continue_on_error {
7930            TNS_PIPELINE_MODE_CONTINUE_ON_ERROR
7931        } else {
7932            TNS_PIPELINE_MODE_ABORT_ON_ERROR
7933        };
7934        for (index, request) in requests.iter().enumerate() {
7935            let token_num = index as u64 + 1;
7936            let mut payload = Vec::new();
7937            let mut first_packet_flags = 0u16;
7938            if index == 0 {
7939                // Flush any pending close-cursors piggyback on the first op so
7940                // server cursors retired since the last round trip (evicted from
7941                // the statement cache or released by a closed cursor) are
7942                // actually closed — otherwise a sequence of pipelines that open
7943                // query cursors leaks them server-side (ORA-01000). The
7944                // reference likewise rides queued closes as a piggyback on the
7945                // next message; it is consumed before the begin-pipeline
7946                // piggyback's sequence number, matching the ordinary execute
7947                // path where the close-cursors piggyback is prepended first.
7948                if let Some(close_piggyback) = self.take_close_cursors_piggyback() {
7949                    payload.extend_from_slice(&close_piggyback);
7950                }
7951                let piggyback_seq = next_ttc_sequence(&mut self.ttc_seq_num);
7952                payload.extend_from_slice(&build_begin_pipeline_piggyback(
7953                    piggyback_seq,
7954                    token_num,
7955                    pipeline_mode,
7956                ));
7957                first_packet_flags |= TNS_DATA_FLAGS_BEGIN_PIPELINE;
7958            }
7959            let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
7960            match request {
7961                PipelineRequest::Execute {
7962                    sql,
7963                    bind_rows,
7964                    prefetch_rows,
7965                } => {
7966                    self.protocol_limits.check_batch_rows(bind_rows.len())?;
7967                    if let Some(first_row) = bind_rows.first() {
7968                        self.protocol_limits.check_binds(first_row.len())?;
7969                    }
7970                    payload.extend_from_slice(
7971                        &build_execute_payload_with_bind_rows_and_options_with_seq(
7972                            sql,
7973                            *prefetch_rows,
7974                            seq_num,
7975                            statement_is_query(sql),
7976                            bind_rows,
7977                            ExecuteOptions::default()
7978                                .with_token_num(token_num)
7979                                .with_max_string_size(self.capabilities.max_string_size),
7980                            self.capabilities.ttc_field_version,
7981                        )?,
7982                    );
7983                }
7984                PipelineRequest::Commit => {
7985                    payload.extend_from_slice(&build_function_payload_with_seq_and_token(
7986                        TNS_FUNC_COMMIT,
7987                        seq_num,
7988                        token_num,
7989                        self.capabilities.ttc_field_version,
7990                    ));
7991                }
7992            }
7993            trace_query_bytes("PIPELINE op payload", &payload);
7994            self.core
7995                .send_data_packet_with_flags(
7996                    cx,
7997                    &payload,
7998                    self.sdu,
7999                    first_packet_flags,
8000                    TNS_DATA_FLAGS_END_OF_REQUEST,
8001                )
8002                .await?;
8003        }
8004        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
8005        let end_payload = build_end_pipeline_payload_with_seq(seq_num);
8006        trace_query_bytes("PIPELINE end payload", &end_payload);
8007        self.core
8008            .send_data_packet(cx, &end_payload, self.sdu)
8009            .await?;
8010        let mut responses = Vec::with_capacity(requests.len() + 1);
8011        for _ in 0..=requests.len() {
8012            let response = match self.read_pipeline_response_cancellable(cx).await {
8013                Ok(response) => response,
8014                Err(Error::CallTimeout(timeout_ms)) => {
8015                    return self.recover_from_call_timeout(cx, timeout_ms).await;
8016                }
8017                Err(err) => return Err(err),
8018            };
8019            trace_query_bytes("PIPELINE response", &response.payload);
8020            responses.push(response.payload);
8021        }
8022        Ok(responses)
8023    }
8024
8025    /// Runs a batch as a true single-round-trip pipeline (like [`Self::run_pipeline`])
8026    /// and decodes each per-operation response into a [`QueryResult`], reusing
8027    /// the same `parse_query_response_*` decoders the ordinary execute path uses
8028    /// — no result-layer reimplementation. The end-pipeline response (the N+1th
8029    /// raw payload) is consumed for framing but not returned.
8030    ///
8031    /// Each operation is decoded with its own bind row and prefetch (carried by
8032    /// [`PipelineRequest::Execute`]); the returned vector has one entry per
8033    /// request, in token order. A per-operation server error is captured as
8034    /// `Err` for that slot rather than aborting the batch, so the caller can
8035    /// implement both abort-on-error and continue-on-error semantics over the
8036    /// decoded results (the wire batch already ran to completion — the server
8037    /// answers every message in both pipeline modes).
8038    ///
8039    /// The connection's `txn_in_progress` flag is refreshed from the last
8040    /// successfully decoded operation that carried an end-of-call STATUS, so a
8041    /// pipeline ending in commit/DML leaves the flag consistent with the
8042    /// sequential path (test_7614). No extra round trips are issued here: a
8043    /// query whose rows did not all fit in the prefetch returns its open
8044    /// `cursor_id` + `columns` + `more_rows` in the [`QueryResult`] so the
8045    /// caller can finish the fetch over the ordinary public cursor API, exactly
8046    /// as the reference `_complete_pipeline_op` does.
8047    pub async fn run_pipeline_decoded(
8048        &mut self,
8049        cx: &Cx,
8050        requests: &[PipelineRequest],
8051        continue_on_error: bool,
8052    ) -> Result<Vec<Result<QueryResult>>> {
8053        let raw = self.run_pipeline(cx, requests, continue_on_error).await?;
8054        // raw has requests.len() + 1 entries (the last is the end-pipeline
8055        // response, consumed for framing only).
8056        let mut decoded = Vec::with_capacity(requests.len());
8057        for (index, request) in requests.iter().enumerate() {
8058            let payload = &raw[index];
8059            let outcome = match request {
8060                PipelineRequest::Commit => {
8061                    // A commit op answers with a plain function response; decode
8062                    // it the same way the standalone commit path does so the
8063                    // txn-in-progress bit is sampled identically.
8064                    match parse_plain_function_response_with_limits(
8065                        payload,
8066                        self.capabilities,
8067                        self.protocol_limits,
8068                    ) {
8069                        Ok(txn_in_progress) => Ok(QueryResult {
8070                            txn_in_progress: Some(txn_in_progress),
8071                            ..QueryResult::default()
8072                        }),
8073                        Err(err) => Err(Error::Protocol(err)),
8074                    }
8075                }
8076                PipelineRequest::Execute { sql, bind_rows, .. } => {
8077                    parse_query_response_with_binds_options_columns_and_limits(
8078                        payload,
8079                        self.capabilities,
8080                        bind_rows.first().map(Vec::as_slice).unwrap_or(&[]),
8081                        ExecuteOptions::default(),
8082                        &[],
8083                        self.protocol_limits,
8084                    )
8085                    .map_err(Error::Protocol)
8086                    .inspect(|result| {
8087                        // Track open query cursors so a later op or a follow-up
8088                        // fetch on this connection does not collide with them.
8089                        self.remember_cursor_columns(result);
8090                        if result.cursor_id != 0 && statement_is_query(sql) {
8091                            self.in_use_cursors.insert(result.cursor_id);
8092                        }
8093                    })
8094                }
8095            };
8096            // Refresh txn-in-progress from any op that carried a STATUS message,
8097            // mirroring the sequential per-op execute bookkeeping.
8098            if let Ok(result) = &outcome {
8099                if let Some(txn_in_progress) = result.txn_in_progress {
8100                    self.txn_in_progress = txn_in_progress;
8101                }
8102            }
8103            decoded.push(outcome);
8104        }
8105        Ok(decoded)
8106    }
8107
8108    async fn send_function(&mut self, cx: &Cx, function_code: u8) -> Result<()> {
8109        observe_cancellation_between_round_trips(cx)?;
8110        self.ensure_clean_before_request().await?;
8111        let seq_num = next_ttc_sequence(&mut self.ttc_seq_num);
8112        self.core
8113            .send_data_packet(
8114                cx,
8115                &build_function_payload_with_seq(
8116                    function_code,
8117                    seq_num,
8118                    self.capabilities.ttc_field_version,
8119                ),
8120                self.sdu,
8121            )
8122            .await?;
8123        let capabilities = self.capabilities;
8124        let limits = self.protocol_limits;
8125        let response = self
8126            .read_response_cancellable(cx, !self.supports_end_of_response, |bytes| {
8127                response_complete(&parse_plain_function_response_with_limits(
8128                    bytes,
8129                    capabilities,
8130                    limits,
8131                ))
8132            })
8133            .await?;
8134        // Surface server errors (e.g. ORA-01012 after a killed session) that
8135        // arrive on plain function round trips; pool ping health checks and
8136        // commit/rollback depend on these not being silently swallowed. The
8137        // returned bit refreshes `txn_in_progress` from the wire end-of-call
8138        // status (reference protocol.pyx `_process_call_status`).
8139        let txn_in_progress = self.note_parse(parse_plain_function_response_with_limits(
8140            &response,
8141            self.capabilities,
8142            self.protocol_limits,
8143        ))?;
8144        self.txn_in_progress = txn_in_progress;
8145        Ok(())
8146    }
8147
8148    /// Mark CLOB/BLOB result columns that actually hold JSON.
8149    ///
8150    /// A column described over the wire as CLOB or BLOB can be a JSON column
8151    /// (`IS JSON` storage); the fetch metadata does not say so directly. For each
8152    /// such candidate this runs a catalog probe against `ALL_JSON_COLUMNS` in the
8153    /// current schema and flips `is_json` when the column is registered as JSON.
8154    /// Columns already flagged JSON, non-LOB columns, and unnamed (expression)
8155    /// columns are skipped. `timeout_ms` bounds each probe (the call timeout).
8156    ///
8157    /// The reference fires the same `ALL_JSON_COLUMNS` lookup after describing a
8158    /// LOB result column so JSON-in-LOB values decode correctly.
8159    pub async fn supplement_json_column_metadata(
8160        &mut self,
8161        cx: &Cx,
8162        columns: &mut [ColumnMetadata],
8163        timeout_ms: Option<u32>,
8164    ) -> Result<()> {
8165        let candidates = json_lob_probe_candidates(columns);
8166        if candidates.is_empty() {
8167            return Ok(());
8168        }
8169        for (index, column_name) in candidates {
8170            let result = self
8171                .execute_query_with_binds_call_timeout(
8172                    cx,
8173                    "select 1 \
8174                     from all_json_columns \
8175                     where owner = sys_context('USERENV', 'CURRENT_SCHEMA') \
8176                       and column_name = :1",
8177                    1,
8178                    &[BindValue::Text(column_name)],
8179                    timeout_ms,
8180                )
8181                .await?;
8182            if !result.rows.is_empty() {
8183                columns[index] = columns[index].clone().with_is_json(true);
8184            }
8185        }
8186        Ok(())
8187    }
8188}
8189
8190impl CancelHandle {
8191    /// Request cancellation of the connection operation currently in flight.
8192    ///
8193    /// The blocking facade for synchronous callers is [`Self::cancel_blocking`];
8194    /// Rust cannot overload that zero-argument wrapper with this `&Cx` form.
8195    ///
8196    /// This is request-only: it sends the BREAK marker and records that recovery
8197    /// is pending, but the connection owner remains responsible for draining the
8198    /// cancel response and reconciling the session back to Ready or Dead.
8199    pub async fn cancel(&mut self, cx: &Cx) -> Result<()> {
8200        observe_cancellation_between_round_trips(cx)?;
8201        if !self.should_send_break_request()? {
8202            return Ok(());
8203        }
8204        let mut write = lock_write(cx, &self.write).await?;
8205        if !self.should_send_break_request()? {
8206            return Ok(());
8207        }
8208        match send_marker(&mut *write, TNS_MARKER_TYPE_BREAK).await {
8209            Ok(()) => self.recovery.mark_break_sent(),
8210            Err(err) => {
8211                self.recovery.mark_dead();
8212                Err(err)
8213            }
8214        }
8215    }
8216
8217    /// Send the request-only BREAK needed by a local recovery path without
8218    /// consulting the operation context.
8219    ///
8220    /// A caller can arrive here precisely because that context has already
8221    /// been cancelled. Recovery must still get the server to stop the
8222    /// in-flight operation before its owner can drain the multi-packet cancel
8223    /// response and safely hand the connection back. A recovery thread owns
8224    /// the bounded marker write so async I/O cannot observe the caller's
8225    /// cancelled ambient context.
8226    pub(crate) fn cancel_for_recovery(&mut self) -> Result<()> {
8227        if !self.should_send_break_request()? {
8228            return Ok(());
8229        }
8230        match crate::recovery::send_break_without_current_cx(
8231            &self.write,
8232            BREAK_DRAIN_RECOVERY_TIMEOUT,
8233        ) {
8234            Ok(()) => self.recovery.mark_break_sent(),
8235            Err(err) => {
8236                self.recovery.mark_dead();
8237                Err(err)
8238            }
8239        }
8240    }
8241
8242    fn should_send_break_request(&self) -> Result<bool> {
8243        match self.recovery.phase() {
8244            SessionRecoveryPhase::Dead => {
8245                Err(Error::ConnectionClosed("connection is closed".into()))
8246            }
8247            SessionRecoveryPhase::BreakSent | SessionRecoveryPhase::Draining => Ok(false),
8248            SessionRecoveryPhase::Ready | SessionRecoveryPhase::InFlight => Ok(true),
8249        }
8250    }
8251
8252    /// Blocking facade for synchronous callers.
8253    pub fn cancel_blocking(&mut self) -> Result<()> {
8254        let runtime = build_io_runtime()?;
8255        runtime.block_on(async {
8256            let cx = Cx::current()
8257                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8258            self.cancel(&cx).await
8259        })
8260    }
8261}
8262
8263/// Synchronous facade over [`Connection`].
8264///
8265/// Each associated function spins up a private single-threaded Asupersync
8266/// runtime, drives the corresponding async [`Connection`] method to
8267/// completion, and blocks the calling thread until it returns. The functions
8268/// take a `&mut Connection` (returned by [`BlockingConnection::connect`]) so a
8269/// connection can be reused across calls. This is the simplest way to use the
8270/// driver from ordinary synchronous Rust.
8271///
8272/// ```no_run
8273/// use oraclemcp_driver_cx::{BlockingConnection, ConnectOptions};
8274/// use oraclemcp_driver_cx::protocol::ClientIdentity;
8275///
8276/// # fn main() -> Result<(), oraclemcp_driver_cx::Error> {
8277/// let identity = ClientIdentity::new("svc", "host", "user", "term", "rust-oracledb")?;
8278/// let mut conn = BlockingConnection::connect(
8279///     ConnectOptions::new("dbhost:1521/FREEPDB1", "app", "pw", identity),
8280/// )?;
8281/// let row = BlockingConnection::query_one(&mut conn, "select 1 from dual", ())?;
8282/// let value: i64 = row.get(0)?;
8283/// assert_eq!(value, 1);
8284/// BlockingConnection::close(conn)?;
8285/// # Ok(())
8286/// # }
8287/// ```
8288pub struct BlockingConnection;
8289
8290impl BlockingConnection {
8291    /// Open a connection synchronously. See [`Connection::connect`].
8292    pub fn connect(options: ConnectOptions) -> Result<Connection> {
8293        let runtime = build_io_runtime()?;
8294        runtime.block_on(async {
8295            let cx = Cx::current()
8296                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8297            Connection::connect(&cx, options).await
8298        })
8299    }
8300
8301    pub fn ping(connection: &mut Connection) -> Result<()> {
8302        let runtime = build_io_runtime()?;
8303        runtime.block_on(async {
8304            let cx = Cx::current()
8305                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8306            connection.ping(&cx).await
8307        })
8308    }
8309
8310    pub fn ping_with_timeout(connection: &mut Connection, timeout_ms: u32) -> Result<()> {
8311        let runtime = build_io_runtime()?;
8312        runtime.block_on(async {
8313            let cx = Cx::current()
8314                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8315            connection.ping_with_timeout(&cx, timeout_ms).await
8316        })
8317    }
8318
8319    pub fn change_password(
8320        connection: &mut Connection,
8321        old_password: &str,
8322        new_password: &str,
8323    ) -> Result<()> {
8324        let runtime = build_io_runtime()?;
8325        runtime.block_on(async {
8326            let cx = Cx::current()
8327                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8328            connection
8329                .change_password(&cx, old_password, new_password)
8330                .await
8331        })
8332    }
8333
8334    /// Blocking wrapper for [`Connection::cancel`].
8335    pub fn cancel(connection: &mut Connection) -> Result<()> {
8336        block_on_io(|cx| async move { connection.cancel(&cx).await })
8337    }
8338
8339    pub fn commit(connection: &mut Connection) -> Result<()> {
8340        let runtime = build_io_runtime()?;
8341        runtime.block_on(async {
8342            let cx = Cx::current()
8343                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8344            connection.commit(&cx).await
8345        })
8346    }
8347
8348    /// Register a CQN subscription (FUNC 125, opcode 1). See
8349    /// [`Connection::subscribe_register`].
8350    #[allow(clippy::too_many_arguments)]
8351    pub fn subscribe_register(
8352        connection: &mut Connection,
8353        namespace: u32,
8354        name: Option<&str>,
8355        public_qos: u32,
8356        operations: u32,
8357        timeout: u32,
8358        grouping_class: u8,
8359        grouping_value: u32,
8360        grouping_type: u8,
8361    ) -> Result<SubscribeResult> {
8362        let runtime = build_io_runtime()?;
8363        runtime.block_on(async {
8364            let cx = Cx::current()
8365                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8366            connection
8367                .subscribe_register(
8368                    &cx,
8369                    namespace,
8370                    name,
8371                    public_qos,
8372                    operations,
8373                    timeout,
8374                    grouping_class,
8375                    grouping_value,
8376                    grouping_type,
8377                )
8378                .await
8379        })
8380    }
8381
8382    /// Unregister a CQN subscription (FUNC 125, opcode 2). See
8383    /// [`Connection::subscribe_unregister`].
8384    #[allow(clippy::too_many_arguments)]
8385    pub fn subscribe_unregister(
8386        connection: &mut Connection,
8387        registration_id: u64,
8388        client_id: &[u8],
8389        namespace: u32,
8390        name: Option<&str>,
8391        public_qos: u32,
8392        operations: u32,
8393        timeout: u32,
8394        grouping_class: u8,
8395        grouping_value: u32,
8396        grouping_type: u8,
8397    ) -> Result<()> {
8398        let runtime = build_io_runtime()?;
8399        runtime.block_on(async {
8400            let cx = Cx::current()
8401                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8402            connection
8403                .subscribe_unregister(
8404                    &cx,
8405                    registration_id,
8406                    client_id,
8407                    namespace,
8408                    name,
8409                    public_qos,
8410                    operations,
8411                    timeout,
8412                    grouping_class,
8413                    grouping_value,
8414                    grouping_type,
8415                )
8416                .await
8417        })
8418    }
8419
8420    /// Send the blocking CQN NOTIFY registration message. See
8421    /// [`Connection::notify_register`].
8422    pub fn notify_register(connection: &mut Connection, client_id: &[u8]) -> Result<()> {
8423        block_on_io(|cx| async move { connection.notify_register(&cx, client_id).await })
8424    }
8425
8426    /// Blocking wrapper for [`Connection::recv_notification`].
8427    pub fn recv_notification(
8428        connection: &mut Connection,
8429        namespace: u32,
8430        public_qos: u32,
8431        read_timeout: Duration,
8432    ) -> Result<NotificationOutcome> {
8433        block_on_io(|cx| async move {
8434            connection
8435                .recv_notification(&cx, namespace, public_qos, read_timeout)
8436                .await
8437        })
8438    }
8439
8440    /// Blocking wrapper for [`Connection::register_query`].
8441    pub fn register_query<'r>(
8442        connection: &mut Connection,
8443        registration: Registration<'r>,
8444    ) -> Result<RegistrationOutcome> {
8445        block_on_io(|cx| async move { connection.register_query(&cx, registration).await })
8446    }
8447
8448    pub fn rollback(connection: &mut Connection) -> Result<()> {
8449        let runtime = build_io_runtime()?;
8450        runtime.block_on(async {
8451            let cx = Cx::current()
8452                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8453            connection.rollback(&cx).await
8454        })
8455    }
8456
8457    /// Blocking wrapper for [`Connection::enable_dbms_output`].
8458    pub fn enable_dbms_output(
8459        connection: &mut Connection,
8460        buffer_bytes: Option<u32>,
8461    ) -> Result<()> {
8462        let runtime = build_io_runtime()?;
8463        runtime.block_on(async {
8464            let cx = Cx::current()
8465                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8466            connection.enable_dbms_output(&cx, buffer_bytes).await
8467        })
8468    }
8469
8470    /// Blocking wrapper for [`Connection::read_dbms_output`].
8471    pub fn read_dbms_output(
8472        connection: &mut Connection,
8473        max_lines: usize,
8474        max_chars: usize,
8475    ) -> Result<DbmsOutput> {
8476        let runtime = build_io_runtime()?;
8477        runtime.block_on(async {
8478            let cx = Cx::current()
8479                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8480            connection.read_dbms_output(&cx, max_lines, max_chars).await
8481        })
8482    }
8483
8484    /// Blocking wrapper for [`Connection::fetch_cursor`].
8485    pub fn fetch_cursor(
8486        connection: &mut Connection,
8487        cursor: &oracledb_protocol::thin::CursorValue,
8488        max_rows: usize,
8489    ) -> Result<QueryResult> {
8490        let runtime = build_io_runtime()?;
8491        runtime.block_on(async {
8492            let cx = Cx::current()
8493                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8494            connection.fetch_cursor(&cx, cursor, max_rows).await
8495        })
8496    }
8497
8498    /// Blocking wrapper for [`Connection::describe_object_type`].
8499    pub fn describe_object_type(
8500        connection: &mut Connection,
8501        schema: &str,
8502        type_name: &str,
8503    ) -> Result<ObjectType> {
8504        let runtime = build_io_runtime()?;
8505        runtime.block_on(async {
8506            let cx = Cx::current()
8507                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8508            connection
8509                .describe_object_type(&cx, schema, type_name)
8510                .await
8511        })
8512    }
8513
8514    pub fn begin_sessionless_transaction(
8515        connection: &mut Connection,
8516        transaction_id: &[u8],
8517        timeout: u32,
8518        defer_round_trip: bool,
8519    ) -> Result<()> {
8520        let runtime = build_io_runtime()?;
8521        runtime.block_on(async {
8522            let cx = Cx::current()
8523                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8524            connection
8525                .begin_sessionless_transaction(&cx, transaction_id, timeout, defer_round_trip)
8526                .await
8527        })
8528    }
8529
8530    pub fn resume_sessionless_transaction(
8531        connection: &mut Connection,
8532        transaction_id: &[u8],
8533        timeout: u32,
8534        defer_round_trip: bool,
8535    ) -> Result<()> {
8536        let runtime = build_io_runtime()?;
8537        runtime.block_on(async {
8538            let cx = Cx::current()
8539                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8540            connection
8541                .resume_sessionless_transaction(&cx, transaction_id, timeout, defer_round_trip)
8542                .await
8543        })
8544    }
8545
8546    pub fn suspend_sessionless_transaction(connection: &mut Connection) -> Result<()> {
8547        let runtime = build_io_runtime()?;
8548        runtime.block_on(async {
8549            let cx = Cx::current()
8550                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8551            connection.suspend_sessionless_transaction(&cx).await
8552        })
8553    }
8554
8555    #[allow(clippy::too_many_arguments)]
8556    pub fn tpc_begin(
8557        connection: &mut Connection,
8558        format_id: u32,
8559        global_transaction_id: &[u8],
8560        branch_qualifier: &[u8],
8561        flags: u32,
8562        timeout: u32,
8563    ) -> Result<()> {
8564        let runtime = build_io_runtime()?;
8565        runtime.block_on(async {
8566            let cx = Cx::current()
8567                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8568            connection
8569                .tpc_begin(
8570                    &cx,
8571                    format_id,
8572                    global_transaction_id,
8573                    branch_qualifier,
8574                    flags,
8575                    timeout,
8576                )
8577                .await
8578        })
8579    }
8580
8581    pub fn tpc_end(
8582        connection: &mut Connection,
8583        xid: Option<(u32, &[u8], &[u8])>,
8584        flags: u32,
8585    ) -> Result<()> {
8586        let runtime = build_io_runtime()?;
8587        runtime.block_on(async {
8588            let cx = Cx::current()
8589                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8590            connection.tpc_end(&cx, xid, flags).await
8591        })
8592    }
8593
8594    pub fn tpc_prepare(
8595        connection: &mut Connection,
8596        xid: Option<(u32, &[u8], &[u8])>,
8597    ) -> Result<bool> {
8598        let runtime = build_io_runtime()?;
8599        runtime.block_on(async {
8600            let cx = Cx::current()
8601                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8602            connection.tpc_prepare(&cx, xid).await
8603        })
8604    }
8605
8606    pub fn tpc_commit(
8607        connection: &mut Connection,
8608        xid: Option<(u32, &[u8], &[u8])>,
8609        one_phase: bool,
8610    ) -> Result<()> {
8611        let runtime = build_io_runtime()?;
8612        runtime.block_on(async {
8613            let cx = Cx::current()
8614                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8615            connection.tpc_commit(&cx, xid, one_phase).await
8616        })
8617    }
8618
8619    pub fn tpc_rollback(
8620        connection: &mut Connection,
8621        xid: Option<(u32, &[u8], &[u8])>,
8622    ) -> Result<()> {
8623        let runtime = build_io_runtime()?;
8624        runtime.block_on(async {
8625            let cx = Cx::current()
8626                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8627            connection.tpc_rollback(&cx, xid).await
8628        })
8629    }
8630
8631    /// Blocking wrapper for [`Connection::query`]: bind typed Rust values
8632    /// positionally or by name, then return a blocking lazy row facade.
8633    pub fn query<'conn, 'p>(
8634        connection: &'conn mut Connection,
8635        sql: &str,
8636        params: impl Into<crate::Params<'p>>,
8637    ) -> Result<BlockingRows<'conn>> {
8638        block_on_io(|cx| async move {
8639            connection
8640                .query(&cx, sql, params)
8641                .await
8642                .map(BlockingRows::new)
8643        })
8644    }
8645
8646    /// Blocking wrapper for [`Connection::query_one`].
8647    pub fn query_one<'p>(
8648        connection: &mut Connection,
8649        sql: &str,
8650        params: impl Into<crate::Params<'p>>,
8651    ) -> Result<Row> {
8652        block_on_io(|cx| async move { connection.query_one(&cx, sql, params).await })
8653    }
8654
8655    /// Blocking wrapper for [`Connection::query_opt`].
8656    pub fn query_opt<'p>(
8657        connection: &mut Connection,
8658        sql: &str,
8659        params: impl Into<crate::Params<'p>>,
8660    ) -> Result<Option<Row>> {
8661        block_on_io(|cx| async move { connection.query_opt(&cx, sql, params).await })
8662    }
8663
8664    /// Blocking wrapper for [`Connection::query_all`].
8665    pub fn query_all<'p>(
8666        connection: &mut Connection,
8667        sql: &str,
8668        params: impl Into<crate::Params<'p>>,
8669    ) -> Result<Vec<Row>> {
8670        block_on_io(|cx| async move { connection.query_all(&cx, sql, params).await })
8671    }
8672
8673    /// Blocking wrapper for [`Connection::query_with`].
8674    pub fn query_with<'conn, 'q>(
8675        connection: &'conn mut Connection,
8676        query: Query<'q>,
8677    ) -> Result<BlockingRows<'conn>> {
8678        block_on_io(|cx| async move {
8679            connection
8680                .query_with(&cx, query)
8681                .await
8682                .map(BlockingRows::new)
8683        })
8684    }
8685
8686    /// Blocking wrapper for [`Connection::execute`].
8687    pub fn execute<'p>(
8688        connection: &mut Connection,
8689        sql: &str,
8690        params: impl Into<crate::Params<'p>>,
8691    ) -> Result<ExecuteOutcome> {
8692        block_on_io(|cx| async move { connection.execute(&cx, sql, params).await })
8693    }
8694
8695    /// Blocking wrapper for [`Connection::execute_with`].
8696    pub fn execute_with<'e>(
8697        connection: &mut Connection,
8698        execute: Execute<'e>,
8699    ) -> Result<ExecuteOutcome> {
8700        block_on_io(|cx| async move { connection.execute_with(&cx, execute).await })
8701    }
8702
8703    /// Blocking wrapper for [`Connection::execute_many`].
8704    pub fn execute_many<'b>(
8705        connection: &mut Connection,
8706        sql: &str,
8707        rows: impl Into<crate::BatchRows<'b>>,
8708    ) -> Result<BatchOutcome> {
8709        block_on_io(|cx| async move { connection.execute_many(&cx, sql, rows).await })
8710    }
8711
8712    /// Blocking wrapper for [`Connection::execute_many_with`].
8713    pub fn execute_many_with<'b>(
8714        connection: &mut Connection,
8715        batch: Batch<'b>,
8716    ) -> Result<BatchOutcome> {
8717        block_on_io(|cx| async move { connection.execute_many_with(&cx, batch).await })
8718    }
8719
8720    /// Blocking wrapper for [`Connection::execute_raw`]: the low-level raw
8721    /// execute primitive returning the unprojected [`QueryResult`], the
8722    /// execute-side counterpart to the retained blocking fetch primitives
8723    /// ([`Self::fetch_rows`], [`Self::define_and_fetch_rows_with_columns`],
8724    /// [`Self::scroll_cursor`], [`Self::fetch_cursor`]). Prefer the blocking
8725    /// operation families ([`Self::query`]/[`Self::execute`]/[`Self::execute_many`])
8726    /// for ordinary code; reach for `execute_raw` only when you need the raw
8727    /// wire result (statement-type-agnostic dispatch, parse-only describe, or
8728    /// per-bind-row OUT/RETURNING aggregation).
8729    pub fn execute_raw(
8730        connection: &mut Connection,
8731        sql: &str,
8732        prefetch_rows: u32,
8733        bind_rows: &[Vec<BindValue>],
8734        exec_options: ExecuteOptions,
8735        timeout_ms: Option<u32>,
8736    ) -> Result<QueryResult> {
8737        let runtime = build_io_runtime()?;
8738        runtime.block_on(async {
8739            let cx = Cx::current()
8740                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8741            connection
8742                .execute_raw(&cx, sql, prefetch_rows, bind_rows, exec_options, timeout_ms)
8743                .await
8744        })
8745    }
8746
8747    pub fn fetch_rows(
8748        connection: &mut Connection,
8749        cursor_id: u32,
8750        arraysize: u32,
8751        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
8752    ) -> Result<QueryResult> {
8753        let runtime = build_io_runtime()?;
8754        runtime.block_on(async {
8755            let cx = Cx::current()
8756                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8757            connection
8758                .fetch_rows(&cx, cursor_id, arraysize, previous_row)
8759                .await
8760        })
8761    }
8762
8763    pub fn fetch_rows_with_columns(
8764        connection: &mut Connection,
8765        cursor_id: u32,
8766        arraysize: u32,
8767        known_columns: &[ColumnMetadata],
8768        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
8769    ) -> Result<QueryResult> {
8770        let runtime = build_io_runtime()?;
8771        runtime.block_on(async {
8772            let cx = Cx::current()
8773                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8774            connection
8775                .fetch_rows_with_columns(&cx, cursor_id, arraysize, known_columns, previous_row)
8776                .await
8777        })
8778    }
8779
8780    pub fn define_and_fetch_rows_with_columns(
8781        connection: &mut Connection,
8782        cursor_id: u32,
8783        arraysize: u32,
8784        define_columns: &[ColumnMetadata],
8785        previous_row: Option<&[Option<oracledb_protocol::thin::QueryValue>]>,
8786    ) -> Result<QueryResult> {
8787        let runtime = build_io_runtime()?;
8788        runtime.block_on(async {
8789            let cx = Cx::current()
8790                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8791            connection
8792                .define_and_fetch_rows_with_columns(
8793                    &cx,
8794                    cursor_id,
8795                    arraysize,
8796                    define_columns,
8797                    previous_row,
8798                )
8799                .await
8800        })
8801    }
8802
8803    pub fn scroll_cursor(
8804        connection: &mut Connection,
8805        sql: &str,
8806        cursor_id: u32,
8807        arraysize: u32,
8808        fetch_orientation: u32,
8809        fetch_pos: u32,
8810    ) -> Result<QueryResult> {
8811        let runtime = build_io_runtime()?;
8812        runtime.block_on(async {
8813            let cx = Cx::current()
8814                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8815            connection
8816                .scroll_cursor(&cx, sql, cursor_id, arraysize, fetch_orientation, fetch_pos)
8817                .await
8818        })
8819    }
8820
8821    pub fn read_lob(
8822        connection: &mut Connection,
8823        locator: &[u8],
8824        offset: u64,
8825        amount: u64,
8826    ) -> Result<LobReadResult> {
8827        let runtime = build_io_runtime()?;
8828        runtime.block_on(async {
8829            let cx = Cx::current()
8830                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8831            connection.read_lob(&cx, locator, offset, amount).await
8832        })
8833    }
8834
8835    pub fn read_lob_with_timeout(
8836        connection: &mut Connection,
8837        locator: &[u8],
8838        offset: u64,
8839        amount: u64,
8840        timeout_ms: Option<u32>,
8841    ) -> Result<LobReadResult> {
8842        let runtime = build_io_runtime()?;
8843        runtime.block_on(async {
8844            let cx = Cx::current()
8845                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8846            connection
8847                .read_lob_call_timeout(&cx, locator, offset, amount, timeout_ms)
8848                .await
8849        })
8850    }
8851
8852    pub fn aq_enq_one(
8853        connection: &mut Connection,
8854        queue: &AqQueueDesc,
8855        props: &AqMsgProps,
8856        enq_options: &AqEnqOptions,
8857    ) -> Result<Option<Vec<u8>>> {
8858        let runtime = build_io_runtime()?;
8859        runtime.block_on(async {
8860            let cx = Cx::current()
8861                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8862            connection.aq_enq_one(&cx, queue, props, enq_options).await
8863        })
8864    }
8865
8866    pub fn aq_deq_one(
8867        connection: &mut Connection,
8868        queue: &AqQueueDesc,
8869        deq_options: &AqDeqOptions,
8870    ) -> Result<AqDeqResult> {
8871        let runtime = build_io_runtime()?;
8872        runtime.block_on(async {
8873            let cx = Cx::current()
8874                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8875            connection.aq_deq_one(&cx, queue, deq_options).await
8876        })
8877    }
8878
8879    pub fn aq_enq_many(
8880        connection: &mut Connection,
8881        queue: &AqQueueDesc,
8882        props_list: &[AqMsgProps],
8883        enq_options: &AqEnqOptions,
8884    ) -> Result<Vec<Vec<u8>>> {
8885        let runtime = build_io_runtime()?;
8886        runtime.block_on(async {
8887            let cx = Cx::current()
8888                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8889            connection
8890                .aq_enq_many(&cx, queue, props_list, enq_options)
8891                .await
8892        })
8893    }
8894
8895    pub fn aq_deq_many(
8896        connection: &mut Connection,
8897        queue: &AqQueueDesc,
8898        deq_options: &AqDeqOptions,
8899        max_num_messages: u32,
8900    ) -> Result<Vec<oracledb_protocol::thin::aq::AqDeqMessage>> {
8901        let runtime = build_io_runtime()?;
8902        runtime.block_on(async {
8903            let cx = Cx::current()
8904                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8905            connection
8906                .aq_deq_many(&cx, queue, deq_options, max_num_messages)
8907                .await
8908        })
8909    }
8910
8911    pub fn create_temp_lob(
8912        connection: &mut Connection,
8913        ora_type_num: u8,
8914        csfrm: u8,
8915    ) -> Result<LobReadResult> {
8916        let runtime = build_io_runtime()?;
8917        runtime.block_on(async {
8918            let cx = Cx::current()
8919                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8920            connection.create_temp_lob(&cx, ora_type_num, csfrm).await
8921        })
8922    }
8923
8924    pub fn write_lob(
8925        connection: &mut Connection,
8926        locator: &[u8],
8927        offset: u64,
8928        data: &[u8],
8929    ) -> Result<LobReadResult> {
8930        let runtime = build_io_runtime()?;
8931        runtime.block_on(async {
8932            let cx = Cx::current()
8933                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8934            connection.write_lob(&cx, locator, offset, data).await
8935        })
8936    }
8937
8938    pub fn trim_lob(
8939        connection: &mut Connection,
8940        locator: &[u8],
8941        new_size: u64,
8942    ) -> Result<LobReadResult> {
8943        let runtime = build_io_runtime()?;
8944        runtime.block_on(async {
8945            let cx = Cx::current()
8946                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8947            connection.trim_lob(&cx, locator, new_size).await
8948        })
8949    }
8950
8951    pub fn write_lob_with_timeout(
8952        connection: &mut Connection,
8953        locator: &[u8],
8954        offset: u64,
8955        data: &[u8],
8956        timeout_ms: Option<u32>,
8957    ) -> Result<LobReadResult> {
8958        let runtime = build_io_runtime()?;
8959        runtime.block_on(async {
8960            let cx = Cx::current()
8961                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8962            connection
8963                .write_lob_call_timeout(&cx, locator, offset, data, timeout_ms)
8964                .await
8965        })
8966    }
8967
8968    pub fn trim_lob_with_timeout(
8969        connection: &mut Connection,
8970        locator: &[u8],
8971        new_size: u64,
8972        timeout_ms: Option<u32>,
8973    ) -> Result<LobReadResult> {
8974        let runtime = build_io_runtime()?;
8975        runtime.block_on(async {
8976            let cx = Cx::current()
8977                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8978            connection
8979                .trim_lob_call_timeout(&cx, locator, new_size, timeout_ms)
8980                .await
8981        })
8982    }
8983
8984    pub fn free_temp_lobs(connection: &mut Connection, locators: &[Vec<u8>]) -> Result<()> {
8985        let runtime = build_io_runtime()?;
8986        runtime.block_on(async {
8987            let cx = Cx::current()
8988                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
8989            connection.free_temp_lobs(&cx, locators).await
8990        })
8991    }
8992
8993    pub fn free_temp_lobs_with_timeout(
8994        connection: &mut Connection,
8995        locators: &[Vec<u8>],
8996        timeout_ms: Option<u32>,
8997    ) -> Result<()> {
8998        let runtime = build_io_runtime()?;
8999        runtime.block_on(async {
9000            let cx = Cx::current()
9001                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9002            connection
9003                .free_temp_lobs_call_timeout(&cx, locators, timeout_ms)
9004                .await
9005        })
9006    }
9007
9008    pub fn direct_path_load(
9009        connection: &mut Connection,
9010        schema_name: &str,
9011        table_name: &str,
9012        column_names: &[String],
9013        rows: &[Vec<oracledb_protocol::dpl::DirectPathColumnValue>],
9014        batch_size: u32,
9015    ) -> Result<()> {
9016        let runtime = build_io_runtime()?;
9017        runtime.block_on(async {
9018            let cx = Cx::current()
9019                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9020            connection
9021                .direct_path_load(&cx, schema_name, table_name, column_names, rows, batch_size)
9022                .await
9023        })
9024    }
9025
9026    pub fn run_pipeline(
9027        connection: &mut Connection,
9028        requests: &[PipelineRequest],
9029        continue_on_error: bool,
9030    ) -> Result<Vec<Vec<u8>>> {
9031        let runtime = build_io_runtime()?;
9032        runtime.block_on(async {
9033            let cx = Cx::current()
9034                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9035            connection
9036                .run_pipeline(&cx, requests, continue_on_error)
9037                .await
9038        })
9039    }
9040
9041    pub fn run_pipeline_decoded(
9042        connection: &mut Connection,
9043        requests: &[PipelineRequest],
9044        continue_on_error: bool,
9045    ) -> Result<Vec<Result<QueryResult>>> {
9046        let runtime = build_io_runtime()?;
9047        runtime.block_on(async {
9048            let cx = Cx::current()
9049                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9050            connection
9051                .run_pipeline_decoded(&cx, requests, continue_on_error)
9052                .await
9053        })
9054    }
9055
9056    pub fn direct_path_prepare(
9057        connection: &mut Connection,
9058        schema_name: &str,
9059        table_name: &str,
9060        column_names: &[String],
9061    ) -> Result<oracledb_protocol::dpl::DirectPathPrepareResult> {
9062        let runtime = build_io_runtime()?;
9063        runtime.block_on(async {
9064            let cx = Cx::current()
9065                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9066            connection
9067                .direct_path_prepare(&cx, schema_name, table_name, column_names)
9068                .await
9069        })
9070    }
9071
9072    pub fn direct_path_load_prepared(
9073        connection: &mut Connection,
9074        prepare: &oracledb_protocol::dpl::DirectPathPrepareResult,
9075        rows: &[Vec<oracledb_protocol::dpl::DirectPathColumnValue>],
9076        batch_size: u32,
9077    ) -> Result<()> {
9078        let runtime = build_io_runtime()?;
9079        runtime.block_on(async {
9080            let cx = Cx::current()
9081                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9082            connection
9083                .direct_path_load_prepared(&cx, prepare, rows, batch_size)
9084                .await
9085        })
9086    }
9087
9088    #[doc(hidden)]
9089    pub fn __pyshim_drain_cancel_response(connection: &mut Connection) -> Result<()> {
9090        let runtime = build_io_runtime()?;
9091        runtime.block_on(async { connection.drain_cancel_response().await })
9092    }
9093
9094    /// Reconcile recovery after a blocking pyshim call received the complete
9095    /// ORA-01013 response triggered by a concurrent [`CancelHandle`].
9096    ///
9097    /// This is intentionally hidden: the caller must have parsed the complete
9098    /// TTC response as a structured ORA-01013 before invoking it. At that point
9099    /// `read_response_cancellable` has completed and disarmed its read guard,
9100    /// so there is nothing left to drain; only the handle's `BreakSent` phase
9101    /// remains. Resetting that phase makes the clean connection reusable.
9102    #[doc(hidden)]
9103    pub fn __pyshim_reconcile_completed_cancel_response(connection: &mut Connection) -> Result<()> {
9104        match connection.core.recovery.phase() {
9105            SessionRecoveryPhase::Ready => Ok(()),
9106            SessionRecoveryPhase::BreakSent => {
9107                connection.core.recovery.finish_drain_ready();
9108                Ok(())
9109            }
9110            SessionRecoveryPhase::InFlight | SessionRecoveryPhase::Draining => Err(
9111                Error::ConnectionClosed("cancel response is not complete".into()),
9112            ),
9113            SessionRecoveryPhase::Dead => {
9114                Err(Error::ConnectionClosed("connection is closed".into()))
9115            }
9116        }
9117    }
9118
9119    /// Blocking wrapper for [`Connection::supplement_json_column_metadata`].
9120    pub fn supplement_json_column_metadata(
9121        connection: &mut Connection,
9122        columns: &mut [ColumnMetadata],
9123        timeout_ms: Option<u32>,
9124    ) -> Result<()> {
9125        let runtime = build_io_runtime()?;
9126        runtime.block_on(async {
9127            let cx = Cx::current()
9128                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9129            connection
9130                .supplement_json_column_metadata(&cx, columns, timeout_ms)
9131                .await
9132        })
9133    }
9134
9135    pub fn close(connection: Connection) -> Result<()> {
9136        let runtime = build_io_runtime()?;
9137        runtime.block_on(async {
9138            let cx = Cx::current()
9139                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9140            connection.close(&cx).await
9141        })
9142    }
9143}
9144
9145/// Construct a fresh single-threaded Asupersync runtime with a native reactor.
9146///
9147/// This is the heavy path: it creates an epoll reactor and spawns a worker OS
9148/// thread. It is only called once per thread by [`io_runtime`], which caches
9149/// the result; callers should use [`build_io_runtime`] (the cached accessor)
9150/// rather than this directly.
9151fn new_io_runtime() -> Result<Runtime> {
9152    let reactor = reactor::create_reactor()?;
9153    RuntimeBuilder::current_thread()
9154        .with_reactor(reactor)
9155        .build()
9156        .map_err(|err| Error::Runtime(err.to_string()))
9157}
9158
9159/// Build a fresh single-thread asupersync runtime owned by a connection pool.
9160///
9161/// Unlike [`build_io_runtime`], which returns a thread-local runtime reused for
9162/// every blocking-facade call on a thread, the pool needs a *persistent, owned*
9163/// runtime whose worker thread hosts the region-owned reaper task for the pool's
9164/// whole lifetime. Each call returns a brand-new runtime; the pool stores it and
9165/// drops it (shutting the reaper down) when the last pool handle is dropped.
9166///
9167/// The worker thread carries the `oracledb-pool-bg` name prefix (the same name
9168/// the old detached worker used) so it is identifiable in stack dumps and so the
9169/// pool's threads are distinguishable from the shared blocking-facade runtime's.
9170pub(crate) fn new_pool_runtime() -> Result<Runtime> {
9171    let reactor = reactor::create_reactor()?;
9172    RuntimeBuilder::current_thread()
9173        .with_reactor(reactor)
9174        .thread_name_prefix("oracledb-pool-bg")
9175        .build()
9176        .map_err(|err| Error::Runtime(err.to_string()))
9177}
9178
9179thread_local! {
9180    /// One blocking-facade runtime per calling thread, built lazily on first
9181    /// use and reused for every subsequent `BlockingConnection` /
9182    /// `CancelHandle` call on that thread.
9183    ///
9184    /// The previous behaviour built a brand-new runtime — a fresh epoll reactor
9185    /// plus a worker OS thread that is spawned and immediately joined — on every
9186    /// single call. For the synchronous facade, which the PyO3 shim drives for
9187    /// every suite operation, that fixed per-call cost dominated cheap
9188    /// operations like `select 1 from dual`. Caching the runtime per thread
9189    /// removes that overhead from every call after the first.
9190    ///
9191    /// Correctness is preserved: each `Runtime::block_on` still installs a fresh
9192    /// request-scoped `Cx` (with `Budget::INFINITE`) and runtime/Cx guards for
9193    /// the duration of the polled future, so cancellation and context semantics
9194    /// are unchanged. The connection's socket re-registers (`rearm`) with the
9195    /// persistent reactor on each call exactly as Asupersync's owned TCP halves
9196    /// are designed to; this is strictly less work than dropping and rebuilding
9197    /// a reactor every call. The runtime is current-thread, so it never crosses
9198    /// threads, and it lives for the thread's lifetime.
9199    static IO_RUNTIME: std::cell::RefCell<Option<Runtime>> =
9200        const { std::cell::RefCell::new(None) };
9201}
9202
9203/// Return this thread's cached blocking-facade runtime, building it on first
9204/// use. The returned `Runtime` is a cheap `Arc`-backed clone of the cached
9205/// instance; cloning does not spawn threads or create reactors. Behaviourally
9206/// equivalent to constructing a runtime per call, minus the per-call build cost.
9207fn build_io_runtime() -> Result<Runtime> {
9208    IO_RUNTIME.with(|slot| {
9209        if let Some(runtime) = slot.borrow().as_ref() {
9210            return Ok(runtime.clone());
9211        }
9212        let runtime = new_io_runtime()?;
9213        *slot.borrow_mut() = Some(runtime.clone());
9214        Ok(runtime)
9215    })
9216}
9217
9218/// Run a blocking-facade operation on this thread's cached I/O runtime,
9219/// passing it the ambient [`Cx`] installed by [`Runtime::block_on`].
9220pub(crate) fn block_on_io<F, Fut, T>(operation: F) -> Result<T>
9221where
9222    F: FnOnce(Cx) -> Fut,
9223    Fut: std::future::Future<Output = Result<T>>,
9224{
9225    let runtime = build_io_runtime()?;
9226    runtime.block_on(async {
9227        let cx = Cx::current()
9228            .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
9229        operation(cx).await
9230    })
9231}
9232
9233/// Runs a connection future to completion on a blocking runtime, passing it the
9234/// ambient [`Cx`] (shared shape of the `BlockingConnection` wrappers).
9235#[cfg(feature = "arrow")]
9236pub(crate) fn block_on_connection<F, Fut, T>(operation: F) -> Result<T>
9237where
9238    F: FnOnce(Cx) -> Fut,
9239    Fut: std::future::Future<Output = Result<T>>,
9240{
9241    block_on_io(operation)
9242}
9243
9244#[derive(Clone, Debug, Eq, PartialEq)]
9245struct IncomingPacket {
9246    packet_type: u8,
9247    packet_flags: u8,
9248    payload: Vec<u8>,
9249}
9250
9251async fn lock_write<W>(
9252    cx: &Cx,
9253    write: &Arc<AsyncMutex<W>>,
9254) -> Result<asupersync::sync::OwnedMutexGuard<W>>
9255where
9256    W: AsyncWrite + std::fmt::Debug + Unpin,
9257{
9258    // Borrowed mutex guards have been !Send since asupersync 0.3.5 because their
9259    // thread-local lock-order state must be released on the acquiring thread.
9260    // A write may await I/O, so retain the connection's Send future contract
9261    // with an Arc-backed owned guard while preserving write serialization.
9262    asupersync::sync::OwnedMutexGuard::lock(Arc::clone(write), cx)
9263        .await
9264        .map_err(|err| Error::Runtime(err.to_string()))
9265}
9266
9267async fn write_all_shared<W>(cx: &Cx, write: &Arc<AsyncMutex<W>>, packet: &[u8]) -> Result<()>
9268where
9269    W: AsyncWrite + std::fmt::Debug + Unpin,
9270{
9271    let mut guard = lock_write(cx, write).await?;
9272    guard.write_all(packet).await?;
9273    guard.flush().await?;
9274    Ok(())
9275}
9276
9277async fn shutdown_write_shared<W>(cx: &Cx, write: &Arc<AsyncMutex<W>>) -> Result<()>
9278where
9279    W: AsyncWrite + std::fmt::Debug + Unpin,
9280{
9281    let mut guard = lock_write(cx, write).await?;
9282    guard.shutdown().await?;
9283    Ok(())
9284}
9285
9286async fn send_data_packet_shared<W>(
9287    cx: &Cx,
9288    write: &Arc<AsyncMutex<W>>,
9289    payload: &[u8],
9290    sdu: usize,
9291) -> Result<()>
9292where
9293    W: AsyncWrite + std::fmt::Debug + Unpin,
9294{
9295    let mut guard = lock_write(cx, write).await?;
9296    send_data_packet(&mut *guard, payload, sdu).await
9297}
9298
9299async fn send_data_packet_shared_with_width<W>(
9300    cx: &Cx,
9301    write: &Arc<AsyncMutex<W>>,
9302    payload: &[u8],
9303    sdu: usize,
9304    width: PacketLengthWidth,
9305) -> Result<()>
9306where
9307    W: AsyncWrite + std::fmt::Debug + Unpin,
9308{
9309    let mut guard = lock_write(cx, write).await?;
9310    send_data_packet_with_flags_and_width(&mut *guard, payload, sdu, 0, 0, width).await
9311}
9312
9313async fn send_data_packet_shared_with_flags<W>(
9314    cx: &Cx,
9315    write: &Arc<AsyncMutex<W>>,
9316    payload: &[u8],
9317    sdu: usize,
9318    first_packet_flags: u16,
9319    last_packet_flags: u16,
9320) -> Result<()>
9321where
9322    W: AsyncWrite + std::fmt::Debug + Unpin,
9323{
9324    let mut guard = lock_write(cx, write).await?;
9325    send_data_packet_with_flags(
9326        &mut *guard,
9327        payload,
9328        sdu,
9329        first_packet_flags,
9330        last_packet_flags,
9331    )
9332    .await
9333}
9334
9335async fn send_marker_shared<W>(cx: &Cx, write: &Arc<AsyncMutex<W>>, marker_type: u8) -> Result<()>
9336where
9337    W: AsyncWrite + std::fmt::Debug + Unpin,
9338{
9339    let mut guard = lock_write(cx, write).await?;
9340    send_marker(&mut *guard, marker_type).await
9341}
9342
9343fn lock_write_for_recovery<W>(
9344    write: &Arc<AsyncMutex<W>>,
9345) -> Result<asupersync::sync::OwnedMutexGuard<W>>
9346where
9347    W: AsyncWrite + std::fmt::Debug + Unpin,
9348{
9349    asupersync::sync::OwnedMutexGuard::try_lock(Arc::clone(write)).map_err(|err| match err {
9350        asupersync::sync::TryLockError::Locked => Error::ConnectionClosed(
9351            "write lock unavailable while recovering from cancellation".into(),
9352        ),
9353        asupersync::sync::TryLockError::Poisoned => {
9354            Error::ConnectionClosed("write lock poisoned while recovering from cancellation".into())
9355        }
9356    })
9357}
9358
9359pub(crate) async fn send_marker_recovery<W>(
9360    write: &Arc<AsyncMutex<W>>,
9361    marker_type: u8,
9362) -> Result<()>
9363where
9364    W: AsyncWrite + std::fmt::Debug + Unpin,
9365{
9366    let mut guard = lock_write_for_recovery(write)?;
9367    send_marker(&mut *guard, marker_type).await
9368}
9369
9370async fn send_data_packet<W>(stream: &mut W, payload: &[u8], sdu: usize) -> Result<()>
9371where
9372    W: AsyncWrite + Unpin,
9373{
9374    send_data_packet_with_flags(stream, payload, sdu, 0, 0).await
9375}
9376
9377/// Sends a TTC payload as one or more data packets, applying
9378/// `first_packet_flags` to the first packet and `last_packet_flags` to the
9379/// last (combined when the payload fits a single packet) -- the WriteBuffer
9380/// `_data_flags` semantics the pipeline framing relies on (BEGIN_PIPELINE on
9381/// the packet carrying the begin piggyback, END_OF_REQUEST on a message's
9382/// final packet).
9383async fn send_data_packet_with_flags<W>(
9384    stream: &mut W,
9385    payload: &[u8],
9386    sdu: usize,
9387    first_packet_flags: u16,
9388    last_packet_flags: u16,
9389) -> Result<()>
9390where
9391    W: AsyncWrite + Unpin,
9392{
9393    send_data_packet_with_flags_and_width(
9394        stream,
9395        payload,
9396        sdu,
9397        first_packet_flags,
9398        last_packet_flags,
9399        PacketLengthWidth::Large32,
9400    )
9401    .await
9402}
9403
9404async fn send_data_packet_with_flags_and_width<W>(
9405    stream: &mut W,
9406    payload: &[u8],
9407    sdu: usize,
9408    first_packet_flags: u16,
9409    last_packet_flags: u16,
9410    width: PacketLengthWidth,
9411) -> Result<()>
9412where
9413    W: AsyncWrite + Unpin,
9414{
9415    let max_payload = sdu.saturating_sub(TNS_DATA_PACKET_OVERHEAD).max(1);
9416    let chunk_count = payload.chunks(max_payload).len();
9417    for (index, chunk) in payload.chunks(max_payload).enumerate() {
9418        let mut flags = 0u16;
9419        if index == 0 {
9420            flags |= first_packet_flags;
9421        }
9422        if index + 1 == chunk_count {
9423            flags |= last_packet_flags;
9424        }
9425        let packet = encode_packet(TNS_PACKET_TYPE_DATA, 0, Some(flags), chunk, width)?;
9426        stream.write_all(&packet).await?;
9427    }
9428    // The full request payload is now written to the socket. A cancellation that
9429    // lands on the trailing flush (asupersync's `poll_flush` also returns
9430    // `Io(Interrupted,"cancelled")`) has NOT lost the request — the bytes are
9431    // already on the wire, and flush is a formality on an already-buffered
9432    // socket. Swallow that specific cancellation so the round-trip proceeds to
9433    // its cancellation-aware read, which surfaces the typed `Error::Cancelled`
9434    // and arms break-and-drain recovery. Without this, a cancel racing the flush
9435    // leaked a raw `Io(Interrupted)` from the write path, bypassing the read-side
9436    // cancellation typing entirely. Any other flush error still propagates.
9437    match stream.flush().await {
9438        Ok(()) => {}
9439        Err(err) if is_asupersync_cancellation(&err) => {}
9440        Err(err) => return Err(err.into()),
9441    }
9442    Ok(())
9443}
9444
9445struct DataResponse {
9446    payload: Vec<u8>,
9447    flush_out_binds: bool,
9448}
9449
9450#[cfg(test)]
9451async fn read_data_response<R, W>(
9452    read: &mut R,
9453    cx: &Cx,
9454    write: &Arc<AsyncMutex<W>>,
9455) -> Result<Vec<u8>>
9456where
9457    R: AsyncRead + Unpin,
9458    W: AsyncWrite + std::fmt::Debug + Unpin,
9459{
9460    read_data_response_with_limits(read, cx, write, ProtocolLimits::DEFAULT).await
9461}
9462
9463async fn read_data_response_with_limits<R, W>(
9464    read: &mut R,
9465    cx: &Cx,
9466    write: &Arc<AsyncMutex<W>>,
9467    limits: ProtocolLimits,
9468) -> Result<Vec<u8>>
9469where
9470    R: AsyncRead + Unpin,
9471    W: AsyncWrite + std::fmt::Debug + Unpin,
9472{
9473    Ok(
9474        read_data_response_boundary_with_limits(read, cx, write, false, limits)
9475            .await?
9476            .payload,
9477    )
9478}
9479
9480const ASUPERSYNC_TLS_MISSING_CLOSE_NOTIFY: &str = "tls connection closed without close_notify";
9481
9482#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9483enum SessionCloseDisposition {
9484    ResponseComplete,
9485    PeerHardClosed,
9486}
9487
9488fn is_missing_tls_close_notify(error: &std::io::Error) -> bool {
9489    error.kind() == std::io::ErrorKind::UnexpectedEof
9490        && error.to_string() == ASUPERSYNC_TLS_MISSING_CLOSE_NOTIFY
9491}
9492
9493/// Read adapter for the one terminal LOGOFF response.
9494///
9495/// It converts Asupersync's exact missing-`close_notify` signal into ordinary
9496/// EOF only when no application byte has yet been delivered through the
9497/// adapter. The surrounding response reader then reports its usual short-read
9498/// error, which [`read_session_close_response_with_limits`] recognizes via the
9499/// flag below. Once even one byte has arrived, the signal passes through
9500/// unchanged so a partial TNS header or payload can never look like a clean
9501/// session close.
9502struct SessionCloseRead<'a, R> {
9503    inner: &'a mut R,
9504    application_bytes: usize,
9505    missing_close_notify_at_boundary: bool,
9506}
9507
9508impl<'a, R> SessionCloseRead<'a, R> {
9509    fn new(inner: &'a mut R) -> Self {
9510        Self {
9511            inner,
9512            application_bytes: 0,
9513            missing_close_notify_at_boundary: false,
9514        }
9515    }
9516}
9517
9518impl<R> AsyncRead for SessionCloseRead<'_, R>
9519where
9520    R: AsyncRead + Unpin,
9521{
9522    fn poll_read(
9523        self: std::pin::Pin<&mut Self>,
9524        context: &mut std::task::Context<'_>,
9525        buffer: &mut asupersync::io::ReadBuf<'_>,
9526    ) -> std::task::Poll<std::io::Result<()>> {
9527        let this = self.get_mut();
9528        let filled_before = buffer.filled().len();
9529        match std::pin::Pin::new(&mut *this.inner).poll_read(context, buffer) {
9530            std::task::Poll::Ready(Ok(())) => {
9531                this.application_bytes += buffer.filled().len() - filled_before;
9532                std::task::Poll::Ready(Ok(()))
9533            }
9534            std::task::Poll::Ready(Err(error))
9535                if this.application_bytes == 0 && is_missing_tls_close_notify(&error) =>
9536            {
9537                this.missing_close_notify_at_boundary = true;
9538                std::task::Poll::Ready(Ok(()))
9539            }
9540            other => other,
9541        }
9542    }
9543}
9544
9545/// Read the terminal LOGOFF response while accepting Oracle's bare TCP close
9546/// at the empty response boundary. Every ordinary operation, including the
9547/// pre-ACCEPT connect phase, continues to use the strict readers above/below.
9548async fn read_session_close_response_with_limits<R, W, P>(
9549    read: &mut R,
9550    cx: &Cx,
9551    write: &Arc<AsyncMutex<W>>,
9552    classic: bool,
9553    probe: &P,
9554    limits: ProtocolLimits,
9555) -> Result<SessionCloseDisposition>
9556where
9557    R: AsyncRead + Unpin,
9558    W: AsyncWrite + std::fmt::Debug + Unpin,
9559    P: Fn(&[u8]) -> bool,
9560{
9561    let mut close_read = SessionCloseRead::new(read);
9562    let result = if classic {
9563        read_classic_data_response_probed_with_limits(&mut close_read, cx, write, probe, limits)
9564            .await
9565            .map(|_| SessionCloseDisposition::ResponseComplete)
9566    } else {
9567        read_data_response_with_limits(&mut close_read, cx, write, limits)
9568            .await
9569            .map(|_| SessionCloseDisposition::ResponseComplete)
9570    };
9571    match result {
9572        Err(_) if close_read.missing_close_notify_at_boundary => {
9573            Ok(SessionCloseDisposition::PeerHardClosed)
9574        }
9575        other => other,
9576    }
9577}
9578
9579/// Accumulates DATA packets for one classic (pre-END_OF_RESPONSE)
9580/// connect-phase response until the payload's terminal message is complete.
9581/// Used only for the pre-23ai protocol-negotiation / data-types / auth round
9582/// trips, where END_OF_RESPONSE framing is not negotiated and completion is
9583/// message-driven (reference messages/base.pyx `Message.process`).
9584///
9585/// MARKER packets run the same reset dance as the post-connect readers: a
9586/// pre-23ai server answers a failed classic login (e.g. wrong password) with
9587/// a break MARKER *before* the ERROR response, so without the reset exchange
9588/// the caller would surface a misleading `UnexpectedPacket(MARKER)` instead
9589/// of the real ORA-01017 (reference packet.pyx: markers are handled uniformly
9590/// on every read, including the connect-phase auth round trips).
9591async fn read_classic_data_response_with_limits<R, W>(
9592    read: &mut R,
9593    cx: &Cx,
9594    write: &Arc<AsyncMutex<W>>,
9595    limits: ProtocolLimits,
9596) -> Result<Vec<u8>>
9597where
9598    R: AsyncRead + Unpin,
9599    W: AsyncWrite + std::fmt::Debug + Unpin,
9600{
9601    let mut response = Vec::new();
9602    let mut pending_packet: Option<IncomingPacket> = None;
9603    let mut after_reset = false;
9604    loop {
9605        let packet = match pending_packet.take() {
9606            Some(packet) => packet,
9607            None => read_packet_with_limits(read, PacketLengthWidth::Large32, limits).await?,
9608        };
9609        if packet.packet_type == TNS_PACKET_TYPE_MARKER {
9610            pending_packet =
9611                reset_after_marker_with_limits(read, cx, write, &packet, limits).await?;
9612            after_reset = true;
9613            continue;
9614        }
9615        if packet.packet_type != TNS_PACKET_TYPE_DATA {
9616            return Err(Error::UnexpectedPacket(packet.packet_type));
9617        }
9618        let payload =
9619            packet
9620                .payload
9621                .get(2..)
9622                .ok_or(oracledb_protocol::ProtocolError::TtcDecode(
9623                    "missing data packet flags",
9624                ))?;
9625        let combined = response.len().checked_add(payload.len()).ok_or(
9626            oracledb_protocol::ProtocolError::ResourceLimit {
9627                limit: "response_bytes",
9628                observed: usize::MAX,
9629                maximum: limits.max_response_bytes,
9630            },
9631        )?;
9632        limits.check_response_bytes(combined)?;
9633        response.extend_from_slice(payload);
9634        if (after_reset && post_reset_packet_ends_response(payload))
9635            || classic_connect_response_is_complete(&response, limits)?
9636        {
9637            return Ok(response);
9638        }
9639    }
9640}
9641
9642/// Probe predicate for classic (pre-END_OF_RESPONSE) response reassembly:
9643/// whether a parse attempt over the accumulated payload says the response is
9644/// complete. `TtcDecode` is the decoder's "ran out of bytes / short read"
9645/// error — the response needs more packets. ANY other outcome means the
9646/// parser consumed a full response: `Ok` is the happy path, a
9647/// `ServerError`/`ServerErrorInfo` means the terminal ERROR message was
9648/// reached (the caller's real parse will surface it), and structural errors
9649/// (`UnknownMessageType`, `ResourceLimit`, ...) are returned to the caller by
9650/// its real parse instead of hanging the read loop forever.
9651fn response_complete<T>(result: &oracledb_protocol::Result<T>) -> bool {
9652    !matches!(result, Err(oracledb_protocol::ProtocolError::TtcDecode(_)))
9653}
9654
9655/// Accumulates DATA packets for one classic (pre-END_OF_RESPONSE) post-connect
9656/// response, deciding completion with the caller's `probe` over the
9657/// accumulated payload (see
9658/// [`ConnectionCore::read_data_response_probed`]). MARKER packets run the
9659/// same reset dance as [`read_data_response_boundary_seeded`]; after a reset
9660/// the terminal-message-byte relaxation ([`post_reset_packet_ends_response`])
9661/// also ends the response, exactly like the flag-framed reader.
9662async fn read_classic_data_response_probed_with_limits<R, W, P>(
9663    read: &mut R,
9664    cx: &Cx,
9665    write: &Arc<AsyncMutex<W>>,
9666    probe: &P,
9667    limits: ProtocolLimits,
9668) -> Result<Vec<u8>>
9669where
9670    R: AsyncRead + Unpin,
9671    W: AsyncWrite + std::fmt::Debug + Unpin,
9672    P: Fn(&[u8]) -> bool,
9673{
9674    let mut response = Vec::new();
9675    read_classic_data_response_probed_into(read, cx, write, probe, limits, &mut response).await?;
9676    Ok(response)
9677}
9678
9679/// The reassembly loop of [`read_classic_data_response_probed_with_limits`],
9680/// appending onto an existing buffer so the flush-out-binds continuation can
9681/// probe the COMBINED payload (the parser always parses from the response
9682/// start).
9683async fn read_classic_data_response_probed_into<R, W, P>(
9684    read: &mut R,
9685    cx: &Cx,
9686    write: &Arc<AsyncMutex<W>>,
9687    probe: &P,
9688    limits: ProtocolLimits,
9689    response: &mut Vec<u8>,
9690) -> Result<()>
9691where
9692    R: AsyncRead + Unpin,
9693    W: AsyncWrite + std::fmt::Debug + Unpin,
9694    P: Fn(&[u8]) -> bool,
9695{
9696    let mut pending_packet: Option<IncomingPacket> = None;
9697    let mut after_reset = false;
9698    loop {
9699        let packet = match pending_packet.take() {
9700            Some(packet) => packet,
9701            None => read_packet_with_limits(read, PacketLengthWidth::Large32, limits).await?,
9702        };
9703        if packet.packet_type == TNS_PACKET_TYPE_MARKER {
9704            pending_packet =
9705                reset_after_marker_with_limits(read, cx, write, &packet, limits).await?;
9706            after_reset = true;
9707            continue;
9708        }
9709        if packet.packet_type != TNS_PACKET_TYPE_DATA {
9710            return Err(Error::UnexpectedPacket(packet.packet_type));
9711        }
9712        let payload =
9713            packet
9714                .payload
9715                .get(2..)
9716                .ok_or(oracledb_protocol::ProtocolError::TtcDecode(
9717                    "missing data packet flags",
9718                ))?;
9719        let combined = response.len().checked_add(payload.len()).ok_or(
9720            oracledb_protocol::ProtocolError::ResourceLimit {
9721                limit: "response_bytes",
9722                observed: usize::MAX,
9723                maximum: limits.max_response_bytes,
9724            },
9725        )?;
9726        limits.check_response_bytes(combined)?;
9727        response.extend_from_slice(payload);
9728        if (after_reset && post_reset_packet_ends_response(payload)) || probe(response) {
9729            return Ok(());
9730        }
9731    }
9732}
9733
9734/// Classic (pre-END_OF_RESPONSE) counterpart of
9735/// [`read_data_response_flushing_out_binds_with_limits`]: reads one probed
9736/// response and, while it ends at a FLUSH_OUT_BINDS request (terminal message
9737/// byte, same detection as the flag-framed path), answers it and keeps
9738/// accumulating — probing the combined payload — until the real response is
9739/// complete.
9740async fn read_classic_data_response_flushing_out_binds_probed_with_limits<R, W, P>(
9741    read: &mut R,
9742    cx: &Cx,
9743    write: &Arc<AsyncMutex<W>>,
9744    sdu: usize,
9745    probe: &P,
9746    limits: ProtocolLimits,
9747) -> Result<Vec<u8>>
9748where
9749    R: AsyncRead + Unpin,
9750    W: AsyncWrite + std::fmt::Debug + Unpin,
9751    P: Fn(&[u8]) -> bool,
9752{
9753    let mut payload = Vec::new();
9754    read_classic_data_response_probed_into(read, cx, write, probe, limits, &mut payload).await?;
9755    while matches!(payload.last(), Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS)) {
9756        observe_cancellation_between_round_trips(cx)?;
9757        payload.pop();
9758        send_data_packet_shared(cx, write, &[TNS_MSG_TYPE_FLUSH_OUT_BINDS], sdu).await?;
9759        read_classic_data_response_probed_into(read, cx, write, probe, limits, &mut payload)
9760            .await?;
9761    }
9762    Ok(payload)
9763}
9764
9765/// Upper bound on how long the post-break recovery drain may take before the
9766/// driver gives up and declares the connection dead. Mirrors the reference's
9767/// "second timeout while recovering" disconnect (protocol.pyx:454-458): the
9768/// first timeout was the user's `call_timeout`; this guards the *recovery*
9769/// read so a server that never answers the BREAK cannot hang the caller
9770/// forever. Reuses the same 5 s ceiling as [`Connection::drain_cancel_response`].
9771const BREAK_DRAIN_RECOVERY_TIMEOUT: Duration = Duration::from_secs(5);
9772
9773/// Sends a BREAK marker and then **drains** the server's entire break response
9774/// so the wire stream is left at a clean message boundary, exactly as
9775/// python-oracledb does on a call timeout (`_break_external()` then
9776/// `_receive_packet()` / `_reset()`, protocol.pyx:449-451, 507-557).
9777///
9778/// The break response is multi-stage and racy on the wire (confirmed by live
9779/// trace against Oracle 23/26ai): when the server is mid-call it may flush the
9780/// **in-flight response** of the timed-out call *first* — a complete DATA
9781/// response carrying its own end-of-response flag — and only *then* send the
9782/// break-acknowledge **MARKER**, the **RESET** handshake, and the **trailing
9783/// error packet** (ORA-01013 "user requested cancel"). A naive
9784/// `read_data_response` stops at the in-flight response's end-of-response and
9785/// leaves the MARKER + ORA-01013 in the socket, where the *next* operation
9786/// misreads them (it surfaces ORA-01013 / desyncs). The reference avoids this
9787/// because its `_reset()` is what clears `_break_in_progress`, and it always
9788/// runs `_reset()` (consuming the MARKER, the RESET marker, and the trailing
9789/// error packet) before the connection is considered recovered.
9790///
9791/// So this drain does NOT stop at the first end-of-response: it discards any
9792/// in-flight DATA responses until it meets the break-acknowledge MARKER, runs
9793/// the RESET dance via [`reset_after_marker`] (send RESET, discard packets until
9794/// the server RESET marker), and then consumes the trailing error response to
9795/// its end-of-response boundary. Everything read here is discarded — it is the
9796/// dead remains of the cancelled call, not a result for any caller.
9797///
9798/// On success (`Ok(())`) the stream is clean and the connection is reusable. If
9799/// the drain errors or its bounded *secondary* timeout fires, the wire could not
9800/// be left clean, so the connection must be discarded — the error is surfaced as
9801/// [`Error::ConnectionClosed`], which is [`Error::is_connection_lost`].
9802#[allow(dead_code)]
9803async fn break_and_drain_wire<R, W>(
9804    read: &mut R,
9805    write: &Arc<AsyncMutex<W>>,
9806    recovery_timeout: Duration,
9807) -> Result<()>
9808where
9809    R: AsyncRead + Unpin,
9810    W: AsyncWrite + std::fmt::Debug + Unpin,
9811{
9812    let result = time::timeout(
9813        time::wall_now(),
9814        recovery_timeout,
9815        break_and_drain_wire_unbounded(read, write),
9816    )
9817    .await
9818    .ok();
9819    classify_recovery_result(RecoveryWireAction::BreakAndDrain, result)
9820}
9821
9822async fn break_and_drain_wire_unbounded<R, W>(
9823    read: &mut R,
9824    write: &Arc<AsyncMutex<W>>,
9825) -> Result<()>
9826where
9827    R: AsyncRead + Unpin,
9828    W: AsyncWrite + std::fmt::Debug + Unpin,
9829{
9830    break_and_drain_wire_unbounded_with_limits(read, write, ProtocolLimits::DEFAULT, false).await
9831}
9832
9833async fn break_and_drain_wire_unbounded_with_limits<R, W>(
9834    read: &mut R,
9835    write: &Arc<AsyncMutex<W>>,
9836    limits: ProtocolLimits,
9837    classic: bool,
9838) -> Result<()>
9839where
9840    R: AsyncRead + Unpin,
9841    W: AsyncWrite + std::fmt::Debug + Unpin,
9842{
9843    // 1) Send the BREAK marker (reference `_break_external`).
9844    send_marker_recovery(write, TNS_MARKER_TYPE_BREAK)
9845        .await
9846        .map_err(|err| {
9847            Error::ConnectionClosed(format!(
9848                "failed to send break marker on call timeout: {err}"
9849            ))
9850        })?;
9851    // 2) Drain the whole break response.
9852    drain_break_response_recovery_with_limits(read, write, limits, classic).await
9853}
9854
9855/// Sends a BREAK and drains the server's cancel response so the wire is left at
9856/// a clean boundary, for an **explicit** user cancel (rather than a call
9857/// timeout). This is the wire half of [`Connection::cancel`].
9858///
9859/// The wire sequence a user cancel triggers is byte-for-byte the same as a call
9860/// timeout — python-oracledb routes both through `_break_external()` +
9861/// `_reset()` (`cancel()` is `connection.pyx:291` -> `_break_external`;
9862/// `protocol.pyx:533-557`). So this delegates straight to
9863/// [`break_and_drain_wire`] (no duplicated drain loop): the BREAK marker, the
9864/// discard of any in-flight DATA responses, the RESET handshake, and the
9865/// consumption of the trailing ORA-01013 error all happen there.
9866///
9867/// The reference would send an out-of-band (urgent-TCP) break first when
9868/// `supports_oob` is negotiated; when OOB is unavailable it falls back to this
9869/// in-band INTERRUPT/BREAK marker (`protocol.pyx:56-69`). Asupersync's
9870/// `TcpStream` does not expose `send(MSG_OOB)`, so we always take the in-band
9871/// path — which the reference itself uses on every platform where OOB is off
9872/// (e.g. Windows, or `disable_oob`), and which the server handles identically.
9873///
9874/// `Ok(())` means the wire is clean and the connection is reusable; the caller
9875/// surfaces [`Error::Cancelled`]. On a failed drain the error is
9876/// [`Error::ConnectionClosed`] and the connection must be discarded.
9877#[allow(dead_code)]
9878async fn cancel_and_drain_wire<R, W>(
9879    read: &mut R,
9880    write: &Arc<AsyncMutex<W>>,
9881    recovery_timeout: Duration,
9882) -> Result<()>
9883where
9884    R: AsyncRead + Unpin,
9885    W: AsyncWrite + std::fmt::Debug + Unpin,
9886{
9887    break_and_drain_wire(read, write, recovery_timeout).await
9888}
9889
9890/// Drains the server's cancel response **without** sending a BREAK first.
9891///
9892/// Used by the two-thread cancel path: a [`CancelHandle`] on a *separate* thread
9893/// has already sent the BREAK marker while the main thread was blocked inside a
9894/// query round trip. The wire now carries the same multi-stage cancel response a
9895/// timeout break would (the cancelled call's in-flight DATA response, the
9896/// break-ack MARKER, the RESET handshake, and the trailing ORA-01013), so this
9897/// reuses [`drain_break_response_recovery`] — the SAME drain
9898/// `break_and_drain_wire` runs — under the same bounded recovery timeout. It
9899/// just omits the `send_marker` BREAK that the handle thread already issued;
9900/// sending a second BREAK here would inject an extra marker the server answers
9901/// with an extra reset, desyncing the reused connection.
9902///
9903/// `Ok(())` leaves the wire clean and the connection reusable. A drain error or
9904/// a secondary timeout yields [`Error::ConnectionClosed`] (the connection must
9905/// be discarded), matching the break+drain failure semantics.
9906#[allow(dead_code)]
9907async fn drain_cancel_wire<R, W>(
9908    read: &mut R,
9909    write: &Arc<AsyncMutex<W>>,
9910    recovery_timeout: Duration,
9911) -> Result<()>
9912where
9913    R: AsyncRead + Unpin,
9914    W: AsyncWrite + std::fmt::Debug + Unpin,
9915{
9916    let result = time::timeout(
9917        time::wall_now(),
9918        recovery_timeout,
9919        drain_cancel_wire_unbounded(read, write),
9920    )
9921    .await
9922    .ok();
9923    classify_recovery_result(RecoveryWireAction::DrainCancel, result)
9924}
9925
9926async fn drain_cancel_wire_unbounded<R, W>(read: &mut R, write: &Arc<AsyncMutex<W>>) -> Result<()>
9927where
9928    R: AsyncRead + Unpin,
9929    W: AsyncWrite + std::fmt::Debug + Unpin,
9930{
9931    drain_cancel_wire_unbounded_with_limits(read, write, ProtocolLimits::DEFAULT, false).await
9932}
9933
9934async fn drain_cancel_wire_unbounded_with_limits<R, W>(
9935    read: &mut R,
9936    write: &Arc<AsyncMutex<W>>,
9937    limits: ProtocolLimits,
9938    classic: bool,
9939) -> Result<()>
9940where
9941    R: AsyncRead + Unpin,
9942    W: AsyncWrite + std::fmt::Debug + Unpin,
9943{
9944    drain_break_response_recovery_with_limits(read, write, limits, classic).await
9945}
9946
9947/// Drop-guard that marks a connection's recovery phase `BreakSent` if a
9948/// cancellable round-trip read future is **dropped while still in flight**.
9949///
9950/// This is the Scope-based cancel-on-drop half of the cancellation story: when a
9951/// fetch/execute future is raced by a `select!` or a `time::timeout` and the
9952/// losing branch is dropped, the request has already gone out but its response
9953/// is still arriving (or the server is still mid-call). Dropping the future ends
9954/// the `&mut Connection` borrow but leaves those bytes / that running call on the
9955/// wire. The guard's `Drop` records in the single recovery owner that the next
9956/// operation must first send a BREAK and drain (via [`cancel_and_drain_wire`])
9957/// before issuing its own request — so a cancelled fetch never poisons the
9958/// stream for the next one.
9959///
9960/// A read that completes normally calls `CancelDrainGuard::disarm` first, so
9961/// the common (uncancelled) path never arms the flag and pays nothing.
9962struct CancelDrainGuard {
9963    recovery: Arc<SessionRecovery>,
9964    armed: bool,
9965}
9966
9967impl CancelDrainGuard {
9968    /// Mark the response as in flight for the duration of a cancellable read.
9969    fn arm(recovery: Arc<SessionRecovery>) -> Result<Self> {
9970        recovery.begin_or_adopt_operation()?;
9971        Ok(Self {
9972            recovery,
9973            armed: true,
9974        })
9975    }
9976
9977    /// Disarm the guard after the read completed normally, so its `Drop` is a
9978    /// no-op and the next operation does not needlessly break + drain.
9979    fn disarm(&mut self) {
9980        self.recovery.complete_operation();
9981        self.armed = false;
9982    }
9983}
9984
9985impl Drop for CancelDrainGuard {
9986    fn drop(&mut self) {
9987        if self.armed {
9988            // The future was dropped mid-read (cancelled): tell the next
9989            // operation to break + drain the stranded server call first.
9990            self.recovery.mark_break_required();
9991        }
9992    }
9993}
9994
9995/// Reads and discards the full server response to a BREAK: any in-flight DATA
9996/// response(s) of the cancelled call, then the break-acknowledge MARKER, the
9997/// RESET handshake, and the trailing error packet — leaving the reader at a
9998/// clean boundary. See [`break_and_drain_wire`] for why stopping at the first
9999/// end-of-response is insufficient.
10000#[cfg(test)]
10001#[allow(dead_code)]
10002async fn drain_break_response_recovery<R, W>(read: &mut R, write: &Arc<AsyncMutex<W>>) -> Result<()>
10003where
10004    R: AsyncRead + Unpin,
10005    W: AsyncWrite + std::fmt::Debug + Unpin,
10006{
10007    drain_break_response_recovery_with_limits(read, write, ProtocolLimits::DEFAULT, false).await
10008}
10009
10010async fn drain_break_response_recovery_with_limits<R, W>(
10011    read: &mut R,
10012    write: &Arc<AsyncMutex<W>>,
10013    limits: ProtocolLimits,
10014    classic: bool,
10015) -> Result<()>
10016where
10017    R: AsyncRead + Unpin,
10018    W: AsyncWrite + std::fmt::Debug + Unpin,
10019{
10020    // Phase A: discard whole DATA responses until the break-acknowledge MARKER.
10021    // The server flushes the cancelled call's in-flight response first; each is
10022    // a complete DATA response (its own end-of-response) that we drop on the
10023    // floor. The MARKER is what drives the RESET handshake.
10024    let initial_marker = loop {
10025        let packet = read_packet_with_limits(read, PacketLengthWidth::Large32, limits).await?;
10026        match packet.packet_type {
10027            TNS_PACKET_TYPE_MARKER => break packet,
10028            TNS_PACKET_TYPE_DATA => {
10029                trace_connect_bytes("BREAK drain: discarded in-flight packet", &packet.payload);
10030                continue;
10031            }
10032            other => {
10033                // Packet-layer byte (header offset 4), NOT a TTC message
10034                // type: name the TNS packet type so triage is not steered
10035                // toward the application layer (bead
10036                // rust-oracledb-pre23ai-connect-z47u.3).
10037                return Err(Error::UnexpectedPacket(other));
10038            }
10039        }
10040    };
10041
10042    // Phase B: run the RESET dance (send RESET, discard packets until the server
10043    // RESET marker). `reset_after_marker` returns the first non-marker packet
10044    // after the RESET confirmation, if any — that is the head of the trailing
10045    // error response (ORA-01013).
10046    let pending =
10047        reset_after_marker_recovery_with_limits(read, write, &initial_marker, limits).await?;
10048
10049    // Phase C: consume the trailing error response to its end-of-response
10050    // boundary and discard it. Reuses the same boundary loop the normal read
10051    // path uses, seeded with the packet `reset_after_marker` already pulled.
10052    let trailing = read_data_response_boundary_from_recovery_with_limits(
10053        read, write, pending, limits, classic,
10054    )
10055    .await?;
10056    trace_connect_bytes("BREAK drain: trailing error response", &trailing.payload);
10057    Ok(())
10058}
10059
10060#[cfg(test)]
10061async fn read_data_response_flushing_out_binds<R, W>(
10062    read: &mut R,
10063    cx: &Cx,
10064    write: &Arc<AsyncMutex<W>>,
10065    sdu: usize,
10066) -> Result<Vec<u8>>
10067where
10068    R: AsyncRead + Unpin,
10069    W: AsyncWrite + std::fmt::Debug + Unpin,
10070{
10071    read_data_response_flushing_out_binds_with_limits(read, cx, write, sdu, ProtocolLimits::DEFAULT)
10072        .await
10073}
10074
10075async fn read_data_response_flushing_out_binds_with_limits<R, W>(
10076    read: &mut R,
10077    cx: &Cx,
10078    write: &Arc<AsyncMutex<W>>,
10079    sdu: usize,
10080    limits: ProtocolLimits,
10081) -> Result<Vec<u8>>
10082where
10083    R: AsyncRead + Unpin,
10084    W: AsyncWrite + std::fmt::Debug + Unpin,
10085{
10086    let mut response =
10087        read_data_response_boundary_with_limits(read, cx, write, false, limits).await?;
10088    let mut payload = response.payload;
10089    while response.flush_out_binds {
10090        observe_cancellation_between_round_trips(cx)?;
10091        if matches!(payload.last(), Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS)) {
10092            payload.pop();
10093        }
10094        send_data_packet_shared(cx, write, &[TNS_MSG_TYPE_FLUSH_OUT_BINDS], sdu).await?;
10095        response = read_data_response_boundary_with_limits(read, cx, write, false, limits).await?;
10096        let combined = payload.len().checked_add(response.payload.len()).ok_or(
10097            oracledb_protocol::ProtocolError::ResourceLimit {
10098                limit: "response_bytes",
10099                observed: usize::MAX,
10100                maximum: limits.max_response_bytes,
10101            },
10102        )?;
10103        limits.check_response_bytes(combined)?;
10104        payload.extend_from_slice(&response.payload);
10105    }
10106    Ok(payload)
10107}
10108
10109/// Returns whether this DATA packet carries the end of the TTC response, given
10110/// the packet's 2-byte data flags and its post-flags payload.
10111///
10112/// This mirrors the reference `Packet.has_end_of_response`
10113/// (impl/thin/packet.pyx:58-73). The end of a response is signalled either by
10114/// the `END_OF_RESPONSE` / `EOF` data flag, or by a trailing
10115/// `TNS_MSG_TYPE_END_OF_RESPONSE` (29 / 0x1d) byte that arrives **as its own
10116/// minimal packet** -- a packet whose entire post-flags payload is exactly that
10117/// one byte (reference condition `packet_size == PACKET_HEADER_SIZE + 3`).
10118///
10119/// The size guard is load-bearing for multi-packet wide-row results. Without it,
10120/// any DATA packet whose payload merely *happens to end* in byte 0x1d -- an
10121/// utterly ordinary value inside a NUMBER mantissa, a length prefix, or a text
10122/// byte -- would be misread as the end of the response. A wide (e.g. 20-column
10123/// NUMBER/VARCHAR2) single fetch of ~1500+ rows spans several network packets,
10124/// and a mid-stream packet boundary lands on a 0x1d byte often enough that the
10125/// reassembly loop terminated early, truncating the buffer. The TTC decoder then
10126/// mis-framed the continuation, surfacing as "encoded NUMBER too long" /
10127/// "truncated TTC payload" (bead rust-oracledb-n2s).
10128fn data_packet_ends_response(flags: u16, payload: &[u8]) -> bool {
10129    if flags
10130        & (oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE
10131            | oracledb_protocol::thin::TNS_DATA_FLAGS_EOF)
10132        != 0
10133    {
10134        return true;
10135    }
10136    // Fallback for servers that did not negotiate END_OF_RESPONSE framing: a
10137    // response that is a single minimal packet whose entire post-flags payload
10138    // is just the END_OF_RESPONSE marker, or just the FLUSH_OUT_BINDS marker
10139    // (which the reference also treats as end_of_response,
10140    // messages/base.pyx:1267-1269). The exact-length match is the load-bearing
10141    // guard: a multi-packet body packet that merely *ends* in one of these bytes
10142    // must NOT terminate the response.
10143    payload == [TNS_MSG_TYPE_END_OF_RESPONSE] || payload == [TNS_MSG_TYPE_FLUSH_OUT_BINDS]
10144}
10145
10146/// Whether a DATA packet read **after a RESET dance** ends the response, based
10147/// on its terminal TTC message byte alone.
10148///
10149/// After a BREAK/RESET the server stops using request-boundary framing: the
10150/// trailing packets of the break-recovery response do NOT carry the
10151/// `END_OF_RESPONSE` data flag (confirmed by live wire trace against Oracle
10152/// 23ai on the DML-RETURNING error path, test_1600 test_1612 / ORA-12899). The
10153/// server instead sends message-byte-framed packets — e.g. a `FLUSH_OUT_BINDS`
10154/// *request* (a DATA packet ending in byte 0x13) that expects a
10155/// `FLUSH_OUT_BINDS` reply, then the real error packet. The reference detects
10156/// the boundary while *processing* the message (`TNS_MSG_TYPE_FLUSH_OUT_BINDS`
10157/// and `TNS_MSG_TYPE_END_OF_RESPONSE` both set `end_of_response`,
10158/// messages/base.pyx:1267-1269), because its `_check_request_boundary` is off
10159/// for post-reset packets (protocol.pyx:896-906).
10160///
10161/// Unlike [`data_packet_ends_response`], this does NOT require the marker byte
10162/// to be the packet's sole byte — the FLUSH_OUT_BINDS request arrives as
10163/// `07 00 00 13`, the marker as the *last* byte. That is safe here precisely
10164/// because it is gated on the post-reset context, which carries no multi-packet
10165/// wide-row body (the bead rust-oracledb-n2s false-positive only arises on the
10166/// normal request-boundary-framed read path, which never sets `after_reset`).
10167fn post_reset_packet_ends_response(payload: &[u8]) -> bool {
10168    matches!(
10169        payload.last(),
10170        Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS) | Some(&TNS_MSG_TYPE_END_OF_RESPONSE)
10171    )
10172}
10173
10174/// Reads one boundary-delimited TTC response. While `in_pipeline` is set,
10175/// marker packets are silently dropped instead of triggering the
10176/// send-reset/await-reset dance -- the reference does the same while reading
10177/// pipelined responses (packet.pyx:346-370, protocol.pyx:889-906), since the
10178/// server emits a marker alongside an in-pipeline error without expecting a
10179/// reset exchange.
10180#[cfg(test)]
10181#[allow(dead_code)]
10182async fn read_data_response_boundary<R, W>(
10183    read: &mut R,
10184    cx: &Cx,
10185    write: &Arc<AsyncMutex<W>>,
10186    in_pipeline: bool,
10187) -> Result<DataResponse>
10188where
10189    R: AsyncRead + Unpin,
10190    W: AsyncWrite + std::fmt::Debug + Unpin,
10191{
10192    read_data_response_boundary_with_limits(read, cx, write, in_pipeline, ProtocolLimits::DEFAULT)
10193        .await
10194}
10195
10196async fn read_data_response_boundary_with_limits<R, W>(
10197    read: &mut R,
10198    cx: &Cx,
10199    write: &Arc<AsyncMutex<W>>,
10200    in_pipeline: bool,
10201    limits: ProtocolLimits,
10202) -> Result<DataResponse>
10203where
10204    R: AsyncRead + Unpin,
10205    W: AsyncWrite + std::fmt::Debug + Unpin,
10206{
10207    // Normal (23ai / END_OF_RESPONSE-framed) read path: never classic.
10208    read_data_response_boundary_seeded(read, Some(cx), write, in_pipeline, None, limits, false)
10209        .await
10210}
10211
10212/// Like [`read_data_response_boundary`] but seeds the reassembly loop with an
10213/// already-read `seed` packet (e.g. the trailing packet `reset_after_marker`
10214/// pulled past a RESET marker) before reading more from the wire. Used by the
10215/// break-drain path to consume the trailing error response. Always runs the
10216/// non-pipeline (reset-handling) variant.
10217#[cfg(test)]
10218#[allow(dead_code)]
10219async fn read_data_response_boundary_from_recovery<R, W>(
10220    read: &mut R,
10221    write: &Arc<AsyncMutex<W>>,
10222    seed: Option<IncomingPacket>,
10223) -> Result<DataResponse>
10224where
10225    R: AsyncRead + Unpin,
10226    W: AsyncWrite + std::fmt::Debug + Unpin,
10227{
10228    read_data_response_boundary_from_recovery_with_limits(
10229        read,
10230        write,
10231        seed,
10232        ProtocolLimits::DEFAULT,
10233        false,
10234    )
10235    .await
10236}
10237
10238async fn read_data_response_boundary_from_recovery_with_limits<R, W>(
10239    read: &mut R,
10240    write: &Arc<AsyncMutex<W>>,
10241    seed: Option<IncomingPacket>,
10242    limits: ProtocolLimits,
10243    classic: bool,
10244) -> Result<DataResponse>
10245where
10246    R: AsyncRead + Unpin,
10247    W: AsyncWrite + std::fmt::Debug + Unpin,
10248{
10249    read_data_response_boundary_seeded(read, None, write, false, seed, limits, classic).await
10250}
10251
10252async fn read_data_response_boundary_seeded<R, W>(
10253    read: &mut R,
10254    cx: Option<&Cx>,
10255    write: &Arc<AsyncMutex<W>>,
10256    in_pipeline: bool,
10257    seed: Option<IncomingPacket>,
10258    limits: ProtocolLimits,
10259    classic: bool,
10260) -> Result<DataResponse>
10261where
10262    R: AsyncRead + Unpin,
10263    W: AsyncWrite + std::fmt::Debug + Unpin,
10264{
10265    let mut response = Vec::new();
10266    let mut pending_packet = seed;
10267    // Set once this loop has run a RESET dance (reference `_reset`). After a
10268    // RESET the server stops using request-boundary (END_OF_RESPONSE data flag)
10269    // framing for the trailing error response: it sends message-byte-framed
10270    // packets, exactly like the reference's `message.process()` after
10271    // `_reset()`, where `_check_request_boundary` is off (protocol.pyx:819-821,
10272    // 896-906). So a post-reset packet whose payload ends in a terminal message
10273    // byte (FLUSH_OUT_BINDS / END_OF_RESPONSE) ends the response even without
10274    // the data flag. This relaxation is gated on `after_reset` so the wide-row
10275    // false-positive guard (bead rust-oracledb-n2s) on the normal framing path
10276    // is left entirely intact.
10277    let mut after_reset = false;
10278    loop {
10279        let packet = match pending_packet.take() {
10280            Some(packet) => packet,
10281            None => read_packet_with_limits(read, PacketLengthWidth::Large32, limits).await?,
10282        };
10283        if packet.packet_type == TNS_PACKET_TYPE_MARKER {
10284            if in_pipeline {
10285                trace_connect_bytes("MARKER packet skipped in pipeline", &packet.payload);
10286                continue;
10287            }
10288            pending_packet = match cx {
10289                Some(cx) => {
10290                    reset_after_marker_with_limits(read, cx, write, &packet, limits).await?
10291                }
10292                None => {
10293                    reset_after_marker_recovery_with_limits(read, write, &packet, limits).await?
10294                }
10295            };
10296            after_reset = true;
10297            continue;
10298        }
10299        if packet.packet_type != TNS_PACKET_TYPE_DATA {
10300            // Packet-layer byte (header offset 4), NOT a TTC message type:
10301            // name the TNS packet type so triage is not steered toward the
10302            // application layer (bead rust-oracledb-pre23ai-connect-z47u.3).
10303            return Err(Error::UnexpectedPacket(packet.packet_type));
10304        }
10305        let (data_flags, payload) = packet.payload.split_at_checked(2).ok_or(
10306            oracledb_protocol::ProtocolError::TtcDecode("missing data packet flags"),
10307        )?;
10308        let flags = u16::from_be_bytes(
10309            data_flags
10310                .try_into()
10311                .map_err(|_| oracledb_protocol::ProtocolError::TtcDecode("invalid flags"))?,
10312        );
10313        let ends = data_packet_ends_response(flags, payload)
10314            || (after_reset && post_reset_packet_ends_response(payload));
10315        // Single-packet passthrough (bead rust-oracledb-0n0): when the whole
10316        // response is ONE DATA packet (nothing accumulated yet AND this packet
10317        // ends the response), move the packet's owned buffer into `response` and
10318        // strip the 2 flag bytes in place, instead of allocating a fresh Vec and
10319        // copying the entire payload into it. The flag-strip is preserved (drain
10320        // removes the same 2 leading bytes), the end-of-response decision is the
10321        // exact same `ends` computed above, and the FLUSH_OUT_BINDS terminal-byte
10322        // detection below sees an identical byte stream. The multi-packet path is
10323        // unchanged (it must reassemble, so it extends).
10324        if ends && response.is_empty() {
10325            limits.check_response_bytes(payload.len())?;
10326            response = packet.payload;
10327            response.drain(..2);
10328            break;
10329        }
10330        let combined = response.len().checked_add(payload.len()).ok_or(
10331            oracledb_protocol::ProtocolError::ResourceLimit {
10332                limit: "response_bytes",
10333                observed: usize::MAX,
10334                maximum: limits.max_response_bytes,
10335            },
10336        )?;
10337        limits.check_response_bytes(combined)?;
10338        response.extend_from_slice(payload);
10339        if ends {
10340            break;
10341        }
10342        // Classic (pre-END_OF_RESPONSE) recovery framing: on a server that never
10343        // negotiated END_OF_RESPONSE (protocol < 319, i.e. everything before
10344        // 23ai), the trailing error response after a BREAK/RESET carries neither
10345        // the END_OF_RESPONSE data flag nor a terminal marker byte -- it ends at
10346        // its terminal TTC message (ERROR/STATUS). Decide completion by parsing
10347        // the accumulated stream, exactly like the classic connect-phase reader,
10348        // so the recovery drain does not block until its secondary timeout and
10349        // surface a spurious ConnectionClosed instead of the real CallTimeout /
10350        // Cancelled (bead rust-oracledb-99xu). Gated on `classic` so the 23ai
10351        // flag-framed path (and its wide-row false-positive guard) is untouched.
10352        if classic && classic_connect_response_is_complete(&response, limits).unwrap_or(false) {
10353            break;
10354        }
10355    }
10356    // A flush-out-binds response ends with the FLUSH_OUT_BINDS message byte
10357    // (reference messages/base.pyx:1267-1269, which also sets end_of_response).
10358    // Detect it from the terminal message byte of the fully reassembled stream
10359    // rather than mid-stream, so an ordinary data byte 0x13 at a packet boundary
10360    // is never mistaken for it.
10361    let flush_out_binds = matches!(response.last(), Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS));
10362    Ok(DataResponse {
10363        payload: response,
10364        flush_out_binds,
10365    })
10366}
10367
10368const TNS_PACKET_TYPE_MARKER: u8 = 12;
10369const TNS_MARKER_TYPE_BREAK: u8 = 1;
10370const TNS_MARKER_TYPE_RESET: u8 = 2;
10371
10372#[cfg(test)]
10373#[allow(dead_code)]
10374async fn reset_after_marker_recovery<R, W>(
10375    read: &mut R,
10376    write: &Arc<AsyncMutex<W>>,
10377    initial_marker: &IncomingPacket,
10378) -> Result<Option<IncomingPacket>>
10379where
10380    R: AsyncRead + Unpin,
10381    W: AsyncWrite + std::fmt::Debug + Unpin,
10382{
10383    reset_after_marker_recovery_with_limits(read, write, initial_marker, ProtocolLimits::DEFAULT)
10384        .await
10385}
10386
10387async fn reset_after_marker_recovery_with_limits<R, W>(
10388    read: &mut R,
10389    write: &Arc<AsyncMutex<W>>,
10390    initial_marker: &IncomingPacket,
10391    limits: ProtocolLimits,
10392) -> Result<Option<IncomingPacket>>
10393where
10394    R: AsyncRead + Unpin,
10395    W: AsyncWrite + std::fmt::Debug + Unpin,
10396{
10397    trace_connect_bytes("MARKER packet", &initial_marker.payload);
10398    send_marker_recovery(write, TNS_MARKER_TYPE_RESET).await?;
10399    drain_reset_markers_with_limits(read, limits).await
10400}
10401
10402#[cfg(test)]
10403#[allow(dead_code)]
10404async fn reset_after_marker<R, W>(
10405    read: &mut R,
10406    cx: &Cx,
10407    write: &Arc<AsyncMutex<W>>,
10408    initial_marker: &IncomingPacket,
10409) -> Result<Option<IncomingPacket>>
10410where
10411    R: AsyncRead + Unpin,
10412    W: AsyncWrite + std::fmt::Debug + Unpin,
10413{
10414    reset_after_marker_with_limits(read, cx, write, initial_marker, ProtocolLimits::DEFAULT).await
10415}
10416
10417async fn reset_after_marker_with_limits<R, W>(
10418    read: &mut R,
10419    cx: &Cx,
10420    write: &Arc<AsyncMutex<W>>,
10421    initial_marker: &IncomingPacket,
10422    limits: ProtocolLimits,
10423) -> Result<Option<IncomingPacket>>
10424where
10425    R: AsyncRead + Unpin,
10426    W: AsyncWrite + std::fmt::Debug + Unpin,
10427{
10428    trace_connect_bytes("MARKER packet", &initial_marker.payload);
10429    send_marker_shared(cx, write, TNS_MARKER_TYPE_RESET).await?;
10430    drain_reset_markers_with_limits(read, limits).await
10431}
10432
10433#[cfg(test)]
10434#[allow(dead_code)]
10435async fn drain_reset_markers<R>(read: &mut R) -> Result<Option<IncomingPacket>>
10436where
10437    R: AsyncRead + Unpin,
10438{
10439    drain_reset_markers_with_limits(read, ProtocolLimits::DEFAULT).await
10440}
10441
10442async fn drain_reset_markers_with_limits<R>(
10443    read: &mut R,
10444    limits: ProtocolLimits,
10445) -> Result<Option<IncomingPacket>>
10446where
10447    R: AsyncRead + Unpin,
10448{
10449    // Drain the RESET handshake: consume EVERY trailing marker packet — the
10450    // RESET acknowledgement AND any additional markers the server sends after
10451    // it (a documented variant: reference _reset's second loop,
10452    // protocol.pyx:554-556, "some servers send multiple reset markers"). Return
10453    // the first NON-marker packet (the trailing error/data packet) so the caller
10454    // is seeded with it. Returning early on the first RESET marker would leave a
10455    // following marker in the stream, which the caller mis-reads as a fresh
10456    // break and answers with a DUPLICATE RESET, poisoning a reused connection
10457    // (bead rust-oracledb-yhz). Exactly one RESET is ever sent, here.
10458    loop {
10459        let packet = read_packet_with_limits(read, PacketLengthWidth::Large32, limits).await?;
10460        if packet.packet_type != TNS_PACKET_TYPE_MARKER {
10461            return Ok(Some(packet));
10462        }
10463        trace_connect_bytes("MARKER reset response", &packet.payload);
10464    }
10465}
10466
10467async fn send_marker<W>(stream: &mut W, marker_type: u8) -> Result<()>
10468where
10469    W: AsyncWrite + Unpin,
10470{
10471    let packet = encode_packet(
10472        TNS_PACKET_TYPE_MARKER,
10473        0,
10474        None,
10475        &[1, 0, marker_type],
10476        PacketLengthWidth::Large32,
10477    )?;
10478    trace_connect_bytes("send MARKER", &packet);
10479    stream.write_all(&packet).await?;
10480    stream.flush().await?;
10481    Ok(())
10482}
10483
10484#[cfg(test)]
10485#[allow(dead_code)]
10486async fn read_packet<R>(stream: &mut R, width: PacketLengthWidth) -> Result<IncomingPacket>
10487where
10488    R: AsyncRead + Unpin,
10489{
10490    read_packet_with_limits(stream, width, ProtocolLimits::DEFAULT).await
10491}
10492
10493/// Derives the TCP keepalive idle interval from a DSN `EXPIRE_TIME` (minutes,
10494/// reference net.pyx). `0` (the default) disables keepalive; any positive value
10495/// enables it with that many minutes of socket idle time before the first probe,
10496/// so a half-open/dead peer is detected instead of wedging a later read (GH#14).
10497fn keepalive_idle_from_expire_time(expire_time_minutes: u32) -> Option<Duration> {
10498    (expire_time_minutes > 0).then(|| Duration::from_secs(u64::from(expire_time_minutes) * 60))
10499}
10500
10501/// Marker carried through `std::io::Error` only while a read has made no
10502/// progress for its configured inactivity window.
10503#[derive(Debug)]
10504struct InactivityReadExpired(u32);
10505
10506impl std::fmt::Display for InactivityReadExpired {
10507    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10508        write!(formatter, "read made no progress for {} ms", self.0)
10509    }
10510}
10511
10512impl std::error::Error for InactivityReadExpired {}
10513
10514/// An [`AsyncRead`] adapter whose deadline resets whenever its inner reader
10515/// supplies one or more bytes. This is intentionally below packet framing so a
10516/// large, continuously advancing response is not treated as a stalled read.
10517struct InactivityRead<'a, R> {
10518    inner: &'a mut R,
10519    timeout: Option<Duration>,
10520    idle_sleep: Option<std::pin::Pin<Box<time::Sleep>>>,
10521}
10522
10523impl<'a, R> InactivityRead<'a, R> {
10524    fn new(inner: &'a mut R, timeout: Option<Duration>) -> Self {
10525        Self {
10526            inner,
10527            timeout,
10528            idle_sleep: None,
10529        }
10530    }
10531}
10532
10533impl<R> AsyncRead for InactivityRead<'_, R>
10534where
10535    R: AsyncRead + Unpin,
10536{
10537    fn poll_read(
10538        self: std::pin::Pin<&mut Self>,
10539        context: &mut std::task::Context<'_>,
10540        buffer: &mut asupersync::io::ReadBuf<'_>,
10541    ) -> std::task::Poll<std::io::Result<()>> {
10542        let this = self.get_mut();
10543        let filled_before = buffer.filled().len();
10544        match std::pin::Pin::new(&mut *this.inner).poll_read(context, buffer) {
10545            std::task::Poll::Ready(Ok(())) => {
10546                if buffer.filled().len() > filled_before {
10547                    this.idle_sleep = None;
10548                }
10549                std::task::Poll::Ready(Ok(()))
10550            }
10551            std::task::Poll::Ready(Err(error)) => std::task::Poll::Ready(Err(error)),
10552            std::task::Poll::Pending => {
10553                let Some(timeout) = this.timeout else {
10554                    return std::task::Poll::Pending;
10555                };
10556                let sleep = this
10557                    .idle_sleep
10558                    .get_or_insert_with(|| Box::pin(time::sleep(time::wall_now(), timeout)));
10559                if sleep.as_mut().poll(context).is_ready() {
10560                    std::task::Poll::Ready(Err(std::io::Error::new(
10561                        std::io::ErrorKind::TimedOut,
10562                        InactivityReadExpired(duration_to_millis_saturating(timeout)),
10563                    )))
10564                } else {
10565                    std::task::Poll::Pending
10566                }
10567            }
10568        }
10569    }
10570}
10571
10572fn map_inactivity_timeout<U>(result: Result<U>) -> Result<U> {
10573    match result {
10574        Err(Error::Io(error)) => {
10575            let timeout = error
10576                .get_ref()
10577                .and_then(|source| source.downcast_ref::<InactivityReadExpired>())
10578                .map(|marker| marker.0);
10579            match timeout {
10580                Some(timeout) => Err(Error::CallTimeout(timeout)),
10581                None => Err(Error::Io(error)),
10582            }
10583        }
10584        other => other,
10585    }
10586}
10587
10588async fn read_packet_with_limits<R>(
10589    stream: &mut R,
10590    width: PacketLengthWidth,
10591    limits: ProtocolLimits,
10592) -> Result<IncomingPacket>
10593where
10594    R: AsyncRead + Unpin,
10595{
10596    let mut header = [0u8; 8];
10597    stream.read_exact(&mut header).await?;
10598    let [len0, len1, len2, len3, packet_type, packet_flags, _, _] = header;
10599    let declared = match width {
10600        PacketLengthWidth::Legacy16 => usize::from(u16::from_be_bytes([len0, len1])),
10601        PacketLengthWidth::Large32 => {
10602            usize::try_from(u32::from_be_bytes([len0, len1, len2, len3])).unwrap_or(usize::MAX)
10603        }
10604    };
10605    if declared < header.len() {
10606        return Err(oracledb_protocol::ProtocolError::InvalidPacketLength {
10607            length: declared,
10608            minimum: header.len(),
10609        }
10610        .into());
10611    }
10612    limits.check_packet_bytes(declared)?;
10613    let mut payload = vec![0u8; declared - header.len()];
10614    stream.read_exact(&mut payload).await?;
10615    Ok(IncomingPacket {
10616        packet_type,
10617        packet_flags,
10618        payload,
10619    })
10620}
10621
10622/// The endpoint a listener REDIRECT points at, split out of the redirect
10623/// data (reference protocol.pyx `_connect_phase_one` redirect branch).
10624#[derive(Clone, Debug, Eq, PartialEq)]
10625struct RedirectTarget {
10626    /// Host to reconnect the transport to.
10627    host: String,
10628    /// Port to reconnect the transport to.
10629    port: u16,
10630    /// The connect data to send in the CONNECT packet on the redirected
10631    /// connection (the part of the redirect data after the NUL separator).
10632    connect_data: String,
10633}
10634
10635/// Splits a REDIRECT packet payload into the declared redirect-data length
10636/// (u16be prefix) and the data bytes carried inline in this packet. The
10637/// inline bytes may be shorter than the declared length (the remainder then
10638/// arrives in follow-up packets, reference ConnectMessage.process
10639/// `wait_for_packets_sync`) or longer (trailing bytes beyond the declared
10640/// length are ignored).
10641fn redirect_payload_prefix(payload: &[u8]) -> Result<(usize, &[u8])> {
10642    let Some((length_bytes, inline)) = payload.split_first_chunk::<2>() else {
10643        return Err(Error::InvalidRedirectData(format!(
10644            "REDIRECT packet payload of {} byte(s) is too short for the u16 redirect-data length",
10645            payload.len()
10646        )));
10647    };
10648    let declared = usize::from(u16::from_be_bytes(*length_bytes));
10649    let take = inline.len().min(declared);
10650    Ok((declared, &inline[..take]))
10651}
10652
10653/// Assembles the full redirect data starting from the first REDIRECT packet's
10654/// payload, reading follow-up packets from the same connection while the
10655/// declared length is not yet satisfied (the listener may send the length in
10656/// one packet and the data in the next). Follow-up packets must be REDIRECT
10657/// or DATA packets; anything else fails closed as an unexpected packet.
10658async fn read_redirect_data(core: &mut DriverCore, first_payload: &[u8]) -> Result<String> {
10659    let (declared, inline) = redirect_payload_prefix(first_payload)?;
10660    let mut data = inline.to_vec();
10661    while data.len() < declared {
10662        let packet = core.read_packet(PacketLengthWidth::Legacy16).await?;
10663        if packet.packet_type != TNS_PACKET_TYPE_REDIRECT
10664            && packet.packet_type != TNS_PACKET_TYPE_DATA
10665        {
10666            return Err(Error::UnexpectedPacket(packet.packet_type));
10667        }
10668        if packet.payload.is_empty() {
10669            return Err(Error::InvalidRedirectData(format!(
10670                "listener stopped short of the declared redirect data \
10671                 ({} of {declared} byte(s) received)",
10672                data.len()
10673            )));
10674        }
10675        data.extend_from_slice(&packet.payload);
10676    }
10677    data.truncate(declared);
10678    String::from_utf8(data)
10679        .map_err(|_| Error::InvalidRedirectData("redirect data is not valid UTF-8".to_string()))
10680}
10681
10682/// Parses assembled redirect data (`"<address>\0<connect data>"`) into the
10683/// target endpoint, enforcing that the redirect keeps the original transport
10684/// protocol: a `tcps` connect is never silently downgraded to plain `tcp`
10685/// (and a mid-connect `tcp` -> `tcps` upgrade is not supported). The address
10686/// part is a TNS address/descriptor fragment, e.g.
10687/// `(ADDRESS=(PROTOCOL=tcp)(HOST=dispatcher)(PORT=1621))` (reference parses
10688/// it with `ConnectParamsImpl._parse_connect_string` and takes the first
10689/// address). NOTE: when the original connect is `tcps`, the redirect address
10690/// must say `PROTOCOL=tcps` explicitly — an omitted protocol parses as plain
10691/// `tcp` and is refused as a downgrade (fail closed; the reference instead
10692/// ignores the redirect protocol entirely and keeps its original transport).
10693fn parse_redirect_target(
10694    redirect_data: &str,
10695    original_protocol: NetProtocol,
10696) -> Result<RedirectTarget> {
10697    let Some((address_part, connect_data)) = redirect_data.split_once('\0') else {
10698        return Err(Error::InvalidRedirectData(
10699            "missing NUL separator between the redirect address and its connect data".to_string(),
10700        ));
10701    };
10702    let descriptor = connectstring_parse(address_part).map_err(|err| {
10703        Error::InvalidRedirectData(format!("unparseable redirect address: {err}"))
10704    })?;
10705    let address = descriptor
10706        .as_ref()
10707        .and_then(|descriptor| descriptor.first_address())
10708        .ok_or_else(|| {
10709            Error::InvalidRedirectData("redirect address defines no usable endpoint".to_string())
10710        })?;
10711    let host = address
10712        .host
10713        .clone()
10714        .ok_or_else(|| Error::InvalidRedirectData("redirect address has no HOST".to_string()))?;
10715    let target_protocol: NetProtocol = address.protocol.into();
10716    if target_protocol.is_tls() != original_protocol.is_tls() {
10717        return Err(Error::RedirectUnsupported);
10718    }
10719    Ok(RedirectTarget {
10720        host,
10721        port: address.port,
10722        connect_data: connect_data.to_string(),
10723    })
10724}
10725
10726/// [`oracledb_protocol::net::connectstring::parse`] under a driver-error
10727/// signature (used by the redirect-target parser above).
10728fn connectstring_parse(
10729    input: &str,
10730) -> std::result::Result<
10731    Option<oracledb_protocol::net::connectstring::Descriptor>,
10732    oracledb_protocol::ProtocolError,
10733> {
10734    oracledb_protocol::net::connectstring::parse(input)
10735}
10736
10737fn transport_connect_timeout_duration(seconds: f64) -> Duration {
10738    let seconds = if seconds.is_finite() && seconds > 0.0 {
10739        seconds
10740    } else {
10741        20.0
10742    };
10743    Duration::from_secs_f64(seconds.max(0.001))
10744}
10745
10746/// Resolve the fail-closed DN-match setting from the parsed descriptor and
10747/// explicit connection options. Either side opting out disables only identity
10748/// matching; certificate-chain validation remains mandatory.
10749fn effective_ssl_server_dn_match(description: &Description, options: &ConnectOptions) -> bool {
10750    description.security.ssl_server_dn_match && options.ssl_server_dn_match
10751}
10752
10753/// The SDU (session data unit, in bytes) advertised in the CONNECT packet
10754/// (F1, bead `rust-oracledb-clvm`). Precedence: an explicit
10755/// [`ConnectOptions::with_sdu`] value wins; otherwise a DSN-parsed `(SDU=...)`
10756/// (`Description::sdu`, already clamped by the connect-string parser to
10757/// 512..=2_097_152) is honoured; otherwise the shared 8192 default. The caller
10758/// clamps the result to the 16-bit wire field (the classic CONNECT-packet SDU
10759/// ceiling of 65535); the server negotiates the effective SDU down from the
10760/// advertised value in its ACCEPT.
10761fn resolve_effective_sdu(options_sdu: u16, description: &Description) -> u32 {
10762    const BUILDER_DEFAULT_SDU: u16 = 8192;
10763    if options_sdu != BUILDER_DEFAULT_SDU {
10764        u32::from(options_sdu)
10765    } else if description.sdu != DSN_DEFAULT_SDU {
10766        description.sdu
10767    } else {
10768        u32::from(BUILDER_DEFAULT_SDU)
10769    }
10770}
10771
10772/// One transport endpoint to try during multi-address failover (F2).
10773#[derive(Clone, Debug, PartialEq, Eq)]
10774struct ConnectAddress {
10775    host: String,
10776    port: u16,
10777}
10778
10779/// A failure that can only occur after deterministic connection configuration
10780/// has completed and one concrete transport address is being established.
10781///
10782/// The type deliberately has no configuration/auth/wallet variants: every
10783/// value is therefore safe to aggregate and retry against the next address.
10784/// This construction-level boundary prevents a public [`Error::Tls`] produced
10785/// while building rustls configuration from being mistaken for a transient TLS
10786/// handshake failure.
10787#[derive(Debug)]
10788enum TransportEstablishmentError {
10789    Io(std::io::Error),
10790    TlsHandshake(tls::TlsHandshakeError),
10791}
10792
10793impl TransportEstablishmentError {
10794    fn is_terminal(&self) -> bool {
10795        match self {
10796            Self::Io(_) => false,
10797            Self::TlsHandshake(error) => error.is_terminal(),
10798        }
10799    }
10800
10801    fn into_driver_error(self) -> Error {
10802        match self {
10803            Self::Io(error) => Error::Io(error),
10804            Self::TlsHandshake(error) => error.into_driver_error(),
10805        }
10806    }
10807}
10808
10809impl std::fmt::Display for TransportEstablishmentError {
10810    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10811        match self {
10812            Self::Io(error) => write!(f, "I/O error: {error}"),
10813            Self::TlsHandshake(error) => write!(f, "{error}"),
10814        }
10815    }
10816}
10817
10818impl From<std::io::Error> for TransportEstablishmentError {
10819    fn from(error: std::io::Error) -> Self {
10820        Self::Io(error)
10821    }
10822}
10823
10824impl From<tls::TlsHandshakeError> for TransportEstablishmentError {
10825    fn from(error: tls::TlsHandshakeError) -> Self {
10826        Self::TlsHandshake(error)
10827    }
10828}
10829
10830/// Build the ordered list of transport endpoints to try for a (possibly
10831/// multi-address) connect descriptor (F2, bead `rust-oracledb-clvm`),
10832/// restricted to the primary transport `protocol`. Honours `LOAD_BALANCE`
10833/// (shuffle within the balanced scope) and `FAILOVER=OFF` (only the first
10834/// address of that list). Addresses without a host, or whose protocol differs
10835/// from the primary, are skipped. The first entry equals the endpoint
10836/// [`EasyConnect::parse`] selected as primary, so a single-address descriptor
10837/// behaves exactly as before.
10838fn resolve_connect_addresses(
10839    descriptor: &Descriptor,
10840    protocol: NetProtocol,
10841) -> Vec<ConnectAddress> {
10842    let mut out: Vec<ConnectAddress> = Vec::new();
10843    let mut descriptions: Vec<&Description> = descriptor.descriptions.iter().collect();
10844    if descriptor.load_balance {
10845        shuffle_in_place(&mut descriptions);
10846    }
10847    for description in descriptions {
10848        let mut lists: Vec<&AddressList> = description.address_lists.iter().collect();
10849        if description.load_balance {
10850            shuffle_in_place(&mut lists);
10851        }
10852        for list in lists {
10853            let mut addresses: Vec<&Address> = list
10854                .addresses
10855                .iter()
10856                .filter(|address| {
10857                    address.host.is_some() && NetProtocol::from(address.protocol) == protocol
10858                })
10859                .collect();
10860            if list.load_balance || description.load_balance {
10861                shuffle_in_place(&mut addresses);
10862            }
10863            let limit = if list.failover {
10864                addresses.len()
10865            } else {
10866                addresses.len().min(1)
10867            };
10868            for address in addresses.into_iter().take(limit) {
10869                if let Some(host) = &address.host {
10870                    out.push(ConnectAddress {
10871                        host: host.clone(),
10872                        port: address.port,
10873                    });
10874                }
10875            }
10876        }
10877    }
10878    out
10879}
10880
10881/// In-place Fisher–Yates shuffle seeded from the wall clock. `LOAD_BALANCE`
10882/// only needs unpredictability across connects, not cryptographic randomness,
10883/// so this stays dependency-free (no `rand` in the driver crate).
10884fn shuffle_in_place<T>(items: &mut [T]) {
10885    if items.len() < 2 {
10886        return;
10887    }
10888    let mut state = shuffle_seed();
10889    for i in (1..items.len()).rev() {
10890        // xorshift64*
10891        state ^= state << 13;
10892        state ^= state >> 7;
10893        state ^= state << 17;
10894        let j = (state % (i as u64 + 1)) as usize;
10895        items.swap(i, j);
10896    }
10897}
10898
10899fn shuffle_seed() -> u64 {
10900    use std::time::{SystemTime, UNIX_EPOCH};
10901    let nanos = SystemTime::now()
10902        .duration_since(UNIX_EPOCH)
10903        .map(|d| d.as_nanos() as u64)
10904        .unwrap_or(0x9E37_79B9_7F4A_7C15);
10905    // Mix and force a non-zero (odd) seed so xorshift never degenerates.
10906    (nanos ^ nanos.rotate_left(32).wrapping_mul(0x2545_F491_4F6C_DD1D)) | 1
10907}
10908
10909/// Builds the listener connect descriptor, optionally injecting `(SERVER=emon)`
10910/// into `CONNECT_DATA` (between `SERVICE_NAME` and `CID`, matching the golden
10911/// emon connect packet). The reference sets `description.server_type = "emon"`
10912/// for the background CQN connection (subscr.pyx:70-73).
10913fn listener_connect_descriptor_with_server(
10914    descriptor: &EasyConnect,
10915    description: &Description,
10916    identity: &ClientIdentity,
10917    server_type_emon: bool,
10918    token_auth: bool,
10919    ssl_server_dn_match: bool,
10920    ssl_server_cert_dn: Option<&str>,
10921) -> String {
10922    let address = descriptor_address_clause(descriptor);
10923    let connect_data = listener_connect_data_clause(description, identity, server_type_emon);
10924    let security = descriptor_security_clause(
10925        descriptor.protocol,
10926        description,
10927        token_auth,
10928        ssl_server_dn_match,
10929        ssl_server_cert_dn,
10930    );
10931    format!("(DESCRIPTION={}{}{})", address, connect_data, security)
10932}
10933
10934fn auth_connect_descriptor(
10935    descriptor: &EasyConnect,
10936    description: &Description,
10937    token_auth: bool,
10938    ssl_server_dn_match: bool,
10939    ssl_server_cert_dn: Option<&str>,
10940) -> String {
10941    let address = descriptor_address_clause(descriptor);
10942    let connect_data = auth_connect_data_clause(description, descriptor);
10943    let security = descriptor_security_clause(
10944        descriptor.protocol,
10945        description,
10946        token_auth,
10947        ssl_server_dn_match,
10948        ssl_server_cert_dn,
10949    );
10950    format!("(DESCRIPTION={}{}{})", address, connect_data, security)
10951}
10952
10953fn descriptor_address_clause(descriptor: &EasyConnect) -> String {
10954    let protocol = match descriptor.protocol {
10955        NetProtocol::Tcp => "tcp",
10956        NetProtocol::Tcps => "tcps",
10957    };
10958    format!(
10959        "(ADDRESS=(PROTOCOL={})(HOST={})(PORT={}))",
10960        protocol, descriptor.host, descriptor.port
10961    )
10962}
10963
10964fn listener_connect_data_clause(
10965    description: &Description,
10966    identity: &ClientIdentity,
10967    server_type_emon: bool,
10968) -> String {
10969    let mut out = auth_connect_data_clause_from_service(description, None);
10970    if server_type_emon {
10971        out.push_str("(SERVER=emon)");
10972    } else if let Some(server_type) = description.connect_data.server_type {
10973        out.push_str("(SERVER=");
10974        out.push_str(server_type.as_str());
10975        out.push(')');
10976    }
10977    for (key, value) in &description.connect_data.extra {
10978        out.push('(');
10979        out.push_str(key);
10980        out.push('=');
10981        out.push_str(value);
10982        out.push(')');
10983    }
10984    out.push_str("(CID=(PROGRAM=");
10985    out.push_str(&identity.program);
10986    out.push_str(")(HOST=");
10987    out.push_str(&identity.machine);
10988    out.push_str(")(USER=");
10989    out.push_str(&identity.osuser);
10990    out.push_str(")))");
10991    out
10992}
10993
10994fn auth_connect_data_clause(description: &Description, descriptor: &EasyConnect) -> String {
10995    let mut out =
10996        auth_connect_data_clause_from_service(description, Some(&descriptor.service_name));
10997    if let Some(server_type) = description.connect_data.server_type {
10998        out.push_str("(SERVER=");
10999        out.push_str(server_type.as_str());
11000        out.push(')');
11001    }
11002    for (key, value) in &description.connect_data.extra {
11003        out.push('(');
11004        out.push_str(key);
11005        out.push('=');
11006        out.push_str(value);
11007        out.push(')');
11008    }
11009    out.push(')');
11010    out
11011}
11012
11013fn auth_connect_data_clause_from_service(
11014    description: &Description,
11015    fallback_service_name: Option<&str>,
11016) -> String {
11017    let service_name = description
11018        .connect_data
11019        .service_name
11020        .as_deref()
11021        .or(fallback_service_name)
11022        .unwrap_or("");
11023    format!("(CONNECT_DATA=(SERVICE_NAME={service_name})")
11024}
11025
11026fn descriptor_security_clause(
11027    protocol: NetProtocol,
11028    description: &Description,
11029    token_auth: bool,
11030    ssl_server_dn_match: bool,
11031    ssl_server_cert_dn: Option<&str>,
11032) -> String {
11033    let security = &description.security;
11034    if !protocol.is_tls()
11035        && !token_auth
11036        && ssl_server_dn_match
11037        && ssl_server_cert_dn.is_none()
11038        && security.extra.is_empty()
11039    {
11040        return String::new();
11041    }
11042
11043    let mut out = String::from("(SECURITY=");
11044    if protocol.is_tls() || !ssl_server_dn_match {
11045        out.push_str("(SSL_SERVER_DN_MATCH=");
11046        out.push_str(if ssl_server_dn_match { "ON" } else { "OFF" });
11047        out.push(')');
11048    }
11049    if let Some(cert_dn) = ssl_server_cert_dn {
11050        out.push_str("(SSL_SERVER_CERT_DN=");
11051        out.push_str(cert_dn);
11052        out.push(')');
11053    }
11054    for (key, value) in &security.extra {
11055        if key.eq_ignore_ascii_case("TOKEN_AUTH") {
11056            continue;
11057        }
11058        out.push('(');
11059        out.push_str(key);
11060        out.push('=');
11061        out.push_str(value);
11062        out.push(')');
11063    }
11064    if token_auth {
11065        out.push_str("(TOKEN_AUTH=OCI_TOKEN)");
11066    }
11067    out.push(')');
11068    out
11069}
11070
11071fn parse_session_u32(
11072    data: &std::collections::BTreeMap<String, String>,
11073    key: &'static str,
11074) -> Result<u32> {
11075    data.get(key)
11076        .ok_or(Error::MissingSessionField(key))?
11077        .parse::<u32>()
11078        .map_err(|_| Error::MissingSessionField(key))
11079}
11080
11081fn parse_session_u16(
11082    data: &std::collections::BTreeMap<String, String>,
11083    key: &'static str,
11084) -> Result<u16> {
11085    // Parse straight into the target width. Going through u64 and casting with
11086    // `as u16` silently wrapped, so AUTH_SERIAL_NUM=70000 was reported as 4464
11087    // and the connection carried a session serial the server never issued —
11088    // which is the number cancellation and session correlation are matched on
11089    // (finding DC7, bead oraclemcp-eng-program-bp8ia.7.11.3).
11090    data.get(key)
11091        .ok_or(Error::MissingSessionField(key))?
11092        .parse::<u16>()
11093        .map_err(|_| Error::MissingSessionField(key))
11094}
11095
11096/// Extract `db_unique_name` from the AUTH phase-two session data: the value of
11097/// `AUTH_SC_REAL_DBUNIQUE_NAME` ONLY (reference 16a57f1cbd58). This key is
11098/// DISTINCT from `AUTH_SC_DBUNIQUE_NAME` (which upstream maps to `db_name`), so
11099/// there is deliberately no fallback. `None` when the key is absent.
11100fn parse_db_unique_name(data: &std::collections::BTreeMap<String, String>) -> Option<String> {
11101    data.get("AUTH_SC_REAL_DBUNIQUE_NAME").cloned()
11102}
11103
11104fn next_ttc_sequence(seq_num: &mut u8) -> u8 {
11105    *seq_num = seq_num.wrapping_add(1);
11106    if *seq_num == 0 {
11107        *seq_num = 1;
11108    }
11109    *seq_num
11110}
11111
11112/// LRU statement-cache insert, bounded to `capacity`. Moves an existing entry
11113/// for `sql` to most-recently-used (replacing its cursor) and evicts the oldest
11114/// entries past `capacity`. Returns the cursor ids that should be closed (the
11115/// replaced cursor and any evicted ones). `capacity == 0` disables caching: the
11116/// freshly inserted cursor is itself evicted and returned for closing, so the
11117/// cache stays empty (python-oracledb `stmtcachesize=0`). A `cursor_id` of 0
11118/// (no server cursor) is never cached. Pure so it is unit-testable without a
11119/// live connection.
11120fn statement_cache_insert(
11121    cache: &mut Vec<CachedStatement>,
11122    capacity: usize,
11123    sql: &str,
11124    cursor_id: u32,
11125    mut bind_shape: Vec<BindShapeSlot>,
11126) -> Vec<u32> {
11127    let mut to_close = Vec::new();
11128    if cursor_id == 0 {
11129        return to_close;
11130    }
11131    if let Some(index) = cache.iter().position(|entry| entry.sql == sql) {
11132        let old = cache.remove(index);
11133        if old.cursor_id != 0 && old.cursor_id != cursor_id {
11134            to_close.push(old.cursor_id);
11135        } else if old.cursor_id == cursor_id && old.bind_shape.len() == bind_shape.len() {
11136            // Re-execution of the SAME open cursor: an untyped-NULL bind is
11137            // written with placeholder VARCHAR metadata and does not disturb
11138            // the type the cursor was parsed with, so the previous concrete
11139            // slot is inherited instead of downgrading it to the placeholder.
11140            for (slot, old_slot) in bind_shape.iter_mut().zip(old.bind_shape) {
11141                if slot.untyped_null {
11142                    *slot = old_slot;
11143                }
11144            }
11145        }
11146    }
11147    cache.push(CachedStatement {
11148        sql: sql.to_string(),
11149        cursor_id,
11150        bind_shape,
11151    });
11152    while cache.len() > capacity {
11153        let evicted = cache.remove(0);
11154        if evicted.cursor_id != 0 {
11155            to_close.push(evicted.cursor_id);
11156        }
11157    }
11158    to_close
11159}
11160
11161/// One statement-cache entry: the open server cursor for a SQL text and the
11162/// bind TYPE shape it was last bound/parsed with (see
11163/// [`Connection::statement_cache`] and bead rust-oracledb-ilel).
11164#[derive(Clone, Debug, PartialEq, Eq)]
11165struct CachedStatement {
11166    sql: String,
11167    cursor_id: u32,
11168    bind_shape: Vec<BindShapeSlot>,
11169}
11170
11171/// Per-position bind TYPE shape used to decide whether an open cached cursor
11172/// may be re-executed with the current binds. The server resolves bind
11173/// conversions against the metadata the cursor was PARSED with, not the
11174/// metadata sent on a re-execute: rebinding a different type through a cached
11175/// cursor makes the server coerce through the stale type (ORA-01722 when text
11176/// rides a NUMBER-parsed cursor). python-oracledb tracks the same change via
11177/// `Statement._binds_changed` (thin/statement.pyx `_set_var`).
11178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11179struct BindShapeSlot {
11180    /// Bind type folded to its interchangeable family: CHAR/VARCHAR/LONG all
11181    /// map to VARCHAR and RAW/LONG_RAW to RAW (mirroring the wire writer's
11182    /// `bind_metadata_types_are_compatible`), so a pure SIZE change never
11183    /// invalidates the cursor — only a TYPE change does.
11184    family: u8,
11185    /// Character-set form: distinguishes NCHAR text from implicit-charset
11186    /// text (python-oracledb `_set_var` also compares `csfrm`).
11187    csfrm: u8,
11188    /// True when every row's value at this position is an untyped NULL. Such
11189    /// a bind is written with placeholder VARCHAR metadata and converts to
11190    /// any parsed type server-side, so it is compatible with any cached slot.
11191    untyped_null: bool,
11192}
11193
11194/// Folds a wire bind type into its statement-cache compatibility family (the
11195/// same classes the metadata writer merges across bind rows).
11196fn bind_type_family(ora_type_num: u8) -> u8 {
11197    use oracledb_protocol::thin::{
11198        ORA_TYPE_NUM_CHAR, ORA_TYPE_NUM_LONG, ORA_TYPE_NUM_LONG_RAW, ORA_TYPE_NUM_RAW,
11199        ORA_TYPE_NUM_VARCHAR,
11200    };
11201    match ora_type_num {
11202        ORA_TYPE_NUM_CHAR | ORA_TYPE_NUM_LONG => ORA_TYPE_NUM_VARCHAR,
11203        ORA_TYPE_NUM_LONG_RAW => ORA_TYPE_NUM_RAW,
11204        other => other,
11205    }
11206}
11207
11208/// Computes the bind TYPE shape of an execute's bind rows. Mirrors the wire
11209/// metadata writer's inference (`write_bind_metadata_for_rows`): the first
11210/// non-NULL value in a column determines its type; a column that is untyped
11211/// NULL in every row is a wildcard slot.
11212fn bind_type_shape(bind_rows: &[Vec<BindValue>]) -> Vec<BindShapeSlot> {
11213    use oracledb_protocol::thin::{bind_value_type_info, CS_FORM_IMPLICIT, ORA_TYPE_NUM_VARCHAR};
11214    let Some(first_row) = bind_rows.first() else {
11215        return Vec::new();
11216    };
11217    (0..first_row.len())
11218        .map(|index| {
11219            let info = bind_rows
11220                .iter()
11221                .find_map(|row| row.get(index).and_then(bind_value_type_info));
11222            match info {
11223                Some(info) => BindShapeSlot {
11224                    family: bind_type_family(info.ora_type_num),
11225                    csfrm: info.csfrm,
11226                    untyped_null: false,
11227                },
11228                None => BindShapeSlot {
11229                    family: ORA_TYPE_NUM_VARCHAR,
11230                    csfrm: CS_FORM_IMPLICIT,
11231                    untyped_null: true,
11232                },
11233            }
11234        })
11235        .collect()
11236}
11237
11238/// True when a cached cursor bound with `cached` may be re-executed with
11239/// binds of shape `new`: every position must keep its type family + charset
11240/// form, except that an untyped NULL in the NEW binds matches anything (it is
11241/// written as a placeholder and null-converts to any parsed type).
11242fn bind_shape_is_compatible(cached: &[BindShapeSlot], new: &[BindShapeSlot]) -> bool {
11243    cached.len() == new.len()
11244        && cached.iter().zip(new).all(|(cached, new)| {
11245            new.untyped_null || (cached.family == new.family && cached.csfrm == new.csfrm)
11246        })
11247}
11248
11249/// Returns whether Oracle will execute `sql` on its row-producing path.
11250///
11251/// A leading `WITH` does not determine that by itself: Oracle permits a CTE
11252/// list before `SELECT` and before DML. Walk each complete CTE definition, then
11253/// inspect the first statement keyword after the list. Syntax we cannot
11254/// confidently walk stays on the non-query path.
11255fn statement_is_query(sql: &str) -> bool {
11256    let mut cursor = SqlStatementCursor::new(sql);
11257    match cursor.next_keyword() {
11258        Some(keyword) if keyword.eq_ignore_ascii_case("select") => true,
11259        Some(keyword) if keyword.eq_ignore_ascii_case("with") => cursor
11260            .cte_statement_keyword()
11261            .is_some_and(|keyword| keyword.eq_ignore_ascii_case("select")),
11262        _ => false,
11263    }
11264}
11265
11266/// A deliberately narrow SQL cursor for query-path selection. It understands
11267/// comments, quoted strings/identifiers, balanced parentheses, and the CTE
11268/// grammar prefix; it is not a general SQL parser.
11269struct SqlStatementCursor<'a> {
11270    bytes: &'a [u8],
11271    index: usize,
11272}
11273
11274impl<'a> SqlStatementCursor<'a> {
11275    fn new(sql: &'a str) -> Self {
11276        Self {
11277            bytes: sql.as_bytes(),
11278            index: 0,
11279        }
11280    }
11281
11282    fn next_keyword(&mut self) -> Option<&'a str> {
11283        self.skip_trivia();
11284        let start = self.index;
11285        while self
11286            .bytes
11287            .get(self.index)
11288            .is_some_and(u8::is_ascii_alphabetic)
11289        {
11290            self.index += 1;
11291        }
11292        (start != self.index)
11293            .then(|| std::str::from_utf8(&self.bytes[start..self.index]).ok())
11294            .flatten()
11295    }
11296
11297    /// Return the statement keyword after one or more conventional CTEs.
11298    ///
11299    /// This accepts only `name [(columns)] AS (subquery)` definitions. A
11300    /// `WITH FUNCTION` or malformed `WITH` is intentionally not interpreted
11301    /// as a query, because treating it as one could route a non-query through
11302    /// the fetch path.
11303    fn cte_statement_keyword(&mut self) -> Option<&'a str> {
11304        loop {
11305            if !self.consume_identifier() {
11306                return None;
11307            }
11308            self.skip_trivia();
11309            if self.peek() == Some(b'(') && !self.consume_parentheses() {
11310                return None;
11311            }
11312            if !self.consume_keyword("as") || !self.consume_parentheses() {
11313                return None;
11314            }
11315            self.skip_trivia();
11316            if self.peek() == Some(b',') {
11317                self.index += 1;
11318                continue;
11319            }
11320            return self.next_keyword();
11321        }
11322    }
11323
11324    fn consume_keyword(&mut self, expected: &str) -> bool {
11325        self.next_keyword()
11326            .is_some_and(|keyword| keyword.eq_ignore_ascii_case(expected))
11327    }
11328
11329    fn consume_identifier(&mut self) -> bool {
11330        self.skip_trivia();
11331        if self.peek() == Some(b'\"') {
11332            return self.consume_quoted_identifier();
11333        }
11334        let start = self.index;
11335        if !self.peek().is_some_and(|byte| byte.is_ascii_alphabetic()) {
11336            return false;
11337        }
11338        while self
11339            .bytes
11340            .get(self.index)
11341            .is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$' | b'#'))
11342        {
11343            self.index += 1;
11344        }
11345        start != self.index
11346    }
11347
11348    fn consume_parentheses(&mut self) -> bool {
11349        self.skip_trivia();
11350        if self.peek() != Some(b'(') {
11351            return false;
11352        }
11353        let mut depth = 0_u32;
11354        while let Some(byte) = self.peek() {
11355            match byte {
11356                b'\'' => {
11357                    if !self.consume_single_quoted() {
11358                        return false;
11359                    }
11360                }
11361                b'\"' => {
11362                    if !self.consume_quoted_identifier() {
11363                        return false;
11364                    }
11365                }
11366                b'q' | b'Q' if self.bytes.get(self.index + 1) == Some(&b'\'') => {
11367                    if !self.consume_q_quoted() {
11368                        return false;
11369                    }
11370                }
11371                b'-' if self.bytes.get(self.index + 1) == Some(&b'-') => {
11372                    self.skip_line_comment();
11373                }
11374                b'/' if self.bytes.get(self.index + 1) == Some(&b'*') => {
11375                    if !self.skip_block_comment() {
11376                        return false;
11377                    }
11378                }
11379                b'(' => {
11380                    depth += 1;
11381                    self.index += 1;
11382                }
11383                b')' => {
11384                    if depth == 0 {
11385                        return false;
11386                    }
11387                    depth -= 1;
11388                    self.index += 1;
11389                    if depth == 0 {
11390                        return true;
11391                    }
11392                }
11393                _ => self.index += 1,
11394            }
11395        }
11396        false
11397    }
11398
11399    fn skip_trivia(&mut self) {
11400        loop {
11401            while self.peek().is_some_and(|byte| byte.is_ascii_whitespace()) {
11402                self.index += 1;
11403            }
11404            match (self.peek(), self.bytes.get(self.index + 1)) {
11405                (Some(b'-'), Some(b'-')) => self.skip_line_comment(),
11406                (Some(b'/'), Some(b'*')) => {
11407                    if !self.skip_block_comment() {
11408                        return;
11409                    }
11410                }
11411                _ => return,
11412            }
11413        }
11414    }
11415
11416    fn consume_single_quoted(&mut self) -> bool {
11417        debug_assert_eq!(self.peek(), Some(b'\''));
11418        self.index += 1;
11419        while let Some(byte) = self.peek() {
11420            self.index += 1;
11421            if byte == b'\'' {
11422                if self.peek() == Some(b'\'') {
11423                    self.index += 1;
11424                } else {
11425                    return true;
11426                }
11427            }
11428        }
11429        false
11430    }
11431
11432    fn consume_quoted_identifier(&mut self) -> bool {
11433        debug_assert_eq!(self.peek(), Some(b'\"'));
11434        self.index += 1;
11435        while let Some(byte) = self.peek() {
11436            self.index += 1;
11437            if byte == b'\"' {
11438                if self.peek() == Some(b'\"') {
11439                    self.index += 1;
11440                } else {
11441                    return true;
11442                }
11443            }
11444        }
11445        false
11446    }
11447
11448    fn consume_q_quoted(&mut self) -> bool {
11449        debug_assert!(matches!(self.peek(), Some(b'q' | b'Q')));
11450        let Some(&opening) = self.bytes.get(self.index + 2) else {
11451            return false;
11452        };
11453        let closing = match opening {
11454            b'[' => b']',
11455            b'{' => b'}',
11456            b'(' => b')',
11457            b'<' => b'>',
11458            other => other,
11459        };
11460        self.index += 3;
11461        while self.index + 1 < self.bytes.len() {
11462            if self.bytes[self.index] == closing && self.bytes[self.index + 1] == b'\'' {
11463                self.index += 2;
11464                return true;
11465            }
11466            self.index += 1;
11467        }
11468        false
11469    }
11470
11471    fn skip_line_comment(&mut self) {
11472        debug_assert_eq!(
11473            self.bytes.get(self.index..self.index + 2),
11474            Some(b"--".as_slice())
11475        );
11476        self.index += 2;
11477        while self
11478            .peek()
11479            .is_some_and(|byte| !matches!(byte, b'\n' | b'\r'))
11480        {
11481            self.index += 1;
11482        }
11483    }
11484
11485    fn skip_block_comment(&mut self) -> bool {
11486        debug_assert_eq!(
11487            self.bytes.get(self.index..self.index + 2),
11488            Some(b"/*".as_slice())
11489        );
11490        self.index += 2;
11491        while self.index + 1 < self.bytes.len() {
11492            if self.bytes[self.index] == b'*' && self.bytes[self.index + 1] == b'/' {
11493                self.index += 2;
11494                return true;
11495            }
11496            self.index += 1;
11497        }
11498        false
11499    }
11500
11501    fn peek(&self) -> Option<u8> {
11502        self.bytes.get(self.index).copied()
11503    }
11504}
11505
11506/// True when any column needs a client-side define to stream its value:
11507/// `CLOB` / `BLOB` / `VECTOR` / native `JSON`. Such columns come back from the
11508/// initial execute as describe-only metadata; the value is delivered on a
11509/// follow-up define-fetch round trip (reference `statement._requires_define`).
11510fn columns_require_define(columns: &[ColumnMetadata]) -> bool {
11511    use oracledb_protocol::thin::{
11512        ORA_TYPE_NUM_BLOB, ORA_TYPE_NUM_CLOB, ORA_TYPE_NUM_JSON, ORA_TYPE_NUM_VECTOR,
11513    };
11514    columns.iter().any(|column| {
11515        matches!(
11516            column.ora_type_num(),
11517            ORA_TYPE_NUM_CLOB | ORA_TYPE_NUM_BLOB | ORA_TYPE_NUM_VECTOR | ORA_TYPE_NUM_JSON
11518        )
11519    })
11520}
11521
11522fn columns_have_lob_prefetch_fields(columns: &[ColumnMetadata]) -> bool {
11523    use oracledb_protocol::thin::{ORA_TYPE_NUM_BLOB, ORA_TYPE_NUM_CLOB};
11524    columns
11525        .iter()
11526        .any(|column| matches!(column.ora_type_num(), ORA_TYPE_NUM_CLOB | ORA_TYPE_NUM_BLOB))
11527}
11528
11529/// Columns that warrant an `ALL_JSON_COLUMNS` probe to learn whether a CLOB/BLOB
11530/// actually stores JSON: not already flagged JSON, of LOB type, and named (an
11531/// unnamed expression column cannot be looked up by name). Returns each
11532/// candidate's index paired with its upper-cased name (the catalog stores names
11533/// upper-cased) so the caller can flip `is_json` in place after the probe.
11534fn json_lob_probe_candidates(columns: &[ColumnMetadata]) -> Vec<(usize, String)> {
11535    use oracledb_protocol::thin::{ORA_TYPE_NUM_BLOB, ORA_TYPE_NUM_CLOB};
11536    columns
11537        .iter()
11538        .enumerate()
11539        .filter(|(_, metadata)| {
11540            !metadata.is_json()
11541                && matches!(
11542                    metadata.ora_type_num(),
11543                    ORA_TYPE_NUM_CLOB | ORA_TYPE_NUM_BLOB
11544                )
11545                && !metadata.name().is_empty()
11546        })
11547        .map(|(index, metadata)| (index, metadata.name().to_ascii_uppercase()))
11548        .collect()
11549}
11550
11551fn trace_connect_step(step: &'static str) {
11552    if std::env::var_os("ORACLEDB_TRACE_CONNECT").is_some() {
11553        eprintln!("oraclemcp_driver_cx::connect: {step}");
11554    }
11555}
11556
11557fn trace_connect_value(label: &'static str, value: &str) {
11558    if std::env::var_os("ORACLEDB_TRACE_CONNECT").is_some() {
11559        eprintln!("oraclemcp_driver_cx::connect: {label}: {value}");
11560    }
11561}
11562
11563fn trace_connect_bytes(label: &'static str, bytes: &[u8]) {
11564    if std::env::var_os("ORACLEDB_TRACE_CONNECT").is_some() {
11565        let mut hex = String::with_capacity(bytes.len() * 2);
11566        for byte in bytes {
11567            use std::fmt::Write as _;
11568            let _ = write!(&mut hex, "{byte:02x}");
11569        }
11570        eprintln!(
11571            "oraclemcp_driver_cx::connect: {label} len={} hex={hex}",
11572            bytes.len()
11573        );
11574    }
11575}
11576
11577fn trace_query_bytes(label: &'static str, bytes: &[u8]) {
11578    if std::env::var_os("ORACLEDB_TRACE_QUERY").is_some() {
11579        let mut hex = String::with_capacity(bytes.len() * 2);
11580        for byte in bytes {
11581            use std::fmt::Write as _;
11582            let _ = write!(&mut hex, "{byte:02x}");
11583        }
11584        eprintln!(
11585            "oraclemcp_driver_cx::query: {label} len={} hex={hex}",
11586            bytes.len()
11587        );
11588    }
11589}
11590
11591#[cfg(test)]
11592mod tests {
11593    use super::*;
11594    use asupersync::lab::{DporExplorer, ExplorerConfig, LabRuntime};
11595    use asupersync::types::{Budget, CancelKind, Time};
11596    use oracledb_protocol::thin::QueryValue;
11597    use std::future::{poll_fn, Future};
11598    use std::io::Read;
11599    use std::net::TcpListener;
11600    use std::pin::pin;
11601    use std::sync::atomic::{AtomicBool, Ordering};
11602    use std::task::{Poll, Waker};
11603    use std::thread;
11604    use std::time::{Duration, Instant};
11605
11606    #[test]
11607    fn statement_is_query_recognizes_select_after_cte_list() {
11608        for sql in [
11609            "WITH x AS (SELECT 1 AS id FROM dual) SELECT id FROM x",
11610            concat!(
11611                "WITH first_cte AS (SELECT 1 AS id FROM dual), ",
11612                "second_cte AS (SELECT id + 1 AS id FROM first_cte) ",
11613                "SELECT id FROM second_cte"
11614            ),
11615            concat!(
11616                "WITH outer_cte AS (",
11617                "WITH inner_cte AS (SELECT q'[)]' AS marker FROM dual) ",
11618                "SELECT marker FROM inner_cte",
11619                ") SELECT marker FROM outer_cte"
11620            ),
11621        ] {
11622            assert!(
11623                statement_is_query(sql),
11624                "CTE SELECT must use query path: {sql}"
11625            );
11626        }
11627    }
11628
11629    #[test]
11630    fn statement_is_query_rejects_cte_prefixed_dml_and_plsql() {
11631        for sql in [
11632            "WITH x AS (SELECT 1 AS id FROM dual) INSERT INTO cte_target (id) SELECT id FROM x",
11633            "WITH x AS (SELECT 1 AS id FROM dual) UPDATE cte_target SET id = id + 1",
11634            "WITH x AS (SELECT 1 AS id FROM dual) DELETE FROM cte_target WHERE id IN (SELECT id FROM x)",
11635            concat!(
11636                "WITH x AS (SELECT 1 AS id FROM dual) ",
11637                "MERGE INTO cte_target target USING x ON (target.id = x.id) ",
11638                "WHEN MATCHED THEN UPDATE SET target.id = x.id"
11639            ),
11640            concat!(
11641                "WITH FUNCTION answer RETURN NUMBER IS BEGIN RETURN 42; END; ",
11642                "SELECT answer FROM dual"
11643            ),
11644        ] {
11645            assert!(
11646                !statement_is_query(sql),
11647                "only SELECT after a conventional CTE list may use query path: {sql}"
11648            );
11649        }
11650    }
11651
11652    #[test]
11653    fn statement_is_query_skips_leading_whitespace_and_comments() {
11654        for sql in [
11655            " \n\t-- leading line comment\nWITH x AS (SELECT 1 FROM dual) SELECT * FROM x",
11656            "/* leading block comment */ WITH x AS (SELECT 1 FROM dual) SELECT * FROM x",
11657            "/* leading block comment */\nSELECT 1 FROM dual",
11658        ] {
11659            assert!(
11660                statement_is_query(sql),
11661                "comments must not hide a query: {sql}"
11662            );
11663        }
11664    }
11665
11666    // ---- bead rust-oracledb-clvm: DSN transport params (F1) + failover (F2) ----
11667
11668    /// Read the SDU advertised in a CONNECT-packet payload (the 4th `u16be`
11669    /// field; see `build_connect_packet_payload`).
11670    fn connect_packet_sdu(payload: &[u8]) -> u16 {
11671        u16::from_be_bytes([payload[6], payload[7]])
11672    }
11673
11674    #[test]
11675    fn f1_dsn_sdu_reaches_the_connect_config() {
11676        // A DSN-set SDU must reach the connect config when the structured
11677        // builder left SDU at its default (the common DSN-only case).
11678        let desc = EasyConnect::parse_descriptor(
11679            "(DESCRIPTION=(SDU=32768)(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1521))\
11680             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11681        )
11682        .expect("descriptor parses");
11683        let primary = desc.first_description();
11684        assert_eq!(primary.sdu, 32768, "parser must capture DSN SDU");
11685        // builder default (8192) => DSN SDU wins.
11686        let advertised =
11687            u16::try_from(resolve_effective_sdu(8192, primary)).expect("32768 fits u16");
11688        assert_eq!(advertised, 32768);
11689        // and it reaches the actual CONNECT packet bytes.
11690        let payload = build_connect_packet_payload(
11691            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1521))\
11692             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11693            advertised,
11694        )
11695        .expect("payload builds");
11696        assert_eq!(connect_packet_sdu(&payload), 32768);
11697    }
11698
11699    #[test]
11700    fn f1_effective_sdu_precedence() {
11701        let dsn = EasyConnect::parse_descriptor(
11702            "(DESCRIPTION=(SDU=16384)(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1))\
11703             (CONNECT_DATA=(SERVICE_NAME=s)))",
11704        )
11705        .expect("parse");
11706        let desc = dsn.first_description();
11707        // explicit builder SDU wins over the DSN.
11708        assert_eq!(resolve_effective_sdu(4096, desc), 4096);
11709        // builder at default => DSN SDU used.
11710        assert_eq!(resolve_effective_sdu(8192, desc), 16384);
11711        // neither set => shared default.
11712        let plain = EasyConnect::parse_descriptor(
11713            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1))(CONNECT_DATA=(SERVICE_NAME=s)))",
11714        )
11715        .expect("parse");
11716        assert_eq!(resolve_effective_sdu(8192, plain.first_description()), 8192);
11717    }
11718
11719    #[test]
11720    fn f1_dsn_transport_connect_timeout_reaches_the_deadline() {
11721        // A DSN-set transport_connect_timeout must drive the connect deadline,
11722        // not the hard-coded 20s.
11723        let desc = EasyConnect::parse_descriptor("h:1521/svc?transport_connect_timeout=3.5")
11724            .expect("EZConnect-Plus parses");
11725        let secs = desc.first_description().tcp_connect_timeout;
11726        assert!((secs - 3.5).abs() < 1e-9, "parser captured {secs}");
11727        let deadline = transport_connect_timeout_duration(secs);
11728        assert_eq!(deadline, Duration::from_secs_f64(3.5));
11729        // sanity: a descriptor without the param keeps the 20s default.
11730        let default_desc = EasyConnect::parse_descriptor("h:1521/svc").expect("parse");
11731        assert_eq!(
11732            transport_connect_timeout_duration(
11733                default_desc.first_description().tcp_connect_timeout
11734            ),
11735            Duration::from_secs(20)
11736        );
11737    }
11738
11739    /// GH#14: the TCP keepalive idle interval is derived from a DSN `EXPIRE_TIME`
11740    /// (minutes). `0`/absent disables it; a positive value maps to that many
11741    /// minutes of socket idle time.
11742    #[test]
11743    fn a11_keepalive_idle_derives_from_expire_time_minutes() {
11744        assert_eq!(keepalive_idle_from_expire_time(0), None);
11745        assert_eq!(
11746            keepalive_idle_from_expire_time(1),
11747            Some(Duration::from_secs(60))
11748        );
11749        assert_eq!(
11750            keepalive_idle_from_expire_time(5),
11751            Some(Duration::from_secs(300))
11752        );
11753        // Tie the derivation to the DSN parser: a descriptor `EXPIRE_TIME=2`
11754        // yields a 120s keepalive idle; the default descriptor disables it.
11755        let with_expire =
11756            EasyConnect::parse_descriptor("h:1521/svc?expire_time=2").expect("parse expire_time");
11757        assert_eq!(
11758            keepalive_idle_from_expire_time(with_expire.first_description().expire_time),
11759            Some(Duration::from_secs(120))
11760        );
11761        let default_desc = EasyConnect::parse_descriptor("h:1521/svc").expect("parse default");
11762        assert_eq!(
11763            keepalive_idle_from_expire_time(default_desc.first_description().expire_time),
11764            None
11765        );
11766    }
11767
11768    /// An `AsyncRead` that never yields a byte and never wakes — models a silent
11769    /// or half-open peer whose data (or FIN/RST) never arrives, so a naive read
11770    /// would hang forever.
11771    #[derive(Debug)]
11772    struct SilentRead;
11773
11774    impl asupersync::io::AsyncRead for SilentRead {
11775        fn poll_read(
11776            self: std::pin::Pin<&mut Self>,
11777            _cx: &mut std::task::Context<'_>,
11778            _buf: &mut asupersync::io::ReadBuf<'_>,
11779        ) -> std::task::Poll<std::io::Result<()>> {
11780            std::task::Poll::Pending
11781        }
11782    }
11783
11784    /// Emits one byte after each delay, modelling a slow large response that
11785    /// is continuously making progress rather than a stalled peer.
11786    struct ProgressRead {
11787        bytes: VecDeque<u8>,
11788        delay: Duration,
11789        sleep: Option<std::pin::Pin<Box<time::Sleep>>>,
11790    }
11791
11792    impl ProgressRead {
11793        fn new(bytes: impl IntoIterator<Item = u8>, delay: Duration) -> Self {
11794            Self {
11795                bytes: bytes.into_iter().collect(),
11796                delay,
11797                sleep: None,
11798            }
11799        }
11800    }
11801
11802    impl asupersync::io::AsyncRead for ProgressRead {
11803        fn poll_read(
11804            mut self: std::pin::Pin<&mut Self>,
11805            context: &mut std::task::Context<'_>,
11806            buffer: &mut asupersync::io::ReadBuf<'_>,
11807        ) -> std::task::Poll<std::io::Result<()>> {
11808            if self.bytes.is_empty() {
11809                return std::task::Poll::Ready(Ok(()));
11810            }
11811            let delay = self.delay;
11812            let sleep = self
11813                .sleep
11814                .get_or_insert_with(|| Box::pin(time::sleep(time::wall_now(), delay)));
11815            if sleep.as_mut().poll(context).is_pending() {
11816                return std::task::Poll::Pending;
11817            }
11818            self.sleep = None;
11819            buffer.put_slice(&[self.bytes.pop_front().expect("checked non-empty")]);
11820            std::task::Poll::Ready(Ok(()))
11821        }
11822    }
11823
11824    /// GH#14 / AC1+AC4+AC5: with an inactivity deadline set, a post-auth framing
11825    /// read against a silent server fails at ~the deadline with `CallTimeout`
11826    /// instead of hanging. Deterministic via the `SilentRead` mock transport.
11827    #[test]
11828    fn a11_inactivity_deadline_fires_on_a_silent_server() {
11829        let runtime = build_io_runtime().expect("io runtime");
11830        let elapsed = runtime.block_on(async {
11831            let mut source = SilentRead;
11832            let mut reader = InactivityRead::new(&mut source, Some(Duration::from_millis(200)));
11833            let started = std::time::Instant::now();
11834            let result = map_inactivity_timeout(
11835                read_packet_with_limits(
11836                    &mut reader,
11837                    PacketLengthWidth::Large32,
11838                    ProtocolLimits::DEFAULT,
11839                )
11840                .await,
11841            );
11842            let elapsed = started.elapsed();
11843            assert!(
11844                matches!(result, Err(Error::CallTimeout(_))),
11845                "expected CallTimeout, got {result:?}"
11846            );
11847            elapsed
11848        });
11849        // Fired promptly at ~200ms — nowhere near an unbounded hang. The bounds
11850        // are generous to stay robust on a loaded CI host.
11851        assert!(
11852            elapsed >= Duration::from_millis(150),
11853            "deadline fired too early ({elapsed:?}); it must honour the configured 200ms"
11854        );
11855        assert!(
11856            elapsed < Duration::from_secs(5),
11857            "deadline should fire promptly, took {elapsed:?}"
11858        );
11859    }
11860
11861    /// GH#14: continuous byte-level progress resets the idle timer. The full
11862    /// packet takes longer than the configured duration but every individual
11863    /// byte arrives sooner, so an operation deadline would fail this test while
11864    /// a true inactivity deadline succeeds.
11865    #[test]
11866    fn a11_inactivity_deadline_resets_after_every_read_progress() {
11867        let runtime = build_io_runtime().expect("io runtime");
11868        runtime.block_on(async {
11869            let packet = encode_packet(
11870                TNS_PACKET_TYPE_DATA,
11871                0,
11872                None,
11873                &[0x01, 0x02],
11874                PacketLengthWidth::Large32,
11875            )
11876            .expect("packet");
11877            let mut source = ProgressRead::new(packet, Duration::from_millis(35));
11878            let mut reader = InactivityRead::new(&mut source, Some(Duration::from_millis(100)));
11879            let started = std::time::Instant::now();
11880            let packet = map_inactivity_timeout(
11881                read_packet_with_limits(
11882                    &mut reader,
11883                    PacketLengthWidth::Large32,
11884                    ProtocolLimits::DEFAULT,
11885                )
11886                .await,
11887            )
11888            .expect("each byte arrived before the idle deadline");
11889            assert_eq!(packet.payload, vec![0x01, 0x02]);
11890            assert!(
11891                started.elapsed() > Duration::from_millis(250),
11892                "the whole packet must outlast one 100 ms inactivity window"
11893            );
11894        });
11895    }
11896
11897    #[test]
11898    fn f2_address_list_yields_all_addresses_in_order() {
11899        let desc = EasyConnect::parse_descriptor(
11900            "(DESCRIPTION=(ADDRESS_LIST=\
11901             (ADDRESS=(PROTOCOL=tcp)(HOST=primary)(PORT=1521))\
11902             (ADDRESS=(PROTOCOL=tcp)(HOST=standby)(PORT=1522)))\
11903             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11904        )
11905        .expect("parse");
11906        let addrs = resolve_connect_addresses(&desc, NetProtocol::Tcp);
11907        assert_eq!(
11908            addrs,
11909            vec![
11910                ConnectAddress {
11911                    host: "primary".into(),
11912                    port: 1521
11913                },
11914                ConnectAddress {
11915                    host: "standby".into(),
11916                    port: 1522
11917                },
11918            ]
11919        );
11920    }
11921
11922    #[test]
11923    fn f2_failover_off_keeps_only_first_address() {
11924        let desc = EasyConnect::parse_descriptor(
11925            "(DESCRIPTION=(ADDRESS_LIST=(FAILOVER=OFF)\
11926             (ADDRESS=(PROTOCOL=tcp)(HOST=only)(PORT=1521))\
11927             (ADDRESS=(PROTOCOL=tcp)(HOST=nope)(PORT=1522)))\
11928             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11929        )
11930        .expect("parse");
11931        let addrs = resolve_connect_addresses(&desc, NetProtocol::Tcp);
11932        assert_eq!(
11933            addrs,
11934            vec![ConnectAddress {
11935                host: "only".into(),
11936                port: 1521
11937            }]
11938        );
11939    }
11940
11941    #[test]
11942    fn f2_load_balance_preserves_address_set() {
11943        // LOAD_BALANCE may reorder, but every address must still be present.
11944        let desc = EasyConnect::parse_descriptor(
11945            "(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)\
11946             (ADDRESS=(PROTOCOL=tcp)(HOST=a)(PORT=1))\
11947             (ADDRESS=(PROTOCOL=tcp)(HOST=b)(PORT=2))\
11948             (ADDRESS=(PROTOCOL=tcp)(HOST=c)(PORT=3)))\
11949             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11950        )
11951        .expect("parse");
11952        let mut addrs = resolve_connect_addresses(&desc, NetProtocol::Tcp);
11953        addrs.sort_by_key(|address| address.port);
11954        assert_eq!(
11955            addrs,
11956            vec![
11957                ConnectAddress {
11958                    host: "a".into(),
11959                    port: 1
11960                },
11961                ConnectAddress {
11962                    host: "b".into(),
11963                    port: 2
11964                },
11965                ConnectAddress {
11966                    host: "c".into(),
11967                    port: 3
11968                },
11969            ]
11970        );
11971    }
11972
11973    #[test]
11974    fn f2_only_primary_protocol_addresses_are_candidates() {
11975        // A mixed-protocol descriptor only yields the primary-protocol
11976        // endpoints (the transport/TLS setup is resolved for one protocol).
11977        let desc = EasyConnect::parse_descriptor(
11978            "(DESCRIPTION=(ADDRESS_LIST=\
11979             (ADDRESS=(PROTOCOL=tcp)(HOST=plain)(PORT=1521))\
11980             (ADDRESS=(PROTOCOL=tcps)(HOST=secure)(PORT=2484)))\
11981             (CONNECT_DATA=(SERVICE_NAME=svc)))",
11982        )
11983        .expect("parse");
11984        assert_eq!(
11985            resolve_connect_addresses(&desc, NetProtocol::Tcp),
11986            vec![ConnectAddress {
11987                host: "plain".into(),
11988                port: 1521
11989            }]
11990        );
11991        assert_eq!(
11992            resolve_connect_addresses(&desc, NetProtocol::Tcps),
11993            vec![ConnectAddress {
11994                host: "secure".into(),
11995                port: 2484
11996            }]
11997        );
11998    }
11999
12000    #[test]
12001    fn f2_transport_attempt_type_only_covers_io_and_tls_handshake() {
12002        // Only errors constructible inside `dial` can reach the failover loop.
12003        // Configuration/auth errors remain ordinary `Error` values and have no
12004        // conversion into this transport-attempt type.
12005        let io_failure = TransportEstablishmentError::from(std::io::Error::new(
12006            std::io::ErrorKind::ConnectionRefused,
12007            "refused",
12008        ));
12009        assert!(matches!(
12010            io_failure.into_driver_error(),
12011            Error::Io(error) if error.kind() == std::io::ErrorKind::ConnectionRefused
12012        ));
12013
12014        let tls_failure = TransportEstablishmentError::from(tls::TlsHandshakeError::new(
12015            "certificate rejected".to_string(),
12016        ));
12017        assert!(matches!(
12018            tls_failure.into_driver_error(),
12019            Error::Tls(detail) if detail == "TCPS handshake failed: certificate rejected"
12020        ));
12021    }
12022
12023    #[test]
12024    fn api_design_nothing_lost_map_covers_current_surface() {
12025        // `BindValue` / `QueryValue` are `#[non_exhaustive]`: the exhaustive
12026        // variant-name `match` that flags a newly-added variant now lives on the
12027        // types themselves (in oracledb-protocol), so this cross-crate test reads
12028        // through the stable `variant_name()` accessor instead of a fragile
12029        // external match. The compile-time tripwire is preserved where the enums
12030        // are defined.
12031        assert_eq!(BindValue::Null.variant_name(), "Null");
12032        assert_eq!(QueryValue::Text(String::new()).variant_name(), "Text");
12033
12034        let design = include_str!("../../../docs/API_DESIGN.md");
12035        for method in [
12036            "execute_query_for_registration",
12037            "execute_query",
12038            "execute_query_collect",
12039            "execute_query_with_timeout",
12040            "execute_query_with_binds",
12041            "execute_query_with_binds_and_timeout",
12042            "query",
12043            "query_named",
12044            "query_named_with_timeout",
12045            "execute_query_with_bind_rows",
12046            "execute_query_with_bind_rows_and_options",
12047            "execute_query_with_bind_rows_and_timeout",
12048            "execute_query_with_bind_rows_options_and_timeout",
12049        ] {
12050            assert!(design.contains(method), "API_DESIGN.md missing {method}");
12051        }
12052
12053        for group in 1..=24 {
12054            let marker = format!("C{group:02}");
12055            assert!(
12056                design.contains(&marker),
12057                "API_DESIGN.md missing capability group {marker}"
12058            );
12059        }
12060
12061        for field in [
12062            "batcherrors",
12063            "arraydmlrowcounts",
12064            "parse_only",
12065            "token_num",
12066            "cursor_id",
12067            "cache_statement",
12068            "scrollable",
12069            "fetch_orientation",
12070            "fetch_pos",
12071            "scroll_operation",
12072            "suspend_on_success",
12073            "no_prefetch",
12074            "registration_id",
12075            "max_string_size",
12076        ] {
12077            assert!(
12078                design.contains(field),
12079                "API_DESIGN.md missing ExecuteOptions field {field}"
12080            );
12081        }
12082
12083        let bind_variants = [
12084            "Null",
12085            "TypedNull",
12086            "Output",
12087            "ReturnOutput",
12088            "ObjectOutput",
12089            "ObjectInput",
12090            "Text",
12091            "Raw",
12092            "Lob",
12093            "Number",
12094            "BinaryInteger",
12095            "BinaryDouble",
12096            "BinaryFloat",
12097            "Boolean",
12098            "IntervalDS",
12099            "IntervalYM",
12100            "DateTime",
12101            "Timestamp",
12102            "TimestampTz",
12103            "Array",
12104            "Vector",
12105            "Json",
12106            "Cursor",
12107        ];
12108        assert_eq!(bind_variants.len(), 23);
12109        for variant in bind_variants {
12110            assert!(
12111                design.contains(&format!("`{variant}`")),
12112                "API_DESIGN.md missing BindValue::{variant}"
12113            );
12114        }
12115
12116        let query_variants = [
12117            "Text",
12118            "TextRaw",
12119            "Raw",
12120            "Rowid",
12121            "BinaryDouble",
12122            "IntervalDS",
12123            "IntervalYM",
12124            "Number",
12125            "Boolean",
12126            "Cursor",
12127            "DateTime",
12128            "TimestampTz",
12129            "Object",
12130            "Lob",
12131            "Vector",
12132            "Json",
12133            "Array",
12134        ];
12135        assert_eq!(query_variants.len(), 17);
12136        for variant in query_variants {
12137            assert!(
12138                design.contains(&format!("`{variant}`")),
12139                "API_DESIGN.md missing QueryValue::{variant}"
12140            );
12141        }
12142    }
12143
12144    #[test]
12145    fn migration_guide_covers_every_deprecated_method() {
12146        // No orphan removal: every old execute/query name that carried a
12147        // `#[deprecated(since = "0.3.0")]` shim and is now removed in
12148        // 0.5.0 must still appear in the user-facing 0.3.0 migration
12149        // guide, so an external consumer can always find the replacement.
12150        // These are exactly the names listed in API_DESIGN.md §8.
12151        let guide = include_str!("../../../docs/MIGRATING-0.3.md");
12152        for method in [
12153            "execute_query",
12154            "execute_query_collect",
12155            "execute_query_with_timeout",
12156            "execute_query_with_binds",
12157            "execute_query_with_binds_and_timeout",
12158            "query_named",
12159            "query_named_with_timeout",
12160            "execute_query_with_bind_rows",
12161            "execute_query_with_bind_rows_and_options",
12162            "execute_query_with_bind_rows_and_timeout",
12163            "execute_query_with_bind_rows_options_and_timeout",
12164            "execute_query_for_registration",
12165        ] {
12166            assert!(
12167                guide.contains(method),
12168                "MIGRATING-0.3.md missing deprecated method {method}"
12169            );
12170        }
12171        // The replacement families and builders must be documented too.
12172        for replacement in [
12173            "query_with",
12174            "execute_with",
12175            "execute_many",
12176            "execute_many_with",
12177            "register_query",
12178            "query_one",
12179            "query_opt",
12180            "query_all",
12181            "Query::timeout",
12182            "Execute::raw_options",
12183            "Batch::raw_options",
12184            "Registration::new",
12185            "execute_raw",
12186        ] {
12187            assert!(
12188                guide.contains(replacement),
12189                "MIGRATING-0.3.md missing replacement {replacement}"
12190            );
12191        }
12192        // The one-release removal window must be stated so external users know
12193        // the shims disappear in 0.5.0.
12194        assert!(
12195            guide.contains("0.5.0"),
12196            "MIGRATING-0.3.md must state the shims are removed in 0.5.0"
12197        );
12198    }
12199
12200    fn cache_entry(sql: &str, cursor_id: u32) -> CachedStatement {
12201        CachedStatement {
12202            sql: sql.into(),
12203            cursor_id,
12204            bind_shape: Vec::new(),
12205        }
12206    }
12207
12208    #[test]
12209    fn statement_cache_evicts_lru_past_capacity() {
12210        let mut cache = Vec::new();
12211        // capacity 2: a third distinct statement evicts the oldest (cursor 10).
12212        assert!(statement_cache_insert(&mut cache, 2, "a", 10, Vec::new()).is_empty());
12213        assert!(statement_cache_insert(&mut cache, 2, "b", 11, Vec::new()).is_empty());
12214        assert_eq!(
12215            statement_cache_insert(&mut cache, 2, "c", 12, Vec::new()),
12216            vec![10]
12217        );
12218        assert_eq!(
12219            cache,
12220            vec![cache_entry("b", 11), cache_entry("c", 12)],
12221            "LRU order retained"
12222        );
12223        // Re-inserting an existing SQL with a new cursor closes the old cursor
12224        // and moves it to most-recently-used; nothing is evicted.
12225        assert_eq!(
12226            statement_cache_insert(&mut cache, 2, "b", 99, Vec::new()),
12227            vec![11]
12228        );
12229        assert_eq!(cache, vec![cache_entry("c", 12), cache_entry("b", 99)]);
12230    }
12231
12232    #[test]
12233    fn statement_cache_size_zero_disables_caching() {
12234        let mut cache = Vec::new();
12235        // capacity 0: the freshly inserted cursor is itself evicted (queued for
12236        // close) and the cache stays empty — caching disabled.
12237        assert_eq!(
12238            statement_cache_insert(&mut cache, 0, "a", 10, Vec::new()),
12239            vec![10]
12240        );
12241        assert!(cache.is_empty(), "size 0 must never retain a statement");
12242        // A no-cursor (0) insert is never cached and closes nothing.
12243        assert!(statement_cache_insert(&mut cache, 5, "a", 0, Vec::new()).is_empty());
12244        assert!(cache.is_empty());
12245    }
12246
12247    fn shape_of(values: &[BindValue]) -> Vec<BindShapeSlot> {
12248        bind_type_shape(&[values.to_vec()])
12249    }
12250
12251    #[test]
12252    fn bind_type_shape_change_is_incompatible_but_size_change_is_not() {
12253        use oracledb_protocol::thin::ORA_TYPE_NUM_LONG;
12254        let number = shape_of(&[BindValue::Number("42".into())]);
12255        let short_text = shape_of(&[BindValue::Text("a".into())]);
12256        let long_text = shape_of(&[BindValue::Text("x".repeat(40_000))]);
12257        let raw = shape_of(&[BindValue::Raw(vec![1, 2, 3])]);
12258        // The repro from bead rust-oracledb-ilel: NUMBER -> TEXT must NOT
12259        // reuse the cached cursor (server-side ORA-01722), nor TEXT -> RAW.
12260        assert!(!bind_shape_is_compatible(&number, &short_text));
12261        assert!(!bind_shape_is_compatible(&short_text, &number));
12262        assert!(!bind_shape_is_compatible(&short_text, &raw));
12263        assert!(!bind_shape_is_compatible(&raw, &number));
12264        // Same type family: identical, and a pure size change stays
12265        // compatible (no re-parse on every string-length change).
12266        assert!(bind_shape_is_compatible(&number, &number));
12267        assert!(bind_shape_is_compatible(&short_text, &long_text));
12268        assert!(bind_shape_is_compatible(&long_text, &short_text));
12269        // CHAR/VARCHAR/LONG fold into one family (the wire writer merges them
12270        // via bind_metadata_types_are_compatible).
12271        let long_typed = shape_of(&[BindValue::TypedNull {
12272            ora_type_num: ORA_TYPE_NUM_LONG,
12273            csfrm: 1,
12274            buffer_size: 10,
12275        }]);
12276        assert!(bind_shape_is_compatible(&short_text, &long_typed));
12277        // Bind-count mismatch is never compatible.
12278        assert!(!bind_shape_is_compatible(
12279            &number,
12280            &shape_of(&[BindValue::Number("1".into()), BindValue::Number("2".into())])
12281        ));
12282    }
12283
12284    #[test]
12285    fn bind_type_shape_untyped_null_matches_any_cached_slot() {
12286        let number = shape_of(&[BindValue::Number("42".into())]);
12287        let null = shape_of(&[BindValue::Null]);
12288        assert!(null[0].untyped_null);
12289        // A NULL bind rides any cached cursor (written as a placeholder, the
12290        // value null-converts server-side)...
12291        assert!(bind_shape_is_compatible(&number, &null));
12292        // ...but a concrete NUMBER does not ride a cursor parsed with the
12293        // VARCHAR placeholder: re-parse for correct select-list typing.
12294        assert!(!bind_shape_is_compatible(&null, &number));
12295        // Text matches the placeholder family.
12296        assert!(bind_shape_is_compatible(
12297            &null,
12298            &shape_of(&[BindValue::Text("x".into())])
12299        ));
12300    }
12301
12302    #[test]
12303    fn bind_type_shape_infers_column_type_from_first_non_null_row() {
12304        // executemany with a leading NULL: the column type comes from the
12305        // first non-NULL row (same inference as the wire metadata writer).
12306        let rows = vec![
12307            vec![BindValue::Null],
12308            vec![BindValue::Number("7".into())],
12309            vec![BindValue::Null],
12310        ];
12311        let shape = bind_type_shape(&rows);
12312        assert!(!shape[0].untyped_null);
12313        assert_eq!(
12314            shape,
12315            shape_of(&[BindValue::Number("7".into())]),
12316            "inferred NUMBER column"
12317        );
12318        // All-NULL column stays a wildcard.
12319        let all_null = bind_type_shape(&[vec![BindValue::Null], vec![BindValue::Null]]);
12320        assert!(all_null[0].untyped_null);
12321    }
12322
12323    #[test]
12324    fn statement_cache_insert_inherits_concrete_slot_over_untyped_null() {
12325        // First execute binds NUMBER; a later re-execute of the SAME cursor
12326        // binds NULL. The stored shape must keep NUMBER (the cursor is still
12327        // parsed for NUMBER), so a following NUMBER execute reuses it.
12328        let number = shape_of(&[BindValue::Number("42".into())]);
12329        let null = shape_of(&[BindValue::Null]);
12330        let mut cache = Vec::new();
12331        assert!(statement_cache_insert(&mut cache, 5, "q", 10, number.clone()).is_empty());
12332        assert!(statement_cache_insert(&mut cache, 5, "q", 10, null).is_empty());
12333        assert_eq!(cache[0].bind_shape, number, "concrete slot inherited");
12334        // A REPLACED cursor (fresh parse) records the new shape verbatim.
12335        let text = shape_of(&[BindValue::Text("x".into())]);
12336        assert_eq!(
12337            statement_cache_insert(&mut cache, 5, "q", 11, text.clone()),
12338            vec![10]
12339        );
12340        assert_eq!(cache[0].bind_shape, text);
12341    }
12342
12343    /// This test previously asserted the wrap it was named for
12344    /// (`auth_serial_num_truncates_to_low_u16_instead_of_rejecting`), pinning
12345    /// 70000 -> 4464 as intended behaviour. A wrapped serial is a session
12346    /// identity the server never issued, so the contract is now rejection.
12347    #[test]
12348    fn auth_serial_num_out_of_u16_range_is_rejected_not_wrapped() {
12349        for out_of_range in ["65536", "70000", "4294967296", "-1"] {
12350            let mut data = BTreeMap::new();
12351            data.insert("AUTH_SERIAL_NUM".to_string(), out_of_range.to_string());
12352            let error = parse_session_u16(&data, "AUTH_SERIAL_NUM")
12353                .expect_err("a serial outside u16 must not be silently wrapped");
12354            assert!(
12355                matches!(error, Error::MissingSessionField("AUTH_SERIAL_NUM")),
12356                "out-of-range {out_of_range} must use the existing typed session-field error, got {error:?}"
12357            );
12358        }
12359    }
12360
12361    /// Positive acceptance: the whole u16 domain still parses exactly, so
12362    /// ordinary authentication fixtures are unaffected.
12363    #[test]
12364    fn auth_serial_num_parses_the_full_u16_domain_exactly() {
12365        for (text, expected) in [("0", 0_u16), ("1", 1), ("4464", 4464), ("65535", 65535)] {
12366            let mut data = BTreeMap::new();
12367            data.insert("AUTH_SERIAL_NUM".to_string(), text.to_string());
12368            assert_eq!(
12369                parse_session_u16(&data, "AUTH_SERIAL_NUM").expect("in-range serial parses"),
12370                expected
12371            );
12372        }
12373    }
12374
12375    #[test]
12376    fn db_unique_name_reads_real_key_not_confused_with_dbunique_name() {
12377        // etib.8: db_unique_name comes from AUTH_SC_REAL_DBUNIQUE_NAME ONLY. It
12378        // must NOT be confused with AUTH_SC_DBUNIQUE_NAME (which upstream maps to
12379        // db_name), and there is no fallback to it.
12380        let mut data = BTreeMap::new();
12381        data.insert(
12382            "AUTH_SC_REAL_DBUNIQUE_NAME".to_string(),
12383            "MYCDB_UNIQUE".to_string(),
12384        );
12385        data.insert(
12386            "AUTH_SC_DBUNIQUE_NAME".to_string(),
12387            "MYCDB_SHOULD_NOT_WIN".to_string(),
12388        );
12389        assert_eq!(parse_db_unique_name(&data).as_deref(), Some("MYCDB_UNIQUE"));
12390
12391        // Only the non-REAL key present -> None (no fallback).
12392        let mut only_non_real = BTreeMap::new();
12393        only_non_real.insert("AUTH_SC_DBUNIQUE_NAME".to_string(), "MYCDB".to_string());
12394        assert_eq!(parse_db_unique_name(&only_non_real), None);
12395
12396        // Missing entirely -> None.
12397        assert_eq!(parse_db_unique_name(&BTreeMap::new()), None);
12398    }
12399
12400    // Character column of the first `needle` in `line` (chars, not bytes — the
12401    // caret aligns by display column, so multibyte chars must be counted as 1).
12402    fn char_col(line: &str, needle: char) -> usize {
12403        line.chars()
12404            .position(|c| c == needle)
12405            .expect("char present")
12406    }
12407
12408    #[test]
12409    fn caret_points_at_the_flagged_char() {
12410        // offset 8 (1-based) is the `x`.
12411        let out = render_caret("select x from t", 8, "ORA-00904: invalid identifier");
12412        let lines: Vec<&str> = out.lines().collect();
12413        assert_eq!(lines[0], "ORA-00904: invalid identifier");
12414        assert!(lines[2].ends_with("select x from t"), "{:?}", lines[2]);
12415        assert_eq!(
12416            char_col(lines[3], '^'),
12417            char_col(lines[2], 'x'),
12418            "caret column must align under the flagged char"
12419        );
12420    }
12421
12422    #[test]
12423    fn caret_handles_multiline_sql() {
12424        // "select *\n" is 9 chars (\n at index 8); the `n` of `no_such` is char
12425        // index 14 -> 1-based offset 15, on line 2.
12426        let out = render_caret("select *\nfrom no_such", 15, "ORA-00942");
12427        let lines: Vec<&str> = out.lines().collect();
12428        assert!(lines[2].starts_with("2 | from no_such"), "{:?}", lines[2]);
12429        assert_eq!(char_col(lines[3], '^'), char_col(lines[2], 'n'));
12430    }
12431
12432    #[test]
12433    fn caret_counts_unicode_scalar_values() {
12434        // The multibyte `é` before the offset must not push the caret off — we
12435        // count chars, not bytes.
12436        let sql = "select 'café' x from t";
12437        let x_idx = sql.chars().position(|c| c == 'x').unwrap();
12438        let out = render_caret(sql, x_idx + 1, "h");
12439        let lines: Vec<&str> = out.lines().collect();
12440        assert_eq!(char_col(lines[3], '^'), char_col(lines[2], 'x'));
12441    }
12442
12443    #[test]
12444    fn caret_clamps_and_never_panics() {
12445        // out-of-range, zero, and empty inputs must render without panicking.
12446        let _ = render_caret("select 1", 999, "h");
12447        let _ = render_caret("select 1", 0, "h");
12448        let _ = render_caret("", 5, "h");
12449        assert!(render_caret("abc", 4, "h").ends_with('^'));
12450    }
12451
12452    fn identity() -> ClientIdentity {
12453        ClientIdentity::new("program", "machine", "osuser", "terminal", "driver")
12454            .expect("test identity should be valid")
12455    }
12456
12457    pub(crate) fn loopback_connection(
12458        read: transport::OracleReadHalf,
12459        write: transport::OracleWriteHalf,
12460    ) -> Connection {
12461        loopback_connection_from_core(ConnectionCore::<DriverTransport>::from_halves(
12462            read,
12463            write,
12464            "loopback_test_write",
12465        ))
12466    }
12467
12468    fn loopback_connection_from_core(core: DriverCore) -> Connection {
12469        Connection {
12470            descriptor: EasyConnect::parse("127.0.0.1:1521/FREEPDB1")
12471                .expect("test connect string should parse"),
12472            identity: identity(),
12473            core,
12474            session_id: 0,
12475            serial_num: 0,
12476            server_version: None,
12477            server_version_tuple: None,
12478            db_unique_name: None,
12479            capabilities: ClientCapabilities::default(),
12480            protocol_limits: ProtocolLimits::DEFAULT,
12481            ttc_seq_num: 0,
12482            sdu: 8192,
12483            protocol_version: 0,
12484            supports_fast_auth: false,
12485            supports_end_of_response: true,
12486            supports_oob: false,
12487            cursor_columns: BTreeMap::new(),
12488            fetch_metadata_by_sql: HashMap::new(),
12489            fetch_metadata_order: VecDeque::new(),
12490            shape_cache: Arc::new(StatementShapeCache::new()),
12491            dead: false,
12492            user: "test_user".into(),
12493            combo_key: Vec::new(),
12494            statement_cache: Vec::new(),
12495            statement_cache_size: STATEMENT_CACHE_SIZE,
12496            in_use_cursors: HashSet::new(),
12497            lob_prefetch_cursors: BTreeSet::new(),
12498            copied_cursors: HashSet::new(),
12499            cursors_to_close: Vec::new(),
12500            sessionless_data: None,
12501            notification_buffer: Vec::new(),
12502            notification_header_consumed: false,
12503            transaction_context: None,
12504            txn_in_progress: false,
12505            #[cfg(feature = "cassette")]
12506            capture_guard: None,
12507        }
12508    }
12509
12510    #[cfg(feature = "cassette")]
12511    fn synthetic_number_columns() -> Vec<ColumnMetadata> {
12512        vec![
12513            ColumnMetadata::new("INTCOL", oracledb_protocol::thin::ORA_TYPE_NUM_NUMBER)
12514                .with_csfrm(oracledb_protocol::thin::CS_FORM_IMPLICIT)
12515                .with_buffer_size(22)
12516                .with_max_size(22)
12517                .with_nulls_allowed(true),
12518            ColumnMetadata::new("NUMBERCOL", oracledb_protocol::thin::ORA_TYPE_NUM_NUMBER)
12519                .with_csfrm(oracledb_protocol::thin::CS_FORM_IMPLICIT)
12520                .with_buffer_size(22)
12521                .with_max_size(22)
12522                .with_nulls_allowed(true),
12523        ]
12524    }
12525
12526    #[cfg(feature = "cassette")]
12527    fn synthetic_connect_packet() -> Result<Vec<u8>> {
12528        let payload = build_connect_packet_payload(
12529            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=fixture-host)(PORT=0))\
12530             (CONNECT_DATA=(SERVICE_NAME=SYNTHETIC)(CID=(PROGRAM=rust-oracledb)\
12531             (HOST=fixture-host)(USER=fixture-user))))",
12532            8192,
12533        )?;
12534        Ok(encode_packet(
12535            TNS_PACKET_TYPE_CONNECT,
12536            0,
12537            None,
12538            &payload,
12539            PacketLengthWidth::Legacy16,
12540        )?)
12541    }
12542
12543    #[cfg(feature = "cassette")]
12544    fn synthetic_accept_packet() -> Result<Vec<u8>> {
12545        Ok(encode_packet(
12546            TNS_PACKET_TYPE_ACCEPT,
12547            0,
12548            None,
12549            b"SYNTHETIC-ACCEPT",
12550            PacketLengthWidth::Legacy16,
12551        )?)
12552    }
12553
12554    #[cfg(feature = "cassette")]
12555    fn synthetic_execute_packet() -> Result<Vec<u8>> {
12556        let payload = build_execute_payload_with_bind_rows_and_options_with_seq(
12557            "select value from synthetic_fixture",
12558            2,
12559            1,
12560            true,
12561            &[],
12562            ExecuteOptions::default(),
12563            ClientCapabilities::default().ttc_field_version,
12564        )?;
12565        Ok(encode_packet(
12566            TNS_PACKET_TYPE_DATA,
12567            0,
12568            Some(0),
12569            &payload,
12570            PacketLengthWidth::Large32,
12571        )?)
12572    }
12573
12574    #[cfg(feature = "cassette")]
12575    fn synthetic_fetch_packet() -> Result<Vec<u8>> {
12576        let payload =
12577            build_fetch_payload_with_seq(42, 2, 2, ClientCapabilities::default().ttc_field_version);
12578        Ok(encode_packet(
12579            TNS_PACKET_TYPE_DATA,
12580            0,
12581            Some(0),
12582            &payload,
12583            PacketLengthWidth::Large32,
12584        )?)
12585    }
12586
12587    #[cfg(feature = "cassette")]
12588    fn synthetic_function_packet(function_code: u8, seq_num: u8) -> Result<Vec<u8>> {
12589        let payload = build_function_payload_with_seq(
12590            function_code,
12591            seq_num,
12592            ClientCapabilities::default().ttc_field_version,
12593        );
12594        Ok(encode_packet(
12595            TNS_PACKET_TYPE_DATA,
12596            0,
12597            Some(0),
12598            &payload,
12599            PacketLengthWidth::Large32,
12600        )?)
12601    }
12602
12603    #[cfg(feature = "cassette")]
12604    fn hex_value(byte: u8) -> Result<u8> {
12605        match byte {
12606            b'0'..=b'9' => Ok(byte - b'0'),
12607            b'a'..=b'f' => Ok(byte - b'a' + 10),
12608            b'A'..=b'F' => Ok(byte - b'A' + 10),
12609            _ => Err(Error::Runtime(format!(
12610                "invalid synthetic fixture hex byte {byte:#04x}"
12611            ))),
12612        }
12613    }
12614
12615    #[cfg(feature = "cassette")]
12616    fn decode_hex_fixture(hex: &str) -> Result<Vec<u8>> {
12617        let clean = hex
12618            .bytes()
12619            .filter(|byte| !byte.is_ascii_whitespace())
12620            .collect::<Vec<_>>();
12621        if clean.len() % 2 != 0 {
12622            return Err(Error::Runtime(
12623                "synthetic fixture hex must contain an even number of digits".into(),
12624            ));
12625        }
12626        let mut out = Vec::with_capacity(clean.len() / 2);
12627        for pair in clean.chunks_exact(2) {
12628            out.push((hex_value(pair[0])? << 4) | hex_value(pair[1])?);
12629        }
12630        Ok(out)
12631    }
12632
12633    #[cfg(feature = "cassette")]
12634    fn synthetic_execute_response_payload() -> Result<Vec<u8>> {
12635        decode_hex_fixture(concat!(
12636            "101710740fb986350b6010fbcb6e06a74ed0787e060a110328014001018201800000",
12637            "014000000000020369010140023ffe010501050556414c554500000000000000000000",
12638            "010707787e060a110b1000021fe8010a010a00062201010001020000000708414c33",
12639            "32555446380801060323a4d500010100000000000004010102013b010102057b0000",
12640            "01010003000000000000000000000000030001010000000002057b0101010300194f",
12641            "52412d30313430333a206e6f206461746120666f756e640a1d",
12642        ))
12643    }
12644
12645    #[cfg(feature = "cassette")]
12646    fn synthetic_fetch_response_payload() -> Result<Vec<u8>> {
12647        decode_hex_fixture("06020101000205dc0001010101000702c1041d")
12648    }
12649
12650    #[cfg(feature = "cassette")]
12651    fn synthetic_plain_function_response_payload() -> [u8; 1] {
12652        [TNS_MSG_TYPE_END_OF_RESPONSE]
12653    }
12654
12655    #[cfg(feature = "cassette")]
12656    #[test]
12657    fn synthetic_cassette_replays_connect_execute_fetch_close_offline() -> Result<()> {
12658        let cassette = include_bytes!("../tests/fixtures/cassettes/select_7_plus_5.tns-cassette");
12659        let (read, write, audit) =
12660            transport::replay_split_with_audit(cassette, transport::ReplayWriteMode::Check)
12661                .map_err(|err| Error::Runtime(format!("invalid replay cassette: {err}")))?;
12662        let mut core = ConnectionCore::<DriverTransport>::from_halves(
12663            read,
12664            write,
12665            "synthetic_fixture_replay_write",
12666        );
12667        let runtime = build_io_runtime()?;
12668
12669        runtime.block_on(async {
12670            let cx = test_cx()?;
12671            let connect_packet = synthetic_connect_packet()?;
12672            core.write_all(&cx, &connect_packet).await?;
12673            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
12674            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
12675            assert_eq!(accept.payload, b"SYNTHETIC-ACCEPT");
12676
12677            let mut conn = loopback_connection_from_core(core);
12678            let execute = conn
12679                .execute_raw(
12680                    &cx,
12681                    "select value from synthetic_fixture",
12682                    2,
12683                    &[],
12684                    ExecuteOptions::default(),
12685                    None,
12686                )
12687                .await?;
12688            assert_eq!(execute.columns.len(), 1);
12689            assert_eq!(execute.rows.len(), 1);
12690            assert_eq!(
12691                execute.cell(0, 0).and_then(QueryValue::as_text),
12692                Some("AL32UTF8")
12693            );
12694
12695            let previous_row = vec![
12696                Some(QueryValue::number_from_text("2", true)),
12697                Some(QueryValue::number_from_text("0.5", false)),
12698            ];
12699            let columns = synthetic_number_columns();
12700            let fetched = conn
12701                .fetch_rows_with_columns(&cx, 42, 2, &columns, Some(&previous_row))
12702                .await?;
12703            assert_eq!(fetched.rows.len(), 1);
12704            assert_eq!(
12705                fetched
12706                    .cell(0, 0)
12707                    .and_then(QueryValue::as_number_text)
12708                    .as_deref(),
12709                Some("3")
12710            );
12711            assert_eq!(
12712                fetched
12713                    .cell(0, 1)
12714                    .and_then(QueryValue::as_number_text)
12715                    .as_deref(),
12716                Some("0.5")
12717            );
12718
12719            conn.close(&cx).await?;
12720            Ok::<_, Error>(())
12721        })?;
12722
12723        audit
12724            .assert_finished()
12725            .map_err(|err| Error::Runtime(err.to_string()))?;
12726        let _ = (
12727            synthetic_accept_packet()?,
12728            synthetic_execute_packet()?,
12729            synthetic_fetch_packet()?,
12730            synthetic_function_packet(TNS_FUNC_ROLLBACK, 3)?,
12731            synthetic_function_packet(TNS_FUNC_LOGOFF, 4)?,
12732            synthetic_execute_response_payload()?,
12733            synthetic_fetch_response_payload()?,
12734            synthetic_plain_function_response_payload(),
12735        );
12736        Ok(())
12737    }
12738
12739    fn server_error(message: &str) -> Error {
12740        Error::Protocol(oracledb_protocol::ProtocolError::ServerError(
12741            message.to_string(),
12742        ))
12743    }
12744
12745    fn structured_error(code: u32, pos: i32) -> Error {
12746        Error::Protocol(oracledb_protocol::ProtocolError::ServerErrorInfo(Box::new(
12747            oracledb_protocol::ServerErrorDetails {
12748                message: format!("ORA-{code:05}: synthetic"),
12749                code,
12750                pos,
12751                ..Default::default()
12752            },
12753        )))
12754    }
12755
12756    fn column(name: &str, ora_type_num: u8, is_json: bool) -> ColumnMetadata {
12757        ColumnMetadata::new(name, ora_type_num).with_is_json(is_json)
12758    }
12759
12760    #[test]
12761    fn json_lob_probe_candidates_selects_named_non_json_lobs() {
12762        use oracledb_protocol::thin::{ORA_TYPE_NUM_BLOB, ORA_TYPE_NUM_CLOB, ORA_TYPE_NUM_VARCHAR};
12763        let columns = vec![
12764            column("doc", ORA_TYPE_NUM_CLOB, false),         // candidate
12765            column("blob_doc", ORA_TYPE_NUM_BLOB, false),    // candidate
12766            column("already_json", ORA_TYPE_NUM_CLOB, true), // skipped: is_json
12767            column("name", ORA_TYPE_NUM_VARCHAR, false),     // skipped: not a LOB
12768            column("", ORA_TYPE_NUM_CLOB, false),            // skipped: unnamed expression
12769        ];
12770        // Names come back upper-cased (the catalog stores them upper-cased) and
12771        // only the two named, non-JSON LOB columns are probed, by original index.
12772        assert_eq!(
12773            json_lob_probe_candidates(&columns),
12774            vec![(0, "DOC".to_string()), (1, "BLOB_DOC".to_string())]
12775        );
12776    }
12777
12778    #[test]
12779    fn json_lob_probe_candidates_empty_when_no_lobs() {
12780        use oracledb_protocol::thin::ORA_TYPE_NUM_VARCHAR;
12781        let columns = vec![column("name", ORA_TYPE_NUM_VARCHAR, false)];
12782        assert!(json_lob_probe_candidates(&columns).is_empty());
12783    }
12784
12785    #[test]
12786    fn ora_code_parses_from_message_and_struct() {
12787        // string path: parsed from the ORA- prefix
12788        assert_eq!(
12789            server_error("ORA-00060: deadlock detected").ora_code(),
12790            Some(60)
12791        );
12792        // structured path: read straight from .code
12793        assert_eq!(structured_error(942, 0).ora_code(), Some(942));
12794        // no ORA- code present
12795        assert_eq!(server_error("listener problem").ora_code(), None);
12796        // non-server errors have no code
12797        assert_eq!(Error::CallTimeout(500).ora_code(), None);
12798    }
12799
12800    #[test]
12801    fn stable_error_methods_classify_without_display_parsing() {
12802        let transient = server_error("ORA-00060: deadlock detected");
12803        assert_eq!(transient.kind(), ErrorKind::Database);
12804        assert_eq!(transient.oracle_code(), Some(60));
12805        assert_eq!(
12806            transient.connection_disposition(),
12807            ConnectionDisposition::Reusable
12808        );
12809        assert_eq!(
12810            transient.retry_hint(),
12811            RetryHint::RetrySameConnectionIfIdempotent
12812        );
12813
12814        let lost = server_error("ORA-03113: end-of-file on communication channel");
12815        assert_eq!(lost.kind(), ErrorKind::Database);
12816        assert_eq!(lost.connection_disposition(), ConnectionDisposition::Dead);
12817        assert_eq!(lost.retry_hint(), RetryHint::ReconnectThenRetryIfIdempotent);
12818
12819        let timeout = Error::CallTimeout(500);
12820        assert_eq!(timeout.kind(), ErrorKind::Timeout);
12821        assert_eq!(
12822            timeout.connection_disposition(),
12823            ConnectionDisposition::Reusable
12824        );
12825        assert_eq!(
12826            timeout.retry_hint(),
12827            RetryHint::RetrySameConnectionIfIdempotent
12828        );
12829
12830        let cancelled = Error::Cancelled;
12831        assert_eq!(cancelled.kind(), ErrorKind::Cancel);
12832        assert_eq!(cancelled.oracle_code(), Some(1013));
12833        assert_eq!(
12834            cancelled.retry_hint(),
12835            RetryHint::RetrySameConnectionIfIdempotent
12836        );
12837
12838        let bind = Error::Bind(BindError::PositionalCountMismatch {
12839            expected: 2,
12840            actual: 1,
12841        });
12842        assert_eq!(bind.kind(), ErrorKind::Conversion);
12843        assert_eq!(bind.retry_hint(), RetryHint::Never);
12844
12845        let resource = Error::Protocol(oracledb_protocol::ProtocolError::ResourceLimit {
12846            limit: "binds",
12847            observed: 4,
12848            maximum: 3,
12849        });
12850        assert_eq!(resource.kind(), ErrorKind::ResourceLimit);
12851        assert_eq!(
12852            resource.connection_disposition(),
12853            ConnectionDisposition::Reusable
12854        );
12855        assert_eq!(resource.retry_hint(), RetryHint::Never);
12856
12857        let session_dead = server_error("ORA-00600: internal error code, arguments: []");
12858        assert_eq!(
12859            session_dead.connection_disposition(),
12860            ConnectionDisposition::Dead
12861        );
12862        assert!(
12863            !session_dead.is_connection_lost(),
12864            "ORA-00600 kills the session but is not a connection-lost retry code"
12865        );
12866        assert_eq!(session_dead.retry_hint(), RetryHint::Never);
12867    }
12868
12869    // ---- W1-T6.2: internal Outcome/CancelKind discipline ----------------------
12870    //
12871    // Cancellation is not "just another error". Each asupersync `CancelKind`
12872    // drives a specific connection disposition BEFORE we flatten to the public
12873    // `Error` at the boundary, and the mapping is METHOD-based (it reads
12874    // `CancelReason::kind`), never a display-string parse.
12875
12876    #[test]
12877    fn cancel_kind_maps_to_disposition() {
12878        // The timeout family (deadline / quota exhaustion) drains and stays
12879        // reusable — it composes like a `call_timeout`.
12880        for kind in [
12881            CancelKind::Timeout,
12882            CancelKind::Deadline,
12883            CancelKind::PollQuota,
12884            CancelKind::CostBudget,
12885        ] {
12886            assert_eq!(
12887                CancelDisposition::from_kind(kind),
12888                CancelDisposition::Timeout,
12889                "{kind:?} must drain + stay reusable (timeout disposition)"
12890            );
12891        }
12892
12893        // Runtime shutdown / resource loss / linked-exit closes the connection.
12894        for kind in [
12895            CancelKind::Shutdown,
12896            CancelKind::ResourceUnavailable,
12897            CancelKind::LinkedExit,
12898        ] {
12899            assert_eq!(
12900                CancelDisposition::from_kind(kind),
12901                CancelDisposition::Close,
12902                "{kind:?} must close the connection"
12903            );
12904        }
12905
12906        // Explicit / topological cancels drain quietly and stay reusable.
12907        for kind in [
12908            CancelKind::User,
12909            CancelKind::RaceLost,
12910            CancelKind::FailFast,
12911            CancelKind::ParentCancelled,
12912        ] {
12913            assert_eq!(
12914                CancelDisposition::from_kind(kind),
12915                CancelDisposition::Cancel,
12916                "{kind:?} must drain quietly + stay reusable (cancel disposition)"
12917            );
12918        }
12919    }
12920
12921    #[test]
12922    fn cancel_disposition_flattens_to_distinct_error_variants() {
12923        // The boundary flatten: each disposition produces a DISTINCT public
12924        // error variant — a cancel is NEVER a generic `Runtime`/`Io` error — and
12925        // the resulting error classifies correctly via the W1-T6.1 methods.
12926
12927        // Timeout -> CallTimeout: reusable + retryable on the same connection.
12928        let timeout = CancelDisposition::Timeout.into_error(750);
12929        assert!(matches!(timeout, Error::CallTimeout(750)));
12930        assert_eq!(timeout.kind(), ErrorKind::Timeout);
12931        assert_eq!(
12932            timeout.connection_disposition(),
12933            ConnectionDisposition::Reusable
12934        );
12935        assert_eq!(
12936            timeout.retry_hint(),
12937            RetryHint::RetrySameConnectionIfIdempotent,
12938            "a drained timeout may be retried on the same connection"
12939        );
12940
12941        // Cancel -> Cancelled (ORA-01013): distinct cancel variant, reusable +
12942        // retryable — explicitly NOT Error::Runtime / Error::Io.
12943        let cancelled = CancelDisposition::Cancel.into_error(750);
12944        assert!(matches!(cancelled, Error::Cancelled));
12945        assert!(
12946            !matches!(cancelled, Error::Runtime(_) | Error::Io(_)),
12947            "a cancel must be a distinct variant, never a generic runtime/io error"
12948        );
12949        assert_eq!(cancelled.kind(), ErrorKind::Cancel);
12950        assert_eq!(cancelled.oracle_code(), Some(1013));
12951        assert_eq!(
12952            cancelled.connection_disposition(),
12953            ConnectionDisposition::Reusable
12954        );
12955        assert_eq!(
12956            cancelled.retry_hint(),
12957            RetryHint::RetrySameConnectionIfIdempotent
12958        );
12959
12960        // Close -> ConnectionClosed: connection is dead; reconnect before retry.
12961        let closed = CancelDisposition::Close.into_error(750);
12962        assert!(matches!(closed, Error::ConnectionClosed(_)));
12963        assert_eq!(closed.kind(), ErrorKind::Network);
12964        assert_eq!(closed.connection_disposition(), ConnectionDisposition::Dead);
12965        assert_eq!(
12966            closed.retry_hint(),
12967            RetryHint::ReconnectThenRetryIfIdempotent
12968        );
12969    }
12970
12971    /// The interrupt-vs-checkpoint race fix: Asupersync marks a cancelled
12972    /// in-flight read as `Interrupted` with the exact payload `"cancelled"`, and
12973    /// the driver keys off that DETERMINISTIC marker so a real cancellation is
12974    /// never mistyped as a raw `Io(Interrupted)` when a *later* `checkpoint()`
12975    /// on the reading thread has not yet observed the cancel flag. A genuine OS
12976    /// `EINTR` (any other message) is left untouched.
12977    #[test]
12978    fn asupersync_cancellation_marker_is_detected_deterministically() {
12979        use std::io::{Error as IoError, ErrorKind};
12980        assert!(
12981            is_asupersync_cancellation(&IoError::new(ErrorKind::Interrupted, "cancelled")),
12982            "the asupersync cancellation marker must be recognized regardless of checkpoint timing"
12983        );
12984        assert!(
12985            !is_asupersync_cancellation(&IoError::new(
12986                ErrorKind::Interrupted,
12987                "Interrupted system call"
12988            )),
12989            "a real OS EINTR (different message) must NOT be treated as a cancellation"
12990        );
12991        // A raw OS EINTR carries the platform's strerror text, never "cancelled".
12992        assert!(!is_asupersync_cancellation(&IoError::from_raw_os_error(4)));
12993        assert!(
12994            !is_asupersync_cancellation(&IoError::new(ErrorKind::WouldBlock, "cancelled")),
12995            "only the Interrupted kind is the cancellation signal"
12996        );
12997    }
12998
12999    #[test]
13000    fn missing_cancel_reason_is_a_plain_cancel_at_checkpoint() {
13001        // A cancel with no recorded `CancelReason` is still a cancel — never a
13002        // runtime error. (The in-operation timeout path defaults the OTHER way,
13003        // to Timeout, because it is entered by a deadline elapse; see
13004        // `recover_from_call_timeout`.)
13005        assert_eq!(cancel_disposition(None), CancelDisposition::Cancel);
13006    }
13007
13008    #[test]
13009    fn cancelled_cx_resolves_to_the_kind_mapped_distinct_error() {
13010        // End-to-end against a real asupersync context: inject a cancel of a
13011        // given kind, confirm `checkpoint()` actually fails and `cancel_reason()`
13012        // carries the kind, then assert the SAME mapping the between-round-trip
13013        // helper applies surfaces the kind-mapped DISTINCT error (never the old
13014        // Error::Runtime(display_string)). A `detached_cancel_context` carries
13015        // cancellation + budget state with no effect caps — exactly what a unit
13016        // test of the cancel mapping needs, with no live runtime required.
13017        fn err_for(kind: CancelKind) -> Error {
13018            let cx = Cx::detached_cancel_context();
13019            cx.cancel_with(kind, Some("test cancel"));
13020            // The cancel must actually be observable through the methods the
13021            // driver relies on — not a display string.
13022            assert!(
13023                cx.checkpoint().is_err(),
13024                "{kind:?}: a cancelled context must fail its checkpoint"
13025            );
13026            let reason = cx.cancel_reason().unwrap_or_else(|| {
13027                panic!("{kind:?}: cancel_reason must carry the structured kind")
13028            });
13029            assert_eq!(reason.kind, kind, "cancel_reason must round-trip the kind");
13030            cancel_disposition(Some(reason)).into_error(750)
13031        }
13032
13033        // Timeout family -> Error::CallTimeout (Timeout kind, reusable).
13034        for kind in [CancelKind::Timeout, CancelKind::Deadline] {
13035            let err = err_for(kind);
13036            assert!(
13037                matches!(err, Error::CallTimeout(_)),
13038                "{kind:?} should surface CallTimeout, got {err:?}"
13039            );
13040            assert_eq!(err.kind(), ErrorKind::Timeout);
13041        }
13042
13043        // Shutdown -> Error::ConnectionClosed (dead).
13044        let shutdown = err_for(CancelKind::Shutdown);
13045        assert!(
13046            matches!(shutdown, Error::ConnectionClosed(_)),
13047            "Shutdown should surface ConnectionClosed, got {shutdown:?}"
13048        );
13049        assert_eq!(
13050            shutdown.connection_disposition(),
13051            ConnectionDisposition::Dead
13052        );
13053
13054        // User / RaceLost -> Error::Cancelled (distinct, reusable) — and crucially
13055        // NOT the old Error::Runtime(display_string).
13056        for kind in [CancelKind::User, CancelKind::RaceLost] {
13057            let err = err_for(kind);
13058            assert!(
13059                matches!(err, Error::Cancelled),
13060                "{kind:?} should surface Cancelled, got {err:?}"
13061            );
13062            assert!(
13063                !matches!(err, Error::Runtime(_)),
13064                "{kind:?} must NOT be flattened to a generic Error::Runtime"
13065            );
13066            assert_eq!(err.kind(), ErrorKind::Cancel);
13067        }
13068    }
13069
13070    #[test]
13071    fn uncancelled_checkpoint_is_ok() {
13072        // The fast path: a healthy context passes the checkpoint untouched, so
13073        // the cancel-mapping branch is never taken.
13074        let cx = Cx::detached_cancel_context();
13075        assert!(cx.checkpoint().is_ok());
13076        assert!(cx.cancel_reason().is_none());
13077    }
13078
13079    #[test]
13080    fn offset_only_from_structured_nonzero() {
13081        assert_eq!(structured_error(942, 14).offset(), Some(14));
13082        assert_eq!(structured_error(942, 0).offset(), None);
13083        assert_eq!(
13084            server_error("ORA-00942: table or view does not exist").offset(),
13085            None
13086        );
13087    }
13088
13089    #[test]
13090    fn transient_classification() {
13091        for &code in TRANSIENT_ORA_CODES {
13092            let err = server_error(&format!("ORA-{code:05}: transient"));
13093            assert!(err.is_transient(), "ORA-{code:05} should be transient");
13094            assert!(err.is_retryable(), "transient implies retryable");
13095            assert!(
13096                !err.is_connection_lost(),
13097                "ORA-{code:05} is not connection-lost"
13098            );
13099        }
13100        // a permanent error: table or view does not exist
13101        let perm = server_error("ORA-00942: table or view does not exist");
13102        assert!(!perm.is_transient());
13103        assert!(!perm.is_connection_lost());
13104        assert!(!perm.is_retryable());
13105    }
13106
13107    #[test]
13108    fn connection_lost_classification() {
13109        for &code in CONNECTION_LOST_ORA_CODES {
13110            let err = server_error(&format!("ORA-{code:05}: lost"));
13111            assert!(
13112                err.is_connection_lost(),
13113                "ORA-{code:05} should be connection-lost"
13114            );
13115            assert!(err.is_retryable(), "connection-lost implies retryable");
13116            assert!(
13117                !err.is_transient(),
13118                "ORA-{code:05} is not a transient (retry-in-place) code"
13119            );
13120        }
13121        // raw I/O counts as the transport being gone
13122        let io = Error::Io(std::io::Error::new(
13123            std::io::ErrorKind::ConnectionReset,
13124            "reset",
13125        ));
13126        assert!(io.is_connection_lost());
13127        assert!(io.is_retryable());
13128
13129        // A plain call timeout is NOT connection-lost: on a timeout the driver
13130        // breaks + drains the wire and the connection stays reusable, mirroring
13131        // python-oracledb's DPY-4024 (ERR_CALL_TIMEOUT_EXCEEDED) which — unlike
13132        // DPY-4011 — does not set is_session_dead (errors.py:124-125). It is
13133        // transient (retry in place) and therefore retryable.
13134        let timeout = Error::CallTimeout(1000);
13135        assert!(
13136            !timeout.is_connection_lost(),
13137            "a call timeout leaves the connection usable after the drain"
13138        );
13139        assert!(
13140            timeout.is_transient(),
13141            "a call timeout is a retry-in-place (transient) condition"
13142        );
13143        assert!(
13144            timeout.is_retryable(),
13145            "transient implies retryable on the same connection"
13146        );
13147
13148        // ConnectionClosed (raised only when the post-timeout drain itself fails
13149        // — a SECOND timeout, the reference's disconnect path) IS connection-lost:
13150        // the wire could not be left clean, so the connection must be discarded.
13151        let recovery_failed =
13152            Error::ConnectionClosed("socket timed out while recovering".to_string());
13153        assert!(
13154            recovery_failed.is_connection_lost(),
13155            "a failed timeout-recovery drain marks the connection lost"
13156        );
13157        assert!(recovery_failed.is_retryable(), "reconnect, then retry");
13158        assert!(
13159            !recovery_failed.is_transient(),
13160            "ConnectionClosed needs a reconnect first, so it is not retry-in-place"
13161        );
13162    }
13163
13164    #[test]
13165    fn resource_limit_error_defines_pre_sync_and_post_sync_disposition() {
13166        let err = oracledb_protocol::ProtocolError::ResourceLimit {
13167            limit: "columns",
13168            observed: 3,
13169            maximum: 2,
13170        };
13171        assert_eq!(
13172            post_sync_protocol_error_disposition(&err),
13173            PostSyncProtocolDisposition::Dead,
13174            "a post-sync resource-limit decode failure leaves unread response bytes"
13175        );
13176
13177        let pre_sync = Error::Protocol(oracledb_protocol::ProtocolError::ResourceLimit {
13178            limit: "columns",
13179            observed: 3,
13180            maximum: 2,
13181        });
13182        assert_eq!(
13183            pre_sync.resource_limit(),
13184            Some(oracledb_protocol::ResourceLimit {
13185                limit: "columns",
13186                observed: 3,
13187                maximum: 2,
13188            })
13189        );
13190        assert!(
13191            !pre_sync.is_connection_lost(),
13192            "client-side/pre-sync resource-limit validation does not imply a lost connection"
13193        );
13194        assert!(
13195            !pre_sync.is_transient(),
13196            "raising the configured limit, not retrying in-place, is the remedy"
13197        );
13198        assert!(
13199            !pre_sync.is_retryable(),
13200            "resource limits are deterministic for the same input and policy"
13201        );
13202        assert!(matches!(
13203            pre_sync,
13204            Error::Protocol(oracledb_protocol::ProtocolError::ResourceLimit {
13205                limit: "columns",
13206                observed: 3,
13207                maximum: 2,
13208            })
13209        ));
13210    }
13211
13212    #[test]
13213    fn post_sync_resource_limit_marks_live_connection_dead() -> Result<()> {
13214        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13215        let addr = listener.local_addr().expect("listener address");
13216        let server = thread::spawn(move || {
13217            let (_socket, _) = listener.accept().expect("accept test client");
13218        });
13219
13220        let runtime = build_io_runtime().expect("asupersync runtime");
13221        let mut conn = runtime.block_on(async {
13222            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13223            let (read, write) = transport::plain_split(stream);
13224            loopback_connection(read, write)
13225        });
13226
13227        let err = conn
13228            .note_parse::<()>(Err(oracledb_protocol::ProtocolError::ResourceLimit {
13229                limit: "response_bytes",
13230                observed: 33,
13231                maximum: 32,
13232            }))
13233            .expect_err("post-sync resource-limit violation must be surfaced");
13234
13235        assert!(matches!(
13236            err,
13237            Error::Protocol(oracledb_protocol::ProtocolError::ResourceLimit {
13238                limit: "response_bytes",
13239                observed: 33,
13240                maximum: 32,
13241            })
13242        ));
13243        assert!(
13244            conn.is_dead(),
13245            "post-sync resource-limit violation stops consuming a response and kills the session"
13246        );
13247
13248        drop(conn);
13249        server.join().expect("server thread joins");
13250        Ok(())
13251    }
13252
13253    #[test]
13254    fn protocol_version_and_fast_auth_accessors_report_negotiated_values() {
13255        // K2 ServerFeatures accessors: the two getters read the fields the
13256        // ACCEPT negotiation populates. Build a loopback connection, set the
13257        // two accept-derived fields to distinct non-default values, and assert
13258        // each getter returns its own field (distinct types u16/bool guarantee
13259        // they cannot be transposed).
13260        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13261        let addr = listener.local_addr().expect("listener address");
13262        let server = thread::spawn(move || {
13263            let (_socket, _) = listener.accept().expect("accept test client");
13264        });
13265
13266        let runtime = build_io_runtime().expect("asupersync runtime");
13267        let mut conn = runtime.block_on(async {
13268            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13269            let (read, write) = transport::plain_split(stream);
13270            loopback_connection(read, write)
13271        });
13272
13273        // Defaults from the loopback constructor.
13274        assert_eq!(conn.protocol_version(), 0);
13275        assert!(!conn.supports_fast_auth());
13276
13277        // Simulate a negotiated ACCEPT: TNS version 319 over the fast-auth path.
13278        conn.protocol_version = 319;
13279        conn.supports_fast_auth = true;
13280        assert_eq!(conn.protocol_version(), 319);
13281        assert!(conn.supports_fast_auth());
13282
13283        drop(conn);
13284        server.join().expect("server thread joins");
13285    }
13286
13287    #[test]
13288    fn host_port_protocol_accessors_report_connected_descriptor() {
13289        // etib.7: host()/port()/protocol() expose the connected endpoint from the
13290        // resolved descriptor. Build a loopback connection, plant a known
13291        // descriptor, and assert each getter returns its own field (the distinct
13292        // types &str/u16/Protocol guarantee they cannot be transposed).
13293        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13294        let addr = listener.local_addr().expect("listener address");
13295        let server = thread::spawn(move || {
13296            let (_socket, _) = listener.accept().expect("accept test client");
13297        });
13298
13299        let runtime = build_io_runtime().expect("asupersync runtime");
13300        let mut conn = runtime.block_on(async {
13301            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13302            let (read, write) = transport::plain_split(stream);
13303            loopback_connection(read, write)
13304        });
13305
13306        conn.descriptor = EasyConnect {
13307            host: "db.example.com".to_string(),
13308            port: 2484,
13309            service_name: "FREEPDB1".to_string(),
13310            protocol: NetProtocol::Tcps,
13311        };
13312
13313        assert_eq!(conn.host(), "db.example.com");
13314        assert_eq!(conn.port(), 2484);
13315        assert_eq!(conn.protocol(), NetProtocol::Tcps);
13316        // The getters agree with the descriptor they delegate to.
13317        assert_eq!(conn.host(), conn.descriptor().host);
13318        assert_eq!(conn.port(), conn.descriptor().port);
13319        assert_eq!(conn.protocol(), conn.descriptor().protocol);
13320
13321        drop(conn);
13322        server.join().expect("server thread joins");
13323    }
13324
13325    // ---- A8 (bead oraclemcp-release-073-iec3.1.11): native single-round-trip
13326    // pipelining, proven offline over a loopback socket -----------------------
13327    //
13328    // `run_pipeline`/`run_pipeline_decoded` write every operation *before*
13329    // reading any response (one write burst, then N+1 boundary reads), so an
13330    // N-statement batch is a single wire round trip. python-oracledb's thin
13331    // mode issues the same batch as N sequential execute round trips. The
13332    // loopback "server" below refuses to answer until it has read the whole
13333    // batch, which terminates only if the client truly pipelined — a
13334    // deterministic, offline proof of the collapse (no live server, cassette
13335    // decode reused for the per-op result-materialization layer).
13336
13337    /// The synthetic execute response payload reused from the committed
13338    /// `select_7_plus_5` cassette fixture — no live capture, pure TNS framing +
13339    /// TTC decoder exercise. Decodes with the *same* per-op decoder the
13340    /// sequential execute path uses.
13341    fn synthetic_pipeline_execute_response_payload() -> Vec<u8> {
13342        const HEX: &str = concat!(
13343            "101710740fb986350b6010fbcb6e06a74ed0787e060a110328014001018201800000",
13344            "014000000000020369010140023ffe010501050556414c554500000000000000000000",
13345            "010707787e060a110b1000021fe8010a010a00062201010001020000000708414c33",
13346            "32555446380801060323a4d500010100000000000004010102013b010102057b0000",
13347            "01010003000000000000000000000000030001010000000002057b0101010300194f",
13348            "52412d30313430333a206e6f206461746120666f756e640a1d",
13349        );
13350        let raw = HEX.as_bytes();
13351        let mut bytes = Vec::with_capacity(raw.len() / 2);
13352        let mut index = 0;
13353        while index < raw.len() {
13354            let hi = (raw[index] as char).to_digit(16).expect("hex digit");
13355            let lo = (raw[index + 1] as char).to_digit(16).expect("hex digit");
13356            bytes.push(((hi << 4) | lo) as u8);
13357            index += 2;
13358        }
13359        bytes
13360    }
13361
13362    fn synthetic_lob_read_response_payload(locator: &[u8], data: &[u8], amount: u64) -> Vec<u8> {
13363        let mut payload = oracledb_protocol::wire::TtcWriter::new();
13364        payload.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_LOB_DATA);
13365        payload
13366            .write_bytes_with_length(data)
13367            .expect("synthetic LOB payload is encodable");
13368        payload.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_PARAMETER);
13369        payload.write_raw(locator);
13370        payload.write_ub8(amount);
13371        payload.write_u8(TNS_MSG_TYPE_END_OF_RESPONSE);
13372        payload.into_bytes()
13373    }
13374
13375    fn synthetic_aq_enqueue_response_payload(msgid: &[u8; 16]) -> Vec<u8> {
13376        let mut payload = oracledb_protocol::wire::TtcWriter::new();
13377        payload.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_PARAMETER);
13378        payload.write_raw(msgid);
13379        payload.write_ub2(0);
13380        payload.write_u8(TNS_MSG_TYPE_END_OF_RESPONSE);
13381        payload.into_bytes()
13382    }
13383
13384    fn synthetic_direct_path_prepare_response_payload(cursor_id: u16) -> Vec<u8> {
13385        let mut payload = oracledb_protocol::wire::TtcWriter::new();
13386        payload.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_PARAMETER);
13387        payload.write_ub4(0); // column metadata count
13388        payload.write_ub2(0); // parameter count
13389        payload.write_ub2(4); // output value count; cursor id is index 3
13390        payload.write_ub4(0);
13391        payload.write_ub4(0);
13392        payload.write_ub4(0);
13393        payload.write_ub4(u32::from(cursor_id));
13394        payload.write_u8(TNS_MSG_TYPE_END_OF_RESPONSE);
13395        let payload = payload.into_bytes();
13396
13397        let decoded = oracledb_protocol::dpl::parse_direct_path_prepare_response(
13398            &payload,
13399            ClientCapabilities::default(),
13400        )
13401        .expect("synthetic direct path prepare response decodes");
13402        assert_eq!(decoded.cursor_id, cursor_id);
13403        assert!(decoded.column_metadata.is_empty());
13404        payload
13405    }
13406
13407    fn synthetic_direct_path_simple_response_payload() -> Vec<u8> {
13408        let mut payload = oracledb_protocol::wire::TtcWriter::new();
13409        payload.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_PARAMETER);
13410        payload.write_ub2(0); // output value count
13411        payload.write_u8(TNS_MSG_TYPE_END_OF_RESPONSE);
13412        let payload = payload.into_bytes();
13413        oracledb_protocol::dpl::parse_direct_path_simple_response(
13414            &payload,
13415            ClientCapabilities::default(),
13416        )
13417        .expect("synthetic direct path simple response decodes");
13418        payload
13419    }
13420
13421    fn synthetic_subscribe_register_response_payload() -> Vec<u8> {
13422        // Real thin CQN register response captured by the protocol golden at
13423        // `thin::subscr::tests::subscribe_response_decodes_registration_and_client_id`.
13424        let payload = vec![
13425            0x08, 0x01, 0x01, 0x00, 0x02, 0x01, 0x2E, 0x01, 0x01, 0x02, 0x01, 0x2E, 0x00, 0x00,
13426            0x01, 0x01, 0x01, 0x36, 0x36, 0x28, 0x41, 0x44, 0x44, 0x52, 0x45, 0x53, 0x53, 0x3D,
13427            0x28, 0x50, 0x52, 0x4F, 0x54, 0x4F, 0x43, 0x4F, 0x4C, 0x3D, 0x54, 0x43, 0x50, 0x29,
13428            0x28, 0x48, 0x4F, 0x53, 0x54, 0x3D, 0x32, 0x39, 0x30, 0x61, 0x63, 0x30, 0x33, 0x30,
13429            0x30, 0x33, 0x38, 0x37, 0x29, 0x28, 0x50, 0x4F, 0x52, 0x54, 0x3D, 0x31, 0x35, 0x32,
13430            0x31, 0x29, 0x29, 0x01, 0x0A, 0x0A, 0x4F, 0x43, 0x49, 0x3A, 0x45, 0x50, 0x3A, 0x33,
13431            0x30, 0x31, 0x09, 0x01, 0x01, 0x02, 0xDD, 0x48, 0x1D,
13432        ];
13433        let decoded = parse_subscribe_response_with_limits(
13434            &payload,
13435            ClientCapabilities::default(),
13436            ProtocolLimits::DEFAULT,
13437        )
13438        .expect("captured CQN register response decodes");
13439        assert_eq!(decoded.registration_id, 302);
13440        assert_eq!(decoded.client_id.as_deref(), Some(&b"OCI:EP:301"[..]));
13441        payload
13442    }
13443
13444    fn serve_dropped_response_recovery(
13445        listener: TcpListener,
13446        expected_request: Vec<u8>,
13447        stranded_response: Vec<u8>,
13448        request_seen: std::sync::mpsc::Sender<()>,
13449    ) -> std::io::Result<bool> {
13450        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
13451
13452        use std::io::Write as _;
13453        let (mut socket, _) = listener.accept()?;
13454        socket.set_read_timeout(Some(Duration::from_secs(5)))?;
13455
13456        assert_eq!(
13457            read_one_wire_data_payload(&mut socket),
13458            expected_request,
13459            "request must preserve its exact payload"
13460        );
13461        request_seen
13462            .send(())
13463            .expect("client waits for request proof");
13464
13465        let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
13466        if next_packet_type == TNS_PACKET_TYPE_MARKER {
13467            assert_eq!(
13468                next_body,
13469                vec![1, 0, TNS_MARKER_TYPE_BREAK],
13470                "reuse must BREAK the stranded response before its request"
13471            );
13472            socket.write_all(&data_packet(&stranded_response, true))?;
13473            socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
13474            assert_eq!(
13475                read_marker_type(&mut socket),
13476                TNS_MARKER_TYPE_RESET,
13477                "response drain must complete the RESET handshake"
13478            );
13479            socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
13480            socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
13481
13482            assert_eq!(
13483                read_one_wire_packet(&mut socket),
13484                TNS_PACKET_TYPE_DATA,
13485                "fresh execute follows the completed response drain"
13486            );
13487            socket.write_all(&data_packet(
13488                &synthetic_pipeline_execute_response_payload(),
13489                true,
13490            ))?;
13491            socket.flush()?;
13492            Ok(true)
13493        } else {
13494            assert_eq!(
13495                next_packet_type, TNS_PACKET_TYPE_DATA,
13496                "without recovery the next operation is sent directly"
13497            );
13498            socket.write_all(&data_packet(&stranded_response, true))?;
13499            socket.write_all(&data_packet(
13500                &synthetic_pipeline_execute_response_payload(),
13501                true,
13502            ))?;
13503            socket.flush()?;
13504            Ok(false)
13505        }
13506    }
13507
13508    fn synthetic_aq_enqueue_request() -> (AqQueueDesc, AqMsgProps, AqEnqOptions) {
13509        let queue = AqQueueDesc::new(
13510            "AQ_QUEUE".to_owned(),
13511            oracledb_protocol::thin::aq::AqPayloadKind::Raw,
13512            None,
13513        );
13514        let props = AqMsgProps {
13515            payload: Some(oracledb_protocol::thin::aq::AqPayloadValue::Raw(
13516                b"payload".to_vec(),
13517            )),
13518            ..AqMsgProps::default()
13519        };
13520        (queue, props, AqEnqOptions::default())
13521    }
13522
13523    /// The committed single-row execute fixture ends with ORA-01403, which
13524    /// marks the cursor exhausted. Rewrite only that terminal error number and
13525    /// omit its message to model the same decoded row/metadata with an open
13526    /// cursor whose continuation must be fetched.
13527    fn synthetic_open_cursor_execute_response_payload() -> Vec<u8> {
13528        const TERMINAL_NO_DATA_PREFIX: &[u8] = &[
13529            0x02, 0x05, 0x7b, // error number: ub4(1403)
13530            0x01, 0x01, // row count: ub8(1)
13531            0x01, 0x03, // SQL type: ub4(3)
13532            0x00, // server checksum: ub4(0)
13533            0x19, // ORA-01403 message length
13534        ];
13535
13536        let mut response = synthetic_pipeline_execute_response_payload();
13537        let terminal = response
13538            .windows(TERMINAL_NO_DATA_PREFIX.len())
13539            .rposition(|window| window == TERMINAL_NO_DATA_PREFIX)
13540            .expect("synthetic response must contain its terminal ORA-01403");
13541        response[terminal + 1] = 0;
13542        response[terminal + 2] = 0;
13543        response.truncate(terminal + 8);
13544        response.push(TNS_MSG_TYPE_END_OF_RESPONSE);
13545
13546        let decoded = sequential_op_decode(&response);
13547        assert_ne!(decoded.cursor_id, 0, "fixture must retain its cursor id");
13548        assert!(decoded.more_rows, "fixture must leave the cursor open");
13549        assert_eq!(decoded.rows.len(), 1, "fixture must retain its first row");
13550        response
13551    }
13552
13553    /// One borrowed NUMBER continuation row with no terminal ORA-01403. The
13554    /// parser therefore reports `more_rows = true`, allowing tests to prove the
13555    /// speculative request-before-callback ordering without a live database.
13556    fn synthetic_open_borrowed_fetch_response(value: &str) -> Vec<u8> {
13557        use oracledb_protocol::thin::{
13558            encode_number_text, TNS_MSG_TYPE_ROW_DATA, TNS_MSG_TYPE_ROW_HEADER,
13559        };
13560
13561        let number = encode_number_text(value).expect("synthetic NUMBER encodes");
13562        let number_len = u8::try_from(number.len()).expect("NUMBER uses short TTC bytes");
13563        let mut response = vec![
13564            TNS_MSG_TYPE_ROW_HEADER,
13565            0, // row-header flags
13566            1,
13567            1, // ub2(num requests = 1)
13568            1,
13569            1, // ub4(iteration = 1)
13570            1,
13571            1, // ub4(num iterations = 1)
13572            0, // ub2(buffer length = 0)
13573            0, // ub4(bit-vector bytes = 0)
13574            0, // ub4(rxhrid length = 0)
13575            TNS_MSG_TYPE_ROW_DATA,
13576            number_len,
13577        ];
13578        response.extend_from_slice(&number);
13579        response.push(TNS_MSG_TYPE_END_OF_RESPONSE);
13580        response
13581    }
13582
13583    /// Reference decode of one op's response through the *same* public decoder
13584    /// the sequential execute path invokes (default caps/limits, matching the
13585    /// loopback connection) — the "sequential" side of the byte-identity check.
13586    fn sequential_op_decode(payload: &[u8]) -> QueryResult {
13587        parse_query_response_with_binds_options_columns_and_limits(
13588            payload,
13589            ClientCapabilities::default(),
13590            &[],
13591            ExecuteOptions::default(),
13592            &[],
13593            ProtocolLimits::DEFAULT,
13594        )
13595        .expect("synthetic execute response decodes")
13596    }
13597
13598    /// Read one whole Large32-framed TNS packet (header + body) from a blocking
13599    /// std socket, returning the packet-type byte. Post-connect every packet on
13600    /// the wire is a Large32 DATA packet.
13601    fn read_one_wire_packet_bytes(socket: &mut std::net::TcpStream) -> (u8, Vec<u8>) {
13602        let mut header = [0u8; 8];
13603        socket.read_exact(&mut header).expect("read packet header");
13604        let declared = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
13605        let mut body = vec![0u8; declared - header.len()];
13606        socket.read_exact(&mut body).expect("read packet body");
13607        (header[4], body)
13608    }
13609
13610    fn read_one_wire_packet(socket: &mut std::net::TcpStream) -> u8 {
13611        read_one_wire_packet_bytes(socket).0
13612    }
13613
13614    fn read_one_wire_data_payload(socket: &mut std::net::TcpStream) -> Vec<u8> {
13615        let (packet_type, body) = read_one_wire_packet_bytes(socket);
13616        assert_eq!(
13617            packet_type, TNS_PACKET_TYPE_DATA,
13618            "expected a DATA request after recovery"
13619        );
13620        assert!(body.len() >= 2, "DATA packet must contain its flags");
13621        body[2..].to_vec()
13622    }
13623
13624    /// Drive an `n`-statement pipeline over a loopback socket whose server side
13625    /// reads the ENTIRE batch (n ops + end-pipeline) before writing any byte
13626    /// back. Returns the decoded per-op results and the number of request
13627    /// packets the server read before it answered (== `n + 1` iff the client
13628    /// pipelined into a single round trip; a sequential client would deadlock
13629    /// this server after op-1).
13630    fn pipeline_batch_over_loopback(n: usize) -> (Vec<QueryResult>, usize) {
13631        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13632        let addr = listener.local_addr().expect("listener address");
13633        let server = thread::spawn(move || {
13634            use std::io::Write as _;
13635            let (mut socket, _) = listener.accept().expect("accept test client");
13636            let mut requests_before_first_response = 0usize;
13637            for _ in 0..=n {
13638                let _packet_type = read_one_wire_packet(&mut socket);
13639                requests_before_first_response += 1;
13640            }
13641            let execute_response =
13642                data_packet(&synthetic_pipeline_execute_response_payload(), true);
13643            for _ in 0..n {
13644                socket
13645                    .write_all(&execute_response)
13646                    .expect("write op response");
13647            }
13648            // The (n+1)-th (end-pipeline) response: a bare END_OF_RESPONSE frame,
13649            // consumed by the runner for framing only.
13650            socket
13651                .write_all(&data_packet(
13652                    &[oracledb_protocol::thin::TNS_MSG_TYPE_END_OF_RESPONSE],
13653                    true,
13654                ))
13655                .expect("write end-pipeline response");
13656            socket.flush().expect("flush responses");
13657            requests_before_first_response
13658        });
13659
13660        let runtime = build_io_runtime().expect("asupersync runtime");
13661        let results = runtime.block_on(async {
13662            let cx = Cx::current().expect("ambient Cx");
13663            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13664            let (read, write) = transport::plain_split(stream);
13665            let mut conn = loopback_connection(read, write);
13666            let requests: Vec<PipelineRequest> = (0..n)
13667                .map(|_| {
13668                    PipelineRequest::execute("select value from synthetic_fixture", Vec::new(), 2)
13669                })
13670                .collect();
13671            conn.run_pipeline_decoded(&cx, &requests, false)
13672                .await
13673                .expect("pipelined batch runs as one round trip")
13674                .into_iter()
13675                .enumerate()
13676                .map(|(index, op)| op.unwrap_or_else(|err| panic!("op {index} decoded: {err:?}")))
13677                .collect::<Vec<_>>()
13678        });
13679
13680        let requests_before_first_response = server.join().expect("server thread joins");
13681        (results, requests_before_first_response)
13682    }
13683
13684    #[test]
13685    fn pipeline_batch_offline_collapses_to_one_round_trip() {
13686        const N: usize = 10;
13687        let (results, requests_before_first_response) = pipeline_batch_over_loopback(N);
13688
13689        assert_eq!(
13690            requests_before_first_response,
13691            N + 1,
13692            "all {N} ops + end-pipeline are written before any response is read == 1 round trip"
13693        );
13694        assert_eq!(results.len(), N, "one decoded result per pipelined op");
13695
13696        // Byte-identical to sequential: each pipelined op decodes through the
13697        // same per-op decoder the ordinary execute path uses, over the same wire
13698        // bytes, so the materialized QueryResult is identical.
13699        let reference = sequential_op_decode(&synthetic_pipeline_execute_response_payload());
13700        for (index, decoded) in results.into_iter().enumerate() {
13701            assert_eq!(
13702                decoded, reference,
13703                "pipelined op {index} decodes byte-identically to the sequential path"
13704            );
13705        }
13706    }
13707
13708    #[test]
13709    fn concurrent_pipeline_batches_do_not_serialize() {
13710        // Two independent connections each run a pipeline concurrently on their
13711        // own OS thread + runtime. The driver holds no cross-connection lock
13712        // (each Connection owns its transport), so — unlike python-oracledb's
13713        // GIL-bound thin mode — the batches proceed in parallel. Both must
13714        // complete with results identical to the sequential decode.
13715        const N: usize = 10;
13716        let reference = sequential_op_decode(&synthetic_pipeline_execute_response_payload());
13717
13718        let worker_a = thread::spawn(|| pipeline_batch_over_loopback(N));
13719        let worker_b = thread::spawn(|| pipeline_batch_over_loopback(N));
13720        let (results_a, count_a) = worker_a.join().expect("worker a joins");
13721        let (results_b, count_b) = worker_b.join().expect("worker b joins");
13722
13723        assert_eq!(count_a, N + 1, "batch A collapsed to one round trip");
13724        assert_eq!(count_b, N + 1, "batch B collapsed to one round trip");
13725        assert_eq!(results_a.len(), N);
13726        assert_eq!(results_b.len(), N);
13727        for (index, decoded) in results_a.iter().chain(results_b.iter()).enumerate() {
13728            assert_eq!(
13729                *decoded, reference,
13730                "concurrent pipelined op {index} matches the sequential decode"
13731            );
13732        }
13733    }
13734
13735    #[test]
13736    fn pipeline_inactivity_timeout_breaks_and_drains_before_reuse() -> Result<()> {
13737        // GH#14: an opt-in read-inactivity timeout must use the same
13738        // BREAK→drain recovery as every other CallTimeout. Pipelining writes
13739        // both the operation and end-pipeline packets before its first read, so
13740        // this loopback refuses to answer until the client BREAKs the stranded
13741        // response; only then will it accept a follow-up query on the same
13742        // connection.
13743        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
13744        const TIMEOUT: Duration = Duration::from_millis(100);
13745
13746        let listener = TcpListener::bind("127.0.0.1:0")?;
13747        let addr = listener.local_addr()?;
13748        let server = thread::spawn(move || -> std::io::Result<()> {
13749            use std::io::Write as _;
13750
13751            let (mut socket, _) = listener.accept()?;
13752            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
13753
13754            for _ in 0..2 {
13755                assert_eq!(
13756                    read_one_wire_packet(&mut socket),
13757                    TNS_PACKET_TYPE_DATA,
13758                    "pipeline must send its operation and end-pipeline packets before reading"
13759                );
13760            }
13761            assert_eq!(
13762                read_marker_type(&mut socket),
13763                TNS_MARKER_TYPE_BREAK,
13764                "inactivity timeout must BREAK the stranded pipeline response"
13765            );
13766            socket.write_all(&data_packet(b"stranded pipeline response", true))?;
13767            socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
13768            assert_eq!(
13769                read_marker_type(&mut socket),
13770                TNS_MARKER_TYPE_RESET,
13771                "pipeline drain must complete the RESET handshake"
13772            );
13773            socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
13774            socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
13775
13776            assert_eq!(
13777                read_one_wire_packet(&mut socket),
13778                TNS_PACKET_TYPE_DATA,
13779                "only a cleanly recovered connection may issue the follow-up query"
13780            );
13781            socket.write_all(&data_packet(
13782                &synthetic_pipeline_execute_response_payload(),
13783                true,
13784            ))?;
13785            socket.flush()?;
13786            Ok(())
13787        });
13788
13789        let runtime = build_io_runtime()?;
13790        runtime.block_on(async {
13791            let cx = test_cx()?;
13792            let stream = TcpStream::connect(addr).await?;
13793            let (read, write) = transport::plain_split(stream);
13794            let mut connection = loopback_connection(read, write);
13795            connection.core.set_inactivity_timeout(Some(TIMEOUT));
13796
13797            let err = connection
13798                .run_pipeline(&cx, &[PipelineRequest::Commit], false)
13799                .await
13800                .expect_err("silent pipeline response must hit the inactivity timeout");
13801            assert!(
13802                matches!(err, Error::CallTimeout(ms) if ms == 100),
13803                "expected the configured inactivity timeout, got {err:?}"
13804            );
13805            assert_eq!(
13806                connection.core.recovery.phase(),
13807                SessionRecoveryPhase::Ready,
13808                "CallTimeout must return only after BREAK-and-drain leaves the wire clean"
13809            );
13810
13811            let reused = connection
13812                .execute_raw(
13813                    &cx,
13814                    "select value from pipeline_timeout_reuse_fixture",
13815                    2,
13816                    &[],
13817                    ExecuteOptions::default(),
13818                    None,
13819                )
13820                .await?;
13821            assert_eq!(
13822                reused,
13823                sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
13824                "the follow-up query must not consume a stranded pipeline response"
13825            );
13826            assert_eq!(
13827                connection.core.recovery.phase(),
13828                SessionRecoveryPhase::Ready
13829            );
13830            Ok::<_, Error>(())
13831        })?;
13832
13833        server.join().expect("pipeline timeout server joins")?;
13834        Ok(())
13835    }
13836
13837    #[test]
13838    fn in_flight_packet_resource_limit_marks_connection_dead() -> Result<()> {
13839        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13840        let addr = listener.local_addr().expect("listener address");
13841        let server = thread::spawn(move || {
13842            let (mut socket, _) = listener.accept().expect("accept test client");
13843            use std::io::Write as _;
13844            socket
13845                .write_all(&data_packet(&[0x01, 0x02, 0x03], true))
13846                .expect("write oversized packet");
13847        });
13848
13849        let runtime = build_io_runtime().expect("asupersync runtime");
13850        let conn = runtime.block_on(async {
13851            let cx = Cx::current()
13852                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
13853            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13854            let (read, write) = transport::plain_split(stream);
13855            let mut conn = loopback_connection(read, write);
13856            let limits = ProtocolLimits {
13857                max_packet_bytes: 12,
13858                max_frame_bytes: 16,
13859                max_response_bytes: 32,
13860                ..ProtocolLimits::DEFAULT
13861            }
13862            .validate()?;
13863            conn.protocol_limits = limits;
13864            conn.core.set_protocol_limits(limits)?;
13865
13866            let err = conn
13867                .core
13868                .read_data_response(&cx)
13869                .await
13870                .expect_err("oversized in-flight packet must fail closed");
13871            assert!(matches!(
13872                err,
13873                Error::Protocol(oracledb_protocol::ProtocolError::ResourceLimit {
13874                    limit: "packet_bytes",
13875                    observed: 13,
13876                    maximum: 12,
13877                })
13878            ));
13879            Ok::<Connection, Error>(conn)
13880        })?;
13881
13882        assert!(
13883            conn.is_dead(),
13884            "in-flight resource-limit violations leave unread wire bytes"
13885        );
13886        assert_eq!(conn.core.recovery.phase(), SessionRecoveryPhase::Dead);
13887
13888        drop(conn);
13889        server.join().expect("server thread joins");
13890        Ok(())
13891    }
13892
13893    // ---- classic (pre-END_OF_RESPONSE) probed response reads ----------------
13894    //
13895    // Pre-23ai servers (ACCEPT protocol version < 319) never send the
13896    // END_OF_RESPONSE/EOF data flags, so `read_data_response_probed` in classic
13897    // mode must decide completion with the caller's probe over the accumulated
13898    // payload — the flag-driven reader would wait until the call timeout.
13899
13900    /// A classic two-packet response: the probe sees the accumulated payload
13901    /// after each DATA packet, reports "incomplete" after packet 1 and
13902    /// "complete" after packet 2, and the returned buffer is the flag-stripped
13903    /// concatenation of both packets.
13904    #[test]
13905    fn classic_probed_read_reassembles_until_probe_reports_complete() -> Result<()> {
13906        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13907        let addr = listener.local_addr().expect("listener address");
13908        let server = thread::spawn(move || {
13909            let (mut socket, _) = listener.accept().expect("accept test client");
13910            use std::io::Write as _;
13911            // Both packets are flagless: a classic server never sets
13912            // END_OF_RESPONSE/EOF, so only the probe can end the read.
13913            socket
13914                .write_all(&data_packet(&[0x01, 0x02], false))
13915                .expect("write first classic packet");
13916            socket
13917                .write_all(&data_packet(&[0x03, 0x04], false))
13918                .expect("write second classic packet");
13919        });
13920
13921        let runtime = build_io_runtime().expect("asupersync runtime");
13922        let probed = Arc::new(std::sync::Mutex::new(Vec::<Vec<u8>>::new()));
13923        let probed_in = Arc::clone(&probed);
13924        let response = runtime.block_on(async {
13925            let cx = Cx::current()
13926                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
13927            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13928            let (read, write) = transport::plain_split(stream);
13929            let mut conn = loopback_connection(read, write);
13930            conn.core
13931                .read_data_response_probed(&cx, true, move |bytes| {
13932                    probed_in
13933                        .lock()
13934                        .expect("probe snapshot lock")
13935                        .push(bytes.to_vec());
13936                    // "Parser consumed the whole response": needs all 4 bytes.
13937                    bytes.len() >= 4
13938                })
13939                .await
13940        })?;
13941
13942        assert_eq!(
13943            response,
13944            [0x01, 0x02, 0x03, 0x04],
13945            "classic read must reassemble both flag-stripped payloads"
13946        );
13947        let probed = probed.lock().expect("probe snapshot lock");
13948        assert_eq!(
13949            probed.as_slice(),
13950            &[vec![0x01, 0x02], vec![0x01, 0x02, 0x03, 0x04]],
13951            "the probe must run over the accumulated payload after every packet"
13952        );
13953        server.join().expect("server thread joins");
13954        Ok(())
13955    }
13956
13957    /// MARKER-free happy path: a single flagless classic packet whose probe
13958    /// reports complete immediately returns that packet's payload.
13959    #[test]
13960    fn classic_probed_read_single_packet_happy_path() -> Result<()> {
13961        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13962        let addr = listener.local_addr().expect("listener address");
13963        let server = thread::spawn(move || {
13964            let (mut socket, _) = listener.accept().expect("accept test client");
13965            use std::io::Write as _;
13966            socket
13967                .write_all(&data_packet(
13968                    &[0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06],
13969                    false,
13970                ))
13971                .expect("write classic packet");
13972        });
13973
13974        let runtime = build_io_runtime().expect("asupersync runtime");
13975        let response = runtime.block_on(async {
13976            let cx = Cx::current()
13977                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
13978            let stream = TcpStream::connect(addr).await.expect("connect to listener");
13979            let (read, write) = transport::plain_split(stream);
13980            let mut conn = loopback_connection(read, write);
13981            conn.core
13982                .read_data_response_probed(&cx, true, |bytes| !bytes.is_empty())
13983                .await
13984        })?;
13985
13986        assert_eq!(response, [0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
13987        server.join().expect("server thread joins");
13988        Ok(())
13989    }
13990
13991    /// With `classic == false` the probed read delegates to the flag-framed
13992    /// reader: an END_OF_RESPONSE-flagged packet completes the response even
13993    /// though the probe never says so — the 23ai path is byte-identical and
13994    /// the probe is never consulted.
13995    #[test]
13996    fn probed_read_ignores_probe_when_not_classic() -> Result<()> {
13997        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
13998        let addr = listener.local_addr().expect("listener address");
13999        let server = thread::spawn(move || {
14000            let (mut socket, _) = listener.accept().expect("accept test client");
14001            use std::io::Write as _;
14002            socket
14003                .write_all(&data_packet(&[0x01, 0x02, 0x03], true))
14004                .expect("write flag-framed packet");
14005        });
14006
14007        let runtime = build_io_runtime().expect("asupersync runtime");
14008        let response = runtime.block_on(async {
14009            let cx = Cx::current()
14010                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
14011            let stream = TcpStream::connect(addr).await.expect("connect to listener");
14012            let (read, write) = transport::plain_split(stream);
14013            let mut conn = loopback_connection(read, write);
14014            conn.core
14015                .read_data_response_probed(&cx, false, |_| false)
14016                .await
14017        })?;
14018
14019        assert_eq!(response, [0x01, 0x02, 0x03]);
14020        server.join().expect("server thread joins");
14021        Ok(())
14022    }
14023
14024    /// A non-DATA/non-MARKER packet mid-response is a protocol violation: the
14025    /// classic probed read fails closed with `UnexpectedPacket` instead of
14026    /// accumulating garbage.
14027    #[test]
14028    fn classic_probed_read_rejects_non_data_packet() -> Result<()> {
14029        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
14030        let addr = listener.local_addr().expect("listener address");
14031        let server = thread::spawn(move || {
14032            let (mut socket, _) = listener.accept().expect("accept test client");
14033            use std::io::Write as _;
14034            let packet = encode_packet(
14035                TNS_PACKET_TYPE_ACCEPT,
14036                0,
14037                None,
14038                &[0x00],
14039                PacketLengthWidth::Large32,
14040            )
14041            .expect("encode unexpected packet");
14042            socket.write_all(&packet).expect("write unexpected packet");
14043        });
14044
14045        let runtime = build_io_runtime().expect("asupersync runtime");
14046        let err = runtime.block_on(async {
14047            let cx = Cx::current().expect("ambient Cx");
14048            let stream = TcpStream::connect(addr).await.expect("connect to listener");
14049            let (read, write) = transport::plain_split(stream);
14050            let mut conn = loopback_connection(read, write);
14051            conn.core
14052                .read_data_response_probed(&cx, true, |_| true)
14053                .await
14054                .expect_err("non-DATA packet must fail closed")
14055        });
14056
14057        assert!(matches!(
14058            err,
14059            Error::UnexpectedPacket(TNS_PACKET_TYPE_ACCEPT)
14060        ));
14061        assert_eq!(err.kind(), ErrorKind::Protocol);
14062        server.join().expect("server thread joins");
14063        Ok(())
14064    }
14065
14066    // Regression (bead rust-oracledb-n2s): the multi-packet wide-row response
14067    // reassembler must NOT treat a non-final DATA packet that merely ends in the
14068    // byte 0x1d (TNS_MSG_TYPE_END_OF_RESPONSE, 29) as the end of the response.
14069    // Only a packet carrying the END_OF_RESPONSE/EOF data flag, or a minimal
14070    // packet whose entire post-flags payload is exactly the single byte 0x1d,
14071    // ends the response. Before the fix the `0x1d` check was unguarded and a
14072    // mid-stream wide-row packet boundary that happened to land on 0x1d
14073    // truncated the buffer ("encoded NUMBER too long" / "truncated TTC payload").
14074    #[test]
14075    fn data_packet_ends_response_requires_flag_or_lone_marker_byte() {
14076        const EOR: u8 = TNS_MSG_TYPE_END_OF_RESPONSE; // 29 / 0x1d
14077        const FOB: u8 = TNS_MSG_TYPE_FLUSH_OUT_BINDS; // 19 / 0x13
14078        let eor_flag = oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE;
14079        let eof_flag = oracledb_protocol::thin::TNS_DATA_FLAGS_EOF;
14080
14081        // The END_OF_RESPONSE data flag ends the response regardless of payload.
14082        assert!(data_packet_ends_response(eor_flag, &[0x01, 0x02, EOR]));
14083        assert!(data_packet_ends_response(eor_flag, &[]));
14084        // The EOF data flag (final packet of legacy framing) likewise ends it.
14085        assert!(data_packet_ends_response(eof_flag, &[0x01, 0x02, 0x03]));
14086
14087        // A lone marker byte arriving as its own minimal packet is a real
14088        // end-of-response (END_OF_RESPONSE or FLUSH_OUT_BINDS) -- the no-EOR
14089        // framing fallback.
14090        assert!(data_packet_ends_response(0x0000, &[EOR]));
14091        assert!(data_packet_ends_response(0x0000, &[FOB]));
14092
14093        // THE BUG: a flagless (mid-stream) wide-row packet whose payload merely
14094        // ENDS in a marker byte (0x1d END_OF_RESPONSE, or 0x13 FLUSH_OUT_BINDS) is
14095        // NOT the end of the response. These must all be false so reassembly keeps
14096        // reading the following packets.
14097        assert!(!data_packet_ends_response(0x0000, &[0xc1, 0x02, EOR]));
14098        assert!(!data_packet_ends_response(0x0000, &[0x00, EOR]));
14099        assert!(!data_packet_ends_response(0x0000, &[EOR, 0x05, 0x06, EOR]));
14100        assert!(!data_packet_ends_response(0x0000, &[0xc1, 0x02, FOB]));
14101        assert!(!data_packet_ends_response(0x0000, &[0x00, FOB]));
14102        // A flagless packet that does not end in a marker byte also keeps reading.
14103        assert!(!data_packet_ends_response(0x0000, &[0x01, 0x02, 0x03]));
14104        assert!(!data_packet_ends_response(0x0000, &[]));
14105    }
14106
14107    /// Pure replay of the `read_data_response_boundary` decision logic over a
14108    /// hand-built packet sequence, returning the reassembled bytes, the index it
14109    /// stopped at, and whether flush-out-binds was detected. Mirrors the async
14110    /// loop's break conditions exactly (minus I/O), INCLUDING the single-packet
14111    /// passthrough (bead rust-oracledb-0n0): when the response is one terminal
14112    /// packet, the owned buffer is moved instead of copied. The `payload` here is
14113    /// already flag-stripped, so the passthrough is a plain move of the same bytes
14114    /// — proving the optimization is byte-identical to the extend path.
14115    fn replay_boundary(packets: &[(u16, Vec<u8>)]) -> (Vec<u8>, Option<usize>, bool) {
14116        let mut reassembled = Vec::new();
14117        let mut stopped_at = None;
14118        for (index, (flags, payload)) in packets.iter().enumerate() {
14119            let ends = data_packet_ends_response(*flags, payload);
14120            if ends && reassembled.is_empty() {
14121                // Passthrough: move the (already flag-stripped) owned buffer.
14122                reassembled = payload.clone();
14123                stopped_at = Some(index);
14124                break;
14125            }
14126            reassembled.extend_from_slice(payload);
14127            if ends {
14128                stopped_at = Some(index);
14129                break;
14130            }
14131        }
14132        let flush_out_binds = matches!(reassembled.last(), Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS));
14133        (reassembled, stopped_at, flush_out_binds)
14134    }
14135
14136    // End-to-end of the boundary loop over a hand-built multi-packet sequence:
14137    // body packets that END in the marker bytes 0x1d (END_OF_RESPONSE) and 0x13
14138    // (FLUSH_OUT_BINDS) -- the old false-positive triggers -- followed by the
14139    // real END_OF_RESPONSE-flagged tail. The reassembled payload must concatenate
14140    // every body packet's bytes (after its 2-byte data flags) in order, proving
14141    // no early break and no byte loss.
14142    #[test]
14143    fn boundary_loop_reassembles_packets_ending_in_marker_byte() {
14144        const EOR: u8 = TNS_MSG_TYPE_END_OF_RESPONSE;
14145        const FOB: u8 = TNS_MSG_TYPE_FLUSH_OUT_BINDS;
14146        let packets: [(u16, Vec<u8>); 5] = [
14147            (0x0000, vec![0x10, 0x11, EOR]), // ends in 0x1d -> must NOT stop
14148            (0x0000, vec![0x20, 0x21, 0x22, FOB]), // ends in 0x13 -> must NOT stop
14149            (0x0000, vec![0x30, 0x31, 0x32, EOR]), // ends in 0x1d -> must NOT stop
14150            (0x0000, vec![0x33, 0x34, 0x35]), // ordinary body packet
14151            (
14152                oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE,
14153                vec![0x40, 0x41, EOR], // real end: carries the EOR flag
14154            ),
14155        ];
14156
14157        let (reassembled, stopped_at, flush_out_binds) = replay_boundary(&packets);
14158
14159        assert_eq!(
14160            stopped_at,
14161            Some(4),
14162            "reassembly must stop only on the flagged final packet, not on a body packet ending in a marker byte"
14163        );
14164        assert!(
14165            !flush_out_binds,
14166            "the response ended in END_OF_RESPONSE, not FLUSH_OUT_BINDS"
14167        );
14168        assert_eq!(
14169            reassembled,
14170            vec![
14171                0x10, 0x11, EOR, // packet 0
14172                0x20, 0x21, 0x22, FOB, // packet 1
14173                0x30, 0x31, 0x32, EOR, // packet 2
14174                0x33, 0x34, 0x35, // packet 3
14175                0x40, 0x41, EOR, // packet 4 (final)
14176            ],
14177            "every body packet's bytes must be concatenated in order with none dropped"
14178        );
14179    }
14180
14181    // A genuine flush-out-binds response (the EOR-flagged final packet ends in
14182    // the FLUSH_OUT_BINDS byte) must set the flag -- AND a mid-stream body packet
14183    // ending in that same byte must not have ended the response prematurely.
14184    #[test]
14185    fn boundary_loop_detects_flush_out_binds_only_at_true_boundary() {
14186        const FOB: u8 = TNS_MSG_TYPE_FLUSH_OUT_BINDS;
14187        let packets: [(u16, Vec<u8>); 2] = [
14188            (0x0000, vec![0x01, 0x02, FOB]), // body packet ending in 0x13 -> keep reading
14189            (
14190                oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE,
14191                vec![0x03, FOB], // EOR-flagged tail whose last message is FLUSH_OUT_BINDS
14192            ),
14193        ];
14194
14195        let (reassembled, stopped_at, flush_out_binds) = replay_boundary(&packets);
14196
14197        assert_eq!(stopped_at, Some(1), "stop on the EOR-flagged tail");
14198        assert!(
14199            flush_out_binds,
14200            "flush-out-binds must be detected from the terminal FLUSH_OUT_BINDS message byte"
14201        );
14202        assert_eq!(reassembled, vec![0x01, 0x02, FOB, 0x03, FOB]);
14203    }
14204
14205    // Single-packet passthrough (bead rust-oracledb-0n0): a response that is ONE
14206    // terminal DATA packet must produce byte-identical reassembled output whether
14207    // it takes the passthrough (move the owned buffer) or the legacy extend path,
14208    // and FLUSH_OUT_BINDS detection on its terminal byte must be unchanged.
14209    #[test]
14210    fn single_packet_passthrough_is_byte_identical_to_extend() {
14211        const EOR: u8 = TNS_MSG_TYPE_END_OF_RESPONSE;
14212        const FOB: u8 = TNS_MSG_TYPE_FLUSH_OUT_BINDS;
14213        let eor_flag = oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE;
14214
14215        // Helper: the legacy extend-only reassembly, for the equivalence oracle.
14216        fn replay_extend_only(packets: &[(u16, Vec<u8>)]) -> (Vec<u8>, Option<usize>, bool) {
14217            let mut reassembled = Vec::new();
14218            let mut stopped_at = None;
14219            for (index, (flags, payload)) in packets.iter().enumerate() {
14220                reassembled.extend_from_slice(payload);
14221                if data_packet_ends_response(*flags, payload) {
14222                    stopped_at = Some(index);
14223                    break;
14224                }
14225            }
14226            let flush = matches!(reassembled.last(), Some(&TNS_MSG_TYPE_FLUSH_OUT_BINDS));
14227            (reassembled, stopped_at, flush)
14228        }
14229
14230        // Several single-terminal-packet shapes, including one ending in the
14231        // FLUSH_OUT_BINDS byte (so the flag-detection path is exercised).
14232        let cases: &[(u16, Vec<u8>)] = &[
14233            (eor_flag, vec![0x40, 0x41, EOR]),
14234            (eor_flag, vec![0x03, FOB]), // terminal FLUSH_OUT_BINDS
14235            (eor_flag, vec![0xde, 0xad, 0xbe, 0xef]),
14236            (eor_flag, vec![0x00]),
14237        ];
14238        for (flags, payload) in cases {
14239            let one = [(*flags, payload.clone())];
14240            let passthrough = replay_boundary(&one);
14241            let extend = replay_extend_only(&one);
14242            assert_eq!(
14243                passthrough, extend,
14244                "passthrough must equal extend for single packet {payload:02x?}"
14245            );
14246            // And the bytes are exactly the (already flag-stripped) payload.
14247            assert_eq!(&passthrough.0, payload);
14248        }
14249    }
14250
14251    #[test]
14252    fn parse_user_and_proxy_bracket_forms() {
14253        // Plain user.
14254        assert_eq!(parse_user_and_proxy("scott"), ("scott".into(), None));
14255        // base[proxy] — reference form.
14256        assert_eq!(
14257            parse_user_and_proxy("scott[proxy]"),
14258            ("scott".into(), Some("proxy".into()))
14259        );
14260        // [proxy] only — upstream e861662 token-auth form (empty base).
14261        assert_eq!(
14262            parse_user_and_proxy("[proxy_only]"),
14263            ("".into(), Some("proxy_only".into()))
14264        );
14265        // No closing bracket → unchanged.
14266        assert_eq!(
14267            parse_user_and_proxy("scott[proxy"),
14268            ("scott[proxy".into(), None)
14269        );
14270        // No opening bracket → unchanged.
14271        assert_eq!(parse_user_and_proxy("scott]"), ("scott]".into(), None));
14272    }
14273
14274    #[test]
14275    fn connect_options_desugars_bracket_user_and_full_user_display() {
14276        let base_proxy = ConnectOptions::new("h:1521/s", "scott[proxy]", "pw", identity());
14277        assert_eq!(base_proxy.user(), "scott");
14278        assert_eq!(base_proxy.proxy_user(), Some("proxy"));
14279        assert_eq!(base_proxy.full_user(), "scott[proxy]");
14280        assert!(matches!(base_proxy.auth_mode(), AuthMode::Proxy));
14281
14282        let proxy_only = ConnectOptions::new("h:1521/s", "[proxy_only]", "", identity())
14283            .with_access_token("super-secret-db-token-xyz");
14284        assert_eq!(proxy_only.user(), "");
14285        assert_eq!(proxy_only.proxy_user(), Some("proxy_only"));
14286        assert_eq!(proxy_only.full_user(), "[proxy_only]");
14287        // Debug must show the full-user form and never leak the token/password.
14288        let dbg = format!("{proxy_only:?}");
14289        assert!(dbg.contains("[proxy_only]"), "debug was {dbg}");
14290        assert!(
14291            !dbg.contains("super-secret-db-token-xyz"),
14292            "token leaked in debug: {dbg}"
14293        );
14294        assert!(
14295            dbg.contains("***redacted***"),
14296            "password/token field missing redaction: {dbg}"
14297        );
14298
14299        // Explicit with_proxy_user overwrites bracket desugar.
14300        let overwritten = ConnectOptions::new("h:1521/s", "scott[from_bracket]", "pw", identity())
14301            .with_proxy_user(Some("from_explicit".into()));
14302        assert_eq!(overwritten.user(), "scott");
14303        assert_eq!(overwritten.proxy_user(), Some("from_explicit"));
14304        assert_eq!(overwritten.full_user(), "scott[from_explicit]");
14305    }
14306
14307    #[test]
14308    fn proxy_only_token_auth_encodes_phase_two_proxy_header() {
14309        // Wire path: empty base user + PROXY_CLIENT_NAME for proxy-only.
14310        use oracledb_protocol::crypto::EncryptedPassword;
14311        use oracledb_protocol::thin::build_auth_phase_two_payload_with_proxy_with_seq;
14312        let encrypted = EncryptedPassword {
14313            session_key: "00".repeat(32),
14314            speedy_key: None,
14315            password: "00".repeat(32),
14316            combo_key: vec![0u8; 32],
14317        };
14318        let payload = build_auth_phase_two_payload_with_proxy_with_seq(
14319            "",
14320            &encrypted,
14321            "rust-oracledb",
14322            0,
14323            "",
14324            1,
14325            &[],
14326            Some("proxy_only"),
14327            None,
14328            17, // TNS_CCAP_FIELD_VERSION_23_1
14329        )
14330        .expect("phase-two proxy payload");
14331        let text = String::from_utf8_lossy(&payload);
14332        assert!(
14333            text.contains("PROXY_CLIENT_NAME") && text.contains("proxy_only"),
14334            "payload missing PROXY_CLIENT_NAME/proxy_only: {text:?}"
14335        );
14336    }
14337
14338    #[test]
14339    fn descriptor_builder_uses_identity_in_listener_cid() {
14340        let options = ConnectOptions::new("localhost/FREEPDB1", "user", "password", identity());
14341        let descriptor =
14342            EasyConnect::parse(&options.connect_string).expect("test connect string should parse");
14343        let full_descriptor = EasyConnect::parse_descriptor(&options.connect_string)
14344            .expect("test connect string should parse as full descriptor");
14345        let description = full_descriptor.first_description();
14346        let built = listener_connect_descriptor_with_server(
14347            &descriptor,
14348            description,
14349            &options.identity,
14350            false,
14351            false,
14352            true,
14353            None,
14354        );
14355        assert!(built.contains("(PROGRAM=program)"));
14356        assert!(built.contains("(HOST=machine)"));
14357        assert!(built.contains("(USER=osuser)"));
14358        assert!(!built.contains("(SERVER=emon)"));
14359        // emon variant injects the SERVER directive ahead of the CID block
14360        let emon = listener_connect_descriptor_with_server(
14361            &descriptor,
14362            description,
14363            &options.identity,
14364            true,
14365            false,
14366            true,
14367            None,
14368        );
14369        assert!(emon.contains("(SERVICE_NAME=FREEPDB1)(SERVER=emon)(CID="));
14370    }
14371
14372    #[test]
14373    fn token_auth_descriptor_uses_tcps_security_and_passthrough() {
14374        let connect_string = concat!(
14375            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=adb.example.test)(PORT=2484))",
14376            "(CONNECT_DATA=(SERVICE_NAME=adbsvc))",
14377            "(SECURITY=(SSL_SERVER_DN_MATCH=off)",
14378            "(SSL_SERVER_CERT_DN=CN=adb.example.test)",
14379            "(OCI_IAM_HOST=private-endpoint)))"
14380        );
14381        let descriptor = EasyConnect::parse(connect_string).expect("parse tcps descriptor");
14382        let full_descriptor =
14383            EasyConnect::parse_descriptor(connect_string).expect("parse full descriptor");
14384        let description = full_descriptor.first_description();
14385        let built = auth_connect_descriptor(
14386            &descriptor,
14387            description,
14388            true,
14389            false,
14390            description.security.ssl_server_cert_dn.as_deref(),
14391        );
14392
14393        assert!(built.contains("(PROTOCOL=tcps)"));
14394        assert!(built.contains("(SECURITY="));
14395        assert!(built.contains("(SSL_SERVER_DN_MATCH=OFF)"));
14396        assert!(built.contains("(SSL_SERVER_CERT_DN=CN=adb.example.test)"));
14397        assert!(built.contains("(OCI_IAM_HOST=private-endpoint)"));
14398        assert!(built.contains("(TOKEN_AUTH=OCI_TOKEN)"));
14399        assert!(!built.contains("WALLET"));
14400    }
14401
14402    // ---- H2: connect-descriptor golden wire-bytes per auth mode ----------
14403    //
14404    // The tests above prove individual clauses show up (`.contains(...)`).
14405    // These pin the ENTIRE built descriptor string byte-for-byte against a
14406    // committed fixture (`tests/golden/connect_descriptor/*.descriptor.txt`)
14407    // AND the entire framed CONNECT wire packet byte-for-byte against a
14408    // committed hex fixture (`tests/golden/connect_descriptor/*.packet.hex`),
14409    // one pair per auth mode (password/plain-TCP, wallet-TCPS with a DC2
14410    // pinned cert DN, IAM-token TCPS). A regression in `auth_connect_descriptor`
14411    // / `descriptor_security_clause` / `build_connect_packet_payload` — a
14412    // reordered field, a dropped clause, a header byte that drifts — fails
14413    // one of these with a diff naming exactly what changed, without a live
14414    // database. The parser side of the same round trip (DC2 cert-DN, DC4
14415    // `CONNECT_TIMEOUT` parsing, full per-auth-mode topology) is pinned
14416    // separately in `oracledb-protocol/tests/connect_descriptor_golden.rs`,
14417    // where the parser types are public.
14418    //
14419    // The wire-packet fixtures mirror the exact `build_connect_packet_payload`
14420    // + `encode_packet` call the real `Connection::connect` path makes (see
14421    // `TNS_PACKET_TYPE_CONNECT` above, around the CONNECT-resend loop), with a
14422    // fixed SDU of 8192 so the header fields are deterministic.
14423
14424    /// Decodes a lowercase/uppercase hex-digit fixture (whitespace ignored)
14425    /// into raw bytes. A small hand-rolled helper rather than a new
14426    /// dependency: the fixture files are plain, newline-wrapped hex dumps.
14427    /// (Named distinctly from the `#[cfg(feature = "cassette")]`-only
14428    /// `decode_hex_fixture` above: this one must be available unconditionally
14429    /// — the golden connect-descriptor tests run under both the default and
14430    /// `cassette` feature sets — and panics rather than returning `Result`,
14431    /// which is the right shape for a test-only fixture loader.)
14432    fn decode_golden_packet_hex(hex: &str) -> Vec<u8> {
14433        let digits: Vec<u8> = hex.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
14434        assert!(
14435            digits.len().is_multiple_of(2),
14436            "hex fixture must have an even number of hex digits"
14437        );
14438        digits
14439            .chunks_exact(2)
14440            .map(|pair| {
14441                let hi = (pair[0] as char).to_digit(16).expect("valid hex digit");
14442                let lo = (pair[1] as char).to_digit(16).expect("valid hex digit");
14443                ((hi << 4) | lo) as u8
14444            })
14445            .collect()
14446    }
14447
14448    /// Builds the full framed CONNECT wire packet for `connect_data`, exactly
14449    /// as `Connection::connect` does on the first (non-resend, non-redirect)
14450    /// attempt: `build_connect_packet_payload` then `encode_packet` with
14451    /// `PacketLengthWidth::Legacy16` and no packet flags / checksum.
14452    fn golden_connect_packet_bytes(connect_data: &str, sdu: u16) -> Vec<u8> {
14453        let payload =
14454            build_connect_packet_payload(connect_data, sdu).expect("connect packet payload");
14455        encode_packet(
14456            TNS_PACKET_TYPE_CONNECT,
14457            0,
14458            None,
14459            &payload,
14460            PacketLengthWidth::Legacy16,
14461        )
14462        .expect("encode CONNECT packet")
14463    }
14464
14465    #[test]
14466    fn golden_password_plain_tcp_descriptor_and_wire_bytes() {
14467        let connect_string = concat!(
14468            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=db.example.test)(PORT=1521))",
14469            "(CONNECT_DATA=(SERVICE_NAME=FREEPDB1)))"
14470        );
14471        let descriptor = EasyConnect::parse(connect_string).expect("parse tcp descriptor");
14472        let full_descriptor =
14473            EasyConnect::parse_descriptor(connect_string).expect("parse full tcp descriptor");
14474        let description = full_descriptor.first_description();
14475        let built = auth_connect_descriptor(&descriptor, description, false, true, None);
14476
14477        let expected_descriptor =
14478            include_str!("../tests/golden/connect_descriptor/password_tcp.descriptor.txt").trim();
14479        assert_eq!(
14480            built, expected_descriptor,
14481            "password/plain-TCP built connect descriptor drifted from the golden fixture"
14482        );
14483
14484        let packet = golden_connect_packet_bytes(&built, 8192);
14485        let expected_packet = decode_golden_packet_hex(include_str!(
14486            "../tests/golden/connect_descriptor/password_tcp.packet.hex"
14487        ));
14488        assert_eq!(
14489            packet, expected_packet,
14490            "password/plain-TCP CONNECT wire packet drifted from the golden fixture"
14491        );
14492    }
14493
14494    #[test]
14495    fn golden_wallet_tcps_cert_dn_descriptor_and_wire_bytes() {
14496        let connect_string = concat!(
14497            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=adb.example.test)(PORT=2484))",
14498            "(CONNECT_DATA=(SERVICE_NAME=adbsvc))",
14499            "(SECURITY=(SSL_SERVER_DN_MATCH=on)",
14500            "(SSL_SERVER_CERT_DN=CN=adb.example.test,O=ExampleCorp,C=US)",
14501            "(MY_WALLET_DIRECTORY=/opt/wallets/adb)))"
14502        );
14503        let descriptor = EasyConnect::parse(connect_string).expect("parse wallet tcps descriptor");
14504        let full_descriptor = EasyConnect::parse_descriptor(connect_string)
14505            .expect("parse full wallet tcps descriptor");
14506        let description = full_descriptor.first_description();
14507        // bead DC2: the pinned cert DN travels ONLY through the DSN-parsed
14508        // `description.security.*` fields here, never through the
14509        // `with_ssl_server_cert_dn` / `with_ssl_server_dn_match` builders —
14510        // the exact path F-DC2 found broken.
14511        let built = auth_connect_descriptor(
14512            &descriptor,
14513            description,
14514            false,
14515            description.security.ssl_server_dn_match,
14516            description.security.ssl_server_cert_dn.as_deref(),
14517        );
14518
14519        let expected_descriptor =
14520            include_str!("../tests/golden/connect_descriptor/wallet_tcps_cert_dn.descriptor.txt")
14521                .trim();
14522        assert_eq!(
14523            built, expected_descriptor,
14524            "wallet-TCPS (DC2 cert-DN) built connect descriptor drifted from the golden fixture"
14525        );
14526        // The wallet directory is a local-only TLS-setup directive: it must
14527        // never be echoed back into the descriptor sent to the listener.
14528        assert!(!built.contains("WALLET"));
14529
14530        let packet = golden_connect_packet_bytes(&built, 8192);
14531        let expected_packet = decode_golden_packet_hex(include_str!(
14532            "../tests/golden/connect_descriptor/wallet_tcps_cert_dn.packet.hex"
14533        ));
14534        assert_eq!(
14535            packet, expected_packet,
14536            "wallet-TCPS (DC2 cert-DN) CONNECT wire packet drifted from the golden fixture"
14537        );
14538    }
14539
14540    #[test]
14541    fn golden_iam_token_tcps_descriptor_and_wire_bytes() {
14542        let connect_string = concat!(
14543            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=adb.example.test)(PORT=2484))",
14544            "(CONNECT_DATA=(SERVICE_NAME=adbsvc))",
14545            "(SECURITY=(SSL_SERVER_DN_MATCH=off)))"
14546        );
14547        let descriptor = EasyConnect::parse(connect_string).expect("parse iam token descriptor");
14548        let full_descriptor =
14549            EasyConnect::parse_descriptor(connect_string).expect("parse full iam token descriptor");
14550        let description = full_descriptor.first_description();
14551        let built = auth_connect_descriptor(
14552            &descriptor,
14553            description,
14554            true,
14555            description.security.ssl_server_dn_match,
14556            None,
14557        );
14558
14559        let expected_descriptor =
14560            include_str!("../tests/golden/connect_descriptor/iam_token_tcps.descriptor.txt").trim();
14561        assert_eq!(
14562            built, expected_descriptor,
14563            "IAM-token TCPS built connect descriptor drifted from the golden fixture"
14564        );
14565
14566        let packet = golden_connect_packet_bytes(&built, 8192);
14567        let expected_packet = decode_golden_packet_hex(include_str!(
14568            "../tests/golden/connect_descriptor/iam_token_tcps.packet.hex"
14569        ));
14570        assert_eq!(
14571            packet, expected_packet,
14572            "IAM-token TCPS CONNECT wire packet drifted from the golden fixture"
14573        );
14574    }
14575
14576    #[test]
14577    fn transport_connect_timeout_bounds_post_dial_accept_read() -> Result<()> {
14578        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
14579        let addr = listener.local_addr().expect("listener address");
14580        let server = thread::spawn(move || -> std::io::Result<()> {
14581            let (mut socket, _) = listener.accept()?;
14582            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
14583            let mut header = [0u8; 8];
14584            socket.read_exact(&mut header)?;
14585            let declared = usize::from(u16::from_be_bytes([header[0], header[1]]));
14586            let mut payload = vec![0u8; declared.saturating_sub(header.len())];
14587            socket.read_exact(&mut payload)?;
14588            thread::sleep(Duration::from_millis(300));
14589            Ok(())
14590        });
14591
14592        let options = ConnectOptions::new(
14593            format!(
14594                "127.0.0.1:{}/FREEPDB1?transport_connect_timeout=100ms",
14595                addr.port()
14596            ),
14597            "user",
14598            "password",
14599            identity(),
14600        );
14601        let runtime = build_io_runtime().expect("asupersync runtime");
14602        let started = Instant::now();
14603        let err = runtime
14604            .block_on(async {
14605                let cx = Cx::current().expect("ambient Cx");
14606                Connection::connect(&cx, options).await
14607            })
14608            .expect_err("stalling listener should hit transport connect timeout");
14609        assert!(
14610            matches!(err, Error::CallTimeout(ms) if ms == 100),
14611            "expected 100ms CallTimeout, got {err:?}"
14612        );
14613        assert!(
14614            started.elapsed() < Duration::from_secs(2),
14615            "post-dial ACCEPT read should be bounded"
14616        );
14617        server.join().expect("server thread joins")?;
14618        Ok(())
14619    }
14620
14621    /// bead F-DC4: a full `(DESCRIPTION=...)` Oracle Net descriptor's own
14622    /// `CONNECT_TIMEOUT` must actually bound a TCPS connect attempt end to
14623    /// end, including a stalled TLS handshake — not just the TCP dial, and
14624    /// not just the easy-connect `?transport_connect_timeout=` query-param
14625    /// form covered by `transport_connect_timeout_bounds_post_dial_accept_read`
14626    /// above. This is an end-to-end companion to
14627    /// `tls::tests::tls_handshake_honors_a_short_caller_supplied_timeout_against_a_stalled_peer`
14628    /// (`tests/tls_handshake.rs`), which isolates the handshake-timeout fix
14629    /// itself by calling `tls_handshake` directly; this test instead proves
14630    /// the full `Connection::connect` pipeline actually delivers that
14631    /// behavior for a full descriptor, whichever layer (the outer connect
14632    /// deadline or the handshake's own timeout) ends up enforcing it.
14633    #[test]
14634    fn full_descriptor_connect_timeout_bounds_a_stalled_tls_handshake() -> Result<()> {
14635        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
14636        let addr = listener.local_addr().expect("listener address");
14637        // Hold the TCP connection open with zero bytes sent, well past the
14638        // assertion window, so only the configured connect timeout (not a
14639        // connection-close race) can explain a fast return.
14640        let server = thread::spawn(move || -> std::io::Result<()> {
14641            let (socket, _) = listener.accept()?;
14642            thread::sleep(Duration::from_secs(3));
14643            drop(socket);
14644            Ok(())
14645        });
14646
14647        let wallet_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tls");
14648        let connect_string = format!(
14649            "(DESCRIPTION=(CONNECT_TIMEOUT=0.3)\
14650             (ADDRESS=(PROTOCOL=tcps)(HOST=127.0.0.1)(PORT={}))\
14651             (CONNECT_DATA=(SERVICE_NAME=FREEPDB1))\
14652             (SECURITY=(SSL_SERVER_DN_MATCH=off)(MY_WALLET_DIRECTORY=\"{wallet_dir}\")))",
14653            addr.port(),
14654        );
14655        let options = ConnectOptions::new(connect_string, "user", "password", identity());
14656        let runtime = build_io_runtime().expect("asupersync runtime");
14657        let started = Instant::now();
14658        let err = runtime
14659            .block_on(async {
14660                let cx = Cx::current().expect("ambient Cx");
14661                Connection::connect(&cx, options).await
14662            })
14663            .expect_err("a peer that never speaks TLS must not let connect succeed");
14664        let elapsed = started.elapsed();
14665        assert!(
14666            elapsed < Duration::from_secs(2),
14667            "the descriptor's 0.3s CONNECT_TIMEOUT must bound the TLS handshake too, not just \
14668             the TCP dial (the old hard-coded ~20s handshake timeout, or the peer's own 3s \
14669             silent hold, would both blow this budget); actually took {elapsed:?}, err={err:?}"
14670        );
14671        server.join().expect("server thread joins")?;
14672        Ok(())
14673    }
14674
14675    /// DC4's short-budget coverage proves the timeout fires promptly. This
14676    /// companion pin proves an explicitly configured budget above the old
14677    /// 20-second ceiling reaches the production TLS handoff unchanged, while
14678    /// keeping the stalled-peer exercise short by letting the peer close first.
14679    #[test]
14680    fn full_descriptor_preserves_above_twenty_second_tls_handshake_budget() -> Result<()> {
14681        const CONFIGURED_TIMEOUT: Duration = Duration::from_secs(45);
14682        const SERVER_HOLD: Duration = Duration::from_millis(250);
14683
14684        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
14685        let addr = listener.local_addr().expect("listener address");
14686        let server = thread::spawn(move || -> std::io::Result<()> {
14687            let (socket, _) = listener.accept()?;
14688            thread::sleep(SERVER_HOLD);
14689            drop(socket);
14690            Ok(())
14691        });
14692
14693        let wallet_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/tls");
14694        let connect_string = format!(
14695            "(DESCRIPTION=(CONNECT_TIMEOUT=45)\
14696             (ADDRESS=(PROTOCOL=tcps)(HOST=127.0.0.1)(PORT={}))\
14697             (CONNECT_DATA=(SERVICE_NAME=FREEPDB1))\
14698             (SECURITY=(SSL_SERVER_DN_MATCH=off)(MY_WALLET_DIRECTORY=\"{wallet_dir}\")))",
14699            addr.port(),
14700        );
14701        let parsed = EasyConnect::parse_descriptor(&connect_string)
14702            .expect("full descriptor with a 45-second CONNECT_TIMEOUT parses");
14703        let resolved_connect_timeout =
14704            transport_connect_timeout_duration(parsed.first_description().tcp_connect_timeout);
14705        assert_eq!(resolved_connect_timeout, CONFIGURED_TIMEOUT);
14706        assert_eq!(
14707            tls::handshake_timeout_from_connect_timeout(resolved_connect_timeout),
14708            CONFIGURED_TIMEOUT,
14709            "the production TLS handoff must not re-clamp a configured 45-second budget"
14710        );
14711
14712        let options = ConnectOptions::new(connect_string, "user", "password", identity());
14713        let runtime = build_io_runtime().expect("asupersync runtime");
14714        let started = Instant::now();
14715        let err = runtime
14716            .block_on(async {
14717                let cx = Cx::current().expect("ambient Cx");
14718                Connection::connect(&cx, options).await
14719            })
14720            .expect_err("a peer that never completes TLS must not connect");
14721        let elapsed = started.elapsed();
14722        assert!(
14723            elapsed >= SERVER_HOLD / 2 && elapsed < Duration::from_secs(2),
14724            "the stalled peer must drive the observed failure without turning a {CONFIGURED_TIMEOUT:?} \
14725             configuration check into a long wait; took {elapsed:?}, err={err:?}"
14726        );
14727        server.join().expect("server thread joins")?;
14728        Ok(())
14729    }
14730
14731    // ---- bead F-DC2 / F-DC3: DSN-only SSL_SERVER_CERT_DN / SSL_SERVER_DN_MATCH ----
14732    //
14733    // `tests/tls_handshake.rs` proves the crate-internal `tls::` module's DN
14734    // check is correct when `TlsParams` is built directly. It does NOT prove
14735    // that the full `Connection::connect` pipeline actually threads a
14736    // `SSL_SERVER_CERT_DN` / `SSL_SERVER_DN_MATCH` supplied ONLY via the
14737    // connect string (never through the `with_ssl_server_cert_dn` /
14738    // `with_ssl_server_dn_match` builder methods) into that verifier — which
14739    // is exactly the gap F-DC2 found: `Connection::connect` was passing the
14740    // raw, unmerged `options.ssl_server_dn_match` /
14741    // `options.ssl_server_cert_dn` (both default/absent unless the builder
14742    // was called) into `tls::resolve_tls_params`, silently dropping whatever
14743    // the DSN itself said. The three tests below drive the real
14744    // `Connection::connect` against a real rustls server presenting the
14745    // CA-signed `leaf.crt` fixture (subject DN
14746    // "C=US, O=ExampleDB, CN=db.example.com", SAN db.example.com/localhost —
14747    // no DNS SAN for a bare IP), dialled by IP (`HOST=127.0.0.1`) so the
14748    // outcome never depends on real DNS resolution.
14749    //
14750    // Discrimination does not rely on the coarse "did it fail" question —
14751    // dialling a non-Oracle stub server always eventually fails one way or
14752    // another. It relies on *which* failure: `check_cert_dn`'s
14753    // `DnMatchError::CertDnMismatch` echoes the pinned DN verbatim in its
14754    // message, while the broken fallback path (`server_cert_dn` silently
14755    // dropped to `None`) instead runs `check_server_name` against
14756    // `HOST=127.0.0.1`, which can never match this leaf's SAN (127.0.0.1 is
14757    // only present as an IP-typed SAN entry, and `parse_cert_identity` only
14758    // collects DNS-typed SAN names) — so that fallback ALWAYS fails, but with
14759    // `DnMatchError::NameMismatch`, a message that never contains the pinned
14760    // DN string. That distinction is what a passing test after the fix, and a
14761    // failing test before it, actually turns on — verified by temporarily
14762    // reverting the `descriptor_ssl_server_dn_match` /
14763    // `descriptor_ssl_server_cert_dn` wiring in `Connection::connect` and
14764    // confirming each test below fails.
14765
14766    /// Spawn a one-shot real rustls TLS server presenting the CA-signed
14767    /// `leaf.crt`/`leaf.key` fixture (the same identity `tests/tls_handshake.rs`
14768    /// uses). It completes exactly one handshake, reads whatever the peer sends
14769    /// next (the driver's TNS CONNECT packet) without attempting to understand
14770    /// it, and then closes without answering — so a `Connection::connect` that
14771    /// gets PAST the TLS/DN layer always still fails overall, just with
14772    /// something other than `Error::Tls`.
14773    fn spawn_dc2_dc3_fixture_tls_server() -> (u16, thread::JoinHandle<()>) {
14774        let mut fixtures = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
14775        fixtures.push("tests");
14776        fixtures.push("fixtures");
14777        fixtures.push("tls");
14778        let leaf = std::fs::read(fixtures.join("leaf.crt")).expect("read leaf.crt fixture");
14779        let key = std::fs::read(fixtures.join("leaf.key")).expect("read leaf.key fixture");
14780        let ca = std::fs::read(fixtures.join("ca.crt")).expect("read ca.crt fixture");
14781
14782        let mut chain: Vec<rustls::pki_types::CertificateDer<'static>> =
14783            rustls_pemfile::certs(&mut std::io::BufReader::new(&leaf[..]))
14784                .filter_map(std::result::Result::ok)
14785                .collect();
14786        chain.extend(
14787            rustls_pemfile::certs(&mut std::io::BufReader::new(&ca[..]))
14788                .filter_map(std::result::Result::ok),
14789        );
14790        let key_der = rustls_pemfile::private_key(&mut std::io::BufReader::new(&key[..]))
14791            .expect("read leaf.key")
14792            .expect("leaf.key must contain a private key");
14793
14794        let config = rustls::ServerConfig::builder()
14795            .with_no_client_auth()
14796            .with_single_cert(chain, key_der)
14797            .expect("fixture server config");
14798        let config = std::sync::Arc::new(config);
14799
14800        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
14801        let port = listener.local_addr().expect("listener address").port();
14802        let handle = thread::spawn(move || {
14803            if let Ok((mut sock, _)) = listener.accept() {
14804                if let Ok(mut conn) = rustls::ServerConnection::new(config) {
14805                    let mut tls = rustls::Stream::new(&mut conn, &mut sock);
14806                    let mut buf = [0u8; 4096];
14807                    // Best-effort: complete the handshake (if the client's
14808                    // verifier accepts it) and read whatever the client sends
14809                    // next. Never answer it — closing here is what turns
14810                    // "got past TLS" into a clean, fast non-Tls failure for
14811                    // the driver instead of a hang.
14812                    let _ = tls.read(&mut buf);
14813                }
14814            }
14815        });
14816        (port, handle)
14817    }
14818
14819    /// Copy the fixture CA-only trust wallet (`ca_wallet.pem` — the CA that
14820    /// signs `leaf.crt`, no client identity) into a fresh temp directory named
14821    /// `ewallet.pem`, the filename the directory-based wallet loader
14822    /// (`resolve_wallet_dir`/`load_wallet`) requires. Mirrors `tls.rs`'s own
14823    /// `temp_wallet_dir` test helper (a different module, so not reusable
14824    /// directly here).
14825    fn dc2_dc3_temp_ca_trust_wallet_dir(label: &str) -> std::path::PathBuf {
14826        let mut fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
14827        fixture.push("tests");
14828        fixture.push("fixtures");
14829        fixture.push("tls");
14830        fixture.push("ca_wallet.pem");
14831
14832        let dir = std::env::temp_dir().join(format!(
14833            "oracledb-dc2-dc3-wallet-{label}-{}",
14834            std::process::id()
14835        ));
14836        std::fs::create_dir_all(&dir).expect("create temp wallet dir");
14837        std::fs::copy(&fixture, dir.join("ewallet.pem")).expect("copy ca_wallet.pem fixture");
14838        dir
14839    }
14840
14841    /// Copy an unrelated synthetic CA into a temp wallet. The local TLS server
14842    /// presents `leaf.crt`, signed by `ca.crt`; trusting this unrelated CA
14843    /// makes the client fail at chain validation (`UnknownIssuer`) before any
14844    /// Oracle protocol bytes are exchanged.
14845    fn dc5_untrusted_temp_wallet_dir(label: &str) -> std::path::PathBuf {
14846        let mut fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
14847        fixture.push("tests");
14848        fixture.push("fixtures");
14849        fixture.push("tls");
14850        fixture.push("synthetic");
14851        fixture.push("ca.pem");
14852
14853        let dir = std::env::temp_dir().join(format!(
14854            "oracledb-dc5-untrusted-wallet-{label}-{}",
14855            std::process::id()
14856        ));
14857        std::fs::create_dir_all(&dir).expect("create temp untrusted wallet dir");
14858        std::fs::copy(&fixture, dir.join("ewallet.pem")).expect("copy unrelated ca.pem fixture");
14859        dir
14860    }
14861
14862    /// Build a full `(DESCRIPTION=...)` TCPS connect string pinning
14863    /// `SSL_SERVER_CERT_DN` (and, when `dn_match_off` is set,
14864    /// `SSL_SERVER_DN_MATCH=OFF`) entirely in the connect string — the
14865    /// DSN-only path F-DC2/F-DC3 found broken. `wallet_dir` must hold a
14866    /// directory-loadable wallet trusting the CA that signed the server's
14867    /// presented certificate.
14868    fn dc2_dc3_connect_string(
14869        port: u16,
14870        wallet_dir: &std::path::Path,
14871        cert_dn: &str,
14872        dn_match_off: bool,
14873    ) -> String {
14874        let dn_match_clause = if dn_match_off {
14875            "(SSL_SERVER_DN_MATCH=off)"
14876        } else {
14877            ""
14878        };
14879        let wallet = wallet_dir.display();
14880        format!(
14881            "(DESCRIPTION=(CONNECT_TIMEOUT=10)\
14882             (ADDRESS=(PROTOCOL=tcps)(HOST=127.0.0.1)(PORT={port}))\
14883             (CONNECT_DATA=(SERVICE_NAME=FREEPDB1))\
14884             (SECURITY={dn_match_clause}(SSL_SERVER_CERT_DN={cert_dn})\
14885             (MY_WALLET_DIRECTORY=\"{wallet}\")))"
14886        )
14887    }
14888
14889    /// The exact phrase `DnMatchError::CertDnMismatch` renders
14890    /// (`crates/oracledb-protocol/src/tls/dn.rs`), independent of the pinned
14891    /// DN value — used to detect that `check_cert_dn` genuinely ran.
14892    const DC_CERT_DN_MISMATCH_PHRASE: &str =
14893        "distinguished name (DN) on the server certificate does not match";
14894    /// The exact phrase `DnMatchError::NameMismatch` renders — used to detect
14895    /// the broken fallback path (hostname/SAN match) the DC2 bug silently
14896    /// took instead of the pinned-DN check.
14897    const DC_NAME_MISMATCH_PHRASE: &str = "does not match the names in the server certificate";
14898
14899    /// A single connect attempt against the loopback address is
14900    /// failover-eligible (`is_failover_eligible`), so a TLS/DN rejection
14901    /// surfaces wrapped in `Error::AllAddressesFailed` rather than as a bare
14902    /// `Error::Tls` — but its `Display`/`Debug` chain still embeds the
14903    /// original message verbatim (via the inner error's own `Display`), so
14904    /// asserting on the *rendered text* is the discriminator that survives
14905    /// that wrapping.
14906    fn dc_rendered_error(err: &Error) -> String {
14907        format!("{err} / debug={err:?}")
14908    }
14909
14910    /// B5 / oraclemcp-u9ldz: an untrusted TCPS server certificate is a terminal
14911    /// certificate-verification failure, not a transport timeout and not a
14912    /// generic all-addresses aggregate. Differential proof against
14913    /// python-oracledb 4.0.1 on the same synthetic shape:
14914    /// `CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate` in
14915    /// ~10 ms, with the server receiving `tlsv1 alert unknown ca`.
14916    #[test]
14917    fn b5_tcps_unknown_issuer_is_tls_error_not_timeout_or_failover() {
14918        let (port, server) = spawn_dc2_dc3_fixture_tls_server();
14919        let wallet_dir = dc5_untrusted_temp_wallet_dir("unknown-issuer");
14920        let options = ConnectOptions::new(
14921            format!("tcps://127.0.0.1:{port}/FREEPDB1?transport_connect_timeout=10"),
14922            "user",
14923            "password",
14924            identity(),
14925        )
14926        .with_wallet_location(wallet_dir.display().to_string());
14927
14928        let runtime = build_io_runtime().expect("asupersync runtime");
14929        let started = Instant::now();
14930        let err = runtime
14931            .block_on(async {
14932                let cx = Cx::current().expect("ambient Cx");
14933                Connection::connect(&cx, options).await
14934            })
14935            .expect_err("an untrusted synthetic TCPS certificate must be refused");
14936        let elapsed = started.elapsed();
14937        let rendered = dc_rendered_error(&err);
14938        assert!(
14939            elapsed < Duration::from_secs(5),
14940            "untrusted issuer must fail fast, not wait for connect timeout; took {elapsed:?}, \
14941             error={rendered}"
14942        );
14943        assert!(
14944            matches!(&err, Error::Tls(detail)
14945                if detail.contains("certificate") && detail.contains("not trusted")),
14946            "untrusted issuer must surface as a structured TLS certificate error, not timeout or \
14947             failover aggregation; got {rendered}"
14948        );
14949        assert!(
14950            !matches!(err, Error::CallTimeout(_) | Error::AllAddressesFailed(_)),
14951            "untrusted issuer must not be hidden as timeout/failover aggregation: {rendered}"
14952        );
14953        let _ = server.join();
14954    }
14955
14956    /// F-DC2 discriminating test: a `SSL_SERVER_CERT_DN` pinned ONLY in the
14957    /// connect string (never through `with_ssl_server_cert_dn`) that does NOT
14958    /// match the server's real subject DN must be refused, with the DN check
14959    /// actually having run (`check_cert_dn`'s rejection echoes the pinned DN
14960    /// verbatim) — not merely refused for some unrelated reason, and not the
14961    /// broken fallback (a hostname/SAN `NameMismatch` against HOST=127.0.0.1,
14962    /// which never mentions the pinned DN at all).
14963    #[test]
14964    fn f_dc2_dsn_only_pinned_cert_dn_mismatch_is_refused() {
14965        let (port, server) = spawn_dc2_dc3_fixture_tls_server();
14966        let wallet_dir = dc2_dc3_temp_ca_trust_wallet_dir("mismatch");
14967        let wrong_dn = "CN=not-the-real-server.invalid,O=Nope,C=ZZ";
14968        let connect_string = dc2_dc3_connect_string(port, &wallet_dir, wrong_dn, false);
14969        let options = ConnectOptions::new(connect_string, "user", "password", identity());
14970        let runtime = build_io_runtime().expect("asupersync runtime");
14971        let err = runtime
14972            .block_on(async {
14973                let cx = Cx::current().expect("ambient Cx");
14974                Connection::connect(&cx, options).await
14975            })
14976            .expect_err(
14977                "a server whose DN does not match a DSN-only pinned SSL_SERVER_CERT_DN must be \
14978                 refused",
14979            );
14980        let rendered = dc_rendered_error(&err);
14981        assert!(
14982            rendered.contains(wrong_dn) && rendered.contains(DC_CERT_DN_MISMATCH_PHRASE),
14983            "the DSN-only pinned SSL_SERVER_CERT_DN must actually reach the verifier — expected \
14984             the rejection to echo the pinned DN {wrong_dn:?} via a CertDnMismatch \
14985             ({DC_CERT_DN_MISMATCH_PHRASE:?}), proving `check_cert_dn` ran with the DSN-supplied \
14986             value; got: {rendered}"
14987        );
14988        let _ = server.join();
14989    }
14990
14991    /// F-DC2 positive counterpart: a `SSL_SERVER_CERT_DN` pinned ONLY in the
14992    /// connect string that DOES match the server's real subject DN must pass
14993    /// the TLS/DN layer cleanly. The stub server never answers a real Oracle
14994    /// listener response, so the overall connect still fails — but the
14995    /// rejection must carry NEITHER DN-match failure phrase, proving the
14996    /// pinned DN was accepted rather than never checked (or checked and
14997    /// rejected via the broken hostname/SAN fallback).
14998    #[test]
14999    fn f_dc2_dsn_only_pinned_cert_dn_match_passes_tls_layer() {
15000        let (port, server) = spawn_dc2_dc3_fixture_tls_server();
15001        let wallet_dir = dc2_dc3_temp_ca_trust_wallet_dir("match");
15002        let real_dn = "CN=db.example.com,O=ExampleDB,C=US";
15003        let connect_string = dc2_dc3_connect_string(port, &wallet_dir, real_dn, false);
15004        let options = ConnectOptions::new(connect_string, "user", "password", identity());
15005        let runtime = build_io_runtime().expect("asupersync runtime");
15006        let err = runtime
15007            .block_on(async {
15008                let cx = Cx::current().expect("ambient Cx");
15009                Connection::connect(&cx, options).await
15010            })
15011            .expect_err(
15012                "the stub server never answers a real Oracle listener response, so connect must \
15013                 still fail overall",
15014            );
15015        let rendered = dc_rendered_error(&err);
15016        assert!(
15017            !rendered.contains(DC_CERT_DN_MISMATCH_PHRASE)
15018                && !rendered.contains(DC_NAME_MISMATCH_PHRASE),
15019            "a matching DSN-only pinned SSL_SERVER_CERT_DN must pass the TLS/DN layer cleanly — \
15020             got a DN-match rejection instead, meaning the pin was not honored (it likely fell \
15021             back to a hostname/SAN check against HOST=127.0.0.1, which this certificate's SAN \
15022             never matches): {rendered}"
15023        );
15024        let _ = server.join();
15025    }
15026
15027    /// F-DC3 discriminating test: `SSL_SERVER_DN_MATCH=OFF` set ONLY in the
15028    /// connect string must deliberately disable the DN check — including
15029    /// against a mismatched pinned `SSL_SERVER_CERT_DN` — never leave it
15030    /// silently enforced. Paired with the default-enforces case above
15031    /// (`f_dc2_dsn_only_pinned_cert_dn_mismatch_is_refused`, which pins the
15032    /// SAME wrong DN without DN_MATCH=OFF and must still be refused).
15033    #[test]
15034    fn f_dc3_dn_match_off_deliberately_skips_the_pinned_cert_dn_check() {
15035        let (port, server) = spawn_dc2_dc3_fixture_tls_server();
15036        let wallet_dir = dc2_dc3_temp_ca_trust_wallet_dir("off");
15037        let wrong_dn = "CN=not-the-real-server.invalid,O=Nope,C=ZZ";
15038        let connect_string = dc2_dc3_connect_string(port, &wallet_dir, wrong_dn, true);
15039        let options = ConnectOptions::new(connect_string, "user", "password", identity());
15040        let runtime = build_io_runtime().expect("asupersync runtime");
15041        let err = runtime
15042            .block_on(async {
15043                let cx = Cx::current().expect("ambient Cx");
15044                Connection::connect(&cx, options).await
15045            })
15046            .expect_err("the stub server never answers a real Oracle listener response");
15047        let rendered = dc_rendered_error(&err);
15048        assert!(
15049            !rendered.contains(DC_CERT_DN_MISMATCH_PHRASE)
15050                && !rendered.contains(DC_NAME_MISMATCH_PHRASE),
15051            "SSL_SERVER_DN_MATCH=OFF set only in the connect string must deliberately disable \
15052             the DN check — even with a mismatched pinned SSL_SERVER_CERT_DN — got a DN-match \
15053             rejection instead, meaning OFF did not actually reach the verifier: {rendered}"
15054        );
15055        let _ = server.join();
15056    }
15057
15058    /// F-DC3 precedence pin: effective `dn_match` is the **AND** of the
15059    /// DSN-parsed `SECURITY.SSL_SERVER_DN_MATCH` and
15060    /// `ConnectOptions::ssl_server_dn_match` (both default `true`). Either side
15061    /// set to OFF disables identity matching; chain-of-trust validation is
15062    /// unaffected (see `OracleServerCertVerifier::run_dn_match` /
15063    /// `resolve_tls_params`).
15064    #[test]
15065    fn f_dc3_dsn_and_options_dn_match_merge_is_and_not_options_only() {
15066        let default_dsn = "tcps://h.example:2484/svc";
15067        let default_desc = EasyConnect::parse_descriptor(default_dsn).expect("parse default dsn");
15068        let default_options = ConnectOptions::new(default_dsn, "u", "p", identity());
15069        assert!(
15070            effective_ssl_server_dn_match(default_desc.first_description(), &default_options),
15071            "default DSN + default options must keep DN matching ON"
15072        );
15073
15074        // DSN-only OFF parses to false on the security block.
15075        let off_dsn = concat!(
15076            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=h.example)(PORT=2484))",
15077            "(CONNECT_DATA=(SERVICE_NAME=svc))",
15078            "(SECURITY=(SSL_SERVER_DN_MATCH=off)))"
15079        );
15080        let off_desc = EasyConnect::parse_descriptor(off_dsn).expect("parse OFF dsn");
15081        assert!(
15082            !off_desc.first_description().security.ssl_server_dn_match,
15083            "DSN SSL_SERVER_DN_MATCH=off must parse to security.ssl_server_dn_match=false"
15084        );
15085        let off_options = ConnectOptions::new(off_dsn, "u", "p", identity());
15086        assert!(
15087            !effective_ssl_server_dn_match(off_desc.first_description(), &off_options),
15088            "DSN SSL_SERVER_DN_MATCH=OFF must win over default options=true"
15089        );
15090
15091        let on_dsn = concat!(
15092            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=h.example)(PORT=2484))",
15093            "(CONNECT_DATA=(SERVICE_NAME=svc))",
15094            "(SECURITY=(SSL_SERVER_DN_MATCH=on)))"
15095        );
15096        let on_desc = EasyConnect::parse_descriptor(on_dsn).expect("parse ON dsn");
15097        assert!(on_desc.first_description().security.ssl_server_dn_match);
15098
15099        // Builder surface: options OFF combines with DSN ON → effective false.
15100        let options_off =
15101            ConnectOptions::new(on_dsn, "u", "p", identity()).with_ssl_server_dn_match(false);
15102        assert!(!options_off.ssl_server_dn_match());
15103        assert!(
15104            !effective_ssl_server_dn_match(on_desc.first_description(), &options_off),
15105            "explicit ConnectOptions::with_ssl_server_dn_match(false) must win over DSN=ON"
15106        );
15107
15108        let both_off =
15109            ConnectOptions::new(off_dsn, "u", "p", identity()).with_ssl_server_dn_match(false);
15110        assert!(
15111            !effective_ssl_server_dn_match(off_desc.first_description(), &both_off),
15112            "both OFF stays OFF"
15113        );
15114
15115        // resolve_tls_params must receive the effective false and set dn_match=false
15116        // (identity short-circuit only — chain still validated by the verifier).
15117        let easy = EasyConnect::parse(off_dsn).expect("easy parse OFF");
15118        let params = crate::tls::resolve_tls_params(
15119            &easy,
15120            None,
15121            None,
15122            effective_ssl_server_dn_match(off_desc.first_description(), &off_options),
15123            None,
15124            false,
15125        )
15126        .expect("resolve with dn_match=false");
15127        assert!(
15128            !params.dn_match,
15129            "resolve_tls_params must record dn_match=false when effective OFF"
15130        );
15131    }
15132
15133    #[test]
15134    fn async_cancel_handle_requests_break_and_reconciles_ready() -> Result<()> {
15135        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
15136        let addr = listener.local_addr().expect("listener address");
15137        let server = thread::spawn(move || {
15138            let (mut socket, _) = listener.accept().expect("accept test client");
15139            socket
15140                .set_read_timeout(Some(Duration::from_secs(5)))
15141                .expect("set read timeout");
15142            let mut packet = [0u8; 11];
15143            socket.read_exact(&mut packet).expect("read marker packet");
15144            packet
15145        });
15146
15147        let runtime = build_io_runtime().expect("asupersync runtime");
15148        let recovery = Arc::new(SessionRecovery::new());
15149        let mut handle = runtime.block_on(async {
15150            let stream = TcpStream::connect(addr).await.expect("connect to listener");
15151            let (_read, write) = transport::plain_split(stream);
15152            CancelHandle {
15153                write: Arc::new(AsyncMutex::with_name("oracle_tcp_write_test", write)),
15154                recovery: Arc::clone(&recovery),
15155            }
15156        });
15157
15158        runtime.block_on(async {
15159            let cx = Cx::current()
15160                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
15161            handle.cancel(&cx).await
15162        })?;
15163
15164        let packet = server.join().expect("server thread joins");
15165        assert_eq!(
15166            packet,
15167            [
15168                0,
15169                0,
15170                0,
15171                11,
15172                TNS_PACKET_TYPE_MARKER,
15173                0,
15174                0,
15175                0,
15176                1,
15177                0,
15178                TNS_MARKER_TYPE_BREAK
15179            ]
15180        );
15181        assert_eq!(
15182            recovery.phase(),
15183            SessionRecoveryPhase::BreakSent,
15184            "CancelHandle::cancel(&Cx) requests cancellation without draining"
15185        );
15186        assert!(
15187            recovery.begin_pending_drain()?,
15188            "the connection owner must be able to adopt the pending cancel response"
15189        );
15190        recovery.finish_drain_ready();
15191        assert_eq!(
15192            recovery.phase(),
15193            SessionRecoveryPhase::Ready,
15194            "successful cancel-response drain reconciles the session to Ready"
15195        );
15196        Ok(())
15197    }
15198
15199    #[test]
15200    fn async_cancel_handle_owner_drain_reconciles_ready() -> Result<()> {
15201        const INFLIGHT_BODY: &[u8] = &[0xCA, 0xFE];
15202        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
15203        const FRESH_BODY: &[u8] = &[0x07, 0x05, 0x0c];
15204
15205        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
15206        let addr = listener.local_addr().expect("listener address");
15207        let server = thread::spawn(move || {
15208            let (mut socket, _) = listener.accept().expect("accept test client");
15209            socket
15210                .set_read_timeout(Some(Duration::from_secs(5)))
15211                .expect("set read timeout");
15212            use std::io::Write as _;
15213
15214            assert_eq!(
15215                read_marker_type(&mut socket),
15216                TNS_MARKER_TYPE_BREAK,
15217                "CancelHandle must send exactly one BREAK request"
15218            );
15219            socket
15220                .write_all(&data_packet(INFLIGHT_BODY, true))
15221                .expect("write in-flight response");
15222            socket
15223                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
15224                .expect("write break-ack marker");
15225            assert_eq!(
15226                read_marker_type(&mut socket),
15227                TNS_MARKER_TYPE_RESET,
15228                "owner drain must answer the break marker with RESET"
15229            );
15230            socket
15231                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
15232                .expect("write reset-confirm marker");
15233            socket
15234                .write_all(&data_packet(ERROR_BODY, true))
15235                .expect("write trailing cancel error packet");
15236            socket
15237                .write_all(&data_packet(FRESH_BODY, true))
15238                .expect("write fresh response");
15239        });
15240
15241        let runtime = build_io_runtime().expect("asupersync runtime");
15242        let next = runtime.block_on(async {
15243            let cx = Cx::current()
15244                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
15245            let stream = TcpStream::connect(addr).await.expect("connect to listener");
15246            let (read, write) = transport::plain_split(stream);
15247            let mut conn = loopback_connection(read, write);
15248            let mut handle = conn.cancel_handle()?;
15249
15250            handle.cancel(&cx).await?;
15251            assert_eq!(
15252                conn.core.recovery.phase(),
15253                SessionRecoveryPhase::BreakSent,
15254                "handle cancel only requests recovery"
15255            );
15256            conn.drain_cancel_response().await?;
15257            assert_eq!(
15258                conn.core.recovery.phase(),
15259                SessionRecoveryPhase::Ready,
15260                "owner drain reconciles a successful cancel response to Ready"
15261            );
15262            conn.core.read_data_response(&cx).await
15263        })?;
15264
15265        assert_eq!(
15266            next, FRESH_BODY,
15267            "after owner drain the next read must consume the fresh response"
15268        );
15269        server.join().expect("server thread joins");
15270        Ok(())
15271    }
15272
15273    #[test]
15274    fn async_cancel_handle_owner_drain_failure_marks_dead() -> Result<()> {
15275        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
15276        let addr = listener.local_addr().expect("listener address");
15277        let server = thread::spawn(move || {
15278            let (mut socket, _) = listener.accept().expect("accept test client");
15279            socket
15280                .set_read_timeout(Some(Duration::from_secs(5)))
15281                .expect("set read timeout");
15282            assert_eq!(
15283                read_marker_type(&mut socket),
15284                TNS_MARKER_TYPE_BREAK,
15285                "CancelHandle must send the BREAK before the failed drain"
15286            );
15287            // Drop the socket without sending a complete cancel response.
15288        });
15289
15290        let runtime = build_io_runtime().expect("asupersync runtime");
15291        runtime.block_on(async {
15292            let cx = Cx::current()
15293                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
15294            let stream = TcpStream::connect(addr).await.expect("connect to listener");
15295            let (read, write) = transport::plain_split(stream);
15296            let mut conn = loopback_connection(read, write);
15297            let mut handle = conn.cancel_handle()?;
15298
15299            handle.cancel(&cx).await?;
15300            assert_eq!(conn.core.recovery.phase(), SessionRecoveryPhase::BreakSent);
15301            assert!(
15302                conn.drain_cancel_response().await.is_err(),
15303                "incomplete cancel response must fail owner drain"
15304            );
15305            assert!(
15306                conn.is_dead(),
15307                "failed owner drain marks the connection dead"
15308            );
15309            assert_eq!(conn.core.recovery.phase(), SessionRecoveryPhase::Dead);
15310            Ok::<(), Error>(())
15311        })?;
15312
15313        server.join().expect("server thread joins");
15314        Ok(())
15315    }
15316
15317    #[test]
15318    fn async_cancel_handle_does_not_send_duplicate_break_when_recovery_pending() -> Result<()> {
15319        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
15320        let addr = listener.local_addr().expect("listener address");
15321        let server = thread::spawn(move || {
15322            let (mut socket, _) = listener.accept().expect("accept test client");
15323            socket
15324                .set_read_timeout(Some(Duration::from_secs(5)))
15325                .expect("set read timeout");
15326            let mut packet = [0u8; 11];
15327            socket.read_exact(&mut packet).expect("read first break");
15328            socket
15329                .set_read_timeout(Some(Duration::from_millis(200)))
15330                .expect("set short read timeout");
15331            let mut extra = [0u8; 1];
15332            let extra_read = socket.read_exact(&mut extra);
15333            assert!(
15334                matches!(
15335                    extra_read.as_ref().map_err(std::io::Error::kind),
15336                    Err(std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)
15337                ),
15338                "duplicate BREAK check expected a read timeout, got {extra_read:?} with byte {:02x}",
15339                extra[0]
15340            );
15341            packet
15342        });
15343
15344        let runtime = build_io_runtime().expect("asupersync runtime");
15345        let recovery = Arc::new(SessionRecovery::new());
15346        let mut handle = runtime.block_on(async {
15347            let stream = TcpStream::connect(addr).await.expect("connect to listener");
15348            let (_read, write) = transport::plain_split(stream);
15349            CancelHandle {
15350                write: Arc::new(AsyncMutex::with_name("oracle_tcp_write_test", write)),
15351                recovery: Arc::clone(&recovery),
15352            }
15353        });
15354
15355        runtime.block_on(async {
15356            let cx = Cx::current()
15357                .ok_or_else(|| Error::Runtime("asupersync did not install an ambient Cx".into()))?;
15358            handle.cancel(&cx).await?;
15359            assert_eq!(recovery.phase(), SessionRecoveryPhase::BreakSent);
15360            handle.cancel(&cx).await?;
15361            assert!(
15362                recovery.begin_pending_drain()?,
15363                "test moves the pending cancel into Draining"
15364            );
15365            handle.cancel(&cx).await
15366        })?;
15367
15368        let packet = server.join().expect("server thread joins");
15369        assert_eq!(
15370            packet,
15371            [
15372                0,
15373                0,
15374                0,
15375                11,
15376                TNS_PACKET_TYPE_MARKER,
15377                0,
15378                0,
15379                0,
15380                1,
15381                0,
15382                TNS_MARKER_TYPE_BREAK
15383            ]
15384        );
15385        assert_eq!(recovery.phase(), SessionRecoveryPhase::Draining);
15386        Ok(())
15387    }
15388
15389    #[test]
15390    fn blocking_cancel_handle_sends_tns_break_marker() {
15391        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
15392        let addr = listener.local_addr().expect("listener address");
15393        let server = thread::spawn(move || {
15394            let (mut socket, _) = listener.accept().expect("accept test client");
15395            socket
15396                .set_read_timeout(Some(Duration::from_secs(5)))
15397                .expect("set read timeout");
15398            let mut packet = [0u8; 11];
15399            socket.read_exact(&mut packet).expect("read marker packet");
15400            packet
15401        });
15402
15403        let runtime = build_io_runtime().expect("asupersync runtime");
15404        let recovery = Arc::new(SessionRecovery::new());
15405        let mut handle = runtime.block_on(async {
15406            let stream = TcpStream::connect(addr).await.expect("connect to listener");
15407            let (_read, write) = transport::plain_split(stream);
15408            CancelHandle {
15409                write: Arc::new(AsyncMutex::with_name("oracle_tcp_write_test", write)),
15410                recovery: Arc::clone(&recovery),
15411            }
15412        });
15413
15414        handle.cancel_blocking().expect("cancel marker write");
15415
15416        let packet = server.join().expect("server thread joins");
15417        assert_eq!(
15418            packet,
15419            [
15420                0,
15421                0,
15422                0,
15423                11,
15424                TNS_PACKET_TYPE_MARKER,
15425                0,
15426                0,
15427                0,
15428                1,
15429                0,
15430                TNS_MARKER_TYPE_BREAK
15431            ]
15432        );
15433        assert_eq!(recovery.phase(), SessionRecoveryPhase::BreakSent);
15434    }
15435
15436    // ---- break_and_drain regression (bead rust-oracledb-2vx) -------------------
15437    //
15438    // On a call timeout the driver must send a BREAK and then DRAIN the server's
15439    // in-flight response + RESET handshake + trailing error packet, leaving the
15440    // wire at a clean boundary so the NEXT operation on the reused connection
15441    // reads its own response — not the stale bytes left behind by the timed-out
15442    // call. The reference does this via `_break_external()` + `_receive_packet()`
15443    // (-> `_reset()` on the MARKER), protocol.pyx:449-451, 507-557.
15444
15445    const EOR_FLAG: u16 = oracledb_protocol::thin::TNS_DATA_FLAGS_END_OF_RESPONSE;
15446
15447    /// A DATA packet carrying `message` after its 2-byte data flags. When
15448    /// `end_of_response` is set it carries the END_OF_RESPONSE data flag, so the
15449    /// reassembler treats it as the final packet of a response.
15450    fn data_packet(message: &[u8], end_of_response: bool) -> Vec<u8> {
15451        let flags = if end_of_response { EOR_FLAG } else { 0 };
15452        encode_packet(
15453            TNS_PACKET_TYPE_DATA,
15454            0,
15455            Some(flags),
15456            message,
15457            PacketLengthWidth::Large32,
15458        )
15459        .expect("encode data packet")
15460    }
15461
15462    /// A MARKER packet of the given marker type (`[1, 0, marker_type]` payload,
15463    /// matching `send_marker`).
15464    fn marker_packet(marker_type: u8) -> Vec<u8> {
15465        encode_packet(
15466            TNS_PACKET_TYPE_MARKER,
15467            0,
15468            None,
15469            &[1, 0, marker_type],
15470            PacketLengthWidth::Large32,
15471        )
15472        .expect("encode marker packet")
15473    }
15474
15475    #[derive(Debug)]
15476    struct ScriptedTransport;
15477
15478    impl WireTransport for ScriptedTransport {
15479        type Read = ScriptedRead;
15480        type Write = ScriptedWrite;
15481    }
15482
15483    #[derive(Debug)]
15484    struct ScriptedRead {
15485        state: Arc<std::sync::Mutex<ScriptedIoState>>,
15486    }
15487
15488    impl ScriptedRead {
15489        fn from_state(state: Arc<std::sync::Mutex<ScriptedIoState>>) -> Self {
15490            Self { state }
15491        }
15492    }
15493
15494    impl asupersync::io::AsyncRead for ScriptedRead {
15495        fn poll_read(
15496            self: std::pin::Pin<&mut Self>,
15497            cx: &mut std::task::Context<'_>,
15498            buf: &mut asupersync::io::ReadBuf<'_>,
15499        ) -> std::task::Poll<std::io::Result<()>> {
15500            let Ok(mut state) = self.state.lock() else {
15501                return std::task::Poll::Ready(Err(std::io::Error::other(
15502                    "scripted transport: poisoned read state",
15503                )));
15504            };
15505
15506            loop {
15507                match state.read.front_mut() {
15508                    Some(ReadAction::Bytes {
15509                        bytes,
15510                        offset,
15511                        max_chunk,
15512                        cancel_current_on_completion,
15513                    }) => {
15514                        if *offset >= bytes.len() {
15515                            state.read.pop_front();
15516                            continue;
15517                        }
15518                        let cap = max_chunk.unwrap_or(usize::MAX);
15519                        let available = bytes.len() - *offset;
15520                        let take = available.min(buf.remaining()).min(cap);
15521                        if take == 0 {
15522                            return std::task::Poll::Ready(Ok(()));
15523                        }
15524                        buf.put_slice(&bytes[*offset..*offset + take]);
15525                        *offset += take;
15526                        if *offset >= bytes.len() {
15527                            let cancel_current_on_completion = *cancel_current_on_completion;
15528                            state.read.pop_front();
15529                            if cancel_current_on_completion {
15530                                if let Some(cx) = Cx::current() {
15531                                    cx.cancel_fast(asupersync::CancelKind::User);
15532                                }
15533                            }
15534                        }
15535                        return std::task::Poll::Ready(Ok(()));
15536                    }
15537                    Some(ReadAction::Pending) => {
15538                        state.read.pop_front();
15539                        cx.waker().wake_by_ref();
15540                        return std::task::Poll::Pending;
15541                    }
15542                    Some(ReadAction::PendingUntil(gate)) => {
15543                        if gate.is_open() {
15544                            state.read.pop_front();
15545                            continue;
15546                        }
15547                        gate.register(cx.waker());
15548                        return std::task::Poll::Pending;
15549                    }
15550                    Some(ReadAction::Eof) | None => return std::task::Poll::Ready(Ok(())),
15551                    Some(ReadAction::Error(message)) => {
15552                        let message = *message;
15553                        state.read.pop_front();
15554                        return std::task::Poll::Ready(Err(std::io::Error::other(message)));
15555                    }
15556                    Some(ReadAction::ErrorKind(kind, message)) => {
15557                        let kind = *kind;
15558                        let message = *message;
15559                        state.read.pop_front();
15560                        return std::task::Poll::Ready(Err(std::io::Error::new(kind, message)));
15561                    }
15562                    Some(ReadAction::AdvanceTime(duration)) => {
15563                        let duration = *duration;
15564                        state.read.pop_front();
15565                        state.clock.advance(duration);
15566                    }
15567                }
15568            }
15569        }
15570    }
15571
15572    #[derive(Debug)]
15573    struct ScriptedWrite {
15574        state: Arc<std::sync::Mutex<ScriptedIoState>>,
15575    }
15576
15577    impl ScriptedWrite {
15578        fn from_state(state: Arc<std::sync::Mutex<ScriptedIoState>>) -> Self {
15579            Self { state }
15580        }
15581    }
15582
15583    impl asupersync::io::AsyncWrite for ScriptedWrite {
15584        fn poll_write(
15585            self: std::pin::Pin<&mut Self>,
15586            cx: &mut std::task::Context<'_>,
15587            buf: &[u8],
15588        ) -> std::task::Poll<std::io::Result<usize>> {
15589            let Ok(mut state) = self.state.lock() else {
15590                return std::task::Poll::Ready(Err(std::io::Error::other(
15591                    "scripted transport: poisoned write state",
15592                )));
15593            };
15594
15595            loop {
15596                match state.write.front_mut() {
15597                    Some(WriteAction::Expect { .. }) => {
15598                        let mut completed = None;
15599                        let take = {
15600                            let Some(WriteAction::Expect {
15601                                bytes,
15602                                offset,
15603                                max_chunk,
15604                            }) = state.write.front_mut()
15605                            else {
15606                                unreachable!("front action already matched Expect");
15607                            };
15608                            if *offset >= bytes.len() {
15609                                state.write.pop_front();
15610                                continue;
15611                            }
15612                            let cap = max_chunk.unwrap_or(usize::MAX);
15613                            let available = bytes.len() - *offset;
15614                            let take = available.min(buf.len()).min(cap);
15615                            if take == 0 {
15616                                return std::task::Poll::Ready(Ok(0));
15617                            }
15618                            if bytes[*offset..*offset + take] != buf[..take] {
15619                                return std::task::Poll::Ready(Err(std::io::Error::other(
15620                                    "scripted transport: write mismatch",
15621                                )));
15622                            }
15623                            *offset += take;
15624                            if *offset >= bytes.len() {
15625                                completed = Some(bytes.clone());
15626                            }
15627                            take
15628                        };
15629                        if let Some(bytes) = completed {
15630                            state.note_write(&bytes);
15631                            state.write.pop_front();
15632                        }
15633                        return std::task::Poll::Ready(Ok(take));
15634                    }
15635                    Some(WriteAction::Pending) => {
15636                        state.write.pop_front();
15637                        cx.waker().wake_by_ref();
15638                        return std::task::Poll::Pending;
15639                    }
15640                    Some(WriteAction::Eof) => {
15641                        state.write.pop_front();
15642                        return std::task::Poll::Ready(Ok(0));
15643                    }
15644                    Some(WriteAction::Error(message)) => {
15645                        let message = *message;
15646                        state.write.pop_front();
15647                        return std::task::Poll::Ready(Err(std::io::Error::other(message)));
15648                    }
15649                    Some(WriteAction::AdvanceTime(duration)) => {
15650                        let duration = *duration;
15651                        state.write.pop_front();
15652                        state.clock.advance(duration);
15653                    }
15654                    None => {
15655                        return std::task::Poll::Ready(Err(std::io::Error::other(
15656                            "scripted transport: unexpected write",
15657                        )));
15658                    }
15659                }
15660            }
15661        }
15662
15663        fn poll_flush(
15664            self: std::pin::Pin<&mut Self>,
15665            _cx: &mut std::task::Context<'_>,
15666        ) -> std::task::Poll<std::io::Result<()>> {
15667            std::task::Poll::Ready(Ok(()))
15668        }
15669
15670        fn poll_shutdown(
15671            self: std::pin::Pin<&mut Self>,
15672            _cx: &mut std::task::Context<'_>,
15673        ) -> std::task::Poll<std::io::Result<()>> {
15674            std::task::Poll::Ready(Ok(()))
15675        }
15676    }
15677
15678    #[derive(Clone, Debug, Default)]
15679    struct ScriptedClock {
15680        nanos: Arc<std::sync::atomic::AtomicU64>,
15681    }
15682
15683    impl ScriptedClock {
15684        fn advance(&self, duration: Duration) {
15685            let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
15686            self.nanos.fetch_add(nanos, Ordering::Relaxed);
15687        }
15688
15689        fn elapsed(&self) -> Duration {
15690            Duration::from_nanos(self.nanos.load(Ordering::Relaxed))
15691        }
15692    }
15693
15694    #[derive(Clone, Default)]
15695    struct ScriptedGate {
15696        ready: Arc<AtomicBool>,
15697        waker: Arc<std::sync::Mutex<Option<Waker>>>,
15698    }
15699
15700    impl std::fmt::Debug for ScriptedGate {
15701        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15702            f.debug_struct("ScriptedGate")
15703                .field("ready", &self.ready.load(Ordering::Relaxed))
15704                .finish_non_exhaustive()
15705        }
15706    }
15707
15708    impl ScriptedGate {
15709        fn open(&self) {
15710            self.ready.store(true, Ordering::Release);
15711            if let Ok(mut waker) = self.waker.lock() {
15712                if let Some(waker) = waker.take() {
15713                    waker.wake();
15714                }
15715            }
15716        }
15717
15718        fn is_open(&self) -> bool {
15719            self.ready.load(Ordering::Acquire)
15720        }
15721
15722        fn register(&self, waker: &Waker) {
15723            if let Ok(mut current) = self.waker.lock() {
15724                let replace = current
15725                    .as_ref()
15726                    .is_none_or(|registered| !registered.will_wake(waker));
15727                if replace {
15728                    *current = Some(waker.clone());
15729                }
15730            }
15731        }
15732    }
15733
15734    #[derive(Debug)]
15735    struct ScriptedIoState {
15736        read: VecDeque<ReadAction>,
15737        write: VecDeque<WriteAction>,
15738        clock: ScriptedClock,
15739        break_writes: usize,
15740        reset_writes: usize,
15741    }
15742
15743    impl ScriptedIoState {
15744        fn new(read: Vec<ReadAction>, write: Vec<WriteAction>, clock: ScriptedClock) -> Self {
15745            Self {
15746                read: read.into(),
15747                write: write.into(),
15748                clock,
15749                break_writes: 0,
15750                reset_writes: 0,
15751            }
15752        }
15753
15754        fn is_consumed(&self) -> bool {
15755            self.read.is_empty() && self.write.is_empty()
15756        }
15757
15758        fn note_write(&mut self, bytes: &[u8]) {
15759            let break_marker = marker_packet(TNS_MARKER_TYPE_BREAK);
15760            let reset_marker = marker_packet(TNS_MARKER_TYPE_RESET);
15761            if bytes == break_marker.as_slice() {
15762                self.break_writes += 1;
15763            } else if bytes == reset_marker.as_slice() {
15764                self.reset_writes += 1;
15765            }
15766        }
15767    }
15768
15769    #[derive(Debug)]
15770    enum ReadAction {
15771        Bytes {
15772            bytes: Vec<u8>,
15773            offset: usize,
15774            max_chunk: Option<usize>,
15775            cancel_current_on_completion: bool,
15776        },
15777        Pending,
15778        PendingUntil(ScriptedGate),
15779        Eof,
15780        Error(&'static str),
15781        ErrorKind(std::io::ErrorKind, &'static str),
15782        AdvanceTime(Duration),
15783    }
15784
15785    impl ReadAction {
15786        fn bytes(bytes: Vec<u8>, max_chunk: Option<usize>) -> Self {
15787            Self::Bytes {
15788                bytes,
15789                offset: 0,
15790                max_chunk,
15791                cancel_current_on_completion: false,
15792            }
15793        }
15794
15795        fn bytes_then_cancel_current(bytes: Vec<u8>, max_chunk: Option<usize>) -> Self {
15796            Self::Bytes {
15797                bytes,
15798                offset: 0,
15799                max_chunk,
15800                cancel_current_on_completion: true,
15801            }
15802        }
15803    }
15804
15805    #[derive(Debug)]
15806    enum WriteAction {
15807        Expect {
15808            bytes: Vec<u8>,
15809            offset: usize,
15810            max_chunk: Option<usize>,
15811        },
15812        Pending,
15813        Eof,
15814        Error(&'static str),
15815        AdvanceTime(Duration),
15816    }
15817
15818    impl WriteAction {
15819        fn expect_bytes(bytes: Vec<u8>, max_chunk: Option<usize>) -> Self {
15820            Self::Expect {
15821                bytes,
15822                offset: 0,
15823                max_chunk,
15824            }
15825        }
15826    }
15827
15828    fn test_cx() -> Result<Cx> {
15829        Cx::current().ok_or_else(|| Error::Runtime("missing ambient Cx in test runtime".into()))
15830    }
15831
15832    #[test]
15833    fn split_connect_descriptor_uses_legacy16_data_framing_before_accept() -> Result<()> {
15834        // OCI Autonomous DB descriptors exceed the listener's 230-byte inline
15835        // CONNECT-data allowance. The descriptor follows CONNECT as a DATA
15836        // packet, but the listener is still using the pre-ACCEPT Legacy16
15837        // header at that point.
15838        let connect_data = format!(
15839            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=adb.example.oraclecloud.com)(PORT=1522))\
15840             (CONNECT_DATA=(SERVICE_NAME={})))",
15841            "x".repeat(oracledb_protocol::thin::TNS_MAX_CONNECT_DATA)
15842        );
15843        assert!(
15844            !connect_data_fits_inline(&connect_data),
15845            "the descriptor must take the split-CONNECT path"
15846        );
15847
15848        let expected = encode_packet(
15849            TNS_PACKET_TYPE_DATA,
15850            0,
15851            Some(0),
15852            connect_data.as_bytes(),
15853            PacketLengthWidth::Legacy16,
15854        )?;
15855        assert_eq!(
15856            &expected[..2],
15857            &u16::try_from(expected.len())
15858                .expect("test packet fits a Legacy16 header")
15859                .to_be_bytes(),
15860            "the first two bytes carry the Legacy16 packet length"
15861        );
15862        assert_eq!(
15863            &expected[2..4],
15864            &[0, 0],
15865            "Legacy16 reserves header bytes 2..4; Large32 would put its length there"
15866        );
15867        assert_eq!(expected[4], TNS_PACKET_TYPE_DATA);
15868        assert_eq!(
15869            &expected[6..8],
15870            &[0, 0],
15871            "split CONNECT keeps DATA flags at zero"
15872        );
15873        let large32 = encode_packet(
15874            TNS_PACKET_TYPE_DATA,
15875            0,
15876            Some(0),
15877            connect_data.as_bytes(),
15878            PacketLengthWidth::Large32,
15879        )?;
15880        assert_ne!(
15881            &expected[..4],
15882            &large32[..4],
15883            "the split-CONNECT header must not be Large32"
15884        );
15885
15886        let state = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
15887            Vec::new(),
15888            vec![WriteAction::expect_bytes(expected, None)],
15889            ScriptedClock::default(),
15890        )));
15891        let core = ConnectionCore::<ScriptedTransport>::from_halves(
15892            ScriptedRead::from_state(Arc::clone(&state)),
15893            ScriptedWrite::from_state(Arc::clone(&state)),
15894            "split_connect_legacy16_write",
15895        );
15896        let runtime = build_io_runtime()?;
15897        runtime.block_on(async {
15898            let cx = test_cx()?;
15899            core.send_connect_data_packet(&cx, connect_data.as_bytes(), 8192)
15900                .await
15901        })?;
15902        assert!(
15903            state
15904                .lock()
15905                .map_err(|_| Error::Runtime("scripted transport state lock poisoned".into()))?
15906                .is_consumed(),
15907            "the pre-ACCEPT split descriptor must be written as the exact Legacy16 DATA packet"
15908        );
15909        Ok(())
15910    }
15911
15912    #[test]
15913    fn connection_core_routes_connect_execute_fetch_over_scripted_transport() -> Result<()> {
15914        const EXECUTE_BODY: &[u8] = b"scripted execute payload";
15915        const FETCH_BODY: &[u8] = b"scripted fetch payload";
15916        const EXECUTE_RESPONSE: &[u8] = b"scripted execute response";
15917        const FETCH_RESPONSE: &[u8] = b"scripted fetch response";
15918
15919        let connect_packet = encode_packet(
15920            TNS_PACKET_TYPE_CONNECT,
15921            0,
15922            None,
15923            b"SCRIPTED-CONNECT",
15924            PacketLengthWidth::Legacy16,
15925        )?;
15926        let accept_packet = encode_packet(
15927            TNS_PACKET_TYPE_ACCEPT,
15928            0,
15929            None,
15930            b"SCRIPTED-ACCEPT",
15931            PacketLengthWidth::Legacy16,
15932        )?;
15933        let execute_packet = encode_packet(
15934            TNS_PACKET_TYPE_DATA,
15935            0,
15936            Some(0),
15937            EXECUTE_BODY,
15938            PacketLengthWidth::Large32,
15939        )?;
15940        let fetch_packet = encode_packet(
15941            TNS_PACKET_TYPE_DATA,
15942            0,
15943            Some(0),
15944            FETCH_BODY,
15945            PacketLengthWidth::Large32,
15946        )?;
15947
15948        let script = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
15949            vec![
15950                ReadAction::bytes(accept_packet, None),
15951                ReadAction::bytes(data_packet(EXECUTE_RESPONSE, true), None),
15952                ReadAction::bytes(data_packet(FETCH_RESPONSE, true), None),
15953            ],
15954            vec![
15955                WriteAction::expect_bytes(connect_packet.clone(), None),
15956                WriteAction::expect_bytes(execute_packet, None),
15957                WriteAction::expect_bytes(fetch_packet, None),
15958            ],
15959            ScriptedClock::default(),
15960        )));
15961        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
15962            ScriptedRead::from_state(Arc::clone(&script)),
15963            ScriptedWrite::from_state(Arc::clone(&script)),
15964            "scripted_core_write",
15965        );
15966
15967        let runtime = build_io_runtime()?;
15968        runtime.block_on(async {
15969            let cx = test_cx()?;
15970            core.write_all(&cx, &connect_packet).await?;
15971            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
15972            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
15973            assert_eq!(accept.payload, b"SCRIPTED-ACCEPT");
15974
15975            core.send_data_packet(&cx, EXECUTE_BODY, 8192).await?;
15976            let execute_response = core.read_data_response(&cx).await?;
15977            assert_eq!(execute_response, EXECUTE_RESPONSE);
15978
15979            core.send_data_packet(&cx, FETCH_BODY, 8192).await?;
15980            let fetch_response = core.read_data_response(&cx).await?;
15981            assert_eq!(fetch_response, FETCH_RESPONSE);
15982            Ok::<_, Error>(())
15983        })?;
15984
15985        let state = script
15986            .lock()
15987            .map_err(|_| Error::Runtime("scripted I/O state lock poisoned".into()))?;
15988        assert!(
15989            state.is_consumed(),
15990            "scripted core must perform exactly the expected connect/execute/fetch I/O"
15991        );
15992        Ok(())
15993    }
15994
15995    #[test]
15996    fn classic_token_auth_negotiates_then_sends_phase_two_over_scripted_transport() -> Result<()> {
15997        const USER: &str = "iam_user";
15998        const TOKEN: &str = "not-a-real-iam-token";
15999        const DRIVER_NAME: &str = "rust-oracledb";
16000        const CONNECT_STRING: &str = "adb.example.oraclecloud.com/service";
16001
16002        let protocol_payload = build_protocol_negotiation_payload()?;
16003        let data_types_payload = build_data_types_payload()?;
16004        let token_payload = build_auth_phase_two_token_payload_with_pop_and_proxy(
16005            USER,
16006            TOKEN,
16007            DRIVER_NAME,
16008            PYTHON_ORACLEDB_COMPAT_VERSION_NUM,
16009            CONNECT_STRING,
16010            None,
16011            None,
16012            None,
16013        )?;
16014        let expected_writes = [protocol_payload, data_types_payload, token_payload]
16015            .into_iter()
16016            .map(|payload| {
16017                encode_packet(
16018                    TNS_PACKET_TYPE_DATA,
16019                    0,
16020                    Some(0),
16021                    &payload,
16022                    PacketLengthWidth::Large32,
16023                )
16024                .map_err(Error::from)
16025            })
16026            .collect::<Result<Vec<_>>>()?;
16027
16028        // A classic server completes each connect-phase response with STATUS,
16029        // not the 23ai END_OF_RESPONSE data flag. This drives the exact
16030        // classic reader selected for an ACCEPT without fast-auth.
16031        let classic_status =
16032            data_packet(&[oracledb_protocol::thin::TNS_MSG_TYPE_STATUS, 0, 0], false);
16033        let script = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
16034            vec![
16035                ReadAction::bytes(classic_status.clone(), None),
16036                ReadAction::bytes(classic_status.clone(), None),
16037                ReadAction::bytes(classic_status, None),
16038            ],
16039            expected_writes
16040                .into_iter()
16041                .map(|packet| WriteAction::expect_bytes(packet, None))
16042                .collect(),
16043            ScriptedClock::default(),
16044        )));
16045        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
16046            ScriptedRead::from_state(Arc::clone(&script)),
16047            ScriptedWrite::from_state(Arc::clone(&script)),
16048            "classic_token_auth_write",
16049        );
16050
16051        let runtime = build_io_runtime()?;
16052        runtime.block_on(async {
16053            let cx = test_cx()?;
16054            let (auth, capabilities) = core
16055                .authenticate_classic_token(
16056                    &cx,
16057                    TokenAuthentication {
16058                        user: USER,
16059                        token: TOKEN,
16060                        driver_name: DRIVER_NAME,
16061                        version_num: PYTHON_ORACLEDB_COMPAT_VERSION_NUM,
16062                        connect_string: CONNECT_STRING,
16063                        edition: None,
16064                        pop: None,
16065                        proxy_user: None,
16066                    },
16067                    8192,
16068                )
16069                .await?;
16070            assert!(auth.session_data.is_empty());
16071            assert_eq!(capabilities, ClientCapabilities::default());
16072            Ok::<_, Error>(())
16073        })?;
16074
16075        assert!(
16076            script
16077                .lock()
16078                .map_err(|_| Error::Runtime("scripted I/O state lock poisoned".into()))?
16079                .is_consumed(),
16080            "classic token auth must send protocol negotiation, data types, then AUTH_TOKEN phase two"
16081        );
16082        Ok(())
16083    }
16084
16085    #[test]
16086    fn scripted_transport_replays_short_pending_and_virtual_time() -> Result<()> {
16087        const EXECUTE_BODY: &[u8] = b"fault-matrix execute payload";
16088        const EXECUTE_RESPONSE: &[u8] = b"fault-matrix execute response";
16089
16090        let connect_packet = encode_packet(
16091            TNS_PACKET_TYPE_CONNECT,
16092            0,
16093            None,
16094            b"FAULT-MATRIX-CONNECT",
16095            PacketLengthWidth::Legacy16,
16096        )?;
16097        let accept_packet = encode_packet(
16098            TNS_PACKET_TYPE_ACCEPT,
16099            0,
16100            None,
16101            b"FAULT-MATRIX-ACCEPT",
16102            PacketLengthWidth::Legacy16,
16103        )?;
16104        let execute_packet = encode_packet(
16105            TNS_PACKET_TYPE_DATA,
16106            0,
16107            Some(0),
16108            EXECUTE_BODY,
16109            PacketLengthWidth::Large32,
16110        )?;
16111        let execute_response_packet = data_packet(EXECUTE_RESPONSE, true);
16112
16113        let clock = ScriptedClock::default();
16114        let script = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
16115            vec![
16116                ReadAction::Pending,
16117                ReadAction::AdvanceTime(Duration::from_millis(7)),
16118                ReadAction::bytes(accept_packet, Some(3)),
16119                ReadAction::Pending,
16120                ReadAction::AdvanceTime(Duration::from_millis(11)),
16121                ReadAction::bytes(execute_response_packet, Some(2)),
16122            ],
16123            vec![
16124                WriteAction::Pending,
16125                WriteAction::AdvanceTime(Duration::from_millis(5)),
16126                WriteAction::expect_bytes(connect_packet.clone(), Some(2)),
16127                WriteAction::Pending,
16128                WriteAction::AdvanceTime(Duration::from_millis(13)),
16129                WriteAction::expect_bytes(execute_packet, Some(3)),
16130            ],
16131            clock.clone(),
16132        )));
16133        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
16134            ScriptedRead::from_state(Arc::clone(&script)),
16135            ScriptedWrite::from_state(Arc::clone(&script)),
16136            "scripted_fault_matrix_write",
16137        );
16138
16139        let runtime = build_io_runtime()?;
16140        runtime.block_on(async {
16141            let cx = test_cx()?;
16142            core.write_all(&cx, &connect_packet).await?;
16143            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
16144            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
16145            assert_eq!(accept.payload, b"FAULT-MATRIX-ACCEPT");
16146
16147            core.send_data_packet(&cx, EXECUTE_BODY, 8192).await?;
16148            let execute_response = core.read_data_response(&cx).await?;
16149            assert_eq!(execute_response, EXECUTE_RESPONSE);
16150            Ok::<_, Error>(())
16151        })?;
16152
16153        assert_eq!(
16154            clock.elapsed(),
16155            Duration::from_millis(36),
16156            "virtual time advances are deterministic and do not require wall-clock sleeps"
16157        );
16158        let state = script
16159            .lock()
16160            .map_err(|_| Error::Runtime("scripted I/O state lock poisoned".into()))?;
16161        assert!(
16162            state.is_consumed(),
16163            "scripted fault matrix must consume every read/write step"
16164        );
16165        Ok(())
16166    }
16167
16168    const DPOR_SATURATION_WINDOW: usize = 1;
16169    const DPOR_WIRE_SEED: u64 = 0xE3_E4_D0_00;
16170    const DPOR_WIRE_MAX_ITERS: usize = 96;
16171    const DPOR_WIRE_TIMEOUT_MS: u32 = 1;
16172    fn dpor_wire_recovery_timeout() -> Duration {
16173        Duration::from_secs(1)
16174    }
16175
16176    #[derive(Clone, Copy, Debug)]
16177    enum DporWireMode {
16178        UserCancel,
16179        Timeout,
16180    }
16181
16182    fn dpor_wire_seed(mode: DporWireMode) -> u64 {
16183        DPOR_WIRE_SEED
16184            + match mode {
16185                DporWireMode::UserCancel => 0,
16186                DporWireMode::Timeout => 1,
16187            }
16188    }
16189
16190    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
16191    enum DporWireResultKind {
16192        Cancelled,
16193        CallTimeout,
16194    }
16195
16196    #[derive(Debug)]
16197    struct DporWireObservation {
16198        result: DporWireResultKind,
16199        phase: SessionRecoveryPhase,
16200        break_writes: usize,
16201        reset_writes: usize,
16202        script_consumed: bool,
16203    }
16204
16205    async fn dpor_read_until_cancel_gate(
16206        core: &mut ConnectionCore<ScriptedTransport>,
16207        cx: &Cx,
16208        cancel_gate: &ScriptedGate,
16209    ) -> Result<Vec<u8>> {
16210        let recovery = Arc::clone(&core.recovery);
16211        let read = async {
16212            let mut guard = CancelDrainGuard::arm(recovery)?;
16213            let response = core.read_data_response(cx).await;
16214            if response.is_ok() {
16215                guard.disarm();
16216            }
16217            response
16218        };
16219        let cancel = poll_fn(|task_cx| {
16220            if cancel_gate.is_open() {
16221                Poll::Ready(())
16222            } else {
16223                cancel_gate.register(task_cx.waker());
16224                Poll::Pending
16225            }
16226        });
16227        let mut read = pin!(read);
16228        let mut cancel = pin!(cancel);
16229
16230        poll_fn(|task_cx| {
16231            if cancel_gate.is_open() {
16232                return Poll::Ready(Err(Error::Cancelled));
16233            }
16234            if let Poll::Ready(result) = read.as_mut().poll(task_cx) {
16235                return Poll::Ready(result);
16236            }
16237            if let Poll::Ready(()) = cancel.as_mut().poll(task_cx) {
16238                return Poll::Ready(Err(Error::Cancelled));
16239            }
16240            Poll::Pending
16241        })
16242        .await
16243    }
16244
16245    async fn dpor_read_until_timeout_gate(
16246        core: &mut ConnectionCore<ScriptedTransport>,
16247        cx: &Cx,
16248        timeout_gate: &ScriptedGate,
16249    ) -> Result<Vec<u8>> {
16250        let recovery = Arc::clone(&core.recovery);
16251        let read = async {
16252            let mut guard = CancelDrainGuard::arm(recovery)?;
16253            let response = core.read_data_response(cx).await;
16254            if response.is_ok() {
16255                guard.disarm();
16256            }
16257            response
16258        };
16259        let timeout = poll_fn(|task_cx| {
16260            if timeout_gate.is_open() {
16261                Poll::Ready(())
16262            } else {
16263                timeout_gate.register(task_cx.waker());
16264                Poll::Pending
16265            }
16266        });
16267        let mut read = pin!(read);
16268        let mut timeout = pin!(timeout);
16269
16270        poll_fn(|task_cx| {
16271            if timeout_gate.is_open() {
16272                return Poll::Ready(Err(Error::CallTimeout(DPOR_WIRE_TIMEOUT_MS)));
16273            }
16274            if let Poll::Ready(result) = read.as_mut().poll(task_cx) {
16275                return Poll::Ready(result);
16276            }
16277            if let Poll::Ready(()) = timeout.as_mut().poll(task_cx) {
16278                return Poll::Ready(Err(Error::CallTimeout(DPOR_WIRE_TIMEOUT_MS)));
16279            }
16280            Poll::Pending
16281        })
16282        .await
16283    }
16284
16285    fn dpor_wire_script(
16286        gate: ScriptedGate,
16287        execute_packet: Vec<u8>,
16288    ) -> Arc<std::sync::Mutex<ScriptedIoState>> {
16289        const INFLIGHT_BODY: &[u8] = b"dpor in-flight response";
16290        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
16291
16292        Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
16293            vec![
16294                ReadAction::PendingUntil(gate),
16295                ReadAction::bytes(data_packet(INFLIGHT_BODY, true), Some(3)),
16296                ReadAction::Pending,
16297                ReadAction::bytes(marker_packet(TNS_MARKER_TYPE_BREAK), Some(2)),
16298                ReadAction::Pending,
16299                ReadAction::bytes(marker_packet(TNS_MARKER_TYPE_RESET), Some(2)),
16300                ReadAction::Pending,
16301                ReadAction::bytes(data_packet(ERROR_BODY, true), Some(2)),
16302            ],
16303            vec![
16304                WriteAction::Pending,
16305                WriteAction::expect_bytes(execute_packet, Some(3)),
16306                WriteAction::Pending,
16307                WriteAction::expect_bytes(marker_packet(TNS_MARKER_TYPE_BREAK), Some(2)),
16308                WriteAction::Pending,
16309                WriteAction::expect_bytes(marker_packet(TNS_MARKER_TYPE_RESET), Some(2)),
16310            ],
16311            ScriptedClock::default(),
16312        )))
16313    }
16314
16315    async fn run_dpor_wire_operation(
16316        mode: DporWireMode,
16317        gate: ScriptedGate,
16318        script: Arc<std::sync::Mutex<ScriptedIoState>>,
16319        execute_body: &'static [u8],
16320    ) -> Result<DporWireObservation> {
16321        let cx = Cx::current().expect("LabRuntime task should install an ambient Cx");
16322        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
16323            ScriptedRead::from_state(Arc::clone(&script)),
16324            ScriptedWrite::from_state(Arc::clone(&script)),
16325            "dpor_wire_core_write",
16326        );
16327        core.send_data_packet(&cx, execute_body, 8192).await?;
16328
16329        let result = match mode {
16330            DporWireMode::UserCancel => dpor_read_until_cancel_gate(&mut core, &cx, &gate).await,
16331            DporWireMode::Timeout => dpor_read_until_timeout_gate(&mut core, &cx, &gate).await,
16332        };
16333        let result = match result {
16334            Ok(payload) => {
16335                return Err(Error::Runtime(format!(
16336                    "DPOR wire race unexpectedly completed normally with payload {payload:?}"
16337                )));
16338            }
16339            Err(Error::Cancelled) => {
16340                core.recovery.begin_drain_after_break()?;
16341                core.cancel_and_drain_wire(dpor_wire_recovery_timeout())?;
16342                core.recovery.finish_drain_ready();
16343                DporWireResultKind::Cancelled
16344            }
16345            Err(Error::CallTimeout(_)) => {
16346                core.recovery.begin_drain_after_break()?;
16347                core.break_and_drain_wire(dpor_wire_recovery_timeout())?;
16348                core.recovery.finish_drain_ready();
16349                DporWireResultKind::CallTimeout
16350            }
16351            Err(err) => return Err(err),
16352        };
16353
16354        let state = script
16355            .lock()
16356            .map_err(|_| Error::Runtime("scripted DPOR wire state lock poisoned".into()))?;
16357        Ok(DporWireObservation {
16358            result,
16359            phase: core.recovery.phase(),
16360            break_writes: state.break_writes,
16361            reset_writes: state.reset_writes,
16362            script_consumed: state.is_consumed(),
16363        })
16364    }
16365
16366    fn explore_dpor_wire_mode(mode: DporWireMode) -> asupersync::lab::ExplorationReport {
16367        const EXECUTE_BODY: &[u8] = b"dpor execute payload";
16368        let execute_packet = encode_packet(
16369            TNS_PACKET_TYPE_DATA,
16370            0,
16371            Some(0),
16372            EXECUTE_BODY,
16373            PacketLengthWidth::Large32,
16374        )
16375        .expect("encode DPOR execute packet");
16376
16377        let mut explorer = DporExplorer::new(
16378            ExplorerConfig::new(dpor_wire_seed(mode), DPOR_WIRE_MAX_ITERS).max_steps(100_000),
16379        );
16380        explorer.explore(|runtime: &mut LabRuntime| {
16381            // Full ConnectionCore execution inside LabRuntime does not quiesce
16382            // because the recovery path intentionally leaves the lab executor
16383            // and drains on a blocking recovery thread. Keep DPOR on the finite
16384            // operation-vs-interrupt ordering, then run the actual scripted
16385            // ConnectionCore recovery path below for every explored schedule.
16386            let order = Arc::new(std::sync::Mutex::new(Vec::new()));
16387            let root = runtime.state.create_root_region(Budget::INFINITE);
16388
16389            let operation_order = Arc::clone(&order);
16390            let (operation, _operation_handle) = runtime
16391                .state
16392                .create_task(root, Budget::INFINITE, async move {
16393                    operation_order
16394                        .lock()
16395                        .expect("record DPOR wire operation ordering")
16396                        .push("operation");
16397                })
16398                .expect("create DPOR wire operation task");
16399            runtime.scheduler.lock().schedule(operation, 0);
16400
16401            let interrupt_order = Arc::clone(&order);
16402            let (interrupt, _interrupt_handle) = runtime
16403                .state
16404                .create_task(root, Budget::INFINITE, async move {
16405                    interrupt_order
16406                        .lock()
16407                        .expect("record DPOR wire interrupt ordering")
16408                        .push("interrupt");
16409                })
16410                .expect("create DPOR wire interrupt task");
16411            runtime.scheduler.lock().schedule(interrupt, 0);
16412            runtime.run_until_quiescent();
16413            assert!(
16414                runtime.is_quiescent(),
16415                "DPOR wire ordering model did not quiesce"
16416            );
16417
16418            let observed_order = order.lock().expect("read DPOR wire ordering").clone();
16419            assert_eq!(
16420                observed_order.len(),
16421                2,
16422                "DPOR wire ordering should include operation and interrupt"
16423            );
16424
16425            let replay_gate = ScriptedGate::default();
16426            replay_gate.open();
16427            let script = dpor_wire_script(replay_gate.clone(), execute_packet.clone());
16428            let io_runtime = build_io_runtime().expect("asupersync runtime for DPOR wire replay");
16429            let observed = io_runtime
16430                .block_on(run_dpor_wire_operation(
16431                    mode,
16432                    replay_gate,
16433                    script,
16434                    EXECUTE_BODY,
16435                ))
16436                .expect("DPOR wire operation should not fail");
16437            let expected = match mode {
16438                DporWireMode::UserCancel => DporWireResultKind::Cancelled,
16439                DporWireMode::Timeout => DporWireResultKind::CallTimeout,
16440            };
16441            assert_eq!(
16442                observed.result, expected,
16443                "delivered cancel/timeout mapped to the wrong public error"
16444            );
16445            assert_eq!(
16446                observed.phase,
16447                SessionRecoveryPhase::Ready,
16448                "wire recovery must finish at a clean Ready boundary"
16449            );
16450            assert_eq!(observed.break_writes, 1, "exactly one BREAK is required");
16451            assert_eq!(observed.reset_writes, 1, "exactly one RESET is required");
16452            assert!(
16453                observed.script_consumed,
16454                "wire recovery must consume the whole scripted break response"
16455            );
16456        })
16457    }
16458
16459    #[test]
16460    fn dpor_wire_cancel_and_timeout_recovery_saturates() {
16461        for mode in [DporWireMode::UserCancel, DporWireMode::Timeout] {
16462            let report = explore_dpor_wire_mode(mode);
16463            eprintln!(
16464                "[dpor-wire] mode={mode:?} seed={} max_iters={} runs={} classes={} saturated={}",
16465                dpor_wire_seed(mode),
16466                DPOR_WIRE_MAX_ITERS,
16467                report.total_runs,
16468                report.unique_classes,
16469                report.coverage.is_saturated(DPOR_SATURATION_WINDOW)
16470            );
16471            assert!(
16472                !report.has_violations(),
16473                "DPOR wire {mode:?} found violations at seeds {:?}",
16474                report.violation_seeds()
16475            );
16476            assert!(
16477                report.total_runs == DPOR_WIRE_MAX_ITERS,
16478                "DPOR wire fallback seed space did not complete for {mode:?}: runs={}, classes={}, new={}",
16479                report.total_runs,
16480                report.unique_classes,
16481                report.coverage.new_class_discoveries
16482            );
16483        }
16484    }
16485
16486    #[test]
16487    fn flush_out_binds_observes_cancel_before_follow_up_round_trip() -> Result<()> {
16488        let first_response = data_packet(&[TNS_MSG_TYPE_FLUSH_OUT_BINDS], true);
16489        let unread_response = data_packet(b"must-not-read-after-cancel", true);
16490        let script = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
16491            vec![
16492                ReadAction::bytes_then_cancel_current(first_response, None),
16493                ReadAction::bytes(unread_response, None),
16494            ],
16495            Vec::new(),
16496            ScriptedClock::default(),
16497        )));
16498
16499        let runtime = build_io_runtime()?;
16500        let err = runtime.block_on(async {
16501            let cx = test_cx()?;
16502            let mut read = ScriptedRead::from_state(Arc::clone(&script));
16503            let write = Arc::new(AsyncMutex::with_name(
16504                "flush_cancel_checkpoint_test_write",
16505                ScriptedWrite::from_state(Arc::clone(&script)),
16506            ));
16507            let err = read_data_response_flushing_out_binds(&mut read, &cx, &write, 8192)
16508                .await
16509                .expect_err("cancel checkpoint must stop before FLUSH_OUT_BINDS follow-up");
16510            Ok::<_, Error>(err)
16511        })?;
16512
16513        // W1-T6.2: a cancel checkpoint surfaces the DISTINCT Error::Cancelled
16514        // (ORA-01013), never a generic Error::Runtime(display_string).
16515        assert!(
16516            matches!(&err, Error::Cancelled),
16517            "flush continuation should stop on the cancellation checkpoint with a distinct cancel error, got {err:?}"
16518        );
16519        assert_eq!(err.kind(), ErrorKind::Cancel);
16520        let state = script
16521            .lock()
16522            .map_err(|_| Error::Runtime("scripted I/O state lock poisoned".into()))?;
16523        assert_eq!(
16524            state.read.len(),
16525            1,
16526            "the next response packet must not be read after cancellation"
16527        );
16528        assert!(
16529            state.write.is_empty(),
16530            "the FLUSH_OUT_BINDS follow-up must not be sent after cancellation"
16531        );
16532        Ok(())
16533    }
16534
16535    #[test]
16536    fn pending_cx_cancel_is_observed_before_fetch_continuation_write() -> Result<()> {
16537        let listener = TcpListener::bind("127.0.0.1:0")?;
16538        let addr = listener.local_addr()?;
16539        let server = thread::spawn(move || -> std::io::Result<Option<u8>> {
16540            let (mut socket, _) = listener.accept()?;
16541            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
16542            let mut first_byte = [0u8; 1];
16543            match socket.read(&mut first_byte) {
16544                Ok(0) => Ok(None),
16545                Ok(_) => Ok(Some(first_byte[0])),
16546                Err(err)
16547                    if matches!(
16548                        err.kind(),
16549                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
16550                    ) =>
16551                {
16552                    Ok(None)
16553                }
16554                Err(err) => Err(err),
16555            }
16556        });
16557
16558        let runtime = build_io_runtime()?;
16559        runtime.block_on(async {
16560            let cx = test_cx()?;
16561            let stream = TcpStream::connect(addr).await?;
16562            let (read, write) = transport::plain_split(stream);
16563            let mut connection = loopback_connection(read, write);
16564            let before_seq = connection.ttc_seq_num;
16565
16566            cx.cancel_fast(asupersync::CancelKind::User);
16567            let err = connection
16568                .fetch_rows_request(&cx, 42, 10)
16569                .await
16570                .expect_err("fetch continuation must checkpoint before writing");
16571            // W1-T6.2: an explicit user cancel surfaces the distinct
16572            // Error::Cancelled, not a generic Error::Runtime(display_string).
16573            assert!(
16574                matches!(&err, Error::Cancelled),
16575                "fetch continuation should stop on the cancellation checkpoint with a distinct cancel error, got {err:?}"
16576            );
16577            assert_eq!(err.kind(), ErrorKind::Cancel);
16578            assert_eq!(
16579                connection.ttc_seq_num, before_seq,
16580                "checkpoint must run before allocating the next TTC sequence number"
16581            );
16582            assert_eq!(
16583                connection.core.recovery.phase(),
16584                SessionRecoveryPhase::Ready,
16585                "checkpoint failure must not arm the recovery state machine"
16586            );
16587            Ok::<_, Error>(())
16588        })?;
16589
16590        let received = server.join().expect("server thread joins")?;
16591        assert_eq!(
16592            received, None,
16593            "cancelled fetch continuation must not write a FETCH packet"
16594        );
16595        Ok(())
16596    }
16597
16598    #[test]
16599    fn fetch_rows_ref_drop_mid_read_arms_break_recovery() -> Result<()> {
16600        let listener = TcpListener::bind("127.0.0.1:0")?;
16601        let addr = listener.local_addr()?;
16602        let (packet_tx, packet_rx) = std::sync::mpsc::channel();
16603        let (release_tx, release_rx) = std::sync::mpsc::channel();
16604        let server = thread::spawn(move || -> std::io::Result<()> {
16605            let (mut socket, _) = listener.accept()?;
16606            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
16607            let mut buf = [0u8; 1024];
16608            let read = socket.read(&mut buf)?;
16609            packet_tx
16610                .send(read)
16611                .expect("test packet notification receiver is alive");
16612            let _ = release_rx.recv_timeout(Duration::from_secs(2));
16613            Ok(())
16614        });
16615
16616        let runtime = build_io_runtime()?;
16617        runtime.block_on(async {
16618            let cx = test_cx()?;
16619            let stream = TcpStream::connect(addr).await?;
16620            let (read, write) = transport::plain_split(stream);
16621            let mut connection = loopback_connection(read, write);
16622
16623            {
16624                let mut fetch = pin!(connection.fetch_rows_ref(&cx, 42, 10, None));
16625                let first_poll = poll_fn(|task_cx| Poll::Ready(fetch.as_mut().poll(task_cx))).await;
16626                assert!(
16627                    matches!(first_poll, Poll::Pending),
16628                    "fetch_rows_ref must wait for the server response"
16629                );
16630                let packet_len = packet_rx
16631                    .recv_timeout(Duration::from_secs(2))
16632                    .expect("fetch request should be sent before the response read waits");
16633                assert!(packet_len > 0, "fetch request packet must not be empty");
16634
16635                let second_poll =
16636                    poll_fn(|task_cx| Poll::Ready(fetch.as_mut().poll(task_cx))).await;
16637                assert!(
16638                    matches!(second_poll, Poll::Pending),
16639                    "fetch_rows_ref response read should still be pending"
16640                );
16641            }
16642
16643            assert_eq!(
16644                connection.core.recovery.phase(),
16645                SessionRecoveryPhase::BreakSent,
16646                "dropping fetch_rows_ref mid-read must arm break/drain recovery"
16647            );
16648            release_tx
16649                .send(())
16650                .expect("test server release receiver is alive");
16651            Ok::<_, Error>(())
16652        })?;
16653
16654        server
16655            .join()
16656            .expect("server thread joins")
16657            .map_err(Error::Io)?;
16658        Ok(())
16659    }
16660
16661    #[test]
16662    fn in_flight_context_cancel_does_not_leak_interrupted_io() -> Result<()> {
16663        let listener = TcpListener::bind("127.0.0.1:0")?;
16664        let addr = listener.local_addr()?;
16665        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
16666        let (release_tx, release_rx) = std::sync::mpsc::channel();
16667        let (cx_tx, cx_rx) = std::sync::mpsc::channel::<Cx>();
16668        let server = thread::spawn(move || -> std::io::Result<()> {
16669            let (mut socket, _) = listener.accept()?;
16670            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
16671            assert_eq!(
16672                read_one_wire_packet(&mut socket),
16673                TNS_PACKET_TYPE_DATA,
16674                "COMMIT request must reach the server before cancellation"
16675            );
16676            request_seen_tx
16677                .send(())
16678                .expect("client cancellation task is alive");
16679            let _ = release_rx.recv_timeout(Duration::from_secs(2));
16680            Ok(())
16681        });
16682
16683        let runtime = build_io_runtime()?;
16684        let canceller = thread::spawn(move || -> Result<()> {
16685            let cancel_cx = cx_rx
16686                .recv_timeout(Duration::from_secs(2))
16687                .map_err(|_| Error::Runtime("COMMIT task never exposed its Cx".into()))?;
16688            request_seen_rx
16689                .recv_timeout(Duration::from_secs(2))
16690                .map_err(|_| Error::Runtime("server never observed COMMIT request".into()))?;
16691            cancel_cx.cancel_fast(CancelKind::User);
16692            Ok(())
16693        });
16694        // A spawned task is essential: the Asupersync scheduler installs its
16695        // cancellation waker for task Cx values, matching normal async-driver
16696        // use rather than `Runtime::block_on`'s top-level harness context.
16697        let task = runtime.handle().spawn(async move {
16698            let cx = test_cx()?;
16699            cx_tx
16700                .send(cx.clone())
16701                .map_err(|_| Error::Runtime("cancellation test coordinator exited".into()))?;
16702            let stream = TcpStream::connect(addr).await?;
16703            let (read, write) = transport::plain_split(stream);
16704            let mut connection = loopback_connection(read, write);
16705
16706            let err = connection
16707                .commit(&cx)
16708                .await
16709                .expect_err("the cancelled in-flight COMMIT must not complete");
16710            Ok::<_, Error>((err, connection.core.recovery.phase()))
16711        });
16712        let (err, phase) = runtime.block_on(task)?;
16713        canceller.join().expect("cancellation thread joins")?;
16714
16715        let _ = release_tx.send(());
16716        server
16717            .join()
16718            .expect("server thread joins")
16719            .map_err(Error::Io)?;
16720
16721        assert!(
16722            matches!(&err, Error::Cancelled),
16723            "a mid-read user cancellation must surface the typed Error::Cancelled, not {err:?}"
16724        );
16725        assert_eq!(err.kind(), ErrorKind::Cancel);
16726        assert_eq!(
16727            phase,
16728            SessionRecoveryPhase::BreakSent,
16729            "the cancelled in-flight response must be reclaimed before a later request"
16730        );
16731        Ok(())
16732    }
16733
16734    #[test]
16735    fn scroll_cursor_context_cancel_arms_recovery_and_is_typed() -> Result<()> {
16736        let listener = TcpListener::bind("127.0.0.1:0")?;
16737        let addr = listener.local_addr()?;
16738        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
16739        let (release_tx, release_rx) = std::sync::mpsc::channel();
16740        let (cx_tx, cx_rx) = std::sync::mpsc::channel::<Cx>();
16741        let server = thread::spawn(move || -> std::io::Result<()> {
16742            let (mut socket, _) = listener.accept()?;
16743            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
16744            assert_eq!(
16745                read_one_wire_packet(&mut socket),
16746                TNS_PACKET_TYPE_DATA,
16747                "SCROLL request must reach the server before cancellation"
16748            );
16749            request_seen_tx
16750                .send(())
16751                .expect("client cancellation task is alive");
16752            let _ = release_rx.recv_timeout(Duration::from_secs(2));
16753            Ok(())
16754        });
16755
16756        let runtime = build_io_runtime()?;
16757        let canceller = thread::spawn(move || -> Result<()> {
16758            let cancel_cx = cx_rx
16759                .recv_timeout(Duration::from_secs(2))
16760                .map_err(|_| Error::Runtime("SCROLL task never exposed its Cx".into()))?;
16761            request_seen_rx
16762                .recv_timeout(Duration::from_secs(2))
16763                .map_err(|_| Error::Runtime("server never observed SCROLL request".into()))?;
16764            cancel_cx.cancel_fast(CancelKind::User);
16765            Ok(())
16766        });
16767        let task = runtime.handle().spawn(async move {
16768            let cx = test_cx()?;
16769            cx_tx
16770                .send(cx.clone())
16771                .map_err(|_| Error::Runtime("cancellation test coordinator exited".into()))?;
16772            let stream = TcpStream::connect(addr).await?;
16773            let (read, write) = transport::plain_split(stream);
16774            let mut connection = loopback_connection(read, write);
16775
16776            let err = connection
16777                .scroll_cursor(&cx, "select value from scroll_cancel_fixture", 42, 1, 0, 0)
16778                .await
16779                .expect_err("the cancelled in-flight SCROLL must not complete");
16780            Ok::<_, Error>((err, connection.core.recovery.phase()))
16781        });
16782        let (err, phase) = runtime.block_on(task)?;
16783        canceller.join().expect("cancellation thread joins")?;
16784
16785        let _ = release_tx.send(());
16786        server
16787            .join()
16788            .expect("server thread joins")
16789            .map_err(Error::Io)?;
16790
16791        assert!(
16792            matches!(&err, Error::Cancelled),
16793            "a mid-read SCROLL cancellation must surface Error::Cancelled, not {err:?}"
16794        );
16795        assert_eq!(
16796            phase,
16797            SessionRecoveryPhase::BreakSent,
16798            "a cancelled SCROLL response must be reclaimed before a later request"
16799        );
16800        Ok(())
16801    }
16802
16803    #[test]
16804    fn dropped_cancellable_read_is_drained_before_commit_request() -> Result<()> {
16805        const STRANDED_BODY: &[u8] = b"stranded response";
16806        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
16807
16808        let commit_packet = encode_packet(
16809            TNS_PACKET_TYPE_DATA,
16810            0,
16811            Some(0),
16812            &build_function_payload_with_seq(
16813                TNS_FUNC_COMMIT,
16814                1,
16815                ClientCapabilities::default().ttc_field_version,
16816            ),
16817            PacketLengthWidth::Large32,
16818        )?;
16819        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
16820        let addr = listener.local_addr().expect("listener address");
16821        let server = thread::spawn(move || {
16822            let (mut socket, _) = listener.accept().expect("accept test client");
16823            socket
16824                .set_read_timeout(Some(Duration::from_secs(5)))
16825                .expect("set read timeout");
16826            use std::io::Write as _;
16827
16828            assert_eq!(
16829                read_marker_type(&mut socket),
16830                TNS_MARKER_TYPE_BREAK,
16831                "commit must send BREAK before its own request when recovery is pending"
16832            );
16833            socket
16834                .write_all(&data_packet(STRANDED_BODY, true))
16835                .expect("write stranded response");
16836            socket
16837                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
16838                .expect("write break-ack marker");
16839            assert_eq!(
16840                read_marker_type(&mut socket),
16841                TNS_MARKER_TYPE_RESET,
16842                "commit recovery drain must answer the server break marker with RESET"
16843            );
16844            socket
16845                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
16846                .expect("write reset-confirm marker");
16847            socket
16848                .write_all(&data_packet(TRAILING_CANCEL_ERROR, true))
16849                .expect("write trailing cancel error packet");
16850
16851            let mut header = [0u8; 8];
16852            socket
16853                .read_exact(&mut header)
16854                .expect("read fresh commit request header");
16855            let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
16856            let mut commit_request = header.to_vec();
16857            let mut body = vec![0u8; len - header.len()];
16858            socket
16859                .read_exact(&mut body)
16860                .expect("read fresh commit request body");
16861            commit_request.extend_from_slice(&body);
16862            assert_eq!(
16863                commit_request, commit_packet,
16864                "fresh COMMIT request must be written after BREAK/RESET drain"
16865            );
16866            socket
16867                .write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))
16868                .expect("write commit response");
16869        });
16870
16871        let runtime = build_io_runtime()?;
16872        runtime.block_on(async {
16873            let cx = test_cx()?;
16874            let stream = TcpStream::connect(addr).await?;
16875            let (read, write) = transport::plain_split(stream);
16876            let mut connection = loopback_connection(read, write);
16877            {
16878                let _guard = CancelDrainGuard::arm(Arc::clone(&connection.core.recovery))?;
16879            }
16880            assert_eq!(
16881                connection.core.recovery.phase(),
16882                SessionRecoveryPhase::BreakSent
16883            );
16884            connection.commit(&cx).await?;
16885            assert_eq!(
16886                connection.core.recovery.phase(),
16887                SessionRecoveryPhase::Ready
16888            );
16889            Ok::<_, Error>(())
16890        })?;
16891
16892        server.join().expect("server thread joins");
16893        Ok(())
16894    }
16895
16896    fn assert_borrowed_stream_cursor_retired(
16897        connection: &Connection,
16898        cursor_id: u32,
16899        expected_phase: SessionRecoveryPhase,
16900    ) {
16901        assert_eq!(connection.core.recovery.phase(), expected_phase);
16902        assert!(!connection.in_use_cursors.contains(&cursor_id));
16903        assert!(!connection.copied_cursors.contains(&cursor_id));
16904        assert!(
16905            connection
16906                .statement_cache
16907                .iter()
16908                .all(|entry| entry.cursor_id != cursor_id),
16909            "failed borrowed stream must evict its cached cursor"
16910        );
16911        assert!(!connection.cursor_columns.contains_key(&cursor_id));
16912        assert!(!connection.lob_prefetch_cursors.contains(&cursor_id));
16913        assert_eq!(
16914            connection
16915                .cursors_to_close
16916                .iter()
16917                .filter(|queued| **queued == cursor_id)
16918                .count(),
16919            1,
16920            "failed borrowed stream must queue exactly one cursor close"
16921        );
16922    }
16923
16924    fn expected_next_close_piggyback(connection: &Connection, cursor_id: u32) -> Vec<u8> {
16925        let mut seq_num = connection.ttc_seq_num;
16926        let close_seq = next_ttc_sequence(&mut seq_num);
16927        oracledb_protocol::thin::build_close_cursors_piggyback(
16928            &[cursor_id],
16929            close_seq,
16930            connection.capabilities.ttc_field_version,
16931        )
16932    }
16933
16934    fn serve_borrowed_stream_break_drain(
16935        socket: &mut std::net::TcpStream,
16936        stranded_response: &[u8],
16937    ) {
16938        use std::io::Write as _;
16939        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
16940
16941        assert_eq!(
16942            read_marker_type(socket),
16943            TNS_MARKER_TYPE_BREAK,
16944            "reuse must BREAK before sending a request or cursor-close piggyback"
16945        );
16946        socket
16947            .write_all(&data_packet(stranded_response, true))
16948            .expect("write stranded borrowed response");
16949        socket
16950            .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
16951            .expect("write break acknowledgement");
16952        assert_eq!(
16953            read_marker_type(socket),
16954            TNS_MARKER_TYPE_RESET,
16955            "drain must RESET before the reuse request"
16956        );
16957        socket
16958            .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
16959            .expect("write reset confirmation");
16960        socket
16961            .write_all(&data_packet(TRAILING_CANCEL_ERROR, true))
16962            .expect("write trailing cancel response");
16963    }
16964
16965    #[test]
16966    fn borrowed_stream_first_page_callback_error_retires_cursor() -> Result<()> {
16967        const SQL: &str = "select value from borrowed_callback_failure";
16968        let response = synthetic_pipeline_execute_response_payload();
16969        let expected = sequential_op_decode(&response);
16970        let cursor_id = expected.cursor_id;
16971        assert_ne!(cursor_id, 0, "fixture must open a query cursor");
16972        assert!(
16973            !expected.rows.is_empty(),
16974            "fixture must invoke the first-page callback"
16975        );
16976
16977        let listener = TcpListener::bind("127.0.0.1:0")?;
16978        let addr = listener.local_addr()?;
16979        let server = thread::spawn(move || -> std::io::Result<()> {
16980            use std::io::Write as _;
16981            let (mut socket, _) = listener.accept()?;
16982            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
16983            let _execute = read_one_wire_packet(&mut socket);
16984            let response_packet = data_packet(&response, true);
16985            socket.write_all(&response_packet)?;
16986            socket.flush()?;
16987
16988            // The retry must parse a fresh statement after the failed stream
16989            // evicted its cached cursor. Its request also carries the deferred
16990            // close piggyback for the abandoned cursor.
16991            let _retry = read_one_wire_packet(&mut socket);
16992            socket.write_all(&response_packet)?;
16993            socket.flush()?;
16994            Ok(())
16995        });
16996
16997        let runtime = build_io_runtime()?;
16998        runtime.block_on(async {
16999            let cx = test_cx()?;
17000            let stream = TcpStream::connect(addr).await?;
17001            let (read, write) = transport::plain_split(stream);
17002            let mut connection = loopback_connection(read, write);
17003
17004            let err = connection
17005                .for_each_row_ref(&cx, SQL, 2, |_row| {
17006                    Err(Error::Runtime("stop borrowed callback".to_string()))
17007                })
17008                .await
17009                .expect_err("callback failure must be surfaced");
17010            assert!(matches!(err, Error::Runtime(message) if message == "stop borrowed callback"));
17011            assert!(!connection.in_use_cursors.contains(&cursor_id));
17012            assert!(
17013                connection
17014                    .statement_cache
17015                    .iter()
17016                    .all(|entry| entry.cursor_id != cursor_id),
17017                "failed borrowed stream must not leave its cursor reusable"
17018            );
17019            assert!(!connection.cursor_columns.contains_key(&cursor_id));
17020            assert_eq!(
17021                connection
17022                    .cursors_to_close
17023                    .iter()
17024                    .filter(|queued| **queued == cursor_id)
17025                    .count(),
17026                1,
17027                "failed borrowed stream must queue one cursor close"
17028            );
17029            assert_eq!(
17030                connection.core.recovery.phase(),
17031                SessionRecoveryPhase::Ready,
17032                "a first-page callback error has no stranded response"
17033            );
17034
17035            let mut retried_rows = 0usize;
17036            connection
17037                .for_each_row_ref(&cx, SQL, 2, |_row| {
17038                    retried_rows += 1;
17039                    Ok(())
17040                })
17041                .await?;
17042            assert_eq!(retried_rows, expected.rows.len());
17043            assert!(
17044                connection
17045                    .statement_cache
17046                    .iter()
17047                    .any(|entry| entry.cursor_id == cursor_id),
17048                "a successful retry must return its fresh cursor to the cache"
17049            );
17050            assert!(!connection.in_use_cursors.contains(&cursor_id));
17051            assert!(!connection.copied_cursors.contains(&cursor_id));
17052            assert!(
17053                !connection.cursors_to_close.contains(&cursor_id),
17054                "the retry request must consume the abandoned cursor's close piggyback"
17055            );
17056            Ok::<_, Error>(())
17057        })?;
17058
17059        server.join().expect("server thread joins")?;
17060        Ok(())
17061    }
17062
17063    #[test]
17064    fn borrowed_stream_paged_callback_error_drains_before_close_and_reuse() -> Result<()> {
17065        const SQL: &str = "select value from paged_borrowed_callback_failure";
17066        const FRESH_SQL: &str = "select 7 + 5 as value from dual";
17067
17068        let execute_response = synthetic_open_cursor_execute_response_payload();
17069        let first = sequential_op_decode(&execute_response);
17070        let cursor_id = first.cursor_id;
17071        let continuation = synthetic_open_borrowed_fetch_response("13");
17072        let parsed_continuation = parse_query_response_borrowed_with_limits(
17073            &continuation,
17074            ClientCapabilities::default(),
17075            &first.columns,
17076            first.rows.last().map(Vec::as_slice),
17077            ProtocolLimits::DEFAULT,
17078        )
17079        .expect("synthetic continuation must decode through the borrowed parser");
17080        assert_eq!(parsed_continuation.batch.row_count(), 1);
17081        assert!(parsed_continuation.more_rows);
17082        drop(parsed_continuation);
17083
17084        let (close_tx, close_rx) = std::sync::mpsc::channel::<Vec<u8>>();
17085        let listener = TcpListener::bind("127.0.0.1:0")?;
17086        let addr = listener.local_addr()?;
17087        let stranded = continuation.clone();
17088        let server = thread::spawn(move || {
17089            use std::io::Write as _;
17090            let (mut socket, _) = listener.accept().expect("accept test client");
17091            socket
17092                .set_read_timeout(Some(Duration::from_secs(5)))
17093                .expect("set read timeout");
17094
17095            let _execute = read_one_wire_data_payload(&mut socket);
17096            socket
17097                .write_all(&data_packet(&execute_response, true))
17098                .expect("write open-cursor execute response");
17099            let _first_fetch = read_one_wire_data_payload(&mut socket);
17100            socket
17101                .write_all(&data_packet(&continuation, true))
17102                .expect("write first continuation page");
17103
17104            // `for_each_row_ref` must send this speculative request before it
17105            // invokes the page callback that fails.
17106            let _speculative_fetch = read_one_wire_data_payload(&mut socket);
17107            serve_borrowed_stream_break_drain(&mut socket, &stranded);
17108
17109            let reuse = read_one_wire_data_payload(&mut socket);
17110            let expected_close = close_rx
17111                .recv_timeout(Duration::from_secs(2))
17112                .expect("client provides expected close piggyback");
17113            assert!(
17114                reuse.starts_with(&expected_close),
17115                "cursor close must be deduplicated and prepended only after BREAK/RESET drain"
17116            );
17117            socket
17118                .write_all(&data_packet(
17119                    &synthetic_pipeline_execute_response_payload(),
17120                    true,
17121                ))
17122                .expect("write fresh reuse response");
17123        });
17124
17125        let runtime = build_io_runtime()?;
17126        runtime.block_on(async {
17127            let cx = test_cx()?;
17128            let stream = TcpStream::connect(addr).await?;
17129            let (read, write) = transport::plain_split(stream);
17130            let mut connection = loopback_connection(read, write);
17131            let mut rows_seen = 0usize;
17132
17133            let err = connection
17134                .for_each_row_ref(&cx, SQL, 2, |_row| {
17135                    rows_seen += 1;
17136                    if rows_seen == 2 {
17137                        Err(Error::Runtime("stop paged callback".into()))
17138                    } else {
17139                        Ok(())
17140                    }
17141                })
17142                .await
17143                .expect_err("paged callback failure must be surfaced");
17144            assert!(matches!(err, Error::Runtime(message) if message == "stop paged callback"));
17145            assert_eq!(
17146                rows_seen, 2,
17147                "failure must occur in the fetched-page callback, after speculative send"
17148            );
17149            assert_borrowed_stream_cursor_retired(
17150                &connection,
17151                cursor_id,
17152                SessionRecoveryPhase::InFlight,
17153            );
17154            connection.close_cursor(cursor_id);
17155            assert_borrowed_stream_cursor_retired(
17156                &connection,
17157                cursor_id,
17158                SessionRecoveryPhase::InFlight,
17159            );
17160
17161            close_tx
17162                .send(expected_next_close_piggyback(&connection, cursor_id))
17163                .expect("server is waiting for close proof");
17164            let fresh = connection
17165                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17166                .await?;
17167            assert_eq!(
17168                fresh,
17169                sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
17170                "same connection must decode its own response after drain"
17171            );
17172            assert_eq!(
17173                connection.core.recovery.phase(),
17174                SessionRecoveryPhase::Ready
17175            );
17176            assert!(!connection.cursors_to_close.contains(&cursor_id));
17177            connection.release_cursor(fresh.cursor_id);
17178            Ok::<_, Error>(())
17179        })?;
17180
17181        server.join().expect("server thread joins");
17182        Ok(())
17183    }
17184
17185    fn exercise_borrowed_stream_fetch_decode_failure(malformed: Vec<u8>) -> Result<()> {
17186        const SQL: &str = "select value from malformed_borrowed_fetch";
17187        const FRESH_SQL: &str = "select 7 + 5 as value from dual";
17188
17189        let execute_response = synthetic_open_cursor_execute_response_payload();
17190        let cursor_id = sequential_op_decode(&execute_response).cursor_id;
17191        let (close_tx, close_rx) = std::sync::mpsc::channel::<Vec<u8>>();
17192        let listener = TcpListener::bind("127.0.0.1:0")?;
17193        let addr = listener.local_addr()?;
17194        let server = thread::spawn(move || {
17195            use std::io::Write as _;
17196            let (mut socket, _) = listener.accept().expect("accept test client");
17197            socket
17198                .set_read_timeout(Some(Duration::from_secs(5)))
17199                .expect("set read timeout");
17200
17201            let _execute = read_one_wire_data_payload(&mut socket);
17202            socket
17203                .write_all(&data_packet(&execute_response, true))
17204                .expect("write open-cursor execute response");
17205            let _fetch = read_one_wire_data_payload(&mut socket);
17206            socket
17207                .write_all(&data_packet(&malformed, true))
17208                .expect("write malformed fetch response");
17209
17210            // The malformed response was fully framed and consumed, so there
17211            // must be no BREAK. The very next packet is the close+reuse DATA.
17212            let reuse = read_one_wire_data_payload(&mut socket);
17213            let expected_close = close_rx
17214                .recv_timeout(Duration::from_secs(2))
17215                .expect("client provides expected close piggyback");
17216            assert!(reuse.starts_with(&expected_close));
17217            socket
17218                .write_all(&data_packet(
17219                    &synthetic_pipeline_execute_response_payload(),
17220                    true,
17221                ))
17222                .expect("write fresh reuse response");
17223        });
17224
17225        let runtime = build_io_runtime()?;
17226        runtime.block_on(async {
17227            let cx = test_cx()?;
17228            let stream = TcpStream::connect(addr).await?;
17229            let (read, write) = transport::plain_split(stream);
17230            let mut connection = loopback_connection(read, write);
17231            let mut rows_seen = 0usize;
17232
17233            let err = connection
17234                .for_each_row_ref(&cx, SQL, 2, |_row| {
17235                    rows_seen += 1;
17236                    Ok(())
17237                })
17238                .await
17239                .expect_err("malformed continuation must fail decoding");
17240            assert!(matches!(err, Error::Protocol(_)));
17241            assert_eq!(rows_seen, 1, "only the execute page may reach the callback");
17242            assert_borrowed_stream_cursor_retired(
17243                &connection,
17244                cursor_id,
17245                SessionRecoveryPhase::Ready,
17246            );
17247            connection.close_cursor(cursor_id);
17248            assert_borrowed_stream_cursor_retired(
17249                &connection,
17250                cursor_id,
17251                SessionRecoveryPhase::Ready,
17252            );
17253
17254            close_tx
17255                .send(expected_next_close_piggyback(&connection, cursor_id))
17256                .expect("server is waiting for close proof");
17257            let fresh = connection
17258                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17259                .await?;
17260            assert_eq!(
17261                fresh,
17262                sequential_op_decode(&synthetic_pipeline_execute_response_payload())
17263            );
17264            assert_eq!(
17265                connection.core.recovery.phase(),
17266                SessionRecoveryPhase::Ready
17267            );
17268            assert!(!connection.cursors_to_close.contains(&cursor_id));
17269            connection.release_cursor(fresh.cursor_id);
17270            Ok::<_, Error>(())
17271        })?;
17272
17273        server.join().expect("server thread joins");
17274        Ok(())
17275    }
17276
17277    #[test]
17278    fn borrowed_stream_malformed_and_truncated_fetches_retire_before_reuse() -> Result<()> {
17279        exercise_borrowed_stream_fetch_decode_failure(vec![0xff])?;
17280        exercise_borrowed_stream_fetch_decode_failure(vec![
17281            oracledb_protocol::thin::TNS_MSG_TYPE_ROW_HEADER,
17282        ])
17283    }
17284
17285    #[test]
17286    fn borrowed_stream_fetch_eof_retires_cursor() -> Result<()> {
17287        const SQL: &str = "select value from eof_borrowed_fetch";
17288        let execute_response = synthetic_open_cursor_execute_response_payload();
17289        let cursor_id = sequential_op_decode(&execute_response).cursor_id;
17290        let listener = TcpListener::bind("127.0.0.1:0")?;
17291        let addr = listener.local_addr()?;
17292        let server = thread::spawn(move || {
17293            use std::io::Write as _;
17294            let (mut socket, _) = listener.accept().expect("accept test client");
17295            socket
17296                .set_read_timeout(Some(Duration::from_secs(5)))
17297                .expect("set read timeout");
17298            let _execute = read_one_wire_data_payload(&mut socket);
17299            socket
17300                .write_all(&data_packet(&execute_response, true))
17301                .expect("write open-cursor execute response");
17302            let _fetch = read_one_wire_data_payload(&mut socket);
17303            socket
17304                .shutdown(std::net::Shutdown::Both)
17305                .expect("close during fetch response");
17306        });
17307
17308        let runtime = build_io_runtime()?;
17309        runtime.block_on(async {
17310            let cx = test_cx()?;
17311            let stream = TcpStream::connect(addr).await?;
17312            let (read, write) = transport::plain_split(stream);
17313            let mut connection = loopback_connection(read, write);
17314            let err = connection
17315                .for_each_row_ref(&cx, SQL, 2, |_row| Ok(()))
17316                .await
17317                .expect_err("EOF during continuation fetch must fail");
17318            assert!(matches!(err, Error::Io(_) | Error::ConnectionClosed(_)));
17319            assert_borrowed_stream_cursor_retired(
17320                &connection,
17321                cursor_id,
17322                SessionRecoveryPhase::BreakSent,
17323            );
17324            connection.close_cursor(cursor_id);
17325            assert_borrowed_stream_cursor_retired(
17326                &connection,
17327                cursor_id,
17328                SessionRecoveryPhase::BreakSent,
17329            );
17330            Ok::<_, Error>(())
17331        })?;
17332
17333        server.join().expect("server thread joins");
17334        Ok(())
17335    }
17336
17337    #[test]
17338    fn borrowed_stream_cancel_before_fetch_request_retires_without_wire_write() -> Result<()> {
17339        const SQL: &str = "select value from pre_request_borrowed_cancel";
17340        let execute_response = synthetic_open_cursor_execute_response_payload();
17341        let cursor_id = sequential_op_decode(&execute_response).cursor_id;
17342        let listener = TcpListener::bind("127.0.0.1:0")?;
17343        let addr = listener.local_addr()?;
17344        let server = thread::spawn(move || -> std::io::Result<Option<u8>> {
17345            use std::io::Write as _;
17346            let (mut socket, _) = listener.accept()?;
17347            socket.set_read_timeout(Some(Duration::from_millis(500)))?;
17348            let _execute = read_one_wire_data_payload(&mut socket);
17349            socket.write_all(&data_packet(&execute_response, true))?;
17350            socket.flush()?;
17351
17352            let mut byte = [0u8; 1];
17353            match socket.read(&mut byte) {
17354                Ok(0) => Ok(None),
17355                Ok(_) => Ok(Some(byte[0])),
17356                Err(err)
17357                    if matches!(
17358                        err.kind(),
17359                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
17360                    ) =>
17361                {
17362                    Ok(None)
17363                }
17364                Err(err) => Err(err),
17365            }
17366        });
17367
17368        let runtime = build_io_runtime()?;
17369        runtime.block_on(async {
17370            let cx = test_cx()?;
17371            let stream = TcpStream::connect(addr).await?;
17372            let (read, write) = transport::plain_split(stream);
17373            let mut connection = loopback_connection(read, write);
17374            let err = connection
17375                .for_each_row_ref(&cx, SQL, 2, |_row| {
17376                    cx.cancel_fast(asupersync::CancelKind::User);
17377                    Ok(())
17378                })
17379                .await
17380                .expect_err("cancel checkpoint must stop before FETCH write");
17381            assert!(matches!(err, Error::Cancelled));
17382            assert_eq!(
17383                connection.ttc_seq_num, 1,
17384                "cancel-before-request must not allocate a FETCH sequence"
17385            );
17386            assert_borrowed_stream_cursor_retired(
17387                &connection,
17388                cursor_id,
17389                SessionRecoveryPhase::Ready,
17390            );
17391            connection.close_cursor(cursor_id);
17392            assert_borrowed_stream_cursor_retired(
17393                &connection,
17394                cursor_id,
17395                SessionRecoveryPhase::Ready,
17396            );
17397            Ok::<_, Error>(())
17398        })?;
17399
17400        let received = server.join().expect("server thread joins")?;
17401        assert_eq!(received, None, "cancel-before-request must write no FETCH");
17402        Ok(())
17403    }
17404
17405    #[test]
17406    fn borrowed_stream_drop_after_fetch_request_drains_before_close_and_reuse() -> Result<()> {
17407        const SQL: &str = "select value from post_request_borrowed_cancel";
17408        const FRESH_SQL: &str = "select 7 + 5 as value from dual";
17409        let execute_response = synthetic_open_cursor_execute_response_payload();
17410        let cursor_id = sequential_op_decode(&execute_response).cursor_id;
17411        let stranded = synthetic_open_borrowed_fetch_response("14");
17412        let (execute_ready_tx, execute_ready_rx) = std::sync::mpsc::channel();
17413        let (fetch_seen_tx, fetch_seen_rx) = std::sync::mpsc::channel();
17414        let (close_tx, close_rx) = std::sync::mpsc::channel::<Vec<u8>>();
17415        let listener = TcpListener::bind("127.0.0.1:0")?;
17416        let addr = listener.local_addr()?;
17417        let server = thread::spawn(move || {
17418            use std::io::Write as _;
17419            let (mut socket, _) = listener.accept().expect("accept test client");
17420            socket
17421                .set_read_timeout(Some(Duration::from_secs(5)))
17422                .expect("set read timeout");
17423            let _execute = read_one_wire_data_payload(&mut socket);
17424            socket
17425                .write_all(&data_packet(&execute_response, true))
17426                .expect("write open-cursor execute response");
17427            socket.flush().expect("flush execute response");
17428            execute_ready_tx
17429                .send(())
17430                .expect("client waits for execute response");
17431            let _fetch = read_one_wire_data_payload(&mut socket);
17432            fetch_seen_tx
17433                .send(())
17434                .expect("client waits for FETCH write");
17435
17436            serve_borrowed_stream_break_drain(&mut socket, &stranded);
17437            let reuse = read_one_wire_data_payload(&mut socket);
17438            let expected_close = close_rx
17439                .recv_timeout(Duration::from_secs(2))
17440                .expect("client provides expected close piggyback");
17441            assert!(reuse.starts_with(&expected_close));
17442            socket
17443                .write_all(&data_packet(
17444                    &synthetic_pipeline_execute_response_payload(),
17445                    true,
17446                ))
17447                .expect("write fresh reuse response");
17448        });
17449
17450        let runtime = build_io_runtime()?;
17451        runtime.block_on(async {
17452            let cx = test_cx()?;
17453            let stream = TcpStream::connect(addr).await?;
17454            let (read, write) = transport::plain_split(stream);
17455            let mut connection = loopback_connection(read, write);
17456            let mut rows_seen = 0usize;
17457
17458            {
17459                let mut fetch = pin!(connection.for_each_row_ref(&cx, SQL, 2, |_row| {
17460                    rows_seen += 1;
17461                    Ok(())
17462                }));
17463                let first_poll = poll_fn(|task_cx| Poll::Ready(fetch.as_mut().poll(task_cx))).await;
17464                assert!(matches!(first_poll, Poll::Pending));
17465                execute_ready_rx
17466                    .recv_timeout(Duration::from_secs(2))
17467                    .expect("server wrote execute response");
17468
17469                let deadline = Instant::now() + Duration::from_secs(2);
17470                loop {
17471                    match fetch_seen_rx.try_recv() {
17472                        Ok(()) => break,
17473                        Err(std::sync::mpsc::TryRecvError::Empty) => {}
17474                        Err(std::sync::mpsc::TryRecvError::Disconnected) => {
17475                            panic!("server exited before seeing FETCH")
17476                        }
17477                    }
17478                    assert!(Instant::now() < deadline, "FETCH request was never sent");
17479                    let polled = poll_fn(|task_cx| Poll::Ready(fetch.as_mut().poll(task_cx))).await;
17480                    assert!(matches!(polled, Poll::Pending));
17481                    thread::yield_now();
17482                }
17483            }
17484
17485            assert_eq!(
17486                rows_seen, 1,
17487                "execute page callback must run before FETCH wait"
17488            );
17489            assert_borrowed_stream_cursor_retired(
17490                &connection,
17491                cursor_id,
17492                SessionRecoveryPhase::BreakSent,
17493            );
17494            connection.close_cursor(cursor_id);
17495            assert_borrowed_stream_cursor_retired(
17496                &connection,
17497                cursor_id,
17498                SessionRecoveryPhase::BreakSent,
17499            );
17500
17501            close_tx
17502                .send(expected_next_close_piggyback(&connection, cursor_id))
17503                .expect("server is waiting for close proof");
17504            let fresh = connection
17505                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17506                .await?;
17507            assert_eq!(
17508                fresh,
17509                sequential_op_decode(&synthetic_pipeline_execute_response_payload())
17510            );
17511            assert_eq!(
17512                connection.core.recovery.phase(),
17513                SessionRecoveryPhase::Ready
17514            );
17515            assert!(!connection.cursors_to_close.contains(&cursor_id));
17516            connection.release_cursor(fresh.cursor_id);
17517            Ok::<_, Error>(())
17518        })?;
17519
17520        server.join().expect("server thread joins");
17521        Ok(())
17522    }
17523
17524    #[test]
17525    fn streaming_cancel_mid_stream_leaves_connection_reusable() -> Result<()> {
17526        // a4-x3s (rust-oracledb iec3.1.12) offline negative control: cancelling
17527        // the async row stream mid-flight must leave the connection at a CLEAN
17528        // wire boundary and fully reusable — no protocol desync, no leaked BREAK,
17529        // no stranded response bytes bleeding into the next query.
17530        //
17531        // The stream is `fetch_rows_ref` (the constant-memory borrowed-batch
17532        // lending iterator). Dropping its in-flight response read arms the
17533        // `CancelDrainGuard` (phase -> BreakSent). The NEXT operation runs the
17534        // shared `ensure_clean_before_request` drain: BREAK, then drain the
17535        // server's stranded response + break-ack MARKER + RESET handshake +
17536        // trailing ORA-01013 cancel error, then issue its own request against a
17537        // clean wire (mirrors python-oracledb `_break_external`/`_reset`,
17538        // protocol.pyx). Reuse is proven by running a REAL query afterwards and
17539        // decoding it byte-identically to the reference — not merely a phase.
17540        const STRANDED_BODY: &[u8] = b"stranded stream response";
17541        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d]; // ORA-01013 user cancel
17542
17543        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
17544        let addr = listener.local_addr().expect("listener address");
17545        let server = thread::spawn(move || {
17546            use std::io::Write as _;
17547            let (mut socket, _) = listener.accept().expect("accept test client");
17548            socket
17549                .set_read_timeout(Some(Duration::from_secs(5)))
17550                .expect("set read timeout");
17551
17552            // 1) The stream's fetch request goes out first.
17553            let _fetch_request = read_one_wire_packet(&mut socket);
17554
17555            // 2) The reuse op's cancel drain breaks and drains the stranded call.
17556            assert_eq!(
17557                read_marker_type(&mut socket),
17558                TNS_MARKER_TYPE_BREAK,
17559                "the reuse op must BREAK the stranded stream before its own request"
17560            );
17561            socket
17562                .write_all(&data_packet(STRANDED_BODY, true))
17563                .expect("write stranded stream response");
17564            socket
17565                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
17566                .expect("write break-ack marker");
17567            assert_eq!(
17568                read_marker_type(&mut socket),
17569                TNS_MARKER_TYPE_RESET,
17570                "the drain must answer the server break marker with RESET"
17571            );
17572            socket
17573                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
17574                .expect("write reset-confirm marker");
17575            socket
17576                .write_all(&data_packet(TRAILING_CANCEL_ERROR, true))
17577                .expect("write trailing cancel error packet");
17578
17579            // 3) The reuse query's fresh request lands on a clean wire; answer it.
17580            let _reuse_request = read_one_wire_packet(&mut socket);
17581            socket
17582                .write_all(&data_packet(
17583                    &synthetic_pipeline_execute_response_payload(),
17584                    true,
17585                ))
17586                .expect("write reuse query response");
17587            socket.flush().expect("flush responses");
17588        });
17589
17590        let runtime = build_io_runtime()?;
17591        runtime.block_on(async {
17592            let cx = test_cx()?;
17593            let stream = TcpStream::connect(addr).await?;
17594            let (read, write) = transport::plain_split(stream);
17595            let mut connection = loopback_connection(read, write);
17596
17597            // Start streaming, drive the request out, then cancel mid-stream by
17598            // dropping the borrowed-batch fetch future while its response read is
17599            // still pending.
17600            {
17601                let mut fetch = pin!(connection.fetch_rows_ref(&cx, 42, 10, None));
17602                let first = poll_fn(|task_cx| Poll::Ready(fetch.as_mut().poll(task_cx))).await;
17603                assert!(
17604                    matches!(first, Poll::Pending),
17605                    "the stream must be waiting on the server response when cancelled"
17606                );
17607            }
17608            assert_eq!(
17609                connection.core.recovery.phase(),
17610                SessionRecoveryPhase::BreakSent,
17611                "cancelling the stream mid-read arms break/drain recovery"
17612            );
17613
17614            // Reuse the SAME connection: a real query must decode correctly,
17615            // proving the wire was drained to a clean boundary.
17616            let reused = connection
17617                .execute_raw(
17618                    &cx,
17619                    "select value from synthetic_fixture",
17620                    2,
17621                    &[],
17622                    ExecuteOptions::default(),
17623                    None,
17624                )
17625                .await?;
17626            assert_eq!(
17627                connection.core.recovery.phase(),
17628                SessionRecoveryPhase::Ready,
17629                "after the drain the connection is back to Ready"
17630            );
17631            assert_eq!(
17632                reused,
17633                sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
17634                "the reused connection decodes the follow-up query byte-identically"
17635            );
17636            Ok::<_, Error>(())
17637        })?;
17638
17639        server.join().expect("server thread joins");
17640        Ok(())
17641    }
17642
17643    #[test]
17644    fn dropped_define_fetch_mid_read_drains_before_connection_reuse() -> Result<()> {
17645        const CURSOR_ID: u32 = 42;
17646        const STRANDED_BODY: &[u8] = b"stranded define-fetch response";
17647        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
17648        const FRESH_SQL: &str = "select value from define_fetch_reuse_fixture";
17649
17650        let listener = TcpListener::bind("127.0.0.1:0")?;
17651        let addr = listener.local_addr()?;
17652        let (define_seen_tx, define_seen_rx) = std::sync::mpsc::channel();
17653        let server = thread::spawn(move || -> std::io::Result<bool> {
17654            use std::io::Write as _;
17655            let (mut socket, _) = listener.accept()?;
17656            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
17657
17658            assert_eq!(
17659                read_one_wire_packet(&mut socket),
17660                TNS_PACKET_TYPE_DATA,
17661                "define-fetch must send a DATA request"
17662            );
17663            define_seen_tx
17664                .send(())
17665                .expect("client waits for define-fetch request proof");
17666
17667            let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
17668            if next_packet_type == TNS_PACKET_TYPE_MARKER {
17669                assert_eq!(
17670                    next_body,
17671                    vec![1, 0, TNS_MARKER_TYPE_BREAK],
17672                    "reuse must BREAK the stranded define-fetch before its request"
17673                );
17674                socket.write_all(&data_packet(STRANDED_BODY, true))?;
17675                socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
17676                assert_eq!(
17677                    read_marker_type(&mut socket),
17678                    TNS_MARKER_TYPE_RESET,
17679                    "define-fetch drain must complete the RESET handshake"
17680                );
17681                socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
17682                socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
17683
17684                assert_eq!(
17685                    read_one_wire_packet(&mut socket),
17686                    TNS_PACKET_TYPE_DATA,
17687                    "fresh execute follows the completed drain"
17688                );
17689                socket.write_all(&data_packet(
17690                    &synthetic_pipeline_execute_response_payload(),
17691                    true,
17692                ))?;
17693                socket.flush()?;
17694                Ok(true)
17695            } else {
17696                assert_eq!(
17697                    next_packet_type, TNS_PACKET_TYPE_DATA,
17698                    "without recovery the next operation is sent directly"
17699                );
17700                // Reproduce stale-wire poisoning: the abandoned define-fetch
17701                // response arrives before the fresh execute response.
17702                socket.write_all(&data_packet(STRANDED_BODY, true))?;
17703                socket.write_all(&data_packet(
17704                    &synthetic_pipeline_execute_response_payload(),
17705                    true,
17706                ))?;
17707                socket.flush()?;
17708                Ok(false)
17709            }
17710        });
17711
17712        let runtime = build_io_runtime()?;
17713        let outcome = runtime.block_on(async {
17714            let cx = test_cx()?;
17715            let stream = TcpStream::connect(addr).await?;
17716            let (read, write) = transport::plain_split(stream);
17717            let mut connection = loopback_connection(read, write);
17718            let define_columns = vec![ColumnMetadata::new(
17719                "DOC",
17720                oracledb_protocol::thin::ORA_TYPE_NUM_JSON,
17721            )];
17722
17723            {
17724                let mut define = pin!(connection.define_and_fetch_rows_with_columns(
17725                    &cx,
17726                    CURSOR_ID,
17727                    10,
17728                    &define_columns,
17729                    None,
17730                ));
17731                let first = poll_fn(|task_cx| Poll::Ready(define.as_mut().poll(task_cx))).await;
17732                assert!(
17733                    matches!(first, Poll::Pending),
17734                    "define-fetch must be waiting for its response before drop"
17735                );
17736                define_seen_rx
17737                    .recv_timeout(Duration::from_secs(2))
17738                    .expect("server observed define-fetch request");
17739            }
17740
17741            let reused = connection
17742                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17743                .await;
17744            Ok::<_, Error>((reused, connection.core.recovery.phase()))
17745        });
17746
17747        let recovered = server.join().expect("define-fetch server joins")?;
17748        let (reused, phase) = outcome?;
17749        let reused = reused.expect("fresh execute must not decode the stranded define-fetch");
17750        assert_eq!(
17751            reused,
17752            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
17753            "reuse must decode its own response byte-identically"
17754        );
17755        assert!(recovered, "reuse must take the BREAK/drain branch");
17756        assert_eq!(phase, SessionRecoveryPhase::Ready);
17757        Ok(())
17758    }
17759
17760    #[test]
17761    fn dropped_commit_mid_read_drains_before_connection_reuse() -> Result<()> {
17762        const STRANDED_BODY: &[u8] = &[TNS_MSG_TYPE_END_OF_RESPONSE];
17763        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
17764        const FRESH_SQL: &str = "select value from commit_reuse_fixture";
17765
17766        let listener = TcpListener::bind("127.0.0.1:0")?;
17767        let addr = listener.local_addr()?;
17768        let (commit_seen_tx, commit_seen_rx) = std::sync::mpsc::channel();
17769        let server = thread::spawn(move || -> std::io::Result<bool> {
17770            use std::io::Write as _;
17771            let (mut socket, _) = listener.accept()?;
17772            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
17773
17774            assert_eq!(
17775                read_one_wire_packet(&mut socket),
17776                TNS_PACKET_TYPE_DATA,
17777                "commit must send a DATA request"
17778            );
17779            commit_seen_tx
17780                .send(())
17781                .expect("client waits for commit request proof");
17782
17783            let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
17784            if next_packet_type == TNS_PACKET_TYPE_MARKER {
17785                assert_eq!(
17786                    next_body,
17787                    vec![1, 0, TNS_MARKER_TYPE_BREAK],
17788                    "reuse must BREAK the stranded commit before its request"
17789                );
17790                socket.write_all(&data_packet(STRANDED_BODY, true))?;
17791                socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
17792                assert_eq!(
17793                    read_marker_type(&mut socket),
17794                    TNS_MARKER_TYPE_RESET,
17795                    "commit drain must complete the RESET handshake"
17796                );
17797                socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
17798                socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
17799
17800                assert_eq!(
17801                    read_one_wire_packet(&mut socket),
17802                    TNS_PACKET_TYPE_DATA,
17803                    "fresh execute follows the completed drain"
17804                );
17805                socket.write_all(&data_packet(
17806                    &synthetic_pipeline_execute_response_payload(),
17807                    true,
17808                ))?;
17809                socket.flush()?;
17810                Ok(true)
17811            } else {
17812                assert_eq!(
17813                    next_packet_type, TNS_PACKET_TYPE_DATA,
17814                    "without recovery the next operation is sent directly"
17815                );
17816                // Negative control for the unfixed path: the abandoned commit
17817                // response arrives before the fresh execute response.
17818                socket.write_all(&data_packet(STRANDED_BODY, true))?;
17819                socket.write_all(&data_packet(
17820                    &synthetic_pipeline_execute_response_payload(),
17821                    true,
17822                ))?;
17823                socket.flush()?;
17824                Ok(false)
17825            }
17826        });
17827
17828        let runtime = build_io_runtime()?;
17829        let outcome = runtime.block_on(async {
17830            let cx = test_cx()?;
17831            let stream = TcpStream::connect(addr).await?;
17832            let (read, write) = transport::plain_split(stream);
17833            let mut connection = loopback_connection(read, write);
17834
17835            {
17836                let mut commit = pin!(connection.commit(&cx));
17837                let first = poll_fn(|task_cx| Poll::Ready(commit.as_mut().poll(task_cx))).await;
17838                assert!(
17839                    matches!(first, Poll::Pending),
17840                    "commit must be waiting for its response before drop"
17841                );
17842                commit_seen_rx
17843                    .recv_timeout(Duration::from_secs(2))
17844                    .expect("server observed commit request");
17845            }
17846
17847            let phase_after_drop = connection.core.recovery.phase();
17848            let reused = connection
17849                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17850                .await;
17851            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
17852        });
17853
17854        let recovered = server.join().expect("commit server joins")?;
17855        let (phase_after_drop, reused, final_phase) = outcome?;
17856        let reused = reused.expect("fresh execute must not decode the stranded commit");
17857        assert_eq!(
17858            reused,
17859            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
17860            "reuse must decode its own response byte-identically"
17861        );
17862        assert!(recovered, "reuse must take the BREAK/drain branch");
17863        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
17864        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
17865        Ok(())
17866    }
17867
17868    #[test]
17869    fn successful_commit_disarms_recovery_before_reuse() -> Result<()> {
17870        const FRESH_SQL: &str = "select value from commit_success_fixture";
17871        let execute_response = synthetic_pipeline_execute_response_payload();
17872        let server_execute_response = execute_response.clone();
17873        let listener = TcpListener::bind("127.0.0.1:0")?;
17874        let addr = listener.local_addr()?;
17875        let server = thread::spawn(move || -> std::io::Result<()> {
17876            use std::io::Write as _;
17877            let (mut socket, _) = listener.accept()?;
17878            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
17879
17880            assert_eq!(
17881                read_one_wire_packet(&mut socket),
17882                TNS_PACKET_TYPE_DATA,
17883                "commit must send a DATA request"
17884            );
17885            socket.write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))?;
17886            socket.flush()?;
17887
17888            assert_eq!(
17889                read_one_wire_packet(&mut socket),
17890                TNS_PACKET_TYPE_DATA,
17891                "a successful commit must not cause a spurious BREAK on reuse"
17892            );
17893            socket.write_all(&data_packet(&server_execute_response, true))?;
17894            socket.flush()
17895        });
17896
17897        let runtime = build_io_runtime()?;
17898        runtime.block_on(async {
17899            let cx = test_cx()?;
17900            let stream = TcpStream::connect(addr).await?;
17901            let (read, write) = transport::plain_split(stream);
17902            let mut connection = loopback_connection(read, write);
17903
17904            connection.commit(&cx).await?;
17905            assert_eq!(
17906                connection.core.recovery.phase(),
17907                SessionRecoveryPhase::Ready,
17908                "a completed response must disarm the plain-function guard"
17909            );
17910
17911            let reused = connection
17912                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
17913                .await?;
17914            assert_eq!(reused, sequential_op_decode(&execute_response));
17915            assert_eq!(
17916                connection.core.recovery.phase(),
17917                SessionRecoveryPhase::Ready
17918            );
17919            Ok::<_, Error>(())
17920        })?;
17921
17922        server.join().expect("successful commit server joins")?;
17923        Ok(())
17924    }
17925
17926    #[test]
17927    fn precancelled_commit_writes_nothing_and_keeps_wire_ready() -> Result<()> {
17928        let listener = TcpListener::bind("127.0.0.1:0")?;
17929        let addr = listener.local_addr()?;
17930        let server = thread::spawn(move || -> std::io::Result<bool> {
17931            let (mut socket, _) = listener.accept()?;
17932            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
17933            let mut byte = [0u8; 1];
17934            match socket.read(&mut byte) {
17935                Ok(0) => Ok(false),
17936                Ok(_) => Ok(true),
17937                Err(err)
17938                    if matches!(
17939                        err.kind(),
17940                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
17941                    ) =>
17942                {
17943                    Ok(false)
17944                }
17945                Err(err) => Err(err),
17946            }
17947        });
17948
17949        let runtime = build_io_runtime()?;
17950        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
17951            let cx = test_cx()?;
17952            let stream = TcpStream::connect(addr).await?;
17953            let (read, write) = transport::plain_split(stream);
17954            let mut connection = loopback_connection(read, write);
17955            let sequence_before = connection.ttc_seq_num;
17956            cx.cancel_fast(CancelKind::User);
17957
17958            let err = connection
17959                .commit(&cx)
17960                .await
17961                .expect_err("pending cancellation stops before COMMIT");
17962            assert!(matches!(err, Error::Cancelled), "{err:?}");
17963            Ok::<_, Error>((
17964                connection.core.recovery.phase(),
17965                sequence_before,
17966                connection.ttc_seq_num,
17967            ))
17968        })?;
17969
17970        assert!(
17971            !server.join().expect("pre-cancel commit server joins")?,
17972            "pre-cancelled COMMIT must not write any wire bytes"
17973        );
17974        assert_eq!(phase, SessionRecoveryPhase::Ready);
17975        assert_eq!(sequence_after, sequence_before);
17976        Ok(())
17977    }
17978
17979    #[test]
17980    fn dropped_change_password_mid_response_drains_before_connection_reuse() -> Result<()> {
17981        const STRANDED_BODY: &[u8] = &[TNS_MSG_TYPE_END_OF_RESPONSE];
17982        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
17983        const FRESH_SQL: &str = "select value from change_password_reuse_fixture";
17984        const OLD_PASSWORD: &str = "old-change-password-proof";
17985        const NEW_PASSWORD: &str = "new-change-password-proof";
17986
17987        let listener = TcpListener::bind("127.0.0.1:0")?;
17988        let addr = listener.local_addr()?;
17989        let (change_seen_tx, change_seen_rx) = std::sync::mpsc::channel();
17990        let server = thread::spawn(move || -> std::io::Result<bool> {
17991            use std::io::Write as _;
17992            let (mut socket, _) = listener.accept()?;
17993            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
17994
17995            let (packet_type, body) = read_one_wire_packet_bytes(&mut socket);
17996            assert_eq!(
17997                packet_type, TNS_PACKET_TYPE_DATA,
17998                "password change must send a DATA request"
17999            );
18000            assert!(
18001                !body
18002                    .windows(OLD_PASSWORD.len())
18003                    .any(|window| window == OLD_PASSWORD.as_bytes()),
18004                "password-change request must not expose the old password"
18005            );
18006            assert!(
18007                !body
18008                    .windows(NEW_PASSWORD.len())
18009                    .any(|window| window == NEW_PASSWORD.as_bytes()),
18010                "password-change request must not expose the new password"
18011            );
18012            change_seen_tx
18013                .send(())
18014                .expect("client waits for password-change request proof");
18015
18016            let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
18017            if next_packet_type == TNS_PACKET_TYPE_MARKER {
18018                assert_eq!(
18019                    next_body,
18020                    vec![1, 0, TNS_MARKER_TYPE_BREAK],
18021                    "reuse must BREAK the stranded password change before its request"
18022                );
18023                socket.write_all(&data_packet(STRANDED_BODY, true))?;
18024                socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
18025                assert_eq!(
18026                    read_marker_type(&mut socket),
18027                    TNS_MARKER_TYPE_RESET,
18028                    "password-change drain must complete the RESET handshake"
18029                );
18030                socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
18031                socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
18032
18033                assert_eq!(
18034                    read_one_wire_packet(&mut socket),
18035                    TNS_PACKET_TYPE_DATA,
18036                    "fresh execute follows the completed drain"
18037                );
18038                socket.write_all(&data_packet(
18039                    &synthetic_pipeline_execute_response_payload(),
18040                    true,
18041                ))?;
18042                socket.flush()?;
18043                Ok(true)
18044            } else {
18045                assert_eq!(
18046                    next_packet_type, TNS_PACKET_TYPE_DATA,
18047                    "without recovery the next operation is sent directly"
18048                );
18049                socket.write_all(&data_packet(STRANDED_BODY, true))?;
18050                socket.write_all(&data_packet(
18051                    &synthetic_pipeline_execute_response_payload(),
18052                    true,
18053                ))?;
18054                socket.flush()?;
18055                Ok(false)
18056            }
18057        });
18058
18059        let runtime = build_io_runtime()?;
18060        let outcome = runtime.block_on(async {
18061            let cx = test_cx()?;
18062            let stream = TcpStream::connect(addr).await?;
18063            let (read, write) = transport::plain_split(stream);
18064            let mut connection = loopback_connection(read, write);
18065            connection.combo_key = vec![0x11; 32];
18066
18067            {
18068                let mut change_password =
18069                    pin!(connection.change_password(&cx, OLD_PASSWORD, NEW_PASSWORD,));
18070                let first =
18071                    poll_fn(|task_cx| Poll::Ready(change_password.as_mut().poll(task_cx))).await;
18072                assert!(
18073                    matches!(first, Poll::Pending),
18074                    "password change must be waiting for its response before drop"
18075                );
18076                change_seen_rx
18077                    .recv_timeout(Duration::from_secs(2))
18078                    .expect("server observed password-change request");
18079            }
18080
18081            let phase_after_drop = connection.core.recovery.phase();
18082            let reused = connection
18083                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18084                .await;
18085            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18086        });
18087
18088        let recovered = server.join().expect("password-change server joins")?;
18089        let (phase_after_drop, reused, final_phase) = outcome?;
18090        let reused = reused.expect("fresh execute must not decode the stranded password change");
18091        assert_eq!(
18092            reused,
18093            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18094            "reuse must decode its own response byte-identically"
18095        );
18096        assert!(recovered, "reuse must take the BREAK/drain branch");
18097        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18098        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18099        Ok(())
18100    }
18101
18102    #[test]
18103    fn successful_change_password_disarms_recovery_before_reuse() -> Result<()> {
18104        const FRESH_SQL: &str = "select value from change_password_success_fixture";
18105        let execute_response = synthetic_pipeline_execute_response_payload();
18106        let server_execute_response = execute_response.clone();
18107        let listener = TcpListener::bind("127.0.0.1:0")?;
18108        let addr = listener.local_addr()?;
18109        let server = thread::spawn(move || -> std::io::Result<()> {
18110            use std::io::Write as _;
18111            let (mut socket, _) = listener.accept()?;
18112            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
18113
18114            assert_eq!(
18115                read_one_wire_packet(&mut socket),
18116                TNS_PACKET_TYPE_DATA,
18117                "password change must send a DATA request"
18118            );
18119            socket.write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))?;
18120            socket.flush()?;
18121
18122            assert_eq!(
18123                read_one_wire_packet(&mut socket),
18124                TNS_PACKET_TYPE_DATA,
18125                "a successful password change must not cause a spurious BREAK on reuse"
18126            );
18127            socket.write_all(&data_packet(&server_execute_response, true))?;
18128            socket.flush()
18129        });
18130
18131        let runtime = build_io_runtime()?;
18132        runtime.block_on(async {
18133            let cx = test_cx()?;
18134            let stream = TcpStream::connect(addr).await?;
18135            let (read, write) = transport::plain_split(stream);
18136            let mut connection = loopback_connection(read, write);
18137            connection.combo_key = vec![0x11; 32];
18138
18139            connection
18140                .change_password(
18141                    &cx,
18142                    "old-change-password-proof",
18143                    "new-change-password-proof",
18144                )
18145                .await?;
18146            assert_eq!(
18147                connection.core.recovery.phase(),
18148                SessionRecoveryPhase::Ready,
18149                "a completed password-change response must disarm its guard"
18150            );
18151
18152            let reused = connection
18153                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18154                .await?;
18155            assert_eq!(reused, sequential_op_decode(&execute_response));
18156            assert_eq!(
18157                connection.core.recovery.phase(),
18158                SessionRecoveryPhase::Ready
18159            );
18160            Ok::<_, Error>(())
18161        })?;
18162
18163        server
18164            .join()
18165            .expect("successful password-change server joins")?;
18166        Ok(())
18167    }
18168
18169    #[test]
18170    fn precancelled_change_password_writes_nothing_and_keeps_wire_ready() -> Result<()> {
18171        let listener = TcpListener::bind("127.0.0.1:0")?;
18172        let addr = listener.local_addr()?;
18173        let server = thread::spawn(move || -> std::io::Result<bool> {
18174            let (mut socket, _) = listener.accept()?;
18175            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
18176            let mut byte = [0u8; 1];
18177            match socket.read(&mut byte) {
18178                Ok(0) => Ok(false),
18179                Ok(_) => Ok(true),
18180                Err(err)
18181                    if matches!(
18182                        err.kind(),
18183                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
18184                    ) =>
18185                {
18186                    Ok(false)
18187                }
18188                Err(err) => Err(err),
18189            }
18190        });
18191
18192        let runtime = build_io_runtime()?;
18193        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
18194            let cx = test_cx()?;
18195            let stream = TcpStream::connect(addr).await?;
18196            let (read, write) = transport::plain_split(stream);
18197            let mut connection = loopback_connection(read, write);
18198            let sequence_before = connection.ttc_seq_num;
18199            cx.cancel_fast(CancelKind::User);
18200
18201            let err = connection
18202                .change_password(
18203                    &cx,
18204                    "old-change-password-proof",
18205                    "new-change-password-proof",
18206                )
18207                .await
18208                .expect_err("pending cancellation stops before PASSWORD CHANGE");
18209            assert!(matches!(err, Error::Cancelled), "{err:?}");
18210            Ok::<_, Error>((
18211                connection.core.recovery.phase(),
18212                sequence_before,
18213                connection.ttc_seq_num,
18214            ))
18215        })?;
18216
18217        assert!(
18218            !server
18219                .join()
18220                .expect("pre-cancel password-change server joins")?,
18221            "pre-cancelled PASSWORD CHANGE must not write any wire bytes"
18222        );
18223        assert_eq!(phase, SessionRecoveryPhase::Ready);
18224        assert_eq!(sequence_after, sequence_before);
18225        Ok(())
18226    }
18227
18228    #[test]
18229    fn dropped_subscribe_register_mid_response_drains_before_connection_reuse() -> Result<()> {
18230        const FRESH_SQL: &str = "select value from subscribe_register_reuse_fixture";
18231
18232        let expected_request = build_subscribe_payload_with_seq(
18233            1,
18234            TNS_SUBSCR_OP_REGISTER,
18235            Some("test_user"),
18236            None,
18237            oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18238            None,
18239            oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18240            0,
18241            10,
18242            0,
18243            0,
18244            0,
18245            0,
18246            ClientCapabilities::default().ttc_field_version,
18247        )?;
18248        let stranded_response = synthetic_subscribe_register_response_payload();
18249        let listener = TcpListener::bind("127.0.0.1:0")?;
18250        let addr = listener.local_addr()?;
18251        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18252        let server = thread::spawn(move || {
18253            serve_dropped_response_recovery(
18254                listener,
18255                expected_request,
18256                stranded_response,
18257                request_seen_tx,
18258            )
18259        });
18260
18261        let runtime = build_io_runtime()?;
18262        let outcome = runtime.block_on(async {
18263            let cx = test_cx()?;
18264            let stream = TcpStream::connect(addr).await?;
18265            let (read, write) = transport::plain_split(stream);
18266            let mut connection = loopback_connection(read, write);
18267
18268            {
18269                let mut subscribe = pin!(connection.subscribe_register(
18270                    &cx,
18271                    oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18272                    None,
18273                    oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18274                    0,
18275                    10,
18276                    0,
18277                    0,
18278                    0,
18279                ));
18280                let first = poll_fn(|task_cx| Poll::Ready(subscribe.as_mut().poll(task_cx))).await;
18281                assert!(
18282                    matches!(first, Poll::Pending),
18283                    "CQN register must be waiting for its response before drop"
18284                );
18285                request_seen_rx
18286                    .recv_timeout(Duration::from_secs(2))
18287                    .expect("server observed CQN register request");
18288            }
18289
18290            let phase_after_drop = connection.core.recovery.phase();
18291            let reused = connection
18292                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18293                .await;
18294            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18295        });
18296
18297        let recovered = server.join().expect("CQN register server joins")?;
18298        let (phase_after_drop, reused, final_phase) = outcome?;
18299        let reused = reused.expect("fresh execute must not decode the stranded CQN register");
18300        assert_eq!(
18301            reused,
18302            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18303            "reuse must decode its own response byte-identically"
18304        );
18305        assert!(recovered, "reuse must take the BREAK/drain branch");
18306        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18307        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18308        Ok(())
18309    }
18310
18311    #[test]
18312    fn dropped_subscribe_unregister_mid_response_drains_before_connection_reuse() -> Result<()> {
18313        const FRESH_SQL: &str = "select value from subscribe_unregister_reuse_fixture";
18314        const CLIENT_ID: &[u8] = b"OCI:EP:301";
18315
18316        let expected_request = build_subscribe_payload_with_seq(
18317            1,
18318            TNS_SUBSCR_OP_UNREGISTER,
18319            Some("test_user"),
18320            Some(CLIENT_ID),
18321            oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18322            None,
18323            oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18324            0,
18325            10,
18326            0,
18327            0,
18328            0,
18329            302,
18330            ClientCapabilities::default().ttc_field_version,
18331        )?;
18332        let listener = TcpListener::bind("127.0.0.1:0")?;
18333        let addr = listener.local_addr()?;
18334        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18335        let server = thread::spawn(move || {
18336            serve_dropped_response_recovery(
18337                listener,
18338                expected_request,
18339                vec![TNS_MSG_TYPE_END_OF_RESPONSE],
18340                request_seen_tx,
18341            )
18342        });
18343
18344        let runtime = build_io_runtime()?;
18345        let outcome = runtime.block_on(async {
18346            let cx = test_cx()?;
18347            let stream = TcpStream::connect(addr).await?;
18348            let (read, write) = transport::plain_split(stream);
18349            let mut connection = loopback_connection(read, write);
18350
18351            {
18352                let mut unsubscribe = pin!(connection.subscribe_unregister(
18353                    &cx,
18354                    302,
18355                    CLIENT_ID,
18356                    oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18357                    None,
18358                    oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18359                    0,
18360                    10,
18361                    0,
18362                    0,
18363                    0,
18364                ));
18365                let first =
18366                    poll_fn(|task_cx| Poll::Ready(unsubscribe.as_mut().poll(task_cx))).await;
18367                assert!(
18368                    matches!(first, Poll::Pending),
18369                    "CQN unregister must be waiting for its response before drop"
18370                );
18371                request_seen_rx
18372                    .recv_timeout(Duration::from_secs(2))
18373                    .expect("server observed CQN unregister request");
18374            }
18375
18376            let phase_after_drop = connection.core.recovery.phase();
18377            let reused = connection
18378                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18379                .await;
18380            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18381        });
18382
18383        let recovered = server.join().expect("CQN unregister server joins")?;
18384        let (phase_after_drop, reused, final_phase) = outcome?;
18385        let reused = reused.expect("fresh execute must not decode the stranded CQN unregister");
18386        assert_eq!(
18387            reused,
18388            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18389            "reuse must decode its own response byte-identically"
18390        );
18391        assert!(recovered, "reuse must take the BREAK/drain branch");
18392        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18393        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18394        Ok(())
18395    }
18396
18397    #[test]
18398    fn successful_subscribe_round_trips_disarm_recovery_before_reuse() -> Result<()> {
18399        const CLIENT_ID: &[u8] = b"OCI:EP:301";
18400        const FRESH_SQL: &str = "select value from subscribe_success_fixture";
18401
18402        let register_request = build_subscribe_payload_with_seq(
18403            1,
18404            TNS_SUBSCR_OP_REGISTER,
18405            Some("test_user"),
18406            None,
18407            oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18408            None,
18409            oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18410            0,
18411            10,
18412            0,
18413            0,
18414            0,
18415            0,
18416            ClientCapabilities::default().ttc_field_version,
18417        )?;
18418        let unregister_request = build_subscribe_payload_with_seq(
18419            2,
18420            TNS_SUBSCR_OP_UNREGISTER,
18421            Some("test_user"),
18422            Some(CLIENT_ID),
18423            oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18424            None,
18425            oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18426            0,
18427            10,
18428            0,
18429            0,
18430            0,
18431            302,
18432            ClientCapabilities::default().ttc_field_version,
18433        )?;
18434        let register_response = synthetic_subscribe_register_response_payload();
18435        let execute_response = synthetic_pipeline_execute_response_payload();
18436        let server_execute_response = execute_response.clone();
18437        let listener = TcpListener::bind("127.0.0.1:0")?;
18438        let addr = listener.local_addr()?;
18439        let server = thread::spawn(move || -> std::io::Result<()> {
18440            use std::io::Write as _;
18441            let (mut socket, _) = listener.accept()?;
18442            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
18443
18444            assert_eq!(
18445                read_one_wire_data_payload(&mut socket),
18446                register_request,
18447                "successful CQN register request remains byte-identical"
18448            );
18449            socket.write_all(&data_packet(&register_response, true))?;
18450            socket.flush()?;
18451
18452            assert_eq!(
18453                read_one_wire_data_payload(&mut socket),
18454                unregister_request,
18455                "successful CQN unregister must follow directly without a spurious BREAK"
18456            );
18457            socket.write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))?;
18458            socket.flush()?;
18459
18460            assert_eq!(
18461                read_one_wire_packet(&mut socket),
18462                TNS_PACKET_TYPE_DATA,
18463                "fresh execute must follow both completed CQN responses directly"
18464            );
18465            socket.write_all(&data_packet(&server_execute_response, true))?;
18466            socket.flush()
18467        });
18468
18469        let runtime = build_io_runtime()?;
18470        runtime.block_on(async {
18471            let cx = test_cx()?;
18472            let stream = TcpStream::connect(addr).await?;
18473            let (read, write) = transport::plain_split(stream);
18474            let mut connection = loopback_connection(read, write);
18475            connection.supports_end_of_response = false;
18476
18477            let registered = connection
18478                .subscribe_register(
18479                    &cx,
18480                    oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18481                    None,
18482                    oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18483                    0,
18484                    10,
18485                    0,
18486                    0,
18487                    0,
18488                )
18489                .await?;
18490            assert_eq!(registered.registration_id, 302);
18491            assert_eq!(registered.client_id.as_deref(), Some(CLIENT_ID));
18492            assert_eq!(
18493                connection.core.recovery.phase(),
18494                SessionRecoveryPhase::Ready,
18495                "completed classic CQN register response must disarm its guard"
18496            );
18497
18498            connection
18499                .subscribe_unregister(
18500                    &cx,
18501                    registered.registration_id,
18502                    CLIENT_ID,
18503                    oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
18504                    None,
18505                    oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
18506                    0,
18507                    10,
18508                    0,
18509                    0,
18510                    0,
18511                )
18512                .await?;
18513            assert_eq!(
18514                connection.core.recovery.phase(),
18515                SessionRecoveryPhase::Ready,
18516                "completed classic CQN unregister response must disarm its guard"
18517            );
18518
18519            let reused = connection
18520                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18521                .await?;
18522            assert_eq!(reused, sequential_op_decode(&execute_response));
18523            assert_eq!(
18524                connection.core.recovery.phase(),
18525                SessionRecoveryPhase::Ready
18526            );
18527            Ok::<_, Error>(())
18528        })?;
18529
18530        server.join().expect("successful CQN server joins")?;
18531        Ok(())
18532    }
18533
18534    #[test]
18535    fn dropped_sessionless_begin_mid_response_drains_before_connection_reuse() -> Result<()> {
18536        const FRESH_SQL: &str = "select value from sessionless_begin_reuse_fixture";
18537        const TRANSACTION_ID: &[u8] = b"qa-sessionless-begin";
18538
18539        let expected_request = build_tpc_txn_switch_payload_with_seq(
18540            1,
18541            0,
18542            TNS_TPC_TXN_START,
18543            TPC_TXN_FLAGS_NEW | TPC_TXN_FLAGS_SESSIONLESS,
18544            30,
18545            Some(TRANSACTION_ID),
18546        );
18547        let listener = TcpListener::bind("127.0.0.1:0")?;
18548        let addr = listener.local_addr()?;
18549        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18550        let server = thread::spawn(move || {
18551            serve_dropped_response_recovery(
18552                listener,
18553                expected_request,
18554                vec![TNS_MSG_TYPE_END_OF_RESPONSE],
18555                request_seen_tx,
18556            )
18557        });
18558
18559        let runtime = build_io_runtime()?;
18560        let outcome = runtime.block_on(async {
18561            let cx = test_cx()?;
18562            let stream = TcpStream::connect(addr).await?;
18563            let (read, write) = transport::plain_split(stream);
18564            let mut connection = loopback_connection(read, write);
18565
18566            {
18567                let mut begin =
18568                    pin!(connection.begin_sessionless_transaction(&cx, TRANSACTION_ID, 30, false,));
18569                let first = poll_fn(|task_cx| Poll::Ready(begin.as_mut().poll(task_cx))).await;
18570                assert!(
18571                    matches!(first, Poll::Pending),
18572                    "sessionless begin must be waiting for its response before drop"
18573                );
18574                request_seen_rx
18575                    .recv_timeout(Duration::from_secs(2))
18576                    .expect("server observed sessionless begin request");
18577            }
18578
18579            let phase_after_drop = connection.core.recovery.phase();
18580            let reused = connection
18581                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18582                .await;
18583            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18584        });
18585
18586        let recovered = server.join().expect("sessionless begin server joins")?;
18587        let (phase_after_drop, reused, final_phase) = outcome?;
18588        let reused =
18589            reused.expect("fresh execute must not decode the stranded sessionless response");
18590        assert_eq!(
18591            reused,
18592            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
18593            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18594            "reuse must decode its own response byte-identically"
18595        );
18596        assert!(recovered, "reuse must take the BREAK/drain branch");
18597        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18598        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18599        Ok(())
18600    }
18601
18602    #[test]
18603    fn dropped_sessionless_suspend_mid_response_drains_before_connection_reuse() -> Result<()> {
18604        const FRESH_SQL: &str = "select value from sessionless_suspend_reuse_fixture";
18605        const TRANSACTION_ID: &[u8] = b"qa-sessionless-suspend";
18606
18607        let expected_request = build_tpc_txn_switch_payload_with_seq(
18608            1,
18609            0,
18610            TNS_TPC_TXN_DETACH,
18611            TPC_TXN_FLAGS_SESSIONLESS,
18612            0,
18613            None,
18614        );
18615        let listener = TcpListener::bind("127.0.0.1:0")?;
18616        let addr = listener.local_addr()?;
18617        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18618        let server = thread::spawn(move || {
18619            serve_dropped_response_recovery(
18620                listener,
18621                expected_request,
18622                vec![TNS_MSG_TYPE_END_OF_RESPONSE],
18623                request_seen_tx,
18624            )
18625        });
18626
18627        let runtime = build_io_runtime()?;
18628        let outcome = runtime.block_on(async {
18629            let cx = test_cx()?;
18630            let stream = TcpStream::connect(addr).await?;
18631            let (read, write) = transport::plain_split(stream);
18632            let mut connection = loopback_connection(read, write);
18633            connection.sessionless_data = Some(SessionlessData {
18634                transaction_id: TRANSACTION_ID.to_vec(),
18635                timeout: 30,
18636                operation: TNS_TPC_TXN_START,
18637                flags: TPC_TXN_FLAGS_NEW,
18638                piggyback_pending: false,
18639                started_on_server: false,
18640            });
18641
18642            {
18643                let mut suspend = pin!(connection.suspend_sessionless_transaction(&cx));
18644                let first = poll_fn(|task_cx| Poll::Ready(suspend.as_mut().poll(task_cx))).await;
18645                assert!(
18646                    matches!(first, Poll::Pending),
18647                    "sessionless suspend must be waiting for its response before drop"
18648                );
18649                request_seen_rx
18650                    .recv_timeout(Duration::from_secs(2))
18651                    .expect("server observed sessionless suspend request");
18652            }
18653
18654            let phase_after_drop = connection.core.recovery.phase();
18655            let reused = connection
18656                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18657                .await;
18658            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18659        });
18660
18661        let recovered = server.join().expect("sessionless suspend server joins")?;
18662        let (phase_after_drop, reused, final_phase) = outcome?;
18663        let reused =
18664            reused.expect("fresh execute must not decode the stranded sessionless response");
18665        assert_eq!(
18666            reused,
18667            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
18668            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18669            "reuse must decode its own response byte-identically"
18670        );
18671        assert!(recovered, "reuse must take the BREAK/drain branch");
18672        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18673        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18674        Ok(())
18675    }
18676
18677    #[test]
18678    fn dropped_tpc_begin_mid_response_drains_before_connection_reuse() -> Result<()> {
18679        const FRESH_SQL: &str = "select value from tpc_begin_reuse_fixture";
18680        const GTID: &[u8] = b"qa-tpc-begin";
18681        const BQUAL: &[u8] = b"branch";
18682
18683        let xid = TpcXid {
18684            format_id: 4400,
18685            global_transaction_id: GTID,
18686            branch_qualifier: BQUAL,
18687        };
18688        let expected_request = build_tpc_switch_payload_with_seq_and_version(
18689            1,
18690            TNS_TPC_TXN_START,
18691            TPC_TXN_FLAGS_NEW,
18692            0,
18693            Some(&xid),
18694            None,
18695            ClientCapabilities::default().ttc_field_version,
18696        );
18697        let listener = TcpListener::bind("127.0.0.1:0")?;
18698        let addr = listener.local_addr()?;
18699        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18700        let server = thread::spawn(move || {
18701            serve_dropped_response_recovery(
18702                listener,
18703                expected_request,
18704                vec![TNS_MSG_TYPE_END_OF_RESPONSE],
18705                request_seen_tx,
18706            )
18707        });
18708
18709        let runtime = build_io_runtime()?;
18710        let outcome = runtime.block_on(async {
18711            let cx = test_cx()?;
18712            let stream = TcpStream::connect(addr).await?;
18713            let (read, write) = transport::plain_split(stream);
18714            let mut connection = loopback_connection(read, write);
18715
18716            {
18717                let mut begin =
18718                    pin!(connection.tpc_begin(&cx, 4400, GTID, BQUAL, TPC_TXN_FLAGS_NEW, 0,));
18719                let first = poll_fn(|task_cx| Poll::Ready(begin.as_mut().poll(task_cx))).await;
18720                assert!(
18721                    matches!(first, Poll::Pending),
18722                    "TPC begin must be waiting for its response before drop"
18723                );
18724                request_seen_rx
18725                    .recv_timeout(Duration::from_secs(2))
18726                    .expect("server observed TPC begin request");
18727            }
18728
18729            let phase_after_drop = connection.core.recovery.phase();
18730            let reused = connection
18731                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18732                .await;
18733            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18734        });
18735
18736        let recovered = server.join().expect("TPC begin server joins")?;
18737        let (phase_after_drop, reused, final_phase) = outcome?;
18738        let reused =
18739            reused.expect("fresh execute must not decode the stranded TPC switch response");
18740        assert_eq!(
18741            reused,
18742            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
18743            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18744            "reuse must decode its own response byte-identically"
18745        );
18746        assert!(recovered, "reuse must take the BREAK/drain branch");
18747        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18748        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18749        Ok(())
18750    }
18751
18752    #[test]
18753    fn dropped_tpc_commit_mid_response_drains_before_connection_reuse() -> Result<()> {
18754        const FRESH_SQL: &str = "select value from tpc_commit_reuse_fixture";
18755        const GTID: &[u8] = b"qa-tpc-commit";
18756        const BQUAL: &[u8] = b"branch";
18757
18758        let xid = TpcXid {
18759            format_id: 4400,
18760            global_transaction_id: GTID,
18761            branch_qualifier: BQUAL,
18762        };
18763        let expected_request = build_tpc_change_state_payload_with_seq_and_version(
18764            1,
18765            TNS_TPC_TXN_COMMIT,
18766            TNS_TPC_TXN_STATE_READ_ONLY,
18767            0,
18768            Some(&xid),
18769            None,
18770            ClientCapabilities::default().ttc_field_version,
18771        );
18772        let listener = TcpListener::bind("127.0.0.1:0")?;
18773        let addr = listener.local_addr()?;
18774        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18775        let server = thread::spawn(move || {
18776            serve_dropped_response_recovery(
18777                listener,
18778                expected_request,
18779                vec![TNS_MSG_TYPE_END_OF_RESPONSE],
18780                request_seen_tx,
18781            )
18782        });
18783
18784        let runtime = build_io_runtime()?;
18785        let outcome = runtime.block_on(async {
18786            let cx = test_cx()?;
18787            let stream = TcpStream::connect(addr).await?;
18788            let (read, write) = transport::plain_split(stream);
18789            let mut connection = loopback_connection(read, write);
18790
18791            {
18792                let mut commit = pin!(connection.tpc_commit(&cx, Some((4400, GTID, BQUAL)), true,));
18793                let first = poll_fn(|task_cx| Poll::Ready(commit.as_mut().poll(task_cx))).await;
18794                assert!(
18795                    matches!(first, Poll::Pending),
18796                    "TPC commit must be waiting for its response before drop"
18797                );
18798                request_seen_rx
18799                    .recv_timeout(Duration::from_secs(2))
18800                    .expect("server observed TPC commit request");
18801            }
18802
18803            let phase_after_drop = connection.core.recovery.phase();
18804            let reused = connection
18805                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18806                .await;
18807            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18808        });
18809
18810        let recovered = server.join().expect("TPC commit server joins")?;
18811        let (phase_after_drop, reused, final_phase) = outcome?;
18812        let reused = reused.expect("fresh execute must not decode the stranded TPC response");
18813        assert_eq!(
18814            reused,
18815            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
18816            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18817            "reuse must decode its own response byte-identically"
18818        );
18819        assert!(recovered, "reuse must take the BREAK/drain branch");
18820        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18821        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18822        Ok(())
18823    }
18824
18825    #[test]
18826    fn successful_tpc_round_trips_disarm_recovery() -> Result<()> {
18827        const GTID: &[u8] = b"qa-tpc-success";
18828        const BQUAL: &[u8] = b"branch";
18829
18830        let xid = TpcXid {
18831            format_id: 4400,
18832            global_transaction_id: GTID,
18833            branch_qualifier: BQUAL,
18834        };
18835        let expected_begin = build_tpc_switch_payload_with_seq_and_version(
18836            1,
18837            TNS_TPC_TXN_START,
18838            TPC_TXN_FLAGS_NEW,
18839            0,
18840            Some(&xid),
18841            None,
18842            ClientCapabilities::default().ttc_field_version,
18843        );
18844        let expected_commit = build_tpc_change_state_payload_with_seq_and_version(
18845            2,
18846            TNS_TPC_TXN_COMMIT,
18847            TNS_TPC_TXN_STATE_READ_ONLY,
18848            0,
18849            Some(&xid),
18850            Some(&[]),
18851            ClientCapabilities::default().ttc_field_version,
18852        );
18853        let mut commit_response = oracledb_protocol::wire::TtcWriter::new();
18854        commit_response.write_u8(oracledb_protocol::thin::TNS_MSG_TYPE_PARAMETER);
18855        commit_response.write_ub4(TNS_TPC_TXN_STATE_READ_ONLY);
18856        commit_response.write_u8(TNS_MSG_TYPE_END_OF_RESPONSE);
18857        let commit_response = commit_response.into_bytes();
18858
18859        let listener = TcpListener::bind("127.0.0.1:0")?;
18860        let addr = listener.local_addr()?;
18861        let server = thread::spawn(move || -> std::io::Result<()> {
18862            use std::io::Write as _;
18863            let (mut socket, _) = listener.accept()?;
18864            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
18865
18866            assert_eq!(read_one_wire_data_payload(&mut socket), expected_begin);
18867            socket.write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))?;
18868            socket.flush()?;
18869
18870            assert_eq!(read_one_wire_data_payload(&mut socket), expected_commit);
18871            socket.write_all(&data_packet(&commit_response, true))?;
18872            socket.flush()
18873        });
18874
18875        let runtime = build_io_runtime()?;
18876        runtime.block_on(async {
18877            let cx = test_cx()?;
18878            let stream = TcpStream::connect(addr).await?;
18879            let (read, write) = transport::plain_split(stream);
18880            let mut connection = loopback_connection(read, write);
18881
18882            connection
18883                .tpc_begin(&cx, 4400, GTID, BQUAL, TPC_TXN_FLAGS_NEW, 0)
18884                .await?;
18885            assert_eq!(
18886                connection.core.recovery.phase(),
18887                SessionRecoveryPhase::Ready
18888            );
18889            connection
18890                .tpc_commit(&cx, Some((4400, GTID, BQUAL)), true)
18891                .await?;
18892            assert_eq!(
18893                connection.core.recovery.phase(),
18894                SessionRecoveryPhase::Ready
18895            );
18896            Ok::<_, Error>(())
18897        })?;
18898
18899        server.join().expect("successful TPC server joins")?;
18900        Ok(())
18901    }
18902
18903    #[test]
18904    fn dropped_direct_path_prepare_mid_response_drains_before_connection_reuse() -> Result<()> {
18905        const FRESH_SQL: &str = "select value from dpl_prepare_reuse_fixture";
18906        const CURSOR_ID: u16 = 73;
18907
18908        let column_names = Vec::<String>::new();
18909        let expected_request =
18910            oracledb_protocol::dpl::build_direct_path_prepare_payload_with_version(
18911                "QA",
18912                "DPL_DROP",
18913                &column_names,
18914                1,
18915                ClientCapabilities::default().ttc_field_version,
18916            )?;
18917        let listener = TcpListener::bind("127.0.0.1:0")?;
18918        let addr = listener.local_addr()?;
18919        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18920        let server = thread::spawn(move || {
18921            serve_dropped_response_recovery(
18922                listener,
18923                expected_request,
18924                synthetic_direct_path_prepare_response_payload(CURSOR_ID),
18925                request_seen_tx,
18926            )
18927        });
18928
18929        let runtime = build_io_runtime()?;
18930        let outcome = runtime.block_on(async {
18931            let cx = test_cx()?;
18932            let stream = TcpStream::connect(addr).await?;
18933            let (read, write) = transport::plain_split(stream);
18934            let mut connection = loopback_connection(read, write);
18935
18936            {
18937                let mut prepare =
18938                    pin!(connection.direct_path_prepare(&cx, "QA", "DPL_DROP", &column_names,));
18939                let first = poll_fn(|task_cx| Poll::Ready(prepare.as_mut().poll(task_cx))).await;
18940                assert!(
18941                    matches!(first, Poll::Pending),
18942                    "direct path prepare must await its response before drop"
18943                );
18944                request_seen_rx
18945                    .recv_timeout(Duration::from_secs(2))
18946                    .expect("server observed direct path prepare request");
18947            }
18948
18949            let phase_after_drop = connection.core.recovery.phase();
18950            let reused = connection
18951                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
18952                .await;
18953            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
18954        });
18955
18956        let recovered = server.join().expect("direct path prepare server joins")?;
18957        let (phase_after_drop, reused, final_phase) = outcome?;
18958        let reused = reused.expect("fresh execute must not decode the stranded DPL response");
18959        assert_eq!(
18960            reused,
18961            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
18962            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
18963            "reuse must decode its own response byte-identically"
18964        );
18965        assert!(recovered, "reuse must take the BREAK/drain branch");
18966        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
18967        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
18968        Ok(())
18969    }
18970
18971    #[test]
18972    fn dropped_direct_path_load_stream_mid_response_drains_before_connection_reuse() -> Result<()> {
18973        const FRESH_SQL: &str = "select value from dpl_stream_reuse_fixture";
18974        const CURSOR_ID: u16 = 73;
18975
18976        let stream = oracledb_protocol::dpl::encode_direct_path_rows(&[], &[], 1)?;
18977        let expected_request =
18978            oracledb_protocol::dpl::build_direct_path_load_stream_payload_with_version(
18979                CURSOR_ID,
18980                &stream,
18981                1,
18982                ClientCapabilities::default().ttc_field_version,
18983            )?;
18984        let listener = TcpListener::bind("127.0.0.1:0")?;
18985        let addr = listener.local_addr()?;
18986        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
18987        let server = thread::spawn(move || {
18988            serve_dropped_response_recovery(
18989                listener,
18990                expected_request,
18991                synthetic_direct_path_simple_response_payload(),
18992                request_seen_tx,
18993            )
18994        });
18995
18996        let runtime = build_io_runtime()?;
18997        let outcome = runtime.block_on(async {
18998            let cx = test_cx()?;
18999            let stream_socket = TcpStream::connect(addr).await?;
19000            let (read, write) = transport::plain_split(stream_socket);
19001            let mut connection = loopback_connection(read, write);
19002
19003            {
19004                let mut load = pin!(connection.direct_path_load_stream(&cx, CURSOR_ID, &stream));
19005                let first = poll_fn(|task_cx| Poll::Ready(load.as_mut().poll(task_cx))).await;
19006                assert!(
19007                    matches!(first, Poll::Pending),
19008                    "direct path load stream must await its response before drop"
19009                );
19010                request_seen_rx
19011                    .recv_timeout(Duration::from_secs(2))
19012                    .expect("server observed direct path load stream request");
19013            }
19014
19015            let phase_after_drop = connection.core.recovery.phase();
19016            let reused = connection
19017                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19018                .await;
19019            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
19020        });
19021
19022        let recovered = server.join().expect("direct path load server joins")?;
19023        let (phase_after_drop, reused, final_phase) = outcome?;
19024        let reused = reused.expect("fresh execute must not decode the stranded DPL response");
19025        assert_eq!(
19026            reused,
19027            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
19028            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
19029            "reuse must decode its own response byte-identically"
19030        );
19031        assert!(recovered, "reuse must take the BREAK/drain branch");
19032        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
19033        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
19034        Ok(())
19035    }
19036
19037    #[test]
19038    fn dropped_direct_path_op_mid_response_drains_before_connection_reuse() -> Result<()> {
19039        const FRESH_SQL: &str = "select value from dpl_op_reuse_fixture";
19040        const CURSOR_ID: u16 = 73;
19041
19042        let expected_request = oracledb_protocol::dpl::build_direct_path_op_payload_with_version(
19043            CURSOR_ID,
19044            oracledb_protocol::dpl::TNS_DP_OP_FINISH,
19045            1,
19046            ClientCapabilities::default().ttc_field_version,
19047        );
19048        let listener = TcpListener::bind("127.0.0.1:0")?;
19049        let addr = listener.local_addr()?;
19050        let (request_seen_tx, request_seen_rx) = std::sync::mpsc::channel();
19051        let server = thread::spawn(move || {
19052            serve_dropped_response_recovery(
19053                listener,
19054                expected_request,
19055                synthetic_direct_path_simple_response_payload(),
19056                request_seen_tx,
19057            )
19058        });
19059
19060        let runtime = build_io_runtime()?;
19061        let outcome = runtime.block_on(async {
19062            let cx = test_cx()?;
19063            let stream = TcpStream::connect(addr).await?;
19064            let (read, write) = transport::plain_split(stream);
19065            let mut connection = loopback_connection(read, write);
19066
19067            {
19068                let mut op = pin!(connection.direct_path_op(
19069                    &cx,
19070                    CURSOR_ID,
19071                    oracledb_protocol::dpl::TNS_DP_OP_FINISH,
19072                ));
19073                let first = poll_fn(|task_cx| Poll::Ready(op.as_mut().poll(task_cx))).await;
19074                assert!(
19075                    matches!(first, Poll::Pending),
19076                    "direct path op must await its response before drop"
19077                );
19078                request_seen_rx
19079                    .recv_timeout(Duration::from_secs(2))
19080                    .expect("server observed direct path op request");
19081            }
19082
19083            let phase_after_drop = connection.core.recovery.phase();
19084            let reused = connection
19085                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19086                .await;
19087            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
19088        });
19089
19090        let recovered = server.join().expect("direct path op server joins")?;
19091        let (phase_after_drop, reused, final_phase) = outcome?;
19092        let reused = reused.expect("fresh execute must not decode the stranded DPL response");
19093        assert_eq!(
19094            reused,
19095            // ubs:ignore — decodes an Oracle TTC test fixture, not a JWT.
19096            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
19097            "reuse must decode its own response byte-identically"
19098        );
19099        assert!(recovered, "reuse must take the BREAK/drain branch");
19100        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
19101        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
19102        Ok(())
19103    }
19104
19105    #[test]
19106    fn successful_direct_path_round_trips_disarm_recovery_before_reuse() -> Result<()> {
19107        const FRESH_SQL: &str = "select value from dpl_success_fixture";
19108        const CURSOR_ID: u16 = 73;
19109
19110        let column_names = Vec::<String>::new();
19111        let stream = oracledb_protocol::dpl::encode_direct_path_rows(&[], &[], 1)?;
19112        let field_version = ClientCapabilities::default().ttc_field_version;
19113        let expected_prepare =
19114            oracledb_protocol::dpl::build_direct_path_prepare_payload_with_version(
19115                "QA",
19116                "DPL_SUCCESS",
19117                &column_names,
19118                1,
19119                field_version,
19120            )?;
19121        let expected_load =
19122            oracledb_protocol::dpl::build_direct_path_load_stream_payload_with_version(
19123                CURSOR_ID,
19124                &stream,
19125                2,
19126                field_version,
19127            )?;
19128        let expected_op = oracledb_protocol::dpl::build_direct_path_op_payload_with_version(
19129            CURSOR_ID,
19130            oracledb_protocol::dpl::TNS_DP_OP_FINISH,
19131            3,
19132            field_version,
19133        );
19134        let execute_response = synthetic_pipeline_execute_response_payload();
19135        let server_execute_response = execute_response.clone();
19136        let listener = TcpListener::bind("127.0.0.1:0")?;
19137        let addr = listener.local_addr()?;
19138        let server = thread::spawn(move || -> std::io::Result<()> {
19139            use std::io::Write as _;
19140            let (mut socket, _) = listener.accept()?;
19141            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
19142
19143            assert_eq!(read_one_wire_data_payload(&mut socket), expected_prepare);
19144            socket.write_all(&data_packet(
19145                &synthetic_direct_path_prepare_response_payload(CURSOR_ID),
19146                true,
19147            ))?;
19148            socket.flush()?;
19149
19150            assert_eq!(read_one_wire_data_payload(&mut socket), expected_load);
19151            socket.write_all(&data_packet(
19152                &synthetic_direct_path_simple_response_payload(),
19153                true,
19154            ))?;
19155            socket.flush()?;
19156
19157            assert_eq!(read_one_wire_data_payload(&mut socket), expected_op);
19158            socket.write_all(&data_packet(
19159                &synthetic_direct_path_simple_response_payload(),
19160                true,
19161            ))?;
19162            socket.flush()?;
19163
19164            assert_eq!(
19165                read_one_wire_packet(&mut socket),
19166                TNS_PACKET_TYPE_DATA,
19167                "reuse after DPL op must not send a spurious BREAK"
19168            );
19169            socket.write_all(&data_packet(&server_execute_response, true))?;
19170            socket.flush()
19171        });
19172
19173        let runtime = build_io_runtime()?;
19174        runtime.block_on(async {
19175            let cx = test_cx()?;
19176            let socket = TcpStream::connect(addr).await?;
19177            let (read, write) = transport::plain_split(socket);
19178            let mut connection = loopback_connection(read, write);
19179
19180            let prepared = connection
19181                .direct_path_prepare(&cx, "QA", "DPL_SUCCESS", &column_names)
19182                .await?;
19183            assert_eq!(prepared.cursor_id, CURSOR_ID);
19184            assert_eq!(
19185                connection.core.recovery.phase(),
19186                SessionRecoveryPhase::Ready
19187            );
19188
19189            connection
19190                .direct_path_load_stream(&cx, CURSOR_ID, &stream)
19191                .await?;
19192            assert_eq!(
19193                connection.core.recovery.phase(),
19194                SessionRecoveryPhase::Ready
19195            );
19196
19197            connection
19198                .direct_path_op(&cx, CURSOR_ID, oracledb_protocol::dpl::TNS_DP_OP_FINISH)
19199                .await?;
19200            assert_eq!(
19201                connection.core.recovery.phase(),
19202                SessionRecoveryPhase::Ready
19203            );
19204
19205            let reused = connection
19206                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19207                .await?;
19208            assert_eq!(reused, sequential_op_decode(&execute_response));
19209            assert_eq!(
19210                connection.core.recovery.phase(),
19211                SessionRecoveryPhase::Ready
19212            );
19213            Ok::<_, Error>(())
19214        })?;
19215
19216        server
19217            .join()
19218            .expect("successful direct path server joins")?;
19219        Ok(())
19220    }
19221
19222    #[test]
19223    fn precancelled_direct_path_prepare_writes_nothing_and_keeps_wire_ready() -> Result<()> {
19224        let listener = TcpListener::bind("127.0.0.1:0")?;
19225        let addr = listener.local_addr()?;
19226        let server = thread::spawn(move || -> std::io::Result<bool> {
19227            let (mut socket, _) = listener.accept()?;
19228            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
19229            let mut byte = [0u8; 1];
19230            match socket.read(&mut byte) {
19231                Ok(0) => Ok(false),
19232                Ok(_) => Ok(true),
19233                Err(err)
19234                    if matches!(
19235                        err.kind(),
19236                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
19237                    ) =>
19238                {
19239                    Ok(false)
19240                }
19241                Err(err) => Err(err),
19242            }
19243        });
19244
19245        let runtime = build_io_runtime()?;
19246        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
19247            let cx = test_cx()?;
19248            let stream = TcpStream::connect(addr).await?;
19249            let (read, write) = transport::plain_split(stream);
19250            let mut connection = loopback_connection(read, write);
19251            let sequence_before = connection.ttc_seq_num;
19252            cx.cancel_fast(CancelKind::User);
19253
19254            let err = connection
19255                .direct_path_prepare(&cx, "QA", "DPL_PRE_CANCEL", &[])
19256                .await
19257                .expect_err("pending cancellation stops before DPL PREPARE");
19258            assert!(matches!(err, Error::Cancelled), "{err:?}");
19259            Ok::<_, Error>((
19260                connection.core.recovery.phase(),
19261                sequence_before,
19262                connection.ttc_seq_num,
19263            ))
19264        })?;
19265
19266        assert!(
19267            !server
19268                .join()
19269                .expect("pre-cancel direct path server joins")?,
19270            "pre-cancelled DPL PREPARE must not write any wire bytes"
19271        );
19272        assert_eq!(phase, SessionRecoveryPhase::Ready);
19273        assert_eq!(sequence_after, sequence_before);
19274        Ok(())
19275    }
19276
19277    #[test]
19278    fn precancelled_subscribe_register_writes_nothing_and_keeps_wire_ready() -> Result<()> {
19279        let listener = TcpListener::bind("127.0.0.1:0")?;
19280        let addr = listener.local_addr()?;
19281        let server = thread::spawn(move || -> std::io::Result<bool> {
19282            let (mut socket, _) = listener.accept()?;
19283            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
19284            let mut byte = [0u8; 1];
19285            match socket.read(&mut byte) {
19286                Ok(0) => Ok(false),
19287                Ok(_) => Ok(true),
19288                Err(err)
19289                    if matches!(
19290                        err.kind(),
19291                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
19292                    ) =>
19293                {
19294                    Ok(false)
19295                }
19296                Err(err) => Err(err),
19297            }
19298        });
19299
19300        let runtime = build_io_runtime()?;
19301        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
19302            let cx = test_cx()?;
19303            let stream = TcpStream::connect(addr).await?;
19304            let (read, write) = transport::plain_split(stream);
19305            let mut connection = loopback_connection(read, write);
19306            let sequence_before = connection.ttc_seq_num;
19307            cx.cancel_fast(CancelKind::User);
19308
19309            let err = connection
19310                .subscribe_register(
19311                    &cx,
19312                    oracledb_protocol::thin::TNS_SUBSCR_NAMESPACE_DBCHANGE,
19313                    None,
19314                    oracledb_protocol::thin::SUBSCR_QOS_ROWIDS,
19315                    0,
19316                    10,
19317                    0,
19318                    0,
19319                    0,
19320                )
19321                .await
19322                .expect_err("pending cancellation stops before CQN REGISTER");
19323            assert!(matches!(err, Error::Cancelled), "{err:?}");
19324            Ok::<_, Error>((
19325                connection.core.recovery.phase(),
19326                sequence_before,
19327                connection.ttc_seq_num,
19328            ))
19329        })?;
19330
19331        assert!(
19332            !server
19333                .join()
19334                .expect("pre-cancel CQN register server joins")?,
19335            "pre-cancelled CQN REGISTER must not write any wire bytes"
19336        );
19337        assert_eq!(phase, SessionRecoveryPhase::Ready);
19338        assert_eq!(sequence_after, sequence_before);
19339        Ok(())
19340    }
19341
19342    #[test]
19343    fn dropped_lob_read_mid_response_drains_before_connection_reuse() -> Result<()> {
19344        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
19345        const FRESH_SQL: &str = "select value from lob_read_reuse_fixture";
19346
19347        let locator = vec![0x11; 4];
19348        let stranded_response = synthetic_lob_read_response_payload(&locator, b"x", 1);
19349        let server_stranded_response = stranded_response.clone();
19350        let listener = TcpListener::bind("127.0.0.1:0")?;
19351        let addr = listener.local_addr()?;
19352        let (lob_seen_tx, lob_seen_rx) = std::sync::mpsc::channel();
19353        let server = thread::spawn(move || -> std::io::Result<bool> {
19354            use std::io::Write as _;
19355            let (mut socket, _) = listener.accept()?;
19356            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
19357
19358            assert_eq!(
19359                read_one_wire_packet(&mut socket),
19360                TNS_PACKET_TYPE_DATA,
19361                "LOB read must send a DATA request"
19362            );
19363            lob_seen_tx
19364                .send(())
19365                .expect("client waits for LOB read request proof");
19366
19367            let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
19368            if next_packet_type == TNS_PACKET_TYPE_MARKER {
19369                assert_eq!(
19370                    next_body,
19371                    vec![1, 0, TNS_MARKER_TYPE_BREAK],
19372                    "reuse must BREAK the stranded LOB read before its request"
19373                );
19374                socket.write_all(&data_packet(&server_stranded_response, true))?;
19375                socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
19376                assert_eq!(
19377                    read_marker_type(&mut socket),
19378                    TNS_MARKER_TYPE_RESET,
19379                    "LOB read drain must complete the RESET handshake"
19380                );
19381                socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
19382                socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
19383
19384                assert_eq!(
19385                    read_one_wire_packet(&mut socket),
19386                    TNS_PACKET_TYPE_DATA,
19387                    "fresh execute follows the completed drain"
19388                );
19389                socket.write_all(&data_packet(
19390                    &synthetic_pipeline_execute_response_payload(),
19391                    true,
19392                ))?;
19393                socket.flush()?;
19394                Ok(true)
19395            } else {
19396                assert_eq!(
19397                    next_packet_type, TNS_PACKET_TYPE_DATA,
19398                    "without recovery the next operation is sent directly"
19399                );
19400                socket.write_all(&data_packet(&server_stranded_response, true))?;
19401                socket.write_all(&data_packet(
19402                    &synthetic_pipeline_execute_response_payload(),
19403                    true,
19404                ))?;
19405                socket.flush()?;
19406                Ok(false)
19407            }
19408        });
19409
19410        let runtime = build_io_runtime()?;
19411        let outcome = runtime.block_on(async {
19412            let cx = test_cx()?;
19413            let stream = TcpStream::connect(addr).await?;
19414            let (read, write) = transport::plain_split(stream);
19415            let mut connection = loopback_connection(read, write);
19416
19417            {
19418                let mut read_lob = pin!(connection.read_lob(&cx, &locator, 1, 1));
19419                let first = poll_fn(|task_cx| Poll::Ready(read_lob.as_mut().poll(task_cx))).await;
19420                assert!(
19421                    matches!(first, Poll::Pending),
19422                    "LOB read must be waiting for its response before drop"
19423                );
19424                lob_seen_rx
19425                    .recv_timeout(Duration::from_secs(2))
19426                    .expect("server observed LOB read request");
19427            }
19428
19429            let phase_after_drop = connection.core.recovery.phase();
19430            let reused = connection
19431                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19432                .await;
19433            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
19434        });
19435
19436        let recovered = server.join().expect("LOB read server joins")?;
19437        let (phase_after_drop, reused, final_phase) = outcome?;
19438        let reused = reused.expect("fresh execute must not decode the stranded LOB response");
19439        assert_eq!(
19440            reused,
19441            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
19442            "reuse must decode its own response byte-identically"
19443        );
19444        assert!(recovered, "reuse must take the BREAK/drain branch");
19445        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
19446        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
19447        Ok(())
19448    }
19449
19450    #[test]
19451    fn dropped_aq_enqueue_mid_response_drains_before_connection_reuse() -> Result<()> {
19452        const TRAILING_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
19453        const FRESH_SQL: &str = "select value from aq_enqueue_reuse_fixture";
19454
19455        let msgid = [0x2a; 16];
19456        let stranded_response = synthetic_aq_enqueue_response_payload(&msgid);
19457        let server_stranded_response = stranded_response.clone();
19458        let listener = TcpListener::bind("127.0.0.1:0")?;
19459        let addr = listener.local_addr()?;
19460        let (aq_seen_tx, aq_seen_rx) = std::sync::mpsc::channel();
19461        let server = thread::spawn(move || -> std::io::Result<bool> {
19462            use std::io::Write as _;
19463            let (mut socket, _) = listener.accept()?;
19464            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
19465
19466            assert_eq!(
19467                read_one_wire_packet(&mut socket),
19468                TNS_PACKET_TYPE_DATA,
19469                "AQ enqueue must send a DATA request"
19470            );
19471            aq_seen_tx
19472                .send(())
19473                .expect("client waits for AQ enqueue request proof");
19474
19475            let (next_packet_type, next_body) = read_one_wire_packet_bytes(&mut socket);
19476            if next_packet_type == TNS_PACKET_TYPE_MARKER {
19477                assert_eq!(
19478                    next_body,
19479                    vec![1, 0, TNS_MARKER_TYPE_BREAK],
19480                    "reuse must BREAK the stranded AQ enqueue before its request"
19481                );
19482                socket.write_all(&data_packet(&server_stranded_response, true))?;
19483                socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
19484                assert_eq!(
19485                    read_marker_type(&mut socket),
19486                    TNS_MARKER_TYPE_RESET,
19487                    "AQ enqueue drain must complete the RESET handshake"
19488                );
19489                socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
19490                socket.write_all(&data_packet(TRAILING_CANCEL_ERROR, true))?;
19491
19492                assert_eq!(
19493                    read_one_wire_packet(&mut socket),
19494                    TNS_PACKET_TYPE_DATA,
19495                    "fresh execute follows the completed drain"
19496                );
19497                socket.write_all(&data_packet(
19498                    &synthetic_pipeline_execute_response_payload(),
19499                    true,
19500                ))?;
19501                socket.flush()?;
19502                Ok(true)
19503            } else {
19504                assert_eq!(
19505                    next_packet_type, TNS_PACKET_TYPE_DATA,
19506                    "without recovery the next operation is sent directly"
19507                );
19508                socket.write_all(&data_packet(&server_stranded_response, true))?;
19509                socket.write_all(&data_packet(
19510                    &synthetic_pipeline_execute_response_payload(),
19511                    true,
19512                ))?;
19513                socket.flush()?;
19514                Ok(false)
19515            }
19516        });
19517
19518        let runtime = build_io_runtime()?;
19519        let outcome = runtime.block_on(async {
19520            let cx = test_cx()?;
19521            let stream = TcpStream::connect(addr).await?;
19522            let (read, write) = transport::plain_split(stream);
19523            let mut connection = loopback_connection(read, write);
19524            let (queue, props, options) = synthetic_aq_enqueue_request();
19525
19526            {
19527                let mut enqueue = pin!(connection.aq_enq_one(&cx, &queue, &props, &options));
19528                let first = poll_fn(|task_cx| Poll::Ready(enqueue.as_mut().poll(task_cx))).await;
19529                assert!(
19530                    matches!(first, Poll::Pending),
19531                    "AQ enqueue must be waiting for its response before drop"
19532                );
19533                aq_seen_rx
19534                    .recv_timeout(Duration::from_secs(2))
19535                    .expect("server observed AQ enqueue request");
19536            }
19537
19538            let phase_after_drop = connection.core.recovery.phase();
19539            let reused = connection
19540                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19541                .await;
19542            Ok::<_, Error>((phase_after_drop, reused, connection.core.recovery.phase()))
19543        });
19544
19545        let recovered = server.join().expect("AQ enqueue server joins")?;
19546        let (phase_after_drop, reused, final_phase) = outcome?;
19547        let reused = reused.expect("fresh execute must not decode the stranded AQ response");
19548        assert_eq!(
19549            reused,
19550            sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
19551            "reuse must decode its own response byte-identically"
19552        );
19553        assert!(recovered, "reuse must take the BREAK/drain branch");
19554        assert_eq!(phase_after_drop, SessionRecoveryPhase::BreakSent);
19555        assert_eq!(final_phase, SessionRecoveryPhase::Ready);
19556        Ok(())
19557    }
19558
19559    #[test]
19560    fn successful_aq_enqueue_disarms_recovery_before_reuse() -> Result<()> {
19561        const FRESH_SQL: &str = "select value from aq_enqueue_success_fixture";
19562        let msgid = [0x2a; 16];
19563        let aq_response = synthetic_aq_enqueue_response_payload(&msgid);
19564        let execute_response = synthetic_pipeline_execute_response_payload();
19565        let server_execute_response = execute_response.clone();
19566        let listener = TcpListener::bind("127.0.0.1:0")?;
19567        let addr = listener.local_addr()?;
19568        let server = thread::spawn(move || -> std::io::Result<()> {
19569            use std::io::Write as _;
19570            let (mut socket, _) = listener.accept()?;
19571            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
19572
19573            assert_eq!(
19574                read_one_wire_packet(&mut socket),
19575                TNS_PACKET_TYPE_DATA,
19576                "AQ enqueue must send a DATA request"
19577            );
19578            socket.write_all(&data_packet(&aq_response, true))?;
19579            socket.flush()?;
19580
19581            assert_eq!(
19582                read_one_wire_packet(&mut socket),
19583                TNS_PACKET_TYPE_DATA,
19584                "a successful AQ enqueue must not cause a spurious BREAK on reuse"
19585            );
19586            socket.write_all(&data_packet(&server_execute_response, true))?;
19587            socket.flush()
19588        });
19589
19590        let runtime = build_io_runtime()?;
19591        runtime.block_on(async {
19592            let cx = test_cx()?;
19593            let stream = TcpStream::connect(addr).await?;
19594            let (read, write) = transport::plain_split(stream);
19595            let mut connection = loopback_connection(read, write);
19596            let (queue, props, options) = synthetic_aq_enqueue_request();
19597
19598            let assigned = connection.aq_enq_one(&cx, &queue, &props, &options).await?;
19599            assert_eq!(assigned.as_deref(), Some(&msgid[..]));
19600            assert_eq!(
19601                connection.core.recovery.phase(),
19602                SessionRecoveryPhase::Ready,
19603                "a completed AQ response must disarm its guard"
19604            );
19605
19606            let reused = connection
19607                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19608                .await?;
19609            assert_eq!(reused, sequential_op_decode(&execute_response));
19610            assert_eq!(
19611                connection.core.recovery.phase(),
19612                SessionRecoveryPhase::Ready
19613            );
19614            Ok::<_, Error>(())
19615        })?;
19616
19617        server.join().expect("successful AQ enqueue server joins")?;
19618        Ok(())
19619    }
19620
19621    #[test]
19622    fn precancelled_aq_enqueue_writes_nothing_and_keeps_wire_ready() -> Result<()> {
19623        let listener = TcpListener::bind("127.0.0.1:0")?;
19624        let addr = listener.local_addr()?;
19625        let server = thread::spawn(move || -> std::io::Result<bool> {
19626            let (mut socket, _) = listener.accept()?;
19627            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
19628            let mut byte = [0u8; 1];
19629            match socket.read(&mut byte) {
19630                Ok(0) => Ok(false),
19631                Ok(_) => Ok(true),
19632                Err(err)
19633                    if matches!(
19634                        err.kind(),
19635                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
19636                    ) =>
19637                {
19638                    Ok(false)
19639                }
19640                Err(err) => Err(err),
19641            }
19642        });
19643
19644        let runtime = build_io_runtime()?;
19645        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
19646            let cx = test_cx()?;
19647            let stream = TcpStream::connect(addr).await?;
19648            let (read, write) = transport::plain_split(stream);
19649            let mut connection = loopback_connection(read, write);
19650            let sequence_before = connection.ttc_seq_num;
19651            let (queue, props, options) = synthetic_aq_enqueue_request();
19652            cx.cancel_fast(CancelKind::User);
19653
19654            let err = connection
19655                .aq_enq_one(&cx, &queue, &props, &options)
19656                .await
19657                .expect_err("pending cancellation stops before AQ ENQUEUE");
19658            assert!(matches!(err, Error::Cancelled), "{err:?}");
19659            Ok::<_, Error>((
19660                connection.core.recovery.phase(),
19661                sequence_before,
19662                connection.ttc_seq_num,
19663            ))
19664        })?;
19665
19666        assert!(
19667            !server.join().expect("pre-cancel AQ enqueue server joins")?,
19668            "pre-cancelled AQ ENQUEUE must not write any wire bytes"
19669        );
19670        assert_eq!(phase, SessionRecoveryPhase::Ready);
19671        assert_eq!(sequence_after, sequence_before);
19672        Ok(())
19673    }
19674
19675    #[test]
19676    fn successful_lob_read_disarms_recovery_before_reuse() -> Result<()> {
19677        const FRESH_SQL: &str = "select value from lob_read_success_fixture";
19678        let locator = vec![0x11; 4];
19679        let replacement_locator = vec![0x22; 4];
19680        let lob_response = synthetic_lob_read_response_payload(&replacement_locator, b"abc", 3);
19681        let execute_response = synthetic_pipeline_execute_response_payload();
19682        let server_execute_response = execute_response.clone();
19683        let listener = TcpListener::bind("127.0.0.1:0")?;
19684        let addr = listener.local_addr()?;
19685        let server = thread::spawn(move || -> std::io::Result<()> {
19686            use std::io::Write as _;
19687            let (mut socket, _) = listener.accept()?;
19688            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
19689
19690            assert_eq!(
19691                read_one_wire_packet(&mut socket),
19692                TNS_PACKET_TYPE_DATA,
19693                "LOB read must send a DATA request"
19694            );
19695            socket.write_all(&data_packet(&lob_response, true))?;
19696            socket.flush()?;
19697
19698            assert_eq!(
19699                read_one_wire_packet(&mut socket),
19700                TNS_PACKET_TYPE_DATA,
19701                "a successful LOB read must not cause a spurious BREAK on reuse"
19702            );
19703            socket.write_all(&data_packet(&server_execute_response, true))?;
19704            socket.flush()
19705        });
19706
19707        let runtime = build_io_runtime()?;
19708        runtime.block_on(async {
19709            let cx = test_cx()?;
19710            let stream = TcpStream::connect(addr).await?;
19711            let (read, write) = transport::plain_split(stream);
19712            let mut connection = loopback_connection(read, write);
19713
19714            let result = connection.read_lob(&cx, &locator, 1, 3).await?;
19715            assert_eq!(result.data.as_deref(), Some(&b"abc"[..]));
19716            assert_eq!(result.locator, replacement_locator);
19717            assert_eq!(result.amount, 3);
19718            assert_eq!(
19719                connection.core.recovery.phase(),
19720                SessionRecoveryPhase::Ready,
19721                "a completed LOB response must disarm its guard"
19722            );
19723
19724            let reused = connection
19725                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19726                .await?;
19727            assert_eq!(reused, sequential_op_decode(&execute_response));
19728            assert_eq!(
19729                connection.core.recovery.phase(),
19730                SessionRecoveryPhase::Ready
19731            );
19732            Ok::<_, Error>(())
19733        })?;
19734
19735        server.join().expect("successful LOB read server joins")?;
19736        Ok(())
19737    }
19738
19739    #[test]
19740    fn precancelled_lob_read_writes_nothing_and_keeps_wire_ready() -> Result<()> {
19741        let listener = TcpListener::bind("127.0.0.1:0")?;
19742        let addr = listener.local_addr()?;
19743        let server = thread::spawn(move || -> std::io::Result<bool> {
19744            let (mut socket, _) = listener.accept()?;
19745            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
19746            let mut byte = [0u8; 1];
19747            match socket.read(&mut byte) {
19748                Ok(0) => Ok(false),
19749                Ok(_) => Ok(true),
19750                Err(err)
19751                    if matches!(
19752                        err.kind(),
19753                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
19754                    ) =>
19755                {
19756                    Ok(false)
19757                }
19758                Err(err) => Err(err),
19759            }
19760        });
19761
19762        let runtime = build_io_runtime()?;
19763        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
19764            let cx = test_cx()?;
19765            let stream = TcpStream::connect(addr).await?;
19766            let (read, write) = transport::plain_split(stream);
19767            let mut connection = loopback_connection(read, write);
19768            let sequence_before = connection.ttc_seq_num;
19769            cx.cancel_fast(CancelKind::User);
19770
19771            let err = connection
19772                .read_lob(&cx, &[0x11; 4], 1, 1)
19773                .await
19774                .expect_err("pending cancellation stops before LOB READ");
19775            assert!(matches!(err, Error::Cancelled), "{err:?}");
19776            Ok::<_, Error>((
19777                connection.core.recovery.phase(),
19778                sequence_before,
19779                connection.ttc_seq_num,
19780            ))
19781        })?;
19782
19783        assert!(
19784            !server.join().expect("pre-cancel LOB read server joins")?,
19785            "pre-cancelled LOB READ must not write any wire bytes"
19786        );
19787        assert_eq!(phase, SessionRecoveryPhase::Ready);
19788        assert_eq!(sequence_after, sequence_before);
19789        Ok(())
19790    }
19791
19792    #[test]
19793    fn precancelled_define_fetch_writes_nothing_and_keeps_wire_ready() -> Result<()> {
19794        const CURSOR_ID: u32 = 42;
19795        let listener = TcpListener::bind("127.0.0.1:0")?;
19796        let addr = listener.local_addr()?;
19797        let server = thread::spawn(move || -> std::io::Result<bool> {
19798            let (mut socket, _) = listener.accept()?;
19799            socket.set_read_timeout(Some(Duration::from_millis(300)))?;
19800            let mut byte = [0u8; 1];
19801            match socket.read(&mut byte) {
19802                Ok(0) => Ok(false),
19803                Ok(_) => Ok(true),
19804                Err(err)
19805                    if matches!(
19806                        err.kind(),
19807                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
19808                    ) =>
19809                {
19810                    Ok(false)
19811                }
19812                Err(err) => Err(err),
19813            }
19814        });
19815
19816        let runtime = build_io_runtime()?;
19817        let (phase, sequence_before, sequence_after) = runtime.block_on(async {
19818            let cx = test_cx()?;
19819            let stream = TcpStream::connect(addr).await?;
19820            let (read, write) = transport::plain_split(stream);
19821            let mut connection = loopback_connection(read, write);
19822            let sequence_before = connection.ttc_seq_num;
19823            cx.cancel_fast(CancelKind::User);
19824
19825            let err = connection
19826                .define_and_fetch_rows_with_columns(
19827                    &cx,
19828                    CURSOR_ID,
19829                    10,
19830                    &[ColumnMetadata::new(
19831                        "DOC",
19832                        oracledb_protocol::thin::ORA_TYPE_NUM_JSON,
19833                    )],
19834                    None,
19835                )
19836                .await
19837                .expect_err("pending cancellation stops before DEFINE-FETCH");
19838            assert!(matches!(err, Error::Cancelled), "{err:?}");
19839            Ok::<_, Error>((
19840                connection.core.recovery.phase(),
19841                sequence_before,
19842                connection.ttc_seq_num,
19843            ))
19844        })?;
19845
19846        assert!(
19847            !server.join().expect("pre-cancel server joins")?,
19848            "pre-cancelled DEFINE-FETCH must not write any wire bytes"
19849        );
19850        assert_eq!(phase, SessionRecoveryPhase::Ready);
19851        assert_eq!(sequence_after, sequence_before);
19852        Ok(())
19853    }
19854
19855    #[test]
19856    fn successful_define_fetch_disarms_recovery_before_reuse() -> Result<()> {
19857        const CURSOR_ID: u32 = 42;
19858        const FRESH_SQL: &str = "select value from define_fetch_success_fixture";
19859        let response = synthetic_pipeline_execute_response_payload();
19860        let server_response = response.clone();
19861        let listener = TcpListener::bind("127.0.0.1:0")?;
19862        let addr = listener.local_addr()?;
19863        let server = thread::spawn(move || -> std::io::Result<()> {
19864            use std::io::Write as _;
19865            let (mut socket, _) = listener.accept()?;
19866            socket.set_read_timeout(Some(Duration::from_secs(2)))?;
19867            assert_eq!(read_one_wire_packet(&mut socket), TNS_PACKET_TYPE_DATA);
19868            socket.write_all(&data_packet(&server_response, true))?;
19869            socket.flush()?;
19870
19871            assert_eq!(
19872                read_one_wire_packet(&mut socket),
19873                TNS_PACKET_TYPE_DATA,
19874                "a successful DEFINE-FETCH must not cause a spurious BREAK on reuse"
19875            );
19876            socket.write_all(&data_packet(&server_response, true))?;
19877            socket.flush()
19878        });
19879
19880        let runtime = build_io_runtime()?;
19881        runtime.block_on(async {
19882            let cx = test_cx()?;
19883            let stream = TcpStream::connect(addr).await?;
19884            let (read, write) = transport::plain_split(stream);
19885            let mut connection = loopback_connection(read, write);
19886            let columns = vec![ColumnMetadata::new(
19887                "VALUE",
19888                oracledb_protocol::thin::ORA_TYPE_NUM_NUMBER,
19889            )];
19890
19891            let defined = connection
19892                .define_and_fetch_rows_with_columns(&cx, CURSOR_ID, 10, &columns, None)
19893                .await?;
19894            assert_eq!(defined.rows.len(), 1);
19895            assert_eq!(
19896                connection.core.recovery.phase(),
19897                SessionRecoveryPhase::Ready
19898            );
19899
19900            let reused = connection
19901                .execute_raw(&cx, FRESH_SQL, 2, &[], ExecuteOptions::default(), None)
19902                .await?;
19903            assert_eq!(reused, sequential_op_decode(&response));
19904            assert_eq!(
19905                connection.core.recovery.phase(),
19906                SessionRecoveryPhase::Ready
19907            );
19908            Ok::<_, Error>(())
19909        })?;
19910
19911        server
19912            .join()
19913            .expect("successful define-fetch server joins")?;
19914        Ok(())
19915    }
19916
19917    #[test]
19918    fn oob_cancel_on_one_lane_leaves_other_lane_undisturbed() -> Result<()> {
19919        // a4-cn4 (rust-oracledb iec3.1.16) cross-lane isolation: an out-of-band
19920        // cancel — a bare BREAK fired from a `CancelHandle` (python-oracledb
19921        // `_break_external`) — on lane A must break + recover ONLY lane A. Lane B,
19922        // a fully independent `Connection` with its own socket, write mutex, and
19923        // recovery state, must complete its query untouched. The driver holds NO
19924        // cross-connection lock, so the isolation is structural; this pins it and
19925        // doubles as the no-cancel negative control (lane B never cancels).
19926        const A_INFLIGHT: &[u8] = b"lane-A in-flight response";
19927        const A_CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d]; // ORA-01013 user cancel
19928
19929        // --- lane A: scripts the out-of-band cancel choreography ---
19930        let listener_a = TcpListener::bind("127.0.0.1:0").expect("bind lane A");
19931        let addr_a = listener_a.local_addr().expect("lane A address");
19932        let server_a = thread::spawn(move || {
19933            use std::io::Write as _;
19934            let (mut socket, _) = listener_a.accept().expect("accept lane A");
19935            socket
19936                .set_read_timeout(Some(Duration::from_secs(5)))
19937                .expect("set read timeout");
19938            assert_eq!(
19939                read_marker_type(&mut socket),
19940                TNS_MARKER_TYPE_BREAK,
19941                "lane A must receive the out-of-band BREAK"
19942            );
19943            socket
19944                .write_all(&data_packet(A_INFLIGHT, true))
19945                .expect("write lane A in-flight response");
19946            socket
19947                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
19948                .expect("write lane A break-ack marker");
19949            assert_eq!(
19950                read_marker_type(&mut socket),
19951                TNS_MARKER_TYPE_RESET,
19952                "lane A owner drain answers the break marker with RESET"
19953            );
19954            socket
19955                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
19956                .expect("write lane A reset-confirm marker");
19957            socket
19958                .write_all(&data_packet(A_CANCEL_ERROR, true))
19959                .expect("write lane A trailing cancel error");
19960        });
19961
19962        // --- lane B: answers an ordinary query, never cancelled ---
19963        let listener_b = TcpListener::bind("127.0.0.1:0").expect("bind lane B");
19964        let addr_b = listener_b.local_addr().expect("lane B address");
19965        let server_b = thread::spawn(move || {
19966            use std::io::Write as _;
19967            let (mut socket, _) = listener_b.accept().expect("accept lane B");
19968            socket
19969                .set_read_timeout(Some(Duration::from_secs(5)))
19970                .expect("set read timeout");
19971            let _query_request = read_one_wire_packet(&mut socket);
19972            socket
19973                .write_all(&data_packet(
19974                    &synthetic_pipeline_execute_response_payload(),
19975                    true,
19976                ))
19977                .expect("write lane B query response");
19978            socket.flush().expect("flush lane B");
19979        });
19980
19981        let runtime = build_io_runtime()?;
19982        runtime.block_on(async {
19983            let cx = test_cx()?;
19984            let (read_a, write_a) = transport::plain_split(TcpStream::connect(addr_a).await?);
19985            let mut conn_a = loopback_connection(read_a, write_a);
19986            let (read_b, write_b) = transport::plain_split(TcpStream::connect(addr_b).await?);
19987            let mut conn_b = loopback_connection(read_b, write_b);
19988
19989            // Out-of-band cancel lane A: fire the bare BREAK from the handle, then
19990            // the owner drains the multi-stage cancel response back to Ready.
19991            let mut handle = conn_a.cancel_handle()?;
19992            handle.cancel(&cx).await?;
19993            assert_eq!(
19994                conn_a.core.recovery.phase(),
19995                SessionRecoveryPhase::BreakSent,
19996                "the out-of-band handle only requests the break"
19997            );
19998            conn_a.drain_cancel_response().await?;
19999            assert_eq!(
20000                conn_a.core.recovery.phase(),
20001                SessionRecoveryPhase::Ready,
20002                "lane A recovers cleanly from the out-of-band cancel"
20003            );
20004            assert!(
20005                !conn_a.is_dead(),
20006                "an out-of-band cancel keeps lane A's session alive"
20007            );
20008
20009            // Lane B — untouched by lane A's cancel — completes its query
20010            // correctly (the no-cancel negative control).
20011            let result_b = conn_b
20012                .execute_raw(
20013                    &cx,
20014                    "select value from synthetic_fixture",
20015                    2,
20016                    &[],
20017                    ExecuteOptions::default(),
20018                    None,
20019                )
20020                .await?;
20021            assert_eq!(
20022                result_b,
20023                sequential_op_decode(&synthetic_pipeline_execute_response_payload()),
20024                "lane B's query is undisturbed by lane A's out-of-band cancel"
20025            );
20026            assert_eq!(
20027                conn_b.core.recovery.phase(),
20028                SessionRecoveryPhase::Ready,
20029                "lane B never entered recovery"
20030            );
20031            Ok::<_, Error>(())
20032        })?;
20033
20034        server_a.join().expect("lane A server joins");
20035        server_b.join().expect("lane B server joins");
20036        Ok(())
20037    }
20038
20039    #[test]
20040    fn missing_tls_close_notify_is_tolerated_only_at_terminal_session_boundary() -> Result<()> {
20041        fn scripted_read(actions: Vec<ReadAction>) -> ScriptedRead {
20042            ScriptedRead::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20043                actions,
20044                Vec::new(),
20045                ScriptedClock::default(),
20046            ))))
20047        }
20048
20049        fn scripted_write() -> Arc<AsyncMutex<ScriptedWrite>> {
20050            Arc::new(AsyncMutex::with_name(
20051                "session_close_notify_test_write",
20052                ScriptedWrite::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20053                    Vec::new(),
20054                    Vec::new(),
20055                    ScriptedClock::default(),
20056                )))),
20057            ))
20058        }
20059
20060        fn missing_notify() -> ReadAction {
20061            ReadAction::ErrorKind(
20062                std::io::ErrorKind::UnexpectedEof,
20063                ASUPERSYNC_TLS_MISSING_CLOSE_NOTIFY,
20064            )
20065        }
20066
20067        let runtime = build_io_runtime()?;
20068
20069        // The pre-ACCEPT and ordinary packet readers remain strict. Turning
20070        // this into EOF globally would mask malformed CONNECT exchanges.
20071        let mut strict_read = scripted_read(vec![missing_notify()]);
20072        let strict_error = runtime
20073            .block_on(read_packet_with_limits(
20074                &mut strict_read,
20075                PacketLengthWidth::Legacy16,
20076                ProtocolLimits::DEFAULT,
20077            ))
20078            .expect_err("pre-ACCEPT missing close_notify must remain an error");
20079        assert!(
20080            matches!(&strict_error, Error::Io(error)
20081                if error.kind() == std::io::ErrorKind::UnexpectedEof
20082                    && error.to_string() == ASUPERSYNC_TLS_MISSING_CLOSE_NOTIFY),
20083            "strict packet read must preserve the typed TLS EOF, got {strict_error:?}"
20084        );
20085
20086        // Oracle is allowed to answer terminal LOGOFF by closing the already
20087        // usable session without a TLS alert and without another TNS packet.
20088        let mut clean_close = scripted_read(vec![missing_notify()]);
20089        let clean_disposition = runtime.block_on(async {
20090            let cx = test_cx()?;
20091            let probe = |_bytes: &[u8]| false;
20092            read_session_close_response_with_limits(
20093                &mut clean_close,
20094                &cx,
20095                &scripted_write(),
20096                false,
20097                &probe,
20098                ProtocolLimits::DEFAULT,
20099            )
20100            .await
20101        })?;
20102        assert_eq!(
20103            clean_disposition,
20104            SessionCloseDisposition::PeerHardClosed,
20105            "a hard close at the empty terminal-response boundary is distinct from a response"
20106        );
20107
20108        // This is the exact tail used by Connection::close after LOGOFF has
20109        // been written. Both modern and classic framing must stop here: the
20110        // shared TLS stream is terminal, so any final TNS EOF write would
20111        // surface Asupersync's `BrokenPipe` instead of a successful close.
20112        for classic in [false, true] {
20113            let state = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20114                vec![missing_notify()],
20115                Vec::new(),
20116                ScriptedClock::default(),
20117            )));
20118            let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
20119                ScriptedRead::from_state(Arc::clone(&state)),
20120                ScriptedWrite::from_state(Arc::clone(&state)),
20121                "session_close_hard_close_write",
20122            );
20123            runtime.block_on(async {
20124                let cx = test_cx()?;
20125                core.finish_session_close(&cx, classic, |_bytes| false)
20126                    .await
20127            })?;
20128            assert!(
20129                state
20130                    .lock()
20131                    .expect("session-close scripted state")
20132                    .is_consumed(),
20133                "peer hard-close must consume the read without attempting a write (classic={classic})"
20134            );
20135        }
20136
20137        // A fully framed response still wins normally; the following hard TLS
20138        // close is never consulted once the application boundary is proven.
20139        let complete = data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true);
20140        let mut complete_close =
20141            scripted_read(vec![ReadAction::bytes(complete, Some(3)), missing_notify()]);
20142        let complete_disposition = runtime.block_on(async {
20143            let cx = test_cx()?;
20144            let probe = |_bytes: &[u8]| true;
20145            read_session_close_response_with_limits(
20146                &mut complete_close,
20147                &cx,
20148                &scripted_write(),
20149                false,
20150                &probe,
20151                ProtocolLimits::DEFAULT,
20152            )
20153            .await
20154        })?;
20155        assert_eq!(
20156            complete_disposition,
20157            SessionCloseDisposition::ResponseComplete,
20158            "a framed terminal response must not be classified as a peer hard-close"
20159        );
20160
20161        // The ordinary complete-response path retains the final TNS EOF write.
20162        let complete = data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true);
20163        let eof = encode_packet(
20164            TNS_PACKET_TYPE_DATA,
20165            0,
20166            Some(oracledb_protocol::thin::TNS_DATA_FLAGS_EOF),
20167            &[],
20168            PacketLengthWidth::Large32,
20169        )?;
20170        let state = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20171            vec![ReadAction::bytes(complete, Some(3))],
20172            vec![WriteAction::expect_bytes(eof, Some(2))],
20173            ScriptedClock::default(),
20174        )));
20175        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
20176            ScriptedRead::from_state(Arc::clone(&state)),
20177            ScriptedWrite::from_state(Arc::clone(&state)),
20178            "session_close_complete_response_write",
20179        );
20180        runtime.block_on(async {
20181            let cx = test_cx()?;
20182            core.finish_session_close(&cx, false, |_bytes| true).await
20183        })?;
20184        assert!(
20185            state
20186                .lock()
20187                .expect("session-close scripted state")
20188                .is_consumed(),
20189            "a complete terminal response must retain the final TNS EOF write"
20190        );
20191
20192        // Once any TNS byte arrived, the same signal proves truncation and
20193        // remains a typed UnexpectedEof. Here the final payload byte is absent.
20194        let mut truncated = data_packet(b"truncated", true);
20195        truncated.pop();
20196        let mut truncated_close = scripted_read(vec![
20197            ReadAction::bytes(truncated, Some(3)),
20198            missing_notify(),
20199        ]);
20200        let truncated_error = runtime
20201            .block_on(async {
20202                let cx = test_cx()?;
20203                let probe = |_bytes: &[u8]| false;
20204                read_session_close_response_with_limits(
20205                    &mut truncated_close,
20206                    &cx,
20207                    &scripted_write(),
20208                    false,
20209                    &probe,
20210                    ProtocolLimits::DEFAULT,
20211                )
20212                .await
20213            })
20214            .expect_err("partial application response must not be accepted as clean close");
20215        assert!(
20216            matches!(&truncated_error, Error::Io(error)
20217                if error.kind() == std::io::ErrorKind::UnexpectedEof
20218                    && error.to_string() == ASUPERSYNC_TLS_MISSING_CLOSE_NOTIFY),
20219            "truncated response must preserve the typed TLS EOF, got {truncated_error:?}"
20220        );
20221
20222        Ok(())
20223    }
20224
20225    #[test]
20226    fn scripted_transport_injects_errors_and_eof() -> Result<()> {
20227        let payload = encode_packet(
20228            TNS_PACKET_TYPE_CONNECT,
20229            0,
20230            None,
20231            b"FAULT",
20232            PacketLengthWidth::Legacy16,
20233        )?;
20234
20235        let runtime = build_io_runtime()?;
20236
20237        let read_error = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20238            vec![ReadAction::Error("scripted read fault")],
20239            Vec::new(),
20240            ScriptedClock::default(),
20241        )));
20242        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
20243            ScriptedRead::from_state(read_error),
20244            ScriptedWrite::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20245                Vec::new(),
20246                Vec::new(),
20247                ScriptedClock::default(),
20248            )))),
20249            "scripted_read_error_write",
20250        );
20251        let read_err = runtime.block_on(async {
20252            match core.read_packet(PacketLengthWidth::Legacy16).await {
20253                Ok(_) => Err(Error::Runtime(
20254                    "scripted read fault unexpectedly succeeded".into(),
20255                )),
20256                Err(err) => Ok(err),
20257            }
20258        })?;
20259        assert!(
20260            read_err.to_string().contains("scripted read fault"),
20261            "scripted read error should keep its diagnostic"
20262        );
20263
20264        let read_eof = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20265            vec![ReadAction::Eof],
20266            Vec::new(),
20267            ScriptedClock::default(),
20268        )));
20269        let mut core = ConnectionCore::<ScriptedTransport>::from_halves(
20270            ScriptedRead::from_state(read_eof),
20271            ScriptedWrite::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20272                Vec::new(),
20273                Vec::new(),
20274                ScriptedClock::default(),
20275            )))),
20276            "scripted_read_eof_write",
20277        );
20278        let eof_err = runtime.block_on(async {
20279            match core.read_packet(PacketLengthWidth::Legacy16).await {
20280                Ok(_) => Err(Error::Runtime(
20281                    "scripted read EOF unexpectedly succeeded".into(),
20282                )),
20283                Err(err) => Ok(err),
20284            }
20285        })?;
20286        let eof_message = eof_err.to_string().to_ascii_lowercase();
20287        assert!(
20288            matches!(&eof_err, Error::Io(_))
20289                && (eof_message.contains("failed to fill whole buffer")
20290                    || eof_message.contains("early eof")
20291                    || eof_message.contains("unexpected eof")
20292                    || eof_message.contains("end of file")),
20293            "scripted EOF should surface as an incomplete read, got {eof_err:?}"
20294        );
20295
20296        let write_error = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20297            Vec::new(),
20298            vec![WriteAction::Error("scripted write fault")],
20299            ScriptedClock::default(),
20300        )));
20301        let core = ConnectionCore::<ScriptedTransport>::from_halves(
20302            ScriptedRead::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20303                Vec::new(),
20304                Vec::new(),
20305                ScriptedClock::default(),
20306            )))),
20307            ScriptedWrite::from_state(write_error),
20308            "scripted_write_error_write",
20309        );
20310        let write_err = runtime.block_on(async {
20311            let cx = test_cx()?;
20312            match core.write_all(&cx, &payload).await {
20313                Ok(()) => Err(Error::Runtime(
20314                    "scripted write error unexpectedly succeeded".into(),
20315                )),
20316                Err(err) => Ok(err),
20317            }
20318        })?;
20319        assert!(
20320            write_err.to_string().contains("scripted write fault"),
20321            "scripted write error should keep its diagnostic"
20322        );
20323
20324        let write_eof = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20325            Vec::new(),
20326            vec![WriteAction::Eof],
20327            ScriptedClock::default(),
20328        )));
20329        let core = ConnectionCore::<ScriptedTransport>::from_halves(
20330            ScriptedRead::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20331                Vec::new(),
20332                Vec::new(),
20333                ScriptedClock::default(),
20334            )))),
20335            ScriptedWrite::from_state(write_eof),
20336            "scripted_write_eof_write",
20337        );
20338        let write_eof_err = runtime.block_on(async {
20339            let cx = test_cx()?;
20340            match core.write_all(&cx, &payload).await {
20341                Ok(()) => Err(Error::Runtime(
20342                    "scripted write EOF unexpectedly succeeded".into(),
20343                )),
20344                Err(err) => Ok(err),
20345            }
20346        })?;
20347        assert!(
20348            write_eof_err
20349                .to_string()
20350                .contains("failed to write whole buffer")
20351                || write_eof_err.to_string().contains("write zero"),
20352            "scripted write EOF should surface as an incomplete write"
20353        );
20354
20355        Ok(())
20356    }
20357
20358    #[test]
20359    fn scripted_transport_rejects_mismatched_and_extra_writes() -> Result<()> {
20360        let expected = encode_packet(
20361            TNS_PACKET_TYPE_CONNECT,
20362            0,
20363            None,
20364            b"EXPECTED",
20365            PacketLengthWidth::Legacy16,
20366        )?;
20367        let actual = encode_packet(
20368            TNS_PACKET_TYPE_CONNECT,
20369            0,
20370            None,
20371            b"ACTUAL",
20372            PacketLengthWidth::Legacy16,
20373        )?;
20374
20375        let runtime = build_io_runtime()?;
20376        let mismatch = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20377            Vec::new(),
20378            vec![WriteAction::expect_bytes(expected, None)],
20379            ScriptedClock::default(),
20380        )));
20381        let core = ConnectionCore::<ScriptedTransport>::from_halves(
20382            ScriptedRead::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20383                Vec::new(),
20384                Vec::new(),
20385                ScriptedClock::default(),
20386            )))),
20387            ScriptedWrite::from_state(mismatch),
20388            "scripted_mismatch_write",
20389        );
20390        let mismatch_err = runtime.block_on(async {
20391            let cx = test_cx()?;
20392            match core.write_all(&cx, &actual).await {
20393                Ok(()) => Err(Error::Runtime(
20394                    "scripted mismatched write unexpectedly succeeded".into(),
20395                )),
20396                Err(err) => Ok(err),
20397            }
20398        })?;
20399        assert!(
20400            mismatch_err.to_string().contains("write mismatch"),
20401            "scripted write mismatch should be explicit"
20402        );
20403
20404        let extra = Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20405            Vec::new(),
20406            Vec::new(),
20407            ScriptedClock::default(),
20408        )));
20409        let core = ConnectionCore::<ScriptedTransport>::from_halves(
20410            ScriptedRead::from_state(Arc::new(std::sync::Mutex::new(ScriptedIoState::new(
20411                Vec::new(),
20412                Vec::new(),
20413                ScriptedClock::default(),
20414            )))),
20415            ScriptedWrite::from_state(extra),
20416            "scripted_extra_write",
20417        );
20418        let extra_err = runtime.block_on(async {
20419            let cx = test_cx()?;
20420            match core.write_all(&cx, &actual).await {
20421                Ok(()) => Err(Error::Runtime(
20422                    "scripted extra write unexpectedly succeeded".into(),
20423                )),
20424                Err(err) => Ok(err),
20425            }
20426        })?;
20427        assert!(
20428            extra_err.to_string().contains("unexpected write"),
20429            "scripted extra write should be rejected"
20430        );
20431
20432        Ok(())
20433    }
20434
20435    #[cfg(feature = "cassette")]
20436    #[test]
20437    fn connection_core_routes_connect_execute_fetch_over_replay_transport() -> Result<()> {
20438        use oracledb_protocol::net::cassette::{self, Direction};
20439
20440        const EXECUTE_BODY: &[u8] = b"replay execute payload";
20441        const FETCH_BODY: &[u8] = b"replay fetch payload";
20442        const EXECUTE_RESPONSE: &[u8] = b"replay execute response";
20443        const FETCH_RESPONSE: &[u8] = b"replay fetch response";
20444
20445        let connect_packet = encode_packet(
20446            TNS_PACKET_TYPE_CONNECT,
20447            0,
20448            None,
20449            b"REPLAY-CONNECT",
20450            PacketLengthWidth::Legacy16,
20451        )?;
20452        let accept_packet = encode_packet(
20453            TNS_PACKET_TYPE_ACCEPT,
20454            0,
20455            None,
20456            b"REPLAY-ACCEPT",
20457            PacketLengthWidth::Legacy16,
20458        )?;
20459        let execute_packet = encode_packet(
20460            TNS_PACKET_TYPE_DATA,
20461            0,
20462            Some(0),
20463            EXECUTE_BODY,
20464            PacketLengthWidth::Large32,
20465        )?;
20466        let fetch_packet = encode_packet(
20467            TNS_PACKET_TYPE_DATA,
20468            0,
20469            Some(0),
20470            FETCH_BODY,
20471            PacketLengthWidth::Large32,
20472        )?;
20473
20474        let mut cassette_bytes = Vec::new();
20475        cassette::write_header(&mut cassette_bytes);
20476        cassette::write_frame(
20477            &mut cassette_bytes,
20478            Direction::ClientToServer,
20479            0,
20480            &connect_packet,
20481        );
20482        cassette::write_frame(
20483            &mut cassette_bytes,
20484            Direction::ServerToClient,
20485            1,
20486            &accept_packet,
20487        );
20488        cassette::write_frame(
20489            &mut cassette_bytes,
20490            Direction::ClientToServer,
20491            2,
20492            &execute_packet,
20493        );
20494        cassette::write_frame(
20495            &mut cassette_bytes,
20496            Direction::ServerToClient,
20497            3,
20498            &data_packet(EXECUTE_RESPONSE, true),
20499        );
20500        cassette::write_frame(
20501            &mut cassette_bytes,
20502            Direction::ClientToServer,
20503            4,
20504            &fetch_packet,
20505        );
20506        cassette::write_frame(
20507            &mut cassette_bytes,
20508            Direction::ServerToClient,
20509            5,
20510            &data_packet(FETCH_RESPONSE, true),
20511        );
20512
20513        let (read, write) =
20514            transport::replay_split(&cassette_bytes, transport::ReplayWriteMode::Check)
20515                .map_err(|err| Error::Runtime(format!("invalid replay cassette: {err}")))?;
20516        let mut core =
20517            ConnectionCore::<DriverTransport>::from_halves(read, write, "replay_core_write");
20518
20519        let runtime = build_io_runtime()?;
20520        runtime.block_on(async {
20521            let cx = test_cx()?;
20522            core.write_all(&cx, &connect_packet).await?;
20523            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
20524            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
20525            assert_eq!(accept.payload, b"REPLAY-ACCEPT");
20526
20527            core.send_data_packet(&cx, EXECUTE_BODY, 8192).await?;
20528            let execute_response = core.read_data_response(&cx).await?;
20529            assert_eq!(execute_response, EXECUTE_RESPONSE);
20530
20531            core.send_data_packet(&cx, FETCH_BODY, 8192).await?;
20532            let fetch_response = core.read_data_response(&cx).await?;
20533            assert_eq!(fetch_response, FETCH_RESPONSE);
20534            Ok::<_, Error>(())
20535        })?;
20536        Ok(())
20537    }
20538
20539    /// K6 DoD: a captured query-FAILURE session is scrubbed of auth secrets,
20540    /// the artifact passes the secret-scan (C4), and offline replay of the
20541    /// artifact reproduces the failure with no database.
20542    #[cfg(feature = "cassette")]
20543    #[test]
20544    fn support_capture_scrubbed_cassette_replays_query_failure() -> Result<()> {
20545        use oracledb_protocol::net::cassette::{self, Direction};
20546
20547        const QUERY_BODY: &[u8] = b"SELECT * FROM missing_table";
20548        // The failure that offline replay must reproduce (secret-free ORA text).
20549        const ERROR_RESPONSE: &[u8] = b"ORA-00942: table or view does not exist";
20550
20551        let connect_packet = encode_packet(
20552            TNS_PACKET_TYPE_CONNECT,
20553            0,
20554            None,
20555            b"K6-CONNECT",
20556            PacketLengthWidth::Legacy16,
20557        )?;
20558        let accept_packet = encode_packet(
20559            TNS_PACKET_TYPE_ACCEPT,
20560            0,
20561            None,
20562            b"K6-ACCEPT",
20563            PacketLengthWidth::Legacy16,
20564        )?;
20565        // Auth-phase frames carrying secret material (password verifier +
20566        // session key) — exactly what a naive capture would leak to disk.
20567        let mut auth_body = b"AUTH_PASSWORD=hunter2 AUTH_SESSKEY=".to_vec();
20568        auth_body.extend_from_slice(&[0x5A_u8; 48]);
20569        let auth_request = encode_packet(
20570            TNS_PACKET_TYPE_DATA,
20571            0,
20572            Some(0),
20573            &auth_body,
20574            PacketLengthWidth::Large32,
20575        )?;
20576        let auth_response_body = b"AUTH_SVR SESSION_KEY=deadbeefcafef00ddeadbeefcafef00d".to_vec();
20577        let query_packet = encode_packet(
20578            TNS_PACKET_TYPE_DATA,
20579            0,
20580            Some(0),
20581            QUERY_BODY,
20582            PacketLengthWidth::Large32,
20583        )?;
20584
20585        // The raw captured session, as the recording transport would produce it.
20586        let mut raw = Vec::new();
20587        cassette::write_header(&mut raw);
20588        cassette::write_frame(&mut raw, Direction::ClientToServer, 0, &connect_packet);
20589        cassette::write_frame(&mut raw, Direction::ServerToClient, 1, &accept_packet);
20590        cassette::write_frame(&mut raw, Direction::ClientToServer, 2, &auth_request);
20591        cassette::write_frame(
20592            &mut raw,
20593            Direction::ServerToClient,
20594            3,
20595            &data_packet(&auth_response_body, true),
20596        );
20597        cassette::write_frame(&mut raw, Direction::ClientToServer, 4, &query_packet);
20598        cassette::write_frame(
20599            &mut raw,
20600            Direction::ServerToClient,
20601            5,
20602            &data_packet(ERROR_RESPONSE, true),
20603        );
20604
20605        // The RAW capture carries secrets — this is why the scrub gate exists.
20606        assert!(
20607            !transport::scan_for_secret_fields(&raw).is_empty(),
20608            "raw capture is expected to contain auth secrets"
20609        );
20610
20611        // Scrub the auth phase and run the fail-closed refuse gate.
20612        let (scrubbed, report) = transport::scrub_and_gate(&raw)
20613            .map_err(|e| Error::Runtime(format!("scrub gate refused unexpectedly: {e}")))?;
20614        assert!(report.redacted_frames >= 1, "auth frames must be redacted");
20615        // C4 secret-scan passes on the persisted artifact.
20616        assert!(
20617            transport::scan_for_secret_fields(&scrubbed).is_empty(),
20618            "scrubbed artifact must pass the secret scan"
20619        );
20620
20621        // Persist as a shareable file, reload it, and confirm it still scans clean.
20622        let path = std::env::temp_dir().join(format!(
20623            "oracledb-k6-replay-{}.tns-cassette",
20624            std::process::id()
20625        ));
20626        std::fs::write(&path, &scrubbed).map_err(|e| Error::Runtime(e.to_string()))?;
20627        let from_disk = std::fs::read(&path).map_err(|e| Error::Runtime(e.to_string()))?;
20628        assert!(transport::scan_for_secret_fields(&from_disk).is_empty());
20629
20630        // Offline replay reproduces the query FAILURE with no database.
20631        let (read, write) = transport::replay_split(&from_disk, transport::ReplayWriteMode::Ignore)
20632            .map_err(|err| Error::Runtime(format!("invalid replay cassette: {err}")))?;
20633        let mut core =
20634            ConnectionCore::<DriverTransport>::from_halves(read, write, "k6_replay_write");
20635        let runtime = build_io_runtime()?;
20636        let replay = runtime.block_on(async {
20637            let cx = test_cx()?;
20638            core.write_all(&cx, &connect_packet).await?;
20639            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
20640            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
20641
20642            // Auth round-trip: the recorded server frame is redacted but its TNS
20643            // framing is intact, so the decoder walks past it structurally.
20644            core.send_data_packet(&cx, &auth_body, 8192).await?;
20645            let _auth_response = core.read_data_response(&cx).await?;
20646
20647            core.send_data_packet(&cx, QUERY_BODY, 8192).await?;
20648            core.read_data_response(&cx).await
20649        });
20650        let _ = std::fs::remove_file(&path);
20651        let failure = replay?;
20652        assert_eq!(
20653            failure, ERROR_RESPONSE,
20654            "offline replay must reproduce the recorded query failure"
20655        );
20656        Ok(())
20657    }
20658
20659    #[cfg(feature = "cassette")]
20660    #[test]
20661    fn connection_core_routes_connect_execute_fetch_over_recording_transport() -> Result<()> {
20662        use oracledb_protocol::net::cassette::{self, Direction};
20663        use std::io::Write as _;
20664
20665        const EXECUTE_BODY: &[u8] = b"recording execute payload";
20666        const FETCH_BODY: &[u8] = b"recording fetch payload";
20667        const EXECUTE_RESPONSE: &[u8] = b"recording execute response";
20668        const FETCH_RESPONSE: &[u8] = b"recording fetch response";
20669
20670        let connect_packet = encode_packet(
20671            TNS_PACKET_TYPE_CONNECT,
20672            0,
20673            None,
20674            b"RECORDING-CONNECT",
20675            PacketLengthWidth::Legacy16,
20676        )?;
20677        let accept_packet = encode_packet(
20678            TNS_PACKET_TYPE_ACCEPT,
20679            0,
20680            None,
20681            b"RECORDING-ACCEPT",
20682            PacketLengthWidth::Legacy16,
20683        )?;
20684        let execute_packet = encode_packet(
20685            TNS_PACKET_TYPE_DATA,
20686            0,
20687            Some(0),
20688            EXECUTE_BODY,
20689            PacketLengthWidth::Large32,
20690        )?;
20691        let fetch_packet = encode_packet(
20692            TNS_PACKET_TYPE_DATA,
20693            0,
20694            Some(0),
20695            FETCH_BODY,
20696            PacketLengthWidth::Large32,
20697        )?;
20698        let execute_response_packet = data_packet(EXECUTE_RESPONSE, true);
20699        let fetch_response_packet = data_packet(FETCH_RESPONSE, true);
20700
20701        let listener = TcpListener::bind("127.0.0.1:0")?;
20702        let addr = listener.local_addr()?;
20703        let server_connect = connect_packet.clone();
20704        let server_accept = accept_packet.clone();
20705        let server_execute = execute_packet.clone();
20706        let server_fetch = fetch_packet.clone();
20707        let server_execute_response = execute_response_packet.clone();
20708        let server_fetch_response = fetch_response_packet.clone();
20709        let server = thread::spawn(move || -> std::io::Result<()> {
20710            let (mut socket, _) = listener.accept()?;
20711            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
20712
20713            let mut got = vec![0u8; server_connect.len()];
20714            socket.read_exact(&mut got)?;
20715            assert_eq!(got, server_connect);
20716            socket.write_all(&server_accept)?;
20717
20718            let mut got = vec![0u8; server_execute.len()];
20719            socket.read_exact(&mut got)?;
20720            assert_eq!(got, server_execute);
20721            socket.write_all(&server_execute_response)?;
20722
20723            let mut got = vec![0u8; server_fetch.len()];
20724            socket.read_exact(&mut got)?;
20725            assert_eq!(got, server_fetch);
20726            socket.write_all(&server_fetch_response)?;
20727            Ok(())
20728        });
20729
20730        let runtime = build_io_runtime()?;
20731        let cassette_bytes = runtime.block_on(async {
20732            let cx = test_cx()?;
20733            let scope = transport::capture_scope();
20734            let stream = TcpStream::connect(addr).await?;
20735            let (read, write) = transport::plain_split(stream);
20736            let mut core =
20737                ConnectionCore::<DriverTransport>::from_halves(read, write, "recording_core_write");
20738
20739            core.write_all(&cx, &connect_packet).await?;
20740            let accept = core.read_packet(PacketLengthWidth::Legacy16).await?;
20741            assert_eq!(accept.packet_type, TNS_PACKET_TYPE_ACCEPT);
20742            assert_eq!(accept.payload, b"RECORDING-ACCEPT");
20743
20744            core.send_data_packet(&cx, EXECUTE_BODY, 8192).await?;
20745            let execute_response = core.read_data_response(&cx).await?;
20746            assert_eq!(execute_response, EXECUTE_RESPONSE);
20747
20748            core.send_data_packet(&cx, FETCH_BODY, 8192).await?;
20749            let fetch_response = core.read_data_response(&cx).await?;
20750            assert_eq!(fetch_response, FETCH_RESPONSE);
20751
20752            Ok::<_, Error>(scope.to_cassette_bytes())
20753        })?;
20754
20755        server
20756            .join()
20757            .map_err(|_| Error::Runtime("recording test server thread panicked".into()))??;
20758        let frames = cassette::decode_all(&cassette_bytes)
20759            .map_err(|err| Error::Runtime(format!("invalid recorded cassette: {err}")))?;
20760        let (accept_header, accept_payload) = accept_packet.split_at(8);
20761        let (execute_response_header, execute_response_payload) =
20762            execute_response_packet.split_at(8);
20763        let (fetch_response_header, fetch_response_payload) = fetch_response_packet.split_at(8);
20764
20765        assert_eq!(frames.len(), 9);
20766        assert_eq!(frames[0].direction, Direction::ClientToServer);
20767        assert_eq!(frames[0].bytes, connect_packet);
20768        assert_eq!(frames[1].direction, Direction::ServerToClient);
20769        assert_eq!(frames[1].bytes, accept_header);
20770        assert_eq!(frames[2].direction, Direction::ServerToClient);
20771        assert_eq!(frames[2].bytes, accept_payload);
20772        assert_eq!(frames[3].direction, Direction::ClientToServer);
20773        assert_eq!(frames[3].bytes, execute_packet);
20774        assert_eq!(frames[4].direction, Direction::ServerToClient);
20775        assert_eq!(frames[4].bytes, execute_response_header);
20776        assert_eq!(frames[5].direction, Direction::ServerToClient);
20777        assert_eq!(frames[5].bytes, execute_response_payload);
20778        assert_eq!(frames[6].direction, Direction::ClientToServer);
20779        assert_eq!(frames[6].bytes, fetch_packet);
20780        assert_eq!(frames[7].direction, Direction::ServerToClient);
20781        assert_eq!(frames[7].bytes, fetch_response_header);
20782        assert_eq!(frames[8].direction, Direction::ServerToClient);
20783        assert_eq!(frames[8].bytes, fetch_response_payload);
20784        Ok(())
20785    }
20786
20787    /// Reads exactly one 11-byte TNS marker packet from `socket` and returns its
20788    /// marker type byte (payload byte 2). Used by the server side of the seam to
20789    /// observe the BREAK and RESET markers the client emits.
20790    fn read_marker_type(socket: &mut std::net::TcpStream) -> u8 {
20791        let mut packet = [0u8; 11];
20792        socket.read_exact(&mut packet).expect("read marker packet");
20793        assert_eq!(
20794            packet[4], TNS_PACKET_TYPE_MARKER,
20795            "expected a MARKER packet"
20796        );
20797        packet[10]
20798    }
20799
20800    // THE FIX: break_and_drain_wire sends BREAK, then consumes the ENTIRE
20801    // post-timeout sequence so the stream is left at a clean boundary. The
20802    // sequence here matches the live wire trace against Oracle 23/26ai: the
20803    // server flushes the cancelled call's IN-FLIGHT RESPONSE *first* (a complete
20804    // DATA response carrying its own end-of-response flag) and only THEN sends
20805    // the break-ack MARKER, the RESET handshake, and the trailing ORA-01013
20806    // error packet. A drain that stopped at the in-flight response's
20807    // end-of-response would leave the MARKER + error in the socket; the fix
20808    // discards the in-flight response(s), runs the RESET dance, and consumes the
20809    // trailing error too. A FOLLOWING read_data_response then decodes the NEXT
20810    // response correctly rather than the stale leftovers.
20811    #[test]
20812    fn break_and_drain_consumes_inflight_response_and_reset_then_next_read_is_fresh() {
20813        // The cancelled call's in-flight response (carries end-of-response): the
20814        // stale bytes that must be discarded, NOT mistaken for the next result.
20815        const INFLIGHT_BODY: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF];
20816        // The trailing error packet (ORA-01013-shaped; arbitrary payload here).
20817        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x02];
20818        // The genuine response to the NEXT operation on the reused connection.
20819        const FRESH_BODY: &[u8] = &[0x11, 0x22, 0x33, 0x44, 0x55];
20820
20821        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
20822        let addr = listener.local_addr().expect("listener address");
20823        let server = thread::spawn(move || {
20824            let (mut socket, _) = listener.accept().expect("accept test client");
20825            socket
20826                .set_read_timeout(Some(Duration::from_secs(5)))
20827                .expect("set read timeout");
20828            use std::io::Write as _;
20829
20830            // 1) Client sends BREAK.
20831            assert_eq!(
20832                read_marker_type(&mut socket),
20833                TNS_MARKER_TYPE_BREAK,
20834                "client must send a BREAK marker first"
20835            );
20836            // 2) Server flushes the cancelled call's in-flight response FIRST,
20837            //    with its OWN end-of-response flag (the exact race that made a
20838            //    stop-at-first-boundary drain leak the MARKER + error).
20839            socket
20840                .write_all(&data_packet(INFLIGHT_BODY, true))
20841                .expect("write in-flight response");
20842            // 3) Server's break-ack MARKER -> drives the client's RESET dance.
20843            socket
20844                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
20845                .expect("write break-ack marker");
20846            // 4) Client replies with RESET; server confirms with a RESET marker.
20847            assert_eq!(
20848                read_marker_type(&mut socket),
20849                TNS_MARKER_TYPE_RESET,
20850                "client must answer the marker with a RESET"
20851            );
20852            socket
20853                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
20854                .expect("write reset-confirm marker");
20855            // 5) Trailing error packet (ORA-01013) that ends the break response.
20856            socket
20857                .write_all(&data_packet(ERROR_BODY, true))
20858                .expect("write trailing error packet");
20859            // 6) The FRESH response to the next operation on the reused conn.
20860            socket
20861                .write_all(&data_packet(FRESH_BODY, true))
20862                .expect("write fresh response");
20863        });
20864
20865        let runtime = build_io_runtime().expect("asupersync runtime");
20866        let next = runtime.block_on(async {
20867            let cx = Cx::current().expect("ambient Cx");
20868            let stream = TcpStream::connect(addr).await.expect("connect to listener");
20869            let (mut read, write) = transport::plain_split(stream);
20870            let write: SharedWriteHalf = Arc::new(AsyncMutex::with_name("drain_test_write", write));
20871
20872            // The fix: break + drain leaves the stream clean.
20873            break_and_drain_wire(&mut read, &write, Duration::from_secs(5))
20874                .await
20875                .expect("drain must succeed and leave the stream clean");
20876
20877            // The next operation reads its OWN response, not the stale leftovers.
20878            read_data_response(&mut read, &cx, &write)
20879                .await
20880                .expect("next read after drain must decode cleanly")
20881        });
20882
20883        assert_eq!(
20884            next, FRESH_BODY,
20885            "after break_and_drain the reused connection must read the FRESH response, \
20886             not the stale in-flight response ({INFLIGHT_BODY:?}) or error body ({ERROR_BODY:?})"
20887        );
20888        server.join().expect("server thread joins");
20889    }
20890
20891    // bead rust-oracledb-99xu: on a pre-23ai server (no END_OF_RESPONSE framing)
20892    // the trailing error response after a BREAK/RESET carries NEITHER the
20893    // END_OF_RESPONSE data flag NOR a terminal marker byte -- it ends at its
20894    // terminal TTC message (here a STATUS). The flag-only recovery reader could
20895    // not detect that boundary and blocked until its secondary timeout, so the
20896    // call-timeout / cancel surfaced as ConnectionClosed instead of the real
20897    // CallTimeout / Cancelled (observed live against Oracle 18c/21c). The
20898    // classic-framing drain must complete on the terminal message and leave the
20899    // stream clean for the reused connection.
20900    #[test]
20901    fn classic_pre23ai_break_drain_completes_on_terminal_message_not_flag() {
20902        // A minimal, valid classic terminal: a STATUS message (msg type 9) whose
20903        // ub4 call-status and ub2 sequence are both zero-length. It carries NO
20904        // end-of-response flag and does NOT end in a marker byte.
20905        // TNS_MSG_TYPE_STATUS == 9 (oracledb_protocol::thin::constants).
20906        const CLASSIC_STATUS_TERMINAL: &[u8] = &[9, 0, 0];
20907        const FRESH_BODY: &[u8] = &[0x11, 0x22, 0x33, 0x44, 0x55];
20908
20909        // Guard: the flag-only detectors must NOT recognise this classic
20910        // terminal, which is precisely why the `classic` completion rule is
20911        // load-bearing (if either fired, the bug could never have occurred).
20912        assert!(
20913            !data_packet_ends_response(0, CLASSIC_STATUS_TERMINAL),
20914            "flag-framed detector must not terminate a flagless classic response"
20915        );
20916        assert!(
20917            !post_reset_packet_ends_response(CLASSIC_STATUS_TERMINAL),
20918            "post-reset marker-byte detector must not terminate a STATUS terminal"
20919        );
20920        assert!(
20921            classic_connect_response_is_complete(CLASSIC_STATUS_TERMINAL, ProtocolLimits::DEFAULT)
20922                .unwrap(),
20923            "the classic reader must recognise the STATUS terminal as complete"
20924        );
20925
20926        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
20927        let addr = listener.local_addr().expect("listener address");
20928        let server = thread::spawn(move || {
20929            let (mut socket, _) = listener.accept().expect("accept test client");
20930            socket
20931                .set_read_timeout(Some(Duration::from_secs(5)))
20932                .expect("set read timeout");
20933            use std::io::Write as _;
20934
20935            // The two-thread cancel path: the BREAK was already sent by the
20936            // handle thread, so the drain begins at the server's break-ack
20937            // MARKER. Reference cancel wire sequence, pre-23ai framing.
20938            socket
20939                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
20940                .expect("write break-ack marker");
20941            assert_eq!(
20942                read_marker_type(&mut socket),
20943                TNS_MARKER_TYPE_RESET,
20944                "client must answer the marker with a RESET"
20945            );
20946            socket
20947                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
20948                .expect("write reset-confirm marker");
20949            // Trailing error/STATUS response in CLASSIC framing: no EOR flag.
20950            socket
20951                .write_all(&data_packet(CLASSIC_STATUS_TERMINAL, false))
20952                .expect("write flagless classic terminal");
20953            // The FRESH response the reused connection must read next.
20954            socket
20955                .write_all(&data_packet(FRESH_BODY, true))
20956                .expect("write fresh response");
20957        });
20958
20959        let runtime = build_io_runtime().expect("asupersync runtime");
20960        let next = runtime.block_on(async {
20961            let cx = Cx::current().expect("ambient Cx");
20962            let stream = TcpStream::connect(addr).await.expect("connect to listener");
20963            let (mut read, write) = transport::plain_split(stream);
20964            let write: SharedWriteHalf =
20965                Arc::new(AsyncMutex::with_name("classic_drain_test_write", write));
20966
20967            // classic = true: the drain completes on the terminal message.
20968            drain_break_response_recovery_with_limits(
20969                &mut read,
20970                &write,
20971                ProtocolLimits::DEFAULT,
20972                true,
20973            )
20974            .await
20975            .expect("classic drain must complete on the terminal message");
20976
20977            read_data_response(&mut read, &cx, &write)
20978                .await
20979                .expect("next read after classic drain must decode cleanly")
20980        });
20981
20982        assert_eq!(
20983            next, FRESH_BODY,
20984            "after the classic drain the reused connection must read the FRESH response"
20985        );
20986        server.join().expect("server thread joins");
20987    }
20988
20989    // W1-T2.2: core recovery must not inherit the expired operation context.
20990    // The core moves the read half to a short-lived no-ambient recovery thread;
20991    // this test timeout-cancels the caller context before recovery starts and
20992    // proves the bounded drain still completes.
20993    #[test]
20994    fn core_break_and_drain_runs_after_caller_context_timeout() {
20995        const INFLIGHT_BODY: &[u8] = &[0xD1, 0xA1, 0xB1];
20996        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
20997
20998        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
20999        let addr = listener.local_addr().expect("listener address");
21000        let server = thread::spawn(move || {
21001            let (mut socket, _) = listener.accept().expect("accept test client");
21002            socket
21003                .set_read_timeout(Some(Duration::from_secs(5)))
21004                .expect("set read timeout");
21005            use std::io::Write as _;
21006
21007            assert_eq!(
21008                read_marker_type(&mut socket),
21009                TNS_MARKER_TYPE_BREAK,
21010                "recovery must send BREAK even after caller context timeout"
21011            );
21012            socket
21013                .write_all(&data_packet(INFLIGHT_BODY, true))
21014                .expect("write in-flight response");
21015            socket
21016                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21017                .expect("write break-ack marker");
21018            assert_eq!(
21019                read_marker_type(&mut socket),
21020                TNS_MARKER_TYPE_RESET,
21021                "recovery must answer break marker with RESET"
21022            );
21023            socket
21024                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21025                .expect("write reset-confirm marker");
21026            socket
21027                .write_all(&data_packet(ERROR_BODY, true))
21028                .expect("write trailing error packet");
21029        });
21030
21031        let runtime = build_io_runtime().expect("asupersync runtime");
21032        runtime.block_on(async {
21033            let cx = Cx::current().expect("ambient Cx");
21034            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21035            let (read, write) = transport::plain_split(stream);
21036            let mut core = ConnectionCore::<DriverTransport>::from_halves(
21037                read,
21038                write,
21039                "timeout_drain_test_write",
21040            );
21041
21042            cx.cancel_fast(asupersync::CancelKind::Timeout);
21043            assert!(
21044                cx.checkpoint().is_err(),
21045                "test must start from an expired caller context"
21046            );
21047
21048            core.break_and_drain_wire(Duration::from_secs(5))
21049                .expect("recovery drain must ignore the expired caller context");
21050        });
21051
21052        server.join().expect("server thread joins");
21053    }
21054
21055    #[test]
21056    fn preexpired_query_deadline_does_not_break_idle_connection() -> Result<()> {
21057        const INFLIGHT_BODY: &[u8] = &[0xd1, 0xa1, 0xb1];
21058        const CANCEL_ERROR: &[u8] = &[0x04, 0x01, 0x0d];
21059
21060        let commit_packet = encode_packet(
21061            TNS_PACKET_TYPE_DATA,
21062            0,
21063            Some(0),
21064            &build_function_payload_with_seq(
21065                TNS_FUNC_COMMIT,
21066                1,
21067                ClientCapabilities::default().ttc_field_version,
21068            ),
21069            PacketLengthWidth::Large32,
21070        )?;
21071
21072        let listener = TcpListener::bind("127.0.0.1:0")?;
21073        let addr = listener.local_addr()?;
21074        let server = thread::spawn(move || -> std::io::Result<usize> {
21075            let (mut socket, _) = listener.accept()?;
21076            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
21077            use std::io::Write as _;
21078
21079            let mut break_count = 0usize;
21080            loop {
21081                let mut header = [0u8; 8];
21082                socket.read_exact(&mut header)?;
21083                let declared =
21084                    u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
21085                let mut packet = header.to_vec();
21086                let mut body = vec![0u8; declared - header.len()];
21087                socket.read_exact(&mut body)?;
21088                packet.extend_from_slice(&body);
21089                if packet[4] == TNS_PACKET_TYPE_MARKER {
21090                    assert_eq!(packet[10], TNS_MARKER_TYPE_BREAK);
21091                    break_count += 1;
21092                    socket.write_all(&data_packet(INFLIGHT_BODY, true))?;
21093                    socket.write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))?;
21094                    assert_eq!(read_marker_type(&mut socket), TNS_MARKER_TYPE_RESET);
21095                    socket.write_all(&marker_packet(TNS_MARKER_TYPE_RESET))?;
21096                    socket.write_all(&data_packet(CANCEL_ERROR, true))?;
21097                    socket.flush()?;
21098                    continue;
21099                }
21100
21101                assert_eq!(
21102                    packet, commit_packet,
21103                    "the first ordinary request after both local expiries must be COMMIT"
21104                );
21105                socket.write_all(&data_packet(&[TNS_MSG_TYPE_END_OF_RESPONSE], true))?;
21106                socket.flush()?;
21107                return Ok(break_count);
21108            }
21109        });
21110
21111        let runtime = build_io_runtime()?;
21112        runtime.block_on(async {
21113            let cx = Cx::current().expect("runtime installs an ambient Cx");
21114            let socket = TcpStream::connect(addr).await?;
21115            let (read, write) = transport::plain_split(socket);
21116            let mut connection = loopback_connection(read, write);
21117
21118            fn assert_send<T: Send>(_: &T) {}
21119            let zero_timeout = connection.execute_with(
21120                &cx,
21121                Execute::new("begin null; end;").timeout(Duration::ZERO),
21122            );
21123            assert_send(&zero_timeout);
21124            let err = zero_timeout
21125                .await
21126                .expect_err("an already-expired query deadline must fail");
21127            assert!(
21128                matches!(err, Error::CallTimeout(0)),
21129                "pre-expired deadline must surface CallTimeout(0), got {err:?}"
21130            );
21131
21132            let ambient_deadline = QueryDeadline::from_budget(
21133                asupersync::time::wall_now(),
21134                Budget::new().with_deadline(Time::ZERO),
21135                None,
21136            );
21137            let ambient_err = connection
21138                .execute_with_deadline(&cx, Execute::new("begin null; end;"), ambient_deadline)
21139                .await
21140                .expect_err("an expired ambient deadline must fail before polling");
21141            assert!(
21142                matches!(ambient_err, Error::CallTimeout(0)),
21143                "expired ambient deadline must surface CallTimeout(0), got {ambient_err:?}"
21144            );
21145            assert_eq!(
21146                connection.core.recovery.phase(),
21147                SessionRecoveryPhase::Ready,
21148                "a future that was never polled must not arm wire recovery"
21149            );
21150            assert!(
21151                !connection.dead,
21152                "local before-start expiry must not mark a healthy connection dead"
21153            );
21154
21155            connection.commit(&cx).await?;
21156            Ok::<_, Error>(())
21157        })?;
21158
21159        let break_count = server.join().expect("server thread joins")?;
21160        assert_eq!(
21161            break_count, 0,
21162            "neither a zero request timeout nor an expired ambient deadline may send BREAK"
21163        );
21164        Ok(())
21165    }
21166
21167    #[test]
21168    fn prestart_expiry_preserves_structured_cancel_without_wire_io() -> Result<()> {
21169        let listener = TcpListener::bind("127.0.0.1:0")?;
21170        let addr = listener.local_addr()?;
21171        let server = thread::spawn(move || -> std::io::Result<Vec<usize>> {
21172            let mut received = Vec::with_capacity(2);
21173            for _ in 0..2 {
21174                let (mut socket, _) = listener.accept()?;
21175                socket.set_read_timeout(Some(Duration::from_secs(5)))?;
21176                let mut bytes = Vec::new();
21177                socket.read_to_end(&mut bytes)?;
21178                received.push(bytes.len());
21179            }
21180            Ok(received)
21181        });
21182
21183        for kind in [CancelKind::User, CancelKind::Shutdown] {
21184            let runtime = build_io_runtime()?;
21185            runtime.block_on(async {
21186                let socket = TcpStream::connect(addr).await?;
21187                let (read, write) = transport::plain_split(socket);
21188                let mut connection = loopback_connection(read, write);
21189                let cx = Cx::current().expect("runtime installs an ambient Cx");
21190                cx.cancel_with(kind, Some("pre-start cancellation test"));
21191
21192                let err = connection
21193                    .execute_with(
21194                        &cx,
21195                        Execute::new("begin null; end;").timeout(Duration::ZERO),
21196                    )
21197                    .await
21198                    .expect_err("an already-expired operation must not start");
21199
21200                match kind {
21201                    CancelKind::User => {
21202                        assert!(
21203                            matches!(err, Error::Cancelled),
21204                            "user cancellation must remain distinct, got {err:?}"
21205                        );
21206                        assert!(
21207                            !connection.is_dead(),
21208                            "user cancellation before start leaves the connection reusable"
21209                        );
21210                        assert_eq!(
21211                            connection.core.recovery.phase(),
21212                            SessionRecoveryPhase::Ready
21213                        );
21214                    }
21215                    CancelKind::Shutdown => {
21216                        assert!(
21217                            matches!(err, Error::ConnectionClosed(_)),
21218                            "shutdown cancellation must close the connection, got {err:?}"
21219                        );
21220                        assert!(
21221                            connection.is_dead(),
21222                            "shutdown cancellation before start must mark the connection dead"
21223                        );
21224                        assert_eq!(connection.core.recovery.phase(), SessionRecoveryPhase::Dead);
21225                    }
21226                    _ => unreachable!("the test covers exactly User and Shutdown"),
21227                }
21228
21229                drop(connection);
21230                Ok::<_, Error>(())
21231            })?;
21232        }
21233
21234        let received = server.join().expect("server thread joins")?;
21235        assert_eq!(
21236            received,
21237            vec![0, 0],
21238            "before-start cancellation must emit neither a request nor BREAK"
21239        );
21240        Ok(())
21241    }
21242
21243    // bead rust-oracledb-yhz: a compliant-but-non-minimal server may send
21244    // MULTIPLE RESET markers after the client's RESET (reference _reset second
21245    // loop, protocol.pyx:554-556). The drain must consume ALL of them and send
21246    // exactly ONE RESET. The pre-fix reset_after_marker returned on the first
21247    // RESET marker, so the caller read the second one, mistook it for a fresh
21248    // break, and sent a DUPLICATE RESET — poisoning the reused connection.
21249    #[test]
21250    fn reset_after_marker_drains_multiple_trailing_markers_no_duplicate_reset() {
21251        const INFLIGHT_BODY: &[u8] = &[0xDE, 0xAD];
21252        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x02];
21253        const FRESH_BODY: &[u8] = &[0x11, 0x22, 0x33];
21254
21255        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21256        let addr = listener.local_addr().expect("listener address");
21257        let server = thread::spawn(move || {
21258            let (mut socket, _) = listener.accept().expect("accept test client");
21259            socket
21260                .set_read_timeout(Some(Duration::from_secs(5)))
21261                .expect("set read timeout");
21262            use std::io::Write as _;
21263
21264            assert_eq!(
21265                read_marker_type(&mut socket),
21266                TNS_MARKER_TYPE_BREAK,
21267                "client must send a BREAK marker first"
21268            );
21269            socket
21270                .write_all(&data_packet(INFLIGHT_BODY, true))
21271                .expect("write in-flight response");
21272            socket
21273                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21274                .expect("write break-ack marker");
21275            // The client answers the marker with exactly ONE RESET.
21276            assert_eq!(
21277                read_marker_type(&mut socket),
21278                TNS_MARKER_TYPE_RESET,
21279                "client must answer with a RESET"
21280            );
21281            // Server now sends TWO RESET markers (the yhz trigger) before the
21282            // trailing error + the fresh response.
21283            socket
21284                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21285                .expect("write reset marker #1");
21286            socket
21287                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21288                .expect("write reset marker #2");
21289            socket
21290                .write_all(&data_packet(ERROR_BODY, true))
21291                .expect("write trailing error packet");
21292            socket
21293                .write_all(&data_packet(FRESH_BODY, true))
21294                .expect("write fresh response");
21295            // No DUPLICATE RESET may arrive. With the bug the client answers the
21296            // second RESET marker with a second RESET, which (sent during the
21297            // drain) is already in our buffer by now.
21298            socket
21299                .set_read_timeout(Some(Duration::from_millis(750)))
21300                .expect("set short read timeout");
21301            let mut extra = [0u8; 11];
21302            if socket.read_exact(&mut extra).is_ok() {
21303                panic!(
21304                    "client sent a DUPLICATE marker (type {}): the drain did not \
21305                     consume all trailing RESET markers (bead rust-oracledb-yhz)",
21306                    extra[10]
21307                );
21308            }
21309        });
21310
21311        let runtime = build_io_runtime().expect("asupersync runtime");
21312        let next = runtime.block_on(async {
21313            let cx = Cx::current().expect("ambient Cx");
21314            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21315            let (mut read, write) = transport::plain_split(stream);
21316            let write: SharedWriteHalf = Arc::new(AsyncMutex::with_name("yhz_test_write", write));
21317            break_and_drain_wire(&mut read, &write, Duration::from_secs(5))
21318                .await
21319                .expect("drain must succeed even with multiple RESET markers");
21320            read_data_response(&mut read, &cx, &write)
21321                .await
21322                .expect("next read after drain must decode cleanly")
21323        });
21324
21325        assert_eq!(
21326            next, FRESH_BODY,
21327            "after draining multiple RESET markers the reused connection must read \
21328             the FRESH response"
21329        );
21330        server.join().expect("server thread joins");
21331    }
21332
21333    // THE BUG (pre-fix contrast): if the timeout path sends ONLY a BREAK and
21334    // does NOT drain, the in-flight response tail is still sitting in the socket.
21335    // The next read_data_response then reassembles those STALE bytes as if they
21336    // were the next operation's response — the wire is desynced. This test pins
21337    // that broken behavior to prove the regression test above is meaningful: it
21338    // asserts that without the drain the next read returns the stale tail.
21339    #[test]
21340    fn break_without_drain_leaves_stale_bytes_for_next_read() {
21341        const STALE_BODY: &[u8] = &[0x53, 0x54, 0x41, 0x4c, 0x45]; // "STALE"
21342        const FRESH_BODY: &[u8] = &[0x11, 0x22, 0x33];
21343
21344        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21345        let addr = listener.local_addr().expect("listener address");
21346        let server = thread::spawn(move || {
21347            let (mut socket, _) = listener.accept().expect("accept test client");
21348            socket
21349                .set_read_timeout(Some(Duration::from_secs(5)))
21350                .expect("set read timeout");
21351            use std::io::Write as _;
21352            // Client sends BREAK (the only thing the OLD code did).
21353            assert_eq!(read_marker_type(&mut socket), TNS_MARKER_TYPE_BREAK);
21354            // The server's in-flight response (end-of-response) was already on
21355            // its way when the break fired: it lands in the socket unconsumed.
21356            socket
21357                .write_all(&data_packet(STALE_BODY, true))
21358                .expect("write stale in-flight response");
21359            // ... and then the fresh response the caller actually wanted.
21360            socket
21361                .write_all(&data_packet(FRESH_BODY, true))
21362                .expect("write fresh response");
21363        });
21364
21365        let runtime = build_io_runtime().expect("asupersync runtime");
21366        let first_read = runtime.block_on(async {
21367            let cx = Cx::current().expect("ambient Cx");
21368            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21369            let (mut read, write) = transport::plain_split(stream);
21370            let write: SharedWriteHalf =
21371                Arc::new(AsyncMutex::with_name("nodrain_test_write", write));
21372
21373            // Reproduce the OLD timeout path: send BREAK, do NOT drain.
21374            send_marker_shared(&cx, &write, TNS_MARKER_TYPE_BREAK)
21375                .await
21376                .expect("send break");
21377
21378            // The very next read picks up the STALE in-flight response.
21379            read_data_response(&mut read, &cx, &write)
21380                .await
21381                .expect("read after bare break")
21382        });
21383
21384        assert_eq!(
21385            first_read, STALE_BODY,
21386            "without the drain, the next read misframes onto the stale in-flight bytes — \
21387             this is the bug break_and_drain fixes"
21388        );
21389        server.join().expect("server thread joins");
21390    }
21391
21392    // bead rust-oracledb-zhm: the DML-RETURNING error path (test_1600 test_1612,
21393    // ORA-12899) deadlocked. Confirmed by live wire trace against Oracle 23ai:
21394    // a RETURNING statement that errors does NOT come back as a plain DATA
21395    // response. The server signals it out-of-band, exactly as on a call-timeout
21396    // BREAK: it sends a BREAK marker, the client runs the RESET dance, and the
21397    // server then sends a FLUSH_OUT_BINDS *request* — a DATA packet whose data
21398    // flags are 0x0000 (NO end-of-response flag, because the break-recovery path
21399    // does not use request-boundary framing) and whose payload ends in the
21400    // FLUSH_OUT_BINDS message byte (0x13). The reference recognises this as
21401    // end-of-response while *processing* the message (messages/base.pyx:1267-1269
21402    // sets end_of_response on TNS_MSG_TYPE_FLUSH_OUT_BINDS) and replies with a
21403    // FLUSH_OUT_BINDS message; the server then sends another BREAK/RESET pair and
21404    // finally the real ORA-12899 error packet.
21405    //
21406    // THE BUG: our `read_data_response_boundary` fed the post-RESET trailing
21407    // packet back through `data_packet_ends_response`, which (correctly, for the
21408    // wide-row false-positive guard, bead n2s) returns false for a flagless
21409    // packet that merely *ends* in 0x13. So the boundary loop tried to read
21410    // another packet that the server never sends (it is waiting for our
21411    // FLUSH_OUT_BINDS reply) and we blocked forever in recvfrom/epoll.
21412    //
21413    // THE FIX: a packet that arrives *after a RESET* inside the boundary loop is
21414    // message-byte framed, not request-boundary framed (mirroring the reference,
21415    // whose `_check_request_boundary` is off for post-reset packets). So once the
21416    // loop has run a RESET, a trailing FLUSH_OUT_BINDS / END_OF_RESPONSE message
21417    // byte terminates the response. The wide-row guard is untouched because it
21418    // applies only to the normal (no-reset) framing.
21419    //
21420    // This hermetic test replays that exact sequence and drives the real
21421    // execute-path reader (`read_data_response_flushing_out_binds`). Pre-fix it
21422    // hangs at step (4) below; the bounded timeout converts the hang into a test
21423    // failure instead of stalling the whole suite.
21424    #[test]
21425    fn dml_returning_error_flush_out_binds_after_reset_completes_without_hang() {
21426        // The real ORA-12899 error payload tail (end-of-response flagged).
21427        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x02, 0x37];
21428        // The FLUSH_OUT_BINDS *request* the server sends after the first reset:
21429        // flagless DATA packet whose payload ends in the FLUSH_OUT_BINDS byte.
21430        // Matches the live trace body `07 00 00 13`.
21431        const FLUSH_REQUEST_BODY: &[u8] = &[0x07, 0x00, 0x00, TNS_MSG_TYPE_FLUSH_OUT_BINDS];
21432
21433        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21434        let addr = listener.local_addr().expect("listener address");
21435        let server = thread::spawn(move || {
21436            let (mut socket, _) = listener.accept().expect("accept test client");
21437            socket
21438                .set_read_timeout(Some(Duration::from_secs(5)))
21439                .expect("set read timeout");
21440            use std::io::Write as _;
21441
21442            // 1) Server signals the RETURNING error out-of-band with a BREAK.
21443            socket
21444                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21445                .expect("write break marker");
21446            // 2) Client answers with RESET; server confirms with a RESET marker.
21447            assert_eq!(
21448                read_marker_type(&mut socket),
21449                TNS_MARKER_TYPE_RESET,
21450                "client must answer the BREAK with a RESET"
21451            );
21452            socket
21453                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21454                .expect("write reset-confirm marker");
21455            // 3) Server sends the FLUSH_OUT_BINDS request: flagless DATA packet
21456            //    ending in 0x13. THIS is the packet the pre-fix loop refused to
21457            //    treat as a boundary, then blocked reading the next packet.
21458            socket
21459                .write_all(&data_packet(FLUSH_REQUEST_BODY, false))
21460                .expect("write flush-out-binds request");
21461            // 4) Client must reply with a FLUSH_OUT_BINDS message of its own
21462            //    (a DATA packet whose single-byte payload is 0x13).
21463            let mut header = [0u8; 8];
21464            socket
21465                .read_exact(&mut header)
21466                .expect("read flush-out-binds reply header");
21467            assert_eq!(
21468                header[4], TNS_PACKET_TYPE_DATA,
21469                "client's flush-out-binds reply must be a DATA packet"
21470            );
21471            let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
21472            let mut body = vec![0u8; len - 8];
21473            socket
21474                .read_exact(&mut body)
21475                .expect("read flush-out-binds reply body");
21476            assert_eq!(
21477                body.last().copied(),
21478                Some(TNS_MSG_TYPE_FLUSH_OUT_BINDS),
21479                "client must reply with a FLUSH_OUT_BINDS message"
21480            );
21481            // 5) Server sends another BREAK/RESET pair before the real error.
21482            socket
21483                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21484                .expect("write second break marker");
21485            assert_eq!(
21486                read_marker_type(&mut socket),
21487                TNS_MARKER_TYPE_RESET,
21488                "client must answer the second BREAK with a RESET"
21489            );
21490            socket
21491                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21492                .expect("write second reset-confirm marker");
21493            // 6) Finally, the genuine ORA-12899 error packet (end-of-response).
21494            socket
21495                .write_all(&data_packet(ERROR_BODY, true))
21496                .expect("write trailing ORA-12899 error packet");
21497        });
21498
21499        let runtime = build_io_runtime().expect("asupersync runtime");
21500        let payload = runtime.block_on(async {
21501            let cx = Cx::current().expect("ambient Cx");
21502            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21503            let (mut read, write) = transport::plain_split(stream);
21504            let write: SharedWriteHalf =
21505                Arc::new(AsyncMutex::with_name("returning_err_test_write", write));
21506
21507            // Drive the real execute-path reader. Bound it so the pre-fix hang
21508            // surfaces as a timeout error rather than stalling the whole suite.
21509            time::timeout(
21510                time::wall_now(),
21511                Duration::from_secs(10),
21512                read_data_response_flushing_out_binds(&mut read, &cx, &write, 8192),
21513            )
21514            .await
21515            .expect("must NOT hang on the DML-RETURNING error path (flush-out-binds after reset)")
21516            .expect("read must complete and yield the trailing error payload")
21517        });
21518
21519        // The fully reassembled response ends with the real error packet's bytes
21520        // (the FLUSH_OUT_BINDS request body is consumed/popped, not surfaced).
21521        assert!(
21522            payload.ends_with(ERROR_BODY),
21523            "the reassembled response must end with the ORA-12899 error payload, got {payload:?}"
21524        );
21525        server.join().expect("server thread joins");
21526    }
21527
21528    // ---- explicit cancel (bead rust-oracledb-wnz) -----------------------------
21529    //
21530    // Connection::cancel() must do for an EXPLICIT user cancel exactly what the
21531    // call-timeout path does for a timeout: send the BREAK, drain the server's
21532    // in-flight response + the break-ack MARKER + the RESET handshake + the
21533    // trailing ORA-01013 error, then leave the wire at a clean boundary so the
21534    // SAME connection is reusable for the next operation. It reuses the proven
21535    // `break_and_drain_wire` machinery (no duplicate drain loop). The only thing
21536    // that differs from the timeout path is the surfaced error semantics: a
21537    // successful cancel is `Ok(())` (the connection is clean), and the in-flight
21538    // operation observes `Error::Cancelled` (ORA-01013 user-requested-cancel),
21539    // which — like DPY-4024 — is NOT connection-lost (the session survives).
21540
21541    #[test]
21542    fn cancel_and_drain_wire_leaves_connection_reusable() {
21543        // The cancelled call's in-flight response (its own end-of-response): the
21544        // stale bytes that must be discarded, never mistaken for the next result.
21545        const INFLIGHT_BODY: &[u8] = &[0xCA, 0xFE];
21546        // The trailing ORA-01013-shaped error packet ending the cancel response.
21547        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
21548        // The genuine response to `select 7+5` on the reused connection.
21549        const FRESH_BODY: &[u8] = &[0x07, 0x05, 0x0c];
21550
21551        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21552        let addr = listener.local_addr().expect("listener address");
21553        let server = thread::spawn(move || {
21554            let (mut socket, _) = listener.accept().expect("accept test client");
21555            socket
21556                .set_read_timeout(Some(Duration::from_secs(5)))
21557                .expect("set read timeout");
21558            use std::io::Write as _;
21559
21560            // 1) Client sends BREAK to cancel the in-flight slow query.
21561            assert_eq!(
21562                read_marker_type(&mut socket),
21563                TNS_MARKER_TYPE_BREAK,
21564                "cancel must send a BREAK marker first"
21565            );
21566            // 2) Server flushes the cancelled call's in-flight response FIRST.
21567            socket
21568                .write_all(&data_packet(INFLIGHT_BODY, true))
21569                .expect("write in-flight response");
21570            // 3) Server's break-ack MARKER drives the client's RESET dance.
21571            socket
21572                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21573                .expect("write break-ack marker");
21574            // 4) Client answers with RESET; server confirms.
21575            assert_eq!(
21576                read_marker_type(&mut socket),
21577                TNS_MARKER_TYPE_RESET,
21578                "cancel must answer the marker with a RESET"
21579            );
21580            socket
21581                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21582                .expect("write reset-confirm marker");
21583            // 5) Trailing ORA-01013 error ending the cancel response.
21584            socket
21585                .write_all(&data_packet(ERROR_BODY, true))
21586                .expect("write trailing error packet");
21587            // 6) The FRESH response to the next operation (select 7+5 -> 12).
21588            socket
21589                .write_all(&data_packet(FRESH_BODY, true))
21590                .expect("write fresh response");
21591        });
21592
21593        let runtime = build_io_runtime().expect("asupersync runtime");
21594        let next = runtime.block_on(async {
21595            let cx = Cx::current().expect("ambient Cx");
21596            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21597            let (mut read, write) = transport::plain_split(stream);
21598            let write: SharedWriteHalf =
21599                Arc::new(AsyncMutex::with_name("cancel_test_write", write));
21600
21601            // The cancel: break + drain leaves the stream clean and reusable.
21602            cancel_and_drain_wire(&mut read, &write, Duration::from_secs(5))
21603                .await
21604                .expect("cancel drain must succeed and leave the stream clean");
21605
21606            // The next operation reads its OWN response on the SAME connection.
21607            read_data_response(&mut read, &cx, &write)
21608                .await
21609                .expect("next read after cancel must decode cleanly")
21610        });
21611
21612        assert_eq!(
21613            next, FRESH_BODY,
21614            "after cancel the reused connection must read the FRESH response, not the \
21615             stale in-flight response ({INFLIGHT_BODY:?}) or error body ({ERROR_BODY:?})"
21616        );
21617        server.join().expect("server thread joins");
21618    }
21619
21620    // A bare `fetch_rows_request` whose paired `fetch_rows_ref_response` is never
21621    // consumed leaves the recovery phase `InFlight` with a stranded page on the
21622    // wire (no response future was dropped to fire a `CancelDrainGuard`).
21623    // `ensure_clean_before_request` must treat that exactly like a dropped fetch:
21624    // break + drain the stranded page and reconcile to `Ready`, so the next
21625    // operation reads its OWN response instead of the connection wedging forever
21626    // on "operation attempted while a response is still in flight". Offline
21627    // regression for the live `stranded_prefetch_request_is_drained_before_reuse`
21628    // proof (bead rust-oracledb-004o).
21629    #[test]
21630    fn ensure_clean_drains_inflight_bare_request_before_reuse() {
21631        // The stranded speculative page (its own end-of-response): stale bytes
21632        // that must be discarded, never mistaken for the next result.
21633        const INFLIGHT_BODY: &[u8] = &[0xCA, 0xFE];
21634        // The trailing ORA-01013-shaped error packet ending the drain response.
21635        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
21636        // The genuine response to the reuse operation.
21637        const FRESH_BODY: &[u8] = &[0x07, 0x05, 0x0c];
21638
21639        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21640        let addr = listener.local_addr().expect("listener address");
21641        let server = thread::spawn(move || {
21642            let (mut socket, _) = listener.accept().expect("accept test client");
21643            socket
21644                .set_read_timeout(Some(Duration::from_secs(5)))
21645                .expect("set read timeout");
21646            use std::io::Write as _;
21647
21648            // The reuse op must break + drain the stranded page first. Without the
21649            // InFlight handling this BREAK never arrives (the op errors out) and
21650            // this read times out — the regression's failure mode.
21651            assert_eq!(
21652                read_marker_type(&mut socket),
21653                TNS_MARKER_TYPE_BREAK,
21654                "reuse after a bare request must send a BREAK to drain the stranded page"
21655            );
21656            socket
21657                .write_all(&data_packet(INFLIGHT_BODY, true))
21658                .expect("write stranded page");
21659            socket
21660                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21661                .expect("write break-ack marker");
21662            assert_eq!(
21663                read_marker_type(&mut socket),
21664                TNS_MARKER_TYPE_RESET,
21665                "drain must answer the break-ack marker with a RESET"
21666            );
21667            socket
21668                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21669                .expect("write reset-confirm marker");
21670            socket
21671                .write_all(&data_packet(ERROR_BODY, true))
21672                .expect("write trailing error packet");
21673            socket
21674                .write_all(&data_packet(FRESH_BODY, true))
21675                .expect("write fresh response");
21676        });
21677
21678        let runtime = build_io_runtime().expect("asupersync runtime");
21679        let next = runtime
21680            .block_on(async {
21681                let cx = Cx::current().expect("ambient Cx");
21682                let stream = TcpStream::connect(addr).await.expect("connect to listener");
21683                let (read, write) = transport::plain_split(stream);
21684                let mut conn = loopback_connection(read, write);
21685
21686                // Simulate a bare `fetch_rows_request`: a speculative response is
21687                // outstanding, so the phase is `InFlight` with no guard armed.
21688                conn.core
21689                    .recovery
21690                    .begin_operation()
21691                    .expect("enter InFlight");
21692                assert_eq!(conn.core.recovery.phase(), SessionRecoveryPhase::InFlight);
21693
21694                // The next operation's pre-flight cleanup must reclaim the wire.
21695                conn.ensure_clean_before_request()
21696                    .await
21697                    .expect("a stranded bare request must be drained, not wedge the connection");
21698                assert_eq!(
21699                    conn.core.recovery.phase(),
21700                    SessionRecoveryPhase::Ready,
21701                    "after draining the stranded page the session is Ready for reuse"
21702                );
21703
21704                conn.core.read_data_response(&cx).await
21705            })
21706            .expect("the reused connection must read its fresh response");
21707
21708        assert_eq!(
21709            next, FRESH_BODY,
21710            "after draining the stranded bare request the reused connection must read \
21711             the FRESH response, not the stranded page ({INFLIGHT_BODY:?})"
21712        );
21713        server.join().expect("server thread joins");
21714    }
21715
21716    // The two-thread cancel path (a `CancelHandle` on another thread already
21717    // sent the BREAK while the main thread is blocked in the query) needs a
21718    // DRAIN-ONLY clean-up: it must NOT send a second BREAK, but it must still
21719    // consume the in-flight response + break-ack MARKER + RESET handshake +
21720    // trailing ORA-01013, exactly like the full break+drain. `drain_cancel_wire`
21721    // is that drain-only half, sharing `drain_break_response_recovery` with the
21722    // break+drain path. The server here sends NO marker before its in-flight
21723    // response is flushed and does NOT expect a BREAK from us (the handle thread
21724    // already sent it) — only the RESET in answer to the break-ack marker.
21725    #[test]
21726    fn drain_cancel_wire_drains_without_sending_a_break() {
21727        const INFLIGHT_BODY: &[u8] = &[0xCA, 0xFE];
21728        const ERROR_BODY: &[u8] = &[0x04, 0x01, 0x0d];
21729        const FRESH_BODY: &[u8] = &[0x07, 0x05, 0x0c];
21730
21731        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
21732        let addr = listener.local_addr().expect("listener address");
21733        let server = thread::spawn(move || {
21734            let (mut socket, _) = listener.accept().expect("accept test client");
21735            socket
21736                .set_read_timeout(Some(Duration::from_secs(5)))
21737                .expect("set read timeout");
21738            use std::io::Write as _;
21739
21740            // The drain-only path sends NO BREAK first (the handle thread did).
21741            // Server flushes the in-flight response then the break-ack MARKER.
21742            socket
21743                .write_all(&data_packet(INFLIGHT_BODY, true))
21744                .expect("write in-flight response");
21745            socket
21746                .write_all(&marker_packet(TNS_MARKER_TYPE_BREAK))
21747                .expect("write break-ack marker");
21748            // The drain answers the marker with a RESET.
21749            assert_eq!(
21750                read_marker_type(&mut socket),
21751                TNS_MARKER_TYPE_RESET,
21752                "drain must answer the break-ack marker with a RESET"
21753            );
21754            socket
21755                .write_all(&marker_packet(TNS_MARKER_TYPE_RESET))
21756                .expect("write reset-confirm marker");
21757            socket
21758                .write_all(&data_packet(ERROR_BODY, true))
21759                .expect("write trailing error packet");
21760            socket
21761                .write_all(&data_packet(FRESH_BODY, true))
21762                .expect("write fresh response");
21763            // No BREAK marker may ever arrive on this path.
21764            socket
21765                .set_read_timeout(Some(Duration::from_millis(500)))
21766                .expect("set short read timeout");
21767            let mut extra = [0u8; 11];
21768            if let Ok(()) = socket.read_exact(&mut extra) {
21769                assert_ne!(
21770                    extra[10], TNS_MARKER_TYPE_BREAK,
21771                    "drain-only cancel must NOT send a BREAK marker"
21772                );
21773            }
21774        });
21775
21776        let runtime = build_io_runtime().expect("asupersync runtime");
21777        let next = runtime.block_on(async {
21778            let cx = Cx::current().expect("ambient Cx");
21779            let stream = TcpStream::connect(addr).await.expect("connect to listener");
21780            let (mut read, write) = transport::plain_split(stream);
21781            let write: SharedWriteHalf =
21782                Arc::new(AsyncMutex::with_name("drain_cancel_test_write", write));
21783
21784            drain_cancel_wire(&mut read, &write, Duration::from_secs(5))
21785                .await
21786                .expect("drain-only cancel must succeed and leave the stream clean");
21787
21788            read_data_response(&mut read, &cx, &write)
21789                .await
21790                .expect("next read after drain must decode cleanly")
21791        });
21792
21793        assert_eq!(
21794            next, FRESH_BODY,
21795            "after drain-only cancel the reused connection must read the FRESH response"
21796        );
21797        server.join().expect("server thread joins");
21798    }
21799
21800    // The Scope-based cancel-on-drop guard. While a cancellable round trip's
21801    // read future is in flight the guard owns the InFlight recovery phase; if the
21802    // future is dropped (cancelled — e.g. by a `select!`/`timeout` racing it)
21803    // before the read completes, the guard's Drop moves the phase to BreakSent,
21804    // so the NEXT operation on the connection breaks + drains the stranded
21805    // server call rather than reassembling its leftover bytes as its own
21806    // response. A CLEAN completion calls `disarm()` first, so a normal read
21807    // returns the phase to Ready.
21808    #[test]
21809    fn cancel_drain_guard_transitions_recovery_phase_only_when_dropped_in_flight() -> Result<()> {
21810        let recovery = Arc::new(SessionRecovery::new());
21811
21812        // A guard dropped WITHOUT disarming (the future was cancelled mid-read):
21813        // the recovery phase records that a break/drain is required.
21814        {
21815            let _guard = CancelDrainGuard::arm(Arc::clone(&recovery))?;
21816            assert_eq!(recovery.phase(), SessionRecoveryPhase::InFlight);
21817        }
21818        assert_eq!(
21819            recovery.phase(),
21820            SessionRecoveryPhase::BreakSent,
21821            "dropping an armed guard (cancelled in flight) must require recovery"
21822        );
21823        assert!(recovery.begin_pending_drain()?);
21824        assert_eq!(recovery.phase(), SessionRecoveryPhase::Draining);
21825        assert!(
21826            recovery.begin_pending_drain().is_err(),
21827            "a drain that is already running must not start a second drain"
21828        );
21829        recovery.finish_drain_ready();
21830        assert_eq!(recovery.phase(), SessionRecoveryPhase::Ready);
21831
21832        // Strict operation starts require Ready; a second operation cannot start
21833        // while an earlier response is still in flight.
21834        recovery.begin_operation()?;
21835        match recovery.begin_operation() {
21836            Err(Error::ConnectionClosed(message)) => {
21837                assert!(message.contains("still in flight"));
21838            }
21839            other => {
21840                return Err(Error::Runtime(format!(
21841                    "second operation start should fail while InFlight, got {other:?}"
21842                )));
21843            }
21844        }
21845        recovery.complete_operation();
21846        assert_eq!(recovery.phase(), SessionRecoveryPhase::Ready);
21847
21848        // A response reader may adopt an already-sent prefetch request's
21849        // InFlight phase and complete it back to Ready.
21850        recovery.begin_operation()?;
21851        {
21852            let mut guard = CancelDrainGuard::arm(Arc::clone(&recovery))?;
21853            assert_eq!(recovery.phase(), SessionRecoveryPhase::InFlight);
21854            guard.disarm();
21855        }
21856        assert_eq!(recovery.phase(), SessionRecoveryPhase::Ready);
21857
21858        // A guard that DISARMS before drop (the read completed normally): the
21859        // phase returns to Ready and no recovery is needed.
21860        {
21861            let mut guard = CancelDrainGuard::arm(Arc::clone(&recovery))?;
21862            assert_eq!(recovery.phase(), SessionRecoveryPhase::InFlight);
21863            guard.disarm();
21864        }
21865        assert_eq!(
21866            recovery.phase(),
21867            SessionRecoveryPhase::Ready,
21868            "a disarmed guard (clean completion) must NOT require recovery"
21869        );
21870        Ok(())
21871    }
21872
21873    #[test]
21874    fn cancelled_error_is_not_connection_lost_but_is_transient() {
21875        let cancelled = Error::Cancelled;
21876        assert!(
21877            !cancelled.is_connection_lost(),
21878            "a user cancel leaves the session alive (ORA-01013 / DPY-4024 semantics)"
21879        );
21880        assert!(
21881            cancelled.is_transient(),
21882            "a cancelled operation may be retried on the same clean connection"
21883        );
21884        // ORA-01013 is the server-side code for user-requested cancel.
21885        assert_eq!(cancelled.ora_code(), Some(1013));
21886    }
21887
21888    // ------------------------------------------------------------------
21889    // Listener REDIRECT handling (bead rust-oracledb-pre23ai-connect-z47u.6)
21890    // ------------------------------------------------------------------
21891
21892    /// Reads one TNS packet from a test-listener socket, returning
21893    /// `(packet_type, packet_flags, payload)`.
21894    fn read_tns_packet_sync(
21895        socket: &mut std::net::TcpStream,
21896    ) -> std::io::Result<(u8, u8, Vec<u8>)> {
21897        let mut header = [0u8; 8];
21898        socket.read_exact(&mut header)?;
21899        let declared = usize::from(u16::from_be_bytes([header[0], header[1]]));
21900        let mut payload = vec![0u8; declared.saturating_sub(header.len())];
21901        socket.read_exact(&mut payload)?;
21902        Ok((header[4], header[5], payload))
21903    }
21904
21905    fn send_tns_packet_sync(
21906        socket: &mut std::net::TcpStream,
21907        packet_type: u8,
21908        payload: &[u8],
21909    ) -> std::io::Result<()> {
21910        use std::io::Write as _;
21911        let packet = encode_packet(packet_type, 0, None, payload, PacketLengthWidth::Legacy16)
21912            .expect("encode test packet");
21913        socket.write_all(&packet)
21914    }
21915
21916    /// The REDIRECT packet payload for `redirect_data`: u16be length prefix
21917    /// followed by the data bytes.
21918    fn redirect_packet_payload(redirect_data: &str) -> Vec<u8> {
21919        let bytes = redirect_data.as_bytes();
21920        let mut payload = Vec::with_capacity(2 + bytes.len());
21921        payload.extend_from_slice(
21922            &u16::try_from(bytes.len())
21923                .expect("test data fits")
21924                .to_be_bytes(),
21925        );
21926        payload.extend_from_slice(bytes);
21927        payload
21928    }
21929
21930    #[test]
21931    fn redirect_payload_prefix_accepts_inline_partial_and_rejects_truncated() {
21932        // Well-formed: length prefix + full inline data.
21933        let payload = redirect_packet_payload("abc");
21934        assert_eq!(redirect_payload_prefix(&payload).unwrap(), (3, &b"abc"[..]));
21935        // Declared length exceeding the inline bytes: the remainder arrives in
21936        // follow-up packets; the prefix reports what is available.
21937        assert_eq!(
21938            redirect_payload_prefix(&[0x00, 0x10, b'x']).unwrap(),
21939            (16, &b"x"[..])
21940        );
21941        // Length-only payload (data entirely in follow-up packets).
21942        assert_eq!(
21943            redirect_payload_prefix(&[0x00, 0x05]).unwrap(),
21944            (5, &[][..])
21945        );
21946        // Trailing bytes beyond the declared length are ignored.
21947        assert_eq!(
21948            redirect_payload_prefix(&[0x00, 0x01, b'a', b'b']).unwrap(),
21949            (1, &b"a"[..])
21950        );
21951        // Truncated: too short to even carry the u16 length.
21952        for bad in [&[][..], &[0x00][..]] {
21953            assert!(
21954                matches!(
21955                    redirect_payload_prefix(bad),
21956                    Err(Error::InvalidRedirectData(_))
21957                ),
21958                "payload {bad:?} must be rejected as malformed"
21959            );
21960        }
21961    }
21962
21963    #[test]
21964    fn parse_redirect_target_well_formed_and_malformed() {
21965        // Well-formed: "<address>\0<connect data>".
21966        let data = "(ADDRESS=(PROTOCOL=tcp)(HOST=dispatcher.example)(PORT=1621))\0\
21967                    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=dispatcher.example)(PORT=1621))\
21968                    (CONNECT_DATA=(SERVICE_NAME=svc)))";
21969        let target = parse_redirect_target(data, NetProtocol::Tcp).expect("well-formed redirect");
21970        assert_eq!(target.host, "dispatcher.example");
21971        assert_eq!(target.port, 1621);
21972        assert!(target.connect_data.starts_with("(DESCRIPTION="));
21973        // Missing the NUL separator between address and connect data.
21974        assert!(matches!(
21975            parse_redirect_target("(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1))", NetProtocol::Tcp),
21976            Err(Error::InvalidRedirectData(_))
21977        ));
21978        // Address part with no usable HOST.
21979        assert!(matches!(
21980            parse_redirect_target("(ADDRESS=(PROTOCOL=tcp)(PORT=1621))\0x", NetProtocol::Tcp),
21981            Err(Error::InvalidRedirectData(_))
21982        ));
21983        // Unparseable address part.
21984        assert!(matches!(
21985            parse_redirect_target("(((\0x", NetProtocol::Tcp),
21986            Err(Error::InvalidRedirectData(_))
21987        ));
21988    }
21989
21990    /// `Error::RedirectUnsupported` is kept ONLY for a redirect that demands a
21991    /// transport protocol change: a `tcps` connect is never downgraded to
21992    /// plain `tcp` (silent TLS strip), and a mid-connect `tcp` -> `tcps`
21993    /// upgrade is not supported. Same-protocol redirects are followed.
21994    #[test]
21995    fn parse_redirect_target_refuses_transport_protocol_change() {
21996        let tcp_addr = "(ADDRESS=(PROTOCOL=tcp)(HOST=h)(PORT=1521))\0cd";
21997        let tcps_addr = "(ADDRESS=(PROTOCOL=tcps)(HOST=h)(PORT=2484))\0cd";
21998        let no_protocol = "(ADDRESS=(HOST=h)(PORT=1521))\0cd";
21999        // tcps -> tcp downgrade refused, whether explicit or (fail closed)
22000        // because the redirect omitted the protocol.
22001        assert!(matches!(
22002            parse_redirect_target(tcp_addr, NetProtocol::Tcps),
22003            Err(Error::RedirectUnsupported)
22004        ));
22005        assert!(matches!(
22006            parse_redirect_target(no_protocol, NetProtocol::Tcps),
22007            Err(Error::RedirectUnsupported)
22008        ));
22009        // tcp -> tcps upgrade is not supported mid-connect.
22010        assert!(matches!(
22011            parse_redirect_target(tcps_addr, NetProtocol::Tcp),
22012            Err(Error::RedirectUnsupported)
22013        ));
22014        // Protocol preserved: followed.
22015        assert!(parse_redirect_target(tcps_addr, NetProtocol::Tcps).is_ok());
22016        assert!(parse_redirect_target(no_protocol, NetProtocol::Tcp).is_ok());
22017        assert!(parse_redirect_target(tcp_addr, NetProtocol::Tcp).is_ok());
22018    }
22019
22020    /// End-to-end redirect through real sockets: the first listener answers
22021    /// CONNECT with REDIRECT; the driver must reconnect to the redirected
22022    /// address and resend CONNECT there carrying TNS_PACKET_FLAG_REDIRECT and
22023    /// the redirect-supplied connect data. The target listener REFUSEs so the
22024    /// test ends before authentication; the surfaced ListenerRefused proves
22025    /// the whole redirect hop executed.
22026    #[test]
22027    fn connect_follows_listener_redirect_and_flags_the_new_connect() -> Result<()> {
22028        let redirect_listener = TcpListener::bind("127.0.0.1:0").expect("bind redirect listener");
22029        let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
22030        let redirect_addr = redirect_listener.local_addr().expect("redirect addr");
22031        let target_addr = target_listener.local_addr().expect("target addr");
22032        let redirect_connect_data = format!(
22033            "(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={}))\
22034             (CONNECT_DATA=(SERVICE_NAME=redirsvc)))",
22035            target_addr.port()
22036        );
22037        let redirect_data = format!(
22038            "(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={}))\0{}",
22039            target_addr.port(),
22040            redirect_connect_data
22041        );
22042
22043        let first = thread::spawn(move || -> std::io::Result<(u8, u8)> {
22044            let (mut socket, _) = redirect_listener.accept()?;
22045            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22046            let (packet_type, packet_flags, _payload) = read_tns_packet_sync(&mut socket)?;
22047            send_tns_packet_sync(
22048                &mut socket,
22049                TNS_PACKET_TYPE_REDIRECT,
22050                &redirect_packet_payload(&redirect_data),
22051            )?;
22052            Ok((packet_type, packet_flags))
22053        });
22054        let expected_connect_data = redirect_connect_data;
22055        let second = thread::spawn(move || -> std::io::Result<(u8, u8, bool)> {
22056            let (mut socket, _) = target_listener.accept()?;
22057            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22058            let (packet_type, packet_flags, payload) = read_tns_packet_sync(&mut socket)?;
22059            let carries_connect_data = payload
22060                .windows(expected_connect_data.len())
22061                .any(|window| window == expected_connect_data.as_bytes());
22062            send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_REFUSE, b"(ERR=12514)")?;
22063            Ok((packet_type, packet_flags, carries_connect_data))
22064        });
22065
22066        let options = ConnectOptions::new(
22067            format!("127.0.0.1:{}/redirsvc", redirect_addr.port()),
22068            "user",
22069            "password",
22070            identity(),
22071        );
22072        let runtime = build_io_runtime().expect("asupersync runtime");
22073        let err = runtime
22074            .block_on(async {
22075                let cx = Cx::current().expect("ambient Cx");
22076                Connection::connect(&cx, options).await
22077            })
22078            .expect_err("target listener refuses; the refusal must surface");
22079        assert!(
22080            matches!(&err, Error::ListenerRefused(msg) if msg.contains("ERR=12514")),
22081            "expected the TARGET listener's refusal, got {err:?}"
22082        );
22083        let (first_type, first_flags) = first.join().expect("redirect listener thread")?;
22084        assert_eq!(first_type, TNS_PACKET_TYPE_CONNECT);
22085        assert_eq!(first_flags, 0, "initial CONNECT carries no redirect flag");
22086        let (second_type, second_flags, carries_connect_data) =
22087            second.join().expect("target listener thread")?;
22088        assert_eq!(second_type, TNS_PACKET_TYPE_CONNECT);
22089        assert_eq!(
22090            second_flags, TNS_PACKET_FLAG_REDIRECT,
22091            "the CONNECT resent to the redirect target must carry the REDIRECT packet flag"
22092        );
22093        assert!(
22094            carries_connect_data,
22095            "the redirected CONNECT must carry the redirect-supplied connect data"
22096        );
22097        Ok(())
22098    }
22099
22100    /// Redirect/RESEND interplay plus chunked redirect data: the first
22101    /// listener asks for a RESEND before redirecting, and its REDIRECT packet
22102    /// carries only the u16 length (the data follows in a second REDIRECT
22103    /// packet). The redirected listener then ALSO asks for a RESEND — the
22104    /// resent CONNECT on the redirected connection must still carry the
22105    /// REDIRECT packet flag (reference keeps the flag on the recreated
22106    /// ConnectMessage across resends).
22107    #[test]
22108    fn connect_redirect_interleaves_with_resend_and_chunked_redirect_data() -> Result<()> {
22109        let redirect_listener = TcpListener::bind("127.0.0.1:0").expect("bind redirect listener");
22110        let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
22111        let redirect_addr = redirect_listener.local_addr().expect("redirect addr");
22112        let target_addr = target_listener.local_addr().expect("target addr");
22113        let redirect_data = format!(
22114            "(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={port}))\0\
22115             (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={port}))\
22116             (CONNECT_DATA=(SERVICE_NAME=redirsvc)))",
22117            port = target_addr.port()
22118        );
22119
22120        let first = thread::spawn(move || -> std::io::Result<()> {
22121            let (mut socket, _) = redirect_listener.accept()?;
22122            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22123            let _ = read_tns_packet_sync(&mut socket)?;
22124            // Ask for a resend BEFORE redirecting (pre-23ai listeners resend
22125            // routinely).
22126            send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_RESEND, &[])?;
22127            let _ = read_tns_packet_sync(&mut socket)?;
22128            // Chunked redirect: length-only REDIRECT packet, data in a
22129            // follow-up REDIRECT packet.
22130            let length = u16::try_from(redirect_data.len()).expect("test redirect data fits u16");
22131            send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_REDIRECT, &length.to_be_bytes())?;
22132            send_tns_packet_sync(
22133                &mut socket,
22134                TNS_PACKET_TYPE_REDIRECT,
22135                redirect_data.as_bytes(),
22136            )?;
22137            Ok(())
22138        });
22139        let second = thread::spawn(move || -> std::io::Result<(u8, u8)> {
22140            let (mut socket, _) = target_listener.accept()?;
22141            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22142            let (_, first_flags, _) = read_tns_packet_sync(&mut socket)?;
22143            // The redirected listener itself asks for a resend; the resent
22144            // CONNECT must still be redirect-flagged.
22145            send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_RESEND, &[])?;
22146            let (_, resent_flags, _) = read_tns_packet_sync(&mut socket)?;
22147            send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_REFUSE, b"(ERR=12514)")?;
22148            Ok((first_flags, resent_flags))
22149        });
22150
22151        let options = ConnectOptions::new(
22152            format!("127.0.0.1:{}/redirsvc", redirect_addr.port()),
22153            "user",
22154            "password",
22155            identity(),
22156        );
22157        let runtime = build_io_runtime().expect("asupersync runtime");
22158        let err = runtime
22159            .block_on(async {
22160                let cx = Cx::current().expect("ambient Cx");
22161                Connection::connect(&cx, options).await
22162            })
22163            .expect_err("target listener refuses; the refusal must surface");
22164        assert!(
22165            matches!(&err, Error::ListenerRefused(msg) if msg.contains("ERR=12514")),
22166            "expected the TARGET listener's refusal, got {err:?}"
22167        );
22168        first.join().expect("redirect listener thread")?;
22169        let (first_flags, resent_flags) = second.join().expect("target listener thread")?;
22170        assert_eq!(
22171            first_flags, TNS_PACKET_FLAG_REDIRECT,
22172            "redirected CONNECT must be flagged"
22173        );
22174        assert_eq!(
22175            resent_flags, TNS_PACKET_FLAG_REDIRECT,
22176            "a RESEND on the redirected connection must keep the redirect flag"
22177        );
22178        Ok(())
22179    }
22180
22181    /// A listener that answers every CONNECT with another REDIRECT (here: to
22182    /// itself) must terminate with a structured error instead of spinning
22183    /// forever — never a hang, never an opaque I/O error.
22184    #[test]
22185    fn connect_redirect_loop_is_bounded() -> Result<()> {
22186        let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
22187        let addr = listener.local_addr().expect("listener addr");
22188        let redirect_data = format!(
22189            "(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={port}))\0\
22190             (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT={port}))\
22191             (CONNECT_DATA=(SERVICE_NAME=loopsvc)))",
22192            port = addr.port()
22193        );
22194        let hops = u32::from(MAX_CONNECT_REDIRECT_ROUNDS) + 1;
22195        let server = thread::spawn(move || -> std::io::Result<u32> {
22196            let mut served = 0;
22197            // Initial connection plus MAX redirected reconnects, each answered
22198            // with a self-redirect.
22199            for _ in 0..hops {
22200                let (mut socket, _) = listener.accept()?;
22201                socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22202                let _ = read_tns_packet_sync(&mut socket)?;
22203                send_tns_packet_sync(
22204                    &mut socket,
22205                    TNS_PACKET_TYPE_REDIRECT,
22206                    &redirect_packet_payload(&redirect_data),
22207                )?;
22208                served += 1;
22209            }
22210            Ok(served)
22211        });
22212
22213        let options = ConnectOptions::new(
22214            format!("127.0.0.1:{}/loopsvc", addr.port()),
22215            "user",
22216            "password",
22217            identity(),
22218        );
22219        let runtime = build_io_runtime().expect("asupersync runtime");
22220        let err = runtime
22221            .block_on(async {
22222                let cx = Cx::current().expect("ambient Cx");
22223                Connection::connect(&cx, options).await
22224            })
22225            .expect_err("a redirect loop must terminate with a structured error");
22226        assert!(
22227            matches!(err, Error::ConnectRedirectLoop(rounds)
22228                if rounds == MAX_CONNECT_REDIRECT_ROUNDS + 1),
22229            "expected ConnectRedirectLoop, got {err:?}"
22230        );
22231        assert_eq!(err.kind(), ErrorKind::Protocol);
22232        let served = server.join().expect("listener thread")?;
22233        assert_eq!(served, hops, "every hop reached the listener");
22234        Ok(())
22235    }
22236
22237    /// A listener that answers every CONNECT with RESEND must terminate with
22238    /// a structured error instead of spinning forever, mirroring
22239    /// `connect_redirect_loop_is_bounded` above but for the RESEND bound.
22240    /// `Error::ConnectResendLoop` had zero test coverage before H5.
22241    #[test]
22242    fn connect_resend_loop_is_bounded() -> Result<()> {
22243        let listener = TcpListener::bind("127.0.0.1:0").expect("bind listener");
22244        let addr = listener.local_addr().expect("listener addr");
22245        let hops = u32::from(MAX_CONNECT_RESEND_ROUNDS) + 1;
22246        // Unlike a REDIRECT (a new connection to a new target), a RESEND is
22247        // answered on the SAME socket: the client just retransmits CONNECT.
22248        let server = thread::spawn(move || -> std::io::Result<u32> {
22249            let (mut socket, _) = listener.accept()?;
22250            socket.set_read_timeout(Some(Duration::from_secs(5)))?;
22251            let mut served = 0;
22252            for _ in 0..hops {
22253                let _ = read_tns_packet_sync(&mut socket)?;
22254                send_tns_packet_sync(&mut socket, TNS_PACKET_TYPE_RESEND, &[])?;
22255                served += 1;
22256            }
22257            Ok(served)
22258        });
22259
22260        let options = ConnectOptions::new(
22261            format!("127.0.0.1:{}/resendsvc", addr.port()),
22262            "user",
22263            "password",
22264            identity(),
22265        );
22266        let runtime = build_io_runtime().expect("asupersync runtime");
22267        let err = runtime
22268            .block_on(async {
22269                let cx = Cx::current().expect("ambient Cx");
22270                Connection::connect(&cx, options).await
22271            })
22272            .expect_err("a resend loop must terminate with a structured error");
22273        assert!(
22274            matches!(err, Error::ConnectResendLoop(rounds)
22275                if rounds == MAX_CONNECT_RESEND_ROUNDS + 1),
22276            "expected ConnectResendLoop, got {err:?}"
22277        );
22278        assert_eq!(err.kind(), ErrorKind::Protocol);
22279        let served = server.join().expect("listener thread")?;
22280        assert_eq!(served, hops, "every round reached the listener");
22281        Ok(())
22282    }
22283
22284    /// A multi-address `ADDRESS_LIST` where every address refuses the
22285    /// transport must aggregate into `Error::AllAddressesFailed` rather than
22286    /// surfacing only the last address's raw I/O error. Both addresses are
22287    /// distinct loopback addresses at destination port zero. TCP port zero
22288    /// cannot be allocated to a listener, so parallel tests cannot race to
22289    /// reuse it after fixture setup. No live database is needed; this is a pure
22290    /// transport failover test. `Error::AllAddressesFailed` had zero test
22291    /// coverage before H5.
22292    #[test]
22293    fn connect_all_addresses_failed_when_every_address_refuses() {
22294        let host_a = "127.0.0.1";
22295        let host_b = "127.0.0.2";
22296
22297        let connect_string = format!(
22298            "(DESCRIPTION=(RETRY_COUNT=0)\
22299             (ADDRESS_LIST=(ADDRESS=(PROTOCOL=tcp)(HOST={host_a})(PORT=0))\
22300             (ADDRESS=(PROTOCOL=tcp)(HOST={host_b})(PORT=0)))\
22301             (CONNECT_DATA=(SERVICE_NAME=svc)))"
22302        );
22303        let options = ConnectOptions::new(connect_string, "user", "password", identity());
22304        let runtime = build_io_runtime().expect("asupersync runtime");
22305        let err = runtime
22306            .block_on(async {
22307                let cx = Cx::current().expect("ambient Cx");
22308                Connection::connect(&cx, options).await
22309            })
22310            .expect_err("every address refuses; the aggregate must surface");
22311        assert!(
22312            matches!(&err, Error::AllAddressesFailed(detail) if detail.contains("tried 2 address(es)")
22313                && detail.contains(host_a) && detail.contains(host_b)),
22314            "expected AllAddressesFailed naming both addresses, got {err:?}"
22315        );
22316        assert_eq!(err.kind(), ErrorKind::Network);
22317    }
22318
22319    /// Public-API regression for bead rust-oracledb-4sfc: deterministic TLS
22320    /// preparation must finish before the first address is dialled. The wallet
22321    /// fixture has a valid CA certificate plus a malformed PKCS#8 client key,
22322    /// reproducing the configuration failure that used to occur only after TCP
22323    /// connect and could therefore be retried into an unrelated diagnostic.
22324    #[test]
22325    fn connection_connect_returns_tls_configuration_error_without_dialling() {
22326        let listener = TcpListener::bind("127.0.0.1:0").expect("bind dial sentinel");
22327        listener
22328            .set_nonblocking(true)
22329            .expect("make dial sentinel nonblocking");
22330        let port = listener.local_addr().expect("dial sentinel address").port();
22331        let wallet = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
22332            .join("tests/fixtures/tls/invalid_client_key");
22333        let options = ConnectOptions::new(
22334            format!("tcps://127.0.0.1:{port}/svc"),
22335            "user",
22336            "password",
22337            identity(),
22338        )
22339        .with_wallet_location(wallet.display().to_string());
22340
22341        let runtime = build_io_runtime().expect("asupersync runtime");
22342        let error = runtime
22343            .block_on(async {
22344                let cx = Cx::current().expect("ambient Cx");
22345                Connection::connect(&cx, options).await
22346            })
22347            .expect_err("the invalid client key must fail TLS preparation");
22348        assert!(
22349            matches!(&error, Error::Tls(detail) if detail.contains("private key")),
22350            "the original typed TLS configuration error must surface, got {error:?}"
22351        );
22352
22353        match listener.accept() {
22354            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
22355            Ok(_) => panic!("deterministic TLS configuration failure dialled the listener"),
22356            Err(error) => panic!("dial sentinel accept failed unexpectedly: {error}"),
22357        }
22358    }
22359
22360    // ------------------------------------------------------------------
22361    // Packet-layer vs TTC-layer error labelling
22362    // (bead rust-oracledb-pre23ai-connect-z47u.3)
22363    // ------------------------------------------------------------------
22364
22365    /// The packet-layer error text is self-triaging: it names known TNS
22366    /// packet types so a stray RESEND is never mistaken for TTC message 11
22367    /// (IO_VECTOR) — the mislabel that once steered a triage session toward
22368    /// SDU-reassembly hypotheses.
22369    #[test]
22370    fn unexpected_packet_error_names_tns_packet_types() {
22371        assert_eq!(
22372            Error::UnexpectedPacket(TNS_PACKET_TYPE_RESEND).to_string(),
22373            "unexpected TNS packet type 11 (RESEND)"
22374        );
22375        assert_eq!(
22376            Error::UnexpectedPacket(99).to_string(),
22377            "unexpected TNS packet type 99 (unknown)"
22378        );
22379    }
22380
22381    /// The flag-framed boundary reader's non-DATA arm reports the NETWORK
22382    /// packet type byte (header offset 4) as `Error::UnexpectedPacket`, not
22383    /// as a TTC `UnknownMessageType` (which names application-layer message
22384    /// types and previously mislabelled this byte with `position: 4`).
22385    #[test]
22386    fn flag_framed_reader_labels_non_data_packet_as_packet_layer_error() -> Result<()> {
22387        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
22388        let addr = listener.local_addr().expect("listener address");
22389        let server = thread::spawn(move || {
22390            let (mut socket, _) = listener.accept().expect("accept test client");
22391            use std::io::Write as _;
22392            let packet = encode_packet(
22393                TNS_PACKET_TYPE_RESEND,
22394                0,
22395                None,
22396                &[],
22397                PacketLengthWidth::Large32,
22398            )
22399            .expect("encode unexpected packet");
22400            socket.write_all(&packet).expect("write unexpected packet");
22401        });
22402
22403        let runtime = build_io_runtime().expect("asupersync runtime");
22404        let err = runtime.block_on(async {
22405            let cx = Cx::current().expect("ambient Cx");
22406            let stream = TcpStream::connect(addr).await.expect("connect to listener");
22407            let (read, write) = transport::plain_split(stream);
22408            let mut conn = loopback_connection(read, write);
22409            conn.core
22410                .read_data_response(&cx)
22411                .await
22412                .expect_err("non-DATA packet must fail closed")
22413        });
22414
22415        assert!(
22416            matches!(err, Error::UnexpectedPacket(TNS_PACKET_TYPE_RESEND)),
22417            "expected the packet-layer error, got {err:?}"
22418        );
22419        assert!(
22420            err.to_string().contains("TNS packet type 11 (RESEND)"),
22421            "error text must name the TNS packet type: {err}"
22422        );
22423        server.join().expect("server thread joins");
22424        Ok(())
22425    }
22426
22427    /// The break-drain reader (phase A: discarding in-flight responses until
22428    /// the break-acknowledge MARKER) likewise reports a stray non-DATA /
22429    /// non-MARKER packet as `Error::UnexpectedPacket` — a packet-layer byte,
22430    /// not a TTC message type.
22431    #[test]
22432    fn break_drain_labels_non_data_packet_as_packet_layer_error() -> Result<()> {
22433        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local listener");
22434        let addr = listener.local_addr().expect("listener address");
22435        let server = thread::spawn(move || {
22436            let (mut socket, _) = listener.accept().expect("accept test client");
22437            use std::io::Write as _;
22438            let packet = encode_packet(
22439                TNS_PACKET_TYPE_ACCEPT,
22440                0,
22441                None,
22442                &[0x00],
22443                PacketLengthWidth::Large32,
22444            )
22445            .expect("encode unexpected packet");
22446            socket.write_all(&packet).expect("write unexpected packet");
22447        });
22448
22449        let runtime = build_io_runtime().expect("asupersync runtime");
22450        let err = runtime.block_on(async {
22451            let stream = TcpStream::connect(addr).await.expect("connect to listener");
22452            let (mut read, write) = transport::plain_split(stream);
22453            let write = Arc::new(AsyncMutex::with_name("break_drain_test_write", write));
22454            drain_break_response_recovery(&mut read, &write)
22455                .await
22456                .expect_err("non-DATA/non-MARKER packet must fail closed")
22457        });
22458
22459        assert!(
22460            matches!(err, Error::UnexpectedPacket(TNS_PACKET_TYPE_ACCEPT)),
22461            "expected the packet-layer error, got {err:?}"
22462        );
22463        assert!(
22464            err.to_string().contains("TNS packet type 2 (ACCEPT)"),
22465            "error text must name the TNS packet type: {err}"
22466        );
22467        server.join().expect("server thread joins");
22468        Ok(())
22469    }
22470}