Skip to main content

camel_component_sql/
session.rs

1//! Block-owned transaction session over a guarded pooled connection.
2//!
3//! [`SqlTxSession`] is the concrete [`TransactionSession`] implementation for
4//! `transacted { datasource }` blocks: the sql component's `Arc::downcast`
5//! target reached through the port's `Any` supertrait upcast. It is the sole
6//! owner of its pooled connection (the connection is never stored in exchange
7//! extensions), armed with a discard guard from checkout until an acknowledged
8//! finalization: any phase except `Done`/`Detached` dropped out from under the
9//! session detaches the connection synchronously (R0, `DiscardOnDrop`).
10//!
11//! The lifecycle keys on a private `TxPhase`, never on the frozen
12//! [`TransactionState`]: "BEGIN bytes may be on the wire" and "COMMIT handed
13//! off" drive the finalization decision but cannot be expressed by the port
14//! enum (604c §A). `BEGIN` / `COMMIT` /
15//! `ROLLBACK` are issued as plain statements on the borrowed
16//! connection — no sqlx `Transaction` wrapper is ever stored, and the borrow
17//! is confined to one await scope inside this module.
18//!
19//! Unit-tier testability without Docker: the driver-facing statement IO is
20//! behind the private `TxIo` trait (the real backend is
21//! `AnyConnIo` over an `AnyPool` connection; fixtures script a fake), and
22//! the time source is behind `TxTimer` (the default `TokioTimer` runs on
23//! tokio's clock, so `start_paused` tests get a virtual clock; an injected
24//! timer replaces it). The camel-api port is untouched by both seams.
25//!
26//! Rulings: `.opencode/fleet/orders/604c-sqltrans-s2-ruling.md` (§A/§B) and
27//! `604d-sqltrans-s2-ruling2.md` (total rollback contract). Binding
28//! precedence: `openspec/changes/sqltrans/specs/sql-transactions/spec.md`.
29
30use std::future::Future;
31use std::pin::Pin;
32use std::sync::Arc;
33use std::sync::Mutex as SyncMutex;
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::time::Duration;
36
37use camel_api::transaction::{
38    BeginFuture, FinalizeFuture, TransactionError, TransactionOutcome, TransactionSession,
39    TransactionState,
40};
41use sqlx::Any;
42use sqlx::AnyPool;
43use sqlx::pool::PoolConnection;
44use tokio::sync::Mutex as AsyncMutex;
45
46/// Fixed finalize grace (604c §A): one absolute deadline,
47/// `finalize_start + 5 s`, covering every finalization SQL in the run
48/// (COMMIT plus any cleanup ROLLBACK). A seam parameter, not a second knob:
49/// the open path always uses this constant.
50const FINALIZE_GRACE: Duration = Duration::from_secs(5);
51
52const SQL_BEGIN: &str = "BEGIN";
53const SQL_COMMIT: &str = "COMMIT";
54const SQL_ROLLBACK: &str = "ROLLBACK";
55
56/// Private lifecycle phase behind the frozen port enum (604c §A).
57///
58/// `Clean`/`BeginPending`/`Open`/`Detached` are the phases finalization can
59/// legally enter; only this module's begin/commit/rollback paths move the
60/// phase into `*InFlight`/`Done`.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62enum TxPhase {
63    /// Hygiene acknowledged, nothing sent.
64    Clean,
65    /// Set before the BEGIN write; cleared only by the ACK.
66    BeginPending,
67    /// BEGIN acknowledged.
68    Open,
69    /// Set immediately before the COMMIT write.
70    CommitInFlight,
71    /// ROLLBACK sent, not yet acknowledged.
72    RollbackInFlight,
73    /// Acknowledged finalization, guard disarmed.
74    Done,
75    /// Connection discarded; terminal.
76    Detached,
77}
78
79/// Projects [`TxPhase`] onto the frozen [`TransactionState`], row for row
80/// per the 604c §A table (`BeginPending → Fresh` is lossy by design: nothing
81/// may decide on `state()`).
82#[must_use]
83fn project(phase: TxPhase) -> TransactionState {
84    match phase {
85        TxPhase::Clean | TxPhase::BeginPending => TransactionState::Fresh,
86        TxPhase::Open => TransactionState::Active,
87        TxPhase::CommitInFlight | TxPhase::RollbackInFlight => TransactionState::Finalizing,
88        TxPhase::Done => TransactionState::Done,
89        TxPhase::Detached => TransactionState::Detached,
90    }
91}
92
93/// Driver-neutral severity: only the PG driver's exact `ERROR` severity
94/// counts as affirmative rejection evidence (604c R7); `FATAL`/`PANIC`
95/// (57P01), warnings/notices, and unmapped drivers are not evidence.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97enum DbSeverity {
98    Error,
99    Other,
100}
101
102/// Affirmative database error, driver-neutral: severity, SQLSTATE, message.
103#[derive(Debug, Clone)]
104pub(crate) struct DbAnswer {
105    severity: DbSeverity,
106    code: Option<String>,
107    message: String,
108}
109
110/// Statement failure seen by the session.
111#[derive(Debug, Clone)]
112pub(crate) enum TxIoFailure {
113    /// The server answered with an affirmative database error.
114    Database(DbAnswer),
115    /// Transport/protocol/pool failure or a connection with no driver
116    /// mapping: the statement's outcome is unknown.
117    Lost,
118}
119
120/// R7 disposition of a failed COMMIT.
121enum CommitDisposition {
122    /// Affirmative rejection: severity exactly `ERROR` AND SQLSTATE class
123    /// `23` (integrity) or `40` (transaction abort — the server affirms the
124    /// transaction is over).
125    Rejected {
126        /// Driver-reported detail carried into `CommitFailed`.
127        reason: String,
128    },
129    /// Everything else: `FATAL`/`PANIC` severity (57P01), other classes,
130    /// Io, Protocol, PoolClosed — uncertain, detach, no rollback claim.
131    Lost,
132}
133
134/// Classifies a COMMIT failure per the R7 rows.
135#[must_use]
136fn commit_disposition(failure: &TxIoFailure) -> CommitDisposition {
137    let TxIoFailure::Database(answer) = failure else {
138        return CommitDisposition::Lost;
139    };
140    let reject_class = answer
141        .code
142        .as_deref()
143        .is_some_and(|code| code.starts_with("23") || code.starts_with("40"));
144    if answer.severity == DbSeverity::Error && reject_class {
145        CommitDisposition::Rejected {
146            reason: match answer.code.as_deref() {
147                Some(code) => format!("SQLSTATE {code}: {}", answer.message),
148                None => answer.message.clone(),
149            },
150        }
151    } else {
152        CommitDisposition::Lost
153    }
154}
155
156/// Boxed one-statement execution against the guarded connection.
157type ExecFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TxIoFailure>> + Send + 'a>>;
158
159/// Driver-facing statement IO for one checked-out connection.
160///
161/// The real backend ([`AnyConnIo`]) wraps the pooled `AnyConnection`; the
162/// unit fixtures script a fake. This seam is what keeps the session's phase
163/// machine unit-tier testable without Docker; the camel-api port stays
164/// untouched.
165pub(crate) trait TxIo: Send + 'static {
166    /// Execute one plain statement (`BEGIN`/`COMMIT`/`ROLLBACK`) on the
167    /// guarded connection. The returned future must record the statement only
168    /// when actually polled, so a future dropped by a deadline race counts as
169    /// never issued.
170    fn exec(&mut self, sql: &'static str) -> ExecFuture<'_>;
171
172    /// Detach synchronously: close/discard the connection, never return it
173    /// to the pool, send no SQL (R0/R3 semantics).
174    fn detach(&mut self);
175
176    /// Return the connection to the pool (guard disarmed). Consumes the
177    /// backend.
178    fn release(self: Box<Self>);
179}
180
181/// Real backend: sole owner of one pooled `AnyConnection`.
182struct AnyConnIo {
183    conn: Option<PoolConnection<Any>>,
184}
185
186impl TxIo for AnyConnIo {
187    fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
188        Box::pin(async move {
189            let Some(conn) = self.conn.as_mut() else {
190                return Err(TxIoFailure::Lost);
191            };
192            match sqlx::query(sqlx::AssertSqlSafe(sql))
193                .execute(&mut **conn)
194                .await
195            {
196                Ok(_) => Ok(()),
197                Err(error) => Err(to_io_failure(&error)),
198            }
199        })
200    }
201
202    fn detach(&mut self) {
203        // Detach first so the pool never sees this connection again; dropping
204        // the detached handle closes it (same convention as the producer's
205        // `DiscardOnDrop` guard).
206        if let Some(conn) = self.conn.take() {
207            drop(conn.detach());
208        }
209    }
210
211    fn release(self: Box<Self>) {
212        // Dropping the `PoolConnection` returns it to the pool.
213        drop(self);
214    }
215}
216
217/// Placeholder left in the admission slot once the real backend left it
218/// (released or detached): every statement on it fails lost, so latent misuse
219/// can never touch a connection that no longer belongs to the session.
220struct DetachedIo;
221
222impl TxIo for DetachedIo {
223    fn exec(&mut self, _sql: &'static str) -> ExecFuture<'_> {
224        Box::pin(std::future::ready(Err(TxIoFailure::Lost)))
225    }
226
227    fn detach(&mut self) {}
228
229    fn release(self: Box<Self>) {}
230}
231
232/// Checkout guard: sole owner of the checked-out backend from the instant
233/// `pool.acquire()` resolves until the session takes ownership.
234///
235/// R0 arms AT checkout (frozen spec: "The discard guard is armed on
236/// connection checkout"): dropping this guard — the open future dying
237/// mid-hygiene, any error path in `open` — detaches synchronously, so a
238/// connection whose statement outcome is unknown is never returned to the
239/// pool. The guard is disarmed exactly on the `with_io` hand-off, where the
240/// session's own [`Drop`] guard takes over.
241struct CheckedOutBackend {
242    io: Option<Box<dyn TxIo>>,
243}
244
245impl CheckedOutBackend {
246    /// Arms the guard over the freshly checked-out backend.
247    fn arm(io: Box<dyn TxIo>) -> Self {
248        Self { io: Some(io) }
249    }
250
251    /// Hands the backend to the guard-bearing session; the guard no longer
252    /// owns it. Only called after the admission hygiene acknowledged.
253    fn disarm(mut self) -> Box<dyn TxIo> {
254        match self.io.take() {
255            Some(io) => io,
256            None => {
257                // Unreachable for a correct hand-off (the slot holds the
258                // backend until this call), but the session must fail
259                // closed rather than panic: the lost placeholder makes
260                // every statement error and the guard still disarms.
261                // log-policy: system-broken
262                tracing::error!(
263                    "checked-out backend missing at the with_io hand-off; \
264                     the session continues on the lost placeholder"
265                );
266                Box::new(DetachedIo)
267            }
268        }
269    }
270}
271
272impl TxIo for CheckedOutBackend {
273    fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
274        let Some(io) = self.io.as_mut() else {
275            return Box::pin(std::future::ready(Err(TxIoFailure::Lost)));
276        };
277        io.exec(sql)
278    }
279
280    fn detach(&mut self) {
281        // Delegates to the backend (idempotent): the slot empties, so the
282        // guard's own Drop stays a no-op.
283        if let Some(mut io) = self.io.take() {
284            io.detach();
285        }
286    }
287
288    fn release(mut self: Box<Self>) {
289        if let Some(io) = self.io.take() {
290            io.release();
291        }
292    }
293}
294
295impl Drop for CheckedOutBackend {
296    fn drop(&mut self) {
297        if let Some(mut io) = self.io.take() {
298            io.detach();
299        }
300    }
301}
302
303/// Maps a sqlx error onto the driver-neutral failure.
304fn to_io_failure(error: &sqlx::Error) -> TxIoFailure {
305    match error {
306        sqlx::Error::Database(db) => TxIoFailure::Database(DbAnswer {
307            severity: db_severity(&**db),
308            code: db.code().as_deref().map(str::to_owned),
309            message: db.message().to_owned(),
310        }),
311        // Io, Protocol, PoolClosed, PoolTimedOut, WorkerCrashed, ...: the
312        // outcome is unknown.
313        _ => TxIoFailure::Lost,
314    }
315}
316
317/// PG severity mapping, fail-closed: only the PG driver's exact `ERROR`
318/// severity counts as [`DbSeverity::Error`] (604c R7 names 57P01 — a
319/// `FATAL` — as the `CommitUncertain` shape, so severity must be exact).
320#[cfg(feature = "postgres")]
321fn db_severity(db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
322    match db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>() {
323        Some(pg) if pg.severity() == sqlx::postgres::PgSeverity::Error => DbSeverity::Error,
324        _ => DbSeverity::Other,
325    }
326}
327
328/// Non-PG builds cannot prove severity: not affirmative evidence.
329#[cfg(not(feature = "postgres"))]
330fn db_severity(_db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
331    DbSeverity::Other
332}
333
334/// Time source for the session's deadlines (absolute instants per the
335/// spec's "Deadlines are compared as absolute instants" clause).
336///
337/// The default [`TokioTimer`] runs on tokio's clock: real when unpaused and
338/// fully virtual under `#[tokio::test(start_paused = true)]`. Tests may
339/// inject any other [`TxTimer`] through
340/// [`SqlTxSession::with_io`].
341pub(crate) trait TxTimer: Send + Sync + 'static {
342    /// Absolute now.
343    fn now(&self) -> tokio::time::Instant;
344
345    /// Sleep until the absolute instant.
346    fn sleep_until(
347        &self,
348        deadline: tokio::time::Instant,
349    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
350}
351
352/// Default timer on tokio's clock.
353struct TokioTimer;
354
355impl TxTimer for TokioTimer {
356    fn now(&self) -> tokio::time::Instant {
357        tokio::time::Instant::now()
358    }
359
360    fn sleep_until(
361        &self,
362        deadline: tokio::time::Instant,
363    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
364        Box::pin(tokio::time::sleep_until(deadline))
365    }
366}
367
368/// Outcome of one deadline-raced statement.
369#[derive(Debug)]
370enum StmtOutcome {
371    /// The driver acknowledged the statement.
372    Ack,
373    /// The deadline fired before the driver answered.
374    Deadline,
375    /// The driver answered with an error.
376    Failed(TxIoFailure),
377}
378
379/// Executes one plain statement raced against an absolute deadline.
380///
381/// Biased with the deadline arm first, so a tie resolves like the ruling's
382/// tie rule (deadline wins). The losing future is dropped by the race; the
383/// connection state is then unknown and every caller detaches or reports
384/// uncertainty accordingly.
385async fn run_statement(
386    io: &mut dyn TxIo,
387    sql: &'static str,
388    deadline: tokio::time::Instant,
389    timer: &dyn TxTimer,
390) -> StmtOutcome {
391    tokio::select! {
392        biased;
393        _ = timer.sleep_until(deadline) => StmtOutcome::Deadline,
394        result = io.exec(sql) => match result {
395            Ok(()) => StmtOutcome::Ack,
396            Err(failure) => StmtOutcome::Failed(failure),
397        },
398    }
399}
400
401/// Milliseconds elapsed on the injected clock since `since`.
402fn elapsed_ms(timer: &dyn TxTimer, since: tokio::time::Instant) -> u64 {
403    u64::try_from(timer.now().saturating_duration_since(since).as_millis()).unwrap_or(u64::MAX)
404}
405
406/// One block-owned transaction on one datasource.
407///
408/// The session owns its pooled connection as sole owner through the
409/// admission slot (a `tokio::sync::Mutex` around the `TxIo` backend: the
410/// slot IS the one-statement-at-a-time admission, `try_lock` → `Busy`), the
411/// discard guard is that same ownership armed from checkout — dropping the
412/// session in any phase except `Done`/`Detached` detaches synchronously
413/// (R0). `rollback_only` is the port's atomic flag.
414///
415/// Constructed through `open` (checkout + admission hygiene
416/// → `Clean`) by the datasource manager; unit fixtures construct directly
417/// over a scripted backend via `with_io`.
418pub struct SqlTxSession {
419    datasource: Arc<str>,
420    /// Admission slot: `try_lock` → one statement at a time; holds the
421    /// guarded connection backend.
422    slot: AsyncMutex<Box<dyn TxIo>>,
423    /// Private phase; short critical sections, never held across an await.
424    phase: SyncMutex<TxPhase>,
425    /// The port's rollback-only flag (req 4: handled joined DB errors).
426    rollback_only: AtomicBool,
427    /// Injected time source.
428    timer: Arc<dyn TxTimer>,
429    /// Bound for the lazy BEGIN (604c §B.2: `begin_start + acquire_deadline`).
430    acquire_deadline: Duration,
431    /// Finalize grace: `finalize_start + finalize_grace` covers every
432    /// finalization SQL in the run.
433    finalize_grace: Duration,
434    /// Pool size for `PoolExhausted` naming.
435    max_connections: u32,
436}
437
438impl SqlTxSession {
439    /// Builds a session in [`TxPhase::Clean`] over an already-checked-out,
440    /// hygiene-acknowledged backend.
441    ///
442    /// `finalize_grace` is a seam for virtual-clock fixtures; the open path
443    /// always uses [`FINALIZE_GRACE`].
444    pub(crate) fn with_io(
445        datasource: impl Into<Arc<str>>,
446        io: Box<dyn TxIo>,
447        timer: Arc<dyn TxTimer>,
448        acquire_deadline: Duration,
449        finalize_grace: Duration,
450        max_connections: u32,
451    ) -> Self {
452        Self {
453            datasource: datasource.into(),
454            slot: AsyncMutex::new(io),
455            phase: SyncMutex::new(TxPhase::Clean),
456            rollback_only: AtomicBool::new(false),
457            timer,
458            acquire_deadline,
459            finalize_grace,
460            max_connections,
461        }
462    }
463
464    /// Admission path for the datasource manager's `open_session`: check out
465    /// a pooled connection, run the hygiene `ROLLBACK` exactly once, land in
466    /// [`TxPhase::Clean`].
467    ///
468    /// Checkout and hygiene race the same absolute instants —
469    /// `min(block_abs, open_start + acquire_deadline)` (604c admission) — and
470    /// the winner is decided by comparing those instants, never by polling
471    /// order: `PoolExhausted` iff `acquire_abs < block_abs` strictly, else
472    /// `Timeout` (tie included). The guard arms at checkout: the backend owns
473    /// the connection from the moment the checkout future resolves, so a
474    /// failure after that detaches. Exactly one `ROLLBACK` attempt is made
475    /// even when a deadline fires (the race drops the in-flight future).
476    /// `BEGIN` is never sent here.
477    pub(crate) async fn open(
478        datasource: impl Into<Arc<str>>,
479        pool: &AnyPool,
480        block_abs: tokio::time::Instant,
481        acquire_deadline: Duration,
482        timer: Arc<dyn TxTimer>,
483    ) -> Result<Self, TransactionError> {
484        let datasource = datasource.into();
485        let max_connections = crate::pool_factory::pool_max_connections(pool);
486        let open_start = timer.now();
487        let acquire_abs = open_start + acquire_deadline;
488
489        let conn = tokio::select! {
490            biased;
491            _ = timer.sleep_until(block_abs) => {
492                // Frozen spec "Block timeout": deadlines are compared as
493                // absolute instants, never by polling order. When this arm
494                // wins while the acquire deadline is strictly earlier, both
495                // instants have passed at the same poll and the admission
496                // reports `PoolExhausted`; the tie and any block-first
497                // ordering report `Timeout`.
498                if acquire_abs < block_abs {
499                    return Err(TransactionError::PoolExhausted {
500                        datasource: datasource.to_string(),
501                        max_connections,
502                        waited_ms: elapsed_ms(timer.as_ref(), open_start),
503                    });
504                }
505                return Err(TransactionError::Timeout {
506                    datasource: datasource.to_string(),
507                    // Elapsed time since the block entry (open start), not
508                    // since the deadline: the typed error names datasource
509                    // and elapsed time (frozen spec "Block timeout").
510                    elapsed_ms: elapsed_ms(timer.as_ref(), open_start),
511                });
512            }
513            _ = timer.sleep_until(acquire_abs) => {
514                return Err(TransactionError::PoolExhausted {
515                    datasource: datasource.to_string(),
516                    max_connections,
517                    waited_ms: elapsed_ms(timer.as_ref(), open_start),
518                });
519            }
520            acquired = pool.acquire() => {
521                acquired.map_err(|_| TransactionError::PoolExhausted {
522                    datasource: datasource.to_string(),
523                    max_connections,
524                    waited_ms: elapsed_ms(timer.as_ref(), open_start),
525                })?
526            }
527        };
528
529        // R0 arms AT checkout (frozen spec: "The discard guard is armed on
530        // connection checkout"): from this instant the guard owns the
531        // connection, so a dropped open future mid-hygiene detaches instead
532        // of re-pooling. The guard disarms exactly at the `with_io` hand-off
533        // inside [`Self::admit`].
534        let backend = CheckedOutBackend::arm(Box::new(AnyConnIo { conn: Some(conn) }));
535        Self::admit(
536            datasource,
537            backend,
538            block_abs,
539            acquire_abs,
540            acquire_deadline,
541            max_connections,
542            timer,
543        )
544        .await
545    }
546
547    /// Admission tail shared by [`SqlTxSession::open`] and the unit fixtures:
548    /// hygiene `ROLLBACK` against the already-armed checkout guard, then the
549    /// disarm into the guard-bearing session. Crate-visible so the fixtures
550    /// can drive the checkout guard over a scripted backend.
551    async fn admit(
552        datasource: Arc<str>,
553        backend: CheckedOutBackend,
554        block_abs: tokio::time::Instant,
555        acquire_abs: tokio::time::Instant,
556        acquire_deadline: Duration,
557        max_connections: u32,
558        timer: Arc<dyn TxTimer>,
559    ) -> Result<Self, TransactionError> {
560        let mut backend = backend;
561        admission_hygiene(
562            &mut backend,
563            Arc::clone(&timer),
564            &datasource,
565            max_connections,
566            block_abs,
567            acquire_abs,
568        )
569        .await?;
570
571        Ok(Self::with_io(
572            datasource,
573            backend.disarm(),
574            timer,
575            acquire_deadline,
576            FINALIZE_GRACE,
577            max_connections,
578        ))
579    }
580
581    /// Manager entry point over a real pool: `open` on the
582    /// default tokio clock.
583    ///
584    /// The injectable-clock `open` stays crate-private for the
585    /// unit fixtures; this wrapper is the constructor the datasource manager
586    /// (sqltrans-exec step 9) and the PG integration suite
587    /// (`crates/camel-test/tests/sql_transacted_test.rs`) drive.
588    pub async fn open_on_pool(
589        datasource: impl Into<Arc<str>>,
590        pool: &AnyPool,
591        block_abs: tokio::time::Instant,
592        acquire_deadline: Duration,
593    ) -> Result<Self, TransactionError> {
594        Self::open(
595            datasource,
596            pool,
597            block_abs,
598            acquire_deadline,
599            Arc::new(TokioTimer),
600        )
601        .await
602    }
603
604    /// Test-support statement execution on the session's own connection: the
605    /// body-side counterpart of a joined `sql:` step once the executor lends
606    /// this connection to the producer (sqltrans-exec step 9).
607    ///
608    /// One plain statement through the same admission slot the block owns —
609    /// an overlapping admission observes the held-slot arm — and never
610    /// finalizes the transaction. The PG integration fixtures use it to put
611    /// rows inside the session's transaction before the segment commits or
612    /// rolls back; the executor's lent-connection path is the supported
613    /// surface, not this helper.
614    ///
615    /// Returns the driver message on failure: the fixtures assert a
616    /// statement's success, not a typed session outcome.
617    ///
618    /// `#[doc(hidden)]`: remove when the producer lends the session
619    /// connection (executor slice).
620    #[doc(hidden)]
621    pub async fn exec_statement_for_test(&self, sql: &'static str) -> Result<(), String> {
622        let Ok(mut slot) = self.slot.try_lock() else {
623            return Err(TransactionError::Busy {
624                datasource: self.datasource.to_string(),
625            }
626            .to_string());
627        };
628        match slot.exec(sql).await {
629            Ok(()) => Ok(()),
630            Err(TxIoFailure::Database(answer)) => Err(format!(
631                "statement `{sql}` failed: SQLSTATE {}: {}",
632                answer.code.as_deref().unwrap_or("-"),
633                answer.message
634            )),
635            Err(TxIoFailure::Lost) => Err(format!(
636                "statement `{sql}` lost the connection (outcome unknown)"
637            )),
638        }
639    }
640
641    fn phase(&self) -> TxPhase {
642        *self
643            .phase
644            .lock()
645            .unwrap_or_else(std::sync::PoisonError::into_inner)
646    }
647
648    fn store_phase(&self, phase: TxPhase) {
649        *self
650            .phase
651            .lock()
652            .unwrap_or_else(std::sync::PoisonError::into_inner) = phase;
653    }
654
655    /// Detaches through the slot: connection closed/discarded, never
656    /// re-pooled, no SQL; phase → `Detached` (terminal).
657    fn detach_slot(&self, slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
658        slot.detach();
659        let _ = std::mem::replace(&mut **slot, Box::new(DetachedIo));
660        self.store_phase(TxPhase::Detached);
661    }
662
663    /// `begin()` per 604c §B, verbatim.
664    ///
665    /// The slot lock orders every begin state transition: the phase is judged
666    /// INSIDE the lock, so a concurrent begin that detaches (§B.4/§B.5)
667    /// between this call's admission and its write can never be overwritten —
668    /// `Detached` is terminal and is never transitioned from (§B.1).
669    async fn begin_inner(&self) -> Result<(), TransactionError> {
670        let datasource = self.datasource.to_string();
671        let Ok(mut slot) = self.slot.try_lock() else {
672            // §B.1 requires the slot to judge the phase; a held slot means
673            // another begin/statement is mid-flight — the frozen Busy row.
674            return Err(TransactionError::Busy { datasource });
675        };
676        match self.phase() {
677            TxPhase::Open => return Ok(()),
678            TxPhase::Clean => {}
679            _ => return Err(TransactionError::SessionAborted { datasource }),
680        }
681        // §A/§B: BeginPending goes up BEFORE the BEGIN write and is cleared
682        // only by the ACK, so a dropped future stays BeginPending (R3/R0).
683        self.store_phase(TxPhase::BeginPending);
684        let begin_start = self.timer.now();
685        let deadline = begin_start + self.acquire_deadline;
686        match run_statement(&mut **slot, SQL_BEGIN, deadline, self.timer.as_ref()).await {
687            StmtOutcome::Ack => {
688                self.store_phase(TxPhase::Open);
689                Ok(())
690            }
691            StmtOutcome::Deadline => {
692                // §B.4: own timeout → detach, `PoolExhausted`; NO cleanup SQL.
693                self.detach_slot(&mut slot);
694                Err(TransactionError::PoolExhausted {
695                    datasource,
696                    max_connections: self.max_connections,
697                    waited_ms: elapsed_ms(self.timer.as_ref(), begin_start),
698                })
699            }
700            StmtOutcome::Failed(_) => {
701                // §B.5: any driver error → detach, `RollbackUncertain`; NO
702                // cleanup SQL (protocol position unknown, nothing durable).
703                self.detach_slot(&mut slot);
704                Err(TransactionError::RollbackUncertain { datasource })
705            }
706        }
707    }
708
709    /// `commit()` per 604d + R7.
710    async fn commit_inner(&self) -> Result<TransactionOutcome, TransactionError> {
711        let datasource = self.datasource.to_string();
712        // Port contract: precondition `Active`; otherwise no SQL.
713        if self.phase() != TxPhase::Open {
714            return Err(TransactionError::SessionAborted { datasource });
715        }
716        let Ok(mut slot) = self.slot.try_lock() else {
717            // Unreachable for a correct owner (finalization happens after the
718            // body); a held slot means the commit cannot be verified.
719            // log-policy: system-broken
720            tracing::error!(
721                datasource = %self.datasource,
722                "commit while the session slot is held; the commit outcome cannot be verified"
723            );
724            return Err(TransactionError::CommitUncertain { datasource });
725        };
726        let finalize_start = self.timer.now();
727        let grace_deadline = finalize_start + self.finalize_grace;
728        // R7: handed-off marker set immediately before the COMMIT write.
729        // After the handoff the block deadline and cancellation are never
730        // consulted — only this finalize grace applies.
731        self.store_phase(TxPhase::CommitInFlight);
732        match run_statement(&mut **slot, SQL_COMMIT, grace_deadline, self.timer.as_ref()).await {
733            StmtOutcome::Ack => {
734                self.store_phase(TxPhase::Done);
735                release_to_pool(&mut slot);
736                Ok(TransactionOutcome::Committed)
737            }
738            StmtOutcome::Deadline => {
739                // Grace elapsed: uncertain, detach, no ROLLBACK, no claim.
740                self.detach_slot(&mut slot);
741                Err(TransactionError::CommitUncertain { datasource })
742            }
743            StmtOutcome::Failed(failure) => match commit_disposition(&failure) {
744                CommitDisposition::Lost => {
745                    // R7: FATAL/PANIC severity (57P01), other SQLSTATE
746                    // classes, Io, Protocol, PoolClosed — detach immediately;
747                    // no ROLLBACK, no rollback claim.
748                    self.detach_slot(&mut slot);
749                    Err(TransactionError::CommitUncertain { datasource })
750                }
751                CommitDisposition::Rejected { reason } => {
752                    // ONE cleanup ROLLBACK within the remaining grace (a
753                    // no-op WARNING on PG). The frozen spec WINS over 604c
754                    // R7's sub-row: a COMMIT rejected by the database SHALL
755                    // fail with the typed `CommitFailed` in BOTH cleanup
756                    // outcomes — the cleanup uncertainty stays observable
757                    // through the warn! log and the `Detached` state and
758                    // never replaces the primary.
759                    match run_statement(
760                        &mut **slot,
761                        SQL_ROLLBACK,
762                        grace_deadline,
763                        self.timer.as_ref(),
764                    )
765                    .await
766                    {
767                        StmtOutcome::Ack => {
768                            self.store_phase(TxPhase::Done);
769                            release_to_pool(&mut slot);
770                            // 604d: the session returns only the cleanup
771                            // result or the typed commit result — the
772                            // segment owns primary-vs-cleanup separation.
773                            Err(TransactionError::CommitFailed { datasource, reason })
774                        }
775                        StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
776                            self.detach_slot(&mut slot);
777                            // log-policy: cleanup-uncertainty — logged, never
778                            // substituted for the primary.
779                            tracing::warn!(
780                                datasource = %self.datasource,
781                                "COMMIT was rejected and the cleanup ROLLBACK was \
782                                 not acknowledged; the connection is detached and \
783                                 the typed CommitFailed stands"
784                            );
785                            Err(TransactionError::CommitFailed { datasource, reason })
786                        }
787                    }
788                }
789            },
790        }
791    }
792
793    /// Total `rollback()` per the 604d contract; the session selects the
794    /// action from its private phase (R1–R3 + R4/R5 rollback legs + the
795    /// defensive fallback).
796    async fn rollback_inner(&self) -> Result<TransactionOutcome, TransactionError> {
797        let datasource = self.datasource.to_string();
798        match self.phase() {
799            TxPhase::Clean => {
800                // R2: BEGIN never attempted — disarm, return the connection
801                // clean, no SQL; nothing was begun, so nothing is durable.
802                debug_assert!(
803                    !self.is_rollback_only(),
804                    "R2 clean rollback with rollback_only set: the flag is unreachable in Clean"
805                );
806                let Ok(mut slot) = self.slot.try_lock() else {
807                    // log-policy: system-broken
808                    tracing::error!(
809                        datasource = %self.datasource,
810                        "clean rollback while the session slot is held; the connection cannot be returned"
811                    );
812                    return Err(TransactionError::RollbackUncertain { datasource });
813                };
814                self.store_phase(TxPhase::Done);
815                release_to_pool(&mut slot);
816                Ok(TransactionOutcome::RolledBack)
817            }
818            TxPhase::BeginPending => {
819                // R3: protocol position unknown — detach, no SQL.
820                let Ok(mut slot) = self.slot.try_lock() else {
821                    // log-policy: system-broken
822                    tracing::error!(
823                        datasource = %self.datasource,
824                        "rollback while the session slot is held; the connection cannot be detached"
825                    );
826                    return Err(TransactionError::RollbackUncertain { datasource });
827                };
828                self.detach_slot(&mut slot);
829                Err(TransactionError::RollbackUncertain { datasource })
830            }
831            TxPhase::Open => {
832                let Ok(mut slot) = self.slot.try_lock() else {
833                    // log-policy: system-broken
834                    tracing::error!(
835                        datasource = %self.datasource,
836                        "rollback while the session slot is held; the connection cannot be rolled back"
837                    );
838                    return Err(TransactionError::RollbackUncertain { datasource });
839                };
840                let finalize_start = self.timer.now();
841                let grace_deadline = finalize_start + self.finalize_grace;
842                self.store_phase(TxPhase::RollbackInFlight);
843                match run_statement(
844                    &mut **slot,
845                    SQL_ROLLBACK,
846                    grace_deadline,
847                    self.timer.as_ref(),
848                )
849                .await
850                {
851                    StmtOutcome::Ack => {
852                        self.store_phase(TxPhase::Done);
853                        release_to_pool(&mut slot);
854                        Ok(TransactionOutcome::RolledBack)
855                    }
856                    StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
857                        // Not acknowledged / stalled past grace: detach.
858                        self.detach_slot(&mut slot);
859                        Err(TransactionError::RollbackUncertain { datasource })
860                    }
861                }
862            }
863            TxPhase::Detached => {
864                // R1: already detached — no SQL.
865                Err(TransactionError::RollbackUncertain { datasource })
866            }
867            TxPhase::CommitInFlight | TxPhase::RollbackInFlight | TxPhase::Done => {
868                // Defensive fallback (604c totality note): no SQL, and the
869                // return must NOT claim detachment happened.
870                // log-policy: system-broken
871                tracing::error!(
872                    datasource = %self.datasource,
873                    "defensive finalization entry: session is already finalizing or done; \
874                     no SQL sent, no detachment performed"
875                );
876                Err(TransactionError::RollbackUncertain { datasource })
877            }
878        }
879    }
880}
881
882/// Consumes the slot's backend, returning the connection to the pool.
883fn release_to_pool(slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
884    let io = std::mem::replace(&mut **slot, Box::new(DetachedIo));
885    io.release();
886}
887
888/// Admission hygiene: ONE `ROLLBACK` on the freshly checked-out connection,
889/// raced against the same absolute instants as the checkout.
890///
891/// A clean connection answers the hygiene as a safe no-op (probe P4); any
892/// abandoned transaction on it is terminated, so a prior borrower's writes
893/// can never be committed by this block. Unacknowledged hygiene detaches the
894/// connection without sending `BEGIN`.
895async fn admission_hygiene(
896    io: &mut dyn TxIo,
897    timer: Arc<dyn TxTimer>,
898    datasource: &str,
899    max_connections: u32,
900    block_abs: tokio::time::Instant,
901    acquire_abs: tokio::time::Instant,
902) -> Result<(), TransactionError> {
903    let hygiene_start = timer.now();
904    let result = tokio::select! {
905        biased;
906        _ = timer.sleep_until(block_abs) => {
907            // Absolute-instant comparison (frozen spec "Block timeout"): a
908            // strictly-earlier acquire deadline that also elapsed at this
909            // poll reports `PoolExhausted`; the tie and block-first report
910            // `Timeout`.
911            if acquire_abs < block_abs {
912                Err(TransactionError::PoolExhausted {
913                    datasource: datasource.to_owned(),
914                    max_connections,
915                    waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
916                })
917            } else {
918                Err(TransactionError::Timeout {
919                    datasource: datasource.to_owned(),
920                    // Elapsed time since the hygiene start, not since the
921                    // deadline: the typed error names datasource and elapsed
922                    // time.
923                    elapsed_ms: elapsed_ms(timer.as_ref(), hygiene_start),
924                })
925            }
926        }
927        _ = timer.sleep_until(acquire_abs) => Err(TransactionError::PoolExhausted {
928            datasource: datasource.to_owned(),
929            max_connections,
930            waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
931        }),
932        ack = io.exec(SQL_ROLLBACK) => match ack {
933            Ok(()) => Ok(()),
934            Err(_) => Err(TransactionError::RollbackUncertain {
935                datasource: datasource.to_owned(),
936            }),
937        },
938    };
939    match result {
940        Ok(()) => Ok(()),
941        Err(error) => {
942            io.detach();
943            Err(error)
944        }
945    }
946}
947
948impl Drop for SqlTxSession {
949    fn drop(&mut self) {
950        // R0 (604c §A): forced drop in any phase except Done/Detached —
951        // detach synchronously (connection closed/detached, never returned to
952        // the pool), no SQL. This is the guard invariant, not a cooperative
953        // row. No session future can hold the slot here: the port's futures
954        // borrow the session (or hold an Arc clone of it), so none outlives
955        // this drop.
956        if matches!(self.phase(), TxPhase::Done | TxPhase::Detached) {
957            return;
958        }
959        match self.slot.try_lock() {
960            Ok(mut slot) => {
961                slot.detach();
962                let _ = std::mem::replace(&mut *slot, Box::new(DetachedIo));
963            }
964            Err(_) => {
965                // log-policy: system-broken
966                tracing::error!(
967                    datasource = %self.datasource,
968                    "session dropped while its statement slot is held; \
969                     the connection cannot be detached from here"
970                );
971            }
972        }
973    }
974}
975
976impl TransactionSession for SqlTxSession {
977    fn datasource(&self) -> &str {
978        &self.datasource
979    }
980
981    fn state(&self) -> TransactionState {
982        project(self.phase())
983    }
984
985    fn begin(&self) -> BeginFuture<'_> {
986        Box::pin(self.begin_inner())
987    }
988
989    fn set_rollback_only(&self) {
990        self.rollback_only.store(true, Ordering::Relaxed);
991    }
992
993    fn is_rollback_only(&self) -> bool {
994        self.rollback_only.load(Ordering::Relaxed)
995    }
996
997    fn commit(&self) -> FinalizeFuture<'_> {
998        Box::pin(self.commit_inner())
999    }
1000
1001    fn rollback(&self) -> FinalizeFuture<'_> {
1002        Box::pin(self.rollback_inner())
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use std::collections::HashMap;
1009    use std::sync::Mutex as SyncMutex;
1010    use std::task::{Context, Poll, Waker};
1011
1012    use super::*;
1013    use futures::task::noop_waker;
1014
1015    const ACQUIRE: Duration = Duration::from_millis(50);
1016    const GRACE: Duration = Duration::from_secs(5);
1017    const MAX_CONNECTIONS: u32 = 4;
1018
1019    /// Scripted driver answer per statement text; unscripted statements ack.
1020    #[derive(Debug, Clone)]
1021    enum Scripted {
1022        Ack,
1023        /// The statement never completes (stalls past any deadline).
1024        Pending,
1025        Fail(TxIoFailure),
1026    }
1027
1028    /// Observable fake-driver state shared with the fixture.
1029    #[derive(Debug, Default)]
1030    struct FakeShared {
1031        responses: HashMap<&'static str, Scripted>,
1032        issued: Vec<&'static str>,
1033        detached: bool,
1034        released: bool,
1035    }
1036
1037    /// Fake [`TxIo`] backend driven by a shared script.
1038    struct FakeIo {
1039        shared: Arc<SyncMutex<FakeShared>>,
1040    }
1041
1042    impl FakeIo {
1043        fn channel() -> (Box<dyn TxIo>, Arc<SyncMutex<FakeShared>>) {
1044            let shared = Arc::new(SyncMutex::new(FakeShared::default()));
1045            (
1046                Box::new(FakeIo {
1047                    shared: Arc::clone(&shared),
1048                }),
1049                shared,
1050            )
1051        }
1052
1053        fn script(sql: &'static str, answer: Scripted, shared: &SyncMutex<FakeShared>) {
1054            shared
1055                .lock()
1056                .unwrap_or_else(std::sync::PoisonError::into_inner)
1057                .responses
1058                .insert(sql, answer);
1059        }
1060    }
1061
1062    impl TxIo for FakeIo {
1063        fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
1064            Box::pin(async move {
1065                // Record on first poll: a future dropped by a deadline race
1066                // counts as never issued.
1067                self.shared
1068                    .lock()
1069                    .unwrap_or_else(std::sync::PoisonError::into_inner)
1070                    .issued
1071                    .push(sql);
1072                let scripted = self
1073                    .shared
1074                    .lock()
1075                    .unwrap_or_else(std::sync::PoisonError::into_inner)
1076                    .responses
1077                    .get(&sql)
1078                    .cloned()
1079                    .unwrap_or(Scripted::Ack);
1080                match scripted {
1081                    Scripted::Ack => Ok(()),
1082                    Scripted::Pending => std::future::pending().await,
1083                    Scripted::Fail(failure) => Err(failure),
1084                }
1085            })
1086        }
1087
1088        fn detach(&mut self) {
1089            self.shared
1090                .lock()
1091                .unwrap_or_else(std::sync::PoisonError::into_inner)
1092                .detached = true;
1093        }
1094
1095        fn release(self: Box<Self>) {
1096            self.shared
1097                .lock()
1098                .unwrap_or_else(std::sync::PoisonError::into_inner)
1099                .released = true;
1100        }
1101    }
1102
1103    fn issued_of(shared: &SyncMutex<FakeShared>) -> Vec<&'static str> {
1104        shared
1105            .lock()
1106            .unwrap_or_else(std::sync::PoisonError::into_inner)
1107            .issued
1108            .clone()
1109    }
1110
1111    fn is_detached(shared: &SyncMutex<FakeShared>) -> bool {
1112        shared
1113            .lock()
1114            .unwrap_or_else(std::sync::PoisonError::into_inner)
1115            .detached
1116    }
1117
1118    fn is_released(shared: &SyncMutex<FakeShared>) -> bool {
1119        shared
1120            .lock()
1121            .unwrap_or_else(std::sync::PoisonError::into_inner)
1122            .released
1123    }
1124
1125    fn db_error(severity: DbSeverity, code: &str, message: &str) -> TxIoFailure {
1126        TxIoFailure::Database(DbAnswer {
1127            severity,
1128            code: Some(code.to_owned()),
1129            message: message.to_owned(),
1130        })
1131    }
1132
1133    fn test_session(io: Box<dyn TxIo>, timer: Arc<dyn TxTimer>) -> SqlTxSession {
1134        SqlTxSession::with_io("pg", io, timer, ACQUIRE, GRACE, MAX_CONNECTIONS)
1135    }
1136
1137    /// Polls once; returns true when the future stayed pending.
1138    fn poll_once_pending<F: Future>(pinned: &mut Pin<&mut F>) -> bool {
1139        let waker: Waker = noop_waker();
1140        let mut cx = Context::from_waker(&waker);
1141        matches!(pinned.as_mut().poll(&mut cx), Poll::Pending)
1142    }
1143
1144    /// Timer whose deadlines have always already elapsed: proves the
1145    /// injected-clock seam is honored (the deadline arm wins the biased tie).
1146    struct AlwaysElapsed;
1147
1148    impl TxTimer for AlwaysElapsed {
1149        fn now(&self) -> tokio::time::Instant {
1150            tokio::time::Instant::now()
1151        }
1152
1153        fn sleep_until(
1154            &self,
1155            _deadline: tokio::time::Instant,
1156        ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
1157            Box::pin(std::future::ready(()))
1158        }
1159    }
1160
1161    /// 604c §A projection table, row for row.
1162    #[test]
1163    fn phase_projection_matches_604c_table() {
1164        let rows = [
1165            (TxPhase::Clean, TransactionState::Fresh),
1166            (TxPhase::BeginPending, TransactionState::Fresh),
1167            (TxPhase::Open, TransactionState::Active),
1168            (TxPhase::CommitInFlight, TransactionState::Finalizing),
1169            (TxPhase::RollbackInFlight, TransactionState::Finalizing),
1170            (TxPhase::Done, TransactionState::Done),
1171            (TxPhase::Detached, TransactionState::Detached),
1172        ];
1173        for (phase, expected) in rows {
1174            assert_eq!(
1175                project(phase),
1176                expected,
1177                "604c §A projection mismatch for {phase:?}"
1178            );
1179        }
1180    }
1181
1182    /// §B.1: `begin` on an `Open` session is an idempotent no-op — the
1183    /// second call sends no SQL.
1184    #[tokio::test]
1185    async fn begin_is_idempotent_when_open() {
1186        let (io, shared) = FakeIo::channel();
1187        let session = test_session(io, Arc::new(TokioTimer));
1188        session.begin().await.expect("first begin acknowledges");
1189        assert_eq!(session.state(), TransactionState::Active);
1190
1191        let second = session.begin().await;
1192        assert_eq!(second, Ok(()), "begin on Open is an idempotent no-op");
1193        assert_eq!(
1194            issued_of(&shared),
1195            vec![SQL_BEGIN],
1196            "the idempotent call must not send BEGIN again"
1197        );
1198        assert_eq!(session.state(), TransactionState::Active);
1199    }
1200
1201    /// §B.1: `begin` from a non-Clean, non-Open phase is `SessionAborted`
1202    /// with no SQL.
1203    #[tokio::test]
1204    async fn begin_from_non_clean_phases_is_aborted() {
1205        // Done entry (after an R2 clean rollback).
1206        let (io, shared) = FakeIo::channel();
1207        let session = test_session(io, Arc::new(TokioTimer));
1208        session.rollback().await.expect("clean rollback");
1209        let error = session.begin().await.expect_err("begin from Done aborts");
1210        assert_eq!(
1211            error,
1212            TransactionError::SessionAborted {
1213                datasource: "pg".to_owned()
1214            }
1215        );
1216        assert!(
1217            issued_of(&shared).is_empty(),
1218            "the aborted begin must send no SQL"
1219        );
1220
1221        // BeginPending entry (a begin future dropped mid-BEGIN): the block
1222        // scope drops the pinned future and frees the slot.
1223        let (io, shared) = FakeIo::channel();
1224        FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1225        let session = test_session(io, Arc::new(TokioTimer));
1226        {
1227            let mut begin = std::pin::pin!(session.begin());
1228            assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
1229        }
1230        let error = session
1231            .begin()
1232            .await
1233            .expect_err("begin from BeginPending aborts");
1234        assert_eq!(
1235            error,
1236            TransactionError::SessionAborted {
1237                datasource: "pg".to_owned()
1238            }
1239        );
1240        assert_eq!(
1241            issued_of(&shared),
1242            vec![SQL_BEGIN],
1243            "the aborted attempt must not send another BEGIN"
1244        );
1245    }
1246
1247    /// §B.1 + Detached-is-terminal under a begin/detach race: a concurrent
1248    /// begin can never overwrite the terminal phase. Begin #1 stalls inside
1249    /// its BEGIN write (slot held); the racing begin #2 observes `Busy`
1250    /// without touching state (the phase is judged only under the slot
1251    /// lock); when begin #1's own deadline fires it detaches (§B.4) — begin
1252    /// #3 then sees `Detached` under the lock and reports `SessionAborted`,
1253    /// leaving the phase `Detached` (no `BeginPending` overwrite) and sending
1254    /// no SQL.
1255    #[tokio::test(start_paused = true)]
1256    async fn begin_racing_detach_never_overwrites_detached() {
1257        let (io, shared) = FakeIo::channel();
1258        FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1259        let session = test_session(io, Arc::new(TokioTimer));
1260
1261        // Begin #1: holds the slot inside its BEGIN write.
1262        let mut first = std::pin::pin!(session.begin());
1263        assert!(poll_once_pending(&mut first), "the BEGIN write must stall");
1264        assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
1265
1266        // Begin #2, racing while the slot is held: Busy, no state touched.
1267        let racing = session.begin().await;
1268        assert_eq!(
1269            racing,
1270            Err(TransactionError::Busy {
1271                datasource: "pg".to_owned()
1272            }),
1273            "the raced begin is rejected on the held slot before any phase read"
1274        );
1275
1276        // Begin #1's own deadline fires → §B.4: detach, `PoolExhausted`.
1277        let first_outcome = first.await;
1278        assert_eq!(
1279            first_outcome,
1280            Err(TransactionError::PoolExhausted {
1281                datasource: "pg".to_owned(),
1282                max_connections: MAX_CONNECTIONS,
1283                waited_ms: ACQUIRE.as_millis() as u64,
1284            }),
1285            "the stalled begin detaches per §B.4"
1286        );
1287        assert_eq!(session.state(), TransactionState::Detached);
1288
1289        // Begin #3 after the detach: `SessionAborted`, phase stays
1290        // `Detached`, no further SQL.
1291        let third = session.begin().await;
1292        assert_eq!(
1293            third,
1294            Err(TransactionError::SessionAborted {
1295                datasource: "pg".to_owned()
1296            }),
1297            "begin on a Detached session aborts, never overwrites the terminal phase"
1298        );
1299        assert_eq!(session.state(), TransactionState::Detached);
1300        assert_eq!(
1301            issued_of(&shared),
1302            vec![SQL_BEGIN],
1303            "neither raced begin sent SQL"
1304        );
1305    }
1306
1307    /// §B.4: BEGIN stalled past its own deadline → `PoolExhausted` naming
1308    /// datasource, max_connections and the waited time; detach; NO cleanup
1309    /// SQL. A further rollback is the R1 row (no SQL, `RollbackUncertain`).
1310    #[tokio::test(start_paused = true)]
1311    async fn begin_own_timeout_reports_pool_exhausted_detaches() {
1312        let (io, shared) = FakeIo::channel();
1313        FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1314        let session = test_session(io, Arc::new(TokioTimer));
1315
1316        let error = session.begin().await.expect_err("begin deadline");
1317        assert_eq!(
1318            error,
1319            TransactionError::PoolExhausted {
1320                datasource: "pg".to_owned(),
1321                max_connections: MAX_CONNECTIONS,
1322                // Sane waited semantics: measures from the begin start, and
1323                // the virtual clock jumps exactly to the deadline.
1324                waited_ms: ACQUIRE.as_millis() as u64,
1325            }
1326        );
1327        assert!(
1328            ACQUIRE > Duration::ZERO,
1329            "the begin deadline must be a positive bound the wait is measured against"
1330        );
1331        assert_eq!(session.state(), TransactionState::Detached);
1332        assert_eq!(
1333            issued_of(&shared),
1334            vec![SQL_BEGIN],
1335            "no cleanup SQL after the begin timeout"
1336        );
1337        assert!(is_detached(&shared), "the begin timeout detaches");
1338        assert!(
1339            !is_released(&shared),
1340            "a detached connection is never re-pooled"
1341        );
1342
1343        // R1: a detached session never sends SQL again.
1344        let result = session.rollback().await;
1345        assert_eq!(
1346            result,
1347            Err(TransactionError::RollbackUncertain {
1348                datasource: "pg".to_owned()
1349            })
1350        );
1351        assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R1 sends no SQL");
1352    }
1353
1354    /// §B.5: any driver error at BEGIN → detach + `RollbackUncertain`; NO
1355    /// cleanup SQL.
1356    #[tokio::test]
1357    async fn begin_driver_error_detaches_reports_rollback_uncertain() {
1358        let (io, shared) = FakeIo::channel();
1359        FakeIo::script(
1360            SQL_BEGIN,
1361            Scripted::Fail(db_error(DbSeverity::Other, "08006", "connection failure")),
1362            &shared,
1363        );
1364        let session = test_session(io, Arc::new(TokioTimer));
1365
1366        let error = session.begin().await.expect_err("begin driver error");
1367        assert_eq!(
1368            error,
1369            TransactionError::RollbackUncertain {
1370                datasource: "pg".to_owned()
1371            }
1372        );
1373        assert_eq!(session.state(), TransactionState::Detached);
1374        assert_eq!(
1375            issued_of(&shared),
1376            vec![SQL_BEGIN],
1377            "no cleanup SQL after a begin driver error"
1378        );
1379        assert!(is_detached(&shared));
1380    }
1381
1382    /// The injected-clock seam: a timer whose deadlines have already elapsed
1383    /// must time the BEGIN out before any statement reaches the driver, even
1384    /// though the fake would acknowledge it.
1385    #[tokio::test]
1386    async fn injected_timer_times_out_begin() {
1387        let (io, shared) = FakeIo::channel();
1388        let session = test_session(io, Arc::new(AlwaysElapsed));
1389
1390        let error = session.begin().await.expect_err("injected deadline");
1391        assert_eq!(
1392            error,
1393            TransactionError::PoolExhausted {
1394                datasource: "pg".to_owned(),
1395                max_connections: MAX_CONNECTIONS,
1396                waited_ms: 0,
1397            }
1398        );
1399        assert_eq!(session.state(), TransactionState::Detached);
1400        assert!(
1401            issued_of(&shared).is_empty(),
1402            "an already-elapsed deadline cancels the write before the driver sees it"
1403        );
1404        assert!(is_detached(&shared));
1405    }
1406
1407    /// R7 classifier table: severity-`ERROR` SQLSTATE classes 23/40 are the
1408    /// ONLY affirmative rejections (`CommitFailed` + exactly one cleanup
1409    /// ROLLBACK); FATAL 57P01, class-57 57014, class-08 08006, and transport
1410    /// failures are `CommitUncertain` — no ROLLBACK, no rollback claim,
1411    /// detach.
1412    #[tokio::test]
1413    async fn transacted_commit_classifier_table() {
1414        let rows: Vec<(&str, TxIoFailure, TransactionError, bool)> = vec![
1415            (
1416                "23503 integrity violation",
1417                db_error(DbSeverity::Error, "23503", "foreign key violated"),
1418                TransactionError::CommitFailed {
1419                    datasource: "pg".to_owned(),
1420                    reason: "SQLSTATE 23503: foreign key violated".to_owned(),
1421                },
1422                true,
1423            ),
1424            (
1425                "40001 transaction abort class",
1426                db_error(DbSeverity::Error, "40001", "could not serialize access"),
1427                TransactionError::CommitFailed {
1428                    datasource: "pg".to_owned(),
1429                    reason: "SQLSTATE 40001: could not serialize access".to_owned(),
1430                },
1431                true,
1432            ),
1433            (
1434                "57P01 backend fatal",
1435                db_error(
1436                    DbSeverity::Other,
1437                    "57P01",
1438                    "terminating connection due to administrator command",
1439                ),
1440                TransactionError::CommitUncertain {
1441                    datasource: "pg".to_owned(),
1442                },
1443                false,
1444            ),
1445            (
1446                "57014 query canceled (class 57)",
1447                db_error(
1448                    DbSeverity::Error,
1449                    "57014",
1450                    "canceling statement due to user request",
1451                ),
1452                TransactionError::CommitUncertain {
1453                    datasource: "pg".to_owned(),
1454                },
1455                false,
1456            ),
1457            (
1458                "08006 connection failure (class 08)",
1459                db_error(DbSeverity::Error, "08006", "connection failure"),
1460                TransactionError::CommitUncertain {
1461                    datasource: "pg".to_owned(),
1462                },
1463                false,
1464            ),
1465            (
1466                "io transport error",
1467                TxIoFailure::Lost,
1468                TransactionError::CommitUncertain {
1469                    datasource: "pg".to_owned(),
1470                },
1471                false,
1472            ),
1473        ];
1474
1475        for (name, commit_failure, expected, cleanup_issued) in rows {
1476            let (io, shared) = FakeIo::channel();
1477            FakeIo::script(SQL_COMMIT, Scripted::Fail(commit_failure), &shared);
1478            let session = test_session(io, Arc::new(TokioTimer));
1479            session.begin().await.expect("BEGIN must acknowledge");
1480            assert_eq!(session.state(), TransactionState::Active, "row {name}");
1481
1482            let result = session.commit().await;
1483            assert_eq!(result, Err(expected), "row {name}");
1484
1485            let expected_issued = if cleanup_issued {
1486                vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK]
1487            } else {
1488                vec![SQL_BEGIN, SQL_COMMIT]
1489            };
1490            assert_eq!(issued_of(&shared), expected_issued, "row {name}");
1491            if cleanup_issued {
1492                assert!(
1493                    is_released(&shared),
1494                    "cleanup acknowledged: connection returned to the pool (row {name})"
1495                );
1496                assert!(
1497                    !is_detached(&shared),
1498                    "no detach after an acknowledged cleanup (row {name})"
1499                );
1500                assert_eq!(session.state(), TransactionState::Done, "row {name}");
1501            } else {
1502                assert!(is_detached(&shared), "detach immediately (row {name})");
1503                assert!(
1504                    !is_released(&shared),
1505                    "no rollback claim and no re-pool (row {name})"
1506                );
1507                assert_eq!(session.state(), TransactionState::Detached, "row {name}");
1508            }
1509        }
1510    }
1511
1512    /// Port contract: `commit` requires `Active`; otherwise no SQL.
1513    #[tokio::test]
1514    async fn commit_requires_open_sends_no_sql() {
1515        // Clean entry.
1516        let (io, shared) = FakeIo::channel();
1517        let session = test_session(io, Arc::new(TokioTimer));
1518        let error = session
1519            .commit()
1520            .await
1521            .expect_err("commit from Clean aborts");
1522        assert_eq!(
1523            error,
1524            TransactionError::SessionAborted {
1525                datasource: "pg".to_owned()
1526            }
1527        );
1528        assert!(
1529            issued_of(&shared).is_empty(),
1530            "the aborted commit must send no SQL"
1531        );
1532
1533        // Done entry (after an acknowledged rollback).
1534        let (io, shared) = FakeIo::channel();
1535        let session = test_session(io, Arc::new(TokioTimer));
1536        session.begin().await.expect("BEGIN must acknowledge");
1537        session.rollback().await.expect("rollback acknowledges");
1538        let error = session.commit().await.expect_err("commit from Done aborts");
1539        assert_eq!(
1540            error,
1541            TransactionError::SessionAborted {
1542                datasource: "pg".to_owned()
1543            }
1544        );
1545        assert_eq!(
1546            issued_of(&shared),
1547            vec![SQL_BEGIN, SQL_ROLLBACK],
1548            "the aborted commit must send no SQL"
1549        );
1550    }
1551
1552    /// 604d defensive rows: a `Finalizing`/`Done` rollback entry sends no
1553    /// SQL, logs `error!`, changes no phase, and claims NO detachment.
1554    #[tracing_test::traced_test]
1555    #[tokio::test]
1556    async fn defensive_finalization_entry_logs_error_without_detach_claim() {
1557        // CommitInFlight entry: a commit future dropped mid-COMMIT.
1558        let (io, shared) = FakeIo::channel();
1559        FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
1560        let session = test_session(io, Arc::new(TokioTimer));
1561        session.begin().await.expect("BEGIN must acknowledge");
1562        {
1563            let mut commit = std::pin::pin!(session.commit());
1564            assert!(poll_once_pending(&mut commit), "COMMIT must stay pending");
1565            assert_eq!(session.state(), TransactionState::Finalizing);
1566        }
1567
1568        let result = session.rollback().await;
1569        assert_eq!(
1570            result,
1571            Err(TransactionError::RollbackUncertain {
1572                datasource: "pg".to_owned()
1573            }),
1574            "defensive Finalizing entry returns Err, never an outcome claim"
1575        );
1576        assert_eq!(
1577            session.state(),
1578            TransactionState::Finalizing,
1579            "the defensive entry changes no phase"
1580        );
1581        assert!(logs_contain("defensive finalization entry"));
1582        assert_eq!(
1583            issued_of(&shared),
1584            vec![SQL_BEGIN, SQL_COMMIT],
1585            "no SQL on the defensive path"
1586        );
1587        assert!(
1588            !is_detached(&shared),
1589            "the defensive entry must NOT claim detachment happened"
1590        );
1591        assert!(!is_released(&shared));
1592
1593        // Done entry: a further rollback after an acknowledged rollback.
1594        let (io, shared) = FakeIo::channel();
1595        let session = test_session(io, Arc::new(TokioTimer));
1596        session.begin().await.expect("BEGIN must acknowledge");
1597        assert_eq!(session.rollback().await, Ok(TransactionOutcome::RolledBack));
1598        let result = session.rollback().await;
1599        assert_eq!(
1600            result,
1601            Err(TransactionError::RollbackUncertain {
1602                datasource: "pg".to_owned()
1603            }),
1604            "defensive Done entry returns Err, never an outcome claim"
1605        );
1606        assert_eq!(
1607            session.state(),
1608            TransactionState::Done,
1609            "the defensive entry changes no phase"
1610        );
1611        assert!(logs_contain("defensive finalization entry"));
1612        assert_eq!(
1613            issued_of(&shared),
1614            vec![SQL_BEGIN, SQL_ROLLBACK],
1615            "no SQL on the defensive path"
1616        );
1617        assert!(
1618            !is_detached(&shared),
1619            "the Done entry adds no detach: the connection was already released by the first rollback"
1620        );
1621    }
1622
1623    /// R2: rollback from `Clean` — no SQL, guard disarmed, connection
1624    /// returned clean, `Ok(RolledBack)`.
1625    #[tokio::test]
1626    async fn r2_clean_rollback_returns_connection_clean() {
1627        let (io, shared) = FakeIo::channel();
1628        let session = test_session(io, Arc::new(TokioTimer));
1629        assert_eq!(session.state(), TransactionState::Fresh);
1630        assert!(!session.is_rollback_only());
1631
1632        let result = session.rollback().await;
1633        assert_eq!(result, Ok(TransactionOutcome::RolledBack));
1634        assert_eq!(session.state(), TransactionState::Done);
1635        assert!(
1636            issued_of(&shared).is_empty(),
1637            "R2 sends no SQL: nothing was begun"
1638        );
1639        assert!(
1640            is_released(&shared),
1641            "the connection is returned to the pool clean"
1642        );
1643        assert!(!is_detached(&shared));
1644    }
1645
1646    /// The rollback-only flag round-trips on the port's atomic and does not
1647    /// change session-level rollback mechanics (the segment owns the R4
1648    /// precedence per 604d).
1649    #[tokio::test]
1650    async fn rollback_only_flag_and_open_rollback_acks() {
1651        let (io, shared) = FakeIo::channel();
1652        let session = test_session(io, Arc::new(TokioTimer));
1653        assert!(!session.is_rollback_only());
1654        session.set_rollback_only();
1655        assert!(session.is_rollback_only());
1656
1657        session.begin().await.expect("BEGIN must acknowledge");
1658        let result = session.rollback().await;
1659        assert_eq!(result, Ok(TransactionOutcome::RolledBack));
1660        assert_eq!(issued_of(&shared), vec![SQL_BEGIN, SQL_ROLLBACK]);
1661        assert!(
1662            session.is_rollback_only(),
1663            "finalization does not clear the flag"
1664        );
1665    }
1666
1667    /// Busy admission (req "Busy block session"): a held slot fails any
1668    /// statement run with the typed `Busy` error, deterministically.
1669    #[tokio::test]
1670    async fn busy_slot_try_lock_reports_busy() {
1671        let (io, shared) = FakeIo::channel();
1672        let session = test_session(io, Arc::new(TokioTimer));
1673
1674        let held = session
1675            .slot
1676            .try_lock()
1677            .expect("the slot must be free before the fixture holds it");
1678        let error = session.begin().await.expect_err("held slot");
1679        assert_eq!(
1680            error,
1681            TransactionError::Busy {
1682                datasource: "pg".to_owned()
1683            }
1684        );
1685        assert!(
1686            issued_of(&shared).is_empty(),
1687            "a busy-rejected begin sends no SQL"
1688        );
1689        drop(held);
1690
1691        session.begin().await.expect("begin after the slot frees");
1692        assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
1693    }
1694
1695    /// Frozen fixture `transacted_hygiene_unacknowledged` (spec admission
1696    /// clause): an unacknowledged hygiene ROLLBACK detaches the connection
1697    /// without sending BEGIN, and exactly one ROLLBACK attempt is made.
1698    #[tokio::test]
1699    async fn transacted_hygiene_unacknowledged() {
1700        let (mut io, shared) = FakeIo::channel();
1701        FakeIo::script(
1702            SQL_ROLLBACK,
1703            Scripted::Fail(db_error(DbSeverity::Error, "08006", "connection failure")),
1704            &shared,
1705        );
1706        let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1707        let now = timer.now();
1708
1709        let error = admission_hygiene(
1710            &mut *io,
1711            Arc::clone(&timer),
1712            "pg",
1713            MAX_CONNECTIONS,
1714            now + Duration::from_secs(60),
1715            now + ACQUIRE,
1716        )
1717        .await
1718        .expect_err("unacknowledged hygiene");
1719        assert_eq!(
1720            error,
1721            TransactionError::RollbackUncertain {
1722                datasource: "pg".to_owned()
1723            }
1724        );
1725        assert_eq!(
1726            issued_of(&shared),
1727            vec![SQL_ROLLBACK],
1728            "exactly one ROLLBACK attempt, BEGIN never sent"
1729        );
1730        assert!(is_detached(&shared), "unacknowledged hygiene detaches");
1731    }
1732
1733    /// Real-backend smoke over an in-memory SQLite pool: hygiene is skipped
1734    /// (SQLite errors on a clean-connection ROLLBACK; hygiene is PG-runtime
1735    /// territory exercised by the PG suite), but BEGIN/COMMIT/ROLLBACK run
1736    /// as plain statements through [`AnyConnIo`], and a released connection
1737    /// serves the pool again.
1738    #[tokio::test]
1739    async fn sqlite_pool_begin_commit_and_rollback_smoke() {
1740        sqlx::any::install_default_drivers();
1741        let pool = sqlx::any::AnyPoolOptions::new() // allow-test-wait: in-memory sqlite connect, no network
1742            .max_connections(2)
1743            .connect("sqlite::memory:")
1744            .await
1745            .expect("in-memory sqlite pool");
1746        let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1747
1748        let conn = pool.acquire().await.expect("first connection"); // allow-test-wait: pool max 2, no other holders
1749        let session = SqlTxSession::with_io(
1750            "pg",
1751            Box::new(AnyConnIo { conn: Some(conn) }),
1752            Arc::clone(&timer),
1753            ACQUIRE,
1754            GRACE,
1755            2,
1756        );
1757        session.begin().await.expect("real BEGIN");
1758        assert_eq!(session.state(), TransactionState::Active);
1759        let outcome = session.commit().await.expect("real COMMIT");
1760        assert_eq!(outcome, TransactionOutcome::Committed);
1761        assert_eq!(session.state(), TransactionState::Done);
1762
1763        let conn = pool.acquire().await.expect("second connection"); // allow-test-wait: first session released, pool max 2
1764        let session = SqlTxSession::with_io(
1765            "pg",
1766            Box::new(AnyConnIo { conn: Some(conn) }),
1767            timer,
1768            ACQUIRE,
1769            GRACE,
1770            2,
1771        );
1772        session.begin().await.expect("real BEGIN");
1773        let outcome = session.rollback().await.expect("real ROLLBACK");
1774        assert_eq!(outcome, TransactionOutcome::RolledBack);
1775        assert_eq!(session.state(), TransactionState::Done);
1776
1777        // Released connections serve the pool again.
1778        sqlx::query("SELECT 1")
1779            .execute(&pool)
1780            .await
1781            .expect("pool usable after finalization");
1782        pool.close().await;
1783    }
1784
1785    /// R0: dropping the session mid-transaction detaches synchronously —
1786    /// no SQL, never re-pooled.
1787    #[tokio::test]
1788    async fn forced_drop_detaches_without_sql() {
1789        assert_forced_drop_from_open().await;
1790    }
1791
1792    /// Frozen fixture `transacted_forced_drop_inline` (spec cancellation
1793    /// cutoff): the inline-dispatcher route-level drop lands with the
1794    /// executor wiring (step 9 / family); the armed `DiscardOnDrop` guard
1795    /// THIS fixture pins is the same mechanism that drop path triggers — the
1796    /// session is dropped with the transaction open, no SQL is sent, and the
1797    /// connection is never re-pooled.
1798    #[tokio::test]
1799    async fn transacted_forced_drop_inline() {
1800        assert_forced_drop_from_open().await;
1801    }
1802
1803    async fn assert_forced_drop_from_open() {
1804        let (io, shared) = FakeIo::channel();
1805        let session = test_session(io, Arc::new(TokioTimer));
1806        session.begin().await.expect("BEGIN must acknowledge");
1807        assert_eq!(session.state(), TransactionState::Active);
1808
1809        drop(session);
1810        assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R0 sends no SQL");
1811        assert!(is_detached(&shared), "R0 detaches synchronously");
1812        assert!(!is_released(&shared), "R0 never returns the connection");
1813    }
1814
1815    /// R3 via the total rollback: a begin future left pending in
1816    /// `BeginPending` (BEGIN write never acknowledged) — `rollback()`
1817    /// detaches with no further SQL and reports `RollbackUncertain`.
1818    #[tokio::test]
1819    async fn transacted_begin_pending_deadline() {
1820        let (io, shared) = FakeIo::channel();
1821        FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1822        let session = test_session(io, Arc::new(TokioTimer));
1823
1824        // Leave BEGIN pending: one poll (BeginPending is set before the
1825        // write), then drop the future — the phase stays BeginPending and
1826        // the slot frees.
1827        {
1828            let mut begin = std::pin::pin!(session.begin());
1829            assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
1830            assert_eq!(
1831                session.state(),
1832                TransactionState::Fresh,
1833                "BeginPending projects lossily onto Fresh"
1834            );
1835        }
1836
1837        let result = session.rollback().await;
1838        assert_eq!(
1839            result,
1840            Err(TransactionError::RollbackUncertain {
1841                datasource: "pg".to_owned()
1842            }),
1843            "R3: protocol position unknown, nothing acknowledged"
1844        );
1845        assert_eq!(
1846            issued_of(&shared),
1847            vec![SQL_BEGIN],
1848            "R3 sends no SQL: no ROLLBACK on an unacknowledged BEGIN"
1849        );
1850        assert!(is_detached(&shared), "R3 detaches the connection");
1851        assert!(
1852            !is_released(&shared),
1853            "a detached connection is never returned to the pool"
1854        );
1855        assert_eq!(session.state(), TransactionState::Detached);
1856    }
1857
1858    /// Finalize grace, COMMIT leg — frozen fixture `transacted_stalled_commit`
1859    /// (spec "Block timeout"): a COMMIT stalled past `finalize_start + 5 s` is
1860    /// `CommitUncertain` — detach, no cleanup ROLLBACK, no claim.
1861    #[tokio::test(start_paused = true)]
1862    async fn transacted_stalled_commit() {
1863        let (io, shared) = FakeIo::channel();
1864        FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
1865        let session = test_session(io, Arc::new(TokioTimer));
1866        session.begin().await.expect("BEGIN must acknowledge");
1867
1868        let result = session.commit().await;
1869        assert_eq!(
1870            result,
1871            Err(TransactionError::CommitUncertain {
1872                datasource: "pg".to_owned()
1873            }),
1874            "grace elapsed: the commit outcome is uncertain"
1875        );
1876        assert_eq!(
1877            issued_of(&shared),
1878            vec![SQL_BEGIN, SQL_COMMIT],
1879            "no cleanup ROLLBACK after a stalled COMMIT"
1880        );
1881        assert!(is_detached(&shared), "the grace expiry detaches");
1882        assert!(
1883            !is_released(&shared),
1884            "a detached connection is never re-pooled"
1885        );
1886        assert_eq!(session.state(), TransactionState::Detached);
1887    }
1888
1889    /// Finalize grace, ROLLBACK leg — frozen fixture
1890    /// `transacted_stalled_rollback` (spec "Block timeout"): a ROLLBACK
1891    /// stalled past the grace is `RollbackUncertain` — detach, no further SQL.
1892    #[tokio::test(start_paused = true)]
1893    async fn transacted_stalled_rollback() {
1894        let (io, shared) = FakeIo::channel();
1895        FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1896        let session = test_session(io, Arc::new(TokioTimer));
1897        session.begin().await.expect("BEGIN must acknowledge");
1898
1899        let result = session.rollback().await;
1900        assert_eq!(
1901            result,
1902            Err(TransactionError::RollbackUncertain {
1903                datasource: "pg".to_owned()
1904            }),
1905            "grace elapsed: the rollback is not acknowledged"
1906        );
1907        assert_eq!(
1908            issued_of(&shared),
1909            vec![SQL_BEGIN, SQL_ROLLBACK],
1910            "exactly one ROLLBACK attempt within the grace"
1911        );
1912        assert!(is_detached(&shared), "the grace expiry detaches");
1913        assert!(
1914            !is_released(&shared),
1915            "a detached connection is never re-pooled"
1916        );
1917        assert_eq!(session.state(), TransactionState::Detached);
1918    }
1919
1920    /// Frozen "CommitFailed stands" (spec Cancellation cutoff, precedence
1921    /// over 604c R7's sub-row): COMMIT rejected with 23503 but the cleanup
1922    /// ROLLBACK itself stalls past the grace — the typed `CommitFailed` is
1923    /// the primary in BOTH cleanup outcomes; the cleanup uncertainty is
1924    /// observable through the warn! log and the `Detached` state only. The
1925    /// connection detaches, never re-pools. Adjudication:
1926    /// `openspec/changes/sqltrans-exec/design.md` "Edge adjudications".
1927    #[tracing_test::traced_test]
1928    #[tokio::test(start_paused = true)]
1929    async fn commit_cleanup_unacknowledged_keeps_commit_failed() {
1930        let (io, shared) = FakeIo::channel();
1931        FakeIo::script(
1932            SQL_COMMIT,
1933            Scripted::Fail(db_error(DbSeverity::Error, "23503", "foreign key violated")),
1934            &shared,
1935        );
1936        FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1937        let session = test_session(io, Arc::new(TokioTimer));
1938        session.begin().await.expect("BEGIN must acknowledge");
1939
1940        let result = session.commit().await;
1941        assert_eq!(
1942            result,
1943            Err(TransactionError::CommitFailed {
1944                datasource: "pg".to_owned(),
1945                reason: "SQLSTATE 23503: foreign key violated".to_owned(),
1946            }),
1947            "the typed commit failure stands; cleanup uncertainty never replaces it"
1948        );
1949        assert_eq!(
1950            issued_of(&shared),
1951            vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK],
1952            "exactly one cleanup ROLLBACK attempt within the remaining grace"
1953        );
1954        assert!(is_detached(&shared), "unacknowledged cleanup detaches");
1955        assert!(
1956            !is_released(&shared),
1957            "the connection is never returned to the pool with unknown state"
1958        );
1959        assert_eq!(session.state(), TransactionState::Detached);
1960        assert!(
1961            logs_contain("not acknowledged"),
1962            "the cleanup uncertainty is observable through the warn! log"
1963        );
1964    }
1965
1966    /// Hygiene deadline (MINOR-1 semantics): the `Timeout` error measures the
1967    /// time elapsed from the hygiene start, not from the deadline.
1968    #[tokio::test(start_paused = true)]
1969    async fn hygiene_deadline_reports_timeout_elapsed_from_start() {
1970        let (mut io, shared) = FakeIo::channel();
1971        FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1972        let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1973        let now = timer.now();
1974        let block_deadline = Duration::from_millis(10);
1975
1976        let error = admission_hygiene(
1977            &mut *io,
1978            Arc::clone(&timer),
1979            "pg",
1980            MAX_CONNECTIONS,
1981            now + block_deadline,
1982            now + Duration::from_secs(60),
1983        )
1984        .await
1985        .expect_err("block deadline elapses while hygiene is pending");
1986        assert_eq!(
1987            error,
1988            TransactionError::Timeout {
1989                datasource: "pg".to_owned(),
1990                elapsed_ms: block_deadline.as_millis() as u64,
1991            },
1992            "elapsed must measure from the hygiene start (> 0), not from the deadline"
1993        );
1994        assert_eq!(
1995            issued_of(&shared),
1996            vec![SQL_ROLLBACK],
1997            "exactly one ROLLBACK attempt, BEGIN never sent"
1998        );
1999        assert!(
2000            is_detached(&shared),
2001            "deadline expiry during hygiene detaches"
2002        );
2003    }
2004
2005    /// One admission-hygiene deadline case with the hygiene ROLLBACK held
2006    /// pending: returns the typed error after asserting the invariant shared
2007    /// by every deadline ordering — exactly one ROLLBACK attempt, BEGIN never
2008    /// sent, the connection detached and never released.
2009    async fn hygiene_deadline_case(block: Duration, acquire: Duration) -> TransactionError {
2010        let (mut io, shared) = FakeIo::channel();
2011        FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2012        let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2013        let now = timer.now();
2014
2015        let error = admission_hygiene(
2016            &mut *io,
2017            Arc::clone(&timer),
2018            "pg",
2019            MAX_CONNECTIONS,
2020            now + block,
2021            now + acquire,
2022        )
2023        .await
2024        .expect_err("hygiene stays pending past both deadlines");
2025        assert_eq!(
2026            issued_of(&shared),
2027            vec![SQL_ROLLBACK],
2028            "exactly one ROLLBACK attempt, BEGIN never sent"
2029        );
2030        assert!(
2031            is_detached(&shared),
2032            "deadline expiry during hygiene detaches"
2033        );
2034        assert!(
2035            !is_released(&shared),
2036            "a detached connection is never re-pooled"
2037        );
2038        error
2039    }
2040
2041    /// Frozen fixture `transacted_hygiene_deadline_expiry` (spec admission
2042    /// clause): the hygiene ROLLBACK is left pending while the virtual clock
2043    /// advances through the three deadline orderings — `PoolExhausted` for
2044    /// acquire-first, `Timeout` for block-first, and `Timeout` for the tie
2045    /// (the biased block arm) — with exactly one ROLLBACK attempt, BEGIN never
2046    /// sent, and the connection detached.
2047    #[tokio::test(start_paused = true)]
2048    async fn transacted_hygiene_deadline_expiry() {
2049        let cases: [(&str, Duration, Duration, TransactionError); 3] = [
2050            (
2051                "acquire-first: acquire 10 ms < block 60 s",
2052                Duration::from_secs(60),
2053                Duration::from_millis(10),
2054                TransactionError::PoolExhausted {
2055                    datasource: "pg".to_owned(),
2056                    max_connections: MAX_CONNECTIONS,
2057                    waited_ms: 10,
2058                },
2059            ),
2060            (
2061                "block-first: block 10 ms < acquire 60 s",
2062                Duration::from_millis(10),
2063                Duration::from_secs(60),
2064                TransactionError::Timeout {
2065                    datasource: "pg".to_owned(),
2066                    elapsed_ms: 10,
2067                },
2068            ),
2069            (
2070                "tie: both 10 ms — the biased block arm wins",
2071                Duration::from_millis(10),
2072                Duration::from_millis(10),
2073                TransactionError::Timeout {
2074                    datasource: "pg".to_owned(),
2075                    elapsed_ms: 10,
2076                },
2077            ),
2078        ];
2079
2080        for (label, block, acquire, expected) in cases {
2081            let error = hygiene_deadline_case(block, acquire).await;
2082            assert_eq!(error, expected, "{label}");
2083        }
2084    }
2085
2086    /// R0 arms AT checkout (frozen spec: "The discard guard is armed on
2087    /// connection checkout"): dropping the open future while the admission
2088    /// hygiene `ROLLBACK` is still pending detaches the checked-out
2089    /// connection — it is never released back to the pool. This is the
2090    /// checkout-guard twin of `transacted_forced_drop_inline`: the
2091    /// guard-bearing session does not exist yet when the open future dies,
2092    /// so the arming cannot wait for `with_io`.
2093    #[tokio::test(start_paused = true)]
2094    async fn open_future_dropped_mid_hygiene_detaches_at_checkout() {
2095        let (io, shared) = FakeIo::channel();
2096        FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2097        let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2098        let now = timer.now();
2099
2100        // One poll: the hygiene `ROLLBACK` is issued and stays pending;
2101        // leaving the block drops the open future mid-hygiene.
2102        {
2103            let mut open = std::pin::pin!(SqlTxSession::admit(
2104                "pg".into(),
2105                CheckedOutBackend::arm(io),
2106                now + Duration::from_secs(60),
2107                now + Duration::from_secs(60),
2108                ACQUIRE,
2109                MAX_CONNECTIONS,
2110                Arc::clone(&timer),
2111            ));
2112            assert!(poll_once_pending(&mut open), "hygiene must stay pending");
2113            assert_eq!(
2114                issued_of(&shared),
2115                vec![SQL_ROLLBACK],
2116                "exactly one ROLLBACK attempt, BEGIN never sent"
2117            );
2118        }
2119
2120        assert!(
2121            is_detached(&shared),
2122            "a drop mid-hygiene detaches (R0 arms at checkout)"
2123        );
2124        assert!(
2125            !is_released(&shared),
2126            "the detached connection is never re-pooled"
2127        );
2128    }
2129
2130    /// Frozen fixture `transacted_acquire_deadline_first` (spec "Block
2131    /// timeout"): the acquire deadline elapses first → typed `PoolExhausted`
2132    /// naming the datasource, the pool size, and the waited milliseconds.
2133    #[tokio::test(start_paused = true)]
2134    async fn transacted_acquire_deadline_first() {
2135        let error = hygiene_deadline_case(Duration::from_secs(60), Duration::from_millis(10)).await;
2136        match error {
2137            TransactionError::PoolExhausted {
2138                datasource,
2139                max_connections,
2140                waited_ms,
2141            } => {
2142                assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2143                assert_eq!(max_connections, MAX_CONNECTIONS);
2144                assert_eq!(waited_ms, 10, "waited_ms measures from the hygiene start");
2145            }
2146            other => panic!("expected typed PoolExhausted, got {other:?}"),
2147        }
2148    }
2149
2150    /// Frozen fixture `transacted_block_deadline_first` (spec "Block
2151    /// timeout"): with block deadline 30 s and acquire deadline 60 s, the
2152    /// typed `Timeout` names the datasource and the elapsed time measured
2153    /// from block entry.
2154    #[tokio::test(start_paused = true)]
2155    async fn transacted_block_deadline_first() {
2156        let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(60)).await;
2157        assert_eq!(
2158            error,
2159            TransactionError::Timeout {
2160                datasource: "pg".to_owned(),
2161                elapsed_ms: 30_000,
2162            },
2163            "elapsed is measured from block entry, not from the deadline"
2164        );
2165    }
2166
2167    /// Frozen fixture `transacted_deadline_tie` (spec "Block timeout"): both
2168    /// deadlines equal (30 s) at admission → the biased block arm reports
2169    /// `Timeout`, never `PoolExhausted`. Distinct from the body-race tie
2170    /// fixture `transacted_deadline_tie_selects_timeout` in camel-core.
2171    #[tokio::test(start_paused = true)]
2172    async fn transacted_deadline_tie() {
2173        let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(30)).await;
2174        assert_eq!(
2175            error,
2176            TransactionError::Timeout {
2177                datasource: "pg".to_owned(),
2178                elapsed_ms: 30_000,
2179            },
2180            "the tie resolves to the block-deadline error, never PoolExhausted"
2181        );
2182    }
2183
2184    /// Frozen "Block timeout" instant comparison, both deadlines already
2185    /// elapsed at the FIRST poll (paused clock): the race is decided by the
2186    /// stored absolute instants, not by the biased polling order. With the
2187    /// acquire deadline strictly earlier (`acquire_abs < block_abs`), the
2188    /// admission reports `PoolExhausted` even though the block timer arm is
2189    /// polled first; the tie (equal instants) reports `Timeout`.
2190    ///
2191    /// Distinct from [`transacted_hygiene_deadline_expiry`], whose orderings
2192    /// fire while both timers still run — this fixture is the same-poll
2193    /// pathology: at the first poll both `sleep_until` futures are ready.
2194    #[tokio::test(start_paused = true)]
2195    async fn transacted_deadline_both_elapsed_at_first_poll() {
2196        async fn case(block: Duration, acquire: Duration) -> TransactionError {
2197            let (mut io, shared) = FakeIo::channel();
2198            FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2199            let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2200            let now = timer.now();
2201            let hygiene = std::pin::pin!(admission_hygiene(
2202                &mut *io,
2203                Arc::clone(&timer),
2204                "pg",
2205                MAX_CONNECTIONS,
2206                now + block,
2207                now + acquire,
2208            ));
2209            // Advance past BOTH deadlines before the first poll: every race
2210            // arm is ready at once, so only the instant comparison decides.
2211            tokio::time::sleep(block.max(acquire) + Duration::from_secs(1)).await;
2212            let error = hygiene.await.expect_err("both deadlines are spent");
2213            assert!(
2214                issued_of(&shared).is_empty(),
2215                "the race resolved before any I/O was polled"
2216            );
2217            assert!(is_detached(&shared), "the losing deadline detaches");
2218            error
2219        }
2220
2221        let error = case(Duration::from_secs(60), Duration::from_millis(10)).await;
2222        match error {
2223            TransactionError::PoolExhausted {
2224                datasource,
2225                max_connections,
2226                ..
2227            } => {
2228                assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2229                assert_eq!(max_connections, MAX_CONNECTIONS);
2230            }
2231            other => panic!(
2232                "acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
2233            ),
2234        }
2235
2236        let error = case(Duration::from_millis(10), Duration::from_millis(10)).await;
2237        assert!(
2238            matches!(error, TransactionError::Timeout { .. }),
2239            "equal instants report Timeout on the tie, got {error:?}"
2240        );
2241    }
2242
2243    /// Frozen "Block timeout" instant comparison at the OPEN race site
2244    /// (checkout vs the two deadlines): the injected timer's sleeps are
2245    /// always ready, so both deadline arms resolve at the first poll —
2246    /// exactly the pathology the biased order cannot decide. With the
2247    /// acquire deadline strictly earlier, the open reports `PoolExhausted`;
2248    /// with equal instants, `Timeout`. The pool is never polled (`acquire`
2249    /// loses the race) — an in-memory SQLite pool stands in for the real one.
2250    #[tokio::test]
2251    async fn transacted_open_race_both_deadlines_elapsed_at_first_poll() {
2252        sqlx::any::install_default_drivers();
2253        let pool = sqlx::any::AnyPoolOptions::new() // allow-test-wait: in-memory sqlite connect, no network
2254            .max_connections(2)
2255            .connect("sqlite::memory:")
2256            .await
2257            .expect("in-memory sqlite pool");
2258        let timer: Arc<dyn TxTimer> = Arc::new(AlwaysElapsed);
2259        let now = timer.now();
2260
2261        // acquire_abs = now + 10 ms is strictly before block_abs = now + 60 s
2262        // and both sleeps resolve at the first poll → PoolExhausted.
2263        let open = SqlTxSession::open(
2264            "pg",
2265            &pool,
2266            now + Duration::from_secs(60),
2267            Duration::from_millis(10),
2268            Arc::clone(&timer),
2269        )
2270        .await;
2271        let error = match open {
2272            Err(error) => error,
2273            Ok(_) => panic!("both admission deadlines are spent"),
2274        };
2275        match error {
2276            TransactionError::PoolExhausted { datasource, .. } => {
2277                assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2278            }
2279            other => panic!(
2280                "acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
2281            ),
2282        }
2283
2284        // Equal instants → the tie reports Timeout, never PoolExhausted.
2285        let open = SqlTxSession::open(
2286            "pg",
2287            &pool,
2288            now + Duration::from_millis(10),
2289            Duration::from_millis(10),
2290            timer,
2291        )
2292        .await;
2293        let error = match open {
2294            Err(error) => error,
2295            Ok(_) => panic!("both admission deadlines are spent"),
2296        };
2297        assert!(
2298            matches!(error, TransactionError::Timeout { .. }),
2299            "equal instants report Timeout on the tie, got {error:?}"
2300        );
2301    }
2302
2303    /// R0 from `Clean`: dropping the session before any statement detaches
2304    /// synchronously, no SQL, never re-pooled.
2305    #[tokio::test]
2306    async fn forced_drop_from_clean_detaches_without_sql() {
2307        let (io, shared) = FakeIo::channel();
2308        let session = test_session(io, Arc::new(TokioTimer));
2309        assert_eq!(session.state(), TransactionState::Fresh);
2310
2311        drop(session);
2312        assert!(issued_of(&shared).is_empty(), "R0 from Clean sends no SQL");
2313        assert!(is_detached(&shared), "R0 detaches synchronously");
2314        assert!(!is_released(&shared), "R0 never returns the connection");
2315    }
2316
2317    /// R0 from `BeginPending`: a begin future left pending, then the session
2318    /// dropped — synchronous detach, no further SQL.
2319    #[tokio::test]
2320    async fn forced_drop_from_begin_pending_detaches_without_sql() {
2321        let (io, shared) = FakeIo::channel();
2322        FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
2323        let session = test_session(io, Arc::new(TokioTimer));
2324        {
2325            let mut begin = std::pin::pin!(session.begin());
2326            assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
2327        }
2328
2329        drop(session);
2330        assert_eq!(
2331            issued_of(&shared),
2332            vec![SQL_BEGIN],
2333            "R0 from BeginPending sends no further SQL"
2334        );
2335        assert!(is_detached(&shared), "R0 detaches synchronously");
2336        assert!(!is_released(&shared), "R0 never returns the connection");
2337    }
2338}