camel_core/transacted_segment.rs
1//! The transacted-block runtime segment (sqltrans-exec step 7, ruling 604d).
2//!
3//! [`TransactedSegment`] wraps one `transacted { datasource }` block body in
4//! the block lifecycle: open a session through the provider-neutral
5//! [`TransactionManager`] port, install the [`BLOCK_SESSION`] binding for the
6//! body task, race the body against the block deadline and the pipeline
7//! cancellation token, then finalize per the 604d pseudocode — commit only
8//! through the `state() == Active` R7 gate, otherwise the session's TOTAL
9//! `rollback()` (the session selects the action from its private `TxPhase`;
10//! the segment never re-derives lifecycle rows).
11//!
12//! Hexagonal boundary: this module is generic over the `camel-api` port. It
13//! never references `camel-sql`; the admission `min(block_abs, acquire_abs)`
14//! race and its `PoolExhausted` vs `Timeout` primary mapping live inside the
15//! manager's `open_session` (the sql component), and this segment maps the
16//! open result onto the exchange outcome. The port's `open_session()` carries
17//! no block instant (the production manager arms a stand-in internal one), so
18//! a ready `PoolExhausted` that resolves with the real block deadline already
19//! spent is re-adjudicated HERE, by absolute instants through
20//! [`TransactionManager::acquire_deadline`] (rc-9awnc). Step 9 wires the
21//! registry-resolved manager and this segment into the executor; nothing here
22//! resolves a registry.
23//!
24//! Decisions this module carries (all traced to a ruling):
25//!
26//! - **Open seam.** The segment takes an `Arc<dyn TransactionManager>`; the
27//! port's `open_session()` IS the "async closure returning
28//! `Result<Arc<dyn TransactionSession>, TransactionError>`". The segment
29//! still bounds the open await at `block_abs`: the open arm is polled
30//! first (a resolved open is authoritative — its internal race compares
31//! the absolute instants), and the timer resolves only a still-pending
32//! open (tie included → [`TransactionError::Timeout`] with elapsed
33//! measured from block entry): an open hook that ignores the block
34//! deadline can never hang the block.
35//! - **Cancellation.** The pipeline cancellation surface is the per-start
36//! `CANCEL_TOKEN` task-local the executor scopes around `run_steps`
37//! (ADR-0043); `run_steps` already maps an observed cancellation to
38//! [`CamelError::ConsumerStopping`]. The frozen `TransactionError` family
39//! has NO cancellation variant, so the segment's cancellation primary is
40//! `CamelError::ConsumerStopping` — the established convention — never
41//! `Timeout` (a deadline is not a cancellation).
42//! - **Cleanup context.** [`CamelError`] has no `with_cleanup` field, so the
43//! 604d `(Some(p), Err(u))` row logs the cleanup uncertainty (`warn!`) and
44//! returns the primary — the frozen spec: "the body error is primary and
45//! finalization uncertainty is carried in the outcome, not substituted for
46//! it". The `(None, Err(u))` row reports `u` itself (there is no primary to
47//! protect).
48//! - **Scope id.** One id is allocated per block execution (shared counter
49//! across clones) and exposed through the installed [`BlockSession`]; the
50//! executor may force a loader-baked id via
51//! [`TransactedSegment::run_with_scope`] when the `JOIN_SCOPE` baking
52//! decorator lands (step 8/9 wiring).
53//!
54//! [`BLOCK_SESSION`]: camel_api::transaction::join::BLOCK_SESSION
55
56use std::future::Future;
57use std::pin::Pin;
58use std::sync::Arc;
59use std::sync::atomic::AtomicU64;
60use std::sync::atomic::Ordering;
61use std::time::Duration;
62
63use camel_api::CamelError;
64use camel_api::Exchange;
65use camel_api::OutcomePipeline;
66use camel_api::OutcomeSegment;
67use camel_api::PipelineOutcome;
68use camel_api::TransactionState;
69use camel_api::transaction::TransactionError;
70use camel_api::transaction::TransactionManager;
71use camel_api::transaction::TransactionOutcome;
72use camel_api::transaction::TransactionSession;
73use camel_api::transaction::join::BlockSession;
74use camel_api::transaction::join::JoinScope;
75use tokio_util::sync::CancellationToken;
76
77use crate::lifecycle::adapters::route_compiler::CANCEL_TOKEN;
78
79/// Default block deadline measured at block entry (frozen spec "Block
80/// timeout": default 30 s, per-block override).
81pub const DEFAULT_BLOCK_TIMEOUT: Duration = Duration::from_secs(30);
82
83/// Outcome-aware structural segment for a `transacted { datasource }` block.
84///
85/// Operates at the [`PipelineOutcome`] layer so a clean `Stopped` from the
86/// body propagates unchanged per ADR-0025 — a Stop is successful control
87/// flow and MUST NOT become a rollback report (604c R2).
88#[derive(Clone)]
89pub struct TransactedSegment {
90 /// Datasource the block is transacted on; names every typed error.
91 pub datasource: String,
92 /// Block deadline measured from entry; default [`DEFAULT_BLOCK_TIMEOUT`],
93 /// per-block override through [`TransactedSegment::with_block_timeout`].
94 pub block_timeout: Duration,
95 /// Open seam: `open_session()` checks out + hygienizes the connection
96 /// (lazy — `BEGIN` is never sent here). Resolved above this segment.
97 pub manager: Arc<dyn TransactionManager>,
98 /// The block body pipeline.
99 pub body: OutcomeSegment,
100 /// Per-execution scope allocation, shared across clones so two runs of
101 /// the same compiled block never observe the same scope id.
102 scope_seq: Arc<AtomicU64>,
103}
104
105impl TransactedSegment {
106 /// Build a segment on `datasource` with the default block timeout.
107 #[must_use]
108 pub fn new(
109 datasource: impl Into<String>,
110 manager: Arc<dyn TransactionManager>,
111 body: OutcomeSegment,
112 ) -> Self {
113 Self {
114 datasource: datasource.into(),
115 block_timeout: DEFAULT_BLOCK_TIMEOUT,
116 manager,
117 body,
118 scope_seq: Arc::new(AtomicU64::new(0)),
119 }
120 }
121
122 /// Override the block deadline (frozen spec "Block timeout": per-block
123 /// override of the 30 s default).
124 #[must_use]
125 pub fn with_block_timeout(mut self, block_timeout: Duration) -> Self {
126 self.block_timeout = block_timeout;
127 self
128 }
129
130 /// Run the block with a runtime-allocated scope id.
131 pub async fn run(&mut self, exchange: Exchange) -> PipelineOutcome {
132 let scope = JoinScope::new(self.scope_seq.fetch_add(1, Ordering::Relaxed));
133 self.run_in(exchange, scope).await
134 }
135
136 /// Run the block with a caller-chosen scope id.
137 ///
138 /// The seam the executor (step 9) uses once joined sql steps carry a
139 /// loader-baked scope: the installed [`BlockSession`] must carry the SAME
140 /// id the joined steps compare against.
141 pub async fn run_with_scope(
142 &mut self,
143 exchange: Exchange,
144 scope: JoinScope,
145 ) -> PipelineOutcome {
146 self.run_in(exchange, scope).await
147 }
148
149 /// One block execution: admission, body race, finalization.
150 async fn run_in(&mut self, exchange: Exchange, scope: JoinScope) -> PipelineOutcome {
151 // Block deadline at BLOCK ENTRY as an absolute instant (frozen spec
152 // "Block timeout": deadlines are compared, never polled).
153 let entry = tokio::time::Instant::now();
154 let block_abs = entry + self.block_timeout;
155 let datasource = self.datasource.clone();
156
157 // Pipeline cancellation surface (ADR-0043): the executor scopes
158 // CANCEL_TOKEN around run_steps; absent means "never cancelled",
159 // exactly like run_steps' own between-steps check.
160 let cancel = CANCEL_TOKEN.try_with(CancellationToken::clone).ok();
161
162 // Admission: checkout + hygiene race `min(block_abs, acquire_abs)`
163 // INSIDE the manager's open (604c admission; `PoolExhausted` vs
164 // `Timeout` primary mapping happens in camel-sql's open). This
165 // segment bounds the await at block_abs: the open arm is polled
166 // FIRST, so a resolved open is authoritative — its internal race
167 // already compares block_abs/acquire_abs as absolute instants
168 // (`PoolExhausted` iff `acquire_abs < block_abs`, frozen spec "Block
169 // timeout", never decided by polling order). The timer arm resolves
170 // only a STILL-PENDING open (tie included → `Timeout`), expiry drops
171 // the open future, so a checked-out connection detaches via the
172 // guard (R0). Any open error maps onto the exchange failure and the
173 // (partially opened) session is simply discarded.
174 //
175 // rc-9awnc: the port's `open_session()` carries no block instant, so
176 // a manager that arms a stand-in internal block instant cannot decide
177 // the both-elapsed tie itself. When a `PoolExhausted` resolves with
178 // the REAL block deadline also spent (now >= block_abs), the segment
179 // adjudicates by absolute instants — `acquire_abs = open_start +
180 // acquire_deadline()`; `block_abs <= acquire_abs` (tie included) →
181 // `Timeout` measured from entry, acquire strictly first → the
182 // `PoolExhausted` passes through. Soundness: the stand-in instant
183 // never elapses first, so `PoolExhausted` always implies the real
184 // acquire arm elapsed. A `PoolExhausted` while `now < block_abs` is a
185 // genuine acquire expiry and passes through unchanged; non-deadline
186 // errors (`RollbackUncertain`, …) are never re-adjudicated.
187 let open_start = tokio::time::Instant::now();
188 let session: Arc<dyn TransactionSession> = tokio::select! {
189 biased;
190 opened = self.manager.open_session() => match opened {
191 Ok(session) => session,
192 Err(e @ TransactionError::PoolExhausted { .. })
193 if tokio::time::Instant::now() >= block_abs =>
194 {
195 let acquire_abs = open_start + self.manager.acquire_deadline();
196 if block_abs <= acquire_abs {
197 return PipelineOutcome::Failed(CamelError::from(timeout_error(
198 &datasource,
199 entry,
200 )));
201 }
202 return PipelineOutcome::Failed(CamelError::from(e));
203 }
204 Err(e) => return PipelineOutcome::Failed(CamelError::from(e)),
205 },
206 _ = tokio::time::sleep_until(block_abs) => {
207 return PipelineOutcome::Failed(CamelError::from(timeout_error(&datasource, entry)));
208 }
209 };
210
211 // Install BLOCK_SESSION for the body task: datasource, this run's
212 // scope id, and the block's own session allocation.
213 let block_session =
214 BlockSession::new(self.datasource.as_str(), scope, Arc::clone(&session));
215
216 // Body race (604c §A): `biased select { sleep_until(block_deadline),
217 // CANCEL_TOKEN.cancelled(), body }` IN THAT ORDER — tie → deadline
218 // wins → Timeout.
219 let body_end = tokio::select! {
220 biased;
221 _ = tokio::time::sleep_until(block_abs) => BodyEnd::Deadline,
222 _ = cancelled_or_pending(cancel.as_ref()) => BodyEnd::Cancelled,
223 outcome = block_session.enter(self.body.run(exchange)) => match outcome {
224 PipelineOutcome::Failed(e) => BodyEnd::Err(e),
225 // Boxed: PipelineOutcome dwarfs the other variants and the
226 // deadline/cancelled arms would carry the padding.
227 outcome @ (PipelineOutcome::Completed(_) | PipelineOutcome::Stopped(_)) => {
228 BodyEnd::Ok(Box::new(outcome))
229 }
230 },
231 };
232
233 self.finalize(session, body_end, cancel.as_ref(), entry, block_abs)
234 .await
235 }
236
237 /// 604d finalization pseudocode, line for line.
238 ///
239 /// The segment decides commit-vs-rollback ONLY; the session's total
240 /// `rollback()` selects the lifecycle action from its private `TxPhase`.
241 /// A cleanup result never replaces an existing primary error.
242 async fn finalize(
243 &self,
244 s: Arc<dyn TransactionSession>,
245 body_end: BodyEnd,
246 cancel: Option<&CancellationToken>,
247 entry: tokio::time::Instant,
248 block_abs: tokio::time::Instant,
249 ) -> PipelineOutcome {
250 let datasource = self.datasource.clone();
251
252 // primary = match body_end { // precedence lives here, unchanged
253 let (mut primary, ok_outcome): (Option<CamelError>, Option<Box<PipelineOutcome>>) =
254 match body_end {
255 BodyEnd::Deadline => (Some(timeout_error(&datasource, entry).into()), None),
256 BodyEnd::Err(e) => (Some(e), None),
257 // The frozen TransactionError family has no cancellation variant;
258 // the pipeline convention (run_steps) is ConsumerStopping.
259 BodyEnd::Cancelled => (Some(CamelError::ConsumerStopping), None),
260 BodyEnd::Ok(_) if s.is_rollback_only() => (
261 Some(
262 TransactionError::AbortedByHandledError {
263 datasource: datasource.clone(),
264 }
265 .into(),
266 ),
267 None,
268 ),
269 BodyEnd::Ok(outcome) => (None, Some(outcome)),
270 };
271
272 // if primary.is_none() && s.state() == Active { // R7 gate
273 if primary.is_none() && s.state() == TransactionState::Active {
274 // The gate reads the observable state (lossy Fresh is fine: any
275 // non-Active state falls through to the total rollback).
276 let now = tokio::time::Instant::now();
277 // if CANCEL_TOKEN.is_cancelled() || now >= block_deadline { // R6 cutoff
278 if cancel.is_some_and(CancellationToken::is_cancelled) || now >= block_abs {
279 // primary = Some(if now >= block_deadline { Timeout } else { Cancelled })
280 primary = Some(if now >= block_abs {
281 timeout_error(&datasource, entry).into()
282 } else {
283 CamelError::ConsumerStopping
284 });
285 } else {
286 // else { return map_commit(s.commit().await, body_end) } // R7, no re-consult
287 return map_commit(s.commit().await, ok_outcome, &datasource);
288 }
289 }
290
291 // let r = s.rollback().await; // R1–R6: session selects by TxPhase
292 let r = s.rollback().await;
293 // match (primary, r) { ... }
294 match (primary, r) {
295 // (None, Ok(_)) => body_end_ok_unchanged — R2 clean; Stop
296 // propagates per ADR-0025 (a Stop never becomes a rollback report).
297 // Unreachable-by-construction: primary None implies the body
298 // ended Ok, so the outcome is always present — an `expect` keeps
299 // the invariant loud where a silent fallback would have to name a
300 // typed error that is a misnomer here (nothing was committed and
301 // the rollback was acknowledged).
302 (None, Ok(_)) => {
303 *ok_outcome.expect("primary None implies the body ended Ok") // allow-unwrap: unreachable invariant; loud panic beats a silent misnamed fallback
304 }
305 // (None, Err(u)) => Err(u) — e.g. step-local drop left BeginPending
306 (None, Err(u)) => PipelineOutcome::Failed(CamelError::from(u)),
307 // (Some(p), Ok(_)) => Err(p)
308 (Some(p), Ok(_)) => PipelineOutcome::Failed(p),
309 // (Some(p), Err(u)) => Err(p).with_cleanup(u) — CamelError carries
310 // no cleanup-context field, so the uncertainty is logged and the
311 // primary returned (frozen spec: never substituted).
312 (Some(p), Err(u)) => {
313 tracing::warn!(
314 datasource = %datasource,
315 cleanup = %u,
316 primary = %p,
317 "transacted block cleanup was not acknowledged; the primary error stands"
318 );
319 PipelineOutcome::Failed(p)
320 }
321 }
322 }
323}
324
325impl OutcomePipeline for TransactedSegment {
326 fn clone_box(&self) -> Box<dyn OutcomePipeline> {
327 Box::new(self.clone())
328 }
329
330 fn run<'a>(
331 &'a mut self,
332 exchange: Exchange,
333 ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
334 // Qualified call: inherent methods shadow trait methods, but the
335 // names collide here — select the inherent `run` explicitly.
336 Box::pin(TransactedSegment::run(self, exchange))
337 }
338}
339
340/// The body-race resolution: `BodyEnd ∈ {Ok(Continue), Ok(Stopped), Err(e),
341/// Deadline, Cancelled}` (604c §A). `Ok` carries the success outcome —
342/// `Completed` or a clean `Stopped`, both preserved unchanged.
343enum BodyEnd {
344 /// The body returned a success outcome (`Completed` or `Stopped`).
345 /// Boxed: `PipelineOutcome` dwarfs the other variants.
346 Ok(Box<PipelineOutcome>),
347 /// The body failed with an unhandled error.
348 Err(CamelError),
349 /// The block deadline elapsed first (tie included).
350 Deadline,
351 /// The pipeline cancellation token fired first.
352 Cancelled,
353}
354
355/// `Timeout { datasource, elapsed }` measured from BLOCK ENTRY (frozen spec
356/// "Block timeout": the typed error names the datasource and elapsed time).
357fn timeout_error(datasource: &str, entry: tokio::time::Instant) -> TransactionError {
358 TransactionError::Timeout {
359 datasource: datasource.to_owned(),
360 elapsed_ms: u64::try_from(entry.elapsed().as_millis()).unwrap_or(u64::MAX),
361 }
362}
363
364/// The race branch for cancellation: the scoped token's `cancelled()` future,
365/// or a never-ready future when the task-local is absent (direct calls and
366/// unscooped tests never observe a cancellation).
367async fn cancelled_or_pending(cancel: Option<&CancellationToken>) {
368 match cancel {
369 Some(token) => token.cancelled().await,
370 None => std::future::pending::<()>().await,
371 }
372}
373
374/// map_commit: commit Ok + body Ok/Stopped → the block's success outcome
375/// (Stopped propagates unchanged per ADR-0025); commit Err(e) → Err(e) — a
376/// cleanup result never replaces a primary, and the session already folded
377/// its cleanup into the returned error (the port has no separate cleanup
378/// channel for commit).
379fn map_commit(
380 commit: Result<TransactionOutcome, TransactionError>,
381 body_outcome: Option<Box<PipelineOutcome>>,
382 datasource: &str,
383) -> PipelineOutcome {
384 match commit {
385 Ok(TransactionOutcome::Committed) => {
386 body_outcome.map(|boxed| *boxed).unwrap_or_else(|| {
387 // log-policy: system-broken
388 tracing::error!(
389 datasource,
390 "commit acknowledged but the body outcome was lost; reporting CommitUncertain"
391 );
392 PipelineOutcome::Failed(CamelError::Transaction(
393 TransactionError::CommitUncertain {
394 datasource: datasource.to_owned(),
395 },
396 ))
397 })
398 }
399 Ok(outcome) => {
400 // log-policy: system-broken
401 tracing::error!(
402 datasource,
403 ?outcome,
404 "commit resolved to a non-Committed outcome; reporting CommitUncertain"
405 );
406 PipelineOutcome::Failed(CamelError::Transaction(TransactionError::CommitUncertain {
407 datasource: datasource.to_owned(),
408 }))
409 }
410 Err(e) => PipelineOutcome::Failed(CamelError::from(e)),
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use std::sync::Arc;
417 use std::sync::Mutex;
418 use std::sync::atomic::AtomicBool;
419 use std::sync::atomic::Ordering;
420 use std::task::Poll;
421 use std::time::Duration;
422
423 use camel_api::Message;
424 use camel_api::transaction::join::current_block_session;
425 use camel_component_api::test_support::log_capture;
426
427 use super::*;
428
429 const DS: &str = "pg";
430
431 /// Install a bare registry as the process-global tracing default, once
432 /// per test binary. Guards the `capture_logs_async` test against
433 /// callsite-interest poisoning: `tracing` caches each callsite's
434 /// `Interest` process-wide from its FIRST macro execution, evaluated
435 /// against the executing thread's dispatcher. Subscriber-less sibling
436 /// tests in this binary reach the segment's cleanup `warn!` callsite
437 /// first and cache `Interest::never`, so a later thread-local
438 /// `set_default` capture silently drops the event. The global registry
439 /// heals prior poison and floors future interest evaluations at
440 /// `sometimes` (fix pattern: c3853198; bd rc-img5).
441 fn ensure_global_tracing_default() {
442 static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
443 if INIT.set(()).is_ok() {
444 let _ = tracing::subscriber::set_global_default(tracing_subscriber::registry());
445 }
446 }
447
448 // ── Fake session ────────────────────────────────────────────────────
449
450 /// Scripted [`TransactionSession`]: the segment's fixture. `state` is
451 /// whatever the test wants the lossy projection to report; the
452 /// `rollback()`/`commit()` scripts stand in for the session's private
453 /// `TxPhase` machinery (implemented for real by `SqlTxSession`).
454 struct FakeSession {
455 commit_result: Result<TransactionOutcome, TransactionError>,
456 rollback_result: Result<TransactionOutcome, TransactionError>,
457 state: TransactionState,
458 rollback_only: AtomicBool,
459 calls: Mutex<Vec<&'static str>>,
460 /// When set, `commit()` stays pending until the token fires: the
461 /// cancellation-mid-commit seam for the frozen post-cutoff fixtures.
462 commit_gate: Option<CancellationToken>,
463 }
464
465 impl FakeSession {
466 fn new(
467 state: TransactionState,
468 commit: Result<TransactionOutcome, TransactionError>,
469 rollback: Result<TransactionOutcome, TransactionError>,
470 ) -> Arc<Self> {
471 Arc::new(Self {
472 commit_result: commit,
473 rollback_result: rollback,
474 state,
475 rollback_only: AtomicBool::new(false),
476 calls: Mutex::new(Vec::new()),
477 commit_gate: None,
478 })
479 }
480
481 /// A session whose `commit()` stays pending until `gate` fires: the
482 /// cancellation-mid-commit seam for the frozen post-cutoff fixtures.
483 /// The commit resolves with `commit` after the gate; the rollback
484 /// script MUST never be reached (R7 never consults cancellation).
485 fn gated(
486 commit: Result<TransactionOutcome, TransactionError>,
487 gate: CancellationToken,
488 ) -> Arc<Self> {
489 Arc::new(Self {
490 commit_result: commit,
491 rollback_result: Ok(TransactionOutcome::RolledBack),
492 state: TransactionState::Active,
493 rollback_only: AtomicBool::new(false),
494 calls: Mutex::new(Vec::new()),
495 commit_gate: Some(gate),
496 })
497 }
498
499 fn with_flag(self: Arc<Self>) -> Arc<Self> {
500 self.rollback_only.store(true, Ordering::Relaxed);
501 self
502 }
503
504 fn record(&self, call: &'static str) {
505 self.calls
506 .lock()
507 .unwrap_or_else(std::sync::PoisonError::into_inner)
508 .push(call);
509 }
510
511 fn calls(&self) -> Vec<&'static str> {
512 self.calls
513 .lock()
514 .unwrap_or_else(std::sync::PoisonError::into_inner)
515 .clone()
516 }
517 }
518
519 impl TransactionSession for FakeSession {
520 fn datasource(&self) -> &str {
521 DS
522 }
523
524 fn state(&self) -> TransactionState {
525 self.state
526 }
527
528 fn begin(&self) -> camel_api::transaction::BeginFuture<'_> {
529 Box::pin(std::future::ready(Ok(())))
530 }
531
532 fn set_rollback_only(&self) {
533 self.rollback_only.store(true, Ordering::Relaxed);
534 }
535
536 fn is_rollback_only(&self) -> bool {
537 self.rollback_only.load(Ordering::Relaxed)
538 }
539
540 fn commit(&self) -> camel_api::transaction::FinalizeFuture<'_> {
541 self.record("commit");
542 let result = self.commit_result.clone();
543 match self.commit_gate.clone() {
544 // Cancellation-mid-commit seam: hold the COMMIT until the
545 // token fires, then resolve per the script (R7 never
546 // re-consults the token).
547 Some(gate) => Box::pin(async move {
548 gate.cancelled().await;
549 result
550 }),
551 None => Box::pin(std::future::ready(result)),
552 }
553 }
554
555 fn rollback(&self) -> camel_api::transaction::FinalizeFuture<'_> {
556 self.record("rollback");
557 Box::pin(std::future::ready(self.rollback_result.clone()))
558 }
559 }
560
561 // ── Fake manager (the open seam) ────────────────────────────────────
562
563 /// Scripted [`TransactionManager`]: what `open_session()` resolves to.
564 enum OpenScript {
565 /// Hand back an already-built session Arc.
566 Session(Arc<dyn TransactionSession>),
567 /// The hook itself fails (PoolExhausted / Timeout / … from the
568 /// camel-sql admission race). Mapped onto the exchange failure.
569 Fail(TransactionError),
570 /// Checkout never completes: only the segment's block-abs bound
571 /// resolves it.
572 Pending,
573 /// The hook stays pending on its FIRST poll and fails with the
574 /// scripted error from every later poll: at the block-deadline poll
575 /// the open future is READY at the same instant the timer fires, so
576 /// the race must decide by the open's own instant comparison, not by
577 /// polling order.
578 FailAfterFirstPoll(TransactionError),
579 }
580
581 struct FakeManager {
582 script: OpenScript,
583 /// What `acquire_deadline()` reports: the segment re-derives the
584 /// absolute acquire instant from it when adjudicating a both-elapsed
585 /// `PoolExhausted` (rc-9awnc). Mirrors the production manager, whose
586 /// internal block instant is a stand-in (`NO_BLOCK_DEADLINE`).
587 acquire_deadline: Duration,
588 }
589
590 impl FakeManager {
591 /// A manager with the production-default 5 s acquire bound.
592 fn script(script: OpenScript) -> Self {
593 Self {
594 script,
595 acquire_deadline: Duration::from_secs(5),
596 }
597 }
598
599 /// Override the reported acquire bound: the absolute-instant
600 /// adjudication compares it against the real block deadline.
601 fn with_acquire_deadline(mut self, acquire_deadline: Duration) -> Self {
602 self.acquire_deadline = acquire_deadline;
603 self
604 }
605 }
606
607 impl TransactionManager for FakeManager {
608 fn datasource(&self) -> &str {
609 DS
610 }
611
612 fn acquire_deadline(&self) -> Duration {
613 self.acquire_deadline
614 }
615
616 fn open_session(&self) -> camel_api::transaction::OpenSessionFuture<'_> {
617 match &self.script {
618 OpenScript::Session(session) => {
619 let session = Arc::clone(session);
620 Box::pin(std::future::ready(Ok(session)))
621 }
622 OpenScript::Fail(e) => {
623 let e = e.clone();
624 Box::pin(std::future::ready(Err(e)))
625 }
626 OpenScript::Pending => Box::pin(std::future::pending()),
627 OpenScript::FailAfterFirstPoll(e) => {
628 let e = e.clone();
629 // Per-call flag: poll #1 pends (the hook is in flight),
630 // every later poll fails — at the block-deadline wake the
631 // open future is READY at the same poll the timer fires.
632 let mut polled = false;
633 Box::pin(std::future::poll_fn(move |_cx| {
634 if polled {
635 Poll::Ready(Err(e.clone()))
636 } else {
637 polled = true;
638 Poll::Pending
639 }
640 }))
641 }
642 }
643 }
644 }
645
646 // ── Scripted body ───────────────────────────────────────────────────
647
648 /// What the body pipeline does. An [`OutcomePipeline`] so it fits
649 /// [`OutcomeSegment`] exactly like a compiled step chain.
650 #[derive(Clone)]
651 enum BodyScript {
652 /// Complete with `Completed(exchange carrying `text`)`.
653 Complete(&'static str),
654 /// Complete with `Stopped(exchange carrying `text`)`.
655 Stop(&'static str),
656 /// Fail with `ProcessorError("body failed")`.
657 Fail,
658 /// Never resolve — only the deadline branch can win.
659 Hang,
660 /// Cancel the pipeline token as the body's last act, then complete:
661 /// the R6 cutoff sees the flag set after the body race resolved Ok.
662 CancelThenComplete(&'static str, CancellationToken),
663 /// Read the installed BLOCK_SESSION, record `(datasource, scope)` in
664 /// `seen`, prove the session pointer identity, then complete.
665 Observe {
666 expected_session: Arc<dyn TransactionSession>,
667 seen: Arc<Mutex<Option<(String, u64)>>>,
668 },
669 }
670
671 impl OutcomePipeline for BodyScript {
672 fn clone_box(&self) -> Box<dyn OutcomePipeline> {
673 Box::new(self.clone())
674 }
675
676 fn run<'a>(
677 &'a mut self,
678 _exchange: Exchange,
679 ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
680 let script = self.clone();
681 Box::pin(async move {
682 match script {
683 BodyScript::Complete(text) => {
684 PipelineOutcome::Completed(Exchange::new(Message::new(text)))
685 }
686 BodyScript::Stop(text) => {
687 PipelineOutcome::Stopped(Exchange::new(Message::new(text)))
688 }
689 BodyScript::Fail => PipelineOutcome::Failed(CamelError::ProcessorError(
690 "body failed".to_owned(),
691 )),
692 BodyScript::Hang => std::future::pending::<PipelineOutcome>().await,
693 BodyScript::CancelThenComplete(text, token) => {
694 token.cancel();
695 PipelineOutcome::Completed(Exchange::new(Message::new(text)))
696 }
697 BodyScript::Observe {
698 expected_session,
699 seen,
700 } => {
701 let running = current_block_session()
702 .expect("the body task must see BLOCK_SESSION installed");
703 assert_eq!(
704 running.datasource(),
705 DS,
706 "the binding names the block datasource"
707 );
708 assert!(
709 Arc::ptr_eq(&running.session(), &expected_session),
710 "the body must see the block's own session allocation"
711 );
712 *seen
713 .lock()
714 .unwrap_or_else(std::sync::PoisonError::into_inner) =
715 Some((running.datasource().to_owned(), running.scope().get()));
716 PipelineOutcome::Completed(Exchange::new(Message::new("observed")))
717 }
718 }
719 })
720 }
721 }
722
723 // ── Harness ─────────────────────────────────────────────────────────
724
725 fn segment(
726 manager: FakeManager,
727 body: BodyScript,
728 block_timeout: Duration,
729 ) -> TransactedSegment {
730 TransactedSegment::new(DS, Arc::new(manager), OutcomeSegment::new(Box::new(body)))
731 .with_block_timeout(block_timeout)
732 }
733
734 fn session_manager(session: Arc<FakeSession>) -> FakeManager {
735 FakeManager::script(OpenScript::Session(session))
736 }
737
738 fn tx_err(e: &CamelError) -> &TransactionError {
739 match e {
740 CamelError::Transaction(tx) => tx,
741 other => panic!("expected a Transaction error, got {other:?}"),
742 }
743 }
744
745 fn assert_failed_timeout(outcome: PipelineOutcome, min_elapsed_ms: u64) {
746 let PipelineOutcome::Failed(e) = outcome else {
747 panic!("expected Failed, got {outcome:?}");
748 };
749 match tx_err(&e) {
750 TransactionError::Timeout {
751 datasource,
752 elapsed_ms,
753 } => {
754 assert_eq!(datasource, DS);
755 assert!(
756 *elapsed_ms >= min_elapsed_ms,
757 "Timeout.elapsed_ms must measure from block entry: {elapsed_ms}"
758 );
759 }
760 other => panic!("expected Timeout, got {other:?}"),
761 }
762 }
763
764 fn assert_failed_tx(outcome: PipelineOutcome, expected: &TransactionError) {
765 let PipelineOutcome::Failed(e) = outcome else {
766 panic!("expected Failed, got {outcome:?}");
767 };
768 assert_eq!(tx_err(&e), expected, "typed primary mismatch");
769 }
770
771 fn assert_failed_processor(outcome: PipelineOutcome) {
772 let PipelineOutcome::Failed(CamelError::ProcessorError(message)) = outcome else {
773 panic!("expected Failed(ProcessorError), got {outcome:?}");
774 };
775 assert_eq!(message, "body failed", "the body error must stay primary");
776 }
777
778 fn assert_completed_text(outcome: PipelineOutcome, text: &str) {
779 let PipelineOutcome::Completed(ex) = outcome else {
780 panic!("expected Completed, got {outcome:?}");
781 };
782 assert_eq!(ex.input.body.as_text(), Some(text));
783 }
784
785 fn assert_stopped_text(outcome: PipelineOutcome, text: &str) {
786 let PipelineOutcome::Stopped(ex) = outcome else {
787 panic!("expected Stopped, got {outcome:?}");
788 };
789 assert_eq!(ex.input.body.as_text(), Some(text));
790 }
791
792 fn committed() -> Result<TransactionOutcome, TransactionError> {
793 Ok(TransactionOutcome::Committed)
794 }
795
796 fn rolled_back() -> Result<TransactionOutcome, TransactionError> {
797 Ok(TransactionOutcome::RolledBack)
798 }
799
800 fn uncertain() -> Result<TransactionOutcome, TransactionError> {
801 Err(TransactionError::RollbackUncertain {
802 datasource: DS.to_owned(),
803 })
804 }
805
806 /// Assert target for the R7 loop in `transacted_r7_commits_active_body`.
807 enum Assert {
808 Completed,
809 Stopped,
810 }
811
812 // ── THE fixture: fresh-rollback precedence table ────────────────────
813
814 /// The 604d `(primary, r)` outcome table over fresh/lossy sessions:
815 /// Deadline, Err, and Ok bodies crossed with acknowledged and
816 /// unacknowledged `rollback()`, INCLUDING the no-primary row (body Ok +
817 /// a step-local drop leaving `BeginPending`, reported as the lossy
818 /// `Fresh` state with the flag clear + `rollback()` →
819 /// `Err(RollbackUncertain)` ⇒ the reported outcome is
820 /// `Err(RollbackUncertain)`).
821 #[tokio::test]
822 async fn transacted_fresh_rollback_precedence() {
823 // (Some(p), Ok(_)) — R5: Deadline primary, cleanup acknowledged.
824 let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
825 let mut seg = segment(
826 session_manager(session.clone()),
827 BodyScript::Hang,
828 Duration::from_millis(30),
829 );
830 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
831 assert_failed_timeout(outcome, 30);
832 assert_eq!(
833 session.calls(),
834 vec!["rollback"],
835 "commit is never consulted on a Deadline body"
836 );
837
838 // (Some(p), Err(u)) — R5: Deadline primary, cleanup NOT substituted.
839 let session = FakeSession::new(TransactionState::Fresh, committed(), uncertain());
840 let mut seg = segment(
841 session_manager(session.clone()),
842 BodyScript::Hang,
843 Duration::from_millis(30),
844 );
845 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
846 assert_failed_timeout(outcome, 30);
847 assert_eq!(session.calls(), vec!["rollback"]);
848
849 // (Some(p), Ok(_)) — body Err is primary, cleanup acknowledged.
850 let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
851 let mut seg = segment(
852 session_manager(session.clone()),
853 BodyScript::Fail,
854 Duration::from_secs(1),
855 );
856 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
857 assert_failed_processor(outcome);
858 assert_eq!(
859 session.calls(),
860 vec!["rollback"],
861 "commit is never consulted on an Err body"
862 );
863
864 // (Some(p), Err(u)) — body Err primary, cleanup carried in the log.
865 let session = FakeSession::new(TransactionState::Active, committed(), uncertain());
866 let mut seg = segment(
867 session_manager(session.clone()),
868 BodyScript::Fail,
869 Duration::from_secs(1),
870 );
871 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
872 assert_failed_processor(outcome);
873 assert_eq!(session.calls(), vec!["rollback"]);
874
875 // (None, Err(u)) — THE no-primary row: body Ok, flag clear, state()
876 // Fresh (lossy BeginPending — the R7 gate correctly does not infer
877 // begin-ness from state()), cleanup unacknowledged ⇒ the cleanup
878 // result IS the outcome: Err(RollbackUncertain).
879 let session = FakeSession::new(TransactionState::Fresh, committed(), uncertain());
880 let mut seg = segment(
881 session_manager(session.clone()),
882 BodyScript::Complete("ok"),
883 Duration::from_secs(1),
884 );
885 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
886 assert_failed_tx(
887 outcome,
888 &TransactionError::RollbackUncertain {
889 datasource: DS.to_owned(),
890 },
891 );
892 assert_eq!(
893 session.calls(),
894 vec!["rollback"],
895 "Fresh is not Active: the R7 gate must not reach commit"
896 );
897
898 // (None, Ok(_)) — R2 clean: BEGIN never sent, body Ok unchanged.
899 let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
900 let mut seg = segment(
901 session_manager(session.clone()),
902 BodyScript::Complete("ok"),
903 Duration::from_secs(1),
904 );
905 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
906 assert_completed_text(outcome, "ok");
907 assert_eq!(session.calls(), vec!["rollback"]);
908
909 // (None, Ok(_)) — R2 clean Stop propagates per ADR-0025: a Stop must
910 // NOT become a rollback report (the outcome stays Stopped; the
911 // rollback itself is still the session's R2 no-SQL answer).
912 let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
913 let mut seg = segment(
914 session_manager(session.clone()),
915 BodyScript::Stop("halted"),
916 Duration::from_secs(1),
917 );
918 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
919 assert_stopped_text(outcome, "halted");
920 assert_eq!(session.calls(), vec!["rollback"]);
921 }
922
923 // ── Table pins ──────────────────────────────────────────────────────
924
925 /// R7 commit path: body Ok, state Active, flag clear, cutoff passed ⇒
926 /// commit called once, rollback never, the body outcome unchanged; a
927 /// clean Stopped propagates as Stopped (ADR-0025).
928 #[tokio::test]
929 async fn transacted_r7_commits_active_body() {
930 for (body, text, expect) in [
931 (BodyScript::Complete("ok"), "ok", Assert::Completed),
932 (BodyScript::Stop("halted"), "halted", Assert::Stopped),
933 ] {
934 let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
935 let mut seg = segment(
936 session_manager(session.clone()),
937 body,
938 Duration::from_secs(1),
939 );
940 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
941 match expect {
942 Assert::Completed => assert_completed_text(outcome, text),
943 Assert::Stopped => assert_stopped_text(outcome, text),
944 }
945 assert_eq!(
946 session.calls(),
947 vec!["commit"],
948 "R7: exactly one COMMIT, no rollback"
949 );
950 }
951 }
952
953 /// R6 cutoff FAIL: the flag is set between the body race resolving Ok and
954 /// the finalization handoff ⇒ rollback runs, commit is NEVER consulted,
955 /// and the primary is the cancellation error (deadline not elapsed).
956 #[tokio::test]
957 async fn transacted_r6_cutoff_cancels_before_commit() {
958 let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
959 // One token, two handles: the executor-scooped task-local the segment
960 // reads, and the clone the body cancels as its last act.
961 let token = CancellationToken::new();
962 let mut seg = segment(
963 session_manager(session.clone()),
964 BodyScript::CancelThenComplete("ok", token.clone()),
965 Duration::from_secs(1),
966 );
967 let outcome = CANCEL_TOKEN
968 .scope(token, async move {
969 seg.run(Exchange::new(Message::new("m"))).await
970 })
971 .await;
972 let PipelineOutcome::Failed(e) = outcome else {
973 panic!("expected Failed, got {outcome:?}");
974 };
975 assert!(
976 matches!(e, CamelError::ConsumerStopping),
977 "R6 cutoff failure with the deadline unelapsed is the cancellation error, got {e:?}"
978 );
979 assert_eq!(
980 session.calls(),
981 vec!["rollback"],
982 "R6: COMMIT is never sent after a failed cutoff"
983 );
984 }
985
986 /// R4 flag-only: `rollback_only` set + body Ok ⇒ the FLAG alone triggers
987 /// the rollback row with the `AbortedByHandledError` primary; commit is
988 /// never consulted even though the state is Active.
989 #[tokio::test]
990 async fn transacted_flag_only_rolls_back_ok_body() {
991 let session =
992 FakeSession::new(TransactionState::Active, committed(), rolled_back()).with_flag();
993 let mut seg = segment(
994 session_manager(session.clone()),
995 BodyScript::Complete("ok"),
996 Duration::from_secs(1),
997 );
998 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
999 assert_failed_tx(
1000 outcome,
1001 &TransactionError::AbortedByHandledError {
1002 datasource: DS.to_owned(),
1003 },
1004 );
1005 assert_eq!(
1006 session.calls(),
1007 vec!["rollback"],
1008 "R4: the flag alone forbids COMMIT"
1009 );
1010 }
1011
1012 /// Deadline race tie → Timeout wins: with the deadline already elapsed
1013 /// and the body immediately ready, the biased select order resolves
1014 /// Deadline first — never the body's Ok.
1015 #[tokio::test]
1016 async fn transacted_deadline_tie_selects_timeout() {
1017 let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
1018 let mut seg = segment(
1019 session_manager(session.clone()),
1020 BodyScript::Complete("fast"),
1021 Duration::ZERO,
1022 );
1023 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1024 assert_failed_timeout(outcome, 0);
1025 assert_eq!(
1026 session.calls(),
1027 vec!["rollback"],
1028 "commit is never consulted on a Deadline body"
1029 );
1030 }
1031
1032 /// Body-race Cancelled arm: the scoped token is pre-cancelled and the
1033 /// deadline is far, so the biased select resolves Cancelled (never the
1034 /// hanging body, never the deadline). Fresh/clean session ⇒
1035 /// `(Some(ConsumerStopping), Ok(RolledBack))` — the primary is the
1036 /// cancellation error and the connection returns clean, NOT a Timeout.
1037 #[tokio::test]
1038 async fn transacted_cancelled_body_rolls_back_clean() {
1039 let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
1040 let token = CancellationToken::new();
1041 token.cancel(); // pre-cancelled: the race branch is ready on first poll
1042 let mut seg = segment(
1043 session_manager(session.clone()),
1044 BodyScript::Hang,
1045 Duration::from_secs(1),
1046 );
1047 let outcome = CANCEL_TOKEN
1048 .scope(token, async move {
1049 seg.run(Exchange::new(Message::new("m"))).await
1050 })
1051 .await;
1052 let PipelineOutcome::Failed(e) = outcome else {
1053 panic!("expected Failed, got {outcome:?}");
1054 };
1055 assert!(
1056 matches!(e, CamelError::ConsumerStopping),
1057 "a cancelled body race is the cancellation error, never Timeout, got {e:?}"
1058 );
1059 assert_eq!(
1060 session.calls(),
1061 vec!["rollback"],
1062 "cancellation rolls back through the session's clean R2 path"
1063 );
1064 }
1065
1066 /// Frozen fixture `transacted_stalled_rollback`, segment tier (spec "Block
1067 /// timeout"): the body deadline fires (primary `Timeout`) and the cleanup
1068 /// `rollback()` is unacknowledged — the segment reports the Timeout
1069 /// primary (never substitutes the cleanup error) and carries the cleanup
1070 /// uncertainty in the `warn!`, per bd rc-ngk4e (log-carried context;
1071 /// `CamelError` has no `with_cleanup` field).
1072 #[tokio::test]
1073 async fn transacted_stalled_rollback_logs_cleanup_context() {
1074 ensure_global_tracing_default();
1075 let session = FakeSession::new(TransactionState::Active, committed(), uncertain());
1076 let mut seg = segment(
1077 session_manager(session.clone()),
1078 BodyScript::Hang,
1079 Duration::from_millis(30),
1080 );
1081 let (outcome, captured) =
1082 log_capture::capture_logs_async(seg.run(Exchange::new(Message::new("m")))).await;
1083
1084 assert_failed_timeout(outcome, 30);
1085 assert_eq!(
1086 session.calls(),
1087 vec!["rollback"],
1088 "commit is never consulted on a Deadline body"
1089 );
1090 assert!(
1091 captured.contains("transacted block cleanup was not acknowledged"),
1092 "the (Some(p), Err(u)) row carries the cleanup uncertainty in the log: {captured}"
1093 );
1094 assert!(
1095 captured.contains("primary error stands"),
1096 "the log states the primary error is not substituted: {captured}"
1097 );
1098 }
1099
1100 /// BLOCK_SESSION binding: the body task sees the block's datasource, its
1101 /// own session allocation, and a per-execution scope id that increments
1102 /// across runs of the same segment (so it can be baked into joined steps).
1103 #[tokio::test]
1104 async fn transacted_block_session_scopes_the_body() {
1105 let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
1106 let seen = Arc::new(Mutex::new(None));
1107 let mut seg = segment(
1108 session_manager(session.clone()),
1109 BodyScript::Observe {
1110 expected_session: session,
1111 seen: Arc::clone(&seen),
1112 },
1113 Duration::from_secs(1),
1114 );
1115 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1116 assert_completed_text(outcome, "observed");
1117 let (datasource, first_scope) = {
1118 let guard = seen
1119 .lock()
1120 .unwrap_or_else(std::sync::PoisonError::into_inner);
1121 guard
1122 .clone()
1123 .expect("the body recorded the installed binding")
1124 };
1125 assert_eq!(datasource, DS);
1126
1127 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1128 assert_completed_text(outcome, "observed");
1129 let (_, second_scope) = {
1130 let guard = seen
1131 .lock()
1132 .unwrap_or_else(std::sync::PoisonError::into_inner);
1133 guard.clone().expect("the second run recorded its binding")
1134 };
1135 assert_eq!(
1136 second_scope,
1137 first_scope + 1,
1138 "every block execution allocates a fresh scope id"
1139 );
1140 }
1141
1142 /// Admission: open-hook errors map onto the exchange failure unchanged
1143 /// (`PoolExhausted` and `Timeout` primaries are the camel-sql race's to
1144 /// name) and the partially opened session is simply discarded. A hook
1145 /// that ignores the block deadline is bounded at block_abs with tie →
1146 /// Timeout measured from entry.
1147 #[tokio::test]
1148 async fn transacted_open_error_maps_to_exchange_failure() {
1149 // PoolExhausted straight from the admission race (fixture (c) of
1150 // rc-9awnc: the block deadline has NOT elapsed when the open
1151 // resolves — a genuine acquire expiry, passed through unchanged).
1152 let mut seg = segment(
1153 FakeManager::script(OpenScript::Fail(TransactionError::PoolExhausted {
1154 datasource: DS.to_owned(),
1155 max_connections: 1,
1156 waited_ms: 5,
1157 })),
1158 BodyScript::Complete("ok"),
1159 Duration::from_secs(1),
1160 );
1161 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1162 assert_failed_tx(
1163 outcome,
1164 &TransactionError::PoolExhausted {
1165 datasource: DS.to_owned(),
1166 max_connections: 1,
1167 waited_ms: 5,
1168 },
1169 );
1170
1171 // Timeout straight from the admission race — passed through, not
1172 // re-mapped by the segment (a non-deadline open error family member
1173 // is never re-adjudicated; `Timeout` from the manager is already the
1174 // race's own verdict).
1175 let mut seg = segment(
1176 FakeManager::script(OpenScript::Fail(TransactionError::Timeout {
1177 datasource: DS.to_owned(),
1178 elapsed_ms: 7,
1179 })),
1180 BodyScript::Complete("ok"),
1181 Duration::from_secs(1),
1182 );
1183 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1184 assert_failed_tx(
1185 outcome,
1186 &TransactionError::Timeout {
1187 datasource: DS.to_owned(),
1188 elapsed_ms: 7,
1189 },
1190 );
1191
1192 // A hook that never completes is bounded by the block deadline
1193 // (biased tie → Timeout, elapsed measured from block entry).
1194 let mut seg = segment(
1195 FakeManager::script(OpenScript::Pending),
1196 BodyScript::Complete("ok"),
1197 Duration::from_millis(20),
1198 );
1199 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1200 assert_failed_timeout(outcome, 20);
1201 }
1202
1203 /// Frozen "Block timeout" instant comparison at the segment's open race
1204 /// (spec: "Deadlines are compared as absolute instants — not by
1205 /// outer-timeout polling order"): an open that resolves AT the
1206 /// block-deadline poll is authoritative. rc-9awnc fixture (b): the
1207 /// acquire arm elapsed STRICTLY first (`acquire_abs = open_start +
1208 /// acquire_deadline()` < `block_abs`), so the ready `PoolExhausted`
1209 /// passes through even though the block timer fires at the same poll.
1210 /// The timer bound applies only to a still-pending open (tie →
1211 /// Timeout, pinned above).
1212 #[tokio::test]
1213 async fn transacted_open_race_ready_open_decides_over_elapsed_deadline() {
1214 // The open stays pending on its first poll, then fails with
1215 // PoolExhausted: at the 20 ms poll the open future and the block
1216 // timer are ready at once, and the absolute comparison passes the
1217 // error through (acquire 5 ms < block 20 ms).
1218 let exhausted = TransactionError::PoolExhausted {
1219 datasource: DS.to_owned(),
1220 max_connections: 1,
1221 waited_ms: 5,
1222 };
1223 let mut seg = segment(
1224 FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone()))
1225 .with_acquire_deadline(Duration::from_millis(5)),
1226 BodyScript::Complete("ok"),
1227 Duration::from_millis(20),
1228 );
1229 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1230 assert_failed_tx(outcome, &exhausted);
1231 }
1232
1233 /// rc-9awnc: both-elapsed adjudication at the segment tier. The port's
1234 /// `open_session()` carries no block instant (the production manager arms
1235 /// a stand-in internal one), so a ready `PoolExhausted` that resolves
1236 /// with the REAL block deadline also spent is re-adjudicated by absolute
1237 /// instants through `acquire_deadline()`: `block_abs <= acquire_abs`
1238 /// (tie included) → `Timeout` from entry; acquire strictly first → the
1239 /// `PoolExhausted` passes through.
1240 #[tokio::test(start_paused = true)]
1241 async fn transacted_open_pool_exhausted_adjudicated_by_absolute_instants() {
1242 let exhausted = TransactionError::PoolExhausted {
1243 datasource: DS.to_owned(),
1244 max_connections: 1,
1245 waited_ms: 5,
1246 };
1247
1248 // Fixture (a): block_abs < acquire_abs (production manager: the
1249 // stand-in internal block instant never elapses first), both elapsed
1250 // at the first poll — the ready `PoolExhausted` does NOT win; the
1251 // earlier block deadline reports `Timeout{elapsed from entry}`.
1252 let mut seg = segment(
1253 FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone())),
1254 BodyScript::Complete("ok"),
1255 Duration::from_millis(20),
1256 );
1257 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1258 assert_failed_timeout(outcome, 20);
1259
1260 // Tie (block_abs == acquire_abs, start-paused tokio time): the
1261 // frozen tie resolves to `Timeout` as well.
1262 let mut seg = segment(
1263 FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone()))
1264 .with_acquire_deadline(Duration::from_millis(20)),
1265 BodyScript::Complete("ok"),
1266 Duration::from_millis(20),
1267 );
1268 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1269 assert_failed_timeout(outcome, 20);
1270
1271 // Fixture (c): `PoolExhausted` resolves while the block deadline has
1272 // NOT elapsed — a genuine acquire expiry, passed through unchanged.
1273 let mut seg = segment(
1274 FakeManager::script(OpenScript::Fail(exhausted.clone())),
1275 BodyScript::Complete("ok"),
1276 Duration::from_millis(20),
1277 );
1278 let outcome = seg.run(Exchange::new(Message::new("m"))).await;
1279 assert_failed_tx(outcome, &exhausted);
1280 }
1281
1282 /// Frozen fixture `transacted_cancel_after_commit_ack` (spec
1283 /// "Cancellation cutoff" / "cancellation after the cutoff with a
1284 /// deterministic ACK"), at the segment tier where CANCEL_TOKEN lives:
1285 /// cancellation arrives MID-COMMIT — the gated fake session resolves
1286 /// COMMIT only once the (scoped) token fires — and R7 never consults it
1287 /// again: the outcome is `Completed` and `rollback` is NEVER called.
1288 ///
1289 /// Determinism: the canceller task runs at the segment's first yield,
1290 /// which is the commit gate itself (open and body resolve on their first
1291 /// poll), so the token is still clean at the R6 cutoff and fires strictly
1292 /// mid-commit.
1293 #[tokio::test]
1294 async fn transacted_cancel_after_commit_ack() {
1295 // One token, three handles: the task-local the segment reads, the
1296 // commit gate, and the canceller's.
1297 let token = CancellationToken::new();
1298 let session = FakeSession::gated(Ok(TransactionOutcome::Committed), token.clone());
1299 tokio::spawn({
1300 let token = token.clone();
1301 async move {
1302 // Runs at the segment's first yield — the commit gate — so
1303 // cancellation lands strictly mid-commit, never at the R6
1304 // cutoff.
1305 token.cancel();
1306 }
1307 });
1308 let mut seg = segment(
1309 session_manager(session.clone()),
1310 BodyScript::Complete("ok"),
1311 Duration::from_secs(1),
1312 );
1313 let outcome = CANCEL_TOKEN
1314 .scope(token, async move {
1315 seg.run(Exchange::new(Message::new("m"))).await
1316 })
1317 .await;
1318 assert_completed_text(outcome, "ok");
1319 assert_eq!(
1320 session.calls(),
1321 vec!["commit"],
1322 "post-handoff cancellation is never consulted: no rollback call"
1323 );
1324 }
1325
1326 /// Frozen fixture `transacted_cancel_after_commit_lost` (spec
1327 /// "Cancellation cutoff" / "cancellation after the cutoff with a lost
1328 /// ACK"), at the segment tier: cancellation arrives mid-commit and the
1329 /// COMMIT acknowledgment is lost (`CommitUncertain`) — the block fails
1330 /// with `CommitUncertain`, and no ROLLBACK is issued or claimed.
1331 #[tokio::test]
1332 async fn transacted_cancel_after_commit_lost() {
1333 let token = CancellationToken::new();
1334 let session = FakeSession::gated(
1335 Err(TransactionError::CommitUncertain {
1336 datasource: DS.to_owned(),
1337 }),
1338 token.clone(),
1339 );
1340 tokio::spawn({
1341 let token = token.clone();
1342 async move {
1343 token.cancel();
1344 }
1345 });
1346 let mut seg = segment(
1347 session_manager(session.clone()),
1348 BodyScript::Complete("ok"),
1349 Duration::from_secs(1),
1350 );
1351 let outcome = CANCEL_TOKEN
1352 .scope(token, async move {
1353 seg.run(Exchange::new(Message::new("m"))).await
1354 })
1355 .await;
1356 assert_failed_tx(
1357 outcome,
1358 &TransactionError::CommitUncertain {
1359 datasource: DS.to_owned(),
1360 },
1361 );
1362 assert_eq!(
1363 session.calls(),
1364 vec!["commit"],
1365 "a lost ACK after the cutoff is never reported as a rollback"
1366 );
1367 }
1368}