Skip to main content

khive_db/sql_bridge/
inline_bridge.rs

1use super::{
2    acquire_handle_slot, async_trait, bind_params, execute_prepared_batch, execute_query,
3    execute_query_page, execute_query_row, map_rusqlite_err, map_write_boundary_err, map_write_err,
4    open_standalone_writer_on_blocking, prepare_batch_statements, prepare_cached_sql_statement,
5    reject_transaction_control_statements, run_manual_atomic_unit, Any, Arc, AtomicEventRows,
6    AtomicUnitOp, ConnectionPool, PageRequest, PoolBackedReader, PoolBackedWriter,
7    SlotTimeoutClass, SqlRow, SqlStatement, SqlValue, SqliteError, SqliteReader, SqliteWriter,
8    StorageCapability, StorageError,
9};
10
11// =============================================================================
12// atomic_unit (ADR-067 Component A, Fork C slice 2)
13// =============================================================================
14
15/// A purely-synchronous `SqlReader`/`SqlWriter` over a borrowed connection,
16/// used to drive an [`AtomicUnitOp`] on the queued or in-memory path, where the
17/// closure body runs inside a `spawn_blocking` (synchronous
18/// `FnOnce(&rusqlite::Connection) -> ...`) rather than a real async context.
19///
20/// Every method here does plain, non-suspending rusqlite work — there is no
21/// real `.await` point anywhere in this impl — so [`block_on_sync`] driving
22/// the resulting future to completion with a single poll is sound, not a
23/// hack: the future can never actually be `Pending`.
24///
25/// `SqlReader`/`SqlWriter` both carry a `'static` supertrait bound (they are
26/// used as `Box<dyn ...>` elsewhere in this module), so this type cannot
27/// hold a real `&'c Connection` borrow — it would tie `InlineWriter` to a
28/// non-`'static` lifetime and, independently, `&Connection` is not `Send`
29/// (`Connection` is `!Sync`), which the `#[async_trait]`-generated futures
30/// require. A raw pointer sidesteps both: `*const Connection` is `Send` and
31/// `'static` on its face, and the safety burden (the pointee outliving
32/// every dereference) is upheld by each atomic-unit owner: it builds an
33/// `InlineWriter` from `conn: &Connection`, drives `op` to completion via
34/// `block_on_sync` synchronously, and drops the `InlineWriter` before that
35/// borrow ends, all within one stack frame.
36pub(super) struct InlineWriter {
37    pub(super) event_rows: Option<Arc<AtomicEventRows>>,
38    pub(super) conn: *const rusqlite::Connection,
39    pub(super) standalone_db: Option<String>,
40}
41
42// SAFETY: `InlineWriter` is never actually shared across a real thread
43// boundary — it is constructed, driven to completion synchronously via
44// `block_on_sync`, and dropped within a single call frame inside the
45// `spawn_blocking` closure (see `atomic_unit`). The `Send`
46// bound `async_trait` imposes on the futures below is a static
47// over-approximation for this restricted, single-threaded usage pattern.
48unsafe impl Send for InlineWriter {}
49
50impl InlineWriter {
51    /// SAFETY: valid for the lifetime of the enclosing synchronous scope in
52    /// `atomic_unit` (see the struct doc comment above) — the pointee is
53    /// never dereferenced after that scope ends.
54    fn conn(&self) -> &rusqlite::Connection {
55        unsafe { &*self.conn }
56    }
57
58    fn operation(&self, standalone: &'static str, inline: &'static str) -> &'static str {
59        if self.standalone_db.is_some() {
60            standalone
61        } else {
62            inline
63        }
64    }
65
66    fn map_write_error(&self, error: rusqlite::Error, operation: &'static str) -> StorageError {
67        if let Some(db) = &self.standalone_db {
68            crate::timeout_sink::maybe_emit_busy(
69                db,
70                crate::timeout_sink::Site::StandaloneSqlBridge,
71                &error,
72            );
73        }
74        map_write_err(error, operation)
75    }
76}
77
78#[async_trait]
79impl khive_storage::SqlReader for InlineWriter {
80    async fn query_row(
81        &mut self,
82        statement: SqlStatement,
83    ) -> khive_storage::types::StorageResult<Option<SqlRow>> {
84        execute_query_row(self.conn(), &statement).map_err(|error| {
85            map_rusqlite_err(
86                error,
87                self.operation("writer.query_row", "inline.query_row"),
88            )
89        })
90    }
91
92    async fn query_all(
93        &mut self,
94        statement: SqlStatement,
95    ) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
96        execute_query(self.conn(), &statement).map_err(|error| {
97            map_rusqlite_err(
98                error,
99                self.operation("writer.query_all", "inline.query_all"),
100            )
101        })
102    }
103
104    async fn query_page(
105        &mut self,
106        statement: SqlStatement,
107        page: PageRequest,
108    ) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
109        execute_query_page(self.conn(), &statement, &page).map_err(|error| {
110            map_rusqlite_err(
111                error,
112                self.operation("writer.query_page", "inline.query_page"),
113            )
114        })
115    }
116
117    async fn query_scalar(
118        &mut self,
119        statement: SqlStatement,
120    ) -> khive_storage::types::StorageResult<Option<SqlValue>> {
121        let row = khive_storage::SqlReader::query_row(self, statement).await?;
122        Ok(row.and_then(|r| r.columns.into_iter().next().map(|c| c.value)))
123    }
124
125    async fn explain(
126        &mut self,
127        statement: SqlStatement,
128    ) -> khive_storage::types::StorageResult<Vec<SqlRow>> {
129        let explain_stmt = SqlStatement {
130            sql: format!("EXPLAIN QUERY PLAN {}", statement.sql),
131            params: statement.params,
132            label: statement.label,
133        };
134        khive_storage::SqlReader::query_all(self, explain_stmt).await
135    }
136}
137
138#[async_trait]
139impl khive_storage::SqlWriter for InlineWriter {
140    async fn execute(
141        &mut self,
142        statement: SqlStatement,
143    ) -> khive_storage::types::StorageResult<u64> {
144        // Boundary: `execute_batch` owns transaction-control rejection;
145        // `atomic_unit` uses this one-statement primitive for its own boundary.
146        let operation = self.operation("execute", "inline.execute");
147        let mut stmt = prepare_cached_sql_statement(self.conn(), &statement.sql)
148            .map_err(|error| self.map_write_error(error, operation))?;
149        bind_params(&mut stmt, &statement.params)
150            .map_err(|error| self.map_write_error(error, operation))?;
151        let affected = stmt
152            .raw_execute()
153            .map_err(|error| self.map_write_error(error, operation))?;
154        if let Some(event_rows) = self.event_rows.as_deref() {
155            event_rows.observe(&statement, affected as u64);
156        }
157        Ok(affected as u64)
158    }
159
160    async fn execute_batch(
161        &mut self,
162        statements: Vec<SqlStatement>,
163    ) -> khive_storage::types::StorageResult<u64> {
164        // Runs inside the writer task's per-request `BEGIN IMMEDIATE`
165        // (atomic_unit flag-on path), so a caller `COMMIT` would close the
166        // task's transaction — reject transaction-control statements up
167        // front, same contract as every other `execute_batch`.
168        let operation = self.operation("execute_batch", "inline.execute_batch");
169        reject_transaction_control_statements(&statements, operation)?;
170        let prepared = prepare_batch_statements(self.conn(), &statements)
171            .map_err(|error| self.map_write_error(error, operation))?;
172        execute_prepared_batch(
173            self.conn(),
174            prepared,
175            &statements,
176            self.event_rows.as_deref(),
177        )
178        .map_err(|error| self.map_write_error(error, operation))
179    }
180
181    async fn execute_script(&mut self, script: String) -> khive_storage::types::StorageResult<()> {
182        // Boundary: this raw script path is internal maintenance only and is
183        // outside the `execute_batch` transaction-control contract.
184        self.conn().execute_batch(&script).map_err(|error| {
185            self.map_write_error(
186                error,
187                self.operation("execute_script", "inline.execute_script"),
188            )
189        })
190    }
191}
192
193/// Poll `fut` exactly once with a no-op waker and return its output.
194///
195/// Only sound for futures that never actually suspend — every caller in
196/// this module drives an [`InlineWriter`], whose methods are pure
197/// synchronous rusqlite calls with no real `.await` point.
198///
199/// ADR-067 Component A: this used to
200/// `unreachable!()`-panic on `Poll::Pending`, and a panicking closure
201/// running inside the writer task's `spawn_blocking` (see
202/// `SqlBridge::atomic_unit`'s flag-on branch) would surface as a
203/// `JoinError` in `run_writer_task`, which is treated as fatal — the writer
204/// task exits and every subsequent `WriterTaskHandle::send` on this pool
205/// fails for the rest of the process. A future `atomic_unit` caller whose
206/// closure ever gains a real suspend point (this file's own contract
207/// already forbids it, but the invariant is enforced by convention, not the
208/// type system) would take down the writer task for the whole daemon.
209/// Returning `Err` instead lets `Pending` flow through the SAME error path
210/// as any other `atomic_unit` op failure: `WriteRequest::execute_and_reply`
211/// treats it as an ordinary `Err`, issues `ROLLBACK` on the writer task's
212/// held transaction, replies the error to the caller, and the writer task's
213/// `spawn_blocking` closure returns normally (not via panic) — so the task
214/// keeps draining subsequent requests instead of dying with the whole pool.
215pub(super) fn block_on_sync<F: std::future::Future>(fut: F) -> Result<F::Output, StorageError> {
216    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
217
218    fn no_op(_: *const ()) {}
219    fn clone_waker(_: *const ()) -> RawWaker {
220        RawWaker::new(std::ptr::null(), &VTABLE)
221    }
222    static VTABLE: RawWakerVTable = RawWakerVTable::new(clone_waker, no_op, no_op, no_op);
223
224    // SAFETY: every `RawWakerVTable` function is a no-op that never
225    // dereferences the data pointer, so a null data pointer is sound.
226    let raw_waker = RawWaker::new(std::ptr::null(), &VTABLE);
227    let waker = unsafe { Waker::from_raw(raw_waker) };
228    let mut cx = Context::from_waker(&waker);
229
230    let mut fut = std::pin::pin!(fut);
231    match fut.as_mut().poll(&mut cx) {
232        Poll::Ready(v) => Ok(v),
233        Poll::Pending => {
234            tracing::error!(target: "khive_db::sql_bridge",
235                "block_on_sync: atomic_unit future suspended on its first poll — \
236                 the closure passed to SqlAccess::atomic_unit must be non-blocking \
237                 (synchronous InlineWriter calls only, no real .await point)"
238            );
239            Err(StorageError::Internal(
240                "atomic_unit future suspended — closure must be non-blocking".to_string(),
241            ))
242        }
243    }
244}
245
246// =============================================================================
247// SqlBridge: the SqlAccess implementor
248// =============================================================================
249
250/// Bridges `ConnectionPool` to `khive_storage::SqlAccess`.
251///
252/// Dispatches based on whether the pool is file-backed or in-memory:
253/// - File-backed: pooled ordinary reader operations and a lazy standalone
254///   connection only for explicitly admitted multi-call read transactions,
255///   plus standalone writer connections capped at one live handle; atomic
256///   units drive a single registered raw transaction span.
257/// - In-memory: pool-backed connections per query (single shared connection).
258pub struct SqlBridge {
259    pool: Arc<ConnectionPool>,
260    pub(super) is_file_backed: bool,
261}
262
263impl SqlBridge {
264    /// Create a new bridge wrapping the given pool.
265    pub fn new(pool: Arc<ConnectionPool>, _is_file_backed: bool) -> Self {
266        // The legacy hint is not an authority for choosing an unguarded
267        // in-memory writer. A caller cannot route a file-backed pool through
268        // PoolBackedWriter by supplying `false`.
269        let is_file_backed = pool.canonical_path().is_some();
270        Self {
271            pool,
272            is_file_backed,
273        }
274    }
275}
276
277#[async_trait]
278impl khive_storage::SqlAccess for SqlBridge {
279    fn database_path(&self) -> Option<std::path::PathBuf> {
280        self.pool.canonical_path().map(std::path::Path::to_path_buf)
281    }
282
283    async fn reader(
284        &self,
285    ) -> khive_storage::types::StorageResult<Box<dyn khive_storage::SqlReader>> {
286        if self.is_file_backed {
287            Ok(Box::new(SqliteReader {
288                handle: None,
289                pool: Arc::clone(&self.pool),
290                poisoned: false,
291            }))
292        } else {
293            Ok(Box::new(PoolBackedReader {
294                pool: Arc::clone(&self.pool),
295                transaction: None,
296            }))
297        }
298    }
299
300    async fn writer(
301        &self,
302    ) -> khive_storage::types::StorageResult<Box<dyn khive_storage::SqlWriter>> {
303        let strict_handle = if self.pool.config().write_routing_strict {
304            self.pool.writer_task_for_write(None, "writer")?
305        } else {
306            None
307        };
308        if self.is_file_backed {
309            if self.pool.config().read_only {
310                return Err(StorageError::Pool {
311                    operation: "writer".into(),
312                    message: "backend is read-only".into(),
313                });
314            }
315            let db = crate::timeout_sink::db_label(&self.pool);
316            // ADR-136 D1 gate 1: queue-first. The handle lookup runs BEFORE
317            // any standalone connection is opened, and a lookup failure is
318            // propagated (never silently degraded) when strict routing is
319            // on. Only the flag-off/degraded case still opens a standalone
320            // connection.
321            let writer_task = if self.pool.config().write_routing_strict {
322                strict_handle
323            } else {
324                match self.pool.writer_task_handle() {
325                    Ok(handle) => handle,
326                    Err(e) => {
327                        tracing::warn!(target: "khive_db::sql_bridge",
328                            error = %e,
329                            "KHIVE_WRITE_ROUTING is not strict; writer() degrades to the \
330                             standalone-connection path"
331                        );
332                        None
333                    }
334                }
335            };
336            if writer_task.is_none() && self.pool.write_queue_active() {
337                // The queue is enabled but this call didn't get a handle
338                // (spawn/runtime degrade) — a direct-route violation in the
339                // making once this writer's execute*/query* methods run.
340                // In-memory pools are excluded: they never spawn a writer
341                // task by documented design (explicit `Some(true)` degrades),
342                // so a violation row there would be noise, not signal.
343                crate::timeout_sink::emit_direct_route_violation(
344                    &db,
345                    crate::timeout_sink::Site::DirectRouteSqlBridgeWriter,
346                );
347            }
348            // A standalone read-write connection is opened only when there is
349            // no queue handle to route writes through — `SqliteWriter`'s
350            // `SqlReader` methods (`query_row`/`query_all`/`query_page`)
351            // use pooled readers in the queue-backed case and lazily open the
352            // closed standalone exception only for an explicit deferred read
353            // transaction. Production callers do read through a `writer()`
354            // handle, so both routes are live.
355            // The standalone open acquires the pool-wide one-permit writer
356            // budget first, and the permit travels in the handle for the
357            // handle's whole lifetime — a queue-backed handle holds no
358            // writer permit (its writes route through the writer task), so
359            // this budget caps exactly the standalone read-write
360            // connections.
361            if writer_task.is_none() {
362                let handle_slot = acquire_handle_slot(
363                    self.pool.sql_bridge_writer_slots(),
364                    self.pool.config().checkout_timeout,
365                    "sql_bridge.writer_handle",
366                    SlotTimeoutClass::Admission,
367                )
368                .await?;
369                return open_standalone_writer_on_blocking(Arc::clone(&self.pool), handle_slot)
370                    .await;
371            }
372            Ok(Box::new(SqliteWriter {
373                observe_direct_errors: true,
374                event_rows: None,
375                handle: None,
376                writer_task,
377                origin: self.pool.origin(),
378                db,
379                pool: Arc::clone(&self.pool),
380            }))
381        } else {
382            Ok(Box::new(PoolBackedWriter {
383                pool: Arc::clone(&self.pool),
384            }))
385        }
386    }
387
388    /// Implements the trait's atomic-unit suspend-free invariant
389    /// (`SqlAccess::atomic_unit`'s doc comment): on the queued and in-memory branches,
390    /// `op` is driven through `block_on_sync` on an `InlineWriter` — a
391    /// single-poll driver that returns `Err` the instant `op`'s future is
392    /// `Pending` instead of ever actually suspending. `op` must therefore
393    /// issue only synchronous DML; see `InlineWriter`'s and
394    /// `block_on_sync`'s doc comments for the full mechanics and why this
395    /// restriction is load-bearing (a suspended poll inside the writer
396    /// task's `spawn_blocking` would otherwise block that task on external
397    /// async work while holding the single write connection).
398    async fn atomic_unit(
399        &self,
400        op: AtomicUnitOp,
401    ) -> khive_storage::types::StorageResult<Box<dyn Any + Send>> {
402        let strict_handle = if self.pool.config().write_routing_strict {
403            self.pool.writer_task_for_write(None, "atomic_unit")?
404        } else {
405            None
406        };
407        let event_rows = Arc::new(AtomicEventRows::default());
408        let result = async {
409            if self.is_file_backed {
410                if self.pool.config().read_only {
411                    return Err(StorageError::Pool {
412                        operation: "atomic_unit".into(),
413                        message: "backend is read-only".into(),
414                    });
415                }
416                // Best-effort, same guard `writer()` uses: `Ok(None)` on flag-off;
417                // `Err(WriterTaskNoRuntime)` propagates loud rather than silently
418                // falling back to a competing connection from a sync caller. ADR-136
419                // D1 gate 3: `Ok(None)` under strict routing is ALSO a fail-closed
420                // error (queue was requested but unavailable), not just a degrade.
421                let handle = if self.pool.config().write_routing_strict {
422                    strict_handle
423                } else {
424                    self.pool.writer_task_handle()?
425                };
426                if handle.is_none() && self.pool.write_queue_active() {
427                    crate::timeout_sink::emit_direct_route_violation(
428                        &crate::timeout_sink::db_label(&self.pool),
429                        crate::timeout_sink::Site::DirectRouteAtomicUnit,
430                    );
431                }
432                if let Some(writer_task) = handle {
433                    // Flag-on: ONE queued WriteRequest. `run_writer_task` already
434                    // has an open `BEGIN IMMEDIATE` on its dedicated connection
435                    // before this closure runs and issues `COMMIT`/`ROLLBACK`
436                    // after it returns — `op` must not (and, via `InlineWriter`,
437                    // does not) issue its own transaction control.
438                    let pending_event_rows = Arc::clone(&event_rows);
439                    return writer_task
440                        .send_bounded_at(
441                            move |conn| {
442                                let mut inline = InlineWriter {
443                                    event_rows: Some(Arc::clone(&pending_event_rows)),
444                                    conn: conn as *const rusqlite::Connection,
445                                    standalone_db: None,
446                                };
447                                // Flatten: `block_on_sync` now returns `Result<F::Output,
448                                // StorageError>` (outer = "did the future actually
449                                // resolve on first poll", inner = the op's own
450                                // `StorageResult`) instead of panicking on `Pending`
451                                // (ADR-067 Component A). Either
452                                // error flows through this closure's ordinary `Err`
453                                // return, which `WriteRequest::execute_and_reply`
454                                // already turns into a normal ROLLBACK + error reply —
455                                // no panic, so the writer task survives.
456                                match block_on_sync(op(&mut inline)) {
457                                    Ok(inner) => inner,
458                                    Err(e) => Err(e),
459                                }
460                            },
461                            "atomic_unit",
462                        )
463                        .await;
464                }
465                // Contract: this acquire waits on the pool-wide one-permit
466                // writer-handle budget — the same permit a live `writer()` handle
467                // holds for its lifetime — so it times out with
468                // `StorageError::AdmissionTimeout` after `checkout_timeout` while a writer
469                // handle is checked out (and a `writer()` call times out while
470                // this unit runs). Callers must not hold a boxed writer handle
471                // across an `atomic_unit()` call on the same pool; drop the
472                // handle first. The `writer_task` branch above never touches this
473                // budget.
474                let handle_slot = acquire_handle_slot(
475                    self.pool.sql_bridge_writer_slots(),
476                    self.pool.config().checkout_timeout,
477                    "sql_bridge.atomic_unit_handle",
478                    SlotTimeoutClass::Admission,
479                )
480                .await?;
481                run_manual_atomic_unit(
482                    Arc::clone(&self.pool),
483                    handle_slot,
484                    op,
485                    Arc::clone(&event_rows),
486                )
487                .await
488                .inspect_err(|error| self.pool.record_direct_writer_error(error))
489            } else {
490                // Every statement shares one connection. Keep its guard through
491                // commit/rollback so other units and ordinary writes cannot join it.
492                let pool = Arc::clone(&self.pool);
493                let pending_event_rows = Arc::clone(&event_rows);
494                tokio::task::spawn_blocking(move || {
495                    let mut guard = pool.try_writer().map_err(|error: SqliteError| {
496                        StorageError::driver(StorageCapability::Sql, "atomic_unit", error)
497                    })?;
498                    let conn = guard.conn();
499                    if !conn.is_autocommit() {
500                        pool.retire_pooled_writer(guard.conn_mut());
501                        return Err(StorageError::writer_task_terminated(
502                            khive_storage::WriterTaskRequestState::SideEffectsUnknown,
503                        ));
504                    }
505                    if let Err(error) = conn.execute_batch("BEGIN IMMEDIATE") {
506                        if !conn.is_autocommit() {
507                            pool.retire_pooled_writer(guard.conn_mut());
508                            return Err(SqliteError::settlement_with_cause(
509                                &error,
510                                khive_storage::error::SqliteWriteStage::Begin,
511                            )
512                            .into_storage_error(StorageCapability::Sql, "atomic_unit.begin"));
513                        }
514                        return Err(map_write_boundary_err(
515                            error,
516                            "atomic_unit.begin",
517                            khive_storage::error::SqliteWriteStage::Begin,
518                        ))
519                        .inspect_err(|error| pool.record_direct_writer_error(error));
520                    }
521                    let _tx_handle = khive_storage::tx_registry::register_scoped(
522                        Some("atomic_unit".to_string()),
523                        pool.origin(),
524                    );
525                    let (result, terminal_state) = crate::writer_task::execute_wrapped_transaction(
526                        conn,
527                        "atomic_unit.commit",
528                        |conn| {
529                            let mut inline = InlineWriter {
530                                event_rows: Some(Arc::clone(&pending_event_rows)),
531                                conn: conn as *const rusqlite::Connection,
532                                standalone_db: None,
533                            };
534                            block_on_sync(op(&mut inline)).and_then(|result| result)
535                        },
536                    );
537                    if terminal_state.is_some() {
538                        pool.retire_pooled_writer(guard.conn_mut());
539                    }
540                    result.inspect_err(|error| pool.record_direct_writer_error(error))
541                })
542                .await
543                .map_err(|error| {
544                    StorageError::driver(StorageCapability::Sql, "atomic_unit", error)
545                })?
546            }
547        }
548        .await;
549        khive_storage::usage::account_event_write(
550            result.as_ref().map(|_| event_rows.committed_rows()),
551        );
552        result
553    }
554}