Skip to main content

slabs_db/
lib.rs

1//! Raw-SQL database library for Slabs.
2//!
3//! This crate owns the tuned `SQLite` WAL wrapper ([`Db`]), the optional `PostgreSQL` wrapper ([`PgDb`]),
4//! URL engine detection ([`DbEngine`]), framework system schemas ([`SYSTEM_SCHEMA_SQL`], [`POSTGRES_SYSTEM_SCHEMA_SQL`]),
5//! and FTS5 query escaping ([`fts5_query`]). It also re-exports [`QueryBuilder`] for dynamic parameterized SQL.
6//!
7//! # Owned types and system tables
8//!
9//! Calling [`Db::init_system_tables`], [`Db::migrate`], or [`Db::migrate_dir`] (and the matching [`PgDb`] methods)
10//! creates these 12 framework tables if they do not exist:
11//!
12//! - `slabs_sessions`
13//! - `slabs_magic_links`
14//! - `slabs_access_tokens`
15//! - `slabs_jobs`
16//! - `slabs_cache`
17//! - `slabs_mail_outbox`
18//! - `slabs_blobs`
19//! - `slabs_webhooks`
20//! - `slabs_webhook_deliveries`
21//! - `slabs_idempotency_keys`
22//! - `slabs_audit_log`
23//! - `slabs_incidents`
24//!
25//! # Invariants
26//!
27//! - **Split WAL pools on file-backed `SQLite`**: [`Db::reader`] returns a read-only pool with up to 16 connections for concurrent `SELECT` queries. [`Db::writer`] and [`Db::pool`] return a dedicated single-connection writer pool (`max_connections(1)`).
28//! - **Explicit `BEGIN IMMEDIATE` transactions**: [`Db::begin`] opens a `BEGIN IMMEDIATE` transaction on the single writer pool. Use it for multi-step mutations so `SQLite` acquires the write lock up front and avoids `SQLITE_BUSY_SNAPSHOT` lock-upgrade failures.
29//! - **In-memory test databases share one connection**: when `database_url` is `"sqlite::memory:"` or contains `"mode=memory"`, [`Db::connect`] clones the single writer pool for [`Db::reader`] because `SQLite` isolates in-memory databases per connection.
30//! - **Tuned `SQLite` pragmas**: [`Db::connect`] sets `foreign_keys = ON`, `synchronous = NORMAL`, `cache_size = -64000`, `temp_store = MEMORY`, `trusted_schema = OFF`, `secure_delete = ON`, and `busy_timeout` (10s writer, 5s reader). File-backed databases also enable `journal_mode = WAL` and `mmap_size = 268435456` (256 MiB).
31//! - **Parameterized SQL only**: always bind untrusted input with `sqlx::query`, `sqlx::query_as`, or [`QueryBuilder`]. Never interpolate user strings into SQL text.
32//! - **FTS5 search escaping**: pass untrusted search strings through [`fts5_query`] before binding to an FTS5 `MATCH ?` clause. It strips double quotes and wraps each whitespace token as `"token"*` joined with `AND`.
33//!
34//! # Usage
35//!
36//! ```rust,no_run
37//! use slabs_core::SlabResult;
38//! use slabs_db::{fts5_query, Db};
39//!
40//! async fn example() -> SlabResult<()> {
41//!     let db = Db::connect("sqlite://app.db?mode=rwc").await?;
42//!     db.init_system_tables().await?;
43//!
44//!     // Concurrent SELECT on the read-only WAL pool.
45//!     let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
46//!         .fetch_one(db.reader())
47//!         .await?;
48//!
49//!     // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
50//!     let mut tx = db.begin().await?;
51//!     sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
52//!         .bind("stale_key")
53//!         .execute(&mut *tx)
54//!         .await?;
55//!     tx.commit().await?;
56//!
57//!     // Safe FTS5 query construction for user input.
58//!     if let Some(match_expr) = fts5_query("deploy \"prod\"") {
59//!         assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
60//!     }
61//!     let _ = count;
62//!     Ok(())
63//! }
64//! ```
65
66use slabs_core::{SlabError, SlabResult};
67use sqlx::{
68    migrate::Migrator,
69    postgres::PgPoolOptions,
70    sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
71    PgPool, Postgres, Sqlite, SqlitePool, Transaction,
72};
73use std::fmt::Write as _;
74use std::path::Path;
75use std::str::FromStr;
76use std::time::Duration;
77
78pub use sqlx::QueryBuilder;
79
80/// Database engine detected from a `DATABASE_URL` string.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum DbEngine {
83    /// Embedded `SQLite` database.
84    Sqlite,
85    /// Networked `PostgreSQL` database.
86    Postgres,
87}
88
89impl DbEngine {
90    /// Detects the [`DbEngine`] from a database connection URL.
91    ///
92    /// Returns [`DbEngine::Postgres`] when the trimmed, lowercased URL starts with
93    /// `"postgres://"` or `"postgresql://"`, and [`DbEngine::Sqlite`] otherwise.
94    #[must_use]
95    pub fn detect(database_url: &str) -> Self {
96        let lower = database_url.trim().to_ascii_lowercase();
97        if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
98            Self::Postgres
99        } else {
100            Self::Sqlite
101        }
102    }
103}
104
105/// Framework-owned `SQLite` DDL for the 12 system tables and their indexes.
106///
107/// Applied idempotently by [`Db::init_system_tables`], [`Db::migrate`], and [`Db::migrate_dir`].
108pub const SYSTEM_SCHEMA_SQL: &str = r"
109CREATE TABLE IF NOT EXISTS slabs_sessions (
110    id TEXT PRIMARY KEY NOT NULL,
111    user_id TEXT NOT NULL,
112    role TEXT NOT NULL DEFAULT 'member',
113    token_hash TEXT NOT NULL UNIQUE,
114    expires_at TEXT NOT NULL,
115    created_at TEXT NOT NULL
116);
117CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
118CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
119
120CREATE TABLE IF NOT EXISTS slabs_magic_links (
121    id TEXT PRIMARY KEY NOT NULL,
122    email TEXT NOT NULL,
123    purpose TEXT NOT NULL DEFAULT 'sign_in',
124    code_hash TEXT NOT NULL UNIQUE,
125    expires_at TEXT NOT NULL,
126    created_at TEXT NOT NULL
127);
128CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
129
130CREATE TABLE IF NOT EXISTS slabs_access_tokens (
131    id TEXT PRIMARY KEY NOT NULL,
132    user_id TEXT NOT NULL,
133    role TEXT NOT NULL DEFAULT 'member',
134    description TEXT NOT NULL DEFAULT '',
135    permission TEXT NOT NULL DEFAULT 'write',
136    token_hash TEXT NOT NULL UNIQUE,
137    last_used_at TEXT,
138    expires_at TEXT,
139    created_at TEXT NOT NULL
140);
141CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
142
143CREATE TABLE IF NOT EXISTS slabs_jobs (
144    id TEXT PRIMARY KEY NOT NULL,
145    job_name TEXT NOT NULL,
146    queue TEXT NOT NULL DEFAULT 'default',
147    payload_json TEXT NOT NULL,
148    status TEXT NOT NULL DEFAULT 'pending',
149    attempts INTEGER NOT NULL DEFAULT 0,
150    max_attempts INTEGER NOT NULL DEFAULT 5,
151    run_at TEXT NOT NULL,
152    locked_until TEXT,
153    last_error TEXT,
154    created_at TEXT NOT NULL,
155    updated_at TEXT NOT NULL
156);
157CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
158CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
159
160CREATE TABLE IF NOT EXISTS slabs_cache (
161    cache_key TEXT PRIMARY KEY NOT NULL,
162    value_text TEXT NOT NULL,
163    expires_at TEXT NOT NULL,
164    updated_at TEXT NOT NULL
165);
166CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
167
168CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
169    id TEXT PRIMARY KEY NOT NULL,
170    from_addr TEXT NOT NULL,
171    to_addr TEXT NOT NULL,
172    subject TEXT NOT NULL,
173    text_body TEXT NOT NULL,
174    html_body TEXT,
175    sent_at TEXT NOT NULL
176);
177
178CREATE TABLE IF NOT EXISTS slabs_blobs (
179    id TEXT PRIMARY KEY NOT NULL,
180    filename TEXT NOT NULL,
181    content_type TEXT NOT NULL,
182    byte_size INTEGER NOT NULL,
183    checksum_sha256 TEXT NOT NULL,
184    storage_key TEXT NOT NULL UNIQUE,
185    scope TEXT,
186    created_at TEXT NOT NULL
187);
188
189CREATE TABLE IF NOT EXISTS slabs_webhooks (
190    id TEXT PRIMARY KEY NOT NULL,
191    scope_id TEXT NOT NULL,
192    name TEXT NOT NULL,
193    url TEXT NOT NULL,
194    signing_secret TEXT NOT NULL,
195    subscribed_actions_json TEXT NOT NULL,
196    active INTEGER NOT NULL DEFAULT 1,
197    created_at TEXT NOT NULL
198);
199CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
200
201CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
202    id TEXT PRIMARY KEY NOT NULL,
203    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
204    action TEXT NOT NULL,
205    payload_json TEXT NOT NULL,
206    signature TEXT NOT NULL,
207    status TEXT NOT NULL DEFAULT 'pending',
208    response_status INTEGER,
209    last_error TEXT,
210    created_at TEXT NOT NULL,
211    delivered_at TEXT
212);
213CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
214
215CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
216    scope TEXT NOT NULL,
217    key TEXT NOT NULL,
218    response_json TEXT,
219    expires_at TEXT,
220    created_at TEXT NOT NULL,
221    PRIMARY KEY (scope, key)
222);
223CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
224
225CREATE TABLE IF NOT EXISTS slabs_audit_log (
226    id TEXT PRIMARY KEY NOT NULL,
227    actor_id TEXT,
228    action TEXT NOT NULL,
229    target_type TEXT NOT NULL,
230    target_id TEXT NOT NULL,
231    metadata_json TEXT NOT NULL DEFAULT '{}',
232    created_at TEXT NOT NULL
233);
234CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
235
236CREATE TABLE IF NOT EXISTS slabs_incidents (
237    id TEXT PRIMARY KEY,
238    fingerprint TEXT NOT NULL UNIQUE,
239    kind TEXT NOT NULL,
240    source_file TEXT NOT NULL,
241    route_pattern TEXT,
242    status_code INTEGER,
243    error_message TEXT NOT NULL,
244    detail TEXT,
245    context_json TEXT NOT NULL,
246    git_sha TEXT,
247    occurrences INTEGER NOT NULL DEFAULT 1,
248    status TEXT NOT NULL DEFAULT 'open',
249    resolved_in_sha TEXT,
250    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
251    first_seen_at TEXT NOT NULL,
252    last_seen_at TEXT NOT NULL
253);
254CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
255    ON slabs_incidents (status, last_seen_at DESC);
256";
257
258/// Framework-owned `PostgreSQL` DDL for the 12 system tables and their indexes.
259///
260/// Uses `TIMESTAMPTZ`, `JSONB`, `BIGINT`, and `BOOLEAN` column types.
261/// Applied idempotently by [`PgDb::init_system_tables`], [`PgDb::migrate`], and [`PgDb::migrate_dir`].
262pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
263CREATE TABLE IF NOT EXISTS slabs_sessions (
264    id TEXT PRIMARY KEY NOT NULL,
265    user_id TEXT NOT NULL,
266    role TEXT NOT NULL DEFAULT 'member',
267    token_hash TEXT NOT NULL UNIQUE,
268    expires_at TIMESTAMPTZ NOT NULL,
269    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
270);
271CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
272CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
273
274CREATE TABLE IF NOT EXISTS slabs_magic_links (
275    id TEXT PRIMARY KEY NOT NULL,
276    email TEXT NOT NULL,
277    purpose TEXT NOT NULL DEFAULT 'sign_in',
278    code_hash TEXT NOT NULL UNIQUE,
279    expires_at TIMESTAMPTZ NOT NULL,
280    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
281);
282CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
283
284CREATE TABLE IF NOT EXISTS slabs_access_tokens (
285    id TEXT PRIMARY KEY NOT NULL,
286    user_id TEXT NOT NULL,
287    role TEXT NOT NULL DEFAULT 'member',
288    description TEXT NOT NULL DEFAULT '',
289    permission TEXT NOT NULL DEFAULT 'write',
290    token_hash TEXT NOT NULL UNIQUE,
291    last_used_at TIMESTAMPTZ,
292    expires_at TIMESTAMPTZ,
293    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
294);
295CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
296
297CREATE TABLE IF NOT EXISTS slabs_jobs (
298    id TEXT PRIMARY KEY NOT NULL,
299    job_name TEXT NOT NULL,
300    queue TEXT NOT NULL DEFAULT 'default',
301    payload_json JSONB NOT NULL,
302    status TEXT NOT NULL DEFAULT 'pending',
303    attempts BIGINT NOT NULL DEFAULT 0,
304    max_attempts BIGINT NOT NULL DEFAULT 5,
305    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
306    locked_until TIMESTAMPTZ,
307    last_error TEXT,
308    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
309    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
310);
311CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
312CREATE INDEX IF NOT EXISTS idx_slabs_jobs_locked_until ON slabs_jobs(status, locked_until);
313
314CREATE TABLE IF NOT EXISTS slabs_cache (
315    cache_key TEXT PRIMARY KEY NOT NULL,
316    value_text TEXT NOT NULL,
317    expires_at TIMESTAMPTZ NOT NULL,
318    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
319);
320CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
321
322CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
323    id TEXT PRIMARY KEY NOT NULL,
324    from_addr TEXT NOT NULL,
325    to_addr TEXT NOT NULL,
326    subject TEXT NOT NULL,
327    text_body TEXT NOT NULL,
328    html_body TEXT,
329    sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
330);
331
332CREATE TABLE IF NOT EXISTS slabs_blobs (
333    id TEXT PRIMARY KEY NOT NULL,
334    filename TEXT NOT NULL,
335    content_type TEXT NOT NULL,
336    byte_size BIGINT NOT NULL,
337    checksum_sha256 TEXT NOT NULL,
338    storage_key TEXT NOT NULL UNIQUE,
339    scope TEXT,
340    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
341);
342
343CREATE TABLE IF NOT EXISTS slabs_webhooks (
344    id TEXT PRIMARY KEY NOT NULL,
345    scope_id TEXT NOT NULL,
346    name TEXT NOT NULL,
347    url TEXT NOT NULL,
348    signing_secret TEXT NOT NULL,
349    subscribed_actions_json JSONB NOT NULL,
350    active BOOLEAN NOT NULL DEFAULT TRUE,
351    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
352);
353CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
354
355CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
356    id TEXT PRIMARY KEY NOT NULL,
357    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
358    action TEXT NOT NULL,
359    payload_json JSONB NOT NULL,
360    signature TEXT NOT NULL,
361    status TEXT NOT NULL DEFAULT 'pending',
362    response_status INTEGER,
363    last_error TEXT,
364    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
365    delivered_at TIMESTAMPTZ
366);
367CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
368
369CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
370    scope TEXT NOT NULL,
371    key TEXT NOT NULL,
372    response_json TEXT,
373    expires_at TIMESTAMPTZ,
374    created_at TEXT NOT NULL,
375    PRIMARY KEY (scope, key)
376);
377CREATE INDEX IF NOT EXISTS idx_slabs_idempotency_keys_expires_at ON slabs_idempotency_keys(expires_at);
378
379CREATE TABLE IF NOT EXISTS slabs_audit_log (
380    id TEXT PRIMARY KEY NOT NULL,
381    actor_id TEXT,
382    action TEXT NOT NULL,
383    target_type TEXT NOT NULL,
384    target_id TEXT NOT NULL,
385    metadata_json TEXT NOT NULL DEFAULT '{}',
386    created_at TEXT NOT NULL
387);
388CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
389
390CREATE TABLE IF NOT EXISTS slabs_incidents (
391    id TEXT PRIMARY KEY,
392    fingerprint TEXT NOT NULL UNIQUE,
393    kind TEXT NOT NULL,
394    source_file TEXT NOT NULL,
395    route_pattern TEXT,
396    status_code INTEGER,
397    error_message TEXT NOT NULL,
398    detail TEXT,
399    context_json TEXT NOT NULL,
400    git_sha TEXT,
401    occurrences INTEGER NOT NULL DEFAULT 1,
402    status TEXT NOT NULL DEFAULT 'open',
403    resolved_in_sha TEXT,
404    recent_occurrences_json TEXT NOT NULL DEFAULT '[]',
405    first_seen_at TEXT NOT NULL,
406    last_seen_at TEXT NOT NULL
407);
408CREATE INDEX IF NOT EXISTS idx_slabs_incidents_status_seen
409    ON slabs_incidents (status, last_seen_at DESC);
410";
411
412/// Converts untrusted user search text into an FTS5 prefix-AND `MATCH` expression.
413///
414/// Splits on whitespace, strips `"` and ASCII control characters (including `\0`), caps
415/// each token to 64 characters, keeps at most 16 tokens, wraps each remaining token as
416/// `"token"*`, and joins them with `AND`.
417/// Returns `None` when the input contains no non-empty tokens after sanitization.
418#[must_use]
419pub fn fts5_query(raw: &str) -> Option<String> {
420    let terms: Vec<String> = raw
421        .split_whitespace()
422        .map(|tok| {
423            tok.chars()
424                .filter(|&ch| ch != '"' && !ch.is_ascii_control())
425                .take(64)
426                .collect::<String>()
427        })
428        .filter(|tok| !tok.is_empty())
429        .take(16)
430        .map(|tok| format!("\"{tok}\"*"))
431        .collect();
432    if terms.is_empty() {
433        None
434    } else {
435        Some(terms.join(" AND "))
436    }
437}
438
439/// Query parameters for cursor-based (keyset) pagination.
440#[derive(Debug, Clone, Default, serde::Deserialize)]
441pub struct Pagination {
442    /// Requested maximum number of items per page.
443    pub limit: Option<u32>,
444    /// Opaque cursor returned as `next_cursor` by the previous page.
445    pub cursor: Option<String>,
446}
447
448impl Pagination {
449    /// Resolves the page size, clamping it between `1` and `max_limit.max(1)`.
450    ///
451    /// Falls back to `default_limit` when [`Pagination::limit`] is `None`.
452    #[must_use]
453    pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
454        let upper = max_limit.max(1);
455        let raw = self.limit.unwrap_or(default_limit);
456        i64::from(raw.clamp(1, upper))
457    }
458
459    /// Returns `clamped_limit + 1` so callers can detect whether more rows exist without a `COUNT(*)`.
460    #[must_use]
461    pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
462        self.clamped_limit(default_limit, max_limit) + 1
463    }
464}
465
466/// One page of cursor-paginated results.
467#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
468pub struct CursorPage<T> {
469    /// Items returned for the current page.
470    pub items: Vec<T>,
471    /// Cursor of the last item when more rows exist, or `None` on the final page.
472    pub next_cursor: Option<String>,
473    /// Whether additional rows exist beyond this page.
474    pub has_more: bool,
475}
476
477impl<T> CursorPage<T> {
478    /// Builds a [`CursorPage`] from rows fetched with `LIMIT (limit + 1)`.
479    ///
480    /// Truncates `rows` to `limit`, sets `has_more` when an extra row was present,
481    /// and computes `next_cursor` from the last retained row via `cursor_fn`.
482    #[must_use]
483    pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
484        let has_more = rows.len() > limit;
485        if has_more {
486            rows.truncate(limit);
487        }
488        let next_cursor = if has_more {
489            rows.last().map(cursor_fn)
490        } else {
491            None
492        };
493        Self {
494            items: rows,
495            next_cursor,
496            has_more,
497        }
498    }
499}
500
501/// Persisted audit event row stored in `slabs_audit_log`.
502#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
503pub struct AuditEntry {
504    /// Prefixed audit entry identifier (`aud_<ulid>`).
505    pub id: String,
506    /// Optional identifier of the user or service that performed the action.
507    pub actor_id: Option<String>,
508    /// Action name describing what happened (for example `"room.archived"`).
509    pub action: String,
510    /// Logical type of the affected resource (for example `"room"`).
511    pub target_type: String,
512    /// Identifier of the affected resource.
513    pub target_id: String,
514    /// JSON-serialized metadata payload attached to the audit event.
515    pub metadata_json: String,
516    /// RFC 3339 UTC timestamp when the audit entry was created.
517    pub created_at: String,
518}
519
520/// Transactional audit log backed by the `slabs_audit_log` system table.
521#[derive(Debug, Clone)]
522pub struct AuditLog {
523    db: Db,
524}
525
526impl AuditLog {
527    /// Creates an [`AuditLog`] handle backed by `db`.
528    #[must_use]
529    pub fn new(db: Db) -> Self {
530        Self { db }
531    }
532
533    /// Inserts an audit entry inside an open `SQLite` transaction so it commits or rolls back atomically.
534    ///
535    /// Returns the generated `aud_<ulid>` identifier.
536    pub async fn record_in_tx(
537        &self,
538        tx: &mut Transaction<'_, Sqlite>,
539        actor_id: Option<&str>,
540        action: &str,
541        target_type: &str,
542        target_id: &str,
543        metadata: &serde_json::Value,
544    ) -> SlabResult<String> {
545        let id = slabs_core::id::new("aud");
546        let created_at = chrono::Utc::now().to_rfc3339();
547        let metadata_json = serde_json::to_string(metadata)
548            .map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;
549
550        sqlx::query(
551            "INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
552             VALUES (?, ?, ?, ?, ?, ?, ?)",
553        )
554        .bind(&id)
555        .bind(actor_id)
556        .bind(action)
557        .bind(target_type)
558        .bind(target_id)
559        .bind(&metadata_json)
560        .bind(&created_at)
561        .execute(&mut **tx)
562        .await?;
563
564        Ok(id)
565    }
566
567    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries for a specific
568    /// `(target_type, target_id)` on the read pool.
569    pub async fn list_for_target(
570        &self,
571        target_type: &str,
572        target_id: &str,
573        limit: i64,
574    ) -> SlabResult<Vec<AuditEntry>> {
575        let limit = limit.clamp(1, 500);
576        let rows: Vec<AuditEntry> = sqlx::query_as(
577            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
578             FROM slabs_audit_log
579             WHERE target_type = ? AND target_id = ?
580             ORDER BY created_at DESC, id DESC
581             LIMIT ?",
582        )
583        .bind(target_type)
584        .bind(target_id)
585        .bind(limit)
586        .fetch_all(self.db.reader())
587        .await?;
588        Ok(rows)
589    }
590
591    /// Lists up to `limit` (clamped to `1..=500`) most recent audit entries across all targets
592    /// on the read pool.
593    pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
594        let limit = limit.clamp(1, 500);
595        let rows: Vec<AuditEntry> = sqlx::query_as(
596            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
597             FROM slabs_audit_log
598             ORDER BY created_at DESC, id DESC
599             LIMIT ?",
600        )
601        .bind(limit)
602        .fetch_all(self.db.reader())
603        .await?;
604        Ok(rows)
605    }
606}
607
608const MAX_INCIDENT_ERROR_BYTES: usize = 1024;
609const MAX_INCIDENT_DETAIL_BYTES: usize = 4096;
610const MAX_RECENT_OCCURRENCES: usize = 10;
611
612fn append_recent_occurrence(existing_json: &str, snapshot: serde_json::Value) -> String {
613    let mut items =
614        serde_json::from_str::<Vec<serde_json::Value>>(existing_json).unwrap_or_default();
615    items.push(snapshot);
616    if items.len() > MAX_RECENT_OCCURRENCES {
617        let drain_count = items.len() - MAX_RECENT_OCCURRENCES;
618        items.drain(..drain_count);
619    }
620    serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_owned())
621}
622
623fn truncate_utf8(input: &str, max_bytes: usize) -> &str {
624    if input.len() <= max_bytes {
625        return input;
626    }
627    let mut end = max_bytes;
628    while end > 0 && !input.is_char_boundary(end) {
629        end -= 1;
630    }
631    &input[..end]
632}
633
634fn format_utc_micros(dt: chrono::DateTime<chrono::Utc>) -> String {
635    dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
636}
637
638/// Persisted runtime incident row stored in `slabs_incidents`.
639#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
640pub struct IncidentRecord {
641    /// Prefixed incident identifier (`inc_<ulid>`).
642    pub id: String,
643    /// Deterministic SHA-256 deduplication fingerprint.
644    pub fingerprint: String,
645    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, or `"client_error"`).
646    pub kind: String,
647    /// Source file associated with the incident (for example `"slabs/rooms/send_message.rs"`, `"jobs/send_email.rs"`, or `"browser"`).
648    pub source_file: String,
649    /// Optional matched HTTP route pattern or job/browser path.
650    pub route_pattern: Option<String>,
651    /// Optional HTTP status code associated with the incident.
652    pub status_code: Option<i64>,
653    /// Truncated error summary (at most 1024 UTF-8 bytes).
654    pub error_message: String,
655    /// Optional extended diagnostic detail (at most 4096 UTF-8 bytes).
656    pub detail: Option<String>,
657    /// JSON-serialized redacted diagnostic context.
658    pub context_json: String,
659    /// Optional Git commit SHA active when the incident was last observed.
660    pub git_sha: Option<String>,
661    /// Number of times this fingerprinted incident has occurred.
662    pub occurrences: i64,
663    /// Lifecycle state (`"open"`, `"resolved"`, or `"reopened"`).
664    pub status: String,
665    /// Optional Git commit SHA recorded when the incident was resolved.
666    pub resolved_in_sha: Option<String>,
667    /// JSON array of the last 10 occurrence snapshots (`seen_at`, `git_sha`, `request_id`, `latency_ms`).
668    pub recent_occurrences_json: String,
669    /// Fixed-width UTC RFC 3339 timestamp when the incident was first recorded.
670    pub first_seen_at: String,
671    /// Fixed-width UTC RFC 3339 timestamp when the incident was most recently updated.
672    pub last_seen_at: String,
673}
674
675/// Lifecycle outcome returned when recording an incident via [`Incidents::record_with_outcome`].
676#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
677#[serde(rename_all = "snake_case")]
678pub enum IncidentOutcome {
679    /// A brand-new incident row was inserted.
680    Opened,
681    /// A previously resolved incident recurred and was transitioned to `"reopened"`.
682    Reopened,
683    /// An already-active (`"open"` or `"reopened"`) incident matched the fingerprint and had its occurrence count incremented.
684    Incremented,
685}
686
687/// Input payload for recording a deduplicated runtime incident in `slabs_incidents`.
688#[derive(Debug, Clone)]
689pub struct IncidentInput {
690    /// Incident category (for example `"panic"`, `"http_5xx"`, `"slow_request"`, `"job_dead"`, `"slow_job"`, `"client_error"`, or `"user_bug_report"`).
691    pub kind: String,
692    /// Source file owning the failing or slow code path.
693    pub source_file: String,
694    /// Optional matched HTTP route pattern or path.
695    pub route_pattern: Option<String>,
696    /// Optional HTTP status code.
697    pub status_code: Option<i64>,
698    /// Error or bottleneck summary (truncated to 1024 UTF-8 bytes on persistence).
699    pub error_message: String,
700    /// Optional extended diagnostic detail (truncated to 4096 UTF-8 bytes on persistence).
701    pub detail: Option<String>,
702    /// Redacted structured JSON context attached to the incident.
703    pub context_json: serde_json::Value,
704    /// Optional Git commit SHA active when the incident occurred.
705    pub git_sha: Option<String>,
706    /// Optional explicit deduplication fingerprint override.
707    ///
708    /// When `None`, the fingerprint is derived deterministically from `(kind, source_file,
709    /// route_pattern, error_message)` — except for `"user_bug_report"`, which includes a unique
710    /// nonce so each user bug report creates a distinct open record unless explicitly fingerprinted.
711    pub custom_fingerprint: Option<String>,
712}
713
714/// Deduplicated runtime incident store backed by the `slabs_incidents` system table.
715#[derive(Debug, Clone)]
716pub struct Incidents {
717    db: Db,
718}
719
720impl Incidents {
721    /// Creates an [`Incidents`] handle backed by `db`.
722    #[must_use]
723    pub fn new(db: Db) -> Self {
724        Self { db }
725    }
726
727    /// Atomically records or deduplicates an incident and returns its exact [`IncidentOutcome`].
728    ///
729    /// Uses `input.custom_fingerprint` when provided (hashed under a domain prefix so fingerprints
730    /// remain fixed-width SHA-256 hex). Otherwise derives the fingerprint deterministically from
731    /// `(kind, source_file, route_pattern, error_message)`, appending a unique nonce when
732    /// `kind == "user_bug_report"` so individual user bug reports remain distinct.
733    ///
734    /// Truncates `error_message` to 1024 bytes and `detail` to 4096 bytes on UTF-8 character
735    /// boundaries, and upserts inside a `BEGIN IMMEDIATE` transaction.
736    pub async fn record_with_outcome(
737        &self,
738        input: IncidentInput,
739    ) -> SlabResult<(IncidentRecord, IncidentOutcome)> {
740        let fingerprint = if let Some(custom) = input
741            .custom_fingerprint
742            .as_deref()
743            .map(str::trim)
744            .filter(|s| !s.is_empty())
745        {
746            slabs_core::fingerprint(&["custom", custom])
747        } else if input.kind == "user_bug_report" {
748            let nonce = slabs_core::id::new("bug");
749            slabs_core::fingerprint(&[
750                &input.kind,
751                &input.source_file,
752                input.route_pattern.as_deref().unwrap_or(""),
753                &input.error_message,
754                &nonce,
755            ])
756        } else {
757            slabs_core::fingerprint(&[
758                &input.kind,
759                &input.source_file,
760                input.route_pattern.as_deref().unwrap_or(""),
761                &input.error_message,
762            ])
763        };
764        let error_message =
765            truncate_utf8(&input.error_message, MAX_INCIDENT_ERROR_BYTES).to_owned();
766        let detail = input
767            .detail
768            .as_deref()
769            .map(|d| truncate_utf8(d, MAX_INCIDENT_DETAIL_BYTES).to_owned());
770        let context_json = serde_json::to_string(&input.context_json).map_err(|e| {
771            SlabError::internal(format!("failed to serialize incident context: {e}"))
772        })?;
773        let now = format_utc_micros(chrono::Utc::now());
774        let occurrence_snapshot = serde_json::json!({
775            "seen_at": now,
776            "git_sha": input.git_sha,
777            "request_id": input.context_json.get("request_id"),
778            "latency_ms": input.context_json.get("latency_ms"),
779        });
780
781        let mut tx = self.db.begin().await?;
782        let existing: Option<IncidentRecord> = sqlx::query_as(
783            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
784                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
785                    recent_occurrences_json, first_seen_at, last_seen_at
786             FROM slabs_incidents
787             WHERE fingerprint = ?",
788        )
789        .bind(&fingerprint)
790        .fetch_optional(&mut *tx)
791        .await?;
792
793        let (record, outcome) = if let Some(prev) = existing {
794            let reopened = prev.status == "resolved";
795            let next_status = if reopened {
796                "reopened".to_owned()
797            } else {
798                prev.status.clone()
799            };
800            let next_resolved_in_sha = if reopened {
801                None
802            } else {
803                prev.resolved_in_sha.clone()
804            };
805            let next_occurrences = prev.occurrences + 1;
806            let next_recent_occurrences_json =
807                append_recent_occurrence(&prev.recent_occurrences_json, occurrence_snapshot);
808
809            sqlx::query(
810                "UPDATE slabs_incidents
811                 SET occurrences = ?,
812                     last_seen_at = ?,
813                     detail = ?,
814                     context_json = ?,
815                     git_sha = ?,
816                     status = ?,
817                     resolved_in_sha = ?,
818                     recent_occurrences_json = ?
819                 WHERE id = ?",
820            )
821            .bind(next_occurrences)
822            .bind(&now)
823            .bind(&detail)
824            .bind(&context_json)
825            .bind(&input.git_sha)
826            .bind(&next_status)
827            .bind(&next_resolved_in_sha)
828            .bind(&next_recent_occurrences_json)
829            .bind(&prev.id)
830            .execute(&mut *tx)
831            .await?;
832
833            let updated = IncidentRecord {
834                id: prev.id,
835                fingerprint: prev.fingerprint,
836                kind: prev.kind,
837                source_file: prev.source_file,
838                route_pattern: prev.route_pattern,
839                status_code: prev.status_code,
840                error_message: prev.error_message,
841                detail,
842                context_json,
843                git_sha: input.git_sha,
844                occurrences: next_occurrences,
845                status: next_status,
846                resolved_in_sha: next_resolved_in_sha,
847                recent_occurrences_json: next_recent_occurrences_json,
848                first_seen_at: prev.first_seen_at,
849                last_seen_at: now,
850            };
851            let outcome = if reopened {
852                IncidentOutcome::Reopened
853            } else {
854                IncidentOutcome::Incremented
855            };
856            (updated, outcome)
857        } else {
858            let id = slabs_core::id::new("inc");
859            let recent_occurrences_json = append_recent_occurrence("[]", occurrence_snapshot);
860            sqlx::query(
861                "INSERT INTO slabs_incidents (
862                     id, fingerprint, kind, source_file, route_pattern, status_code,
863                     error_message, detail, context_json, git_sha, occurrences,
864                     status, resolved_in_sha, recent_occurrences_json, first_seen_at, last_seen_at
865                 )
866                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'open', NULL, ?, ?, ?)",
867            )
868            .bind(&id)
869            .bind(&fingerprint)
870            .bind(&input.kind)
871            .bind(&input.source_file)
872            .bind(&input.route_pattern)
873            .bind(input.status_code)
874            .bind(&error_message)
875            .bind(&detail)
876            .bind(&context_json)
877            .bind(&input.git_sha)
878            .bind(&recent_occurrences_json)
879            .bind(&now)
880            .bind(&now)
881            .execute(&mut *tx)
882            .await?;
883
884            let inserted = IncidentRecord {
885                id,
886                fingerprint,
887                kind: input.kind,
888                source_file: input.source_file,
889                route_pattern: input.route_pattern,
890                status_code: input.status_code,
891                error_message,
892                detail,
893                context_json,
894                git_sha: input.git_sha,
895                occurrences: 1,
896                status: "open".to_owned(),
897                resolved_in_sha: None,
898                recent_occurrences_json,
899                first_seen_at: now.clone(),
900                last_seen_at: now,
901            };
902            (inserted, IncidentOutcome::Opened)
903        };
904
905        tx.commit().await?;
906        Ok((record, outcome))
907    }
908
909    /// Atomically records or deduplicates an incident by deterministic fingerprint.
910    ///
911    /// Delegates to [`Incidents::record_with_outcome`], returning `(record, is_new_or_reopened)`,
912    /// where the boolean is `true` for [`IncidentOutcome::Opened`] or [`IncidentOutcome::Reopened`].
913    pub async fn record(&self, input: IncidentInput) -> SlabResult<(IncidentRecord, bool)> {
914        let (record, outcome) = self.record_with_outcome(input).await?;
915        Ok((
916            record,
917            matches!(outcome, IncidentOutcome::Opened | IncidentOutcome::Reopened),
918        ))
919    }
920
921    /// Lists up to `limit` (clamped to `1..=500`) incidents ordered by `last_seen_at DESC` on the read pool.
922    ///
923    /// - `None` or `Some("active")`: returns active incidents (`status IN ('open', 'reopened')`).
924    /// - `Some("open")`, `Some("reopened")`, or `Some("resolved")`: returns exact status matches.
925    /// - `Some("all")`: returns incidents across all lifecycle states.
926    pub async fn list(&self, status: Option<&str>, limit: i64) -> SlabResult<Vec<IncidentRecord>> {
927        let limit = limit.clamp(1, 500);
928        let filter = status.map(str::trim).filter(|s| !s.is_empty());
929
930        let rows: Vec<IncidentRecord> = match filter {
931            None => {
932                sqlx::query_as(
933                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
934                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
935                            recent_occurrences_json, first_seen_at, last_seen_at
936                     FROM slabs_incidents
937                     WHERE status IN ('open', 'reopened')
938                     ORDER BY last_seen_at DESC, id DESC
939                     LIMIT ?",
940                )
941                .bind(limit)
942                .fetch_all(self.db.reader())
943                .await?
944            }
945            Some(st) if st.eq_ignore_ascii_case("active") => {
946                sqlx::query_as(
947                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
948                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
949                            recent_occurrences_json, first_seen_at, last_seen_at
950                     FROM slabs_incidents
951                     WHERE status IN ('open', 'reopened')
952                     ORDER BY last_seen_at DESC, id DESC
953                     LIMIT ?",
954                )
955                .bind(limit)
956                .fetch_all(self.db.reader())
957                .await?
958            }
959            Some(st) if st.eq_ignore_ascii_case("all") => {
960                sqlx::query_as(
961                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
962                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
963                            recent_occurrences_json, first_seen_at, last_seen_at
964                     FROM slabs_incidents
965                     ORDER BY last_seen_at DESC, id DESC
966                     LIMIT ?",
967                )
968                .bind(limit)
969                .fetch_all(self.db.reader())
970                .await?
971            }
972            Some(st) => {
973                sqlx::query_as(
974                    "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
975                            detail, context_json, git_sha, occurrences, status, resolved_in_sha,
976                            recent_occurrences_json, first_seen_at, last_seen_at
977                     FROM slabs_incidents
978                     WHERE status = ?
979                     ORDER BY last_seen_at DESC, id DESC
980                     LIMIT ?",
981                )
982                .bind(st)
983                .bind(limit)
984                .fetch_all(self.db.reader())
985                .await?
986            }
987        };
988        Ok(rows)
989    }
990
991    /// Fetches a single incident by its `inc_<ulid>` identifier on the read pool.
992    pub async fn get(&self, id: &str) -> SlabResult<Option<IncidentRecord>> {
993        let row: Option<IncidentRecord> = sqlx::query_as(
994            "SELECT id, fingerprint, kind, source_file, route_pattern, status_code, error_message,
995                    detail, context_json, git_sha, occurrences, status, resolved_in_sha,
996                    recent_occurrences_json, first_seen_at, last_seen_at
997             FROM slabs_incidents
998             WHERE id = ?",
999        )
1000        .bind(id)
1001        .fetch_optional(self.db.reader())
1002        .await?;
1003        Ok(row)
1004    }
1005
1006    /// Marks an incident as `"resolved"` with an optional `resolved_in_sha`, updating `last_seen_at`.
1007    ///
1008    /// Returns `true` if a matching row was updated, or `false` if `id` does not exist.
1009    pub async fn resolve(&self, id: &str, resolved_in_sha: Option<&str>) -> SlabResult<bool> {
1010        let now = format_utc_micros(chrono::Utc::now());
1011        let res = sqlx::query(
1012            "UPDATE slabs_incidents
1013             SET status = 'resolved',
1014                 resolved_in_sha = ?,
1015                 last_seen_at = ?
1016             WHERE id = ?",
1017        )
1018        .bind(resolved_in_sha)
1019        .bind(&now)
1020        .bind(id)
1021        .execute(self.db.writer())
1022        .await?;
1023        Ok(res.rows_affected() > 0)
1024    }
1025
1026    /// Auto-resolves active (`"open"` or `"reopened"`) incidents whose `last_seen_at` is older
1027    /// than `stale_days` days, recording `resolved_in_sha = 'auto:stale'` when unset.
1028    ///
1029    /// Passing `0` disables auto-closing and returns `Ok(0)`. Returns the number of rows closed.
1030    pub async fn close_stale(&self, stale_days: u64) -> SlabResult<u64> {
1031        if stale_days == 0 {
1032            return Ok(0);
1033        }
1034        let days = i64::try_from(stale_days.min(3650)).unwrap_or(3650);
1035        let now_dt = chrono::Utc::now();
1036        let cutoff_dt = now_dt
1037            .checked_sub_signed(chrono::Duration::days(days))
1038            .ok_or_else(|| SlabError::internal("stale incident cutoff timestamp overflow"))?;
1039        let now = format_utc_micros(now_dt);
1040        let cutoff = format_utc_micros(cutoff_dt);
1041        let res = sqlx::query(
1042            "UPDATE slabs_incidents
1043             SET status = 'resolved',
1044                 resolved_in_sha = COALESCE(resolved_in_sha, 'auto:stale'),
1045                 last_seen_at = ?
1046             WHERE status IN ('open', 'reopened')
1047               AND last_seen_at < ?",
1048        )
1049        .bind(&now)
1050        .bind(&cutoff)
1051        .execute(self.db.writer())
1052        .await?;
1053        Ok(res.rows_affected())
1054    }
1055
1056    /// Returns the number of currently active (`"open"` or `"reopened"`) incidents on the read pool.
1057    pub async fn count_open(&self) -> SlabResult<i64> {
1058        let (count,): (i64,) = sqlx::query_as(
1059            "SELECT COUNT(*) FROM slabs_incidents WHERE status IN ('open', 'reopened')",
1060        )
1061        .fetch_one(self.db.reader())
1062        .await?;
1063        Ok(count)
1064    }
1065}
1066
1067/// Raw-SQL `SQLite` database wrapper tuned for concurrent WAL workloads.
1068///
1069/// Holds two pools on file-backed databases:
1070/// - A single-connection writer pool (`max_connections(1)`) used by [`Db::writer`], [`Db::pool`], and [`Db::begin`] (`BEGIN IMMEDIATE`).
1071/// - A 16-connection read-only pool used by [`Db::reader`] for parallel `SELECT` queries.
1072///
1073/// In-memory databases (`sqlite::memory:` or `mode=memory`) share the single writer pool for both reads and writes.
1074#[derive(Debug, Clone)]
1075pub struct Db {
1076    read_pool: SqlitePool,
1077    write_pool: SqlitePool,
1078}
1079
1080impl Db {
1081    /// Connects to a `SQLite` database with tuned WAL pragmas and split read/write pools.
1082    ///
1083    /// Creates the database file when missing and enables `foreign_keys = ON`, `synchronous = NORMAL`,
1084    /// `cache_size = -64000`, and `temp_store = MEMORY`. File-backed databases also enable
1085    /// `journal_mode = WAL`, `mmap_size = 268435456`, and a separate 16-connection read-only pool.
1086    /// Returns [`SlabError::Internal`] if `database_url` cannot be parsed.
1087    pub async fn connect(database_url: &str) -> SlabResult<Self> {
1088        let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");
1089
1090        let mut write_opts = SqliteConnectOptions::from_str(database_url)
1091            .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
1092            .create_if_missing(true)
1093            .foreign_keys(true)
1094            .busy_timeout(Duration::from_secs(10))
1095            .synchronous(SqliteSynchronous::Normal)
1096            .pragma("cache_size", "-64000")
1097            .pragma("temp_store", "MEMORY")
1098            .pragma("trusted_schema", "OFF")
1099            .pragma("secure_delete", "ON");
1100
1101        if !is_memory {
1102            write_opts = write_opts
1103                .journal_mode(SqliteJournalMode::Wal)
1104                .pragma("mmap_size", "268435456");
1105        }
1106
1107        // Single dedicated writer guarantees serialized writes without SQLITE_BUSY thrashing.
1108        let write_pool = SqlitePoolOptions::new()
1109            .max_connections(1)
1110            .acquire_timeout(Duration::from_secs(10))
1111            .connect_with(write_opts)
1112            .await?;
1113
1114        let read_pool = if is_memory {
1115            // In-memory SQLite databases are per-connection, so share the single pool in tests.
1116            write_pool.clone()
1117        } else {
1118            let read_opts = SqliteConnectOptions::from_str(database_url)
1119                .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
1120                .read_only(true)
1121                .foreign_keys(true)
1122                .busy_timeout(Duration::from_secs(5))
1123                .pragma("cache_size", "-64000")
1124                .pragma("temp_store", "MEMORY")
1125                .pragma("trusted_schema", "OFF")
1126                .pragma("mmap_size", "268435456");
1127
1128            SqlitePoolOptions::new()
1129                .max_connections(16)
1130                .acquire_timeout(Duration::from_secs(5))
1131                .connect_with(read_opts)
1132                .await?
1133        };
1134
1135        Ok(Self {
1136            read_pool,
1137            write_pool,
1138        })
1139    }
1140
1141    /// Returns the default pool, which aliases the single-connection writer pool.
1142    ///
1143    /// Prefer [`Db::reader`] for read-only `SELECT` queries so reads run concurrently on file-backed databases.
1144    #[must_use]
1145    pub fn pool(&self) -> &SqlitePool {
1146        &self.write_pool
1147    }
1148
1149    /// Returns the concurrent read-only WAL pool (up to 16 connections on file-backed databases).
1150    ///
1151    /// Use this pool for `SELECT` queries. Executing write statements on a file-backed reader pool fails.
1152    #[must_use]
1153    pub fn reader(&self) -> &SqlitePool {
1154        &self.read_pool
1155    }
1156
1157    /// Returns the dedicated single-connection writer pool (`max_connections(1)`).
1158    ///
1159    /// Serializes writes in-process with a 10-second `busy_timeout` to prevent `SQLITE_BUSY` thrashing.
1160    #[must_use]
1161    pub fn writer(&self) -> &SqlitePool {
1162        &self.write_pool
1163    }
1164
1165    /// Opens an explicit `BEGIN IMMEDIATE` transaction on the single writer connection.
1166    ///
1167    /// Acquires the write lock at transaction start, avoiding deferred lock-upgrade `SQLITE_BUSY_SNAPSHOT` errors.
1168    pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
1169        Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
1170    }
1171
1172    /// Ensures an existing `SQLite` system table has `column` (adding it if absent).
1173    async fn ensure_sqlite_column(
1174        &self,
1175        table: &str,
1176        column: &str,
1177        column_def: &str,
1178    ) -> SlabResult<()> {
1179        let query = format!("SELECT name FROM pragma_table_info('{table}')");
1180        let cols: Vec<(String,)> = sqlx::query_as(&query).fetch_all(&self.write_pool).await?;
1181        if !cols.is_empty() && !cols.iter().any(|(name,)| name == column) {
1182            let alter = format!("ALTER TABLE {table} ADD COLUMN {column} {column_def}");
1183            sqlx::raw_sql(&alter).execute(&self.write_pool).await?;
1184        }
1185        Ok(())
1186    }
1187
1188    /// Executes [`SYSTEM_SCHEMA_SQL`] against the writer pool to create all 12 system tables idempotently,
1189    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
1190    /// tables in place when needed.
1191    pub async fn init_system_tables(&self) -> SlabResult<()> {
1192        self.ensure_sqlite_column("slabs_jobs", "locked_until", "TEXT")
1193            .await?;
1194        self.ensure_sqlite_column("slabs_idempotency_keys", "expires_at", "TEXT")
1195            .await?;
1196        self.ensure_sqlite_column("slabs_blobs", "scope", "TEXT")
1197            .await?;
1198        self.ensure_sqlite_column(
1199            "slabs_incidents",
1200            "recent_occurrences_json",
1201            "TEXT NOT NULL DEFAULT '[]'",
1202        )
1203        .await?;
1204        sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
1205            .execute(&self.write_pool)
1206            .await?;
1207        Ok(())
1208    }
1209
1210    /// Creates system tables if missing and runs all pending migrations from `migrator` on the writer pool.
1211    ///
1212    /// Wraps migration failures in [`SlabError::Internal`].
1213    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
1214        self.init_system_tables().await?;
1215        migrator
1216            .run(&self.write_pool)
1217            .await
1218            .map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
1219        Ok(())
1220    }
1221
1222    /// Creates system tables if missing and runs all SQL migrations located in `dir` on the writer pool.
1223    ///
1224    /// Wraps directory load and migration failures in [`SlabError::Internal`].
1225    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
1226        self.init_system_tables().await?;
1227        let migrator = Migrator::new(dir)
1228            .await
1229            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
1230        self.migrate(&migrator).await
1231    }
1232
1233    /// Exports the current `SQLite` schema DDL from `sqlite_master` on the read pool.
1234    ///
1235    /// Excludes internal `sqlite_%` and `_sqlx_%` objects and orders statements by table, index, trigger, then view.
1236    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
1237        let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
1238            "SELECT type, name, sql
1239             FROM sqlite_master
1240             WHERE sql IS NOT NULL
1241               AND name NOT LIKE 'sqlite_%'
1242               AND name NOT LIKE '_sqlx_%'
1243             ORDER BY
1244               CASE type
1245                 WHEN 'table' THEN 1
1246                 WHEN 'index' THEN 2
1247                 WHEN 'trigger' THEN 3
1248                 WHEN 'view' THEN 4
1249                 ELSE 5
1250               END,
1251               name ASC",
1252        )
1253        .fetch_all(&self.read_pool)
1254        .await?;
1255
1256        let mut out = String::from(
1257            "-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
1258        );
1259        for (_kind, _name, sql) in rows {
1260            if let Some(stmt) = sql {
1261                out.push_str(stmt.trim());
1262                if !stmt.trim_end().ends_with(';') {
1263                    out.push(';');
1264                }
1265                out.push_str("\n\n");
1266            }
1267        }
1268        Ok(out)
1269    }
1270
1271    /// Reads a `.sql` file from disk and executes its statements atomically inside a `SQLite` transaction.
1272    ///
1273    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
1274    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
1275        let sql = std::fs::read_to_string(path).map_err(|e| {
1276            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
1277        })?;
1278        if sql.trim().is_empty() {
1279            return Ok(());
1280        }
1281        let mut tx = self.begin().await?;
1282        sqlx::raw_sql(&sql).execute(&mut *tx).await?;
1283        tx.commit().await?;
1284        Ok(())
1285    }
1286
1287    /// Executes `SELECT 1` against the read pool to verify database connectivity.
1288    pub async fn ping(&self) -> SlabResult<()> {
1289        let _: (i64,) = sqlx::query_as("SELECT 1")
1290            .fetch_one(&self.read_pool)
1291            .await?;
1292        Ok(())
1293    }
1294
1295    /// Runs `PRAGMA wal_checkpoint(TRUNCATE)` on the writer pool and cleanly closes
1296    /// both the reader and writer connection pools.
1297    ///
1298    /// Logs a warning if the checkpoint fails rather than panicking so graceful
1299    /// shutdown always completes cleanly.
1300    pub async fn checkpoint_and_close(&self) {
1301        if let Err(err) = sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
1302            .execute(&self.write_pool)
1303            .await
1304        {
1305            tracing::warn!(error = %err, "SQLite WAL checkpoint failed during shutdown");
1306        }
1307        self.read_pool.close().await;
1308        self.write_pool.close().await;
1309    }
1310
1311    /// Runs `SQLite` `EXPLAIN QUERY PLAN` for a single read-only `SELECT` or `WITH` statement
1312    /// against the read pool and returns each plan `detail` line.
1313    ///
1314    /// Rejects empty SQL, queries containing `;`, and statements not starting with `SELECT` or
1315    /// `WITH` (case-insensitive) with [`SlabError::BadRequest`].
1316    pub async fn explain_query_plan(&self, sql: &str) -> SlabResult<Vec<String>> {
1317        let trimmed = sql.trim();
1318        if trimmed.is_empty() {
1319            return Err(SlabError::bad_request("SQL query cannot be empty"));
1320        }
1321        if trimmed.contains(';') {
1322            return Err(SlabError::bad_request(
1323                "SQL query must be a single statement without semicolons",
1324            ));
1325        }
1326
1327        let starts_select = trimmed.len() > 6
1328            && trimmed
1329                .get(..6)
1330                .is_some_and(|p| p.eq_ignore_ascii_case("SELECT"))
1331            && trimmed
1332                .as_bytes()
1333                .get(6)
1334                .is_some_and(u8::is_ascii_whitespace);
1335        let starts_with = trimmed.len() > 4
1336            && trimmed
1337                .get(..4)
1338                .is_some_and(|p| p.eq_ignore_ascii_case("WITH"))
1339            && trimmed
1340                .as_bytes()
1341                .get(4)
1342                .is_some_and(u8::is_ascii_whitespace);
1343
1344        if !starts_select && !starts_with {
1345            return Err(SlabError::bad_request(
1346                "only read-only SELECT or WITH queries can be explained",
1347            ));
1348        }
1349
1350        let explain_sql = format!("EXPLAIN QUERY PLAN {trimmed}");
1351        let rows: Vec<(i64, i64, i64, String)> = sqlx::query_as(&explain_sql)
1352            .fetch_all(self.reader())
1353            .await?;
1354        Ok(rows.into_iter().map(|(_, _, _, detail)| detail).collect())
1355    }
1356}
1357
1358fn quote_pg_ident(ident: &str) -> String {
1359    format!("\"{}\"", ident.replace('"', "\"\""))
1360}
1361
1362/// Raw-SQL `PostgreSQL` database wrapper for multi-node deployments.
1363#[derive(Debug, Clone)]
1364pub struct PgDb {
1365    pool: PgPool,
1366}
1367
1368impl PgDb {
1369    /// Connects to a `PostgreSQL` database with up to 20 pooled connections, a 5-second acquire
1370    /// timeout, a 5-minute idle timeout, and a 30-minute maximum connection lifetime.
1371    pub async fn connect(database_url: &str) -> SlabResult<Self> {
1372        let pool = PgPoolOptions::new()
1373            .max_connections(20)
1374            .acquire_timeout(Duration::from_secs(5))
1375            .idle_timeout(Duration::from_secs(300))
1376            .max_lifetime(Duration::from_secs(1800))
1377            .connect(database_url)
1378            .await?;
1379        Ok(Self { pool })
1380    }
1381
1382    /// Returns the underlying `sqlx` `PostgreSQL` connection pool.
1383    #[must_use]
1384    pub fn pool(&self) -> &PgPool {
1385        &self.pool
1386    }
1387
1388    /// Begins a new `PostgreSQL` transaction on the pool.
1389    pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
1390        Ok(self.pool.begin().await?)
1391    }
1392
1393    /// Executes [`POSTGRES_SYSTEM_SCHEMA_SQL`] to create all 12 system tables idempotently,
1394    /// upgrading legacy `slabs_jobs`, `slabs_idempotency_keys`, `slabs_blobs`, and `slabs_incidents`
1395    /// tables in place when needed.
1396    pub async fn init_system_tables(&self) -> SlabResult<()> {
1397        sqlx::raw_sql(
1398            "ALTER TABLE IF EXISTS slabs_jobs ADD COLUMN IF NOT EXISTS locked_until TIMESTAMPTZ;
1399             ALTER TABLE IF EXISTS slabs_idempotency_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
1400             ALTER TABLE IF EXISTS slabs_blobs ADD COLUMN IF NOT EXISTS scope TEXT;
1401             ALTER TABLE IF EXISTS slabs_incidents ADD COLUMN IF NOT EXISTS recent_occurrences_json TEXT NOT NULL DEFAULT '[]';",
1402        )
1403        .execute(&self.pool)
1404        .await?;
1405        sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
1406            .execute(&self.pool)
1407            .await?;
1408        Ok(())
1409    }
1410
1411    /// Creates system tables if missing and runs all pending migrations from `migrator`.
1412    ///
1413    /// Wraps migration failures in [`SlabError::Internal`].
1414    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
1415        self.init_system_tables().await?;
1416        migrator
1417            .run(&self.pool)
1418            .await
1419            .map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
1420        Ok(())
1421    }
1422
1423    /// Creates system tables if missing and runs all SQL migrations located in `dir`.
1424    ///
1425    /// Wraps directory load and migration failures in [`SlabError::Internal`].
1426    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
1427        self.init_system_tables().await?;
1428        let migrator = Migrator::new(dir)
1429            .await
1430            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
1431        self.migrate(&migrator).await
1432    }
1433
1434    /// Exports `public` schema tables and indexes from `information_schema.columns` and `pg_indexes`.
1435    ///
1436    /// Excludes `_sqlx_%` internal migration tables.
1437    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
1438        let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
1439            "SELECT table_name, column_name, data_type, is_nullable, column_default
1440             FROM information_schema.columns
1441             WHERE table_schema = 'public'
1442               AND table_name NOT LIKE '_sqlx_%'
1443             ORDER BY table_name ASC, ordinal_position ASC",
1444        )
1445        .fetch_all(&self.pool)
1446        .await?;
1447
1448        let indexes: Vec<(String,)> = sqlx::query_as(
1449            "SELECT indexdef
1450             FROM pg_indexes
1451             WHERE schemaname = 'public'
1452               AND tablename NOT LIKE '_sqlx_%'
1453             ORDER BY tablename ASC, indexname ASC",
1454        )
1455        .fetch_all(&self.pool)
1456        .await?;
1457
1458        let mut out = String::from(
1459            "-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
1460        );
1461
1462        let mut current_table: Option<String> = None;
1463        for (table, col, dtype, nullable, default) in cols {
1464            if current_table.as_deref() == Some(table.as_str()) {
1465                out.push_str(",\n");
1466            } else {
1467                if current_table.is_some() {
1468                    out.push_str(");\n\n");
1469                }
1470                let quoted_table = quote_pg_ident(&table);
1471                let _ = writeln!(out, "CREATE TABLE {quoted_table} (");
1472                current_table = Some(table);
1473            }
1474            let quoted_col = quote_pg_ident(&col);
1475            let _ = write!(out, "    {quoted_col} {dtype}");
1476            if nullable == "NO" {
1477                out.push_str(" NOT NULL");
1478            }
1479            if let Some(def) = default {
1480                let _ = write!(out, " DEFAULT {def}");
1481            }
1482        }
1483        if current_table.is_some() {
1484            out.push_str("\n);\n\n");
1485        }
1486
1487        for (indexdef,) in indexes {
1488            out.push_str(&indexdef);
1489            if !indexdef.ends_with(';') {
1490                out.push(';');
1491            }
1492            out.push_str("\n\n");
1493        }
1494
1495        Ok(out)
1496    }
1497
1498    /// Reads a `.sql` file from disk and executes its statements against the `PostgreSQL` pool.
1499    ///
1500    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
1501    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
1502        let sql = std::fs::read_to_string(path).map_err(|e| {
1503            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
1504        })?;
1505        if sql.trim().is_empty() {
1506            return Ok(());
1507        }
1508        sqlx::raw_sql(&sql).execute(&self.pool).await?;
1509        Ok(())
1510    }
1511
1512    /// Executes `SELECT 1` against the `PostgreSQL` pool to verify database connectivity.
1513    pub async fn ping(&self) -> SlabResult<()> {
1514        let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
1515        Ok(())
1516    }
1517}
1518
1519#[cfg(test)]
1520mod tests {
1521    use super::*;
1522
1523    #[test]
1524    fn detects_sqlite_and_postgres_urls() {
1525        assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
1526        assert_eq!(
1527            DbEngine::detect("sqlite://app.db?mode=rwc"),
1528            DbEngine::Sqlite
1529        );
1530        assert_eq!(
1531            DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
1532            DbEngine::Postgres
1533        );
1534        assert_eq!(
1535            DbEngine::detect("postgresql://localhost/slabs"),
1536            DbEngine::Postgres
1537        );
1538    }
1539
1540    #[test]
1541    fn fts5_query_safely_quotes_user_input() {
1542        assert_eq!(
1543            fts5_query(r#"hello "world" fts5"#),
1544            Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
1545        );
1546        assert_eq!(fts5_query("   "), None);
1547    }
1548
1549    #[tokio::test]
1550    async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
1551        let path =
1552            std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
1553        let url = format!("sqlite://{}", path.display());
1554        let db = Db::connect(&url).await.unwrap();
1555        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
1556            .execute(db.writer())
1557            .await
1558            .unwrap();
1559
1560        let mut handles = Vec::new();
1561        // 24 concurrent writers using BEGIN IMMEDIATE + 24 concurrent readers on WAL read_pool
1562        for i in 0..24 {
1563            let db_w = db.clone();
1564            handles.push(tokio::spawn(async move {
1565                let mut tx = db_w.begin().await.unwrap();
1566                sqlx::query("INSERT INTO items (val) VALUES (?)")
1567                    .bind(format!("item-{i}"))
1568                    .execute(&mut *tx)
1569                    .await
1570                    .unwrap();
1571                tx.commit().await.unwrap();
1572            }));
1573
1574            let db_r = db.clone();
1575            handles.push(tokio::spawn(async move {
1576                let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
1577                    .fetch_one(db_r.reader())
1578                    .await
1579                    .unwrap();
1580            }));
1581        }
1582
1583        for h in handles {
1584            h.await.unwrap();
1585        }
1586
1587        let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
1588            .fetch_one(db.reader())
1589            .await
1590            .unwrap();
1591        assert_eq!(total, 24);
1592
1593        let _ = std::fs::remove_file(&path);
1594        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
1595        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
1596    }
1597
1598    #[test]
1599    fn pagination_clamps_limits_and_computes_fetch_limit() {
1600        let default_page = Pagination::default();
1601        assert_eq!(default_page.clamped_limit(20, 100), 20);
1602        assert_eq!(default_page.fetch_limit(20, 100), 21);
1603
1604        let zero_page = Pagination {
1605            limit: Some(0),
1606            cursor: None,
1607        };
1608        assert_eq!(zero_page.clamped_limit(20, 100), 1);
1609        assert_eq!(zero_page.fetch_limit(20, 100), 2);
1610
1611        let huge_page = Pagination {
1612            limit: Some(500),
1613            cursor: Some("cur_1".into()),
1614        };
1615        assert_eq!(huge_page.clamped_limit(20, 100), 100);
1616        assert_eq!(huge_page.fetch_limit(20, 100), 101);
1617        assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
1618    }
1619
1620    #[test]
1621    fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
1622        let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
1623        assert_eq!(page.items, vec![10, 20]);
1624        assert!(page.has_more);
1625        assert_eq!(page.next_cursor.as_deref(), Some("20"));
1626
1627        let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
1628        assert_eq!(exact.items, vec![10, 20]);
1629        assert!(!exact.has_more);
1630        assert!(exact.next_cursor.is_none());
1631
1632        let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
1633        assert_eq!(empty.items, Vec::<i32>::new());
1634        assert!(!empty.has_more);
1635        assert!(empty.next_cursor.is_none());
1636    }
1637
1638    #[tokio::test]
1639    async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
1640        let db = Db::connect("sqlite::memory:").await.unwrap();
1641        db.init_system_tables().await.unwrap();
1642        let audit = AuditLog::new(db.clone());
1643
1644        // Committed transaction persists audit entry
1645        let mut tx = db.begin().await.unwrap();
1646        let entry_id = audit
1647            .record_in_tx(
1648                &mut tx,
1649                Some("usr_1"),
1650                "room.created",
1651                "room",
1652                "room_1",
1653                &serde_json::json!({ "name": "Lobby" }),
1654            )
1655            .await
1656            .unwrap();
1657        assert!(entry_id.starts_with("aud_"));
1658        tx.commit().await.unwrap();
1659
1660        // Rolled back transaction does not persist audit entry
1661        let mut rollback_tx = db.begin().await.unwrap();
1662        let _rolled_back_id = audit
1663            .record_in_tx(
1664                &mut rollback_tx,
1665                Some("usr_2"),
1666                "room.deleted",
1667                "room",
1668                "room_1",
1669                &serde_json::json!({ "reason": "rolled back" }),
1670            )
1671            .await
1672            .unwrap();
1673        rollback_tx.rollback().await.unwrap();
1674
1675        // Second committed entry on another target to verify filtering
1676        let mut tx2 = db.begin().await.unwrap();
1677        let _other_id = audit
1678            .record_in_tx(
1679                &mut tx2,
1680                None,
1681                "user.invited",
1682                "user",
1683                "usr_9",
1684                &serde_json::json!({}),
1685            )
1686            .await
1687            .unwrap();
1688        tx2.commit().await.unwrap();
1689
1690        let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
1691        assert_eq!(room_entries.len(), 1);
1692        assert_eq!(room_entries[0].id, entry_id);
1693        assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
1694        assert_eq!(room_entries[0].action, "room.created");
1695        assert_eq!(room_entries[0].target_type, "room");
1696        assert_eq!(room_entries[0].target_id, "room_1");
1697        assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);
1698
1699        let recent = audit.list_recent(10).await.unwrap();
1700        assert_eq!(recent.len(), 2);
1701
1702        let recent_limited = audit.list_recent(1).await.unwrap();
1703        assert_eq!(recent_limited.len(), 1);
1704    }
1705
1706    #[tokio::test]
1707    async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
1708        let db = Db::connect("sqlite::memory:").await.unwrap();
1709        db.init_system_tables().await.unwrap();
1710
1711        let seed_path = std::env::temp_dir().join(format!(
1712            "slabs_seed_test_{}.sql",
1713            slabs_core::id::new("sql")
1714        ));
1715        std::fs::write(
1716            &seed_path,
1717            "CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
1718             INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
1719             INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
1720        )
1721        .unwrap();
1722
1723        db.execute_sql_file(&seed_path).await.unwrap();
1724        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
1725            .fetch_one(db.reader())
1726            .await
1727            .unwrap();
1728        assert_eq!(count, 2);
1729
1730        // Blank seed file is a no-op
1731        std::fs::write(&seed_path, "   \n\t  ").unwrap();
1732        db.execute_sql_file(&seed_path).await.unwrap();
1733        let _ = std::fs::remove_file(&seed_path);
1734
1735        // Missing file returns an internal error
1736        let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
1737        assert!(db.execute_sql_file(&missing).await.is_err());
1738
1739        // Both system schemas declare the new v0.2.0 system tables
1740        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1741        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1742        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1743        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1744    }
1745
1746    #[test]
1747    fn fts5_query_strips_control_chars_and_caps_tokens_and_lengths() {
1748        assert_eq!(
1749            fts5_query("hello\x00world \x07foo\x7fbar"),
1750            Some("\"helloworld\"* AND \"foobar\"*".to_string())
1751        );
1752        assert_eq!(fts5_query("\0\x01\x1f\x7f"), None);
1753
1754        // Cap at 16 tokens
1755        let many_tokens = (1..=25)
1756            .map(|i| format!("tok{i}"))
1757            .collect::<Vec<_>>()
1758            .join(" ");
1759        let rendered = fts5_query(&many_tokens).unwrap();
1760        assert_eq!(rendered.split(" AND ").count(), 16);
1761        assert!(rendered.contains("\"tok16\"*"));
1762        assert!(!rendered.contains("\"tok17\"*"));
1763
1764        // Cap each token to 64 chars
1765        let huge_token = "a".repeat(100);
1766        let rendered_long = fts5_query(&huge_token).unwrap();
1767        assert_eq!(rendered_long, format!("\"{}\"*", "a".repeat(64)));
1768    }
1769
1770    #[tokio::test]
1771    async fn init_system_tables_adds_locked_until_and_expires_at_and_upgrades_legacy_tables() {
1772        let db = Db::connect("sqlite::memory:").await.unwrap();
1773
1774        // Simulate legacy v0.2.0 tables without locked_until / expires_at
1775        sqlx::raw_sql(
1776            "CREATE TABLE slabs_jobs (
1777                id TEXT PRIMARY KEY NOT NULL,
1778                job_name TEXT NOT NULL,
1779                queue TEXT NOT NULL DEFAULT 'default',
1780                payload_json TEXT NOT NULL,
1781                status TEXT NOT NULL DEFAULT 'pending',
1782                attempts INTEGER NOT NULL DEFAULT 0,
1783                max_attempts INTEGER NOT NULL DEFAULT 5,
1784                run_at TEXT NOT NULL,
1785                last_error TEXT,
1786                created_at TEXT NOT NULL,
1787                updated_at TEXT NOT NULL
1788            );
1789            CREATE TABLE slabs_idempotency_keys (
1790                scope TEXT NOT NULL,
1791                key TEXT NOT NULL,
1792                response_json TEXT,
1793                created_at TEXT NOT NULL,
1794                PRIMARY KEY (scope, key)
1795            );
1796            CREATE TABLE slabs_blobs (
1797                id TEXT PRIMARY KEY NOT NULL,
1798                filename TEXT NOT NULL,
1799                content_type TEXT NOT NULL,
1800                byte_size INTEGER NOT NULL,
1801                checksum_sha256 TEXT NOT NULL,
1802                storage_key TEXT NOT NULL UNIQUE,
1803                created_at TEXT NOT NULL
1804            );
1805            CREATE TABLE slabs_incidents (
1806                id TEXT PRIMARY KEY,
1807                fingerprint TEXT NOT NULL UNIQUE,
1808                kind TEXT NOT NULL,
1809                source_file TEXT NOT NULL,
1810                route_pattern TEXT,
1811                status_code INTEGER,
1812                error_message TEXT NOT NULL,
1813                detail TEXT,
1814                context_json TEXT NOT NULL,
1815                git_sha TEXT,
1816                occurrences INTEGER NOT NULL DEFAULT 1,
1817                status TEXT NOT NULL DEFAULT 'open',
1818                resolved_in_sha TEXT,
1819                first_seen_at TEXT NOT NULL,
1820                last_seen_at TEXT NOT NULL
1821            );",
1822        )
1823        .execute(db.writer())
1824        .await
1825        .unwrap();
1826
1827        // Running init_system_tables twice should upgrade once and stay idempotent
1828        db.init_system_tables().await.unwrap();
1829        db.init_system_tables().await.unwrap();
1830
1831        let job_cols: Vec<(String,)> =
1832            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_jobs')")
1833                .fetch_all(db.reader())
1834                .await
1835                .unwrap();
1836        assert!(job_cols.iter().any(|(c,)| c == "locked_until"));
1837
1838        let idem_cols: Vec<(String,)> =
1839            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_idempotency_keys')")
1840                .fetch_all(db.reader())
1841                .await
1842                .unwrap();
1843        assert!(idem_cols.iter().any(|(c,)| c == "expires_at"));
1844
1845        let blob_cols: Vec<(String,)> =
1846            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_blobs')")
1847                .fetch_all(db.reader())
1848                .await
1849                .unwrap();
1850        assert!(blob_cols.iter().any(|(c,)| c == "scope"));
1851        assert!(SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
1852        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("scope TEXT"));
1853
1854        let incident_cols: Vec<(String,)> =
1855            sqlx::query_as("SELECT name FROM pragma_table_info('slabs_incidents')")
1856                .fetch_all(db.reader())
1857                .await
1858                .unwrap();
1859        assert!(
1860            incident_cols
1861                .iter()
1862                .any(|(c,)| c == "recent_occurrences_json"),
1863            "missing upgraded column recent_occurrences_json"
1864        );
1865        assert!(SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
1866        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("recent_occurrences_json"));
1867        for removed in ["assignee", "external_issue_key", "external_issue_url"] {
1868            assert!(!SYSTEM_SCHEMA_SQL.contains(removed));
1869            assert!(!POSTGRES_SYSTEM_SCHEMA_SQL.contains(removed));
1870        }
1871
1872        // Verify security pragmas
1873        let (trusted_schema,): (i64,) = sqlx::query_as("PRAGMA trusted_schema")
1874            .fetch_one(db.writer())
1875            .await
1876            .unwrap();
1877        assert_eq!(trusted_schema, 0);
1878
1879        let (secure_delete,): (i64,) = sqlx::query_as("PRAGMA secure_delete")
1880            .fetch_one(db.writer())
1881            .await
1882            .unwrap();
1883        assert_eq!(secure_delete, 1);
1884    }
1885
1886    #[tokio::test]
1887    async fn audit_log_clamps_limits_to_1_through_500() {
1888        let db = Db::connect("sqlite::memory:").await.unwrap();
1889        db.init_system_tables().await.unwrap();
1890        let audit = AuditLog::new(db.clone());
1891
1892        let mut tx = db.begin().await.unwrap();
1893        for i in 0..3 {
1894            audit
1895                .record_in_tx(
1896                    &mut tx,
1897                    Some("usr_1"),
1898                    "item.updated",
1899                    "item",
1900                    "item_1",
1901                    &serde_json::json!({ "n": i }),
1902                )
1903                .await
1904                .unwrap();
1905        }
1906        tx.commit().await.unwrap();
1907
1908        // Non-positive limits clamp up to 1 (never SQLite's unlimited -1)
1909        assert_eq!(audit.list_recent(-1).await.unwrap().len(), 1);
1910        assert_eq!(audit.list_recent(0).await.unwrap().len(), 1);
1911        assert_eq!(
1912            audit
1913                .list_for_target("item", "item_1", -5)
1914                .await
1915                .unwrap()
1916                .len(),
1917            1
1918        );
1919        assert_eq!(
1920            audit
1921                .list_for_target("item", "item_1", 0)
1922                .await
1923                .unwrap()
1924                .len(),
1925            1
1926        );
1927        // Huge limit clamps to 500 and still succeeds
1928        assert_eq!(audit.list_recent(10_000).await.unwrap().len(), 3);
1929    }
1930
1931    #[tokio::test]
1932    async fn execute_sql_file_rolls_back_on_error() {
1933        let db = Db::connect("sqlite::memory:").await.unwrap();
1934        sqlx::query("CREATE TABLE items (id TEXT PRIMARY KEY)")
1935            .execute(db.writer())
1936            .await
1937            .unwrap();
1938
1939        let seed_path = std::env::temp_dir().join(format!(
1940            "slabs_seed_rollback_{}.sql",
1941            slabs_core::id::new("sql")
1942        ));
1943        std::fs::write(
1944            &seed_path,
1945            "INSERT INTO items (id) VALUES ('ok_1');\n\
1946             INSERT INTO items (id) VALUES ('ok_1');\n",
1947        )
1948        .unwrap();
1949
1950        assert!(db.execute_sql_file(&seed_path).await.is_err());
1951        let _ = std::fs::remove_file(&seed_path);
1952
1953        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
1954            .fetch_one(db.reader())
1955            .await
1956            .unwrap();
1957        assert_eq!(count, 0);
1958    }
1959
1960    #[test]
1961    fn quote_pg_ident_escapes_double_quotes() {
1962        assert_eq!(quote_pg_ident("users"), "\"users\"");
1963        assert_eq!(quote_pg_ident("weird\"name"), "\"weird\"\"name\"");
1964    }
1965
1966    #[tokio::test]
1967    async fn incidents_record_deduplicate_list_get_resolve_and_reopen() {
1968        let db = Db::connect("sqlite::memory:").await.unwrap();
1969        db.init_system_tables().await.unwrap();
1970        let incidents = Incidents::new(db.clone());
1971
1972        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
1973        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_incidents"));
1974
1975        // Multibyte UTF-8 strings exceeding limits truncate cleanly on char boundaries
1976        let long_msg = "é".repeat(700); // 1400 bytes > 1024
1977        let long_detail = "€".repeat(2000); // 6000 bytes > 4096
1978
1979        let input = IncidentInput {
1980            kind: "panic".into(),
1981            source_file: "slabs/rooms/send_message.rs".into(),
1982            route_pattern: Some("/api/rooms/{room_id}/messages".into()),
1983            status_code: Some(500),
1984            error_message: long_msg.clone(),
1985            detail: Some(long_detail),
1986            context_json: serde_json::json!({ "request_id": "req_1" }),
1987            git_sha: Some("sha_aaa".into()),
1988            custom_fingerprint: None,
1989        };
1990
1991        let (first, is_new) = incidents.record(input.clone()).await.unwrap();
1992        assert!(is_new);
1993        assert!(first.id.starts_with("inc_"));
1994        assert_eq!(first.occurrences, 1);
1995        assert_eq!(first.status, "open");
1996        assert!(first.error_message.len() <= MAX_INCIDENT_ERROR_BYTES);
1997        assert!(first.detail.as_deref().unwrap().len() <= MAX_INCIDENT_DETAIL_BYTES);
1998        assert_eq!(incidents.count_open().await.unwrap(), 1);
1999
2000        // Second identical incident deduplicates and increments occurrences
2001        let mut second_input = input.clone();
2002        second_input.detail = Some("updated detail".into());
2003        second_input.git_sha = Some("sha_bbb".into());
2004        let (second, is_new_second) = incidents.record(second_input).await.unwrap();
2005        assert!(!is_new_second);
2006        assert_eq!(second.id, first.id);
2007        assert_eq!(second.occurrences, 2);
2008        assert_eq!(second.status, "open");
2009        assert_eq!(second.detail.as_deref(), Some("updated detail"));
2010        assert_eq!(second.git_sha.as_deref(), Some("sha_bbb"));
2011
2012        // Fetch by id
2013        let fetched = incidents.get(&first.id).await.unwrap().unwrap();
2014        assert_eq!(fetched.id, first.id);
2015        assert_eq!(fetched.occurrences, 2);
2016        assert!(incidents.get("inc_missing").await.unwrap().is_none());
2017
2018        // Resolve incident
2019        assert!(incidents.resolve(&first.id, Some("sha_fix")).await.unwrap());
2020        assert!(!incidents.resolve("inc_missing", None).await.unwrap());
2021        assert_eq!(incidents.count_open().await.unwrap(), 0);
2022        assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
2023        let resolved_list = incidents.list(Some("resolved"), 10).await.unwrap();
2024        assert_eq!(resolved_list.len(), 1);
2025        assert_eq!(resolved_list[0].resolved_in_sha.as_deref(), Some("sha_fix"));
2026
2027        // Re-occurring resolved incident transitions to "reopened" and returns is_new = true
2028        let (reopened, is_reopened) = incidents.record(input.clone()).await.unwrap();
2029        assert!(is_reopened);
2030        assert_eq!(reopened.id, first.id);
2031        assert_eq!(reopened.status, "reopened");
2032        assert_eq!(reopened.occurrences, 3);
2033        assert!(reopened.resolved_in_sha.is_none());
2034        assert_eq!(incidents.count_open().await.unwrap(), 1);
2035
2036        // Another occurrence while "reopened" keeps status "reopened" and returns is_new = false
2037        let (still_reopened, is_new_again) = incidents.record(input).await.unwrap();
2038        assert!(!is_new_again);
2039        assert_eq!(still_reopened.status, "reopened");
2040        assert_eq!(still_reopened.occurrences, 4);
2041
2042        // Listing with None / "active" / "reopened" / "all" filters accurately and clamps limits
2043        assert_eq!(incidents.list(None, -1).await.unwrap().len(), 1);
2044        assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 1);
2045        assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);
2046        assert!(incidents.list(Some("open"), 10).await.unwrap().is_empty());
2047        assert_eq!(incidents.list(Some("all"), 999).await.unwrap().len(), 1);
2048
2049        // Resolving a "reopened" incident transitions back to "resolved"
2050        assert!(incidents
2051            .resolve(&first.id, Some("sha_fix_2"))
2052            .await
2053            .unwrap());
2054        assert_eq!(incidents.count_open().await.unwrap(), 0);
2055        assert!(incidents.list(Some("active"), 10).await.unwrap().is_empty());
2056        assert!(incidents.list(None, 10).await.unwrap().is_empty());
2057        assert_eq!(incidents.list(Some("resolved"), 10).await.unwrap().len(), 1);
2058        assert_eq!(incidents.list(Some("all"), 10).await.unwrap().len(), 1);
2059    }
2060
2061    #[tokio::test]
2062    async fn incidents_record_with_outcome_lifecycle_and_user_bug_reports() {
2063        let db = Db::connect("sqlite::memory:").await.unwrap();
2064        db.init_system_tables().await.unwrap();
2065        let incidents = Incidents::new(db);
2066
2067        let base = IncidentInput {
2068            kind: "http_5xx".into(),
2069            source_file: "slabs/rooms/show.rs".into(),
2070            route_pattern: Some("/rooms/{id}".into()),
2071            status_code: Some(500),
2072            error_message: "boom".into(),
2073            detail: None,
2074            context_json: serde_json::json!({}),
2075            git_sha: Some("sha_1".into()),
2076            custom_fingerprint: None,
2077        };
2078
2079        let (rec1, outcome1) = incidents.record_with_outcome(base.clone()).await.unwrap();
2080        assert_eq!(outcome1, IncidentOutcome::Opened);
2081        assert_eq!(rec1.status, "open");
2082        assert_eq!(rec1.occurrences, 1);
2083
2084        let (rec2, outcome2) = incidents.record_with_outcome(base.clone()).await.unwrap();
2085        assert_eq!(outcome2, IncidentOutcome::Incremented);
2086        assert_eq!(rec2.id, rec1.id);
2087        assert_eq!(rec2.status, "open");
2088        assert_eq!(rec2.occurrences, 2);
2089
2090        assert!(incidents.resolve(&rec1.id, Some("sha_fix")).await.unwrap());
2091        let (rec3, outcome3) = incidents.record_with_outcome(base.clone()).await.unwrap();
2092        assert_eq!(outcome3, IncidentOutcome::Reopened);
2093        assert_eq!(rec3.id, rec1.id);
2094        assert_eq!(rec3.status, "reopened");
2095        assert_eq!(rec3.occurrences, 3);
2096        assert!(rec3.resolved_in_sha.is_none());
2097
2098        let (rec4, outcome4) = incidents.record_with_outcome(base).await.unwrap();
2099        assert_eq!(outcome4, IncidentOutcome::Incremented);
2100        assert_eq!(rec4.status, "reopened");
2101        assert_eq!(rec4.occurrences, 4);
2102
2103        assert!(incidents.resolve(&rec1.id, Some("sha_fix2")).await.unwrap());
2104        let resolved_row = incidents.get(&rec1.id).await.unwrap().unwrap();
2105        assert_eq!(resolved_row.status, "resolved");
2106        assert_eq!(resolved_row.resolved_in_sha.as_deref(), Some("sha_fix2"));
2107
2108        // User bug reports without custom_fingerprint create distinct open incidents
2109        let bug = IncidentInput {
2110            kind: "user_bug_report".into(),
2111            source_file: "slabs/rooms/show.rs".into(),
2112            route_pattern: Some("/rooms/1".into()),
2113            status_code: None,
2114            error_message: "Button does not respond".into(),
2115            detail: Some("Button does not respond".into()),
2116            context_json: serde_json::json!({ "reporter_user_id": "usr_1" }),
2117            git_sha: None,
2118            custom_fingerprint: None,
2119        };
2120        let (bug1, first_bug_outcome) = incidents.record_with_outcome(bug.clone()).await.unwrap();
2121        let (bug2, second_bug_outcome) = incidents.record_with_outcome(bug).await.unwrap();
2122        assert_eq!(first_bug_outcome, IncidentOutcome::Opened);
2123        assert_eq!(second_bug_outcome, IncidentOutcome::Opened);
2124        assert_ne!(bug1.id, bug2.id);
2125
2126        // Explicit custom_fingerprint deduplicates deterministically when reused
2127        let mut custom = IncidentInput {
2128            kind: "user_bug_report".into(),
2129            source_file: "slabs/rooms/show.rs".into(),
2130            route_pattern: None,
2131            status_code: None,
2132            error_message: "Grouped bug".into(),
2133            detail: None,
2134            context_json: serde_json::json!({}),
2135            git_sha: None,
2136            custom_fingerprint: Some("bug_group_key".into()),
2137        };
2138        let (c1, grouped_first) = incidents.record_with_outcome(custom.clone()).await.unwrap();
2139        let (c2, grouped_second) = incidents.record_with_outcome(custom.clone()).await.unwrap();
2140        assert_eq!(grouped_first, IncidentOutcome::Opened);
2141        assert_eq!(grouped_second, IncidentOutcome::Incremented);
2142        assert_eq!(c1.id, c2.id);
2143        assert_eq!(c2.occurrences, 2);
2144
2145        custom.custom_fingerprint = Some(slabs_core::id::new("bug"));
2146        let (c3, unique_custom) = incidents.record_with_outcome(custom).await.unwrap();
2147        assert_eq!(unique_custom, IncidentOutcome::Opened);
2148        assert_ne!(c3.id, c1.id);
2149    }
2150
2151    #[tokio::test]
2152    async fn explain_query_plan_detects_scan_vs_index_and_rejects_non_select_sql() {
2153        let db = Db::connect("sqlite::memory:").await.unwrap();
2154        sqlx::raw_sql(
2155            "CREATE TABLE messages (
2156                id TEXT PRIMARY KEY NOT NULL,
2157                room_id TEXT NOT NULL,
2158                body TEXT NOT NULL
2159            );
2160            CREATE INDEX idx_messages_room ON messages(room_id);",
2161        )
2162        .execute(db.writer())
2163        .await
2164        .unwrap();
2165
2166        // Unindexed filter -> full table SCAN
2167        let scan_plan = db
2168            .explain_query_plan("SELECT id FROM messages WHERE body = 'hello'")
2169            .await
2170            .unwrap();
2171        assert!(
2172            scan_plan.iter().any(|line| line.contains("SCAN messages")),
2173            "expected SCAN in plan: {scan_plan:?}"
2174        );
2175
2176        // Indexed filter -> SEARCH ... USING INDEX
2177        let index_plan = db
2178            .explain_query_plan("SELECT id FROM messages WHERE room_id = 'room_1'")
2179            .await
2180            .unwrap();
2181        assert!(
2182            index_plan
2183                .iter()
2184                .any(|line| line.contains("USING INDEX idx_messages_room")
2185                    || line.contains("USING COVERING INDEX idx_messages_room")),
2186            "expected USING INDEX in plan: {index_plan:?}"
2187        );
2188
2189        // CTE WITH query is permitted
2190        let cte_plan = db
2191            .explain_query_plan(
2192                "WITH r AS (SELECT id FROM messages WHERE room_id = 'r1') SELECT id FROM r",
2193            )
2194            .await
2195            .unwrap();
2196        assert!(
2197            cte_plan
2198                .iter()
2199                .any(|line| line.contains("idx_messages_room")),
2200            "expected idx_messages_room in CTE plan: {cte_plan:?}"
2201        );
2202
2203        // Reject empty, semicolons, and non-SELECT statements
2204        assert!(db.explain_query_plan("   ").await.is_err());
2205        assert!(db
2206            .explain_query_plan("SELECT 1; DROP TABLE messages")
2207            .await
2208            .is_err());
2209        assert!(db.explain_query_plan("DELETE FROM messages").await.is_err());
2210        assert!(db
2211            .explain_query_plan("UPDATE messages SET body = 'x'")
2212            .await
2213            .is_err());
2214        assert!(db
2215            .explain_query_plan("INSERT INTO messages VALUES ('1','r','b')")
2216            .await
2217            .is_err());
2218        assert!(db.explain_query_plan("DROP TABLE messages").await.is_err());
2219        assert!(db
2220            .explain_query_plan("PRAGMA table_info(messages)")
2221            .await
2222            .is_err());
2223    }
2224
2225    #[tokio::test]
2226    async fn incidents_ring_buffer_active_filtering_and_close_stale() {
2227        let db = Db::connect("sqlite::memory:").await.unwrap();
2228        db.init_system_tables().await.unwrap();
2229        let incidents = Incidents::new(db.clone());
2230
2231        // Record 12 occurrences of the same fingerprinted incident; ring buffer keeps last 10
2232        let mut inc_id = String::new();
2233        for idx in 1..=12 {
2234            let input = IncidentInput {
2235                kind: "http_5xx".into(),
2236                source_file: "slabs/orders/charge.rs".into(),
2237                route_pattern: Some("/api/orders/charge".into()),
2238                status_code: Some(500),
2239                error_message: "gateway timeout".into(),
2240                detail: Some(format!("attempt {idx}")),
2241                context_json: serde_json::json!({
2242                    "request_id": format!("req_{idx}"),
2243                    "latency_ms": idx * 100,
2244                }),
2245                git_sha: Some(format!("sha_{idx:02}")),
2246                custom_fingerprint: None,
2247            };
2248            let (rec, outcome) = incidents.record_with_outcome(input).await.unwrap();
2249            if idx == 1 {
2250                assert_eq!(outcome, IncidentOutcome::Opened);
2251                inc_id = rec.id.clone();
2252            } else {
2253                assert_eq!(outcome, IncidentOutcome::Incremented);
2254            }
2255            if idx == 12 {
2256                let history: Vec<serde_json::Value> =
2257                    serde_json::from_str(&rec.recent_occurrences_json).unwrap();
2258                assert_eq!(history.len(), 10);
2259                assert_eq!(history[0]["git_sha"], "sha_03");
2260                assert_eq!(history[0]["request_id"], "req_3");
2261                assert_eq!(history[0]["latency_ms"], 300);
2262                assert_eq!(history[9]["git_sha"], "sha_12");
2263                assert_eq!(history[9]["request_id"], "req_12");
2264                assert_eq!(history[9]["latency_ms"], 1200);
2265                assert!(history[9]["seen_at"].as_str().is_some());
2266            }
2267        }
2268
2269        // Resolve then recur -> transitions to "reopened" and clears resolved_in_sha
2270        assert!(incidents.resolve(&inc_id, Some("sha_fix")).await.unwrap());
2271        let recur_input = IncidentInput {
2272            kind: "http_5xx".into(),
2273            source_file: "slabs/orders/charge.rs".into(),
2274            route_pattern: Some("/api/orders/charge".into()),
2275            status_code: Some(500),
2276            error_message: "gateway timeout".into(),
2277            detail: None,
2278            context_json: serde_json::json!({ "request_id": "req_13", "latency_ms": 1300 }),
2279            git_sha: Some("sha_13".into()),
2280            custom_fingerprint: None,
2281        };
2282        let (reopened, outcome) = incidents
2283            .record_with_outcome(recur_input.clone())
2284            .await
2285            .unwrap();
2286        assert_eq!(outcome, IncidentOutcome::Reopened);
2287        assert_eq!(reopened.status, "reopened");
2288        assert!(reopened.resolved_in_sha.is_none());
2289
2290        // Add a second fresh "open" incident so active = 1 open + 1 reopened = 2
2291        let fresh_input = IncidentInput {
2292            kind: "slow_request".into(),
2293            source_file: "slabs/orders/list.rs".into(),
2294            route_pattern: Some("/api/orders".into()),
2295            status_code: Some(200),
2296            error_message: "slow query".into(),
2297            detail: None,
2298            context_json: serde_json::json!({ "latency_ms": 900 }),
2299            git_sha: Some("sha_13".into()),
2300            custom_fingerprint: None,
2301        };
2302        let (fresh, fresh_outcome) = incidents.record_with_outcome(fresh_input).await.unwrap();
2303        assert_eq!(fresh_outcome, IncidentOutcome::Opened);
2304
2305        assert_eq!(incidents.count_open().await.unwrap(), 2);
2306        assert_eq!(incidents.list(Some("active"), 10).await.unwrap().len(), 2);
2307        assert_eq!(incidents.list(None, 10).await.unwrap().len(), 2);
2308        assert_eq!(incidents.list(Some("open"), 10).await.unwrap().len(), 1);
2309        assert_eq!(incidents.list(Some("reopened"), 10).await.unwrap().len(), 1);
2310
2311        // Age the reopened incident past 30 days (45 days old)
2312        let old_ts = format_utc_micros(chrono::Utc::now() - chrono::Duration::days(45));
2313        sqlx::query("UPDATE slabs_incidents SET last_seen_at = ? WHERE id = ?")
2314            .bind(&old_ts)
2315            .bind(&inc_id)
2316            .execute(db.writer())
2317            .await
2318            .unwrap();
2319
2320        // close_stale(0) is a no-op
2321        assert_eq!(incidents.close_stale(0).await.unwrap(), 0);
2322        assert_eq!(incidents.count_open().await.unwrap(), 2);
2323
2324        // close_stale(30) auto-resolves only the stale incident and stamps 'auto:stale'
2325        assert_eq!(incidents.close_stale(30).await.unwrap(), 1);
2326        assert_eq!(incidents.count_open().await.unwrap(), 1);
2327        let stale_closed = incidents.get(&inc_id).await.unwrap().unwrap();
2328        assert_eq!(stale_closed.status, "resolved");
2329        assert_eq!(stale_closed.resolved_in_sha.as_deref(), Some("auto:stale"));
2330        let still_fresh = incidents.get(&fresh.id).await.unwrap().unwrap();
2331        assert_eq!(still_fresh.status, "open");
2332
2333        // If the stale-closed incident recurs, it transitions to "reopened" with resolved_in_sha cleared
2334        let (reopened_after_stale, outcome_after_stale) =
2335            incidents.record_with_outcome(recur_input).await.unwrap();
2336        assert_eq!(outcome_after_stale, IncidentOutcome::Reopened);
2337        assert_eq!(reopened_after_stale.status, "reopened");
2338        assert!(reopened_after_stale.resolved_in_sha.is_none());
2339        assert_eq!(incidents.count_open().await.unwrap(), 2);
2340    }
2341
2342    #[tokio::test]
2343    async fn db_checkpoint_and_close_flushes_wal_and_closes_pools() {
2344        let path = std::env::temp_dir().join(format!(
2345            "slabs_checkpoint_close_{}.db",
2346            slabs_core::id::new("db")
2347        ));
2348        let url = format!("sqlite://{}", path.display());
2349        let db = Db::connect(&url).await.unwrap();
2350        db.init_system_tables().await.unwrap();
2351
2352        let mut tx = db.begin().await.unwrap();
2353        sqlx::query("CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)")
2354            .execute(&mut *tx)
2355            .await
2356            .unwrap();
2357        sqlx::query("INSERT INTO notes (id, body) VALUES ('n_1', 'hello wal')")
2358            .execute(&mut *tx)
2359            .await
2360            .unwrap();
2361        tx.commit().await.unwrap();
2362
2363        // Exercise reader pool before shutdown
2364        let (before,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM notes")
2365            .fetch_one(db.reader())
2366            .await
2367            .unwrap();
2368        assert_eq!(before, 1);
2369
2370        db.checkpoint_and_close().await;
2371        assert!(db.reader().is_closed());
2372        assert!(db.pool().is_closed());
2373
2374        // Re-open the database file and verify data is durably persisted
2375        let reopened = Db::connect(&url).await.unwrap();
2376        let (body,): (String,) = sqlx::query_as("SELECT body FROM notes WHERE id = 'n_1'")
2377            .fetch_one(reopened.reader())
2378            .await
2379            .unwrap();
2380        assert_eq!(body, "hello wal");
2381        reopened.checkpoint_and_close().await;
2382
2383        let _ = std::fs::remove_file(&path);
2384        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
2385        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
2386    }
2387}