Skip to main content

spg_embedded/
lib.rs

1// v7.7.2 — every public item in this crate must carry a
2// doc-comment; new code that adds a `pub` without one fails CI.
3#![deny(missing_docs)]
4
5//! # spg-embedded
6//!
7//! Ergonomic embedded-mode entry point for SPG. Wraps the
8//! `spg-engine` execution layer for in-process applications
9//! that don't want to spin up a TCP listener / fork to the
10//! `spg-server` binary.
11//!
12//! ## Quick start
13//!
14//! ```no_run
15//! use spg_embedded::Database;
16//!
17//! // On-disk, durable. WAL fsynced per commit; auto-checkpoint
18//! // at 4 MiB WAL by default.
19//! let mut db = Database::open_path("/data/app.db").unwrap();
20//! db.execute("CREATE TABLE users (id INT NOT NULL, name TEXT)").unwrap();
21//! db.execute("INSERT INTO users VALUES (1, 'alice')").unwrap();
22//! let rows = db.query("SELECT name FROM users WHERE id = 1").unwrap();
23//! for row in &rows {
24//!     println!("{:?}", row);
25//! }
26//! ```
27//!
28//! ## Production checklist (v7.5)
29//!
30//! - **Persistence**: `Database::open_path(p)` writes a
31//!   crash-consistent WAL + periodic checkpoint snapshot. The
32//!   on-disk format is byte-identical to what `spg-server`
33//!   produces, so a database can move between modes without
34//!   conversion.
35//! - **Durability**: every `execute()` that mutates calls
36//!   `fsync` before returning `Ok`. There is no group commit
37//!   in embedded mode — every commit pays one fsync. If you
38//!   need batch throughput, wrap multiple statements in
39//!   [`Database::with_transaction`] which fsyncs only at
40//!   commit.
41//! - **Concurrency**: [`Database`] is `Send` but **not** `Sync`.
42//!   Share across threads via `Arc<Mutex<Database>>`. The
43//!   single-writer model is intentional — see
44//!   [STABILITY § A1](https://github.com/lihao/spg/blob/master/STABILITY.md).
45//! - **Background work**: [`Database::spawn_background_freezer`]
46//!   moves cold rows to disk-resident segments while you keep
47//!   serving requests. It runs in a dedicated thread; drop the
48//!   returned [`FreezerHandle`] (or call `stop()`) for clean
49//!   shutdown.
50//! - **Errors**: all public enums ([`EngineError`],
51//!   [`QueryResult`], [`Value`]) are `#[non_exhaustive]`. Match
52//!   them with a wildcard arm so future v7.x releases can add
53//!   variants without breaking your code.
54//!
55//! ## Panic contract
56//!
57//! - **No `execute()` / `query()` call panics on user input.**
58//!   Malformed SQL, type mismatches, missing tables — all
59//!   return `Err(EngineError::…)`. If you observe a panic on
60//!   a user-controlled string, that is a bug; file an issue.
61//! - The library panics **only** on internal invariant
62//!   violations (e.g., catalog snapshot magic mismatch, WAL
63//!   record CRC sentinel corruption that survived the boot-
64//!   time validation). These represent silent disk corruption
65//!   and an unwind would leak inconsistent state, so the
66//!   release profile uses `panic = abort` — your host process
67//!   dies fast rather than continuing on poisoned data.
68//! - If you cannot tolerate `panic = abort`, build with
69//!   `--profile release-dbg` (keeps unwind tables) and use
70//!   `std::panic::catch_unwind` at your application boundary.
71//!
72//! ## Why a separate crate?
73//!
74//! `spg-engine` is `no_std`-compatible (vendored alloc-only).
75//! The embedded-mode entry point uses `std` (filesystem,
76//! threading), so it lives in its own crate to keep the
77//! `no_std` boundary clean.
78
79pub use spg_engine::{CatalogSnapshot, Engine, EngineError, ParsedStatement, QueryResult};
80pub use spg_storage::{ColumnSchema, DataType, Value, ValueOwned};
81
82/// v7.16.0 — handle for a parsed-and-planned SQL statement.
83/// Hand off to [`Database::execute_prepared`] / [`Database::query_prepared`]
84/// with a `&[Value]` slice carrying the bind parameters (PG-style
85/// `$1`, `$2`, … positional). Cheap to `Clone`; the underlying AST
86/// is shared by handle copies and cloned per bind call by the
87/// engine's executor.
88///
89/// The handle holds a snapshot of the AST at prepare time. If
90/// the engine's plan cache evicts the entry between prepare and
91/// execute (e.g. ANALYZE bumps the statistics version) the
92/// stored AST keeps working — `execute_prepared` operates on
93/// the handle's clone, not the cache entry.
94#[derive(Debug, Clone)]
95pub struct Statement {
96    /// The parsed + planned AST. `spg-engine::prepare_cached`
97    /// returns it as a clone of the cached plan, so any rewrite
98    /// passes (`expand_group_by_all`, `reorder_joins`, …) have
99    /// already run.
100    pub(crate) stmt: ParsedStatement,
101    /// Original SQL source, kept for `Display` / debug only.
102    /// WAL persistence renders from the AST so a bind-time
103    /// rewrite of `$1..$N` survives replay.
104    pub(crate) sql: String,
105}
106
107impl Statement {
108    /// Borrow the original SQL source — useful for tracing and
109    /// debug logs. WAL replay does NOT use this; it serialises
110    /// the bind-final AST instead.
111    #[must_use]
112    pub fn sql(&self) -> &str {
113        &self.sql
114    }
115}
116
117/// v7.16.0 — internal WAL helper. Mirrors what
118/// `Engine::execute_prepared` does to the cloned AST so the WAL
119/// record carries the bind-final SQL text (so replay's
120/// simple-query path reconstructs the same row state without
121/// needing the original `Statement` handle to still be alive).
122/// Errors from the underlying engine helper would only fire if
123/// the bind-final stmt referenced a placeholder past the params
124/// slice — and that case has already errored in the executor
125/// above before this helper runs, so we discard the Result here.
126fn wal_render_with_params(stmt: &mut ParsedStatement, params: &[Value<'static>]) {
127    let _ = spg_engine::substitute_placeholders(stmt, params);
128}
129
130use std::collections::BTreeMap;
131use std::fs::{File, OpenOptions};
132use std::io::Write;
133use std::path::{Path, PathBuf};
134use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
135use std::sync::{Arc, Condvar, Mutex};
136use std::thread::{self, JoinHandle};
137use std::time::{Duration, SystemTime, UNIX_EPOCH};
138
139/// v7.11.3 — wall-clock provider injected into every embedded
140/// `Engine`. Microseconds since the Unix epoch; clamps to
141/// `i64::MAX` if the system clock is far-future. Used by SQL's
142/// `NOW()` / `CURRENT_TIMESTAMP` / `CURRENT_DATE` rewrite layer
143/// so PG-idiomatic time queries work without the caller wiring
144/// their own clock.
145/// v7.36 (mailrs ask #4) — flatten an `EXPLAIN` QueryResult into
146/// the QUERY PLAN string lines. `EXPLAIN` always returns a single-
147/// column TEXT table; anything else is treated as no plan output.
148fn extract_query_plan_lines(result: QueryResult) -> Vec<String> {
149    match result {
150        QueryResult::Rows { rows, .. } => rows
151            .into_iter()
152            .filter_map(|r| {
153                r.values.into_iter().next().and_then(|v| match v {
154                    Value::Text(s) => Some(s.into_owned()),
155                    _ => None,
156                })
157            })
158            .collect(),
159        _ => Vec::new(),
160    }
161}
162
163/// v7.37.2 — auto-warm the OS page cache for cold-tier segments at
164/// `open_path` / `restore` time. Per the zero-customer-change rule
165/// the client never calls `warm_up_cold_tier()` from app code; the
166/// catalog is server-ready when its constructor returns.
167///
168/// Budget controls:
169/// * `SPG_WARM_UP_COLD_BUDGET_MS=N` — stop warming after N ms
170///   wall-clock (best-effort; granularity is per-table). Unset =
171///   no cap.
172/// * `SPG_WARM_UP_COLD_BUDGET_MS=0` — skip warm-up entirely (escape
173///   hatch for ops that need fast restart even at the cost of the
174///   first-query cold spike).
175fn autowarm_cold_tier_on_open(db: &Database) {
176    let budget_ms = std::env::var("SPG_WARM_UP_COLD_BUDGET_MS")
177        .ok()
178        .and_then(|s| s.parse::<u64>().ok());
179    if let Some(0) = budget_ms {
180        return;
181    }
182    let start = std::time::Instant::now();
183    let touched = db.warm_up_cold_tier();
184    let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
185    let over_budget = budget_ms.is_some_and(|b| elapsed_ms > b);
186    let _ = (touched, over_budget); // future: tracing::info
187}
188
189fn wall_clock_micros() -> i64 {
190    SystemTime::now()
191        .duration_since(UNIX_EPOCH)
192        .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
193}
194
195use spg_manifest::{CatalogManifest, ColdSegmentEntry, manifest_path as spg_manifest_path};
196
197// -- v7.1 WAL format constants (mirror `spg-server`'s) ---------
198// Kept private so callers can't mis-frame records; the v3 layout
199// is the same the server uses, so a `spg-server` boot can read a
200// database an embedded process wrote and vice versa.
201const WAL_V2_SENTINEL: u32 = 0x8000_0000;
202const WAL_V3_FLAG: u32 = 0x4000_0000;
203const WAL_V3_TYPE_AUTO_COMMIT_SQL: u8 = 0x01;
204/// v7.18 — durability checkpoint marker stays at 0x02 (skipped on replay).
205const WAL_V3_TYPE_DURABILITY_CHECKPOINT: u8 = 0x02;
206/// v7.18 PITR — auto-commit-sql record with appended (commit_lsn,
207/// commit_unix_us) fields so replay can target a specific point in
208/// time. Backward-compat: v3 records (type 0x01) keep working, the
209/// envelope flag bits are unchanged. The new type byte is the
210/// schema-version discriminator.
211const WAL_V4_TYPE_AUTO_COMMIT_SQL: u8 = 0x10;
212/// v7.18 — sentinel for "no wall clock" inside a v4 record's
213/// commit_unix_us slot. Restore-to-timestamp skips records with
214/// this sentinel (no time anchor); LSN-based restore is
215/// unaffected.
216const WAL_V4_NO_CLOCK: i64 = i64::MIN;
217/// v7.18 — extra header bytes after the type byte in a v4 record:
218/// 8 bytes commit_lsn (u64 LE) + 8 bytes commit_unix_us (i64 LE).
219const WAL_V4_EXTRA_HEADER: usize = 16;
220/// v7.18 PITR — checkpoint anchor record written to the WAL *before*
221/// the snapshot file replaces the on-disk catalog. Carries the
222/// (lsn, ts, snapshot_path) triple so restore tooling can find the
223/// matching base snapshot without scanning the filesystem. Replay
224/// dispatch skips it (same as the v3 durability marker).
225const WAL_V4_TYPE_CHECKPOINT_MARKER: u8 = 0x11;
226
227/// v7.21 (mailrs embed round-12 polish) — one COMMITted explicit
228/// transaction, flushed atomically at COMMIT time. Payload = the
229/// transaction's bind-final mutation statements joined with `";\n"`;
230/// replay re-splits via [`split_statements`] and applies in order.
231/// Same 16-byte (commit_lsn, commit_unix_us) prefix as the v4
232/// auto-commit record. The record is CRC-framed like every other
233/// record, so replay applies the whole transaction or — torn tail —
234/// none of it; a transaction can never half-resurrect.
235///
236/// Why it exists: in-transaction mutations only touch the engine's
237/// shadow catalog (`modified_catalog: false`), so the per-statement
238/// auto-commit append never fired and a COMMIT followed by a crash
239/// (no graceful Drop checkpoint) lost the transaction.
240const WAL_V4_TYPE_TX_COMMIT_SQL: u8 = 0x12;
241
242/// v7.34 (crash-recovery P0 #2) — row-level physical redo record. Same v4
243/// envelope (lsn + ts + payload + CRC) but the payload is `encode_redo_log`
244/// bytes, not SQL. Replay applies the physical [`RowChange`]s via
245/// `Engine::apply_redo` instead of re-executing — O(changed rows), not the
246/// O(records × catalog_rows) statement-replay that hung the mailrs P0.
247const WAL_V5_TYPE_ROW_REDO: u8 = 0x13;
248
249/// v7.1 — auto-checkpoint threshold. Once the WAL grows past
250/// this many bytes, the next successful `execute()` call ends
251/// with a `checkpoint()` so the WAL stays bounded. Tunable via
252/// `SPG_EMBEDDED_CHECKPOINT_BYTES` env.
253/// v7.34 (crash-recovery P0 #2) — opt-in row-level redo WAL records.
254/// Default OFF during bringup; `SPG_WAL_ROW_REDO=1` makes mutating
255/// statements log physical changes (0x13) instead of SQL, so crash
256/// recovery applies them in O(changed rows) rather than re-executing in
257/// O(records × catalog_rows) (the superlinear replay hang root-caused on
258/// the mailrs P0). DDL still logs as SQL (hybrid log). When this returns
259/// true, `open_path` arms the engine's redo capture.
260fn row_redo_enabled() -> bool {
261    std::env::var("SPG_WAL_ROW_REDO")
262        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
263        .unwrap_or(false)
264}
265
266fn default_checkpoint_threshold_bytes() -> u64 {
267    std::env::var("SPG_EMBEDDED_CHECKPOINT_BYTES")
268        .ok()
269        .and_then(|s| s.parse::<u64>().ok())
270        .filter(|&n| n > 0)
271        .unwrap_or(4 * 1024 * 1024)
272}
273
274/// v7.30.3 (mailrs round-26) — per-query byte budget on join/filter
275/// materialisation, default ON at 256 MiB for embed parity with the
276/// server's allocator-level `SPG_MAX_QUERY_BYTES` default. A fat
277/// backfill batch (1000 × full mail bodies) then errors with
278/// `QueryBytesExceeded` instead of walking the host into reclaim
279/// livelock. `SPG_MAX_QUERY_BYTES=0` disables; any other value
280/// overrides. NOT applied to the WAL-replay engine — replay must
281/// never fail on a tuning knob.
282fn engine_with_query_byte_budget(engine: Engine) -> Engine {
283    const DEFAULT_MAX_QUERY_BYTES: usize = 256 * 1024 * 1024;
284    match std::env::var("SPG_MAX_QUERY_BYTES")
285        .ok()
286        .and_then(|s| s.trim().parse::<usize>().ok())
287    {
288        Some(0) => engine,
289        Some(n) => engine.with_max_query_bytes(n),
290        None => engine.with_max_query_bytes(DEFAULT_MAX_QUERY_BYTES),
291    }
292}
293
294/// v7.1 — encode one v3 `auto_commit_sql` record. Layout:
295///
296/// ```text
297/// [u32 LE (len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
298/// [u32 LE crc32 over (type_byte || sql_bytes)]
299/// [u8 type = 0x01]
300/// [sql bytes]
301/// ```
302fn encode_v3_auto_commit(sql: &str) -> Vec<u8> {
303    let payload = sql.as_bytes();
304    let mut crc_buf = Vec::with_capacity(1 + payload.len());
305    crc_buf.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
306    crc_buf.extend_from_slice(payload);
307    let crc = spg_crypto::crc32::crc32(&crc_buf);
308    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
309    let mut out = Vec::with_capacity(4 + 4 + 1 + payload.len());
310    out.extend_from_slice(&header);
311    out.extend_from_slice(&crc.to_le_bytes());
312    out.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
313    out.extend_from_slice(payload);
314    out
315}
316
317/// v7.20 P2 — WAL group-commit. N concurrent commits share one
318/// fsync (the 4.2 ms p50 that profile_breakdown measured as
319/// 99.2% of the durable write path).
320///
321/// Leader-follower protocol, same family as PG's group commit:
322///
323/// 1. `enqueue(record)` — called while the caller still holds
324///    the engine's write lock. Appends the encoded record to the
325///    shared buffer, returns a sequence ticket. O(memcpy).
326/// 2. Caller RELEASES the engine write lock (the next writer's
327///    mutation proceeds in parallel with this batch's fsync).
328/// 3. `wait_flushed(seq)` — if nobody is flushing, the caller
329///    elects itself leader: swaps the buffer out, writes +
330///    fsyncs ONCE for every record in the batch, marks the
331///    batch durable, wakes all followers. Otherwise it parks on
332///    the condvar until a leader covers its seq.
333///
334/// Durability contract is unchanged from v7.19: `execute()`
335/// does not return Ok until the record that describes its
336/// mutation is fsynced. The only change is N callers sharing
337/// one fsync instead of paying one each.
338///
339/// Lock order (deadlock-free): `state` then `file`; never the
340/// reverse. The leader holds `file` WITHOUT `state` during IO so
341/// enqueues continue while fsync runs.
342#[derive(Debug)]
343struct WalGroup {
344    state: Mutex<WalGroupState>,
345    cond: std::sync::Condvar,
346    /// Active chunk file handle. Separate lock from `state` so
347    /// the leader's write+fsync doesn't block concurrent
348    /// enqueues. Swapped by `checkpoint()` at rotation.
349    file: Mutex<File>,
350}
351
352#[derive(Debug)]
353struct WalGroupState {
354    /// Encoded records awaiting flush.
355    buf: Vec<u8>,
356    /// Monotonic enqueue counter (1-based).
357    enqueued_seq: u64,
358    /// Highest seq whose record is fsynced.
359    flushed_seq: u64,
360    /// True while some caller is inside the leader IO section.
361    leader_active: bool,
362    /// Sticky fatal error — a failed fsync poisons the WAL
363    /// (loud, never silent). All current + future waiters error.
364    failed: Option<String>,
365    /// Bytes written to the active chunk since rotation —
366    /// drives the auto-checkpoint trigger.
367    written_len: u64,
368}
369
370/// Ticket returned by the buffered write path; `wait()` blocks
371/// until the record it covers is durable (or the WAL is
372/// poisoned). Cheap to move across threads.
373#[derive(Debug)]
374pub struct WalTicket {
375    group: Arc<WalGroup>,
376    seq: u64,
377}
378
379/// v7.34 (crash-recovery P0 #2) — RAII reset for the WalGroup leader
380/// flag. Electing a leader sets `leader_active = true` and releases the
381/// state lock for the sleep+IO window; if a panic unwinds through that
382/// window the flag would stay true and every follower would park forever
383/// on the condvar — no one left to flush or wake them, the same
384/// total-write hang an unclean stop causes, but self-inflicted. This
385/// guard clears the flag and wakes the followers (so one re-elects) on
386/// ANY drop, including a panic unwind; the normal path disarms it after
387/// resetting the flag itself.
388struct LeaderGuard<'a> {
389    group: &'a WalGroup,
390    armed: bool,
391}
392
393impl Drop for LeaderGuard<'_> {
394    fn drop(&mut self) {
395        if self.armed {
396            let mut g = self.group.state.lock().unwrap_or_else(|e| e.into_inner());
397            g.leader_active = false;
398            drop(g);
399            self.group.cond.notify_all();
400        }
401    }
402}
403
404impl WalGroup {
405    fn new(file: File, initial_len: u64) -> Self {
406        Self {
407            state: Mutex::new(WalGroupState {
408                buf: Vec::new(),
409                enqueued_seq: 0,
410                flushed_seq: 0,
411                leader_active: false,
412                failed: None,
413                written_len: initial_len,
414            }),
415            cond: std::sync::Condvar::new(),
416            file: Mutex::new(file),
417        }
418    }
419
420    /// Append `record` to the pending batch. Returns the seq the
421    /// caller must wait on. Called under the engine write lock —
422    /// keep it O(memcpy).
423    fn enqueue(&self, record: &[u8]) -> u64 {
424        let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner());
425        g.buf.extend_from_slice(record);
426        g.enqueued_seq += 1;
427        g.enqueued_seq
428    }
429
430    /// Block until `seq` is durable. Leader-follower: the first
431    /// arriving waiter flushes for everyone.
432    fn wait_flushed(&self, seq: u64) -> Result<(), EngineError> {
433        let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner());
434        loop {
435            if let Some(e) = &g.failed {
436                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
437                    format!("WAL poisoned by earlier flush failure: {e}"),
438                )));
439            }
440            if g.flushed_seq >= seq {
441                return Ok(());
442            }
443            if !g.leader_active {
444                // Elect self leader.
445                g.leader_active = true;
446                drop(g);
447                // v7.34 — panic-safety: if anything below unwinds before
448                // `leader_active` is reset, this guard releases it +
449                // wakes a follower to re-elect (else all writers park
450                // forever). Disarmed on the normal path after the reset.
451                let mut leader_guard = LeaderGuard {
452                    group: self,
453                    armed: true,
454                };
455                // v7.20 — commit_delay (PG's same-named knob):
456                // before taking the batch, give in-flight
457                // writers a short window to enqueue so the
458                // shared fsync covers more commits. 150 µs costs
459                // ~3.5% on a solo 4.2 ms fsync but multiplies
460                // batch size under load. Tunable via
461                // SPG_COMMIT_DELAY_US (0 disables).
462                let delay = commit_delay_us();
463                if delay > 0 {
464                    std::thread::sleep(std::time::Duration::from_micros(delay));
465                }
466                let (batch, flush_to) = {
467                    let mut g2 = self.state.lock().unwrap_or_else(|e| e.into_inner());
468                    (core::mem::take(&mut g2.buf), g2.enqueued_seq)
469                };
470                let io_result: std::io::Result<()> = (|| {
471                    let mut f = self.file.lock().unwrap_or_else(|e| e.into_inner());
472                    f.write_all(&batch)?;
473                    f.sync_data()
474                })();
475                g = self.state.lock().unwrap_or_else(|e| e.into_inner());
476                g.leader_active = false;
477                leader_guard.armed = false; // normal completion — disarm
478                match io_result {
479                    Ok(()) => {
480                        g.flushed_seq = flush_to;
481                        g.written_len = g.written_len.saturating_add(batch.len() as u64);
482                    }
483                    Err(e) => {
484                        g.failed = Some(e.to_string());
485                    }
486                }
487                self.cond.notify_all();
488                //
489
490                // Loop continues: either our seq is now covered
491                // (leader path normally returns next iteration)
492                // or the error branch surfaces.
493                continue;
494            }
495            g = self.cond.wait(g).unwrap_or_else(|e| e.into_inner());
496        }
497    }
498
499    /// Drain the pending batch + flush synchronously. Caller must
500    /// guarantee no concurrent enqueues (checkpoint holds the
501    /// engine exclusively). Used before rotation so the marker
502    /// lands in the right chunk.
503    fn flush_now(&self) -> Result<(), EngineError> {
504        let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner());
505        if let Some(e) = &g.failed {
506            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
507                format!("WAL poisoned: {e}"),
508            )));
509        }
510        let batch = core::mem::take(&mut g.buf);
511        let flush_to = g.enqueued_seq;
512        if batch.is_empty() {
513            return Ok(());
514        }
515        drop(g);
516        let io: std::io::Result<()> = (|| {
517            let mut f = self.file.lock().unwrap_or_else(|e| e.into_inner());
518            f.write_all(&batch)?;
519            f.sync_data()
520        })();
521        let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner());
522        match io {
523            Ok(()) => {
524                g.flushed_seq = flush_to;
525                g.written_len = g.written_len.saturating_add(batch.len() as u64);
526                self.cond.notify_all();
527                Ok(())
528            }
529            Err(e) => {
530                g.failed = Some(e.to_string());
531                self.cond.notify_all();
532                Err(io_err(e))
533            }
534        }
535    }
536
537    /// Swap the active chunk handle (rotation). Caller flushes
538    /// first; both locks taken in canonical order.
539    fn rotate_file(&self, new_file: File) {
540        let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner());
541        let mut f = self.file.lock().unwrap_or_else(|e| e.into_inner());
542        *f = new_file;
543        g.written_len = 0;
544    }
545
546    fn written_len(&self) -> u64 {
547        let g = self.state.lock().unwrap_or_else(|e| e.into_inner());
548        g.written_len + g.buf.len() as u64
549    }
550}
551
552// ─────────────────────────────────────────────────────────────────────────────
553// CoW-2 (v7.34) — background-checkpoint worker.
554//
555// Splits checkpoint into two halves so the front-end pays only the cheap one:
556//   • Capture (`Database::snapshot_checkpoint_job`) — under &mut self,
557//     Arc-bump the catalog + cheap trailer/cold-segment clones + atomic
558//     commit_lsn load. Front returns to caller in microseconds.
559//   • Execute (`execute_checkpoint_job`, on the worker thread) — serialize
560//     the snapshot, tmp+rename the db / manifest files (each fsynced via
561//     the rename + dir-fsync), enqueue the v4 marker through the WalGroup
562//     (which is already thread-safe so live commits interleave fine),
563//     then rotate the chunk file.
564//
565// Replay floor is the marker LSN captured at front-end time. A crash any
566// time during the worker's sequence is safe: nothing past the previous
567// checkpoint's marker can have been forgotten until the new marker hits
568// the WAL, and live writes between the two go into the same chunk under
569// the old marker — replay re-applies them after restoring the (older)
570// snapshot. snapshot+manifest atomicity (D10) is unchanged from the sync
571// path — CoW-4 tightens it later.
572//
573// Single-instance: a state machine of {pending, inflight} so a new
574// trigger fires only when the worker is fully idle. Any sticky error
575// surfaces on the next `wait()`.
576
577#[derive(Debug)]
578struct CheckpointJob {
579    snapshot: spg_engine::EngineSnapshot,
580    marker_lsn: u64,
581    db_path: PathBuf,
582    wal_dir: PathBuf,
583    wal: Arc<WalGroup>,
584    /// Snapshot-time view of the cold-tier segment set. Carried into the
585    /// worker so any concurrent `freeze_oldest_to_cold` after the trigger
586    /// rides the *next* checkpoint's manifest — same staleness window
587    /// the sync path already had.
588    cold_segments: Vec<(u32, PathBuf)>,
589    /// Shared with `PersistenceCtx` so the worker's chunk rotation is
590    /// visible to subsequent diag / Drop introspection.
591    current_chunk_path: Arc<Mutex<PathBuf>>,
592}
593
594#[derive(Debug, Default)]
595struct CheckpointState {
596    /// Set by the front when it has a job ready; cleared when the worker
597    /// picks it up.
598    pending: Option<CheckpointJob>,
599    /// True while the worker is mid-execute. `pending.is_some() || inflight`
600    /// defines "busy" for the trigger / wait predicate.
601    inflight: bool,
602    /// Sticky error from the worker's last failure. Cleared when surfaced
603    /// to a `wait()` caller.
604    last_error: Option<EngineError>,
605    /// Drop signal — worker exits after the current job (or immediately if
606    /// idle and no pending).
607    shutdown: bool,
608}
609
610#[derive(Debug)]
611struct CheckpointWorker {
612    state: Arc<(Mutex<CheckpointState>, Condvar)>,
613    handle: Option<JoinHandle<()>>,
614}
615
616impl CheckpointWorker {
617    fn spawn() -> Self {
618        let state: Arc<(Mutex<CheckpointState>, Condvar)> =
619            Arc::new((Mutex::new(CheckpointState::default()), Condvar::new()));
620        let state_for_thread = Arc::clone(&state);
621        let handle = thread::Builder::new()
622            .name("spg-checkpoint".into())
623            .spawn(move || checkpoint_worker_loop(&state_for_thread))
624            .expect("spawn checkpoint worker");
625        Self {
626            state,
627            handle: Some(handle),
628        }
629    }
630
631    /// Try to enqueue a job. Returns `Ok(true)` if the worker accepted it,
632    /// `Ok(false)` if a job was already pending or in flight (skip — the
633    /// next trigger will pick up newer state). Surfaces any sticky error
634    /// from a previous run before considering the new job, so async paths
635    /// can't lose a failure indefinitely.
636    fn try_enqueue(&self, job: CheckpointJob) -> Result<bool, EngineError> {
637        let (lock, cond) = &*self.state;
638        let mut g = lock.lock().unwrap_or_else(|e| e.into_inner());
639        if let Some(e) = g.last_error.take() {
640            return Err(e);
641        }
642        if g.pending.is_some() || g.inflight {
643            return Ok(false);
644        }
645        g.pending = Some(job);
646        cond.notify_one();
647        Ok(true)
648    }
649
650    /// Block until the worker is idle (no pending, not in flight). Returns
651    /// any sticky error from the last run; clears it on the way out.
652    fn wait(&self) -> Result<(), EngineError> {
653        let (lock, cond) = &*self.state;
654        let mut g = lock.lock().unwrap_or_else(|e| e.into_inner());
655        while g.pending.is_some() || g.inflight {
656            g = cond.wait(g).unwrap_or_else(|e| e.into_inner());
657        }
658        match g.last_error.take() {
659            Some(e) => Err(e),
660            None => Ok(()),
661        }
662    }
663}
664
665impl Drop for CheckpointWorker {
666    fn drop(&mut self) {
667        {
668            let (lock, cond) = &*self.state;
669            let mut g = lock.lock().unwrap_or_else(|e| e.into_inner());
670            g.shutdown = true;
671            cond.notify_one();
672        }
673        if let Some(h) = self.handle.take() {
674            let _ = h.join();
675        }
676    }
677}
678
679fn checkpoint_worker_loop(state: &Arc<(Mutex<CheckpointState>, Condvar)>) {
680    let (lock, cond) = &**state;
681    loop {
682        let job = {
683            let mut g = lock.lock().unwrap_or_else(|e| e.into_inner());
684            while g.pending.is_none() && !g.shutdown {
685                g = cond.wait(g).unwrap_or_else(|e| e.into_inner());
686            }
687            if g.pending.is_none() {
688                // shutdown with no pending → exit cleanly.
689                return;
690            }
691            // Even on shutdown, drain the pending job first so the Drop-time
692            // final checkpoint is durable before exit.
693            let job = g.pending.take().expect("loop invariant");
694            g.inflight = true;
695            job
696        };
697        let result = execute_checkpoint_job(job);
698        {
699            let mut g = lock.lock().unwrap_or_else(|e| e.into_inner());
700            g.inflight = false;
701            if let Err(e) = result {
702                g.last_error = Some(e);
703            }
704            cond.notify_all();
705        }
706    }
707}
708
709fn execute_checkpoint_job(job: CheckpointJob) -> Result<(), EngineError> {
710    // 1. Serialize the captured snapshot. Heavy; this is the whole point
711    //    of CoW — it runs off the engine borrow.
712    let snapshot = job.snapshot.serialize();
713    // 2. Snapshot tmp+rename. Atomic on POSIX; rename implicitly fsyncs
714    //    the data the next directory walk sees.
715    let tmp = {
716        let mut t = job.db_path.clone();
717        let mut name = t
718            .file_name()
719            .map(std::ffi::OsStr::to_os_string)
720            .unwrap_or_default();
721        name.push(".tmp");
722        t.set_file_name(name);
723        t
724    };
725    std::fs::write(&tmp, &snapshot).map_err(io_err)?;
726    std::fs::rename(&tmp, &job.db_path).map_err(io_err)?;
727    // 3. Manifest tmp+rename (cold tier present).
728    if !job.cold_segments.is_empty() {
729        let snap_crc = spg_crypto::crc32::crc32(&snapshot);
730        let entries: Vec<ColdSegmentEntry> = job
731            .cold_segments
732            .iter()
733            .filter_map(|(segment_id, path)| {
734                let bytes = std::fs::read(path).ok()?;
735                Some(ColdSegmentEntry {
736                    segment_id: *segment_id,
737                    path: path.clone(),
738                    crc32: spg_crypto::crc32::crc32(&bytes),
739                })
740            })
741            .collect();
742        let manifest = CatalogManifest {
743            catalog_crc32: snap_crc,
744            cold_segments: entries,
745            wal_baseline_offset: 0,
746        };
747        let m_bytes = manifest.serialize();
748        let m_path = spg_manifest_path(&job.db_path);
749        if let Some(dir) = m_path.parent() {
750            std::fs::create_dir_all(dir).map_err(io_err)?;
751        }
752        let m_tmp = {
753            let mut t = m_path.clone();
754            let mut name = t
755                .file_name()
756                .map(std::ffi::OsStr::to_os_string)
757                .unwrap_or_default();
758            name.push(".tmp");
759            t.set_file_name(name);
760            t
761        };
762        std::fs::write(&m_tmp, &m_bytes).map_err(io_err)?;
763        std::fs::rename(&m_tmp, &m_path).map_err(io_err)?;
764    }
765    // 4. Enqueue the v4 checkpoint marker carrying the captured LSN. The
766    //    WalGroup is thread-safe so a live commit can interleave — the
767    //    marker's LSN, not its position in the chunk, anchors replay.
768    let marker_ts = wall_clock_micros();
769    let marker = encode_v4_checkpoint_marker(job.marker_lsn, marker_ts, &job.db_path);
770    job.wal.enqueue(&marker);
771    job.wal.flush_now()?;
772    // 5. Rotate the active chunk. New commits land in the fresh chunk;
773    //    pre-marker history stays addressable in the old chunk for PITR /
774    //    retention. The shared `current_chunk_path` is updated under its
775    //    own lock before the WalGroup swap so diag readers never see a
776    //    handle that no longer matches the recorded path.
777    let new_chunk_path = job
778        .wal_dir
779        .join(chunk_filename(marker_ts, job.marker_lsn + 1));
780    let new_handle = OpenOptions::new()
781        .create(true)
782        .append(true)
783        .read(true)
784        .open(&new_chunk_path)
785        .map_err(io_err)?;
786    fsync_dir(&job.wal_dir);
787    {
788        let mut p = job
789            .current_chunk_path
790            .lock()
791            .unwrap_or_else(|e| e.into_inner());
792        *p = new_chunk_path;
793    }
794    job.wal.rotate_file(new_handle);
795    Ok(())
796}
797
798impl WalTicket {
799    /// Block until the record this ticket covers is durable.
800    ///
801    /// Under `SPG_SYNCHRONOUS_COMMIT=off` this returns
802    /// immediately — the background flusher (or the next
803    /// checkpoint / clean shutdown) makes the record durable
804    /// within `SPG_WAL_WRITER_DELAY_MS`. Same contract as PG's
805    /// `synchronous_commit = off`.
806    ///
807    /// # Errors
808    /// Surfaces the leader's IO error if the batch flush failed
809    /// (the WAL is then poisoned for all subsequent writes).
810    pub fn wait(&self) -> Result<(), EngineError> {
811        if !synchronous_commit_on() {
812            return Ok(());
813        }
814        self.group.wait_flushed(self.seq)
815    }
816}
817
818/// v7.19 P3 — retention sweep loop. Runs in a dedicated thread
819/// spawned by `Database::open_path` when `SPG_PITR_RETENTION_HOURS`
820/// is set to a non-zero value. Wakes every
821/// `SPG_PITR_RETENTION_CHECK_SEC` (default 60 s), enumerates chunks
822/// under `wal_dir`, archives via `SPG_PITR_ARCHIVE_CMD` if set, and
823/// deletes anything older than `retention_hours`.
824///
825/// Loud-failure posture matches PG's `archive_command`: if the
826/// archive command returns non-zero, the chunk stays on disk and
827/// a warning prints to stderr. The retention sweep doesn't delete
828/// a chunk it failed to archive.
829fn retention_sweep_loop(
830    wal_dir: PathBuf,
831    retention_hours: u64,
832    check_interval: std::time::Duration,
833    archive_cmd: Option<String>,
834    shutdown: Arc<AtomicBool>,
835) {
836    while !shutdown.load(Ordering::SeqCst) {
837        if let Err(e) = retention_sweep_once(&wal_dir, retention_hours, archive_cmd.as_deref()) {
838            eprintln!("spg-embedded: retention sweep error: {e}");
839        }
840        // Sleep in short ticks so shutdown isn't blocked on a
841        // 60 s naptime when Drop signals.
842        let mut elapsed = std::time::Duration::ZERO;
843        let tick = std::time::Duration::from_millis(250);
844        while elapsed < check_interval {
845            if shutdown.load(Ordering::SeqCst) {
846                return;
847            }
848            std::thread::sleep(tick);
849            elapsed += tick;
850        }
851    }
852}
853
854/// v7.19 P3 — one retention sweep pass over `wal_dir`. Extracted
855/// from the loop so tests can drive it directly. Public so the
856/// e2e_pitr_retention integration test (and any future operator
857/// tooling that wants synchronous retention) can call it.
858pub fn retention_sweep_once(
859    wal_dir: &Path,
860    retention_hours: u64,
861    archive_cmd: Option<&str>,
862) -> std::io::Result<()> {
863    if !wal_dir.exists() {
864        return Ok(());
865    }
866    let now_us = wall_clock_micros();
867    let cutoff_us = (now_us as i128 - (retention_hours as i128 * 3_600 * 1_000_000)) as i64;
868    let chunks = sorted_wal_chunks(wal_dir)?;
869    for chunk in chunks {
870        // Don't sweep the most-recent chunk; it's the live one
871        // execute() is appending to. Compare against the largest
872        // filename-prefix unix_us.
873        let stem = match chunk.file_stem().and_then(|s| s.to_str()) {
874            Some(s) => s,
875            None => continue,
876        };
877        let chunk_us: i64 = stem
878            .split_once('_')
879            .and_then(|(prefix, _)| i64::from_str_radix(prefix, 16).ok())
880            .unwrap_or(0);
881        if chunk_us >= cutoff_us {
882            continue;
883        }
884        // Archive first if requested.
885        if let Some(cmd) = archive_cmd {
886            if !cmd.is_empty() {
887                let output = std::process::Command::new("sh")
888                    .arg("-c")
889                    .arg(cmd)
890                    .arg("--")
891                    .arg(&chunk)
892                    .output()?;
893                if !output.status.success() {
894                    eprintln!(
895                        "spg-embedded: SPG_PITR_ARCHIVE_CMD failed for {} (exit {}); chunk stays on disk",
896                        chunk.display(),
897                        output.status.code().unwrap_or(-1)
898                    );
899                    continue;
900                }
901            }
902        }
903        // Delete the chunk + its sibling .checksum if present.
904        if let Err(e) = std::fs::remove_file(&chunk) {
905            eprintln!(
906                "spg-embedded: retention remove {} failed: {e}",
907                chunk.display()
908            );
909            continue;
910        }
911        let mut cs = chunk.clone();
912        let mut name = cs.file_name().map(|n| n.to_os_string()).unwrap_or_default();
913        name.push(".checksum");
914        cs.set_file_name(name);
915        let _ = std::fs::remove_file(&cs);
916    }
917    Ok(())
918}
919
920/// v7.20 — group-commit delay window in µs (PG `commit_delay`
921/// analogue). The flush leader sleeps this long before taking
922/// the batch so concurrent writers pile in. Default 150 µs;
923/// `SPG_COMMIT_DELAY_US=0` disables.
924fn commit_delay_us() -> u64 {
925    static CACHED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
926    *CACHED.get_or_init(|| {
927        std::env::var("SPG_COMMIT_DELAY_US")
928            .ok()
929            .and_then(|s| s.parse::<u64>().ok())
930            .unwrap_or(150)
931    })
932}
933
934/// v7.20 — PG `synchronous_commit` analogue. `on` (default):
935/// `execute()` blocks until its WAL record is fsynced —
936/// zero-loss durability. `off`: `execute()` returns after the
937/// in-memory mutation + WAL enqueue; a background flusher
938/// thread writes + fsyncs every `SPG_WAL_WRITER_DELAY_MS`
939/// (default 200 ms — PG's `wal_writer_delay` default). Crash
940/// window = up to one flush interval of confirmed-but-unsynced
941/// commits — exactly the trade PG documents for the same
942/// setting. Clean shutdown (Drop / checkpoint) always flushes.
943fn synchronous_commit_on() -> bool {
944    static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
945    *CACHED.get_or_init(|| {
946        !std::env::var("SPG_SYNCHRONOUS_COMMIT")
947            .map(|v| v.eq_ignore_ascii_case("off") || v == "0" || v.eq_ignore_ascii_case("false"))
948            .unwrap_or(false)
949    })
950}
951
952/// v7.20 — background WAL flusher cadence for
953/// `SPG_SYNCHRONOUS_COMMIT=off` (PG `wal_writer_delay`).
954fn wal_writer_delay_ms() -> u64 {
955    static CACHED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
956    *CACHED.get_or_init(|| {
957        std::env::var("SPG_WAL_WRITER_DELAY_MS")
958            .ok()
959            .and_then(|s| s.parse::<u64>().ok())
960            .filter(|&n| n > 0)
961            .unwrap_or(200)
962    })
963}
964
965fn pitr_retention_hours() -> u64 {
966    std::env::var("SPG_PITR_RETENTION_HOURS")
967        .ok()
968        .and_then(|s| s.parse::<u64>().ok())
969        .unwrap_or(0)
970}
971
972fn pitr_retention_check_sec() -> u64 {
973    std::env::var("SPG_PITR_RETENTION_CHECK_SEC")
974        .ok()
975        .and_then(|s| s.parse::<u64>().ok())
976        .filter(|&n| n > 0)
977        .unwrap_or(60)
978}
979
980fn pitr_archive_cmd() -> Option<String> {
981    std::env::var("SPG_PITR_ARCHIVE_CMD")
982        .ok()
983        .filter(|s| !s.is_empty())
984}
985
986/// v7.19 — replay every record from `wal_bytes` whose
987/// `commit_lsn` is strictly greater than `floor_lsn`. v3 records
988/// (no LSN) and v4 records with `commit_lsn <= floor_lsn` are
989/// skipped — the snapshot loaded ahead of this call already
990/// reflects them, and re-applying would DuplicateTable /
991/// double-insert. v3 records inside the legacy migration chunk
992/// always apply because the migration sets `floor_lsn = 0` and
993/// v3 records carry no LSN to compare; the pre-migration
994/// behaviour (every record replays) is what the migration
995/// preserves.
996///
997/// Returns the count of records successfully applied. Same
998/// torn-tail semantics as `replay_wal_into_engine`.
999fn replay_wal_filtered(
1000    wal_bytes: &[u8],
1001    engine: &mut Engine,
1002    floor_lsn: u64,
1003    quarantine: &mut Vec<QuarantinedStmt>,
1004) -> Result<usize, String> {
1005    let records = parse_wal_records(wal_bytes)?;
1006    let mut applied = 0usize;
1007    // v7.37.7 A.1 — per-record-type timing histogram gated on env var.
1008    // Records mailrs prod snapshot's WAL has ~thousands of WAL_V5_ROW_REDO
1009    // entries; v7.37.5 ack claimed batched apply_redo brought replay to
1010    // ~500ms but fresh-extract measurement shows ~250s. This histogram
1011    // splits ROW_REDO vs SQL re-execute time so the fix target is concrete.
1012    let timing = std::env::var_os("SPG_OPEN_PATH_TIMING").is_some();
1013    let mut redo_count = 0u64;
1014    let mut redo_us = 0u128;
1015    let mut sql_count = 0u64;
1016    let mut sql_us = 0u128;
1017    let mut marker_count = 0u64;
1018    let mut skip_count = 0u64;
1019    for r in &records {
1020        // Skip markers + non-SQL records.
1021        if r.type_byte == WAL_V3_TYPE_DURABILITY_CHECKPOINT
1022            || r.type_byte == WAL_V4_TYPE_CHECKPOINT_MARKER
1023        {
1024            marker_count += 1;
1025            continue;
1026        }
1027        // v4 SQL records carry an LSN. Apply iff strictly above
1028        // the snapshot floor.
1029        if r.type_byte == WAL_V4_TYPE_AUTO_COMMIT_SQL
1030            || r.type_byte == WAL_V4_TYPE_TX_COMMIT_SQL
1031            || r.type_byte == WAL_V5_TYPE_ROW_REDO
1032        {
1033            if let Some(lsn) = r.commit_lsn {
1034                if lsn <= floor_lsn {
1035                    skip_count += 1;
1036                    continue;
1037                }
1038            }
1039        }
1040        // v7.34 (crash-recovery P0 #2) — row-level redo record: apply the
1041        // physical changes directly (O(changed rows)) instead of
1042        // re-executing SQL (the O(records × rows) statement-replay that
1043        // hung the mailrs P0). The payload is `encode_redo_log` bytes, not
1044        // SQL, so it never enters the from_utf8 / split_statements path.
1045        if r.type_byte == WAL_V5_TYPE_ROW_REDO {
1046            let t = std::time::Instant::now();
1047            let changes = spg_storage::decode_redo_log(r.sql)
1048                .map_err(|e| format!("redo decode at offset {}: {e:?}", r.offset))?;
1049            engine
1050                .apply_redo(&changes)
1051                .map_err(|e| format!("redo apply at offset {}: {e:?}", r.offset))?;
1052            redo_us += t.elapsed().as_micros();
1053            redo_count += 1;
1054            applied += 1;
1055            continue;
1056        }
1057        // v3 records (type 0x01, no LSN) always apply — the
1058        // legacy migration path is the only place they appear,
1059        // and floor_lsn=0 there.
1060        let sql = match std::str::from_utf8(r.sql) {
1061            Ok(s) => s,
1062            Err(e) => return Err(format!("non-UTF-8 SQL at offset {}: {e}", r.offset)),
1063        };
1064        // v7.21 — a tx-commit record carries the whole transaction
1065        // as a `";\n"`-joined script; auto-commit records are a
1066        // single statement, for which split_statements is a no-op.
1067        //
1068        // v7.30.1 (mailrs round-24 ask 2) — a statement the engine
1069        // REJECTS is quarantined, not fatal: "one statement failed
1070        // to replay" ≠ "the catalog is corrupt". Framing damage
1071        // (parse_wal_records / non-UTF-8 above) still errors — that
1072        // IS corruption. Subsequent statements of a tx script keep
1073        // applying: the bricking class is a no-op-at-runtime
1074        // statement that re-applies non-idempotently, and skipping
1075        // just it reconstructs the runtime state.
1076        let t = std::time::Instant::now();
1077        for stmt in split_statements(sql) {
1078            if let Err(e) = engine.execute(stmt) {
1079                quarantine.push(QuarantinedStmt {
1080                    offset: r.offset,
1081                    sql: stmt.to_string(),
1082                    error: format!("{e:?}"),
1083                });
1084            }
1085        }
1086        sql_us += t.elapsed().as_micros();
1087        sql_count += 1;
1088        applied += 1;
1089    }
1090    if timing {
1091        eprintln!(
1092            "[replay_wal_filtered] total_records={} applied={} redo={} ({:.3}s) sql={} ({:.3}s) marker={} skip_lsn={}",
1093            records.len(),
1094            applied,
1095            redo_count,
1096            redo_us as f64 / 1_000_000.0,
1097            sql_count,
1098            sql_us as f64 / 1_000_000.0,
1099            marker_count,
1100            skip_count,
1101        );
1102    }
1103    Ok(applied)
1104}
1105
1106/// v7.30.1 (mailrs round-24 ask 2) — one statement that failed to
1107/// re-apply during boot replay. Kept for forensics in a
1108/// `quarantine-*.log` beside the WAL chunks; the boot continues.
1109struct QuarantinedStmt {
1110    offset: usize,
1111    sql: String,
1112    error: String,
1113}
1114
1115fn format_quarantine_line(q: &QuarantinedStmt) -> String {
1116    format!("offset {}: {}\n  rejected: {}\n", q.offset, q.sql, q.error)
1117}
1118
1119/// v7.19 — WAL chunk filename format. Zero-padded 16-digit
1120/// hex on both parts so default lexicographic sort matches
1121/// numeric order, with the unix_us prefix coming first so
1122/// the on-disk listing is chronological too.
1123/// v7.34 (crash-recovery P0 #2) — fsync a directory so a newly created
1124/// file's entry is durable. `sync_data` on a chunk file persists its
1125/// bytes but NOT the parent directory entry that names it; a power loss
1126/// after creating a fresh WAL chunk could lose that entry and make the
1127/// chunk (and the committed records in it) unreachable on restart.
1128/// Best-effort — a platform that rejects directory fsync is no worse off.
1129fn fsync_dir(dir: &Path) {
1130    if let Ok(f) = File::open(dir) {
1131        let _ = f.sync_all();
1132    }
1133}
1134
1135fn chunk_filename(unix_us: i64, leading_lsn: u64) -> String {
1136    // Negative timestamps shouldn't happen in practice (we sit
1137    // post-1970), but clamp to 0 so the zero-padded
1138    // representation stays sortable.
1139    let us = unix_us.max(0) as u64;
1140    format!("{us:016x}_{leading_lsn:016x}.wal")
1141}
1142
1143/// v7.19 — filename used for the legacy single-file WAL when
1144/// `open_path` migrates a v7.18-layout database into the new
1145/// chunk directory. Lexicographically smallest possible value
1146/// so subsequent chunks sort after it.
1147fn legacy_chunk_filename() -> String {
1148    chunk_filename(0, 0)
1149}
1150
1151/// CoW-4 (v7.34) — D10 fallback: read one cold-segment file and
1152/// hand its bytes to the catalog. The segment binary is self-validating
1153/// (magic + internal CRC32 via `OwnedSegment::from_bytes`), so we don't
1154/// need the manifest's `segment_crc32` to trust it. Returns `true` on a
1155/// successful attach (caller bumps `cold_segment_paths`), `false` on a
1156/// per-segment failure that is logged but doesn't abort boot.
1157fn attach_segment_from_disk(engine: &mut Engine, segment_id: u32, path: &Path) -> bool {
1158    if engine.catalog().cold_segment(segment_id).is_some() {
1159        return true;
1160    }
1161    let bytes = match std::fs::read(path) {
1162        Ok(b) => b,
1163        Err(e) => {
1164            eprintln!(
1165                "spg-embedded: cold-segment scan skip {}: read failed: {e}",
1166                path.display()
1167            );
1168            return false;
1169        }
1170    };
1171    let mut new_cat = engine.catalog().clone();
1172    if let Err(e) = new_cat.load_segment_bytes_at(segment_id, bytes) {
1173        eprintln!(
1174            "spg-embedded: cold-segment scan skip {}: parse/load failed: {e}",
1175            path.display()
1176        );
1177        return false;
1178    }
1179    engine.replace_catalog(new_cat);
1180    true
1181}
1182
1183/// CoW-4 (v7.34) — D10 + missing-manifest fallback: scan
1184/// `<db>.spg/segments/` for `seg_<id>.spg` files and attach any that
1185/// aren't already in `cold_segment_paths`. Closes the window where a
1186/// crash between snapshot rename and manifest rename leaves
1187/// post-checkpoint cold segments orphaned on disk (the snapshot's CRC
1188/// no longer matches the stale manifest, so the manifest path
1189/// silently dropped them). The segment parser self-verifies, so a
1190/// torn write surfaces as a per-segment skip, never silent corruption.
1191fn scan_cold_segments_dir(
1192    segments_dir: &Path,
1193    engine: &mut Engine,
1194    cold_segment_paths: &mut BTreeMap<u32, PathBuf>,
1195) {
1196    // v7.34.1 (mailrs prod report bug A): single-file catalogs (e.g.
1197    // `/data/spg/mailrs.spg` is a regular file, not the `<db>/<db>.spg`
1198    // layout this scan assumes) make the computed `<db>.spg/segments`
1199    // path traverse a file inode, which surfaces as ENOTDIR (`Not a
1200    // directory`, errno 20). Treat any non-directory state — absent,
1201    // file-in-the-way, stat-blocked — as "no segments to scan" and
1202    // silently return. The eprintln below only fires for the genuine
1203    // mid-walk read errors (permission flip, IO failure) that operators
1204    // need to see.
1205    if !segments_dir.is_dir() {
1206        return;
1207    }
1208    let read_dir = match std::fs::read_dir(segments_dir) {
1209        Ok(rd) => rd,
1210        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
1211        Err(e) => {
1212            eprintln!(
1213                "spg-embedded: cold-segment scan: cannot read {}: {e}",
1214                segments_dir.display()
1215            );
1216            return;
1217        }
1218    };
1219    for entry in read_dir.flatten() {
1220        let path = entry.path();
1221        // Only the canonical `seg_<id>.spg` form. `.tmp` half-renames
1222        // and unknown extensions are skipped — the segment writer's
1223        // tmp+rename pattern guarantees `.spg` files are either fully
1224        // written or absent.
1225        if path.extension().and_then(|s| s.to_str()) != Some("spg") {
1226            continue;
1227        }
1228        let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
1229            continue;
1230        };
1231        let Some(id_str) = stem.strip_prefix("seg_") else {
1232            continue;
1233        };
1234        let Ok(segment_id) = id_str.parse::<u32>() else {
1235            continue;
1236        };
1237        if cold_segment_paths.contains_key(&segment_id) {
1238            continue;
1239        }
1240        if attach_segment_from_disk(engine, segment_id, &path) {
1241            cold_segment_paths.insert(segment_id, path);
1242        }
1243    }
1244}
1245
1246/// v7.19 — list every `.wal` file in `wal_dir` in
1247/// lexicographic order (which doubles as chunk-creation
1248/// order thanks to the zero-padded filename format).
1249fn sorted_wal_chunks(wal_dir: &Path) -> std::io::Result<Vec<PathBuf>> {
1250    let mut paths = Vec::new();
1251    let read_dir = match std::fs::read_dir(wal_dir) {
1252        Ok(rd) => rd,
1253        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(paths),
1254        Err(e) => return Err(e),
1255    };
1256    for entry in read_dir {
1257        let entry = entry?;
1258        let path = entry.path();
1259        if path.extension().and_then(|s| s.to_str()) == Some("wal") {
1260            paths.push(path);
1261        }
1262    }
1263    paths.sort();
1264    Ok(paths)
1265}
1266
1267/// v7.18 PITR — encode one v4 `checkpoint_marker` record. Layout:
1268///
1269/// ```text
1270/// [u32 LE (payload_len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
1271/// [u32 LE crc32 over (type_byte || payload)]
1272/// [u8  type = 0x11]
1273/// payload:
1274///   [u64 LE checkpoint_lsn]
1275///   [i64 LE checkpoint_unix_us  (WAL_V4_NO_CLOCK if no clock)]
1276///   [u16 LE snapshot_path_len]
1277///   [snapshot_path_bytes]
1278/// ```
1279///
1280/// `payload_len` covers only the payload — keeping the framing
1281/// uniform across v3 / v4 record types so torn-write detection in
1282/// `replay_wal_into_engine` stays trivial.
1283fn encode_v4_checkpoint_marker(
1284    checkpoint_lsn: u64,
1285    checkpoint_unix_us: i64,
1286    snapshot_path: &Path,
1287) -> Vec<u8> {
1288    let snapshot_bytes = snapshot_path.to_string_lossy().into_owned();
1289    let snap_payload = snapshot_bytes.as_bytes();
1290    let snap_len_u16: u16 = snap_payload.len().min(u16::MAX as usize) as u16;
1291    let mut payload = Vec::with_capacity(8 + 8 + 2 + snap_payload.len());
1292    payload.extend_from_slice(&checkpoint_lsn.to_le_bytes());
1293    payload.extend_from_slice(&checkpoint_unix_us.to_le_bytes());
1294    payload.extend_from_slice(&snap_len_u16.to_le_bytes());
1295    payload.extend_from_slice(&snap_payload[..snap_len_u16 as usize]);
1296    let mut crc_buf = Vec::with_capacity(1 + payload.len());
1297    crc_buf.push(WAL_V4_TYPE_CHECKPOINT_MARKER);
1298    crc_buf.extend_from_slice(&payload);
1299    let crc = spg_crypto::crc32::crc32(&crc_buf);
1300    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
1301    let mut out = Vec::with_capacity(4 + 4 + 1 + payload.len());
1302    out.extend_from_slice(&header);
1303    out.extend_from_slice(&crc.to_le_bytes());
1304    out.push(WAL_V4_TYPE_CHECKPOINT_MARKER);
1305    out.extend_from_slice(&payload);
1306    out
1307}
1308
1309/// v7.18 PITR — encode one v4 `auto_commit_sql` record. Layout:
1310///
1311/// ```text
1312/// [u32 LE (sql_len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
1313/// [u32 LE crc32 over (type_byte || lsn || ts || sql_bytes)]
1314/// [u8  type = 0x10]
1315/// [u64 LE commit_lsn]
1316/// [i64 LE commit_unix_us  (= WAL_V4_NO_CLOCK when no ClockFn)]
1317/// [sql bytes]
1318/// ```
1319///
1320/// `sql_len` field stays the SQL byte count — same shape as v3 — so
1321/// replay-buffer torn-write detection compares against
1322/// `WAL_V4_EXTRA_HEADER + sql_len`. v3 records (type 0x01) stay
1323/// readable by the same loop with their original 9-byte header
1324/// arithmetic.
1325fn encode_v4_auto_commit(sql: &str, commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
1326    encode_v4_framed(
1327        WAL_V4_TYPE_AUTO_COMMIT_SQL,
1328        sql.as_bytes(),
1329        commit_lsn,
1330        commit_unix_us,
1331    )
1332}
1333
1334/// v7.21 — same envelope, `WAL_V4_TYPE_TX_COMMIT_SQL` type byte.
1335/// `script` = the transaction's statements joined with `";\n"`.
1336fn encode_v4_tx_commit(script: &str, commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
1337    encode_v4_framed(
1338        WAL_V4_TYPE_TX_COMMIT_SQL,
1339        script.as_bytes(),
1340        commit_lsn,
1341        commit_unix_us,
1342    )
1343}
1344
1345/// v7.34 (crash-recovery P0 #2) — encode one row-level redo record. Same
1346/// v4 envelope + CRC, type byte 0x13; the payload is the
1347/// `encode_redo_log` bytes (physical changes) instead of SQL text, so
1348/// replay applies them in place of re-executing the statement.
1349fn encode_v5_row_redo(redo_bytes: &[u8], commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
1350    encode_v4_framed(WAL_V5_TYPE_ROW_REDO, redo_bytes, commit_lsn, commit_unix_us)
1351}
1352
1353fn encode_v4_framed(
1354    type_byte: u8,
1355    payload: &[u8],
1356    commit_lsn: u64,
1357    commit_unix_us: i64,
1358) -> Vec<u8> {
1359    let mut crc_buf = Vec::with_capacity(1 + WAL_V4_EXTRA_HEADER + payload.len());
1360    crc_buf.push(type_byte);
1361    crc_buf.extend_from_slice(&commit_lsn.to_le_bytes());
1362    crc_buf.extend_from_slice(&commit_unix_us.to_le_bytes());
1363    crc_buf.extend_from_slice(payload);
1364    let crc = spg_crypto::crc32::crc32(&crc_buf);
1365    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
1366    let mut out = Vec::with_capacity(4 + 4 + 1 + WAL_V4_EXTRA_HEADER + payload.len());
1367    out.extend_from_slice(&header);
1368    out.extend_from_slice(&crc.to_le_bytes());
1369    out.push(type_byte);
1370    out.extend_from_slice(&commit_lsn.to_le_bytes());
1371    out.extend_from_slice(&commit_unix_us.to_le_bytes());
1372    out.extend_from_slice(payload);
1373    out
1374}
1375
1376/// v7.1 — decode + apply every record in `wal_bytes` to `engine`.
1377/// Returns the count of records successfully applied. A truncated
1378/// trailing record (mid-write torn) is dropped silently — the
1379/// same recovery story `spg-server`'s boot path uses.
1380fn replay_wal_into_engine(wal_bytes: &[u8], engine: &mut Engine) -> Result<usize, String> {
1381    let mut applied = 0usize;
1382    let mut cur = 0usize;
1383    while cur < wal_bytes.len() {
1384        if wal_bytes.len() - cur < 4 {
1385            // Trailing partial header — torn write, drop and stop.
1386            break;
1387        }
1388        let raw_len = u32::from_le_bytes(wal_bytes[cur..cur + 4].try_into().unwrap());
1389        let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
1390        let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
1391        let len_mask = if is_v3 {
1392            !(WAL_V2_SENTINEL | WAL_V3_FLAG)
1393        } else {
1394            !WAL_V2_SENTINEL
1395        };
1396        let rec_len = (raw_len & len_mask) as usize;
1397        let header_len = if is_v3 {
1398            9
1399        } else if is_v2 {
1400            8
1401        } else {
1402            4
1403        };
1404        if wal_bytes.len() - cur < header_len + rec_len {
1405            // Torn record at the tail — drop, stop.
1406            break;
1407        }
1408        if is_v3 {
1409            let type_byte = wal_bytes[cur + 8];
1410            match type_byte {
1411                WAL_V3_TYPE_AUTO_COMMIT_SQL => {}
1412                WAL_V3_TYPE_DURABILITY_CHECKPOINT => {
1413                    // durability_checkpoint marker — skip, no SQL.
1414                    cur += header_len + rec_len;
1415                    continue;
1416                }
1417                WAL_V4_TYPE_CHECKPOINT_MARKER => {
1418                    // v7.18 PITR — checkpoint anchor, skip on replay
1419                    // (engine state past this point reflects the
1420                    // matching snapshot already loaded by the caller).
1421                    cur += header_len + rec_len;
1422                    continue;
1423                }
1424                WAL_V4_TYPE_AUTO_COMMIT_SQL | WAL_V4_TYPE_TX_COMMIT_SQL => {
1425                    // v7.18 PITR — v4 record carries 16 bytes of
1426                    // (commit_lsn, commit_unix_us) between the type
1427                    // byte and the SQL payload. Replay reads them but
1428                    // does not enforce them — the engine doesn't
1429                    // surface LSN/clock here. Restore tooling
1430                    // (spgctl) parses them via parse_wal_record below.
1431                    //
1432                    // v7.21 — tx-commit records (0x12) carry a whole
1433                    // transaction as a `";\n"`-joined script;
1434                    // split_statements is a no-op on the single-
1435                    // statement auto-commit form.
1436                    let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
1437                    if wal_bytes.len() - cur < v4_total {
1438                        // Torn v4 record at the tail — drop, stop.
1439                        break;
1440                    }
1441                    let sql_start = cur + header_len + WAL_V4_EXTRA_HEADER;
1442                    let sql_bytes = &wal_bytes[sql_start..sql_start + rec_len];
1443                    let sql = std::str::from_utf8(sql_bytes)
1444                        .map_err(|e| format!("WAL replay: non-UTF-8 SQL at offset {cur}: {e}"))?;
1445                    for stmt in split_statements(sql) {
1446                        engine.execute(stmt).map_err(|e| {
1447                            format!("WAL replay: apply {stmt:?} at offset {cur} rejected: {e:?}")
1448                        })?;
1449                    }
1450                    applied += 1;
1451                    cur += v4_total;
1452                    continue;
1453                }
1454                other => {
1455                    return Err(format!(
1456                        "WAL replay: unknown v3 type byte {other:#04x} at offset {cur}"
1457                    ));
1458                }
1459            }
1460        }
1461        let sql_bytes = &wal_bytes[cur + header_len..cur + header_len + rec_len];
1462        let sql = std::str::from_utf8(sql_bytes)
1463            .map_err(|e| format!("WAL replay: non-UTF-8 SQL at offset {cur}: {e}"))?;
1464        engine
1465            .execute(sql)
1466            .map_err(|e| format!("WAL replay: apply {sql:?} at offset {cur} rejected: {e:?}"))?;
1467        applied += 1;
1468        cur += header_len + rec_len;
1469    }
1470    Ok(applied)
1471}
1472
1473/// v7.18 PITR — parsed WAL record, surfaced for restore / verify
1474/// tooling. The replay loop above doesn't expose LSN/timestamp;
1475/// `spgctl restore --to <timestamp>` and `spgctl verify` need them.
1476/// Returned offsets are byte-positions inside the WAL buffer.
1477#[derive(Debug, Clone)]
1478pub struct WalRecord<'a> {
1479    /// Byte offset in the WAL buffer where this record starts.
1480    pub offset: usize,
1481    /// Type byte (0x01 = v3 auto-commit, 0x10 = v4 auto-commit,
1482    /// 0x02 = durability checkpoint marker).
1483    pub type_byte: u8,
1484    /// `Some(lsn)` for v4 records, `None` for v3.
1485    pub commit_lsn: Option<u64>,
1486    /// `Some(unix_us)` for v4 records carrying a clock-set timestamp,
1487    /// `None` for v3 or for v4 records explicitly written with
1488    /// `WAL_V4_NO_CLOCK` (sentinel for "no ClockFn at commit time").
1489    pub commit_unix_us: Option<i64>,
1490    /// SQL payload as borrowed bytes. Empty for durability markers.
1491    pub sql: &'a [u8],
1492}
1493
1494/// v7.18 PITR — iterate over `wal_bytes` yielding one `WalRecord`
1495/// per intact record. Torn-tail records terminate iteration
1496/// silently (same recovery story as `replay_wal_into_engine`).
1497/// Unknown type bytes inside a v3 envelope return `Err` so the
1498/// caller knows the WAL was written by a newer SPG.
1499pub fn parse_wal_records(wal_bytes: &[u8]) -> Result<Vec<WalRecord<'_>>, String> {
1500    let mut out = Vec::new();
1501    let mut cur = 0usize;
1502    while cur < wal_bytes.len() {
1503        if wal_bytes.len() - cur < 4 {
1504            break;
1505        }
1506        let raw_len = u32::from_le_bytes(wal_bytes[cur..cur + 4].try_into().unwrap());
1507        let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
1508        let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
1509        let len_mask = if is_v3 {
1510            !(WAL_V2_SENTINEL | WAL_V3_FLAG)
1511        } else {
1512            !WAL_V2_SENTINEL
1513        };
1514        let rec_len = (raw_len & len_mask) as usize;
1515        let header_len = if is_v3 {
1516            9
1517        } else if is_v2 {
1518            8
1519        } else {
1520            4
1521        };
1522        if wal_bytes.len() - cur < header_len + rec_len {
1523            break;
1524        }
1525        if !is_v3 {
1526            // v1 / v2 records carry no type byte; treat as legacy
1527            // auto-commit SQL with no LSN/time.
1528            let sql = &wal_bytes[cur + header_len..cur + header_len + rec_len];
1529            out.push(WalRecord {
1530                offset: cur,
1531                type_byte: WAL_V3_TYPE_AUTO_COMMIT_SQL,
1532                commit_lsn: None,
1533                commit_unix_us: None,
1534                sql,
1535            });
1536            cur += header_len + rec_len;
1537            continue;
1538        }
1539        let type_byte = wal_bytes[cur + 8];
1540        match type_byte {
1541            WAL_V3_TYPE_AUTO_COMMIT_SQL => {
1542                let sql = &wal_bytes[cur + header_len..cur + header_len + rec_len];
1543                out.push(WalRecord {
1544                    offset: cur,
1545                    type_byte,
1546                    commit_lsn: None,
1547                    commit_unix_us: None,
1548                    sql,
1549                });
1550                cur += header_len + rec_len;
1551            }
1552            WAL_V3_TYPE_DURABILITY_CHECKPOINT => {
1553                out.push(WalRecord {
1554                    offset: cur,
1555                    type_byte,
1556                    commit_lsn: None,
1557                    commit_unix_us: None,
1558                    sql: &[],
1559                });
1560                cur += header_len + rec_len;
1561            }
1562            WAL_V4_TYPE_CHECKPOINT_MARKER => {
1563                // v7.18 PITR — payload = (lsn u64)(ts i64)(path_len u16)(path bytes).
1564                // We surface lsn + ts on the WalRecord; the path lives
1565                // in `sql` since the type byte already disambiguates
1566                // record meaning and adding a dedicated field would
1567                // bloat the iterator return type for every variant.
1568                if rec_len < 18 {
1569                    return Err(format!(
1570                        "WAL parse: checkpoint marker at offset {cur} too short ({rec_len} bytes)"
1571                    ));
1572                }
1573                let lsn = u64::from_le_bytes(
1574                    wal_bytes[cur + header_len..cur + header_len + 8]
1575                        .try_into()
1576                        .unwrap(),
1577                );
1578                let ts_raw = i64::from_le_bytes(
1579                    wal_bytes[cur + header_len + 8..cur + header_len + 16]
1580                        .try_into()
1581                        .unwrap(),
1582                );
1583                let path_len = u16::from_le_bytes(
1584                    wal_bytes[cur + header_len + 16..cur + header_len + 18]
1585                        .try_into()
1586                        .unwrap(),
1587                ) as usize;
1588                if rec_len < 18 + path_len {
1589                    return Err(format!(
1590                        "WAL parse: checkpoint marker at offset {cur} truncated path"
1591                    ));
1592                }
1593                let path_start = cur + header_len + 18;
1594                let path_bytes = &wal_bytes[path_start..path_start + path_len];
1595                let commit_unix_us = if ts_raw == WAL_V4_NO_CLOCK {
1596                    None
1597                } else {
1598                    Some(ts_raw)
1599                };
1600                out.push(WalRecord {
1601                    offset: cur,
1602                    type_byte,
1603                    commit_lsn: Some(lsn),
1604                    commit_unix_us,
1605                    sql: path_bytes,
1606                });
1607                cur += header_len + rec_len;
1608            }
1609            WAL_V4_TYPE_AUTO_COMMIT_SQL | WAL_V4_TYPE_TX_COMMIT_SQL | WAL_V5_TYPE_ROW_REDO => {
1610                let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
1611                if wal_bytes.len() - cur < v4_total {
1612                    break;
1613                }
1614                let lsn = u64::from_le_bytes(
1615                    wal_bytes[cur + header_len..cur + header_len + 8]
1616                        .try_into()
1617                        .unwrap(),
1618                );
1619                let ts_raw = i64::from_le_bytes(
1620                    wal_bytes[cur + header_len + 8..cur + header_len + 16]
1621                        .try_into()
1622                        .unwrap(),
1623                );
1624                let commit_unix_us = if ts_raw == WAL_V4_NO_CLOCK {
1625                    None
1626                } else {
1627                    Some(ts_raw)
1628                };
1629                let sql_start = cur + header_len + WAL_V4_EXTRA_HEADER;
1630                let sql = &wal_bytes[sql_start..sql_start + rec_len];
1631                out.push(WalRecord {
1632                    offset: cur,
1633                    type_byte,
1634                    commit_lsn: Some(lsn),
1635                    commit_unix_us,
1636                    sql,
1637                });
1638                cur += v4_total;
1639            }
1640            other => {
1641                return Err(format!(
1642                    "WAL parse: unknown type byte {other:#04x} at offset {cur}"
1643                ));
1644            }
1645        }
1646    }
1647    Ok(out)
1648}
1649
1650/// v7.1 — predicate for "should the next `execute()` mutate the
1651/// WAL?" Returns `false` for SELECT / SHOW / EXPLAIN / BEGIN /
1652/// COMMIT / ROLLBACK and the SPG-specific verbs that don't go
1653/// through the auto-commit record path on the server (CHECKPOINT,
1654/// COMPACT). Conservative: anything we don't explicitly know is
1655/// read-only falls through to "write a WAL record".
1656fn sql_is_read_only(sql: &str) -> bool {
1657    let t = sql.trim_start();
1658    let head = t
1659        .split(|c: char| c.is_whitespace() || c == ';' || c == '(')
1660        .next()
1661        .unwrap_or("");
1662    matches!(
1663        head.to_ascii_lowercase().as_str(),
1664        "select"
1665            | "show"
1666            | "explain"
1667            | "begin"
1668            | "commit"
1669            | "rollback"
1670            | "checkpoint"
1671            | "compact"
1672            | "wait"
1673            | "with"
1674    )
1675}
1676
1677/// Embedded SPG database handle. Owns an `Engine` + provides
1678/// ergonomic wrappers around `execute` and `query`. Drops the
1679/// engine on `Drop` — no WAL flush / fsync, because v6.10.3
1680/// is in-memory only.
1681#[derive(Debug)]
1682pub struct Database {
1683    engine: Engine,
1684    /// v7.1 — persistence sidecar. When `Some(p)`, every
1685    /// `execute(sql)` that mutates state appends a v4
1686    /// `auto_commit_sql` WAL record + fsyncs before the call
1687    /// returns; `Drop` writes a final catalog snapshot to
1688    /// `<db_path>` so the next session boots from a clean
1689    /// snapshot + an empty WAL. `None` = in-memory only (the
1690    /// v6.10.3 shape).
1691    persistence: Option<PersistenceCtx>,
1692    /// v7.18 PITR — monotonic per-database commit LSN. Increments
1693    /// before each successful WAL append; bootstrapped at
1694    /// open_path from `max(parse_wal_records → commit_lsn)` so
1695    /// reopen never reuses an LSN. In-memory databases start at
1696    /// 0 and never advance (no WAL = no LSN-meaningful records).
1697    commit_lsn: AtomicU64,
1698    /// v7.21 (round-12 polish) — explicit-transaction WAL buffer.
1699    /// `Some` between an engine-accepted BEGIN and its
1700    /// COMMIT / ROLLBACK on a persistent database. In-transaction
1701    /// mutations only touch the engine's shadow catalog and report
1702    /// `modified_catalog: false`, so the per-statement auto-commit
1703    /// append never fires for them; their bind-final SQL collects
1704    /// here instead and COMMIT flushes the lot as ONE atomic
1705    /// `WAL_V4_TYPE_TX_COMMIT_SQL` record (ROLLBACK just drops it).
1706    /// Always `None` for in-memory databases.
1707    tx_wal: Option<TxWalBuffer>,
1708}
1709
1710/// See [`Database::tx_wal`].
1711#[derive(Debug, Default)]
1712struct TxWalBuffer {
1713    /// Bind-final SQL of every non-read-only statement the engine
1714    /// accepted inside the open transaction, in execution order.
1715    statements: Vec<String>,
1716    /// `(savepoint_name, statements.len() at SAVEPOINT time)` —
1717    /// `ROLLBACK TO SAVEPOINT` truncates `statements` back to the
1718    /// recorded mark so the WAL record matches what the engine
1719    /// keeps. PG name-reuse semantics (latest wins).
1720    savepoints: Vec<(String, usize)>,
1721}
1722
1723/// Statement-level transaction-control classification for the WAL
1724/// buffer. Runs AFTER the engine accepted the statement, so the
1725/// engine stays the single validator — this only mirrors state.
1726enum TxControl {
1727    Begin,
1728    Commit,
1729    Rollback,
1730    RollbackToSavepoint(String),
1731    Savepoint(String),
1732    ReleaseSavepoint,
1733}
1734
1735fn tx_control_kind(sql: &str) -> Option<TxControl> {
1736    let mut words = sql
1737        .split(|c: char| c.is_whitespace() || c == ';')
1738        .filter(|w| !w.is_empty())
1739        .map(str::to_ascii_lowercase);
1740    let head = words.next()?;
1741    match head.as_str() {
1742        "begin" | "start" => Some(TxControl::Begin),
1743        "commit" | "end" => Some(TxControl::Commit),
1744        "savepoint" => words.next().map(TxControl::Savepoint),
1745        "release" => Some(TxControl::ReleaseSavepoint),
1746        "rollback" => match words.next().as_deref() {
1747            // ROLLBACK TO [SAVEPOINT] <name>
1748            Some("to") => {
1749                let next = words.next()?;
1750                let name = if next == "savepoint" {
1751                    words.next()?
1752                } else {
1753                    next
1754                };
1755                Some(TxControl::RollbackToSavepoint(name))
1756            }
1757            _ => Some(TxControl::Rollback),
1758        },
1759        _ => None,
1760    }
1761}
1762
1763#[derive(Debug)]
1764#[allow(dead_code)] // `wal_dir`/`current_chunk_path` are read at boot; kept for Drop/diag introspection.
1765struct PersistenceCtx {
1766    db_path: PathBuf,
1767    /// v7.19 — WAL chunk directory at `<db_path>.wal/`.
1768    /// Replaces the v7.18 single-file `<db_path>.wal` layout.
1769    /// Each chunk file inside is named
1770    /// `<unix_us>_<leading_lsn>.wal` (zero-padded to 16 digits
1771    /// so default-lex sort = LSN order).
1772    wal_dir: PathBuf,
1773    /// Path of the currently-open chunk file inside `wal_dir`.
1774    /// Rotated at checkpoint and whenever the chunk crosses
1775    /// `checkpoint_threshold_bytes`. CoW-2 (v7.34) wraps it in
1776    /// `Arc<Mutex<…>>` because the background-checkpoint worker
1777    /// performs the rotation; this struct keeps a clone so Drop /
1778    /// diag introspection still see the live path.
1779    current_chunk_path: Arc<Mutex<PathBuf>>,
1780    /// v7.19 P3 — retention sweeper handle. `Some` when
1781    /// `SPG_PITR_RETENTION_HOURS > 0` at open_path time; `None`
1782    /// when retention is disabled (the default; v7.18 behaviour
1783    /// preserved). The thread polls `wal_dir` every
1784    /// `SPG_PITR_RETENTION_CHECK_SEC` seconds, archives via
1785    /// `SPG_PITR_ARCHIVE_CMD` if set, then deletes chunks older
1786    /// than the retention window. Signalled to exit via
1787    /// `retention_shutdown` on Drop.
1788    retention_shutdown: Option<Arc<AtomicBool>>,
1789    retention_thread: Option<std::thread::JoinHandle<()>>,
1790    /// v7.20 — background WAL flusher for
1791    /// `SPG_SYNCHRONOUS_COMMIT=off`. `None` in the default
1792    /// synchronous mode. Flushes the pending batch every
1793    /// `SPG_WAL_WRITER_DELAY_MS`; signalled + joined on Drop
1794    /// before the final checkpoint so clean shutdown never
1795    /// loses confirmed commits.
1796    flusher_shutdown: Option<Arc<AtomicBool>>,
1797    flusher_thread: Option<std::thread::JoinHandle<()>>,
1798    /// v7.20 P2 — group-commit WAL. Shared with WalTickets
1799    /// returned by the buffered write path so `wait()` can run
1800    /// after the engine write lock is released.
1801    wal: Arc<WalGroup>,
1802    checkpoint_threshold_bytes: u64,
1803    /// v7.1.4 — `<db_path>.spg/segments/` directory. Cold-tier
1804    /// segments produced by `freeze_oldest_to_cold` / compaction
1805    /// are persisted here as `seg_<id>.spg` files; the manifest
1806    /// at `<db_path>.spg/manifest.v10` records every active
1807    /// segment + its CRC32 so the next boot can verify + reload.
1808    cold_segments_dir: PathBuf,
1809    cold_segment_paths: BTreeMap<u32, PathBuf>,
1810    /// v7.17.0 Phase 6.2 — cross-process exclusion lock. Acquired
1811    /// via `fs::create_dir` on `<db_path>.lock` at open_path
1812    /// entry; released on Drop by `fs::remove_dir`. atomic on
1813    /// every supported platform. A second process opening the
1814    /// same path while the first is still alive hits the
1815    /// create_dir failure and returns
1816    /// `EngineError::Unsupported("database is locked by another
1817    /// process: …")`. Stale locks (process crashed mid-session)
1818    /// must be cleared via `Database::force_unlock(path)` —
1819    /// SPG can't safely fingerprint who owned a stale directory
1820    /// without a libc dep, which would violate spg-embedded's
1821    /// zero-deps charter.
1822    lock_path: PathBuf,
1823    /// v7.37.5 (mailrs crash-recovery Ask 1) — in-process registry
1824    /// guard. Drops alongside the rest of the Database, which
1825    /// de-registers `lock_path` from `ACTIVE_OPEN_PATHS`. Carried
1826    /// here so its lifetime exactly matches the live Database
1827    /// handle; a concurrent sibling open_path in the same process
1828    /// refuses honestly while this guard exists.
1829    lock_registry_guard: LockRegistryGuard,
1830    /// CoW-2 (v7.34) — background-checkpoint worker. `None` only
1831    /// transiently inside `Drop` after the worker has been signalled
1832    /// and joined. The worker carries Arc clones of `wal` and
1833    /// `current_chunk_path`, so it can rotate the active chunk and
1834    /// reflect the new path back here even after the front-end has
1835    /// returned to the caller.
1836    checkpoint_worker: Option<CheckpointWorker>,
1837}
1838
1839impl Database {
1840    /// Open a fresh in-memory database. No WAL, no catalog
1841    /// snapshot on disk — perfect for tests + short-lived
1842    /// CLI tools.
1843    #[must_use]
1844    pub fn open_in_memory() -> Self {
1845        Self {
1846            engine: engine_with_query_byte_budget(Engine::new().with_clock(wall_clock_micros)),
1847            persistence: None,
1848            commit_lsn: AtomicU64::new(0),
1849            tx_wal: None,
1850        }
1851    }
1852
1853    /// v7.1 — Open or create a persistent database backed by
1854    /// the file at `db_path`. The WAL lives at `db_path` +
1855    /// ".wal" (e.g. `./data/spg.db` → `./data/spg.db.wal`). Boot
1856    /// path:
1857    ///
1858    /// 1. If `db_path` exists, restore the catalog snapshot.
1859    /// 2. If the WAL exists, replay every record into the
1860    ///    restored engine — the same recovery story
1861    ///    `spg-server` uses.
1862    /// 3. Open the WAL in append+sync mode so subsequent
1863    ///    `execute()` writes durably commit (one fsync per
1864    ///    mutation).
1865    ///
1866    /// `Drop` writes a final catalog snapshot + truncates the
1867    /// WAL — operators that need a sync barrier at a specific
1868    /// point use `checkpoint()` explicitly.
1869    pub fn open_path(db_path: impl AsRef<Path>) -> Result<Self, EngineError> {
1870        // v7.37.7 A.1 — per-stage timing gated on env var SPG_OPEN_PATH_TIMING.
1871        // v7.37.5 ack reported `open_path 27min→646ms` after the WAL-replay
1872        // fix, but fresh-tarball benchmarks showed ~250 s — strong evidence
1873        // the ack number was on a warm OS page cache. These prints surface
1874        // where the time actually goes per Database::open_path call. Zero
1875        // cost when env unset (one syscall + branch per stage).
1876        let timing = std::env::var_os("SPG_OPEN_PATH_TIMING").is_some();
1877        let timing_start = std::time::Instant::now();
1878        let mut last_stage = timing_start;
1879        let mut stage = |name: &str, last: &mut std::time::Instant| {
1880            if timing {
1881                let now = std::time::Instant::now();
1882                eprintln!(
1883                    "[open_path/{name}] +{:.3}s (total {:.3}s)",
1884                    now.duration_since(*last).as_secs_f64(),
1885                    now.duration_since(timing_start).as_secs_f64()
1886                );
1887                *last = now;
1888            }
1889        };
1890        let db_path = db_path.as_ref().to_path_buf();
1891        stage("entry", &mut last_stage);
1892        // v7.19 — WAL is a directory of chunk files. Legacy
1893        // single-file path stays variable-named `wal_path` for
1894        // the backward-compat migration block below.
1895        let wal_path = {
1896            let mut p = db_path.clone();
1897            let name = p
1898                .file_name()
1899                .map(|n| {
1900                    let mut s = n.to_os_string();
1901                    s.push(".wal");
1902                    s
1903                })
1904                .unwrap_or_else(|| std::ffi::OsString::from(".wal"));
1905            p.set_file_name(name);
1906            p
1907        };
1908        let wal_dir = wal_path.clone();
1909        if let Some(parent) = db_path.parent()
1910            && !parent.as_os_str().is_empty()
1911        {
1912            std::fs::create_dir_all(parent).map_err(io_err)?;
1913        }
1914        // v7.17.0 Phase 6.2 — acquire cross-process exclusion
1915        // lock before touching any catalog / WAL bytes. atomic
1916        // mkdir on every supported platform; a second process
1917        // opening the same path while the first is still alive
1918        // hits the create_dir failure and gets a clear error.
1919        let lock_path = {
1920            let mut p = db_path.clone();
1921            let name = p
1922                .file_name()
1923                .map(|n| {
1924                    let mut s = n.to_os_string();
1925                    s.push(".lock");
1926                    s
1927                })
1928                .unwrap_or_else(|| std::ffi::OsString::from(".lock"));
1929            p.set_file_name(name);
1930            p
1931        };
1932        // v7.37.5 (mailrs crash-recovery Ask 1) — register the
1933        // lock_path in the in-process registry FIRST. Drop on this
1934        // guard de-registers automatically on any early return
1935        // below; storing it in `PersistenceCtx` ties its lifetime
1936        // to the live Database handle. See `LockRegistryGuard`
1937        // docs for why on-disk identity alone wasn't enough.
1938        let lock_registry_guard = LockRegistryGuard::try_acquire(&lock_path)?;
1939        acquire_path_lock(&lock_path)?;
1940        stage("locks", &mut last_stage);
1941        let mut engine = if db_path.exists() {
1942            let bytes = std::fs::read(&db_path).map_err(io_err)?;
1943            stage("fs::read_catalog", &mut last_stage);
1944            let engine = Engine::restore_envelope(&bytes).map_err(|e| {
1945                EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
1946                    "restore from {}: {e}",
1947                    db_path.display()
1948                )))
1949            })?;
1950            stage("restore_envelope", &mut last_stage);
1951            engine_with_query_byte_budget(engine.with_clock(wall_clock_micros))
1952        } else {
1953            engine_with_query_byte_budget(Engine::new().with_clock(wall_clock_micros))
1954        };
1955        // v7.1.4 — manifest-driven cold-segment reload. The
1956        // manifest sidecar pairs the catalog snapshot CRC with a
1957        // list of `(segment_id, path, crc32)` triples; verify
1958        // before loading so a torn or stale manifest doesn't
1959        // surface phantom data.
1960        let cold_segments_dir = {
1961            let parent = db_path.parent().unwrap_or_else(|| Path::new("."));
1962            let stem = db_path
1963                .file_stem()
1964                .unwrap_or_else(|| std::ffi::OsStr::new("db"))
1965                .to_string_lossy()
1966                .into_owned();
1967            parent.join(format!("{stem}.spg")).join("segments")
1968        };
1969        let mut cold_segment_paths: BTreeMap<u32, PathBuf> = BTreeMap::new();
1970        let manifest_pth = spg_manifest_path(&db_path);
1971        if manifest_pth.exists() && db_path.exists() {
1972            let m_bytes = std::fs::read(&manifest_pth).map_err(io_err)?;
1973            if let Ok(m) = CatalogManifest::deserialize(&m_bytes) {
1974                let snap_bytes = std::fs::read(&db_path).map_err(io_err)?;
1975                let snap_crc = spg_crypto::crc32::crc32(&snap_bytes);
1976                if snap_crc == m.catalog_crc32 {
1977                    for entry in &m.cold_segments {
1978                        if let Ok(seg_bytes) = std::fs::read(&entry.path) {
1979                            let computed = spg_crypto::crc32::crc32(&seg_bytes);
1980                            if computed != entry.crc32 {
1981                                eprintln!(
1982                                    "spg-embedded: manifest skip segment {}: CRC mismatch",
1983                                    entry.segment_id
1984                                );
1985                                continue;
1986                            }
1987                            if engine.catalog().cold_segment(entry.segment_id).is_some() {
1988                                // Already loaded via Catalog::clone path (shouldn't happen
1989                                // since Engine::new + restore_envelope don't populate cold).
1990                                continue;
1991                            }
1992                            let mut new_cat = engine.catalog().clone();
1993                            if let Err(e) =
1994                                new_cat.load_segment_bytes_at(entry.segment_id, seg_bytes)
1995                            {
1996                                eprintln!(
1997                                    "spg-embedded: manifest load segment {} failed: {e}",
1998                                    entry.segment_id
1999                                );
2000                                continue;
2001                            }
2002                            engine.replace_catalog(new_cat);
2003                            cold_segment_paths.insert(entry.segment_id, entry.path.clone());
2004                        } else {
2005                            eprintln!(
2006                                "spg-embedded: manifest skip segment {}: file unreadable",
2007                                entry.segment_id
2008                            );
2009                        }
2010                    }
2011                }
2012            }
2013        }
2014        // CoW-4 (v7.34) — D10 + missing-manifest fallback. Walk
2015        // `<db>.spg/segments/` and attach any `seg_<id>.spg` file that
2016        // the manifest didn't already cover (manifest absent / CRC
2017        // mismatched / a fresher freeze landed after the last
2018        // checkpoint wrote its manifest). The segment binary's own
2019        // magic + CRC32 guards integrity — no need to trust a stale
2020        // manifest entry to trust the file.
2021        stage("manifest+cold_segments", &mut last_stage);
2022        scan_cold_segments_dir(&cold_segments_dir, &mut engine, &mut cold_segment_paths);
2023        stage("scan_cold_segments_dir", &mut last_stage);
2024        // v7.19 — chunked WAL on-disk layout.
2025        //
2026        // Three cases handled here:
2027        //
2028        // 1. wal_dir exists as a DIRECTORY → scan its
2029        //    `<unix_us>_<leading_lsn>.wal` chunks (sorted
2030        //    lexicographically = chunk-creation order), replay
2031        //    them in sequence, advance the LSN watermark to the
2032        //    max commit_lsn seen.
2033        //
2034        // 2. wal_path exists as a FILE → legacy v7.18 layout.
2035        //    Migrate it: create `wal_dir/`, move the single file
2036        //    inside as `0000000000000000_0000000000000000.wal`,
2037        //    then fall through to case 1's replay loop.
2038        //
2039        // 3. Neither exists → fresh database; create wal_dir.
2040        let mut initial_lsn: u64 = 0;
2041        if wal_path.is_file() {
2042            // Case 2: legacy single-file WAL migration.
2043            let legacy_bytes = std::fs::read(&wal_path).map_err(io_err)?;
2044            std::fs::remove_file(&wal_path).map_err(io_err)?;
2045            std::fs::create_dir_all(&wal_dir).map_err(io_err)?;
2046            if !legacy_bytes.is_empty() {
2047                let migrated = wal_dir.join(legacy_chunk_filename());
2048                std::fs::write(&migrated, &legacy_bytes).map_err(io_err)?;
2049            }
2050        } else if !wal_dir.exists() {
2051            // Case 3: fresh database.
2052            std::fs::create_dir_all(&wal_dir).map_err(io_err)?;
2053        }
2054        // Cases 1 + 2 share replay logic now that wal_dir is
2055        // guaranteed to exist (and may be empty for case 3).
2056        //
2057        // Two-pass replay so we don't double-apply records the
2058        // snapshot already reflects:
2059        //
2060        // 1. Find the highest commit_lsn carried by a
2061        //    checkpoint_marker across all chunks. That LSN is the
2062        //    snapshot's high-water mark — anything ≤ it is
2063        //    already in `<db_path>` and replaying it would
2064        //    DuplicateTable / double-insert.
2065        // 2. Replay only records strictly above that LSN.
2066        //
2067        // Case 2 migration (legacy single-file WAL) lands here
2068        // too: the migrated chunk has no marker so the LSN floor
2069        // is 0 and every record applies — exactly the v7.18
2070        // behaviour the migration is supposed to preserve.
2071        let chunk_paths = sorted_wal_chunks(&wal_dir).map_err(io_err)?;
2072        stage("wal::sorted_chunks", &mut last_stage);
2073        let mut snapshot_lsn: u64 = 0;
2074        for chunk in &chunk_paths {
2075            let bytes = std::fs::read(chunk).map_err(io_err)?;
2076            if let Ok(records) = parse_wal_records(&bytes) {
2077                for r in &records {
2078                    if r.type_byte == WAL_V4_TYPE_CHECKPOINT_MARKER {
2079                        if let Some(l) = r.commit_lsn {
2080                            if l > snapshot_lsn {
2081                                snapshot_lsn = l;
2082                            }
2083                        }
2084                    }
2085                }
2086            }
2087        }
2088        stage("wal::snapshot_lsn_scan", &mut last_stage);
2089        let mut quarantined: Vec<QuarantinedStmt> = Vec::new();
2090        for chunk in &chunk_paths {
2091            let bytes = std::fs::read(chunk).map_err(io_err)?;
2092            if bytes.is_empty() {
2093                continue;
2094            }
2095            replay_wal_filtered(&bytes, &mut engine, snapshot_lsn, &mut quarantined)
2096                .map_err(|m| EngineError::Storage(spg_storage::StorageError::Corrupt(m)))?;
2097            if let Ok(records) = parse_wal_records(&bytes) {
2098                if let Some(max) = records.iter().filter_map(|r| r.commit_lsn).max() {
2099                    if max > initial_lsn {
2100                        initial_lsn = max;
2101                    }
2102                }
2103            }
2104        }
2105        stage("wal::replay_filtered", &mut last_stage);
2106        // v7.30.1 (mailrs round-24 ask 2) — replay rejects no longer
2107        // brick the open. Persist the rejected statements beside the
2108        // WAL chunks for forensics and say so loudly; the boot
2109        // continues with every other record applied.
2110        if !quarantined.is_empty() {
2111            let mut body = String::new();
2112            for q in &quarantined {
2113                body.push_str(&format_quarantine_line(q));
2114            }
2115            let qpath = wal_dir.join(format!(
2116                "quarantine-{:016x}.log",
2117                wall_clock_micros().max(0) as u64
2118            ));
2119            match std::fs::write(&qpath, &body) {
2120                Ok(()) => eprintln!(
2121                    "spg-embedded: WAL replay quarantined {} statement(s) — boot continues; \
2122                     forensics at {}",
2123                    quarantined.len(),
2124                    qpath.display()
2125                ),
2126                Err(e) => eprintln!(
2127                    "spg-embedded: WAL replay quarantined {} statement(s) — boot continues; \
2128                     quarantine file write FAILED ({e}), entries follow:\n{body}",
2129                    quarantined.len()
2130                ),
2131            }
2132        }
2133        // Open the "current" chunk — either the last existing
2134        // chunk file (so subsequent appends extend it until the
2135        // size threshold rotates) or a fresh first chunk.
2136        let now_us = wall_clock_micros();
2137        let current_chunk_path = if let Some(last) = chunk_paths.last() {
2138            last.clone()
2139        } else {
2140            wal_dir.join(chunk_filename(now_us, initial_lsn + 1))
2141        };
2142        let wal_file = OpenOptions::new()
2143            .create(true)
2144            .append(true)
2145            .read(true)
2146            .open(&current_chunk_path)
2147            .map_err(io_err)?;
2148        // Persist the (possibly freshly created) chunk's directory entry.
2149        fsync_dir(&wal_dir);
2150        let wal_len = wal_file.metadata().map_err(io_err)?.len();
2151        let wal = Arc::new(WalGroup::new(wal_file, wal_len));
2152        // v7.19 P3 — spawn retention sweep thread when the
2153        // operator opted in via SPG_PITR_RETENTION_HOURS > 0.
2154        // Otherwise stay on the v7.18 behaviour (chunks accumulate
2155        // until something else — backup-pitr archival, manual
2156        // cleanup — moves them).
2157        let retention_hours = pitr_retention_hours();
2158        let (retention_shutdown, retention_thread) = if retention_hours > 0 {
2159            let shutdown = Arc::new(AtomicBool::new(false));
2160            let shutdown_clone = Arc::clone(&shutdown);
2161            let wal_dir_clone = wal_dir.clone();
2162            let check_interval = std::time::Duration::from_secs(pitr_retention_check_sec());
2163            let archive_cmd = pitr_archive_cmd();
2164            let handle = std::thread::Builder::new()
2165                .name("spg-pitr-retention".into())
2166                .spawn(move || {
2167                    retention_sweep_loop(
2168                        wal_dir_clone,
2169                        retention_hours,
2170                        check_interval,
2171                        archive_cmd,
2172                        shutdown_clone,
2173                    );
2174                })
2175                .map_err(io_err)?;
2176            (Some(shutdown), Some(handle))
2177        } else {
2178            (None, None)
2179        };
2180        // v7.20 — background flusher for SPG_SYNCHRONOUS_COMMIT=off.
2181        let (flusher_shutdown, flusher_thread) = if synchronous_commit_on() {
2182            (None, None)
2183        } else {
2184            let shutdown = Arc::new(AtomicBool::new(false));
2185            let shutdown_clone = Arc::clone(&shutdown);
2186            let group = Arc::clone(&wal);
2187            let interval = std::time::Duration::from_millis(wal_writer_delay_ms());
2188            let handle = std::thread::Builder::new()
2189                .name("spg-wal-flusher".into())
2190                .spawn(move || {
2191                    while !shutdown_clone.load(Ordering::SeqCst) {
2192                        std::thread::sleep(interval);
2193                        if let Err(e) = group.flush_now() {
2194                            eprintln!("spg-embedded: background WAL flush failed: {e:?}");
2195                        }
2196                    }
2197                    // Final drain on shutdown signal.
2198                    let _ = group.flush_now();
2199                })
2200                .map_err(io_err)?;
2201            (Some(shutdown), Some(handle))
2202        };
2203        // v7.34 (crash-recovery P0 #2) — arm row-level redo capture for
2204        // subsequent writes (AFTER replay, so re-executed SQL records
2205        // don't capture; 0x13 records replay via apply_redo and never do).
2206        if row_redo_enabled() {
2207            engine.set_redo_capture(true);
2208        }
2209        let db = Self {
2210            engine,
2211            commit_lsn: AtomicU64::new(initial_lsn),
2212            tx_wal: None,
2213            persistence: Some(PersistenceCtx {
2214                db_path,
2215                wal_dir,
2216                current_chunk_path: Arc::new(Mutex::new(current_chunk_path)),
2217                wal,
2218                checkpoint_threshold_bytes: default_checkpoint_threshold_bytes(),
2219                cold_segments_dir,
2220                cold_segment_paths,
2221                lock_path,
2222                lock_registry_guard,
2223                retention_shutdown,
2224                retention_thread,
2225                flusher_shutdown,
2226                flusher_thread,
2227                checkpoint_worker: Some(CheckpointWorker::spawn()),
2228            }),
2229        };
2230        // v7.37.2 (mailrs prod 7.35 pool-exhaustion incident — surface
2231        // fix per `feedback-zero-customer-change-warmup-incident`) —
2232        // automatic cold-tier OS page-cache warm-up so the catalog is
2233        // fully server-ready on return. The client never sees a SPG-
2234        // specific call site; `open_path` behaves like PG's "ready to
2235        // accept queries" semantics. Bounded by
2236        // `SPG_WARM_UP_COLD_BUDGET_MS` (default unset = no cap;
2237        // env-only spec channel, never a client-visible API). `0` =
2238        // skip warm-up entirely (escape hatch for fast restart).
2239        stage("pre_autowarm", &mut last_stage);
2240        autowarm_cold_tier_on_open(&db);
2241        stage("autowarm", &mut last_stage);
2242        Ok(db)
2243    }
2244
2245    /// v7.1.4 — freeze the oldest `max_rows` of `table_name`'s
2246    /// hot tier into a brand-new cold-tier segment + persist
2247    /// it to disk. Same semantics as `spg-server`'s freezer
2248    /// thread; embedded just runs the freeze synchronously on
2249    /// the caller's thread. Persistence + manifest update
2250    /// happen as part of the next `checkpoint()` (or on Drop).
2251    pub fn freeze_oldest_to_cold(
2252        &mut self,
2253        table_name: &str,
2254        index_name: &str,
2255        max_rows: usize,
2256    ) -> Result<spg_storage::FreezeReport, EngineError> {
2257        let report = self
2258            .engine
2259            .freeze_oldest_to_cold(table_name, index_name, max_rows)?;
2260        if let Some(p) = &mut self.persistence {
2261            std::fs::create_dir_all(&p.cold_segments_dir).map_err(io_err)?;
2262            let final_path = p
2263                .cold_segments_dir
2264                .join(format!("seg_{}.spg", report.segment_id));
2265            let tmp_path = p
2266                .cold_segments_dir
2267                .join(format!("seg_{}.spg.tmp", report.segment_id));
2268            std::fs::write(&tmp_path, &report.segment_bytes).map_err(io_err)?;
2269            std::fs::rename(&tmp_path, &final_path).map_err(io_err)?;
2270            p.cold_segment_paths.insert(report.segment_id, final_path);
2271        }
2272        Ok(report)
2273    }
2274
2275    /// v7.1 — override the auto-checkpoint WAL-size ceiling for
2276    /// this `Database` instance. Default is
2277    /// `SPG_EMBEDDED_CHECKPOINT_BYTES` env (4 MiB if unset); the
2278    /// setter wins. No-op when the database is in-memory.
2279    pub fn set_checkpoint_threshold_bytes(&mut self, bytes: u64) {
2280        if let Some(p) = &mut self.persistence {
2281            p.checkpoint_threshold_bytes = bytes.max(1);
2282        }
2283    }
2284
2285    /// v7.31 (memory campaign, round-26 ask 1/ask 4) — per-bucket
2286    /// memory snapshot for the embedding host. Poll it from prod to
2287    /// see where resident bytes live (rows / representation /
2288    /// indexes per table) and to drive host-side shedding before
2289    /// the kernel does it. Same numbers as the server path's
2290    /// `SELECT * FROM spg_memory_stats`.
2291    #[must_use]
2292    pub fn memory_stats(&self) -> spg_engine::MemoryStats {
2293        let mut stats = self.engine.memory_stats();
2294        // v7.31 C2 — fill in bucket D: the engine leaves `wal_bytes`
2295        // None (it has no WAL); we report the live (uncheckpointed)
2296        // WAL footprint via the same `written_len()` meter `metrics()`
2297        // reads. In-memory databases have no persistence → stays None.
2298        if let Some(p) = &self.persistence {
2299            stats.wal_bytes = Some(p.wal.written_len());
2300        }
2301        stats
2302    }
2303
2304    /// v7.1 — flush a fresh catalog snapshot to `db_path` and
2305    /// rotate the WAL. Idempotent; cheap when nothing has happened
2306    /// since the last checkpoint. No-op when the database is in-memory.
2307    ///
2308    /// CoW-2 (v7.34): the heavy half (serialize + tmp+rename + fsync +
2309    /// marker enqueue + chunk rotation) runs on a dedicated worker thread
2310    /// so the caller's engine borrow is released after the cheap capture
2311    /// step. This entry point keeps the **synchronous** contract — it
2312    /// waits for the worker to finish before returning — so existing
2313    /// callers, tests, and operator scripts see no behaviour change;
2314    /// they just pay one extra hop. The non-blocking variant lives at
2315    /// `trigger_checkpoint`, used by the auto-checkpoint hot path so
2316    /// the write that crossed `SPG_EMBEDDED_CHECKPOINT_BYTES` doesn't
2317    /// stall on disk IO.
2318    ///
2319    /// Called automatically when:
2320    /// - the WAL grows past `SPG_EMBEDDED_CHECKPOINT_BYTES` (default
2321    ///   4 MiB) at the end of an `execute()` (via `trigger_checkpoint`,
2322    ///   non-blocking), and
2323    /// - `Drop` runs (synchronous; best-effort, failures logged).
2324    pub fn checkpoint(&mut self) -> Result<(), EngineError> {
2325        if self.persistence.is_none() {
2326            return Ok(());
2327        }
2328        // Drain any prior async checkpoint first so our snapshot reflects
2329        // post-it state (and so a sticky error from it surfaces here, not
2330        // smeared across the next two `wait`s).
2331        self.wait_checkpoint()?;
2332        let Some(job) = self.snapshot_checkpoint_job() else {
2333            return Ok(());
2334        };
2335        let Some(worker) = self
2336            .persistence
2337            .as_ref()
2338            .and_then(|p| p.checkpoint_worker.as_ref())
2339        else {
2340            return Ok(());
2341        };
2342        // `wait_checkpoint` above guaranteed idle; `try_enqueue` only
2343        // returns Ok(false) when busy, so we expect Ok(true) here. The
2344        // bool is dropped — we wait unconditionally to honour the sync
2345        // contract.
2346        let _ = worker.try_enqueue(job)?;
2347        self.wait_checkpoint()
2348    }
2349
2350    /// CoW-2 (v7.34) — non-blocking checkpoint trigger used by the
2351    /// auto-checkpoint hot path (`wal_after_ok` over the threshold).
2352    /// Captures the engine state under `&mut self` then signals the
2353    /// background worker and returns; the serialize / fsync / rotate
2354    /// sequence runs on the worker thread. If a checkpoint is already
2355    /// pending or in flight, the new trigger is silently dropped —
2356    /// the next threshold crossing picks up the newer state.
2357    ///
2358    /// Sticky errors from a prior async run surface here (via
2359    /// `try_enqueue`), so a failed background checkpoint still reaches
2360    /// the caller eventually rather than vanishing.
2361    fn trigger_checkpoint(&mut self) -> Result<(), EngineError> {
2362        if self.persistence.is_none() {
2363            return Ok(());
2364        }
2365        let Some(job) = self.snapshot_checkpoint_job() else {
2366            return Ok(());
2367        };
2368        let Some(worker) = self
2369            .persistence
2370            .as_ref()
2371            .and_then(|p| p.checkpoint_worker.as_ref())
2372        else {
2373            return Ok(());
2374        };
2375        let _accepted = worker.try_enqueue(job)?;
2376        Ok(())
2377    }
2378
2379    /// CoW-2 (v7.34) — block until the background checkpoint worker is
2380    /// idle. Used by sync `checkpoint()` and by Drop to ensure the final
2381    /// snapshot is durable before the process exits.
2382    fn wait_checkpoint(&self) -> Result<(), EngineError> {
2383        match self
2384            .persistence
2385            .as_ref()
2386            .and_then(|p| p.checkpoint_worker.as_ref())
2387        {
2388            Some(w) => w.wait(),
2389            None => Ok(()),
2390        }
2391    }
2392
2393    /// CoW-2 (v7.34) — capture a checkpoint job under `&mut self` (or
2394    /// `&self`, since reading from atomics + cheap clones don't mutate).
2395    /// Returns `None` if the database is in-memory.
2396    fn snapshot_checkpoint_job(&self) -> Option<CheckpointJob> {
2397        let p = self.persistence.as_ref()?;
2398        Some(CheckpointJob {
2399            snapshot: self.engine.snapshot_data(),
2400            marker_lsn: self.commit_lsn.load(Ordering::SeqCst),
2401            db_path: p.db_path.clone(),
2402            wal_dir: p.wal_dir.clone(),
2403            wal: Arc::clone(&p.wal),
2404            cold_segments: p
2405                .cold_segment_paths
2406                .iter()
2407                .map(|(&id, path)| (id, path.clone()))
2408                .collect(),
2409            current_chunk_path: Arc::clone(&p.current_chunk_path),
2410        })
2411    }
2412
2413    /// Restore a database from a previously-captured catalog
2414    /// snapshot. Pairs with `Database::snapshot()` for
2415    /// round-tripping in-memory state without going through
2416    /// the `spg-server` WAL.
2417    pub fn restore(snapshot: &[u8]) -> Result<Self, EngineError> {
2418        let engine = Engine::restore_envelope(snapshot).map_err(|e| {
2419            EngineError::Storage(spg_storage::StorageError::Corrupt(format!("restore: {e}")))
2420        })?;
2421        let db = Self {
2422            engine,
2423            persistence: None,
2424            commit_lsn: AtomicU64::new(0),
2425            tx_wal: None,
2426        };
2427        // v7.37.2 — auto-warm on snapshot restore for the same reason
2428        // `open_path` does (catalog is server-ready when constructor
2429        // returns; client never sees a SPG-specific warmup call).
2430        autowarm_cold_tier_on_open(&db);
2431        Ok(db)
2432    }
2433
2434    /// Take a catalog snapshot suitable for `Database::restore`.
2435    /// The bytes are SPG's canonical catalog envelope (FILE_MAGIC
2436    /// + version + payload); round-trips through every released
2437    /// SPG version per the STABILITY contract.
2438    #[must_use]
2439    pub fn snapshot(&self) -> Vec<u8> {
2440        self.engine.snapshot()
2441    }
2442
2443    /// v7.36 (mailrs ask #4) — programmatic `EXPLAIN` over `sql`,
2444    /// returning each line of the QUERY PLAN as an owned `String`.
2445    /// Skips the WAL (`EXPLAIN` is read-only) and runs against the
2446    /// engine's live catalog. Dogfood callers can attach the plan
2447    /// to a report or assert on its shape from a test without
2448    /// having to parse a tabular result themselves.
2449    ///
2450    /// `sql` is the inner SELECT (no `EXPLAIN` prefix); the helper
2451    /// adds it. For SQL with `$N` placeholders, substitute them
2452    /// into the SQL string before calling — programmatic
2453    /// placeholder-aware EXPLAIN is on the v7.37 plan.
2454    ///
2455    /// # Errors
2456    /// Propagates parse errors on `sql`, plus any engine error the
2457    /// `EXPLAIN` itself raises (table not found, column not found).
2458    pub fn explain(&self, sql: &str) -> Result<Vec<String>, EngineError> {
2459        let full = format!("EXPLAIN {sql}");
2460        let result = self.engine.execute_readonly(&full)?;
2461        Ok(extract_query_plan_lines(result))
2462    }
2463
2464    /// Write-side single-statement execute. Runs the SQL through
2465    /// the buffered group-commit pipeline and blocks until the
2466    /// resulting batch's WAL fsync returns. Read-only statements
2467    /// (SELECT / SHOW / EXPLAIN / BEGIN-COMMIT-ROLLBACK /
2468    /// CHECKPOINT / COMPACT etc.) skip the WAL entirely.
2469    pub fn execute(&mut self, sql: &str) -> Result<QueryResult, EngineError> {
2470        // v7.20 P2 — single-caller convenience over the buffered
2471        // path: enqueue + immediately wait. Batch size is 1 here,
2472        // so the durability behaviour (one fsync before Ok) is
2473        // identical to v7.19. Concurrent callers go through
2474        // `execute_buffered` (AsyncDatabase does) and share the
2475        // leader's fsync.
2476        let (result, ticket) = self.execute_buffered(sql)?;
2477        if let Some(t) = ticket {
2478            t.wait()?;
2479        }
2480        Ok(result)
2481    }
2482
2483    /// v7.20 P2 — group-commit write entry. Runs the engine
2484    /// mutation + encodes/enqueues the WAL record, then RETURNS
2485    /// WITHOUT waiting for the fsync. The caller must call
2486    /// [`WalTicket::wait`] before treating the write as durable
2487    /// — crucially, the caller can (and should) drop whatever
2488    /// lock guards this `Database` first, so the next writer's
2489    /// mutation overlaps this batch's fsync.
2490    ///
2491    /// `None` ticket = nothing hit the WAL (read-only statement,
2492    /// no-op DDL, or in-memory database) — the result is final
2493    /// as returned.
2494    ///
2495    /// # Errors
2496    /// Engine errors propagate unchanged. Auto-checkpoint (when
2497    /// the active chunk crosses the threshold) runs inline and
2498    /// may surface IO errors.
2499    pub fn execute_buffered(
2500        &mut self,
2501        sql: &str,
2502    ) -> Result<(QueryResult, Option<WalTicket>), EngineError> {
2503        let result = self.engine.execute(sql)?;
2504        let modified = matches!(
2505            &result,
2506            QueryResult::CommandOk {
2507                modified_catalog: true,
2508                ..
2509            }
2510        );
2511        let ticket = self.wal_after_ok(sql, modified)?;
2512        Ok((result, ticket))
2513    }
2514
2515    /// v7.21 (round-12 polish) — post-engine WAL bookkeeping shared
2516    /// by the simple ([`Self::execute_buffered`]) and prepared
2517    /// ([`Self::execute_prepared_buffered`]) write paths. `canonical`
2518    /// is the replay text (bind-final for prepared statements);
2519    /// `modified_catalog` comes from the engine result. Three routes:
2520    ///
2521    /// - transaction control → maintain [`Self::tx_wal`]: BEGIN opens
2522    ///   the buffer, COMMIT flushes it as ONE atomic
2523    ///   `WAL_V4_TYPE_TX_COMMIT_SQL` record, ROLLBACK drops it,
2524    ///   SAVEPOINT / ROLLBACK TO mark / truncate it. The engine has
2525    ///   already accepted the statement, so this only mirrors state.
2526    /// - inside an open transaction → buffer the statement (shadow-
2527    ///   catalog mutations report `modified_catalog: false`, so the
2528    ///   auto-commit arm below can't see them).
2529    /// - auto-commit mutation → classic per-statement v4 record.
2530    ///
2531    /// v7.18 PITR — v4 records carry commit LSN + wall-clock micros.
2532    /// The crash window remains one BATCH: replay re-applies
2533    /// idempotently exactly as before, and a torn batch tail drops
2534    /// cleanly (same torn-write handling).
2535    fn wal_after_ok(
2536        &mut self,
2537        canonical: &str,
2538        modified_catalog: bool,
2539    ) -> Result<Option<WalTicket>, EngineError> {
2540        if self.persistence.is_none() {
2541            return Ok(None);
2542        }
2543        let mut record = None;
2544        match tx_control_kind(canonical) {
2545            Some(TxControl::Begin) => {
2546                self.tx_wal = Some(TxWalBuffer::default());
2547            }
2548            Some(TxControl::Commit) => {
2549                if let Some(buf) = self.tx_wal.take()
2550                    && !buf.statements.is_empty()
2551                {
2552                    let script = buf.statements.join(";\n");
2553                    let lsn = self.commit_lsn.fetch_add(1, Ordering::SeqCst) + 1;
2554                    record = Some(encode_v4_tx_commit(&script, lsn, wall_clock_micros()));
2555                }
2556            }
2557            Some(TxControl::Rollback) => {
2558                self.tx_wal = None;
2559            }
2560            Some(TxControl::Savepoint(name)) => {
2561                if let Some(buf) = &mut self.tx_wal {
2562                    // PG name-reuse semantics: latest mark wins.
2563                    buf.savepoints.retain(|(n, _)| n != &name);
2564                    let mark = buf.statements.len();
2565                    buf.savepoints.push((name, mark));
2566                }
2567            }
2568            Some(TxControl::RollbackToSavepoint(name)) => {
2569                if let Some(buf) = &mut self.tx_wal
2570                    && let Some(pos) = buf.savepoints.iter().position(|(n, _)| n == &name)
2571                {
2572                    let mark = buf.savepoints[pos].1;
2573                    buf.statements.truncate(mark);
2574                    // Later savepoints die with the rollback; the
2575                    // target itself survives (PG keeps it
2576                    // re-rollbackable).
2577                    buf.savepoints.truncate(pos + 1);
2578                }
2579            }
2580            Some(TxControl::ReleaseSavepoint) => {
2581                // RELEASE folds the savepoint into the enclosing tx —
2582                // buffered statements stay. The mark also stays:
2583                // marks are only consulted by ROLLBACK TO, which the
2584                // engine validates first, so a dangling mark is
2585                // unreachable.
2586            }
2587            None => {
2588                if let Some(buf) = &mut self.tx_wal {
2589                    if !sql_is_read_only(canonical) {
2590                        buf.statements.push(canonical.to_string());
2591                    }
2592                } else if modified_catalog && !sql_is_read_only(canonical) {
2593                    let lsn = self.commit_lsn.fetch_add(1, Ordering::SeqCst) + 1;
2594                    // v7.34 (crash-recovery P0 #2) — hybrid log: when
2595                    // row-level redo is on and this statement produced row
2596                    // changes (DML), write a physical 0x13 redo record so
2597                    // replay applies it directly. A statement with no row
2598                    // changes (DDL: CREATE/ALTER, never goes through
2599                    // Table::insert/update/delete) drains an empty redo and
2600                    // keeps the SQL record so the schema still replays.
2601                    let redo = if row_redo_enabled() {
2602                        self.engine.take_redo()
2603                    } else {
2604                        Vec::new()
2605                    };
2606                    record = Some(if redo.is_empty() {
2607                        encode_v4_auto_commit(canonical, lsn, wall_clock_micros())
2608                    } else {
2609                        encode_v5_row_redo(
2610                            &spg_storage::encode_redo_log(&redo),
2611                            lsn,
2612                            wall_clock_micros(),
2613                        )
2614                    });
2615                }
2616            }
2617        }
2618        let mut ticket = None;
2619        if let Some(record) = record {
2620            let p = self.persistence.as_mut().expect("checked above");
2621            let seq = p.wal.enqueue(&record);
2622            ticket = Some(WalTicket {
2623                group: Arc::clone(&p.wal),
2624                seq,
2625            });
2626            if p.wal.written_len() >= p.checkpoint_threshold_bytes {
2627                // CoW-2 (v7.34): hot path — fire-and-forget. The worker
2628                // serializes off this thread so the commit that just
2629                // crossed the threshold doesn't stall on a multi-hundred-ms
2630                // snapshot write. Any sticky error from a prior async
2631                // checkpoint surfaces here.
2632                self.trigger_checkpoint()?;
2633            }
2634        }
2635        Ok(ticket)
2636    }
2637
2638    /// v7.3.0 — typed-row variant of [`Database::query`]. Each
2639    /// row decodes into a `T: FromSpgRow` so callers don't
2640    /// pattern-match on `Value` themselves. Use [`spg_row!`] to
2641    /// generate the impl, or write it by hand.
2642    pub fn query_typed<T: FromSpgRow>(&mut self, sql: &str) -> Result<Vec<T>, EngineError> {
2643        let rows = self.query(sql)?;
2644        rows.into_iter().map(|r| T::from_spg_row(&r)).collect()
2645    }
2646
2647    /// Run a SELECT and return rows as a `Vec<Vec<Value>>` —
2648    /// strips the column-schema metadata for read-side
2649    /// ergonomics. Errors on non-Rows results (DML / DDL
2650    /// statements should go through `execute` instead).
2651    pub fn query(&mut self, sql: &str) -> Result<Vec<Vec<Value<'static>>>, EngineError> {
2652        match self.engine.execute(sql)? {
2653            QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
2654            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2655                "query() expects a SELECT — use execute() for DML/DDL".into(),
2656            )),
2657            // v7.5.0 — QueryResult is #[non_exhaustive]; any future
2658            // variant is not a SELECT row stream, treat as Unsupported.
2659            _ => Err(EngineError::Unsupported(
2660                "query() expects a SELECT — use execute() for DML/DDL".into(),
2661            )),
2662        }
2663    }
2664
2665    /// v7.16.0 — column-aware variant of [`Self::query`].
2666    /// Returns the column schema vec alongside the rows so
2667    /// adapters (the spg-sqlx Row impl most notably) can drive
2668    /// name + type-based column lookups. Errors on non-Rows
2669    /// results identically to `query`.
2670    pub fn query_with_columns(
2671        &mut self,
2672        sql: &str,
2673    ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value<'static>>>), EngineError> {
2674        match self.engine.execute(sql)? {
2675            QueryResult::Rows { columns, rows } => {
2676                Ok((columns, rows.into_iter().map(|r| r.values).collect()))
2677            }
2678            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2679                "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
2680            )),
2681            _ => Err(EngineError::Unsupported(
2682                "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
2683            )),
2684        }
2685    }
2686
2687    /// v7.16.0 — column-aware variant of
2688    /// [`Self::query_prepared`]. Same shape as
2689    /// `query_with_columns` but driven from a prepared
2690    /// statement + bound params.
2691    pub fn query_prepared_with_columns(
2692        &mut self,
2693        stmt: &Statement,
2694        params: &[Value<'static>],
2695    ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value<'static>>>), EngineError> {
2696        match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
2697            QueryResult::Rows { columns, rows } => {
2698                Ok((columns, rows.into_iter().map(|r| r.values).collect()))
2699            }
2700            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2701                "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2702            )),
2703            _ => Err(EngineError::Unsupported(
2704                "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2705            )),
2706        }
2707    }
2708
2709    /// Borrow the underlying engine. Escape hatch for callers
2710    /// that need access to `spg-engine` APIs not yet surfaced
2711    /// here (transactions, EXPLAIN ANALYZE, etc.).
2712    #[must_use]
2713    pub const fn engine(&self) -> &Engine {
2714        &self.engine
2715    }
2716
2717    /// Mutable borrow of the underlying engine. Same intent as
2718    /// `engine()` but for write-side APIs (e.g. inserting
2719    /// directly through `Catalog::insert` for high-throughput
2720    /// bulk loads that bypass SQL parsing).
2721    pub const fn engine_mut(&mut self) -> &mut Engine {
2722        &mut self.engine
2723    }
2724
2725    /// v7.38 (mailrs prod 7.35 pool-exhaustion incident) — boot-time
2726    /// plan-IR cache warm-up. Pre-prepares the listed SQL shapes so
2727    /// the first user-facing request doesn't pay the 2-3 s
2728    /// first-fire parse + JOIN-reorder cost on the readonly-blocking
2729    /// pool. Recommended call site: `Database::new` immediately after
2730    /// catalog restore, before serving any traffic. Returns the
2731    /// number of statements successfully cached.
2732    pub fn warm_up_plan_cache(&mut self, sqls: &[&str]) -> usize {
2733        self.engine.warm_up_plan_cache(sqls)
2734    }
2735
2736    /// v7.38 (mailrs prod 7.35 pool-exhaustion incident) — boot-time
2737    /// cold-tier OS page-cache warm-up. Touches every cold segment
2738    /// file in the active catalog so the kernel page cache loads
2739    /// them before user traffic arrives. On a hot-only catalog the
2740    /// call is a near-no-op. Returns the total cold rows touched.
2741    pub fn warm_up_cold_tier(&self) -> usize {
2742        self.engine.warm_up_cold_tier()
2743    }
2744
2745    /// v7.16.0 — parse + plan a SQL string ONCE so subsequent
2746    /// `execute_prepared` / `query_prepared` calls can re-bind
2747    /// parameters without re-parsing. The returned [`Statement`]
2748    /// is a thin handle around the AST + cached source SQL; it's
2749    /// `Clone` so the same plan can drive many bind calls
2750    /// concurrently (each call clones the AST and runs
2751    /// placeholder substitution on the clone — the cached
2752    /// plan stays intact).
2753    ///
2754    /// Plan caching follows the engine's existing version-aware
2755    /// rule: a prepared `Statement` whose statistics version
2756    /// has rolled (ANALYZE ran between prepare and execute)
2757    /// will silently re-prepare under the hood. Callers don't
2758    /// need to detect this.
2759    ///
2760    /// Placeholders in the SQL use PG's `$1`, `$2`, … convention.
2761    /// `bind`-time `Value`s are passed as a slice; arity
2762    /// mismatches surface as `EvalError::PlaceholderOutOfRange`
2763    /// at `execute_prepared` time, not here.
2764    ///
2765    /// # Errors
2766    /// Surfaces `EngineError` (parse error / plan rewrite
2767    /// failure) from the underlying `Engine::prepare`.
2768    pub fn prepare(&mut self, sql: &str) -> Result<Statement, EngineError> {
2769        // Use the cached path so repeated prepares of the same
2770        // SQL are O(1). The engine's plan cache stays shared
2771        // across all callers of this Database — a single
2772        // `PgPool`-shaped consumer (or, later, the spg-sqlx
2773        // adapter) prepares once and reaps the win on every bind.
2774        let stmt = self
2775            .engine
2776            .prepare_cached(sql)
2777            .map_err(EngineError::Parse)?;
2778        Ok(Statement {
2779            stmt,
2780            sql: sql.to_string(),
2781        })
2782    }
2783
2784    /// v7.17.0 Phase 3.P0-66 — describe a SQL string without
2785    /// executing. Returns `(parameter_oid_count, output_columns)`
2786    /// where `output_columns` is empty for non-SELECT statements
2787    /// or for SELECT shapes the describe planner can't resolve
2788    /// (JOIN / subquery / unknown table). Wraps
2789    /// `Engine::describe_prepared` so the spg-sqlx bridge can
2790    /// surface PG-shape Describe replies for
2791    /// `sqlx::query!()` compile-time validation.
2792    ///
2793    /// # Errors
2794    /// Propagates parse errors from the underlying prepare path.
2795    pub fn describe(&mut self, sql: &str) -> Result<(Vec<u32>, Vec<ColumnSchema>), EngineError> {
2796        let stmt = self
2797            .engine
2798            .prepare_cached(sql)
2799            .map_err(EngineError::Parse)?;
2800        Ok(self.engine.describe_prepared(&stmt))
2801    }
2802
2803    /// v7.16.0 — execute a prepared statement with bound
2804    /// parameters. Mirrors `Engine::execute_prepared`: clones
2805    /// the AST, substitutes `$1..$N` → `params[0..N-1]`, runs.
2806    ///
2807    /// Persistence (WAL fsync + auto-checkpoint) follows the
2808    /// same rules as `execute(sql)`: mutating statements get a
2809    /// WAL record AFTER the in-memory exec succeeds. The WAL
2810    /// record carries the substituted, bind-final SQL, so
2811    /// replay reconstructs the same row state without needing
2812    /// the original prepared `Statement` to still be alive.
2813    ///
2814    /// # Errors
2815    /// Propagates engine errors. Param arity mismatch surfaces
2816    /// as `EvalError::PlaceholderOutOfRange`.
2817    pub fn execute_prepared(
2818        &mut self,
2819        stmt: &Statement,
2820        params: &[Value<'static>],
2821    ) -> Result<QueryResult, EngineError> {
2822        let (result, ticket) = self.execute_prepared_buffered(stmt, params)?;
2823        if let Some(t) = ticket {
2824            t.wait()?;
2825        }
2826        Ok(result)
2827    }
2828
2829    /// v7.20 P2 — group-commit variant of
2830    /// [`Database::execute_prepared`]. Same contract as
2831    /// [`Database::execute_buffered`]: mutation + enqueue happen
2832    /// here; the caller waits on the ticket AFTER releasing
2833    /// whatever lock guards this `Database`.
2834    ///
2835    /// # Errors
2836    /// Engine errors propagate unchanged; inline auto-checkpoint
2837    /// may surface IO errors.
2838    pub fn execute_prepared_buffered(
2839        &mut self,
2840        stmt: &Statement,
2841        params: &[Value<'static>],
2842    ) -> Result<(QueryResult, Option<WalTicket>), EngineError> {
2843        let result = self.engine.execute_prepared(stmt.stmt.clone(), params)?;
2844        let modified = matches!(
2845            &result,
2846            QueryResult::CommandOk {
2847                modified_catalog: true,
2848                ..
2849            }
2850        );
2851        // WAL persistence on the bind-final SQL. Build the
2852        // canonical Display form by re-printing the
2853        // placeholder-substituted statement (cheap — the AST
2854        // is already in hand from execute_prepared's internal
2855        // clone) so replay's path is identical to the
2856        // simple-query path. v7.21: also when a transaction is
2857        // open — in-tx mutations report `modified_catalog: false`
2858        // but must reach the tx WAL buffer (see `wal_after_ok`).
2859        let mut ticket = None;
2860        if self.persistence.is_some()
2861            && (modified
2862                || (self.tx_wal.is_some() && !sql_is_read_only(&stmt.sql))
2863                || tx_control_kind(&stmt.sql).is_some())
2864        {
2865            let mut wal_stmt = stmt.stmt.clone();
2866            crate::wal_render_with_params(&mut wal_stmt, params);
2867            let canonical = format!("{wal_stmt}");
2868            ticket = self.wal_after_ok(&canonical, modified)?;
2869        }
2870        Ok((result, ticket))
2871    }
2872
2873    /// v7.16.0 — run a prepared SELECT with bound params and
2874    /// return rows as `Vec<Vec<Value>>`, matching `query()`
2875    /// shape. SELECTs are read-only so this never writes the
2876    /// WAL.
2877    ///
2878    /// # Errors
2879    /// Returns `Unsupported` if the prepared statement isn't a
2880    /// SELECT (use `execute_prepared` for DML/DDL).
2881    pub fn query_prepared(
2882        &mut self,
2883        stmt: &Statement,
2884        params: &[Value<'static>],
2885    ) -> Result<Vec<Vec<Value<'static>>>, EngineError> {
2886        match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
2887            QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
2888            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2889                "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2890            )),
2891            _ => Err(EngineError::Unsupported(
2892                "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2893            )),
2894        }
2895    }
2896
2897    /// v7.18 — parse + plan a SQL string against a
2898    /// `CatalogSnapshot`. Mirror of [`Database::prepare`] for the
2899    /// readonly fan-out path: no writer lock taken, no WAL write,
2900    /// no plan-cache mutation. Static-on-`Self` so callers can
2901    /// dispatch against a snapshot without an `&mut Database`
2902    /// borrow — `AsyncReadHandle::prepare` in spg-embedded-tokio
2903    /// is the load-bearing consumer.
2904    ///
2905    /// # Errors
2906    /// Propagates `EngineError::Parse` from the parser.
2907    pub fn prepare_on_snapshot(
2908        snapshot: &CatalogSnapshot,
2909        sql: &str,
2910    ) -> Result<Statement, EngineError> {
2911        let stmt =
2912            spg_engine::Engine::prepare_on_snapshot(snapshot, sql).map_err(EngineError::Parse)?;
2913        Ok(Statement {
2914            stmt,
2915            sql: sql.to_string(),
2916        })
2917    }
2918
2919    /// v7.18 — execute a prepared `Statement` against a
2920    /// `CatalogSnapshot` with bound params. Mirror of
2921    /// [`Database::execute_prepared`] on the readonly path:
2922    /// writes / DDL hit `EngineError::WriteRequired`. No WAL
2923    /// write, no writer lock, multiple snapshots can run
2924    /// concurrently — the snapshot is immutable from prepare time.
2925    ///
2926    /// # Errors
2927    /// Surfaces `EngineError::WriteRequired` for non-readonly
2928    /// statements; propagates other engine errors.
2929    pub fn execute_prepared_on_snapshot(
2930        snapshot: &CatalogSnapshot,
2931        stmt: &Statement,
2932        params: &[Value<'static>],
2933    ) -> Result<QueryResult, EngineError> {
2934        spg_engine::Engine::execute_readonly_prepared_on_snapshot(
2935            snapshot,
2936            stmt.stmt.clone(),
2937            params,
2938        )
2939    }
2940
2941    /// v7.28 (round-22) — deadline-bounded variant of
2942    /// [`Database::execute_prepared_on_snapshot`]. Returns
2943    /// `EngineError::Cancelled` once the budget elapses; the
2944    /// sqlx driver uses this to keep readonly-INLINE execution
2945    /// from monopolising the caller's async runtime (four slow
2946    /// inbox queries saturated mailrs's whole tokio pool) and
2947    /// re-runs over the blocking pool on timeout.
2948    ///
2949    /// # Errors
2950    /// `EngineError::Cancelled` on budget expiry; engine errors
2951    /// otherwise.
2952    pub fn execute_prepared_on_snapshot_with_budget(
2953        snapshot: &CatalogSnapshot,
2954        stmt: &Statement,
2955        params: &[Value<'static>],
2956        budget_us: u64,
2957    ) -> Result<QueryResult, EngineError> {
2958        fn mono_now_us() -> u64 {
2959            use std::time::{SystemTime, UNIX_EPOCH};
2960            // Monotonic enough for a per-call relative budget: the
2961            // engine only compares (now - start) against the budget
2962            // within one call.
2963            SystemTime::now()
2964                .duration_since(UNIX_EPOCH)
2965                .map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX))
2966                .unwrap_or(0)
2967        }
2968        let deadline = mono_now_us().saturating_add(budget_us);
2969        let token = spg_engine::CancelToken::none().with_deadline(mono_now_us, deadline);
2970        spg_engine::Engine::execute_readonly_prepared_on_snapshot_with_cancel(
2971            snapshot,
2972            stmt.stmt.clone(),
2973            params,
2974            token,
2975        )
2976    }
2977
2978    /// v7.18 — describe a SQL string against a
2979    /// `CatalogSnapshot`. Mirror of [`Database::describe`] on
2980    /// the readonly path. Pure function on the snapshot's
2981    /// catalog; safe to call from any thread.
2982    ///
2983    /// # Errors
2984    /// Propagates `EngineError::Parse` from the parser.
2985    pub fn describe_on_snapshot(
2986        snapshot: &CatalogSnapshot,
2987        sql: &str,
2988    ) -> Result<(Vec<u32>, Vec<ColumnSchema>), EngineError> {
2989        let stmt =
2990            spg_engine::Engine::prepare_on_snapshot(snapshot, sql).map_err(EngineError::Parse)?;
2991        Ok(spg_engine::Engine::describe_prepared_on_snapshot(
2992            snapshot, &stmt,
2993        ))
2994    }
2995
2996    /// v7.21 (round-12 polish) — run a multi-statement SQL script
2997    /// with PG simple-query semantics: the statements execute in
2998    /// order inside ONE implicit transaction, so a mid-script error
2999    /// rolls back the whole script (PG wraps every simple-query
3000    /// message in an implicit transaction). Three exceptions, all
3001    /// PG-faithful:
3002    ///
3003    /// - a script that carries its OWN transaction control
3004    ///   (BEGIN / COMMIT / …) runs statement-by-statement — the
3005    ///   script owns its boundaries;
3006    /// - a script run while the caller already has a transaction
3007    ///   open joins that transaction (no nested BEGIN), and the
3008    ///   caller's COMMIT / ROLLBACK decides its fate;
3009    /// - a single-statement script is plain auto-commit.
3010    ///
3011    /// Returns one `QueryResult` per executed statement. This is the
3012    /// engine behind `sqlx::raw_sql` (mailrs feeds whole
3013    /// `init-schema.sql` files through it) and `spgctl import`.
3014    ///
3015    /// # Errors
3016    /// The first failing statement's error propagates after the
3017    /// implicit ROLLBACK; nothing from the script remains applied.
3018    pub fn execute_script(&mut self, sql: &str) -> Result<Vec<QueryResult>, EngineError> {
3019        let stmts = split_statements(sql);
3020        let script_owns_tx = stmts.iter().any(|s| tx_control_kind(s).is_some());
3021        let wrap = stmts.len() > 1 && !script_owns_tx && !self.engine.in_transaction();
3022        if !wrap {
3023            let mut out = Vec::with_capacity(stmts.len());
3024            for stmt in &stmts {
3025                out.push(self.execute_dump_statement(stmt)?);
3026            }
3027            return Ok(out);
3028        }
3029        self.execute("BEGIN")?;
3030        let mut out = Vec::with_capacity(stmts.len());
3031        for stmt in &stmts {
3032            match self.execute_dump_statement(stmt) {
3033                Ok(r) => out.push(r),
3034                Err(e) => {
3035                    // Best-effort rollback; surface the script error.
3036                    let _ = self.execute("ROLLBACK");
3037                    return Err(e);
3038                }
3039            }
3040        }
3041        self.execute("COMMIT")?;
3042        Ok(out)
3043    }
3044
3045    /// v7.22 (round-13 T2) — execute one `split_statements` chunk,
3046    /// lowering a `COPY … FROM stdin;` block (statement + its data
3047    /// lines, as one chunk) to per-row INSERTs through the shared
3048    /// `spg_engine::copy` helpers. Default-format pg_dump emits
3049    /// COPY blocks, so the zero-change import promise needs this on
3050    /// the embed path; non-COPY statements pass straight through to
3051    /// [`Self::execute`]. Public so `spgctl import` can keep its
3052    /// per-statement error indexing while sharing the lowering.
3053    ///
3054    /// # Errors
3055    /// Engine errors propagate; for COPY the failing row's INSERT
3056    /// error carries the synthesized statement context.
3057    pub fn execute_dump_statement(&mut self, stmt: &str) -> Result<QueryResult, EngineError> {
3058        // Strip pg_dump's `-- Data for Name: …;` banner (it carries
3059        // semicolons of its own) before splitting head from data.
3060        let stmt_clean = strip_leading_sql_noise(stmt);
3061        let head_is_copy = stmt_clean
3062            .get(..4)
3063            .is_some_and(|p| p.eq_ignore_ascii_case("copy"));
3064        if head_is_copy
3065            && let Some((head, data)) = stmt_clean.split_once(';')
3066            && let Some(spec) = spg_engine::copy::parse_copy_from_stdin_head(head)
3067        {
3068            let mut affected: usize = 0;
3069            for line in data.lines() {
3070                // Empty fragments only occur at the chunk boundary
3071                // (the remainder of the COPY line right after `;`);
3072                // data rows are whole non-empty lines.
3073                let line = line.strip_suffix('\r').unwrap_or(line);
3074                if line.is_empty() {
3075                    continue;
3076                }
3077                let values = spg_engine::copy::decode_copy_text_row(line);
3078                let insert = spg_engine::copy::build_copy_insert(
3079                    &spec.table,
3080                    spec.columns.as_deref(),
3081                    &values,
3082                );
3083                match self.execute(&insert)? {
3084                    QueryResult::CommandOk { affected: n, .. } => affected += n,
3085                    _ => affected += 1,
3086                }
3087            }
3088            return Ok(QueryResult::CommandOk {
3089                affected,
3090                modified_catalog: false,
3091            });
3092        }
3093        self.execute(stmt)
3094    }
3095
3096    /// v7.2.0 — run `body` inside an implicit `BEGIN` /
3097    /// `COMMIT` pair. The body receives `&mut Database` so it
3098    /// can `execute()` / `query()` like any other code path;
3099    /// the only difference is that every write in the body
3100    /// lands inside one transaction, and a returned `Err` from
3101    /// the body triggers `ROLLBACK` before the error propagates.
3102    ///
3103    /// Nested calls are not supported — SPG's transaction
3104    /// model is single-writer with explicit `BEGIN` /
3105    /// `COMMIT` / `ROLLBACK`, and a nested `with_transaction`
3106    /// would hit `EngineError::Unsupported("nested
3107    /// transaction")` at the inner `BEGIN`.
3108    pub fn with_transaction<R, F>(&mut self, body: F) -> Result<R, EngineError>
3109    where
3110        F: FnOnce(&mut Self) -> Result<R, EngineError>,
3111    {
3112        self.execute("BEGIN")?;
3113        match body(self) {
3114            Ok(value) => {
3115                self.execute("COMMIT")?;
3116                Ok(value)
3117            }
3118            Err(e) => {
3119                // Best-effort rollback. If ROLLBACK itself
3120                // fails (rare — the engine reports it via
3121                // `Unsupported` only when there's no active
3122                // TX, which can't happen here) we surface the
3123                // original body error, not the rollback error.
3124                let _ = self.execute("ROLLBACK");
3125                Err(e)
3126            }
3127        }
3128    }
3129}
3130
3131impl Default for Database {
3132    fn default() -> Self {
3133        Self::open_in_memory()
3134    }
3135}
3136
3137/// v7.7.5 — observability snapshot returned by
3138/// [`Database::metrics`]. Plain data, no allocations beyond
3139/// what the struct itself takes; cheap to construct and
3140/// cheap to serialise.
3141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3142#[non_exhaustive]
3143pub struct EmbeddedMetrics {
3144    /// Total live row count across every user table (hot
3145    /// tier only — cold-tier rows live in segment files).
3146    pub hot_rows: u64,
3147    /// Sum of `Table::hot_bytes` across every user table.
3148    /// Tracks against the freezer's `hot_tier_bytes` budget.
3149    pub hot_bytes: u64,
3150    /// Number of cold-tier segments registered in the catalog.
3151    /// Includes tombstoned slots (segments retired by
3152    /// compaction whose disk file may still be on disk).
3153    pub cold_segments: u64,
3154    /// User-table count (excludes any future engine-managed
3155    /// internal tables).
3156    pub tables: u64,
3157    /// WAL size at last `execute()` / `checkpoint()`. Zero
3158    /// when the database is in-memory.
3159    pub wal_bytes: u64,
3160    /// `true` when the database was opened with `open_path` —
3161    /// i.e. WAL + checkpoint persistence is active.
3162    pub persistent: bool,
3163}
3164
3165/// v7.2.1 — handle returned by `spawn_background_freezer`.
3166/// Drop signals the worker thread to wind down + joins it,
3167/// so a `Database` (or its shared `Arc<Mutex<Database>>`)
3168/// can safely drop after the handle does.
3169#[must_use = "the background freezer keeps running until this handle is dropped"]
3170#[derive(Debug)]
3171pub struct FreezerHandle {
3172    shutdown: Arc<AtomicBool>,
3173    join: Option<JoinHandle<()>>,
3174}
3175
3176impl FreezerHandle {
3177    /// v7.2.1 — request the worker stop + join. Idempotent;
3178    /// safe to call from `Drop` (which also calls it).
3179    pub fn stop(&mut self) {
3180        self.shutdown.store(true, Ordering::Release);
3181        if let Some(h) = self.join.take() {
3182            let _ = h.join();
3183        }
3184    }
3185}
3186
3187impl Drop for FreezerHandle {
3188    fn drop(&mut self) {
3189        self.stop();
3190    }
3191}
3192
3193/// v7.2.1 — knobs for `Database::spawn_background_freezer`.
3194#[derive(Debug, Clone)]
3195pub struct FreezerOptions {
3196    /// Tick interval. Worker wakes every `tick`, checks the
3197    /// catalog's `hot_tier_bytes`, and freezes if over budget.
3198    pub tick: Duration,
3199    /// Hot-tier byte budget. Exceeded → next tick freezes the
3200    /// largest table's oldest `batch_rows` rows into a new
3201    /// cold segment.
3202    pub hot_tier_bytes: u64,
3203    /// Max rows the freezer demotes per fire.
3204    pub batch_rows: usize,
3205    /// v7.7.4 — auto-compact threshold. When the catalog has
3206    /// at least this many cold segments across all tables, the
3207    /// freezer fires a compaction pass after its next freeze.
3208    /// Set to `usize::MAX` to disable auto-compact entirely;
3209    /// the default is `64`, matching the `spg-server` operating
3210    /// point for SPG_COLD_COMPACT_SEGMENT_THRESHOLD.
3211    pub compact_when_segments_exceed: usize,
3212    /// v7.7.4 — target segment size for compaction merges,
3213    /// in bytes. Default 64 MiB, mirroring `spg-server`. Small
3214    /// segments below this size are merge candidates;
3215    /// segments at or above stay untouched.
3216    pub compact_target_bytes: u64,
3217}
3218
3219impl Default for FreezerOptions {
3220    fn default() -> Self {
3221        // Match the `spg-server` freezer's default operating
3222        // point (SPG_HOT_TIER_BYTES = 4 GiB, batch 1000 rows,
3223        // tick every 1 s) so embedded behaviour is predictable
3224        // for operators familiar with the server.
3225        Self {
3226            tick: Duration::from_secs(1),
3227            hot_tier_bytes: 4 * 1024 * 1024 * 1024,
3228            batch_rows: 1000,
3229            compact_when_segments_exceed: 64,
3230            compact_target_bytes: 64 * 1024 * 1024,
3231        }
3232    }
3233}
3234
3235impl Database {
3236    /// v7.7.4 — observe the catalog's cold-segment count.
3237    /// Useful for tests + dashboards that want to verify
3238    /// auto-compaction is firing.
3239    #[must_use]
3240    pub fn cold_segment_count(&self) -> usize {
3241        self.engine.catalog().cold_segment_count()
3242    }
3243
3244    /// v7.7.5 — observability snapshot. Returns a point-in-time
3245    /// view of the engine + persistence counters. Cheap (no
3246    /// locks beyond the existing `&self` borrow), so safe to
3247    /// call from a hot metrics-scrape path.
3248    ///
3249    /// Fields mirror the operational dashboard
3250    /// [`spg-server`](https://crates.io/crates/spg-server) exposes,
3251    /// minus the network counters that don't apply to embedded.
3252    #[must_use]
3253    pub fn metrics(&self) -> EmbeddedMetrics {
3254        let cat = self.engine.catalog();
3255        let mut hot_rows: u64 = 0;
3256        let mut hot_bytes: u64 = 0;
3257        for name in cat.table_names() {
3258            if let Some(t) = cat.get(&name) {
3259                hot_rows = hot_rows.saturating_add(t.row_count() as u64);
3260                hot_bytes = hot_bytes.saturating_add(t.hot_bytes());
3261            }
3262        }
3263        let (wal_bytes, persistent) = match &self.persistence {
3264            Some(p) => (p.wal.written_len(), true),
3265            None => (0, false),
3266        };
3267        EmbeddedMetrics {
3268            hot_rows,
3269            hot_bytes,
3270            cold_segments: cat.cold_segment_count() as u64,
3271            tables: cat.table_count() as u64,
3272            wal_bytes,
3273            persistent,
3274        }
3275    }
3276
3277    /// v7.2.1 — spawn a background thread that periodically
3278    /// runs `freeze_oldest_to_cold` when the catalog-wide hot
3279    /// tier exceeds `opts.hot_tier_bytes`. The `Arc<Mutex<_>>`
3280    /// pattern matches the v7.2 sharing story: callers wrap
3281    /// their `Database` in `Arc::new(Mutex::new(db))` once,
3282    /// then clone the Arc for the worker + for foreground
3283    /// access. Return value is a handle whose `Drop` joins the
3284    /// worker.
3285    ///
3286    /// Picks the freeze target the same way `spg-server`'s
3287    /// freezer does: largest-`hot_bytes` user table with at
3288    /// least one BTree integer-PK index. Tables without a
3289    /// freezable index are skipped silently.
3290    pub fn spawn_background_freezer(
3291        db: Arc<Mutex<Database>>,
3292        opts: FreezerOptions,
3293    ) -> FreezerHandle {
3294        let shutdown = Arc::new(AtomicBool::new(false));
3295        let shutdown_for_thread = Arc::clone(&shutdown);
3296        let join = thread::Builder::new()
3297            .name("spg-embedded-freezer".into())
3298            .spawn(move || {
3299                background_freezer_loop(db, opts, shutdown_for_thread);
3300            })
3301            .expect("spawn background freezer thread");
3302        FreezerHandle {
3303            shutdown,
3304            join: Some(join),
3305        }
3306    }
3307}
3308
3309/// v7.2.1 — the freezer's main loop, factored out so the
3310/// `Database::spawn_background_freezer` path stays readable.
3311fn background_freezer_loop(
3312    db: Arc<Mutex<Database>>,
3313    opts: FreezerOptions,
3314    shutdown: Arc<AtomicBool>,
3315) {
3316    // Sleep in short slices so a shutdown request resolves
3317    // quickly (vs sleeping the full tick).
3318    let slice = Duration::from_millis(50.min(opts.tick.as_millis() as u64));
3319    let mut last_tick = std::time::Instant::now();
3320    loop {
3321        if shutdown.load(Ordering::Acquire) {
3322            return;
3323        }
3324        thread::sleep(slice);
3325        if last_tick.elapsed() < opts.tick {
3326            continue;
3327        }
3328        last_tick = std::time::Instant::now();
3329        let Ok(mut guard) = db.lock() else {
3330            return;
3331        };
3332        if guard.engine.catalog().hot_tier_bytes() <= opts.hot_tier_bytes {
3333            continue;
3334        }
3335        let Some((table, index)) = pick_freeze_target(&guard) else {
3336            continue;
3337        };
3338        let row_count = guard
3339            .engine
3340            .catalog()
3341            .get(&table)
3342            .map_or(0, spg_storage::Table::row_count);
3343        let to_freeze = opts.batch_rows.min(row_count);
3344        if to_freeze == 0 {
3345            continue;
3346        }
3347        if let Err(e) = guard.freeze_oldest_to_cold(&table, &index, to_freeze) {
3348            eprintln!("spg-embedded: background freeze on {table}.{index} failed: {e:?}");
3349            continue;
3350        }
3351        // v7.7.4 — auto-compact. If the catalog now carries
3352        // more cold segments than the configured threshold,
3353        // run a single compaction pass. Failures are reported
3354        // but don't kill the loop; the next tick will retry.
3355        let count = guard.engine.catalog().cold_segment_count();
3356        if count > opts.compact_when_segments_exceed {
3357            if let Err(e) = guard
3358                .engine
3359                .compact_cold_segments_with_target(opts.compact_target_bytes)
3360            {
3361                eprintln!(
3362                    "spg-embedded: background compact failed (segments={count}, \
3363                     threshold={}): {e:?}",
3364                    opts.compact_when_segments_exceed,
3365                );
3366            }
3367        }
3368    }
3369}
3370
3371/// v7.2.1 — pick the highest-`hot_bytes` user table with a
3372/// BTree integer-PK index. Returns `(table, index_name)` so the
3373/// caller can dispatch through `freeze_oldest_to_cold`.
3374fn pick_freeze_target(db: &Database) -> Option<(String, String)> {
3375    let cat = db.engine.catalog();
3376    let mut best: Option<(String, String, u64)> = None;
3377    for name in cat.table_names() {
3378        let Some(t) = cat.get(&name) else { continue };
3379        if t.row_count() == 0 {
3380            continue;
3381        }
3382        let cols = &t.schema().columns;
3383        let Some(idx) = t.indices().iter().find(|i| {
3384            matches!(i.kind, spg_storage::IndexKind::BTree(_))
3385                && i.column_position < cols.len()
3386                && matches!(
3387                    cols[i.column_position].ty,
3388                    spg_storage::DataType::SmallInt
3389                        | spg_storage::DataType::Int
3390                        | spg_storage::DataType::BigInt
3391                )
3392        }) else {
3393            continue;
3394        };
3395        let hot = t.hot_bytes();
3396        match best {
3397            None => best = Some((name, idx.name.clone(), hot)),
3398            Some((_, _, best_hot)) if hot > best_hot => {
3399                best = Some((name, idx.name.clone(), hot));
3400            }
3401            _ => {}
3402        }
3403    }
3404    best.map(|(t, i, _)| (t, i))
3405}
3406
3407/// v7.7.6 — replay the first `to_seq` records of the WAL at
3408/// `wal_path` into a fresh engine and write the resulting
3409/// catalog snapshot to `out_db_path`. Same semantics as
3410/// `spg revert --wal … --to-seq N --out …` from the CLI:
3411///
3412///   - `to_seq == 0` → snapshot is the empty catalog
3413///   - WAL records beyond `to_seq` are not applied
3414///   - durability-checkpoint markers (v3 type 0x02) are
3415///     consumed without counting against the budget
3416///
3417/// Returns the number of statements actually applied
3418/// (`≤ to_seq`). The output snapshot is byte-identical to
3419/// what `Database::open_path(out_db_path)` would consume on
3420/// a subsequent open.
3421///
3422/// This is the "rewind" operator for an embedded database
3423/// that has been corrupted by a poison statement or a
3424/// half-applied migration. Pair with `cold_segment_paths`
3425/// preservation if your cold-tier files are still on disk.
3426///
3427/// # Errors
3428///
3429/// - `wal_path` unreadable or truncated mid-record
3430/// - WAL record decodes to invalid UTF-8 SQL
3431/// - WAL record's SQL is rejected by the engine
3432/// - `out_db_path` unwritable
3433pub fn revert_wal_to_seq(
3434    wal_path: impl AsRef<Path>,
3435    to_seq: u64,
3436    out_db_path: impl AsRef<Path>,
3437) -> Result<u64, EngineError> {
3438    // v7.19 — accept either a single-file legacy WAL (v7.18 and
3439    // earlier layout) or a chunked WAL directory (v7.19+). For a
3440    // directory, concatenate every `.wal` chunk in sorted order
3441    // — the same order open_path replays them in — so revert
3442    // sees the full record stream.
3443    let path = wal_path.as_ref();
3444    let wal_bytes = if path.is_dir() {
3445        let mut combined = Vec::new();
3446        let chunks = sorted_wal_chunks(path).map_err(io_err)?;
3447        for chunk in chunks {
3448            let bytes = std::fs::read(&chunk).map_err(io_err)?;
3449            combined.extend_from_slice(&bytes);
3450        }
3451        combined
3452    } else {
3453        std::fs::read(path).map_err(io_err)?
3454    };
3455    let mut engine = Engine::new();
3456    let mut applied = 0u64;
3457    let mut cur = 0usize;
3458    while cur < wal_bytes.len() && applied < to_seq {
3459        let (sql_bytes, total) = decode_wal_record(&wal_bytes[cur..])?;
3460        cur += total;
3461        if sql_bytes.is_empty() {
3462            continue;
3463        }
3464        let sql = core::str::from_utf8(&sql_bytes).map_err(|e| {
3465            EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
3466                "WAL record at offset {cur}: non-UTF-8 SQL: {e}"
3467            )))
3468        })?;
3469        // v7.21 — tx-commit records carry a multi-statement script;
3470        // split_statements is a no-op for single-statement records.
3471        for stmt in split_statements(sql) {
3472            engine.execute(stmt)?;
3473        }
3474        applied += 1;
3475    }
3476    let snapshot = engine.snapshot();
3477    std::fs::write(out_db_path.as_ref(), &snapshot).map_err(io_err)?;
3478    Ok(applied)
3479}
3480
3481/// v7.7.6 — decode one WAL record from a byte tail. Returns
3482/// `(sql_bytes, header_plus_payload_len)`. Handles the three
3483/// on-disk formats (v1 / v2 / v3) the same way the CLI
3484/// `decode_one_record` and the engine's `replay_wal_bytes`
3485/// do. CRCs are not re-validated; the caller's intent is
3486/// "apply", not "validate".
3487fn decode_wal_record(tail: &[u8]) -> Result<(Vec<u8>, usize), EngineError> {
3488    if tail.len() < 4 {
3489        return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
3490            format!("WAL truncated record: {} < 4 header bytes", tail.len()),
3491        )));
3492    }
3493    let raw_len = u32::from_le_bytes(tail[..4].try_into().unwrap());
3494    let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
3495    let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
3496    let len_mask = if is_v3 {
3497        !(WAL_V2_SENTINEL | WAL_V3_FLAG)
3498    } else {
3499        !WAL_V2_SENTINEL
3500    };
3501    let rec_len = (raw_len & len_mask) as usize;
3502    let header_len = if is_v3 {
3503        9
3504    } else if is_v2 {
3505        8
3506    } else {
3507        4
3508    };
3509    if tail.len() < header_len + rec_len {
3510        return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
3511            format!(
3512                "WAL truncated record: header+payload {} > available {}",
3513                header_len + rec_len,
3514                tail.len()
3515            ),
3516        )));
3517    }
3518    if is_v3 {
3519        let type_byte = tail[8];
3520        // v3 type 0x01 = auto_commit_sql (payload = SQL).
3521        // v3 type 0x02 = durability marker (no SQL to apply).
3522        // v4 type 0x10 = auto_commit_sql with 16-byte (lsn, ts)
3523        //                prefix between type and SQL — strip
3524        //                the prefix so the caller still sees raw
3525        //                SQL bytes.
3526        // Anything else is unknown.
3527        if type_byte == WAL_V3_TYPE_AUTO_COMMIT_SQL {
3528            let payload = &tail[header_len..header_len + rec_len];
3529            return Ok((payload.to_vec(), header_len + rec_len));
3530        }
3531        if type_byte == WAL_V4_TYPE_AUTO_COMMIT_SQL || type_byte == WAL_V4_TYPE_TX_COMMIT_SQL {
3532            let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
3533            if tail.len() < v4_total {
3534                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
3535                    format!(
3536                        "WAL truncated v4 record: header+payload {v4_total} > available {}",
3537                        tail.len()
3538                    ),
3539                )));
3540            }
3541            let sql_start = header_len + WAL_V4_EXTRA_HEADER;
3542            let sql_bytes = tail[sql_start..sql_start + rec_len].to_vec();
3543            return Ok((sql_bytes, v4_total));
3544        }
3545        // Caller treats empty payload as a skip-marker.
3546        return Ok((Vec::new(), header_len + rec_len));
3547    }
3548    let payload = &tail[header_len..header_len + rec_len];
3549    Ok((payload.to_vec(), header_len + rec_len))
3550}
3551
3552impl Drop for Database {
3553    fn drop(&mut self) {
3554        // v7.1 — best-effort final checkpoint when a persistent
3555        // Database leaves scope. Failures here go to stderr so
3556        // operators see them, but Drop can't propagate errors —
3557        // the WAL itself is already durable, so a checkpoint
3558        // miss only means the next boot replays a few more
3559        // records than strictly necessary.
3560        if self.persistence.is_some() {
3561            if let Err(e) = self.checkpoint() {
3562                eprintln!(
3563                    "spg-embedded: final checkpoint on Drop failed: {e:?} \
3564                     (WAL is intact; next open_path will replay)"
3565                );
3566            }
3567        }
3568        // v7.19 P3 / v7.20 — signal the retention + flusher
3569        // threads to exit, then wait for them. Done BEFORE the
3570        // lock release so background threads don't outlive the
3571        // database handle. The flusher drains the pending batch
3572        // on its way out (final flush_now in the thread body),
3573        // so `SPG_SYNCHRONOUS_COMMIT=off` never loses confirmed
3574        // commits across a clean shutdown.
3575        if let Some(ctx) = self.persistence.as_mut() {
3576            if let Some(shutdown) = ctx.retention_shutdown.take() {
3577                shutdown.store(true, Ordering::SeqCst);
3578            }
3579            if let Some(handle) = ctx.retention_thread.take() {
3580                let _ = handle.join();
3581            }
3582            if let Some(shutdown) = ctx.flusher_shutdown.take() {
3583                shutdown.store(true, Ordering::SeqCst);
3584            }
3585            if let Some(handle) = ctx.flusher_thread.take() {
3586                let _ = handle.join();
3587            }
3588            // CoW-2 (v7.34) — final checkpoint above left the worker
3589            // idle; explicitly drop it here so its shutdown signal +
3590            // thread join happens with a deterministic ordering (before
3591            // the lock release / persistence drop), not whenever Rust
3592            // happens to drop the PersistenceCtx fields.
3593            ctx.checkpoint_worker = None;
3594        }
3595        // v7.17.0 Phase 6.2 — release the cross-process lock on
3596        // clean shutdown. Failure is logged but never panics;
3597        // the operator can clear a stale lock via
3598        // `Database::force_unlock` if a crash kept the
3599        // directory around.
3600        if let Some(ctx) = &self.persistence
3601            && ctx.lock_path.exists()
3602        {
3603            // remove_dir_all: the lock dir carries the owner-pid
3604            // record since round-12.
3605            if let Err(e) = std::fs::remove_dir_all(&ctx.lock_path) {
3606                eprintln!(
3607                    "spg-embedded: lock release on Drop failed for {}: {e:?}",
3608                    ctx.lock_path.display()
3609                );
3610            }
3611        }
3612    }
3613}
3614
3615impl Database {
3616    /// v7.17.0 Phase 6.2 — clear a stale cross-process lock.
3617    /// Use when a previous process crashed mid-session and
3618    /// left `<db_path>.lock` behind. Operators should confirm
3619    /// no other process is currently using the database before
3620    /// calling this — SPG cannot fingerprint stale-vs-live
3621    /// without a libc dep, which would violate spg-embedded's
3622    /// zero-deps charter.
3623    pub fn force_unlock(db_path: impl AsRef<Path>) -> Result<(), EngineError> {
3624        let lock_path = {
3625            let mut p = db_path.as_ref().to_path_buf();
3626            let name = p
3627                .file_name()
3628                .map(|n| {
3629                    let mut s = n.to_os_string();
3630                    s.push(".lock");
3631                    s
3632                })
3633                .unwrap_or_else(|| std::ffi::OsString::from(".lock"));
3634            p.set_file_name(name);
3635            p
3636        };
3637        // v7.37.5 (mailrs crash-recovery Ask 2) — also clear the
3638        // in-process registry entry for this lock_path. The operator
3639        // calling `force_unlock` asserts "no one is using this catalog;
3640        // nuke the lock"; the in-process registry would otherwise
3641        // keep an in-flight sibling `Database::open_path` task
3642        // registered, and a same-process retry post-force_unlock
3643        // would refuse honestly with the Ask 1 in-flight error
3644        // even though the operator just declared the catalog free.
3645        // Drop the registry entry before the disk lock so retries
3646        // see a consistent "free" state. The orphaned in-flight
3647        // task, if any, will surface its own error when it tries
3648        // to release the now-vanished lock dir; that's the
3649        // single-instance contract `force_unlock` documents.
3650        {
3651            let mut set = active_open_paths()
3652                .lock()
3653                .unwrap_or_else(|e| e.into_inner());
3654            set.remove(&lock_path);
3655        }
3656        if !lock_path.exists() {
3657            return Ok(());
3658        }
3659        std::fs::remove_dir_all(&lock_path).map_err(io_err)
3660    }
3661}
3662
3663/// v7.1 — turn a `std::io::Error` into the workspace's
3664/// `EngineError` shape. `EngineError::Storage(Corrupt(_))` is
3665/// the closest existing variant — io failures during boot or
3666/// during a WAL append surface as a storage-layer fault to
3667/// callers, which keeps the public error enum unchanged.
3668fn io_err(e: std::io::Error) -> EngineError {
3669    EngineError::Storage(spg_storage::StorageError::Corrupt(format!("io: {e}")))
3670}
3671
3672/// v7.2.2 — `Database` is `Send`, so the recommended sharing
3673/// pattern for multi-threaded callers is `Arc<Mutex<Database>>`:
3674///
3675/// ```no_run
3676/// use std::sync::{Arc, Mutex};
3677/// use spg_embedded::Database;
3678///
3679/// let db = Database::open_in_memory();
3680/// let shared = Arc::new(Mutex::new(db));
3681/// let shared_for_worker = Arc::clone(&shared);
3682/// std::thread::spawn(move || {
3683///     let mut guard = shared_for_worker.lock().unwrap();
3684///     guard.execute("INSERT INTO t VALUES (1)").unwrap();
3685/// });
3686/// ```
3687///
3688/// Internal `RwLock`-wrapped state — letting many threads
3689/// hold concurrent `&Database` for `SELECT` without contending
3690/// — is parked as STABILITY § "Out of v7.2"; multi-reader
3691/// embedded throughput needs a planner-side change to release
3692/// the engine read lock between scans, which is the v7.x
3693/// "Choice A" line of work already documented in v6.9.1's
3694/// carve-out.
3695#[allow(dead_code)]
3696fn _database_is_send() {
3697    fn assert_send<T: Send>() {}
3698    assert_send::<Database>();
3699}
3700
3701/// v6.10.3 — trait that maps a row's columns onto a user
3702/// struct's fields. v7.3.0 ships the [`spg_row!`] declarative
3703/// macro that generates `impl FromSpgRow for YourStruct` from
3704/// a struct definition (no proc-macro, no syn/quote/
3705/// proc-macro2 deps — the workspace's "0 external deps"
3706/// policy holds).
3707///
3708/// Implementors map a row's columns onto a user struct's
3709/// fields. Errors surface as `EngineError::Unsupported` so the
3710/// caller's error type stays uniform.
3711pub trait FromSpgRow: Sized {
3712    /// Decode one query result row into `Self`. Called once per
3713    /// row by [`Database::query_typed`]. The slice length equals
3714    /// the number of columns in the SELECT projection.
3715    fn from_spg_row(row: &[Value]) -> Result<Self, EngineError>;
3716}
3717
3718/// v7.3.0 — declarative macro that generates `FromSpgRow` impl
3719/// for a user struct. Avoids proc-macro deps
3720/// (syn/quote/proc-macro2) so the workspace's 0-deps policy
3721/// holds; the trade-off vs `#[derive(SpgRow)]` is that the
3722/// macro takes the entire struct definition (fields + types)
3723/// as input rather than annotating an existing struct.
3724///
3725/// ```no_run
3726/// use spg_embedded::{Database, spg_row, FromSpgRow};
3727///
3728/// spg_row! {
3729///     pub struct User {
3730///         pub id: i32,
3731///         pub name: String,
3732///     }
3733/// }
3734///
3735/// let mut db = Database::open_in_memory();
3736/// db.execute("CREATE TABLE users (id INT NOT NULL, name TEXT)").unwrap();
3737/// db.execute("INSERT INTO users VALUES (1, 'alice')").unwrap();
3738/// let users: Vec<User> = db.query_typed("SELECT id, name FROM users").unwrap();
3739/// ```
3740///
3741/// Supported field types: `i16`, `i32`, `i64`, `f32`, `f64`,
3742/// `bool`, `String`, `Vec<f32>` (for `VECTOR(N)` columns),
3743/// `Option<T>` of any of the above.
3744#[macro_export]
3745macro_rules! spg_row {
3746    (
3747        $(#[$meta:meta])*
3748        $vis:vis struct $name:ident {
3749            $(
3750                $(#[$fmeta:meta])*
3751                $fvis:vis $field:ident : $ty:ty,
3752            )*
3753        }
3754    ) => {
3755        $(#[$meta])*
3756        #[derive(Debug, Clone)]
3757        $vis struct $name {
3758            $(
3759                $(#[$fmeta])*
3760                $fvis $field : $ty,
3761            )*
3762        }
3763
3764        impl $crate::FromSpgRow for $name {
3765            fn from_spg_row(row: &[$crate::Value]) -> ::core::result::Result<Self, $crate::EngineError> {
3766                let mut __spg_row_iter = row.iter();
3767                $(
3768                    let $field: $ty = {
3769                        let v = __spg_row_iter
3770                            .next()
3771                            .ok_or_else(|| $crate::EngineError::Unsupported(
3772                                ::std::format!(
3773                                    "spg_row! {}: missing column for field `{}`",
3774                                    ::core::stringify!($name),
3775                                    ::core::stringify!($field)
3776                                )
3777                            ))?;
3778                        <$ty as $crate::FromSpgValue>::from_spg_value(v)
3779                            .map_err(|e| $crate::EngineError::Unsupported(
3780                                ::std::format!(
3781                                    "spg_row! {}: column `{}`: {}",
3782                                    ::core::stringify!($name),
3783                                    ::core::stringify!($field),
3784                                    e
3785                                )
3786                            ))?
3787                    };
3788                )*
3789                Ok(Self { $($field,)* })
3790            }
3791        }
3792    };
3793}
3794
3795/// v7.3.0 — per-column decoder used by `spg_row!`. Surface
3796/// covers every numeric / text / bytes / bool variant in
3797/// `Value`, plus `Option<T>` for nullable columns.
3798pub trait FromSpgValue: Sized {
3799    /// Decode one cell into `Self`. The returned `&'static str`
3800    /// is a short diagnostic for type mismatches (e.g. `"expected
3801    /// integer, got TEXT"`); callers wrap it into their own
3802    /// error type.
3803    fn from_spg_value(v: &Value) -> Result<Self, &'static str>;
3804}
3805
3806macro_rules! impl_from_value_int {
3807    ($($t:ty),* $(,)?) => {
3808        $(
3809            impl FromSpgValue for $t {
3810                fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3811                    match v {
3812                        Value::SmallInt(n) => <$t>::try_from(*n).map_err(|_| "SmallInt does not fit target int type"),
3813                        Value::Int(n)      => <$t>::try_from(*n).map_err(|_| "Int does not fit target int type"),
3814                        Value::BigInt(n)   => <$t>::try_from(*n).map_err(|_| "BigInt does not fit target int type"),
3815                        Value::Null        => Err("NULL in non-Option int column"),
3816                        _ => Err("non-integer value in int column"),
3817                    }
3818                }
3819            }
3820        )*
3821    };
3822}
3823impl_from_value_int!(i16, i32, i64);
3824
3825impl FromSpgValue for f32 {
3826    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3827        match v {
3828            Value::Float(f) => Ok(*f as f32),
3829            Value::Null => Err("NULL in non-Option float column"),
3830            _ => Err("non-float value in float column"),
3831        }
3832    }
3833}
3834
3835impl FromSpgValue for f64 {
3836    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3837        match v {
3838            Value::Float(f) => Ok(*f),
3839            Value::Null => Err("NULL in non-Option float column"),
3840            _ => Err("non-float value in float column"),
3841        }
3842    }
3843}
3844
3845impl FromSpgValue for bool {
3846    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3847        match v {
3848            Value::Bool(b) => Ok(*b),
3849            Value::Null => Err("NULL in non-Option bool column"),
3850            _ => Err("non-bool value in bool column"),
3851        }
3852    }
3853}
3854
3855impl FromSpgValue for String {
3856    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3857        match v {
3858            Value::Text(s) => Ok(s.to_string()),
3859            Value::Null => Err("NULL in non-Option text column"),
3860            _ => Err("non-text value in String column"),
3861        }
3862    }
3863}
3864
3865impl FromSpgValue for Vec<f32> {
3866    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3867        match v {
3868            Value::Vector(xs) => Ok(xs.to_vec()),
3869            Value::Null => Err("NULL in non-Option vector column"),
3870            _ => Err("non-vector value in Vec<f32> column"),
3871        }
3872    }
3873}
3874
3875impl<T: FromSpgValue> FromSpgValue for Option<T> {
3876    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3877        match v {
3878            Value::Null => Ok(None),
3879            other => T::from_spg_value(other).map(Some),
3880        }
3881    }
3882}
3883
3884/// Acquire the cross-process exclusion lock at `lock_path` (atomic
3885/// `mkdir`), recording the owner pid inside. If the lock already
3886/// exists, read the recorded pid and probe liveness — a lock left
3887/// behind by a killed process (docker SIGKILL, crash) is reclaimed
3888/// automatically instead of forcing the operator to delete it by
3889/// hand (mailrs embed round-12: a restarted server came up in
3890/// degraded mode because the previous instance's lock survived).
3891/// v7.27 (mailrs round-21 B) — the prober's environment identity:
3892/// `(hostname, boot-or-container id)`. A pid is only meaningful
3893/// inside the PID namespace that recorded it; mailrs's recovery
3894/// window saw "locked by pid 1" from a STOPPED container because
3895/// the prober's pid 1 (its own init) was alive. When the lock's
3896/// identity differs from ours, liveness is UNDECIDABLE and we
3897/// refuse honestly instead of guessing in either direction.
3898fn host_identity() -> (String, String) {
3899    let hostname = std::process::Command::new("hostname")
3900        .output()
3901        .ok()
3902        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
3903        .unwrap_or_default();
3904    // Linux boot id; containers share the host kernel's boot id, so
3905    // hostname (= container id by default) is the namespace
3906    // discriminator and boot id catches host reboots / pid reuse.
3907    let boot_id = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
3908        .map(|s| s.trim().to_string())
3909        .or_else(|_| {
3910            std::process::Command::new("sysctl")
3911                .args(["-n", "kern.bootsessionuuid"])
3912                .output()
3913                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
3914        })
3915        .unwrap_or_default();
3916    (hostname, boot_id)
3917}
3918
3919/// v7.34 (crash-recovery P0 #2) — process start-time, to tell a reused
3920/// pid apart from a genuinely-held lock. In a container the holder is
3921/// always pid 1; `docker start` reuses the container so the NEW process
3922/// is pid 1 too, on the same host+boot id — a bare `pid_alive(1)` probe
3923/// (`ps -p 1` always succeeds) reads a dead owner's lock as live and the
3924/// engine self-deadlocks on its own catalog. The `(pid, start-time)`
3925/// pair is unique per live process within a boot: a reused pid carries a
3926/// LATER start-time, so a mismatch means the recorded owner is gone.
3927/// Linux reads `/proc/<pid>/stat` field 22 (clock ticks since boot);
3928/// `comm` (field 2) is parenthesised and may contain spaces, so fields
3929/// are taken after the LAST ')'. Other platforms return None and the
3930/// liveness check falls back to pid-alive + the self-pid reclaim. Pure
3931/// std — no libc.
3932#[cfg(target_os = "linux")]
3933fn process_start_time(pid: u32) -> Option<String> {
3934    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
3935    let after = stat.rsplit_once(')').map(|(_, rest)| rest)?;
3936    // After comm: state(1) ppid(2) … starttime is the 20th token.
3937    after.split_whitespace().nth(19).map(str::to_string)
3938}
3939
3940#[cfg(not(target_os = "linux"))]
3941fn process_start_time(_pid: u32) -> Option<String> {
3942    None
3943}
3944
3945/// v7.37.5 (mailrs crash-recovery Ask 1) — in-process registry of
3946/// lock paths currently being opened or held by a live `Database`
3947/// instance in THIS process. Closes the v7.37.10 design gap that
3948/// kept the mailrs lock-hang alive across recurrences:
3949///
3950/// `AsyncDatabase::open_path` runs `Database::open_path` inside
3951/// `tokio::task::spawn_blocking`, which CANNOT be cancelled
3952/// mid-flight. When the awaiting future is dropped (pool
3953/// acquire-timeout, ctrl-c on a slow boot, etc.), the blocking
3954/// task keeps running and STILL HOLDS the lock. A concurrent
3955/// retry then reads the on-disk lock, sees `(pid, start-time)`
3956/// matching its OWN process, and the pid-1 + start-time logic
3957/// declares the lock "owner_alive=true" — refusing to reclaim a
3958/// lock that is, in fact, held by a sibling task in the same
3959/// process. Result: every retry hangs until the in-flight open
3960/// completes (≥ 27 min on the 1.5 MB mailrs WAL before Ask 3).
3961///
3962/// The on-disk identity (pid + start-time + hostname + boot id)
3963/// is sufficient ACROSS processes but ambiguous WITHIN one
3964/// process; this set settles it directly. `acquire_path_lock`
3965/// consults the set first: if the path is present, the on-disk
3966/// lock is held by a live sibling task and we refuse honestly
3967/// without reading the pid file. If absent, a same-pid on-disk
3968/// lock is necessarily a previous-generation orphan (the prior
3969/// holder dropped its `LockRegistryGuard` on Drop, so the set
3970/// no longer contains the path) and the existing pid-1 / stale
3971/// reclaim path handles it.
3972fn active_open_paths() -> &'static std::sync::Mutex<std::collections::HashSet<PathBuf>> {
3973    use std::sync::OnceLock;
3974    static ACTIVE: OnceLock<std::sync::Mutex<std::collections::HashSet<PathBuf>>> = OnceLock::new();
3975    ACTIVE.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
3976}
3977
3978/// RAII guard that registers a `lock_path` in `ACTIVE_OPEN_PATHS`
3979/// on construction and de-registers on Drop. Construction fails
3980/// with `EngineError::Unsupported` when the path is already
3981/// present — that's the v7.37.5 honest refusal for a sibling
3982/// in-flight `Database::open_path` on the same path. Carried by
3983/// `Database` for the live duration of the handle so concurrent
3984/// open attempts (sqlx pool retries, mailrs `force_unlock` +
3985/// re-open dance) see the registration even while the prior
3986/// open's `spawn_blocking` task is still in WAL replay.
3987#[derive(Debug)]
3988pub(crate) struct LockRegistryGuard {
3989    path: PathBuf,
3990}
3991
3992impl LockRegistryGuard {
3993    fn try_acquire(lock_path: &Path) -> Result<Self, EngineError> {
3994        let mut set = active_open_paths()
3995            .lock()
3996            .unwrap_or_else(|e| e.into_inner());
3997        if set.contains(lock_path) {
3998            return Err(EngineError::Unsupported(format!(
3999                "database is locked by an in-flight task in this process: {} \
4000                 (a sibling `Database::open_path` / `AsyncDatabase::open_path` is \
4001                 still holding the lock; wait for it to complete, or shut down the \
4002                 prior caller before retrying)",
4003                lock_path.display()
4004            )));
4005        }
4006        set.insert(lock_path.to_path_buf());
4007        Ok(Self {
4008            path: lock_path.to_path_buf(),
4009        })
4010    }
4011}
4012
4013impl Drop for LockRegistryGuard {
4014    fn drop(&mut self) {
4015        let mut set = active_open_paths()
4016            .lock()
4017            .unwrap_or_else(|e| e.into_inner());
4018        set.remove(&self.path);
4019    }
4020}
4021
4022/// v7.37.5 — diagnostic predicate used by tests + future cross-
4023/// boundary force_unlock plumbing (Ask 2) to decide whether a
4024/// same-process retry should refuse honestly vs. reclaim.
4025#[doc(hidden)]
4026pub fn is_lock_path_active_in_process(lock_path: &Path) -> bool {
4027    active_open_paths()
4028        .lock()
4029        .map(|s| s.contains(lock_path))
4030        .unwrap_or(false)
4031}
4032
4033fn acquire_path_lock(lock_path: &Path) -> Result<(), EngineError> {
4034    // v7.37.5 (Ask 1) — the in-process registry check happens in
4035    // `LockRegistryGuard::try_acquire`, called by `open_path`
4036    // BEFORE this function. By the time we get here, the caller
4037    // already owns the registry slot; the on-disk acquire below
4038    // can race with same-pid siblings only when force_unlock
4039    // cleared the registry mid-flight (the operator's
4040    // single-instance contract), which is correct behaviour.
4041    for attempt in 0..2 {
4042        match std::fs::create_dir(lock_path) {
4043            Ok(()) => {
4044                // Best-effort owner record; liveness probing treats a
4045                // missing pid file as stale (crash between mkdir and
4046                // write is indistinguishable from an ancient lock).
4047                // v7.27 — lines 2+3 record the owner's environment
4048                // identity (hostname, boot id) so a prober in a
4049                // different namespace refuses instead of misreading
4050                // the pid. v7.34 — line 4 records the owner's process
4051                // start-time so a reused pid (container pid-1 restart)
4052                // is distinguishable from a live holder.
4053                let (host, boot) = host_identity();
4054                let start = process_start_time(std::process::id()).unwrap_or_default();
4055                let _ = std::fs::write(
4056                    lock_path.join("pid"),
4057                    format!("{}\n{host}\n{boot}\n{start}\n", std::process::id()),
4058                );
4059                return Ok(());
4060            }
4061            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt == 0 => {
4062                let record = std::fs::read_to_string(lock_path.join("pid")).unwrap_or_default();
4063                let mut lines = record.lines();
4064                let owner = lines.next().and_then(|s| s.trim().parse::<u32>().ok());
4065                let lock_host = lines.next().unwrap_or("").trim().to_string();
4066                let lock_boot = lines.next().unwrap_or("").trim().to_string();
4067                let lock_start = lines.next().unwrap_or("").trim().to_string();
4068                // Note(v7.37.10 design choice): we do NOT auto-reclaim a
4069                // lock whose (pid, start-time) matches OUR own process.
4070                // Tempting fix for the mailrs 2026-06-19 recurrence —
4071                // "the prior open_path future got cancelled, its lock
4072                // leaked" — but `AsyncDatabase::open_path` runs the
4073                // blocking `Database::open_path` inside
4074                // `tokio::task::spawn_blocking`, which CANNOT be
4075                // cancelled mid-flight. When the awaiting future is
4076                // dropped (pool acquire-timeout), the spawn_blocking
4077                // task keeps running and STILL HOLDS the lock; auto-
4078                // reclaiming would let a concurrent retry steal a live
4079                // task's lock and corrupt WAL replay. The mailrs flow
4080                // is correctly resolved by waiting for the in-flight
4081                // replay to finish — sentori's spg-sqlx pool config
4082                // needs a higher `acquire_timeout` than spg's worst-
4083                // case replay time. Tracking that separately as a
4084                // spg-sqlx pool-default change for v7.38.
4085                // v7.27 — identity check BEFORE the pid probe. A pid
4086                // recorded in another namespace is undecidable both
4087                // ways (a stale lock can look held, a held lock can
4088                // look stale — the unsafe direction). Old-format
4089                // locks (pid only) keep the legacy same-host
4090                // assumption.
4091                // v7.37.10 — skip host_identity when the recorded owner
4092                // is PID 1. PID 1 means containerised; `docker compose
4093                // up -d` recreates the container with a new hostname so
4094                // a strict host-identity match would refuse every
4095                // restart even when the start-time check below would
4096                // correctly declare the old generation stale. The
4097                // start-time check is more accurate for the container
4098                // case anyway — let it decide.
4099                let lock_is_pid1 = owner == Some(1);
4100                if !lock_host.is_empty() && !lock_is_pid1 {
4101                    let (my_host, my_boot) = host_identity();
4102                    let same_env = lock_host == my_host
4103                        && (lock_boot.is_empty() || my_boot.is_empty() || lock_boot == my_boot);
4104                    if !same_env {
4105                        return Err(EngineError::Unsupported(format!(
4106                            "database lock {} was taken in a different host/container \
4107                             (owner: pid {} on {:?}; we are {:?}) — liveness is \
4108                             undecidable from here. If you are sure the owner is gone, \
4109                             call Database::force_unlock() or `spg import --force-unlock`.",
4110                            lock_path.display(),
4111                            owner.unwrap_or(0),
4112                            lock_host,
4113                            my_host
4114                        )));
4115                    }
4116                }
4117                // v7.34 (crash-recovery P0 #2) — pid-reuse-safe liveness.
4118                // A bare `pid_alive` self-deadlocks in a container: the
4119                // dead owner was pid 1, `docker start` reuses the container
4120                // so the prober is pid 1 too, and `ps -p 1` always succeeds.
4121                // The recorded (pid, start-time) pair settles it — the
4122                // owner is alive ONLY if its pid is alive AND its CURRENT
4123                // start-time still matches the recorded one:
4124                //  - container restart: pid 1 alive, but the new pid-1's
4125                //    start-time differs from the dead owner's → stale.
4126                //  - genuine double-open (same live process): start-time
4127                //    matches (it wrote it) → held — correctly refused, so a
4128                //    second writer can't steal a live lock.
4129                // v7.37.10 — for PID-1 owners with no recorded start-time
4130                // (a pre-v7.34 lock from a previous container generation),
4131                // treat as stale: a new container's PID 1 cannot share
4132                // identity with the previous container's PID 1. Gated on
4133                // `process_start_time` having returned `Some(_)` so the
4134                // arm only fires on Linux (where /proc is queryable); on
4135                // macOS, where PID 1 is `launchd` (a real long-running
4136                // system process), the empty-start-time fallback keeps
4137                // the safer pid-alive answer.
4138                let owner_alive = owner.is_some_and(|p| {
4139                    if !pid_alive(p) {
4140                        return false;
4141                    }
4142                    let now = process_start_time(p);
4143                    match (now, lock_start.is_empty()) {
4144                        (Some(t), false) => t == lock_start,
4145                        (Some(_), true) if p == 1 => false,
4146                        _ => true,
4147                    }
4148                });
4149                if owner_alive {
4150                    return Err(EngineError::Unsupported(format!(
4151                        "database is locked by another process (pid {}): {}; \
4152                         stop that process first, or call Database::force_unlock()",
4153                        owner.unwrap_or(0),
4154                        lock_path.display()
4155                    )));
4156                }
4157                // Stale — owner pid dead, reused, or unrecorded. Reclaim.
4158                eprintln!(
4159                    "spg-embedded: reclaiming stale lock {} (owner pid {:?} not a live holder)",
4160                    lock_path.display(),
4161                    owner
4162                );
4163                std::fs::remove_dir_all(lock_path).map_err(io_err)?;
4164                // Loop retries the create_dir; a concurrent reclaimer
4165                // winning the race surfaces as AlreadyExists on
4166                // attempt 1 below.
4167            }
4168            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4169                return Err(EngineError::Unsupported(format!(
4170                    "database is locked by another process: {}; \
4171                     stop that process first, or call Database::force_unlock()",
4172                    lock_path.display()
4173                )));
4174            }
4175            Err(e) => return Err(io_err(e)),
4176        }
4177    }
4178    unreachable!("acquire_path_lock loop covers both attempts")
4179}
4180
4181/// Probe whether `pid` is a live process. Unix: `ps -p` via the
4182/// system binary (std-only — no libc dependency). `ps -p` exits 0
4183/// for ANY live pid regardless of owner; `kill -0` was rejected
4184/// here because it fails with EPERM on another user's live process,
4185/// which would read as "dead" and reclaim a held lock. Probe
4186/// failure (no `ps` binary, exec error) conservatively reports
4187/// alive so locks are never auto-reclaimed on doubt; non-unix
4188/// targets do the same.
4189#[cfg(unix)]
4190fn pid_alive(pid: u32) -> bool {
4191    // v7.37.10 — `/proc/<pid>` directory existence is the
4192    // most reliable liveness signal on Linux, and crucially
4193    // doesn't depend on `procps` being installed in the
4194    // container image. Minimal images(rust:slim, distroless,
4195    // mailrs-mmalloc's stripped runtime)don't ship `ps`, and
4196    // a failed `Command::spawn` previously fell back to
4197    // "treat as alive" — which inverted the meaning of every
4198    // stale-lock probe in those environments. Probe /proc
4199    // first on Linux; fall back to `ps -p` on other unix
4200    // (macOS / BSD), where procps-equivalent tools ship by
4201    // default.
4202    #[cfg(target_os = "linux")]
4203    {
4204        if std::path::Path::new("/proc").is_dir() {
4205            return std::path::Path::new(&format!("/proc/{pid}")).exists();
4206        }
4207    }
4208    match std::process::Command::new("ps")
4209        .arg("-p")
4210        .arg(pid.to_string())
4211        .stdout(std::process::Stdio::null())
4212        .stderr(std::process::Stdio::null())
4213        .status()
4214    {
4215        Ok(status) => status.success(),
4216        Err(_) => true,
4217    }
4218}
4219
4220#[cfg(not(unix))]
4221fn pid_alive(_pid: u32) -> bool {
4222    true
4223}
4224
4225/// Strip leading whitespace, `--` line comments and NON-conditional
4226/// block comments from a chunk so statement-head checks (COPY
4227/// detection most notably) see the first real token. pg_dump
4228/// prefixes every data block with a `-- Data for Name: …;` banner —
4229/// which itself contains semicolons, so head checks must run on the
4230/// stripped text. MySQL executable conditional comments (`/*!`) are
4231/// content and stay.
4232/// v7.22 — see `split_statements`' `mysql_escapes` tracking. Only
4233/// short chunks are inspected (the signal statements are one-liners;
4234/// COPY data blocks are skipped by the length guard).
4235fn note_dialect_signals(chunk: &str, mysql_escapes: &mut bool) {
4236    if chunk.len() > 4096 {
4237        return;
4238    }
4239    let lower = chunk.to_ascii_lowercase();
4240    if lower.contains("sql_mode") {
4241        *mysql_escapes = true;
4242    } else if lower.contains("standard_conforming_strings") {
4243        *mysql_escapes = lower.contains("off");
4244    }
4245}
4246
4247fn strip_leading_sql_noise(mut s: &str) -> &str {
4248    loop {
4249        let t = s.trim_start();
4250        if let Some(rest) = t.strip_prefix("--") {
4251            s = rest.split_once('\n').map_or("", |(_, r)| r);
4252            continue;
4253        }
4254        if t.starts_with("/*") && !t.starts_with("/*!") {
4255            match t.find("*/") {
4256                Some(e) => {
4257                    s = &t[e + 2..];
4258                    continue;
4259                }
4260                None => return "",
4261            }
4262        }
4263        return t;
4264    }
4265}
4266
4267/// Split a multi-statement SQL script into individual statements on
4268/// top-level `;`, honouring single-quoted strings (with `''`
4269/// escapes), double-quoted identifiers, dollar-quoted bodies
4270/// (`$tag$ … $tag$`), line comments (`--`) and MySQL executable
4271/// conditional comments (`/*!… */` stay statement content; plain
4272/// nested block comments don't). Chunks that contain no statement
4273/// content (whitespace / comments only) are dropped. PG's
4274/// simple-query protocol does this server-side; the embed path owns
4275/// it here.
4276///
4277/// v7.22 (mailrs round-13 gap 1) — psql meta-command lines are
4278/// dropped for client parity: a line whose first non-whitespace
4279/// byte is `\` BETWEEN statements (PG 18's pg_dump wraps scripts in
4280/// `\restrict` / `\unrestrict`) never reaches the parser, the same
4281/// way psql consumes `\`-lines client-side and never sends them. A
4282/// mid-statement backslash stays an ordinary byte — pg_dump only
4283/// emits meta-commands between statements.
4284pub fn split_statements(sql: &str) -> Vec<&str> {
4285    let bytes = sql.as_bytes();
4286    let mut stmts = Vec::new();
4287    let mut start = 0usize;
4288    let mut has_content = false;
4289    // v7.22 (round-13 T3) — stream-tracked string dialect, mirroring
4290    // the engine's session flag: a statement mentioning `sql_mode`
4291    // (mysqldump preamble, often inside `/*!…*/`) switches plain
4292    // strings to backslash-escape scanning;
4293    // `standard_conforming_strings` (pg_dump preamble) switches
4294    // back. Without this the scanner ends a MySQL `'…\'…'` literal
4295    // early and splits inside data.
4296    let mut mysql_escapes = false;
4297    let mut i = 0usize;
4298    while i < bytes.len() {
4299        match bytes[i] {
4300            b'\\' if !has_content => {
4301                // Start-of-statement `\` = psql meta-command line.
4302                // Consume through end-of-line; restart the chunk
4303                // after it so the line never lands in the output.
4304                while i < bytes.len() && bytes[i] != b'\n' {
4305                    i += 1;
4306                }
4307                start = if i < bytes.len() { i + 1 } else { i };
4308            }
4309            b'\'' => {
4310                has_content = true;
4311                // PG escape-string form `E'...'` honours backslash
4312                // escapes (`E'a\';b'` is ONE literal) — detect via
4313                // the immediately-preceding standalone E/e. MySQL
4314                // dialect sessions treat EVERY plain string that way.
4315                let escape_string = mysql_escapes
4316                    || (i >= 1
4317                        && matches!(bytes[i - 1], b'e' | b'E')
4318                        && !(i >= 2
4319                            && (bytes[i - 2].is_ascii_alphanumeric() || bytes[i - 2] == b'_')));
4320                i += 1;
4321                while i < bytes.len() {
4322                    if escape_string && bytes[i] == b'\\' {
4323                        // Skip the escaped byte (covers \' and \\).
4324                        i += 2;
4325                        continue;
4326                    }
4327                    if bytes[i] == b'\'' {
4328                        // `''` is an escaped quote inside the literal.
4329                        if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
4330                            i += 2;
4331                            continue;
4332                        }
4333                        break;
4334                    }
4335                    i += 1;
4336                }
4337            }
4338            b'"' => {
4339                has_content = true;
4340                i += 1;
4341                while i < bytes.len() && bytes[i] != b'"' {
4342                    i += 1;
4343                }
4344            }
4345            b'$' => {
4346                // Possible dollar-quote opener `$tag$` (tag may be
4347                // empty). If the shape doesn't match, it's a plain
4348                // `$` (positional param) — fall through.
4349                let tag_end = bytes[i + 1..]
4350                    .iter()
4351                    .position(|&b| !(b.is_ascii_alphanumeric() || b == b'_'))
4352                    .map(|off| i + 1 + off);
4353                if let Some(te) = tag_end
4354                    && te < bytes.len()
4355                    && bytes[te] == b'$'
4356                {
4357                    has_content = true;
4358                    let tag = &sql[i..=te];
4359                    // Find the closing `$tag$`.
4360                    if let Some(close) = sql[te + 1..].find(tag) {
4361                        i = te + 1 + close + tag.len();
4362                        continue;
4363                    }
4364                    // Unterminated — consume the rest; the parser
4365                    // will report it.
4366                    i = bytes.len();
4367                    continue;
4368                }
4369                has_content = true;
4370            }
4371            b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => {
4372                while i < bytes.len() && bytes[i] != b'\n' {
4373                    i += 1;
4374                }
4375            }
4376            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
4377                // v7.22 (round-13 T3) — MySQL conditional comments
4378                // `/*!40101 … */` are EXECUTABLE (mysqldump wraps
4379                // its whole preamble + DISABLE KEYS hints in them);
4380                // they must stay statement content for the engine,
4381                // not be skipped as commentary.
4382                if i + 2 < bytes.len() && bytes[i + 2] == b'!' {
4383                    has_content = true;
4384                }
4385                let mut depth = 1usize;
4386                i += 2;
4387                while i < bytes.len() && depth > 0 {
4388                    if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
4389                        depth += 1;
4390                        i += 2;
4391                    } else if bytes[i] == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
4392                        depth -= 1;
4393                        i += 2;
4394                    } else {
4395                        i += 1;
4396                    }
4397                }
4398                continue;
4399            }
4400            b';' => {
4401                if has_content {
4402                    let head = &sql[start..i];
4403                    // v7.22 (round-13 T2) — a `COPY … FROM stdin;`
4404                    // statement owns its following data block
4405                    // through the `\.` terminator line (data lines
4406                    // may contain `;`, so generic splitting would
4407                    // shred them). Swallow head + data into ONE
4408                    // chunk; `execute_script` lowers it to INSERTs.
4409                    // pg_dump prefixes the COPY with a comment
4410                    // banner — strip it before the head check.
4411                    let head_clean = strip_leading_sql_noise(head);
4412                    let is_copy_head = head_clean
4413                        .get(..4)
4414                        .is_some_and(|p| p.eq_ignore_ascii_case("copy"))
4415                        && spg_engine::copy::parse_copy_from_stdin_head(head_clean).is_some();
4416                    if is_copy_head {
4417                        // Scan whole lines after the ';' until the
4418                        // `\.` terminator (or EOF — torn dumps lose
4419                        // their tail, same as psql would error).
4420                        let mut j = i + 1;
4421                        let data_end;
4422                        loop {
4423                            if j >= bytes.len() {
4424                                data_end = bytes.len();
4425                                break;
4426                            }
4427                            let line_end = sql[j..].find('\n').map_or(bytes.len(), |off| j + off);
4428                            if sql[j..line_end].trim_end_matches('\r').trim() == "\\." {
4429                                data_end = j;
4430                                i = line_end; // bottom i += 1 skips \n
4431                                break;
4432                            }
4433                            j = line_end + 1;
4434                        }
4435                        stmts.push(&sql[start..data_end]);
4436                        if data_end == bytes.len() {
4437                            i = bytes.len();
4438                        }
4439                        start = i + 1;
4440                        has_content = false;
4441                        i += 1;
4442                        continue;
4443                    }
4444                    note_dialect_signals(head, &mut mysql_escapes);
4445                    stmts.push(head);
4446                }
4447                start = i + 1;
4448                has_content = false;
4449            }
4450            b => {
4451                if !b.is_ascii_whitespace() {
4452                    has_content = true;
4453                }
4454            }
4455        }
4456        i += 1;
4457    }
4458    if has_content {
4459        stmts.push(&sql[start..]);
4460    }
4461    stmts
4462}
4463
4464#[cfg(test)]
4465mod tests {
4466    use super::*;
4467
4468    #[test]
4469    fn split_statements_basic_and_trailing() {
4470        assert_eq!(
4471            split_statements("CREATE TABLE a (x INT); INSERT INTO a VALUES (1)"),
4472            vec!["CREATE TABLE a (x INT)", " INSERT INTO a VALUES (1)"]
4473        );
4474        // whitespace/comment-only chunks drop
4475        assert!(split_statements("  ;; -- nothing\n;").is_empty());
4476    }
4477
4478    #[test]
4479    fn split_statements_quoting_forms() {
4480        // ';' inside a plain literal, a doubled quote, an E-string
4481        // backslash escape, a quoted identifier, and a dollar-quoted
4482        // body must not split.
4483        let cases = [
4484            "INSERT INTO t VALUES ('a;b')",
4485            "INSERT INTO t VALUES ('it''s; fine')",
4486            r"INSERT INTO t VALUES (E'it\'s; fine')",
4487            "CREATE TABLE \"odd;name\" (x INT)",
4488            "DO $body$ BEGIN PERFORM 1; END $body$",
4489            "DO $$ SELECT 1; $$",
4490        ];
4491        for sql in cases {
4492            assert_eq!(split_statements(sql), vec![sql], "must stay whole: {sql}");
4493        }
4494        // ...and each still splits cleanly from a neighbour.
4495        for sql in cases {
4496            let script = format!("{sql};\nSELECT 2");
4497            assert_eq!(
4498                split_statements(&script),
4499                vec![sql, "\nSELECT 2"],
4500                "must split after: {sql}"
4501            );
4502        }
4503    }
4504
4505    #[test]
4506    fn split_statements_drops_psql_meta_lines() {
4507        // v7.22 round-13 gap 1 — PG 18 pg_dump wraps scripts in
4508        // `\restrict` / `\unrestrict`; psql parity = the lines never
4509        // reach the parser.
4510        let script = "\\restrict TOKEN123\nSELECT 1;\n\\unrestrict TOKEN123\nSELECT 2;\n\\.\n";
4511        assert_eq!(split_statements(script), vec!["SELECT 1", "SELECT 2"]);
4512        // Mid-statement backslash is NOT a meta-command.
4513        let s2 = r"SELECT E'a\\b'";
4514        assert_eq!(split_statements(s2), vec![s2]);
4515    }
4516
4517    #[test]
4518    fn split_statements_comments_hide_semicolons() {
4519        let script = "-- c1 ; still comment\nSELECT 1; /* a ; b /* nested ; */ */ SELECT 2";
4520        let got = split_statements(script);
4521        assert_eq!(got.len(), 2);
4522        assert!(got[0].contains("SELECT 1"));
4523        assert!(got[1].contains("SELECT 2"));
4524    }
4525
4526    #[test]
4527    fn in_memory_create_insert_select() {
4528        let mut db = Database::open_in_memory();
4529        db.execute("CREATE TABLE t (id INT NOT NULL, name TEXT)")
4530            .unwrap();
4531        db.execute("INSERT INTO t VALUES (1, 'alice')").unwrap();
4532        db.execute("INSERT INTO t VALUES (2, 'bob')").unwrap();
4533        let rows = db.query("SELECT id FROM t WHERE id = 1").unwrap();
4534        assert_eq!(rows.len(), 1);
4535        match &rows[0][0] {
4536            Value::Int(1) => {}
4537            other => panic!("expected Int(1), got {other:?}"),
4538        }
4539    }
4540
4541    #[test]
4542    fn query_on_non_select_errors() {
4543        let mut db = Database::open_in_memory();
4544        db.execute("CREATE TABLE t (id INT)").unwrap();
4545        let r = db.query("INSERT INTO t VALUES (1)");
4546        assert!(r.is_err(), "query() on INSERT must error");
4547    }
4548
4549    #[test]
4550    fn snapshot_roundtrip() {
4551        let mut db = Database::open_in_memory();
4552        db.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
4553        db.execute("INSERT INTO t VALUES (42)").unwrap();
4554        let bytes = db.snapshot();
4555        let mut restored = Database::restore(&bytes).unwrap();
4556        let rows = restored.query("SELECT id FROM t WHERE id = 42").unwrap();
4557        assert_eq!(rows.len(), 1);
4558        match &rows[0][0] {
4559            Value::Int(42) => {}
4560            other => panic!("expected Int(42), got {other:?}"),
4561        }
4562    }
4563
4564    #[test]
4565    fn from_spg_row_trait_shape() {
4566        struct User {
4567            _id: i32,
4568        }
4569        impl FromSpgRow for User {
4570            fn from_spg_row(row: &[Value]) -> Result<Self, EngineError> {
4571                match row.first() {
4572                    Some(Value::Int(n)) => Ok(Self { _id: *n }),
4573                    _ => Err(EngineError::Unsupported("bad id".into())),
4574                }
4575            }
4576        }
4577        let row = vec![Value::Int(7)];
4578        let _u = User::from_spg_row(&row).unwrap();
4579    }
4580
4581    // ─────────────────────────────────────────────────────────────
4582    // v7.37.5 — mailrs crash-recovery lock-hang regression tests.
4583    // Three asks; each closed atomically:
4584    //   Ask 1 — in-process registry refuses sibling sl-blocking
4585    //   Ask 2 — force_unlock clears the in-process registry too
4586    //   Ask 3 — apply_redo batches DELETE/INSERT/UPDATE so the
4587    //           index rebuild happens once per replay, not once
4588    //           per WAL record
4589    // ─────────────────────────────────────────────────────────────
4590
4591    fn tmpdir() -> std::path::PathBuf {
4592        let base = std::env::temp_dir().join(format!(
4593            "spg-v7375-lockhang-{}-{}",
4594            std::process::id(),
4595            std::time::SystemTime::now()
4596                .duration_since(std::time::UNIX_EPOCH)
4597                .unwrap()
4598                .as_nanos()
4599        ));
4600        std::fs::create_dir_all(&base).unwrap();
4601        base
4602    }
4603
4604    #[test]
4605    fn ask1_in_process_registry_refuses_sibling_open() {
4606        // Two `Database::open_path` calls in the same process MUST
4607        // NOT both succeed (the second would race the first's WAL
4608        // replay). v7.37.10 leaned on on-disk pid + start-time
4609        // matching; v7.37.5 settles it directly via
4610        // `ACTIVE_OPEN_PATHS`.
4611        let dir = tmpdir();
4612        let db_path = dir.join("t.spg");
4613        let first = Database::open_path(&db_path).expect("first open succeeds");
4614        // Confirm the registry registered this path.
4615        let lock_path = {
4616            let mut p = db_path.clone();
4617            let mut s = p.file_name().unwrap().to_os_string();
4618            s.push(".lock");
4619            p.set_file_name(s);
4620            p
4621        };
4622        assert!(
4623            is_lock_path_active_in_process(&lock_path),
4624            "lock_path must be registered while Database is live"
4625        );
4626        // Sibling open MUST refuse honestly (not hang).
4627        let second = Database::open_path(&db_path);
4628        assert!(
4629            matches!(second, Err(EngineError::Unsupported(_))),
4630            "sibling open_path on same path must refuse, got {second:?}"
4631        );
4632        drop(first);
4633        // Once dropped, the registry releases and a fresh open
4634        // succeeds.
4635        assert!(
4636            !is_lock_path_active_in_process(&lock_path),
4637            "lock_path must be de-registered after Database is dropped"
4638        );
4639        let third = Database::open_path(&db_path);
4640        assert!(
4641            third.is_ok(),
4642            "post-drop open_path on same path must succeed, got {third:?}"
4643        );
4644        let _ = std::fs::remove_dir_all(&dir);
4645    }
4646
4647    #[test]
4648    fn ask2_force_unlock_clears_in_process_registry() {
4649        // `force_unlock` is the operator's "no one owns this catalog"
4650        // assertion. Post-Ask-1 the in-process registry would refuse
4651        // a sibling open even after force_unlock — Ask 2 wires
4652        // force_unlock to ALSO clear the registry so retries see a
4653        // consistent "free" state.
4654        let dir = tmpdir();
4655        let db_path = dir.join("u.spg");
4656        // Open a database to populate the registry, then keep the
4657        // handle so the registry entry survives.
4658        let _first = Database::open_path(&db_path).expect("first open succeeds");
4659        let lock_path = {
4660            let mut p = db_path.clone();
4661            let mut s = p.file_name().unwrap().to_os_string();
4662            s.push(".lock");
4663            p.set_file_name(s);
4664            p
4665        };
4666        assert!(is_lock_path_active_in_process(&lock_path));
4667        // force_unlock — operator declares the catalog free.
4668        Database::force_unlock(&db_path).expect("force_unlock succeeds");
4669        // Registry MUST be cleared (Ask 2 contract).
4670        assert!(
4671            !is_lock_path_active_in_process(&lock_path),
4672            "force_unlock must clear the in-process registry entry"
4673        );
4674        // Disk lock is also gone.
4675        assert!(
4676            !lock_path.exists(),
4677            "force_unlock must remove the on-disk lock dir"
4678        );
4679        let _ = std::fs::remove_dir_all(&dir);
4680    }
4681
4682    #[test]
4683    fn ask3_apply_redo_differential_vs_per_record_path() {
4684        // v7.37.5 — differential test: batched `apply_redo` MUST
4685        // produce the same final catalog state (rows + indices)
4686        // as the legacy per-record path that called the public
4687        // `Table::insert`, `update_row`, `delete_rows` in order.
4688        // Built on a smaller table so the per-record path is
4689        // tractable. Mixes Insert/Update/Delete to exercise the
4690        // composition logic.
4691        use spg_storage::{Catalog, ColumnSchema, Row, RowChange, TableSchema};
4692        use spg_storage::{DataType, Value};
4693
4694        fn build_seed_catalog() -> Catalog {
4695            let columns = vec![
4696                ColumnSchema::new("a", DataType::Int, false),
4697                ColumnSchema::new("b", DataType::Int, false),
4698                ColumnSchema::new("c", DataType::Int, false),
4699            ];
4700            let mut cat = Catalog::new();
4701            cat.create_table(TableSchema::new("t", columns)).unwrap();
4702            // 3 BTree indices on a, b, c.
4703            cat.get_mut("t")
4704                .unwrap()
4705                .add_index("idx_a".into(), "a")
4706                .unwrap();
4707            cat.get_mut("t")
4708                .unwrap()
4709                .add_index("idx_b".into(), "b")
4710                .unwrap();
4711            cat.get_mut("t")
4712                .unwrap()
4713                .add_index("idx_c".into(), "c")
4714                .unwrap();
4715            for r in 0..100 {
4716                cat.get_mut("t")
4717                    .unwrap()
4718                    .insert(Row::new(vec![
4719                        Value::Int(r),
4720                        Value::Int(r * 2),
4721                        Value::Int(r * 3),
4722                    ]))
4723                    .unwrap();
4724            }
4725            cat
4726        }
4727
4728        let changes: Vec<RowChange> = vec![
4729            RowChange::Delete {
4730                table: "t".to_string(),
4731                positions: vec![5, 7, 9],
4732            },
4733            RowChange::Insert {
4734                table: "t".to_string(),
4735                row: Row::new(vec![Value::Int(999), Value::Int(1998), Value::Int(2997)]),
4736            },
4737            RowChange::Update {
4738                table: "t".to_string(),
4739                pos: 3,
4740                new_row: vec![Value::Int(42), Value::Int(84), Value::Int(126)],
4741            },
4742            RowChange::Delete {
4743                table: "t".to_string(),
4744                positions: vec![0, 1],
4745            },
4746        ];
4747
4748        // Path A: the new batched `apply_redo`.
4749        let mut cat_batched = build_seed_catalog();
4750        cat_batched.apply_redo(&changes).unwrap();
4751
4752        // Path B: the legacy per-record path via the public
4753        // `Table` mutators. Position semantics for `Delete` /
4754        // `Update` are identical to `apply_redo`'s composition
4755        // (positions reference the post-prior-change layout).
4756        let mut cat_legacy = build_seed_catalog();
4757        for change in &changes {
4758            match change {
4759                RowChange::Insert { table, row } => {
4760                    cat_legacy
4761                        .get_mut(table)
4762                        .unwrap()
4763                        .insert(row.clone())
4764                        .unwrap();
4765                }
4766                RowChange::Update {
4767                    table,
4768                    pos,
4769                    new_row,
4770                } => {
4771                    cat_legacy
4772                        .get_mut(table)
4773                        .unwrap()
4774                        .update_row(*pos, new_row.clone())
4775                        .unwrap();
4776                }
4777                RowChange::Delete { table, positions } => {
4778                    cat_legacy.get_mut(table).unwrap().delete_rows(positions);
4779                }
4780            }
4781        }
4782
4783        let a = cat_batched.get("t").unwrap();
4784        let b = cat_legacy.get("t").unwrap();
4785        assert_eq!(
4786            a.rows().len(),
4787            b.rows().len(),
4788            "row counts differ after replay"
4789        );
4790        for (i, (ar, br)) in a.rows().iter().zip(b.rows().iter()).enumerate() {
4791            assert_eq!(
4792                ar.values, br.values,
4793                "row {i} differs: batched={:?} legacy={:?}",
4794                ar.values, br.values
4795            );
4796        }
4797    }
4798
4799    #[test]
4800    fn ask3_apply_redo_batches_index_rebuilds() {
4801        // Synthetic reproducer for the 27-min mailrs WAL replay
4802        // hang. Build a 100k-row table with 13 BTree indices, then
4803        // apply 5000 `RowChange::Delete` records via the public
4804        // `Catalog::apply_redo` entry point. Pre-v7.37.5 each
4805        // record triggered a full `rebuild_indices` — minutes of
4806        // CPU. Post-v7.37.5 there's exactly one rebuild at the
4807        // end.
4808        //
4809        // The assertion is a wall-clock budget: even on a slow
4810        // CI box this must complete in well under 10 seconds.
4811        use spg_storage::{Catalog, ColumnSchema, Row, RowChange, TableSchema};
4812        use spg_storage::{DataType, Value};
4813
4814        const N_ROWS: usize = 100_000;
4815        const N_INDICES: usize = 13;
4816        const N_DELETE_RECORDS: usize = 5_000;
4817        const ROWS_PER_RECORD: usize = 1; // mirrors mailrs WAL shape
4818
4819        // Build a catalog with one table, N_INDICES BTree indices
4820        // over int columns.
4821        let columns: Vec<ColumnSchema> = (0..N_INDICES)
4822            .map(|i| ColumnSchema::new(format!("c{i}"), DataType::Int, false))
4823            .collect();
4824        let schema = TableSchema::new("t", columns);
4825        let mut catalog = Catalog::new();
4826        catalog.create_table(schema).unwrap();
4827        for i in 0..N_INDICES {
4828            catalog
4829                .get_mut("t")
4830                .unwrap()
4831                .add_index(format!("idx_c{i}"), &format!("c{i}"))
4832                .unwrap();
4833        }
4834        for r in 0..N_ROWS {
4835            let row = Row::new(
4836                (0..N_INDICES)
4837                    .map(|c| Value::Int((r as i32) * 31 + (c as i32)))
4838                    .collect(),
4839            );
4840            catalog.get_mut("t").unwrap().insert(row).unwrap();
4841        }
4842        // Build the 5000 Delete records. Each record references
4843        // positions valid at the time it would have been written;
4844        // since each removes ROWS_PER_RECORD row (at position 0
4845        // post-prior-deletes), the position stays 0 throughout —
4846        // mirrors a sentinel/oldest-first sweep.
4847        let changes: Vec<RowChange> = (0..N_DELETE_RECORDS)
4848            .map(|_| RowChange::Delete {
4849                table: "t".to_string(),
4850                positions: (0..ROWS_PER_RECORD).collect(),
4851            })
4852            .collect();
4853
4854        let start = std::time::Instant::now();
4855        catalog.apply_redo(&changes).unwrap();
4856        let elapsed = start.elapsed();
4857        let remaining = catalog.get("t").unwrap().rows().len();
4858        assert_eq!(
4859            remaining,
4860            N_ROWS - N_DELETE_RECORDS * ROWS_PER_RECORD,
4861            "expected {} rows left after {} deletes",
4862            N_ROWS - N_DELETE_RECORDS * ROWS_PER_RECORD,
4863            N_DELETE_RECORDS * ROWS_PER_RECORD
4864        );
4865        // 10 s budget — pre-v7.37.5 was 27 minutes on prod-shape;
4866        // post-fix is ~300 ms locally. A 10 s ceiling leaves
4867        // generous headroom for slow CI.
4868        assert!(
4869            elapsed < std::time::Duration::from_secs(10),
4870            "apply_redo of {N_DELETE_RECORDS} DELETE records on {N_ROWS}-row × {N_INDICES}-index table \
4871             took {elapsed:?} — Ask 3 batching regression"
4872        );
4873        eprintln!(
4874            "ask3_apply_redo_batches_index_rebuilds: {N_DELETE_RECORDS} DELETE records \
4875             on {N_ROWS}-row × {N_INDICES}-index table replayed in {elapsed:?}"
4876        );
4877    }
4878}