Skip to main content

khive_db/
writer_task.rs

1//! Single-writer task and bounded write queue (ADR-067 Component A).
2//!
3//! `WriterTask` (via `spawn` and the drain loop `run_writer_task`) owns a
4//! dedicated standalone writer `rusqlite::Connection` and is the only code
5//! path that issues `BEGIN IMMEDIATE` for write traffic routed through the
6//! channel it drains. Callers reach it exclusively through a
7//! [`WriterTaskHandle`], sending a typed closure and awaiting a typed
8//! oneshot reply so each store method's natural return type (e.g.
9//! `BatchWriteSummary`) survives the trip through the type-erased channel
10//! unmodified — a flat `Result<u64, StorageError>` reply would conflate
11//! `affected`/`failed` into one count and drop `first_error`.
12//!
13//! See `crates/khive-db/docs/api/writer-task.md` for migration-slice scope
14//! (which write paths currently route through this vs. the legacy
15//! pool-mutex path) and the ADR-067 component breakdown.
16//!
17//! ## ADR-136 D1 gate 5: writer classification
18//!
19//! Every connection that issues writes against a khive-db file falls into
20//! exactly one of the rows below. Request-path store writes, runtime
21//! merge/symmetric-edge transactions,
22//! and `khive_storage::SqlAccess` (`SqlBridge::writer`/`atomic_unit`) are subject
23//! to `PoolConfig::write_queue_enabled` / `write_routing_strict` routing.
24//! Everything else here is an
25//! explicit, intentional exemption — not an implicit gap left over from an
26//! incomplete migration.
27//!
28//! | Writer | Connection | Request-path write | Routing |
29//! | --- | --- | --- | --- |
30//! | Request-path writes (`create`, `update`, batch upserts, …) | `WriterTaskHandle` (queue-first) or a standalone/pool-mutex connection on degrade | Yes | Queue-first (ADR-136 D1 gate 1); strict routing fails closed on degrade |
31//! | Startup / schema migrations (`migrations::run_migrations`, `apply_schema_plan`) | The pool's own writer-mutex connection (`ConnectionPool::new`, before the `WriterTask` is ever spawned) | No | Exempt — runs once at boot, before any queue handle exists to route through |
32//! | Checkpointing (`checkpoint::CheckpointConnection`) | Dedicated standalone connection, opened once at task startup (ADR-091 Amendment 5, #1652) | No | Exempt by design — the whole point of that fix was moving checkpoint I/O OFF the pool writer's admission path; routing it back through the write queue would reintroduce the contention it removed |
33//! | Recovery (`walpin` beacon/sidecar bookkeeping) | None — file-level bookkeeping (PID beacons, heartbeats) alongside the database, not a SQL connection against it | No | N/A — never acquires a database writer connection |
34//! | Top-level maintenance (`VACUUM` via `execute_script_top_level`/`WriterTaskHandle::send_top_level`) | `WriterTaskHandle`, skipping the per-request `BEGIN IMMEDIATE`/`COMMIT` wrap only | Yes | Routed through the SAME single writer owner as every other queued request — only the transaction wrap is skipped, never the queue |
35//!
36//! Store constructors may run outside Tokio and temporarily cache no handle;
37//! every store request-path write refreshes through
38//! `ConnectionPool::writer_task_for_write` at execution time. Strict routing
39//! refuses a missing handle, while the explicit compatibility fallback emits
40//! its store-specific violation at the actual direct-writer seam. Runtime
41//! entity/note merges and symmetric edge updates use the same routing policy
42//! through a closed operation adapter. The strict default itself remains gated
43//! by ADR-135 F2 / ADR-136 D2 evidence.
44//!
45//! A `direct_route_violation` sink row (`timeout_sink::emit_direct_route_violation`,
46//! ADR-136 D1 gate 6c) is emitted ONLY for the first row's degrade path — a
47//! request-path write that bypassed an enabled queue. The other four
48//! rows are exempt by design and never emit that row.
49
50use rusqlite::Connection;
51use std::collections::HashMap;
52use std::panic::{catch_unwind, AssertUnwindSafe};
53use std::path::{Path, PathBuf};
54use std::sync::atomic::{AtomicBool, Ordering};
55use std::sync::{Arc, Mutex, OnceLock};
56use std::time::{Duration, Instant};
57use tokio::sync::{mpsc, oneshot};
58
59use khive_storage::error::{StorageError, WriterTaskRequestState};
60
61use crate::error::SqliteError;
62use crate::pool::{ConnectionPool, WriterAcquisitionCounters};
63use crate::writer_admission_metrics::{
64    AdmissionObservation, Snapshot, Unavailable, WriterAdmissionMetrics,
65};
66
67#[path = "writer_task_labels.rs"]
68mod labels;
69
70pub(crate) use labels::{collect_statement_labels, MAX_WRITE_LABELS};
71use labels::{dedup_labels, SubmitLabels};
72
73/// Retry delays after a busy/locked `BEGIN IMMEDIATE` refusal. The operation
74/// closure remains owned by the request until one BEGIN succeeds, so these
75/// are the only retries this path may perform. Persistent contention is
76/// bounded to three total BEGIN attempts and 15 ms of explicit backoff, and
77/// the attempts together share one configured `busy_timeout` acquisition
78/// budget rather than each waiting out a full window of their own.
79const WRITER_BEGIN_RETRY_DELAYS: [Duration; 2] =
80    [Duration::from_millis(5), Duration::from_millis(10)];
81
82/// Closure signature for a write operation executed against the writer
83/// task's dedicated connection.
84///
85/// `conn` is already inside a `BEGIN IMMEDIATE` transaction opened by
86/// `run_writer_task` when this runs. The closure must issue DML (and, in
87/// later slices, named `SAVEPOINT`s) only — never a bare `BEGIN` / `COMMIT`
88/// / `ROLLBACK` — a nested bare `BEGIN IMMEDIATE` would violate SQLite's
89/// nested-transaction rule and return `SQLITE_ERROR: cannot start a
90/// transaction within a transaction` (ADR-067 lines 271-276).
91type WriteOp<R> = Box<dyn FnOnce(&Connection) -> Result<R, StorageError> + Send>;
92
93/// Latest completed writer-task span for one database, decomposed at the
94/// boundaries an operator can act on (#1849). A zero value means that phase
95/// did not run (top-level/early-failure request) or completed below the
96/// microsecond clock resolution; `total_micros` retains the full span.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct WriterStageObservation {
99    pub queue_wait_micros: u64,
100    pub transaction_acquire_micros: u64,
101    pub body_micros: u64,
102    pub commit_micros: u64,
103    pub total_micros: u64,
104    pub queue_depth_at_entry: u64,
105    pub observed_at_unix_ms: u64,
106    /// Distinct labels the drained request ran, in first-seen order,
107    /// deduplicated and bounded at `MAX_WRITE_LABELS`. Resolved only for a
108    /// write that crossed the slow-write threshold, so empty for every write
109    /// below it; also empty when no statement in the request carried a label
110    /// and the submit site had no name in hand — e.g. an opaque closure from
111    /// a caller with no `&'static str` operation.
112    pub labels: Vec<String>,
113    /// Distinct labels dropped past `MAX_WRITE_LABELS`, when the request
114    /// named more; `None` when nothing was dropped.
115    pub labels_truncated: Option<u64>,
116}
117
118static WRITER_STAGE_OBSERVATIONS: OnceLock<
119    Mutex<HashMap<Option<PathBuf>, WriterStageObservation>>,
120> = OnceLock::new();
121
122fn writer_stage_observations() -> &'static Mutex<HashMap<Option<PathBuf>, WriterStageObservation>> {
123    WRITER_STAGE_OBSERVATIONS.get_or_init(|| Mutex::new(HashMap::new()))
124}
125
126fn writer_db_key_from_path(path: Option<&Path>) -> Option<PathBuf> {
127    path.map(Path::to_path_buf)
128}
129
130fn writer_db_key(pool: &ConnectionPool) -> Option<PathBuf> {
131    writer_db_key_from_path(pool.canonical_path())
132}
133
134fn duration_micros(duration: Duration) -> u64 {
135    duration.as_micros().min(u128::from(u64::MAX)) as u64
136}
137
138fn observed_at_unix_ms() -> u64 {
139    std::time::SystemTime::now()
140        .duration_since(std::time::UNIX_EPOCH)
141        .map(|duration| duration.as_millis() as u64)
142        .unwrap_or(0)
143}
144
145/// Pure in-memory read of the most recently completed writer-task span for
146/// this exact backend. It acquires no SQLite connection and performs no I/O.
147pub fn last_writer_stage_observation(pool: &ConnectionPool) -> Option<WriterStageObservation> {
148    writer_stage_observations()
149        .lock()
150        .unwrap_or_else(std::sync::PoisonError::into_inner)
151        .get(&writer_db_key(pool))
152        .cloned()
153}
154
155#[cfg(test)]
156trait TestWriterStageClock: Send + Sync {
157    fn now(&self) -> Instant;
158    fn at_commit(&self);
159}
160
161struct WriteTelemetryOptions {
162    attempt_log: bool,
163    top_level: bool,
164}
165
166struct WriteTelemetry {
167    #[cfg(test)]
168    test_clock: Option<std::sync::Arc<dyn TestWriterStageClock>>,
169    backend_key: Option<PathBuf>,
170    db: String,
171    submitted_at: Instant,
172    queue_depth_at_entry: usize,
173    slow_write_threshold: Option<Duration>,
174    labels: SubmitLabels,
175    /// Per-attempt mode (`timeout_sink::writer_attempt_log_enabled`) of the
176    /// handle this request was submitted through.
177    attempt_log: bool,
178    top_level: bool,
179    /// The caller's request id, read from the submitting task's request
180    /// context at submit time, so a per-attempt row joins to the caller's
181    /// own record of the request. `None` for writes no request scoped.
182    request_id: Option<u64>,
183}
184
185impl WriteTelemetry {
186    fn new(
187        backend_key: Option<PathBuf>,
188        db: String,
189        queue_depth_at_entry: usize,
190        slow_write_threshold: Option<Duration>,
191        labels: SubmitLabels,
192        options: WriteTelemetryOptions,
193    ) -> Self {
194        Self {
195            #[cfg(test)]
196            test_clock: None,
197            backend_key,
198            db,
199            submitted_at: Instant::now(),
200            queue_depth_at_entry,
201            slow_write_threshold,
202            labels,
203            attempt_log: options.attempt_log,
204            top_level: options.top_level,
205            request_id: khive_storage::current_request_id(),
206        }
207    }
208
209    fn queue_wait(&self) -> Duration {
210        self.submitted_at.elapsed()
211    }
212
213    /// The labels named on this request, bounded to [`MAX_WRITE_LABELS`]
214    /// plus the count of distinct labels dropped. Computed only on the slow
215    /// path, since only [`Self::finish`] calls it: the fast path never turns
216    /// a [`SubmitLabels::Site`] name into an allocation.
217    fn resolve_labels(&self) -> (Vec<String>, Option<u64>) {
218        match &self.labels {
219            SubmitLabels::None => (Vec::new(), None),
220            SubmitLabels::Site(site) => (vec![(*site).to_owned()], None),
221            SubmitLabels::Statements(labels) => {
222                if labels.len() <= MAX_WRITE_LABELS {
223                    (labels.clone(), None)
224                } else {
225                    let dropped = (labels.len() - MAX_WRITE_LABELS) as u64;
226                    (labels[..MAX_WRITE_LABELS].to_vec(), Some(dropped))
227                }
228            }
229        }
230    }
231
232    #[allow(clippy::too_many_arguments)]
233    fn finish(
234        self,
235        queue_wait: Duration,
236        transaction_acquire: Duration,
237        body: Duration,
238        commit: Duration,
239        succeeded: bool,
240        rows_changed: u64,
241    ) {
242        let total = self.submitted_at.elapsed();
243        let slow = self
244            .slow_write_threshold
245            .is_some_and(|threshold| total >= threshold);
246        // Labels are resolved only for a write that crossed the slow
247        // threshold, or for every write in per-attempt mode, so outside that
248        // mode a fast write never turns a site name into an allocation; its
249        // observation carries no labels.
250        let (labels, labels_truncated) = if slow || self.attempt_log {
251            self.resolve_labels()
252        } else {
253            (Vec::new(), None)
254        };
255        let observation = WriterStageObservation {
256            queue_wait_micros: duration_micros(queue_wait),
257            transaction_acquire_micros: duration_micros(transaction_acquire),
258            body_micros: duration_micros(body),
259            commit_micros: duration_micros(commit),
260            total_micros: duration_micros(total),
261            queue_depth_at_entry: self.queue_depth_at_entry as u64,
262            observed_at_unix_ms: observed_at_unix_ms(),
263            labels,
264            labels_truncated,
265        };
266        writer_stage_observations()
267            .lock()
268            .unwrap_or_else(std::sync::PoisonError::into_inner)
269            .insert(self.backend_key, observation.clone());
270
271        if slow {
272            crate::timeout_sink::emit_slow_write(&self.db, &observation);
273        }
274        if self.attempt_log {
275            crate::timeout_sink::emit_writer_attempt(
276                &self.db,
277                &observation,
278                crate::timeout_sink::WriterAttempt {
279                    request_id: self.request_id,
280                    succeeded,
281                    rows_changed,
282                    top_level: self.top_level,
283                },
284            );
285        }
286    }
287}
288
289struct ReplyReceipt<R> {
290    commit_issued: AtomicBool,
291    completed: Mutex<Option<Result<R, StorageError>>>,
292}
293
294impl<R> Default for ReplyReceipt<R> {
295    fn default() -> Self {
296        Self {
297            commit_issued: AtomicBool::new(false),
298            completed: Mutex::new(None),
299        }
300    }
301}
302
303impl<R> ReplyReceipt<R> {
304    fn completed(&self) -> std::sync::MutexGuard<'_, Option<Result<R, StorageError>>> {
305        self.completed
306            .lock()
307            .unwrap_or_else(std::sync::PoisonError::into_inner)
308    }
309}
310
311struct PendingWrite<R> {
312    reply_rx: oneshot::Receiver<Result<R, StorageError>>,
313    receipt: Arc<ReplyReceipt<R>>,
314}
315
316impl<R> PendingWrite<R> {
317    async fn wait(self) -> Result<R, StorageError> {
318        match self.reply_rx.await {
319            Ok(result) => result,
320            Err(source) => {
321                // A computed error is stronger evidence than a missing delivery, including
322                // a known rollback or a native SQLite failure before COMMIT.
323                if let Some(Err(error)) = self.receipt.completed().take() {
324                    return Err(error);
325                }
326                if self.receipt.commit_issued.load(Ordering::Acquire) {
327                    Err(StorageError::WriteOutcomeUnknown {
328                        source: Box::new(source),
329                    })
330                } else {
331                    Err(writer_task_terminated(
332                        WriterTaskRequestState::SideEffectsUnknown,
333                    ))
334                }
335            }
336        }
337    }
338}
339
340// Private drain tests also await the raw typed reply, without changing their assertions.
341#[cfg(test)]
342impl<R> std::future::Future for PendingWrite<R> {
343    type Output = Result<Result<R, StorageError>, oneshot::error::RecvError>;
344
345    fn poll(
346        self: std::pin::Pin<&mut Self>,
347        cx: &mut std::task::Context<'_>,
348    ) -> std::task::Poll<Self::Output> {
349        std::future::Future::poll(std::pin::Pin::new(&mut self.get_mut().reply_rx), cx)
350    }
351}
352
353/// One write request awaiting execution by the writer task.
354///
355/// Carries a typed closure and a typed oneshot reply so that the concrete
356/// return type `R` (e.g. `BatchWriteSummary`) is preserved end to end,
357/// while [`AnyWriteRequest`] lets the drain loop hold heterogeneous
358/// requests in one homogeneous channel.
359///
360/// `top_level` (ADR-067 Component A): when `true`,
361/// the drain loop runs this request's operation WITHOUT wrapping it in a
362/// `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` — still serialized through the
363/// single writer owner (only one request drains at a time regardless of
364/// this flag), but with the transaction wrap skipped entirely. Exists for
365/// statements SQLite forbids inside any open transaction (e.g. `VACUUM`);
366/// see [`WriterTaskHandle::send_top_level`].
367pub struct WriteRequest<R: Send + 'static> {
368    op: WriteOp<R>,
369    reply: oneshot::Sender<Result<R, StorageError>>,
370    receipt: Arc<ReplyReceipt<R>>,
371    top_level: bool,
372    /// Only the typed checkpoint entry point may bypass disk admission.
373    checkpoint_bypass: bool,
374    vacuum_copy_headroom: bool,
375    /// The lease class of the issuing thread's scope when the request was
376    /// queued, applied on the writer thread when it takes the volume lease.
377    lease_class: crate::disk_guard::WriteClassContext,
378    telemetry: WriteTelemetry,
379    admission: Option<AdmissionObservation>,
380}
381
382mod sealed {
383    /// Restricts [`super::AnyWriteRequest`] to implementations defined in
384    /// this module — only [`super::WriteRequest<R>`] implements it — and
385    /// carries the drain loop's internal terminal-state reporting methods
386    /// without changing the public execution-method signatures.
387    pub trait Sealed {
388        fn start_execution(&mut self);
389
390        fn execute_and_reply_reporting_terminal(
391            self: Box<Self>,
392            conn: &rusqlite::Connection,
393            tx_span: Option<khive_storage::tx_registry::TxHandle>,
394            queue_wait: std::time::Duration,
395            transaction_acquire: std::time::Duration,
396        ) -> Option<khive_storage::error::WriterTaskRequestState>;
397
398        fn execute_and_reply_top_level_reporting_terminal(
399            self: Box<Self>,
400            conn: &rusqlite::Connection,
401            queue_wait: std::time::Duration,
402        ) -> Option<khive_storage::error::WriterTaskRequestState>;
403
404        fn reply_error_after_begin(
405            self: Box<Self>,
406            err: khive_storage::error::StorageError,
407            queue_wait: std::time::Duration,
408            transaction_acquire: std::time::Duration,
409        );
410    }
411}
412
413/// Type-erased write request the writer task's drain loop can hold in a
414/// homogeneous channel (`mpsc::Sender<Box<dyn AnyWriteRequest + Send>>`),
415/// while each concrete [`WriteRequest<R>`] still carries its own typed
416/// reply. Sealed: only this module may implement it (ADR-067 lines
417/// 210-212).
418pub trait AnyWriteRequest: sealed::Sealed + Send {
419    /// Runs this request's operation against `conn`, commits or rolls back
420    /// the enclosing transaction based on the outcome, and sends the
421    /// (possibly commit-failure-adjusted) result to the request's oneshot
422    /// reply channel.
423    ///
424    /// `conn` must already be inside a successfully-opened `BEGIN IMMEDIATE`
425    /// transaction opened by the caller (`run_writer_task`) — this method
426    /// issues only `COMMIT` / `ROLLBACK`, never `BEGIN`, so `run_writer_task`
427    /// remains the sole issuer of `BEGIN IMMEDIATE` (ADR-067 Component A).
428    /// Callers must use [`Self::reply_error`] instead when the enclosing
429    /// `BEGIN IMMEDIATE` itself failed — this method must not be invoked in
430    /// that case.
431    fn execute_and_reply(self: Box<Self>, conn: &Connection);
432
433    /// Runs this request's operation directly against `conn` — no
434    /// transaction wrap, no `COMMIT`/`ROLLBACK` — and sends the result to
435    /// the request's oneshot reply channel.
436    ///
437    /// Used only for [`Self::is_top_level`] requests: the drain loop calls
438    /// this INSTEAD of `execute_and_reply` for such requests, skipping
439    /// `BEGIN IMMEDIATE` entirely so a statement that must run outside any
440    /// transaction (e.g. `VACUUM`) can still be serialized through the
441    /// single writer owner.
442    fn execute_and_reply_top_level(self: Box<Self>, conn: &Connection);
443
444    /// Replies with `err` without running this request's operation or
445    /// touching `conn`.
446    ///
447    /// Used when the enclosing `BEGIN IMMEDIATE` failed (for example,
448    /// `SQLITE_BUSY` from lock contention with an unmigrated writer path
449    /// still holding the pool's writer mutex — reachable while only
450    /// `entity.rs` is routed through this channel). Running the operation
451    /// anyway would execute its DML against `conn` in autocommit mode,
452    /// landing partial writes for a request the caller is told failed.
453    /// Skipping the operation entirely keeps "the caller got an error" and
454    /// "no rows landed" true together.
455    fn reply_error(self: Box<Self>, err: StorageError);
456
457    /// `true` if the drain loop must run this request via
458    /// [`Self::execute_and_reply_top_level`] (no transaction wrap) instead
459    /// of [`Self::execute_and_reply`] (wrapped in `BEGIN IMMEDIATE`).
460    fn is_top_level(&self) -> bool;
461
462    fn is_checkpoint_bypass(&self) -> bool;
463
464    fn needs_vacuum_headroom(&self) -> bool;
465
466    /// The issuing thread's lease-class context, captured when it was queued.
467    fn lease_class(&self) -> crate::disk_guard::WriteClassContext;
468
469    /// Time from the caller constructing this request (before bounded-channel
470    /// admission) until the writer task dequeued it.
471    fn queue_wait(&self) -> Duration;
472}
473
474#[derive(Debug, Clone, Copy, PartialEq, Eq)]
475enum RollbackDisposition {
476    RolledBack,
477    SideEffectsUnknown,
478}
479
480/// Roll back a failed wrapped request and verify that the connection really
481/// returned to autocommit mode before it can serve another request.
482fn rollback_after_failure(conn: &Connection, failure_context: &'static str) -> RollbackDisposition {
483    match conn.execute_batch("ROLLBACK") {
484        Ok(()) if conn.is_autocommit() => RollbackDisposition::RolledBack,
485        Ok(()) => {
486            tracing::error!(
487                failure_context,
488                "writer transaction: ROLLBACK returned success but the connection is still in a \
489                 transaction; request side effects are unknown"
490            );
491            RollbackDisposition::SideEffectsUnknown
492        }
493        Err(rollback_error) => {
494            tracing::error!(
495                error = %rollback_error,
496                failure_context,
497                "writer transaction: rollback after request failure failed; request side effects are \
498                 unknown"
499            );
500            RollbackDisposition::SideEffectsUnknown
501        }
502    }
503}
504
505/// Execute an operation inside an already-open transaction and apply the
506/// shared commit, rollback, panic, and autocommit verification rules.
507///
508/// This worker/owned adapter catches callback panics, attempts rollback, and
509/// returns a typed terminal outcome. In contrast, [`crate::pool::WriterGuard::transaction`]
510/// propagates callback panics and settles its owner during unwinding.
511pub(crate) fn execute_wrapped_transaction<R, F>(
512    conn: &Connection,
513    commit_operation: &'static str,
514    operation: F,
515) -> (Result<R, StorageError>, Option<WriterTaskRequestState>)
516where
517    F: FnOnce(&Connection) -> Result<R, StorageError>,
518{
519    let profiled = execute_wrapped_transaction_profiled(
520        conn,
521        commit_operation,
522        None,
523        false,
524        None,
525        operation,
526        #[cfg(test)]
527        None,
528    );
529    (profiled.result, profiled.terminal_state)
530}
531
532/// The standalone SQL bridge shares settlement rules while retaining its
533/// native commit error source and timeout/full observation site.
534pub(crate) fn execute_wrapped_sql_bridge_transaction<R, F>(
535    conn: &Connection,
536    commit_operation: &'static str,
537    db: &str,
538    operation: F,
539) -> (Result<R, StorageError>, Option<WriterTaskRequestState>)
540where
541    F: FnOnce(&Connection) -> Result<R, StorageError>,
542{
543    let profiled = execute_wrapped_transaction_profiled(
544        conn,
545        commit_operation,
546        Some(db),
547        true,
548        None,
549        operation,
550        #[cfg(test)]
551        None,
552    );
553    (profiled.result, profiled.terminal_state)
554}
555
556struct ProfiledWrappedTransaction<R> {
557    result: Result<R, StorageError>,
558    terminal_state: Option<WriterTaskRequestState>,
559    body: Duration,
560    commit: Duration,
561}
562
563fn execute_wrapped_transaction_profiled<R, F>(
564    conn: &Connection,
565    commit_operation: &'static str,
566    db: Option<&str>,
567    direct_sql_bridge: bool,
568    commit_issued: Option<&AtomicBool>,
569    operation: F,
570    #[cfg(test)] test_clock: Option<&dyn TestWriterStageClock>,
571) -> ProfiledWrappedTransaction<R>
572where
573    F: FnOnce(&Connection) -> Result<R, StorageError>,
574{
575    let body_started = Instant::now();
576    #[cfg(test)]
577    let body_started = test_clock.map_or(body_started, TestWriterStageClock::now);
578    // Keep panic-to-terminal conversion local to this adapter; the public
579    // WriterGuard transaction intentionally propagates the callback's unwind.
580    let operation_outcome = catch_unwind(AssertUnwindSafe(|| {
581        operation(conn).map_err(crate::error::statement_failure)
582    }));
583    #[cfg(not(test))]
584    let body = body_started.elapsed();
585    #[cfg(test)]
586    let body = test_clock.map_or_else(
587        || body_started.elapsed(),
588        |clock| clock.now().duration_since(body_started),
589    );
590
591    match operation_outcome {
592        Ok(Ok(value)) => {
593            let commit_started = Instant::now();
594            #[cfg(test)]
595            let commit_started = test_clock.map_or(commit_started, TestWriterStageClock::now);
596            #[cfg(test)]
597            if let Some(clock) = test_clock {
598                clock.at_commit();
599            }
600            if let Some(issued) = commit_issued {
601                issued.store(true, Ordering::Release);
602            }
603            #[cfg(any(test, feature = "test-support"))]
604            crate::test_hooks::commit_reply_issued(conn);
605            let commit_outcome = conn.execute_batch("COMMIT");
606            #[cfg(any(test, feature = "test-support"))]
607            crate::test_hooks::commit_reply_completed(
608                conn,
609                commit_outcome.is_ok(),
610                conn.is_autocommit(),
611            );
612            #[cfg(not(test))]
613            let commit = commit_started.elapsed();
614            #[cfg(test)]
615            let commit = test_clock.map_or_else(
616                || commit_started.elapsed(),
617                |clock| clock.now().duration_since(commit_started),
618            );
619            match commit_outcome {
620                Ok(()) if conn.is_autocommit() => ProfiledWrappedTransaction {
621                    result: Ok(value),
622                    terminal_state: None,
623                    body,
624                    commit,
625                },
626                Ok(()) => {
627                    tracing::error!(
628                    "writer transaction: COMMIT returned success but the connection is still in \
629                     a transaction; request side effects are unknown"
630                );
631                    let request_state = WriterTaskRequestState::SideEffectsUnknown;
632                    ProfiledWrappedTransaction {
633                        result: Err(writer_task_terminated(request_state)),
634                        terminal_state: Some(request_state),
635                        body,
636                        commit,
637                    }
638                }
639                Err(commit_error) => {
640                    if let Some(db) = db {
641                        if direct_sql_bridge {
642                            crate::timeout_sink::maybe_emit_busy(
643                                db,
644                                crate::timeout_sink::Site::StandaloneSqlBridge,
645                                &commit_error,
646                            );
647                        } else {
648                            crate::timeout_sink::maybe_emit_sqlite_full(db, &commit_error);
649                        }
650                    }
651                    match rollback_after_failure(conn, "commit failure") {
652                        RollbackDisposition::RolledBack => ProfiledWrappedTransaction {
653                            result: Err(StorageError::WriterTaskRequestFailed {
654                                request_state: WriterTaskRequestState::TransactionRolledBack,
655                                source: Box::new({
656                                    let failure = crate::error::native_write_failure(
657                                        &commit_error,
658                                        khive_storage::error::SqliteWriteStage::Commit,
659                                    );
660                                    let error = if direct_sql_bridge {
661                                        StorageError::driver(
662                                            khive_storage::StorageCapability::Sql,
663                                            commit_operation,
664                                            commit_error,
665                                        )
666                                    } else {
667                                        StorageError::Pool {
668                                            operation: commit_operation.into(),
669                                            message: commit_error.to_string(),
670                                        }
671                                    };
672                                    match failure {
673                                        Some(failure) => error.with_sqlite_write_failure(failure),
674                                        None => error,
675                                    }
676                                }),
677                            }),
678                            terminal_state: None,
679                            body,
680                            commit,
681                        },
682                        RollbackDisposition::SideEffectsUnknown => {
683                            let request_state = WriterTaskRequestState::SideEffectsUnknown;
684                            ProfiledWrappedTransaction {
685                                result: Err(writer_task_terminated_with_cause(
686                                    request_state,
687                                    &commit_error,
688                                    khive_storage::error::SqliteWriteStage::Commit,
689                                )),
690                                terminal_state: Some(request_state),
691                                body,
692                                commit,
693                            }
694                        }
695                    }
696                }
697            }
698        }
699        Ok(Err(operation_error)) => {
700            match rollback_after_failure(conn, "request operation failure") {
701                RollbackDisposition::RolledBack => ProfiledWrappedTransaction {
702                    result: Err(StorageError::WriterTaskRequestFailed {
703                        request_state: WriterTaskRequestState::TransactionRolledBack,
704                        source: Box::new(operation_error),
705                    }),
706                    terminal_state: None,
707                    body,
708                    commit: Duration::ZERO,
709                },
710                RollbackDisposition::SideEffectsUnknown => {
711                    // SQLite may have already rolled back a failed transaction,
712                    // leaving no transaction for the explicit ROLLBACK.
713                    // Escalate the original cause once; retain native FULL evidence below.
714                    if let Some(db) = db {
715                        crate::timeout_sink::maybe_emit_sqlite_full(db, &operation_error);
716                    }
717                    let request_state = WriterTaskRequestState::SideEffectsUnknown;
718                    ProfiledWrappedTransaction {
719                        result: Err(writer_task_terminated_with_cause(
720                            request_state,
721                            &operation_error,
722                            khive_storage::error::SqliteWriteStage::Statement,
723                        )),
724                        terminal_state: Some(request_state),
725                        body,
726                        commit: Duration::ZERO,
727                    }
728                }
729            }
730        }
731        Err(_panic_payload) => {
732            let request_state = match rollback_after_failure(conn, "request panic") {
733                RollbackDisposition::RolledBack => WriterTaskRequestState::TransactionRolledBack,
734                RollbackDisposition::SideEffectsUnknown => {
735                    WriterTaskRequestState::SideEffectsUnknown
736                }
737            };
738            ProfiledWrappedTransaction {
739                result: Err(writer_task_terminated(request_state)),
740                terminal_state: Some(request_state),
741                body,
742                commit: Duration::ZERO,
743            }
744        }
745    }
746}
747
748fn reply_with_admission<R>(
749    reply: oneshot::Sender<Result<R, StorageError>>,
750    mut admission: Option<AdmissionObservation>,
751    receipt: &ReplyReceipt<R>,
752    suppress: bool,
753) {
754    if let Some(observation) = admission.as_mut() {
755        observation.reply_attempt();
756    }
757    if suppress {
758        drop(reply);
759        return;
760    }
761    let result = receipt.completed().take().expect("completed writer result");
762    let _ = reply.send(result);
763}
764
765impl<R: Send + 'static> sealed::Sealed for WriteRequest<R> {
766    fn start_execution(&mut self) {
767        if let Some(observation) = self.admission.as_mut() {
768            observation.start_execution();
769        }
770    }
771
772    fn execute_and_reply_reporting_terminal(
773        self: Box<Self>,
774        conn: &Connection,
775        tx_span: Option<khive_storage::tx_registry::TxHandle>,
776        queue_wait: Duration,
777        transaction_acquire: Duration,
778    ) -> Option<WriterTaskRequestState> {
779        // Keep the typed reply sender outside the unwind boundary. Calling
780        // `(self.op)(conn)` directly would drop `self.reply` while unwinding,
781        // leaving the active caller with only an untyped RecvError.
782        let WriteRequest {
783            op,
784            reply,
785            receipt,
786            telemetry,
787            admission,
788            ..
789        } = *self;
790        #[cfg(any(test, feature = "test-support"))]
791        let reply_probe = crate::test_hooks::begin_commit_reply_request(conn);
792        let changes_before = conn.total_changes();
793        let profiled = execute_wrapped_transaction_profiled(
794            conn,
795            "writer_task_commit",
796            Some(&telemetry.db),
797            false,
798            Some(&receipt.commit_issued),
799            op,
800            #[cfg(test)]
801            telemetry.test_clock.as_deref(),
802        );
803        let rows_changed = conn.total_changes().saturating_sub(changes_before);
804        let succeeded = profiled.result.is_ok();
805        *receipt.completed() = Some(profiled.result);
806        if let Some(Err(error)) = receipt.completed().as_ref() {
807            crate::timeout_sink::maybe_emit_sqlite_full(&telemetry.db, error);
808        }
809        // The reply wake can make the caller immediately observe the
810        // committed/error result. Deregister the transaction span first so
811        // tx_registry continues to mean "currently open SQL transaction",
812        // never "a transaction whose caller has already resumed" (#1790).
813        drop(tx_span);
814        telemetry.finish(
815            queue_wait,
816            transaction_acquire,
817            profiled.body,
818            profiled.commit,
819            succeeded,
820            rows_changed,
821        );
822        // The receiver may already be gone (caller dropped its future) —
823        // that is not this task's problem to report.
824        #[cfg(not(any(test, feature = "test-support")))]
825        let suppress = false;
826        #[cfg(any(test, feature = "test-support"))]
827        let suppress = reply_probe
828            .as_ref()
829            .is_some_and(|probe| probe.suppress_successful_reply());
830        reply_with_admission(reply, admission, &receipt, suppress);
831        profiled.terminal_state
832    }
833
834    fn execute_and_reply_top_level_reporting_terminal(
835        self: Box<Self>,
836        conn: &Connection,
837        queue_wait: Duration,
838    ) -> Option<WriterTaskRequestState> {
839        let WriteRequest {
840            op,
841            reply,
842            receipt,
843            telemetry,
844            admission,
845            ..
846        } = *self;
847        let changes_before = conn.total_changes();
848        let body_started = Instant::now();
849        let outcome = catch_unwind(AssertUnwindSafe(|| {
850            op(conn).map_err(crate::error::statement_failure)
851        }));
852        let body = body_started.elapsed();
853        let rows_changed = conn.total_changes().saturating_sub(changes_before);
854        let (result, terminal_state, open_transaction) = match outcome {
855            Ok(outcome) if conn.is_autocommit() => (outcome, None, false),
856            Ok(outcome) => {
857                let request_state = WriterTaskRequestState::SideEffectsUnknown;
858                let error = match outcome {
859                    Err(error) => writer_task_terminated_with_cause(
860                        request_state,
861                        &error,
862                        khive_storage::error::SqliteWriteStage::Statement,
863                    ),
864                    Ok(_) => writer_task_terminated(request_state),
865                };
866                (Err(error), Some(request_state), true)
867            }
868            Err(_panic_payload) => {
869                let state = WriterTaskRequestState::SideEffectsUnknown;
870                (Err(writer_task_terminated(state)), Some(state), false)
871            }
872        };
873        let succeeded = result.is_ok();
874        *receipt.completed() = Some(result);
875        let telemetry_db = telemetry.db.clone();
876        telemetry.finish(
877            queue_wait,
878            Duration::ZERO,
879            body,
880            Duration::ZERO,
881            succeeded,
882            rows_changed,
883        );
884        if open_transaction {
885            tracing::error!(
886                "writer task: top-level request returned with an open transaction; request \
887                 side effects are unknown"
888            );
889        } else if terminal_state.is_none() {
890            if let Some(Err(error)) = receipt.completed().as_ref() {
891                crate::timeout_sink::maybe_emit_sqlite_full(&telemetry_db, error);
892            }
893        }
894        reply_with_admission(reply, admission, &receipt, false);
895        terminal_state
896    }
897
898    fn reply_error_after_begin(
899        self: Box<Self>,
900        err: StorageError,
901        queue_wait: Duration,
902        transaction_acquire: Duration,
903    ) {
904        let WriteRequest {
905            reply,
906            receipt,
907            telemetry,
908            admission,
909            ..
910        } = *self;
911        *receipt.completed() = Some(Err(err));
912        telemetry.finish(
913            queue_wait,
914            transaction_acquire,
915            Duration::ZERO,
916            Duration::ZERO,
917            false,
918            0,
919        );
920        reply_with_admission(reply, admission, &receipt, false);
921    }
922}
923
924impl<R: Send + 'static> AnyWriteRequest for WriteRequest<R> {
925    fn execute_and_reply(mut self: Box<Self>, conn: &Connection) {
926        let queue_wait = self.queue_wait();
927        sealed::Sealed::start_execution(self.as_mut());
928        let _ = sealed::Sealed::execute_and_reply_reporting_terminal(
929            self,
930            conn,
931            None,
932            queue_wait,
933            Duration::ZERO,
934        );
935    }
936
937    fn execute_and_reply_top_level(mut self: Box<Self>, conn: &Connection) {
938        let queue_wait = self.queue_wait();
939        sealed::Sealed::start_execution(self.as_mut());
940        let _ =
941            sealed::Sealed::execute_and_reply_top_level_reporting_terminal(self, conn, queue_wait);
942    }
943
944    fn reply_error(self: Box<Self>, err: StorageError) {
945        let queue_wait = self.queue_wait();
946        sealed::Sealed::reply_error_after_begin(self, err, queue_wait, Duration::ZERO);
947    }
948
949    fn is_top_level(&self) -> bool {
950        self.top_level
951    }
952
953    fn is_checkpoint_bypass(&self) -> bool {
954        self.checkpoint_bypass
955    }
956
957    fn needs_vacuum_headroom(&self) -> bool {
958        self.vacuum_copy_headroom
959    }
960
961    fn lease_class(&self) -> crate::disk_guard::WriteClassContext {
962        self.lease_class
963    }
964
965    fn queue_wait(&self) -> Duration {
966        self.telemetry.queue_wait()
967    }
968}
969
970fn writer_task_terminated(request_state: WriterTaskRequestState) -> StorageError {
971    StorageError::writer_task_terminated(request_state)
972}
973
974fn writer_task_terminated_with_cause(
975    request_state: WriterTaskRequestState,
976    error: &(dyn std::error::Error + 'static),
977    stage: khive_storage::error::SqliteWriteStage,
978) -> StorageError {
979    let mut source = Some(error);
980    let mut sqlite_full_codes = None;
981    while let Some(current) = source {
982        if let Some(rusqlite::Error::SqliteFailure(code, _)) =
983            current.downcast_ref::<rusqlite::Error>()
984        {
985            if code.code == rusqlite::ErrorCode::DiskFull {
986                sqlite_full_codes = Some((code.extended_code & 0xff, code.extended_code));
987                break;
988            }
989        }
990        source = current.source();
991    }
992    // The original error was already escalated at the failing boundary.
993    // A source-free pair preserves caller evidence without duplicating that sink event.
994    let terminal = StorageError::WriterTaskTerminated {
995        request_state,
996        sqlite_full_codes,
997    };
998    match crate::error::native_write_failure(error, stage) {
999        Some(mut failure) => {
1000            failure.settlement_unknown =
1001                request_state == WriterTaskRequestState::SideEffectsUnknown;
1002            terminal.with_sqlite_write_failure(failure)
1003        }
1004        None => terminal,
1005    }
1006}
1007
1008fn writer_task_begin_error(error: rusqlite::Error, busy_timeout: Duration) -> StorageError {
1009    let failure =
1010        crate::error::native_write_failure(&error, khive_storage::error::SqliteWriteStage::Begin);
1011    let mapped = if crate::timeout_sink::is_busy_or_locked(&error) {
1012        StorageError::WriterTaskBusy {
1013            timeout_ms: u64::try_from(busy_timeout.as_millis()).unwrap_or(u64::MAX),
1014        }
1015    } else {
1016        StorageError::Pool {
1017            operation: "writer_task_begin".into(),
1018            message: error.to_string(),
1019        }
1020    };
1021    match failure {
1022        Some(failure) => mapped.with_sqlite_write_failure(failure),
1023        None => mapped,
1024    }
1025}
1026
1027/// Sender half of the write queue. Cheaply cloneable (wraps an
1028/// `mpsc::Sender`) — every migrated store that shares one writer task holds
1029/// a clone of this handle.
1030#[derive(Clone, Debug)]
1031pub struct WriterTaskHandle {
1032    tx: mpsc::Sender<Box<dyn AnyWriteRequest + Send>>,
1033    /// Exact canonical backend identity used by the in-memory stage registry.
1034    /// Kept separate from `db`, whose lossy display form is logging-only.
1035    backend_key: Option<PathBuf>,
1036    /// This handle's pool's writer-timeout sink identity (`timeout_sink::db_label`),
1037    /// captured at spawn so `send_with_timeout`'s `WriteQueueFull` path can
1038    /// report a `queue_saturation` sink row (ADR-136 D1 gate 6a) without
1039    /// needing a `&ConnectionPool` reference.
1040    db: String,
1041    /// Slow-write latency bound (`timeout_sink::slow_write_threshold`),
1042    /// resolved once at spawn. `None` disables slow-write rows. Captured
1043    /// here rather than read per send so the caller path pays no env lookup
1044    /// and tests get a deterministic value by setting the override before
1045    /// spawning their own writer task.
1046    slow_write_threshold: Option<std::time::Duration>,
1047    /// Per-attempt mode (`timeout_sink::writer_attempt_log_enabled`),
1048    /// resolved once at spawn like the slow-write bound.
1049    attempt_log: bool,
1050    /// Default enqueue-capacity deadline for [`Self::send_bounded`] /
1051    /// [`Self::send_top_level_bounded`], captured from
1052    /// `PoolConfig::write_admission_deadline_ms` at [`spawn`] (ADR-131
1053    /// Decision 2). Bounds ONLY the wait for channel capacity, the same
1054    /// boundary `send_with_timeout` already documents — never the reply wait
1055    /// after acceptance (#1382).
1056    ///
1057    /// This is a dedicated admission authority, distinct from
1058    /// `PoolConfig::checkout_timeout` (reader/pool checkout). The two used
1059    /// to be conflated here before ADR-131 Decision 2 (#1382, #1643).
1060    ///
1061    /// ADR-131 Decision 2's outer-request-budget clamp ("when the caller's outer
1062    /// request deadline leaves less time remaining than the configured
1063    /// admission deadline, the admission deadline applied to that operation
1064    /// is the remaining outer budget instead") is explicitly DEFERRED: no
1065    /// outer request deadline is plumbed to `send_bounded` /
1066    /// `send_top_level_bounded`'s call sites as of #1737, so there is no
1067    /// budget to clamp against. When an outer deadline reaches this call
1068    /// path, clamp here rather than faking a shorter deadline against a
1069    /// nonexistent budget.
1070    enqueue_timeout: std::time::Duration,
1071    admission_metrics: Arc<WriterAdmissionMetrics>,
1072    strict_routing: bool,
1073}
1074
1075impl WriterTaskHandle {
1076    pub(crate) fn is_closed(&self) -> bool {
1077        self.tx.is_closed()
1078    }
1079
1080    fn unavailable_before_acceptance(&self) -> StorageError {
1081        if self.strict_routing {
1082            StorageError::WriterOwnerUnavailable {
1083                operation: "writer_task_enqueue".into(),
1084                source: Box::new(StorageError::Pool {
1085                    operation: "writer_task_enqueue".into(),
1086                    message: "writer owner is stopped".into(),
1087                }),
1088            }
1089        } else {
1090            writer_task_terminated(WriterTaskRequestState::NotStarted)
1091        }
1092    }
1093
1094    /// Enqueue a write operation and return the oneshot receiver its reply
1095    /// will arrive on, once the request has actually been accepted onto the
1096    /// channel.
1097    ///
1098    /// Shared by [`Self::send`] and [`Self::send_with_timeout`] so that a
1099    /// caller-supplied deadline (see `send_with_timeout`) can bound ONLY
1100    /// this enqueue step — never the reply-wait that follows it. Once this
1101    /// returns `Ok`, the request has been accepted by the writer task and
1102    /// will either run to completion or receive a typed terminal error if an
1103    /// earlier request kills the task before this operation begins. The
1104    /// returned receiver must be awaited without a timeout; abandoning it
1105    /// here would silently drop the request's eventual result, not cancel the
1106    /// request itself.
1107    async fn enqueue<R, F>(&self, op: F) -> Result<PendingWrite<R>, StorageError>
1108    where
1109        R: Send + 'static,
1110        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1111    {
1112        self.enqueue_inner(op, false, false, false, SubmitLabels::None)
1113            .await
1114    }
1115
1116    /// Shared enqueue path for both transaction-wrapped ([`Self::enqueue`])
1117    /// and top-level ([`Self::send_top_level`]) requests — `top_level`
1118    /// controls which [`AnyWriteRequest`] method the drain loop invokes.
1119    /// `labels` is what the submit site knows about this request's
1120    /// statements; see [`SubmitLabels`].
1121    async fn enqueue_inner<R, F>(
1122        &self,
1123        op: F,
1124        top_level: bool,
1125        checkpoint_bypass: bool,
1126        vacuum_copy_headroom: bool,
1127        labels: SubmitLabels,
1128    ) -> Result<PendingWrite<R>, StorageError>
1129    where
1130        R: Send + 'static,
1131        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1132    {
1133        let (reply_tx, reply_rx) = oneshot::channel();
1134        let receipt = Arc::new(ReplyReceipt::default());
1135        // Normalize here (once per request) so every submit path — including
1136        // the public `send_labelled` entry points a caller can hand a raw
1137        // list — records distinct labels in first-seen order. Bounding stays
1138        // in `resolve_labels`, which runs only on the slow path.
1139        let labels = match labels {
1140            SubmitLabels::Statements(labels) => {
1141                SubmitLabels::Statements(dedup_labels(labels.iter().map(String::as_str)))
1142            }
1143            other => other,
1144        };
1145        let telemetry = WriteTelemetry::new(
1146            self.backend_key.clone(),
1147            self.db.clone(),
1148            self.queue_depth(),
1149            self.slow_write_threshold,
1150            labels,
1151            WriteTelemetryOptions {
1152                attempt_log: self.attempt_log,
1153                top_level,
1154            },
1155        );
1156        let mut request = Box::new(WriteRequest {
1157            op: Box::new(op),
1158            reply: reply_tx,
1159            receipt: Arc::clone(&receipt),
1160            top_level,
1161            checkpoint_bypass,
1162            vacuum_copy_headroom,
1163            lease_class: crate::disk_guard::WriteClassContext::capture(),
1164            telemetry,
1165            admission: None,
1166        });
1167        request.admission = Some(self.admission_metrics.offer());
1168        let permit = self
1169            .tx
1170            .reserve()
1171            .await
1172            .map_err(|_| self.unavailable_before_acceptance())?;
1173        if let Some(observation) = request.admission.as_mut() {
1174            observation.accepted();
1175        }
1176        permit.send(request);
1177
1178        Ok(PendingWrite { reply_rx, receipt })
1179    }
1180
1181    /// Send a write operation to the writer task and await its typed reply.
1182    ///
1183    /// Backpressure: this suspends on the channel's `send().await` when the
1184    /// bounded queue is full (ADR-067 "Channel capacity and queue-full
1185    /// policy") — there is no `try_send` escape hatch. Callers that need a
1186    /// deadline on that wait should use [`Self::send_with_timeout`] instead.
1187    pub async fn send<R, F>(&self, op: F) -> Result<R, StorageError>
1188    where
1189        R: Send + 'static,
1190        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1191    {
1192        let reply_rx = self.enqueue(op).await?;
1193        reply_rx.wait().await
1194    }
1195
1196    /// Like [`Self::send`], but bounds the wait for the bounded channel to
1197    /// free capacity with `timeout`.
1198    ///
1199    /// The timeout applies ONLY to enqueueing the request (the channel
1200    /// `send().await` that can suspend on a full queue) — never to waiting
1201    /// for the writer task's reply once the request has been accepted.
1202    /// `StorageError::WriteQueueFull` means exactly "the bounded channel was
1203    /// full and this request was never accepted"; it must never be returned
1204    /// for a request that was accepted and is still executing (or already
1205    /// committed) by the time `timeout` elapses — that would misreport a
1206    /// slow op or a lock wait as a queue-capacity failure, and could tell a
1207    /// caller a write failed when it actually landed. ADR-067's queue-full
1208    /// policy has no immediate-error `try_send` path — only this caller-side
1209    /// deadline on the enqueue step.
1210    pub async fn send_with_timeout<R, F>(
1211        &self,
1212        op: F,
1213        timeout: std::time::Duration,
1214    ) -> Result<R, StorageError>
1215    where
1216        R: Send + 'static,
1217        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1218    {
1219        self.send_with_timeout_labelled(op, timeout, SubmitLabels::None)
1220            .await
1221    }
1222
1223    /// Shared body of [`Self::send_with_timeout`] and its labelled variants.
1224    /// `labels` is carried onto the request's writer-stage observation and
1225    /// `slow_write` row; see [`SubmitLabels`].
1226    async fn send_with_timeout_labelled<R, F>(
1227        &self,
1228        op: F,
1229        timeout: std::time::Duration,
1230        labels: SubmitLabels,
1231    ) -> Result<R, StorageError>
1232    where
1233        R: Send + 'static,
1234        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1235    {
1236        let reply_rx = match tokio::time::timeout(
1237            timeout,
1238            self.enqueue_inner(op, false, false, false, labels),
1239        )
1240        .await
1241        {
1242            Ok(Ok(reply_rx)) => reply_rx,
1243            Ok(Err(e)) => return Err(e),
1244            Err(_elapsed) => {
1245                let timeout_ms = timeout.as_millis() as u64;
1246                self.admission_metrics.record_capacity_deadline();
1247                crate::timeout_sink::emit_queue_saturation(&self.db, timeout_ms);
1248                return Err(StorageError::WriteQueueFull { timeout_ms });
1249            }
1250        };
1251
1252        reply_rx.wait().await
1253    }
1254
1255    /// Like [`Self::send`], but bounds the enqueue-capacity wait with this
1256    /// handle's configured `enqueue_timeout`
1257    /// (`PoolConfig::write_admission_deadline_ms` at spawn time, ADR-131
1258    /// Decision 2) instead of waiting indefinitely (#1382).
1259    ///
1260    /// Once the request is accepted onto the channel, the reply wait is
1261    /// unbounded by this method, identical to [`Self::send`] — this bounds
1262    /// only queue-capacity admission, never SQLite execution or reply
1263    /// latency. Callers that need a non-default deadline should use
1264    /// [`Self::send_with_timeout`] directly.
1265    pub async fn send_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
1266    where
1267        R: Send + 'static,
1268        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1269    {
1270        self.send_with_timeout(op, self.enqueue_timeout).await
1271    }
1272
1273    /// Send a write operation that MUST run outside any open transaction
1274    /// (e.g. `VACUUM`, which SQLite forbids inside `BEGIN`/`COMMIT`) and
1275    /// await its typed reply.
1276    ///
1277    /// Still serialized through the same single writer owner as
1278    /// [`Self::send`] — the request goes through the identical bounded
1279    /// channel and drain loop, one request at a time — but the drain loop
1280    /// skips the per-request `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` wrap
1281    /// entirely for this request (ADR-067 Component A). The single-writer
1282    /// guarantee is preserved; only
1283    /// the transaction wrap is skipped.
1284    pub async fn send_top_level<R, F>(&self, op: F) -> Result<R, StorageError>
1285    where
1286        R: Send + 'static,
1287        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1288    {
1289        let reply_rx = self
1290            .enqueue_inner(op, true, false, false, SubmitLabels::None)
1291            .await?;
1292        reply_rx.wait().await
1293    }
1294
1295    /// Like [`Self::send_top_level`], but bounds the enqueue-capacity wait
1296    /// with this handle's configured `enqueue_timeout`, mirroring
1297    /// [`Self::send_bounded`] for top-level (transaction-skipping) requests
1298    /// (#1382).
1299    pub async fn send_top_level_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
1300    where
1301        R: Send + 'static,
1302        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1303    {
1304        self.send_top_level_bounded_inner(op, false, false, SubmitLabels::None)
1305            .await
1306    }
1307
1308    /// Checkpoint-only top-level dispatch. It remains serialized by the
1309    /// writer task but never waits for the capacity lease or floor probe.
1310    pub(crate) async fn send_checkpoint_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
1311    where
1312        R: Send + 'static,
1313        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1314    {
1315        self.send_top_level_bounded_inner(op, true, false, SubmitLabels::Site("wal_checkpoint"))
1316            .await
1317    }
1318
1319    /// Typed VACUUM dispatch with a copy-sized metadata estimate at dequeue.
1320    pub(crate) async fn send_vacuum_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
1321    where
1322        R: Send + 'static,
1323        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1324    {
1325        self.send_top_level_bounded_inner(op, false, true, SubmitLabels::Site("vacuum"))
1326            .await
1327    }
1328
1329    async fn send_top_level_bounded_inner<R, F>(
1330        &self,
1331        op: F,
1332        checkpoint_bypass: bool,
1333        vacuum_copy_headroom: bool,
1334        labels: SubmitLabels,
1335    ) -> Result<R, StorageError>
1336    where
1337        R: Send + 'static,
1338        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
1339    {
1340        let reply_rx = match tokio::time::timeout(
1341            self.enqueue_timeout,
1342            self.enqueue_inner(op, true, checkpoint_bypass, vacuum_copy_headroom, labels),
1343        )
1344        .await
1345        {
1346            Ok(Ok(reply_rx)) => reply_rx,
1347            Ok(Err(e)) => return Err(e),
1348            Err(_elapsed) => {
1349                let timeout_ms = self.enqueue_timeout.as_millis() as u64;
1350                self.admission_metrics.record_capacity_deadline();
1351                crate::timeout_sink::emit_queue_saturation(&self.db, timeout_ms);
1352                return Err(StorageError::WriteQueueFull { timeout_ms });
1353            }
1354        };
1355
1356        reply_rx.wait().await
1357    }
1358
1359    /// Current write-queue backlog depth: requests enqueued but not yet
1360    /// accepted by the writer task's drain loop.
1361    ///
1362    /// Reads `mpsc::Sender::max_capacity() - capacity()`, so it is a
1363    /// point-in-time snapshot racy under concurrent senders/the drain loop
1364    /// draining concurrently — acceptable for a monitoring gauge (the
1365    /// load/perf harness metrics read-surface), never used for any correctness
1366    /// decision.
1367    pub fn queue_depth(&self) -> usize {
1368        self.tx.max_capacity() - self.tx.capacity()
1369    }
1370
1371    /// The bounded channel's configured capacity
1372    /// (`PoolConfig::write_queue_capacity`).
1373    pub fn capacity(&self) -> usize {
1374        self.tx.max_capacity()
1375    }
1376
1377    pub(crate) fn admission_snapshot(&self) -> Result<Snapshot, Unavailable> {
1378        self.admission_metrics.snapshot()
1379    }
1380}
1381
1382/// Spawn the write-owner task (ADR-067 Component A) on the current Tokio
1383/// runtime.
1384///
1385/// Opens a dedicated standalone writer connection independent of the pool's
1386/// Mutex-guarded `writer()` connection used by unmigrated paths. That one-time
1387/// infrastructure open is uncounted; every dequeued top-level request or
1388/// successful `BEGIN IMMEDIATE` increments the writer-task acquisition class.
1389/// Returns the cloneable [`WriterTaskHandle`] sender half. The task normally
1390/// runs until every handle clone is dropped and the channel closes; a request
1391/// panic, failed rollback, or poisoned connection puts it into the permanent
1392/// terminal state documented below.
1393///
1394/// # Terminal settlement
1395/// Retiring an unsettled writer, including when its blocking owner unwinds,
1396/// releases the volume lease only after cleanup restored autocommit or the
1397/// connection closed. If neither is possible, path, volume, and errors are
1398/// reported to stderr and tracing and the pool is poisoned: that request
1399/// reports [`SqliteError::WriterSettlementUnknown`] and every later write is
1400/// refused with [`SqliteError::WriterPoisoned`] before it starts.
1401///
1402/// `capacity` bounds the channel (`PoolConfig::write_queue_capacity` /
1403/// `KHIVE_WRITE_QUEUE_CAPACITY`, ADR-067 recommends 256).
1404///
1405/// # Errors
1406/// Must be called from within a Tokio runtime context (calls
1407/// `tokio::spawn`). Returns an error if the pool cannot open a standalone
1408/// writer connection (e.g. an in-memory pool has no standalone-connection
1409/// support). See `crates/khive-db/docs/api/writer-task.md` for the
1410/// migration-slice scope this commits per `BEGIN IMMEDIATE`.
1411pub fn spawn(pool: &ConnectionPool, capacity: usize) -> Result<WriterTaskHandle, SqliteError> {
1412    pool.spawn_writer_task(capacity)
1413}
1414
1415/// Consume a verified lifetime connection inside its admission-owning task.
1416/// Only the pool's private connection factory opens that connection.
1417pub(crate) fn spawn_with_connection(
1418    pool: &ConnectionPool,
1419    conn: Connection,
1420    capacity: usize,
1421) -> Result<WriterTaskHandle, SqliteError> {
1422    // The lifetime connection is infrastructure, not one acquisition per
1423    // write. Each dequeued request is counted below at the task's actual
1424    // ownership boundary instead.
1425    let acquisition_counters = pool.writer_acquisition_counters();
1426    let write_admission = pool.write_admission();
1427    let busy_timeout = pool.config().busy_timeout;
1428    let origin = pool.origin();
1429    let backend_key = writer_db_key(pool);
1430    let db = crate::timeout_sink::db_label(pool);
1431    let (tx, rx) = mpsc::channel(capacity.max(1));
1432    let join = tokio::spawn(run_writer_task(
1433        (conn, pool.timeout_sink_writer_lease()),
1434        rx,
1435        origin,
1436        db.clone(),
1437        acquisition_counters,
1438        write_admission,
1439        busy_timeout,
1440    ));
1441    // Stored on the pool (not returned) so the handle's clone-and-share
1442    // contract stays untouched; see ConnectionPool::take_writer_task_join
1443    // for who awaits it and why.
1444    pool.set_writer_task_join(join);
1445    Ok(WriterTaskHandle {
1446        tx,
1447        backend_key,
1448        db,
1449        slow_write_threshold: crate::timeout_sink::slow_write_threshold(),
1450        attempt_log: crate::timeout_sink::writer_attempt_log_enabled(),
1451        enqueue_timeout: std::time::Duration::from_millis(
1452            pool.config().write_admission_deadline_ms,
1453        ),
1454        admission_metrics: WriterAdmissionMetrics::new(),
1455        strict_routing: pool.config().write_routing_strict,
1456    })
1457}
1458
1459/// Permanently close admission, then reply to every request that was already
1460/// accepted into the bounded channel without invoking its operation closure.
1461///
1462/// Closing before draining is load-bearing: draining an open receiver would
1463/// wait forever while [`WriterTaskHandle`] clones still exist, while dropping
1464/// the receiver immediately would discard buffered requests and their typed
1465/// reply senders.
1466async fn close_and_fail_queued_requests(rx: &mut mpsc::Receiver<Box<dyn AnyWriteRequest + Send>>) {
1467    rx.close();
1468    while let Some(request) = rx.recv().await {
1469        request.reply_error(writer_task_terminated(WriterTaskRequestState::NotStarted));
1470    }
1471}
1472
1473/// Acquire the request transaction without multiplying its busy-timeout budget.
1474/// The setter is supplied so tests can fail SQLite's timeout update while still
1475/// executing real BEGIN statements; production uses `Connection::busy_timeout`.
1476fn begin_immediate_with_retry(
1477    conn: &Connection,
1478    acquisition_counters: &WriterAcquisitionCounters,
1479    busy_timeout: Duration,
1480    mut set_busy_timeout: impl FnMut(&Connection, Duration) -> rusqlite::Result<()>,
1481) -> (rusqlite::Result<()>, Duration, u32) {
1482    let transaction_acquire_started = Instant::now();
1483    let mut begin_attempt = 1_u32;
1484    let mut retry_delays = WRITER_BEGIN_RETRY_DELAYS.into_iter();
1485    let mut busy_timeout_lowered = false;
1486    let begin_outcome = loop {
1487        match conn.execute_batch("BEGIN IMMEDIATE") {
1488            Ok(()) => break Ok(()),
1489            Err(error) if crate::timeout_sink::is_busy_or_locked(&error) => {
1490                // Every busy/locked refusal is counted here,
1491                // whether or not it goes on to be retried: this
1492                // is the pre-PR meaning of the counter, and the
1493                // outer match below no longer counts the final
1494                // refusal a second time.
1495                acquisition_counters.record_writer_task_begin_busy();
1496                let Some(delay) = retry_delays.next() else {
1497                    break Err(error);
1498                };
1499                // The whole retry sequence shares one
1500                // `busy_timeout` budget: each SQLite attempt is
1501                // itself bounded by `busy_timeout`, so without a
1502                // shrinking budget three attempts could each
1503                // wait out a full window and multiply the
1504                // serialized writer's contention window instead
1505                // of bounding it.
1506                let remaining_budget =
1507                    busy_timeout.saturating_sub(transaction_acquire_started.elapsed());
1508                if remaining_budget.is_zero() {
1509                    break Err(error);
1510                }
1511                if let Err(set_err) = set_busy_timeout(conn, remaining_budget) {
1512                    tracing::warn!(
1513                        error = %set_err,
1514                        "writer task: failed to lower busy_timeout for BEGIN \
1515                         retry; surfacing the original busy refusal"
1516                    );
1517                    // A retry with the old timeout could exceed the shared budget.
1518                    break Err(error);
1519                }
1520                busy_timeout_lowered = true;
1521                // Count only refusals that will actually be retried. A failed
1522                // timeout reduction leaves this refusal visible to the caller.
1523                acquisition_counters.record_writer_task_begin_busy_absorbed();
1524                tracing::debug!(
1525                    attempt = begin_attempt,
1526                    backoff_ms = delay.as_millis() as u64,
1527                    budget_remaining_ms = remaining_budget.as_millis() as u64,
1528                    "writer task: BEGIN IMMEDIATE refused busy; retrying before \
1529                     request execution"
1530                );
1531                std::thread::sleep(delay);
1532                begin_attempt = begin_attempt.saturating_add(1);
1533            }
1534            Err(error) => break Err(error),
1535        }
1536    };
1537    let transaction_acquire = transaction_acquire_started.elapsed();
1538    // Restore the pool-configured busy_timeout only if a retry
1539    // actually lowered it, so the common uncontended request
1540    // never pays for an extra pragma write; the next request
1541    // dequeued on this same connection must still start from
1542    // the full configured budget.
1543    if busy_timeout_lowered {
1544        if let Err(restore_err) = set_busy_timeout(conn, busy_timeout) {
1545            tracing::warn!(
1546                error = %restore_err,
1547                "writer task: failed to restore busy_timeout after a BEGIN retry \
1548                 sequence"
1549            );
1550        }
1551    }
1552    (begin_outcome, transaction_acquire, begin_attempt)
1553}
1554
1555struct BlockingWriterConnection {
1556    conn: Option<Connection>,
1557    admission: Arc<crate::pool::WriteAdmission>,
1558    volume_lease: Option<crate::disk_guard::VolumeLease>,
1559}
1560
1561impl BlockingWriterConnection {
1562    fn new(conn: Connection, admission: Arc<crate::pool::WriteAdmission>) -> Self {
1563        Self {
1564            conn: Some(conn),
1565            admission,
1566            volume_lease: None,
1567        }
1568    }
1569
1570    fn finish(
1571        mut self,
1572        state: Option<WriterTaskRequestState>,
1573    ) -> (Option<Connection>, Option<WriterTaskRequestState>) {
1574        if state.is_some() {
1575            self.retire();
1576            (None, state)
1577        } else {
1578            (self.conn.take(), None)
1579        }
1580    }
1581
1582    fn retire(&mut self) {
1583        if let Some(conn) = self.conn.take() {
1584            // A terminal failure has poisoned the admission; the request that
1585            // retired this writer already carries its terminal state.
1586            let _ = self.admission.close_retired_connection(conn);
1587        }
1588    }
1589}
1590
1591impl Drop for BlockingWriterConnection {
1592    fn drop(&mut self) {
1593        self.retire();
1594    }
1595}
1596
1597impl std::ops::Deref for BlockingWriterConnection {
1598    type Target = Connection;
1599
1600    fn deref(&self) -> &Connection {
1601        self.conn
1602            .as_ref()
1603            .expect("blocking writer owns its connection until settlement")
1604    }
1605}
1606
1607/// Drain loop: the sole caller of `BEGIN IMMEDIATE` for write traffic routed
1608/// through the channel. Busy/locked `BEGIN IMMEDIATE` refusals receive the
1609/// bounded retry above before a final failure replies the request's error via
1610/// [`AnyWriteRequest::reply_error`] without invoking the request's closure.
1611///
1612/// A request-operation panic is contained inside the concrete
1613/// [`WriteRequest<R>`] so its typed reply survives. A panic, failed rollback,
1614/// or otherwise poisoned connection makes the task terminal. The task then
1615/// closes admission, explicitly fails every already-queued request as
1616/// [`WriterTaskRequestState::NotStarted`], and exits permanently. There is no
1617/// supervisor or connection restart; later sends observe the closed channel.
1618/// See
1619/// `crates/khive-db/docs/api/writer-task.md` for the full failure matrix.
1620async fn run_writer_task(
1621    mut owner: (Connection, Option<crate::timeout_sink::WriterLease>),
1622    mut rx: mpsc::Receiver<Box<dyn AnyWriteRequest + Send>>,
1623    origin: khive_storage::tx_registry::TxOrigin,
1624    db: String,
1625    acquisition_counters: Arc<WriterAcquisitionCounters>,
1626    write_admission: Arc<crate::pool::WriteAdmission>,
1627    busy_timeout: Duration,
1628) {
1629    #[cfg(any(test, feature = "test-support"))]
1630    if let Err(error) = crate::test_hooks::adopt(&mut owner.0) {
1631        tracing::error!(%error, "writer task: test hook registration failed");
1632    }
1633    while let Some(mut request) = rx.recv().await {
1634        // The bounded-channel wait ends at this exact dequeue boundary.
1635        // Sampling inside the blocking closure would misattribute a saturated
1636        // Tokio blocking pool to writer-queue contention (#1849).
1637        let queue_wait = request.queue_wait();
1638        sealed::Sealed::start_execution(request.as_mut());
1639        let origin = origin.clone();
1640        let blocking_counters = Arc::clone(&acquisition_counters);
1641        let blocking_admission = Arc::clone(&write_admission);
1642        let blocking_db = db.clone();
1643        // Tuple field order drops the connection before its sink lease, both
1644        // while idle and when a cancelled parent discards a native result.
1645        let conn = owner.0;
1646        let blocking_sink_lease = owner.1.clone();
1647        let outcome = tokio::task::spawn_blocking(move || {
1648            // The issuer's lease class applies on this thread, so the lease
1649            // taken below is recorded as what the issuer's work is for.
1650            let _lease_class = request.lease_class().enter();
1651            let outcome = (|| {
1652                let mut conn = BlockingWriterConnection::new(conn, Arc::clone(&blocking_admission));
1653                let acquisition_counters = blocking_counters;
1654                // A top-level request deliberately skips BEGIN, so it would
1655                // silently join any transaction leaked by an earlier request.
1656                // Refuse every request before dispatch if the connection is not
1657                // demonstrably clean, then retire the writer task.
1658                if !conn.is_autocommit() {
1659                    tracing::error!(
1660                    "writer task: connection is not in autocommit mode before request dispatch; \
1661                     retiring the poisoned writer without running the request"
1662                );
1663                    let request_state = WriterTaskRequestState::NotStarted;
1664                    request.reply_error(writer_task_terminated(request_state));
1665                    return conn.finish(Some(request_state));
1666                }
1667
1668                // The lease precedes SQLite writer acquisition and remains held
1669                // until the request has committed, rolled back, or returned to
1670                // autocommit. Checkpoint requests deliberately skip both steps.
1671                conn.volume_lease = if request.is_checkpoint_bypass() {
1672                    None
1673                } else {
1674                    let class = if request.needs_vacuum_headroom() {
1675                        crate::disk_guard::LeaseClass::Maintenance
1676                    } else {
1677                        crate::disk_guard::LeaseClass::WriterTask
1678                    };
1679                    match blocking_admission.acquire(class) {
1680                        Ok(lease) => lease,
1681                        Err(error) => {
1682                            request.reply_error(error.into_storage_error(
1683                                khive_storage::StorageCapability::Sql,
1684                                "writer_task_admission",
1685                            ));
1686                            return conn.finish(None);
1687                        }
1688                    }
1689                };
1690
1691                let terminal_state = if request.is_top_level() {
1692                    if !request.is_checkpoint_bypass() {
1693                        let admission = if request.needs_vacuum_headroom() {
1694                            blocking_admission.check_for_vacuum()
1695                        } else {
1696                            blocking_admission.check()
1697                        };
1698                        if let Err(error) = admission {
1699                            request.reply_error(error.into_storage_error(
1700                                khive_storage::StorageCapability::Sql,
1701                                "writer_task_admission",
1702                            ));
1703                            return conn.finish(None);
1704                        }
1705                    }
1706                    // ADR-067 Component A:
1707                    // no BEGIN IMMEDIATE for this request — some statements
1708                    // (e.g. VACUUM) are rejected by SQLite inside any open
1709                    // transaction. Still runs on this task's dedicated
1710                    // connection and still serialized one-request-at-a-time by
1711                    // this same drain loop, so the single-writer guarantee
1712                    // holds; only the transaction wrap is skipped.
1713                    acquisition_counters.record_writer_task_acquisition();
1714                    sealed::Sealed::execute_and_reply_top_level_reporting_terminal(
1715                        request, &conn, queue_wait,
1716                    )
1717                } else {
1718                    let tx_span = khive_storage::tx_registry::register_scoped(
1719                        Some("writer_task_tx".to_string()),
1720                        origin,
1721                    );
1722                    let (begin_outcome, transaction_acquire, begin_attempt) =
1723                        begin_immediate_with_retry(
1724                            &conn,
1725                            &acquisition_counters,
1726                            busy_timeout,
1727                            Connection::busy_timeout,
1728                        );
1729                    match begin_outcome {
1730                        Ok(()) => {
1731                            if let Err(error) = blocking_admission.check() {
1732                                let request_state =
1733                                    match rollback_after_failure(&conn, "capacity admission") {
1734                                        RollbackDisposition::RolledBack => None,
1735                                        RollbackDisposition::SideEffectsUnknown => {
1736                                            Some(WriterTaskRequestState::SideEffectsUnknown)
1737                                        }
1738                                    };
1739                                drop(tx_span);
1740                                let error = if let Some(state) = request_state {
1741                                    writer_task_terminated(state)
1742                                } else {
1743                                    error.into_storage_error(
1744                                        khive_storage::StorageCapability::Sql,
1745                                        "writer_task_admission",
1746                                    )
1747                                };
1748                                sealed::Sealed::reply_error_after_begin(
1749                                    request,
1750                                    error,
1751                                    queue_wait,
1752                                    transaction_acquire,
1753                                );
1754                                return conn.finish(request_state);
1755                            }
1756                            acquisition_counters.record_writer_task_acquisition();
1757                            sealed::Sealed::execute_and_reply_reporting_terminal(
1758                                request,
1759                                &conn,
1760                                Some(tx_span),
1761                                queue_wait,
1762                                transaction_acquire,
1763                            )
1764                        }
1765                        Err(e) => {
1766                            // Do NOT run the request's operation: `conn` never
1767                            // entered a transaction, so executing the op's DML
1768                            // here would run in autocommit mode and land partial
1769                            // writes for a request the caller is about to be told
1770                            // failed.
1771                            crate::timeout_sink::maybe_emit_sqlite_full(&blocking_db, &e);
1772                            tracing::warn!(
1773                                error = %e,
1774                                attempts = begin_attempt,
1775                                "writer task: BEGIN IMMEDIATE failed; replying an \
1776                                 error without running the request's operation"
1777                            );
1778                            // Although BEGIN never opened a SQL transaction, the
1779                            // scoped attempt is observable in tx_registry. Drop
1780                            // it before waking the caller for the same reply-side
1781                            // lifecycle guarantee as successful requests (#1790).
1782                            drop(tx_span);
1783                            // A busy/locked refusal was already counted inside
1784                            // the retry loop above, including this final one —
1785                            // classifying and counting it again here would
1786                            // double it. Only a non-busy BEGIN failure (which
1787                            // never enters the retry loop's busy arm) still
1788                            // needs its counter recorded at this seam.
1789                            let begin_error = writer_task_begin_error(e, busy_timeout);
1790                            if !matches!(
1791                                begin_error.without_sqlite_write_stage(),
1792                                StorageError::WriterTaskBusy { .. }
1793                            ) {
1794                                acquisition_counters.record_writer_task_begin_error();
1795                            }
1796                            sealed::Sealed::reply_error_after_begin(
1797                                request,
1798                                begin_error,
1799                                queue_wait,
1800                                transaction_acquire,
1801                            );
1802                            None
1803                        }
1804                    }
1805                };
1806                conn.finish(terminal_state)
1807            })();
1808            (outcome, blocking_sink_lease)
1809        })
1810        .await;
1811
1812        match outcome {
1813            Ok(((Some(returned_conn), None), _sink_lease)) => owner.0 = returned_conn,
1814            Ok(((_returned_conn, Some(request_state)), _sink_lease)) => {
1815                acquisition_counters.record_writer_task_request_failure();
1816                if request_state == WriterTaskRequestState::SideEffectsUnknown {
1817                    acquisition_counters.record_writer_task_side_effects_unknown();
1818                }
1819                tracing::error!(
1820                    request_state = %request_state,
1821                    "writer task reached a terminal request or connection state; closing and \
1822                     failing the queue without restarting"
1823                );
1824                crate::timeout_sink::emit_writer_task_retirement(
1825                    &db,
1826                    &format!("terminal request state: {request_state}"),
1827                );
1828                close_and_fail_queued_requests(&mut rx).await;
1829                return;
1830            }
1831            Ok(((None, None), _sink_lease)) => {
1832                unreachable!("a reusable writer returns its connection")
1833            }
1834            Err(join_err) => {
1835                acquisition_counters.record_writer_task_request_failure();
1836                tracing::error!(
1837                    error = %join_err,
1838                    "writer task blocking closure failed outside the request \
1839                     panic boundary; closing and failing the queue without restarting"
1840                );
1841                crate::timeout_sink::emit_writer_task_retirement(
1842                    &db,
1843                    &format!("blocking closure join failure: {join_err}"),
1844                );
1845                close_and_fail_queued_requests(&mut rx).await;
1846                return;
1847            }
1848        }
1849    }
1850}
1851
1852#[cfg(test)]
1853#[path = "writer_task_tests.rs"]
1854mod tests;
1855
1856#[cfg(test)]
1857#[path = "writer_task_lease_close_tests.rs"]
1858mod volume_lease_close_tests;
1859
1860#[cfg(test)]
1861#[path = "writer_task_slow_write_label_tests.rs"]
1862mod slow_write_label_tests;
1863
1864#[cfg(all(test, any(unix, windows)))]
1865#[path = "writer_task_identity_tests.rs"]
1866mod identity_tests;
1867
1868#[cfg(test)]
1869#[path = "writer_routing_outcome_tests.rs"]
1870mod writer_routing_outcome_tests;
1871
1872#[cfg(test)]
1873mod reply_evidence_tests {
1874    use super::*;
1875    use crate::test_hooks::TestHooks;
1876    use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1877
1878    #[tokio::test]
1879    async fn lost_delivery_retains_real_statement_and_commit_failures() {
1880        for fail_commit in [false, true] {
1881            let conn = crate::test_hooks::registered(Connection::open_in_memory().unwrap());
1882            conn.execute_batch("CREATE TABLE receipt_probe(id INTEGER PRIMARY KEY); INSERT INTO receipt_probe VALUES(1); BEGIN IMMEDIATE").unwrap();
1883            if fail_commit {
1884                conn.test_authorizer(Some(|context: AuthContext<'_>| match context.action {
1885                    AuthAction::Transaction {
1886                        operation: TransactionOperation::Unknown,
1887                    } => Authorization::Deny,
1888                    _ => Authorization::Allow,
1889                }))
1890                .unwrap();
1891            }
1892            let receipt = Arc::new(ReplyReceipt::default());
1893            let profiled = execute_wrapped_transaction_profiled(
1894                &conn,
1895                "receipt_commit",
1896                None,
1897                false,
1898                Some(&receipt.commit_issued),
1899                |conn| {
1900                    conn.execute(
1901                        "INSERT INTO receipt_probe VALUES(?1)",
1902                        [if fail_commit { 2 } else { 1 }],
1903                    )
1904                    .map_err(|error| {
1905                        StorageError::driver(
1906                            khive_storage::StorageCapability::Sql,
1907                            "receipt_statement",
1908                            error,
1909                        )
1910                    })
1911                },
1912                None,
1913            );
1914            assert!(
1915                conn.is_autocommit(),
1916                "both real failures must prove rollback before lost delivery"
1917            );
1918            assert_eq!(receipt.commit_issued.load(Ordering::Acquire), fail_commit);
1919            *receipt.completed() = Some(profiled.result);
1920            let (reply, reply_rx) = oneshot::channel();
1921            drop(reply);
1922            let error = PendingWrite { reply_rx, receipt }
1923                .wait()
1924                .await
1925                .expect_err("retained failure");
1926            let failure = crate::error::native_write_failure(
1927                &error,
1928                khive_storage::error::SqliteWriteStage::Statement,
1929            );
1930            let expected_code = if fail_commit {
1931                rusqlite::ffi::SQLITE_AUTH
1932            } else {
1933                rusqlite::ffi::SQLITE_CONSTRAINT
1934            };
1935            assert!(
1936                failure
1937                    .is_some_and(|failure| failure.primary_code == expected_code
1938                        && !failure.settlement_unknown),
1939                "lost delivery must retain the real native code and known rollback: {error:?}"
1940            );
1941            assert!(!error.is_write_outcome_unknown());
1942            let count: i64 = conn
1943                .query_row("SELECT count(*) FROM receipt_probe", [], |row| row.get(0))
1944                .unwrap();
1945            assert_eq!(count, 1, "real rollback preserves the original stored row");
1946        }
1947    }
1948}