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};
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]) {
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, 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.
145fn wall_clock_micros() -> i64 {
146    SystemTime::now()
147        .duration_since(UNIX_EPOCH)
148        .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
149}
150
151use spg_manifest::{CatalogManifest, ColdSegmentEntry, manifest_path as spg_manifest_path};
152
153// -- v7.1 WAL format constants (mirror `spg-server`'s) ---------
154// Kept private so callers can't mis-frame records; the v3 layout
155// is the same the server uses, so a `spg-server` boot can read a
156// database an embedded process wrote and vice versa.
157const WAL_V2_SENTINEL: u32 = 0x8000_0000;
158const WAL_V3_FLAG: u32 = 0x4000_0000;
159const WAL_V3_TYPE_AUTO_COMMIT_SQL: u8 = 0x01;
160/// v7.18 — durability checkpoint marker stays at 0x02 (skipped on replay).
161const WAL_V3_TYPE_DURABILITY_CHECKPOINT: u8 = 0x02;
162/// v7.18 PITR — auto-commit-sql record with appended (commit_lsn,
163/// commit_unix_us) fields so replay can target a specific point in
164/// time. Backward-compat: v3 records (type 0x01) keep working, the
165/// envelope flag bits are unchanged. The new type byte is the
166/// schema-version discriminator.
167const WAL_V4_TYPE_AUTO_COMMIT_SQL: u8 = 0x10;
168/// v7.18 — sentinel for "no wall clock" inside a v4 record's
169/// commit_unix_us slot. Restore-to-timestamp skips records with
170/// this sentinel (no time anchor); LSN-based restore is
171/// unaffected.
172const WAL_V4_NO_CLOCK: i64 = i64::MIN;
173/// v7.18 — extra header bytes after the type byte in a v4 record:
174/// 8 bytes commit_lsn (u64 LE) + 8 bytes commit_unix_us (i64 LE).
175const WAL_V4_EXTRA_HEADER: usize = 16;
176/// v7.18 PITR — checkpoint anchor record written to the WAL *before*
177/// the snapshot file replaces the on-disk catalog. Carries the
178/// (lsn, ts, snapshot_path) triple so restore tooling can find the
179/// matching base snapshot without scanning the filesystem. Replay
180/// dispatch skips it (same as the v3 durability marker).
181const WAL_V4_TYPE_CHECKPOINT_MARKER: u8 = 0x11;
182
183/// v7.21 (mailrs embed round-12 polish) — one COMMITted explicit
184/// transaction, flushed atomically at COMMIT time. Payload = the
185/// transaction's bind-final mutation statements joined with `";\n"`;
186/// replay re-splits via [`split_statements`] and applies in order.
187/// Same 16-byte (commit_lsn, commit_unix_us) prefix as the v4
188/// auto-commit record. The record is CRC-framed like every other
189/// record, so replay applies the whole transaction or — torn tail —
190/// none of it; a transaction can never half-resurrect.
191///
192/// Why it exists: in-transaction mutations only touch the engine's
193/// shadow catalog (`modified_catalog: false`), so the per-statement
194/// auto-commit append never fired and a COMMIT followed by a crash
195/// (no graceful Drop checkpoint) lost the transaction.
196const WAL_V4_TYPE_TX_COMMIT_SQL: u8 = 0x12;
197
198/// v7.1 — auto-checkpoint threshold. Once the WAL grows past
199/// this many bytes, the next successful `execute()` call ends
200/// with a `checkpoint()` so the WAL stays bounded. Tunable via
201/// `SPG_EMBEDDED_CHECKPOINT_BYTES` env.
202fn default_checkpoint_threshold_bytes() -> u64 {
203    std::env::var("SPG_EMBEDDED_CHECKPOINT_BYTES")
204        .ok()
205        .and_then(|s| s.parse::<u64>().ok())
206        .filter(|&n| n > 0)
207        .unwrap_or(4 * 1024 * 1024)
208}
209
210/// v7.1 — encode one v3 `auto_commit_sql` record. Layout:
211///
212/// ```text
213/// [u32 LE (len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
214/// [u32 LE crc32 over (type_byte || sql_bytes)]
215/// [u8 type = 0x01]
216/// [sql bytes]
217/// ```
218fn encode_v3_auto_commit(sql: &str) -> Vec<u8> {
219    let payload = sql.as_bytes();
220    let mut crc_buf = Vec::with_capacity(1 + payload.len());
221    crc_buf.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
222    crc_buf.extend_from_slice(payload);
223    let crc = spg_crypto::crc32::crc32(&crc_buf);
224    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
225    let mut out = Vec::with_capacity(4 + 4 + 1 + payload.len());
226    out.extend_from_slice(&header);
227    out.extend_from_slice(&crc.to_le_bytes());
228    out.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
229    out.extend_from_slice(payload);
230    out
231}
232
233/// v7.20 P2 — WAL group-commit. N concurrent commits share one
234/// fsync (the 4.2 ms p50 that profile_breakdown measured as
235/// 99.2% of the durable write path).
236///
237/// Leader-follower protocol, same family as PG's group commit:
238///
239/// 1. `enqueue(record)` — called while the caller still holds
240///    the engine's write lock. Appends the encoded record to the
241///    shared buffer, returns a sequence ticket. O(memcpy).
242/// 2. Caller RELEASES the engine write lock (the next writer's
243///    mutation proceeds in parallel with this batch's fsync).
244/// 3. `wait_flushed(seq)` — if nobody is flushing, the caller
245///    elects itself leader: swaps the buffer out, writes +
246///    fsyncs ONCE for every record in the batch, marks the
247///    batch durable, wakes all followers. Otherwise it parks on
248///    the condvar until a leader covers its seq.
249///
250/// Durability contract is unchanged from v7.19: `execute()`
251/// does not return Ok until the record that describes its
252/// mutation is fsynced. The only change is N callers sharing
253/// one fsync instead of paying one each.
254///
255/// Lock order (deadlock-free): `state` then `file`; never the
256/// reverse. The leader holds `file` WITHOUT `state` during IO so
257/// enqueues continue while fsync runs.
258#[derive(Debug)]
259struct WalGroup {
260    state: Mutex<WalGroupState>,
261    cond: std::sync::Condvar,
262    /// Active chunk file handle. Separate lock from `state` so
263    /// the leader's write+fsync doesn't block concurrent
264    /// enqueues. Swapped by `checkpoint()` at rotation.
265    file: Mutex<File>,
266}
267
268#[derive(Debug)]
269struct WalGroupState {
270    /// Encoded records awaiting flush.
271    buf: Vec<u8>,
272    /// Monotonic enqueue counter (1-based).
273    enqueued_seq: u64,
274    /// Highest seq whose record is fsynced.
275    flushed_seq: u64,
276    /// True while some caller is inside the leader IO section.
277    leader_active: bool,
278    /// Sticky fatal error — a failed fsync poisons the WAL
279    /// (loud, never silent). All current + future waiters error.
280    failed: Option<String>,
281    /// Bytes written to the active chunk since rotation —
282    /// drives the auto-checkpoint trigger.
283    written_len: u64,
284}
285
286/// Ticket returned by the buffered write path; `wait()` blocks
287/// until the record it covers is durable (or the WAL is
288/// poisoned). Cheap to move across threads.
289#[derive(Debug)]
290pub struct WalTicket {
291    group: Arc<WalGroup>,
292    seq: u64,
293}
294
295impl WalGroup {
296    fn new(file: File, initial_len: u64) -> Self {
297        Self {
298            state: Mutex::new(WalGroupState {
299                buf: Vec::new(),
300                enqueued_seq: 0,
301                flushed_seq: 0,
302                leader_active: false,
303                failed: None,
304                written_len: initial_len,
305            }),
306            cond: std::sync::Condvar::new(),
307            file: Mutex::new(file),
308        }
309    }
310
311    /// Append `record` to the pending batch. Returns the seq the
312    /// caller must wait on. Called under the engine write lock —
313    /// keep it O(memcpy).
314    fn enqueue(&self, record: &[u8]) -> u64 {
315        let mut g = self.state.lock().expect("wal state poisoned");
316        g.buf.extend_from_slice(record);
317        g.enqueued_seq += 1;
318        g.enqueued_seq
319    }
320
321    /// Block until `seq` is durable. Leader-follower: the first
322    /// arriving waiter flushes for everyone.
323    fn wait_flushed(&self, seq: u64) -> Result<(), EngineError> {
324        let mut g = self.state.lock().expect("wal state poisoned");
325        loop {
326            if let Some(e) = &g.failed {
327                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
328                    format!("WAL poisoned by earlier flush failure: {e}"),
329                )));
330            }
331            if g.flushed_seq >= seq {
332                return Ok(());
333            }
334            if !g.leader_active {
335                // Elect self leader.
336                g.leader_active = true;
337                drop(g);
338                // v7.20 — commit_delay (PG's same-named knob):
339                // before taking the batch, give in-flight
340                // writers a short window to enqueue so the
341                // shared fsync covers more commits. 150 µs costs
342                // ~3.5% on a solo 4.2 ms fsync but multiplies
343                // batch size under load. Tunable via
344                // SPG_COMMIT_DELAY_US (0 disables).
345                let delay = commit_delay_us();
346                if delay > 0 {
347                    std::thread::sleep(std::time::Duration::from_micros(delay));
348                }
349                let (batch, flush_to) = {
350                    let mut g2 = self.state.lock().expect("wal state poisoned");
351                    (core::mem::take(&mut g2.buf), g2.enqueued_seq)
352                };
353                let io_result: std::io::Result<()> = (|| {
354                    let mut f = self.file.lock().expect("wal file poisoned");
355                    f.write_all(&batch)?;
356                    f.sync_data()
357                })();
358                g = self.state.lock().expect("wal state poisoned");
359                g.leader_active = false;
360                match io_result {
361                    Ok(()) => {
362                        g.flushed_seq = flush_to;
363                        g.written_len = g.written_len.saturating_add(batch.len() as u64);
364                    }
365                    Err(e) => {
366                        g.failed = Some(e.to_string());
367                    }
368                }
369                self.cond.notify_all();
370                //
371
372                // Loop continues: either our seq is now covered
373                // (leader path normally returns next iteration)
374                // or the error branch surfaces.
375                continue;
376            }
377            g = self.cond.wait(g).expect("wal condvar poisoned");
378        }
379    }
380
381    /// Drain the pending batch + flush synchronously. Caller must
382    /// guarantee no concurrent enqueues (checkpoint holds the
383    /// engine exclusively). Used before rotation so the marker
384    /// lands in the right chunk.
385    fn flush_now(&self) -> Result<(), EngineError> {
386        let mut g = self.state.lock().expect("wal state poisoned");
387        if let Some(e) = &g.failed {
388            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
389                format!("WAL poisoned: {e}"),
390            )));
391        }
392        let batch = core::mem::take(&mut g.buf);
393        let flush_to = g.enqueued_seq;
394        if batch.is_empty() {
395            return Ok(());
396        }
397        drop(g);
398        let io: std::io::Result<()> = (|| {
399            let mut f = self.file.lock().expect("wal file poisoned");
400            f.write_all(&batch)?;
401            f.sync_data()
402        })();
403        let mut g = self.state.lock().expect("wal state poisoned");
404        match io {
405            Ok(()) => {
406                g.flushed_seq = flush_to;
407                g.written_len = g.written_len.saturating_add(batch.len() as u64);
408                self.cond.notify_all();
409                Ok(())
410            }
411            Err(e) => {
412                g.failed = Some(e.to_string());
413                self.cond.notify_all();
414                Err(io_err(e))
415            }
416        }
417    }
418
419    /// Swap the active chunk handle (rotation). Caller flushes
420    /// first; both locks taken in canonical order.
421    fn rotate_file(&self, new_file: File) {
422        let mut g = self.state.lock().expect("wal state poisoned");
423        let mut f = self.file.lock().expect("wal file poisoned");
424        *f = new_file;
425        g.written_len = 0;
426    }
427
428    fn written_len(&self) -> u64 {
429        let g = self.state.lock().expect("wal state poisoned");
430        g.written_len + g.buf.len() as u64
431    }
432}
433
434impl WalTicket {
435    /// Block until the record this ticket covers is durable.
436    ///
437    /// Under `SPG_SYNCHRONOUS_COMMIT=off` this returns
438    /// immediately — the background flusher (or the next
439    /// checkpoint / clean shutdown) makes the record durable
440    /// within `SPG_WAL_WRITER_DELAY_MS`. Same contract as PG's
441    /// `synchronous_commit = off`.
442    ///
443    /// # Errors
444    /// Surfaces the leader's IO error if the batch flush failed
445    /// (the WAL is then poisoned for all subsequent writes).
446    pub fn wait(&self) -> Result<(), EngineError> {
447        if !synchronous_commit_on() {
448            return Ok(());
449        }
450        self.group.wait_flushed(self.seq)
451    }
452}
453
454/// v7.19 P3 — retention sweep loop. Runs in a dedicated thread
455/// spawned by `Database::open_path` when `SPG_PITR_RETENTION_HOURS`
456/// is set to a non-zero value. Wakes every
457/// `SPG_PITR_RETENTION_CHECK_SEC` (default 60 s), enumerates chunks
458/// under `wal_dir`, archives via `SPG_PITR_ARCHIVE_CMD` if set, and
459/// deletes anything older than `retention_hours`.
460///
461/// Loud-failure posture matches PG's `archive_command`: if the
462/// archive command returns non-zero, the chunk stays on disk and
463/// a warning prints to stderr. The retention sweep doesn't delete
464/// a chunk it failed to archive.
465fn retention_sweep_loop(
466    wal_dir: PathBuf,
467    retention_hours: u64,
468    check_interval: std::time::Duration,
469    archive_cmd: Option<String>,
470    shutdown: Arc<AtomicBool>,
471) {
472    while !shutdown.load(Ordering::SeqCst) {
473        if let Err(e) = retention_sweep_once(&wal_dir, retention_hours, archive_cmd.as_deref()) {
474            eprintln!("spg-embedded: retention sweep error: {e}");
475        }
476        // Sleep in short ticks so shutdown isn't blocked on a
477        // 60 s naptime when Drop signals.
478        let mut elapsed = std::time::Duration::ZERO;
479        let tick = std::time::Duration::from_millis(250);
480        while elapsed < check_interval {
481            if shutdown.load(Ordering::SeqCst) {
482                return;
483            }
484            std::thread::sleep(tick);
485            elapsed += tick;
486        }
487    }
488}
489
490/// v7.19 P3 — one retention sweep pass over `wal_dir`. Extracted
491/// from the loop so tests can drive it directly. Public so the
492/// e2e_pitr_retention integration test (and any future operator
493/// tooling that wants synchronous retention) can call it.
494pub fn retention_sweep_once(
495    wal_dir: &Path,
496    retention_hours: u64,
497    archive_cmd: Option<&str>,
498) -> std::io::Result<()> {
499    if !wal_dir.exists() {
500        return Ok(());
501    }
502    let now_us = wall_clock_micros();
503    let cutoff_us = (now_us as i128 - (retention_hours as i128 * 3_600 * 1_000_000)) as i64;
504    let chunks = sorted_wal_chunks(wal_dir)?;
505    for chunk in chunks {
506        // Don't sweep the most-recent chunk; it's the live one
507        // execute() is appending to. Compare against the largest
508        // filename-prefix unix_us.
509        let stem = match chunk.file_stem().and_then(|s| s.to_str()) {
510            Some(s) => s,
511            None => continue,
512        };
513        let chunk_us: i64 = stem
514            .split_once('_')
515            .and_then(|(prefix, _)| i64::from_str_radix(prefix, 16).ok())
516            .unwrap_or(0);
517        if chunk_us >= cutoff_us {
518            continue;
519        }
520        // Archive first if requested.
521        if let Some(cmd) = archive_cmd {
522            if !cmd.is_empty() {
523                let output = std::process::Command::new("sh")
524                    .arg("-c")
525                    .arg(cmd)
526                    .arg("--")
527                    .arg(&chunk)
528                    .output()?;
529                if !output.status.success() {
530                    eprintln!(
531                        "spg-embedded: SPG_PITR_ARCHIVE_CMD failed for {} (exit {}); chunk stays on disk",
532                        chunk.display(),
533                        output.status.code().unwrap_or(-1)
534                    );
535                    continue;
536                }
537            }
538        }
539        // Delete the chunk + its sibling .checksum if present.
540        if let Err(e) = std::fs::remove_file(&chunk) {
541            eprintln!(
542                "spg-embedded: retention remove {} failed: {e}",
543                chunk.display()
544            );
545            continue;
546        }
547        let mut cs = chunk.clone();
548        let mut name = cs.file_name().map(|n| n.to_os_string()).unwrap_or_default();
549        name.push(".checksum");
550        cs.set_file_name(name);
551        let _ = std::fs::remove_file(&cs);
552    }
553    Ok(())
554}
555
556/// v7.20 — group-commit delay window in µs (PG `commit_delay`
557/// analogue). The flush leader sleeps this long before taking
558/// the batch so concurrent writers pile in. Default 150 µs;
559/// `SPG_COMMIT_DELAY_US=0` disables.
560fn commit_delay_us() -> u64 {
561    static CACHED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
562    *CACHED.get_or_init(|| {
563        std::env::var("SPG_COMMIT_DELAY_US")
564            .ok()
565            .and_then(|s| s.parse::<u64>().ok())
566            .unwrap_or(150)
567    })
568}
569
570/// v7.20 — PG `synchronous_commit` analogue. `on` (default):
571/// `execute()` blocks until its WAL record is fsynced —
572/// zero-loss durability. `off`: `execute()` returns after the
573/// in-memory mutation + WAL enqueue; a background flusher
574/// thread writes + fsyncs every `SPG_WAL_WRITER_DELAY_MS`
575/// (default 200 ms — PG's `wal_writer_delay` default). Crash
576/// window = up to one flush interval of confirmed-but-unsynced
577/// commits — exactly the trade PG documents for the same
578/// setting. Clean shutdown (Drop / checkpoint) always flushes.
579fn synchronous_commit_on() -> bool {
580    static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
581    *CACHED.get_or_init(|| {
582        !std::env::var("SPG_SYNCHRONOUS_COMMIT")
583            .map(|v| v.eq_ignore_ascii_case("off") || v == "0" || v.eq_ignore_ascii_case("false"))
584            .unwrap_or(false)
585    })
586}
587
588/// v7.20 — background WAL flusher cadence for
589/// `SPG_SYNCHRONOUS_COMMIT=off` (PG `wal_writer_delay`).
590fn wal_writer_delay_ms() -> u64 {
591    static CACHED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
592    *CACHED.get_or_init(|| {
593        std::env::var("SPG_WAL_WRITER_DELAY_MS")
594            .ok()
595            .and_then(|s| s.parse::<u64>().ok())
596            .filter(|&n| n > 0)
597            .unwrap_or(200)
598    })
599}
600
601fn pitr_retention_hours() -> u64 {
602    std::env::var("SPG_PITR_RETENTION_HOURS")
603        .ok()
604        .and_then(|s| s.parse::<u64>().ok())
605        .unwrap_or(0)
606}
607
608fn pitr_retention_check_sec() -> u64 {
609    std::env::var("SPG_PITR_RETENTION_CHECK_SEC")
610        .ok()
611        .and_then(|s| s.parse::<u64>().ok())
612        .filter(|&n| n > 0)
613        .unwrap_or(60)
614}
615
616fn pitr_archive_cmd() -> Option<String> {
617    std::env::var("SPG_PITR_ARCHIVE_CMD")
618        .ok()
619        .filter(|s| !s.is_empty())
620}
621
622/// v7.19 — replay every record from `wal_bytes` whose
623/// `commit_lsn` is strictly greater than `floor_lsn`. v3 records
624/// (no LSN) and v4 records with `commit_lsn <= floor_lsn` are
625/// skipped — the snapshot loaded ahead of this call already
626/// reflects them, and re-applying would DuplicateTable /
627/// double-insert. v3 records inside the legacy migration chunk
628/// always apply because the migration sets `floor_lsn = 0` and
629/// v3 records carry no LSN to compare; the pre-migration
630/// behaviour (every record replays) is what the migration
631/// preserves.
632///
633/// Returns the count of records successfully applied. Same
634/// torn-tail semantics as `replay_wal_into_engine`.
635fn replay_wal_filtered(
636    wal_bytes: &[u8],
637    engine: &mut Engine,
638    floor_lsn: u64,
639    quarantine: &mut Vec<QuarantinedStmt>,
640) -> Result<usize, String> {
641    let records = parse_wal_records(wal_bytes)?;
642    let mut applied = 0usize;
643    for r in &records {
644        // Skip markers + non-SQL records.
645        if r.type_byte == WAL_V3_TYPE_DURABILITY_CHECKPOINT
646            || r.type_byte == WAL_V4_TYPE_CHECKPOINT_MARKER
647        {
648            continue;
649        }
650        // v4 SQL records carry an LSN. Apply iff strictly above
651        // the snapshot floor.
652        if r.type_byte == WAL_V4_TYPE_AUTO_COMMIT_SQL || r.type_byte == WAL_V4_TYPE_TX_COMMIT_SQL {
653            if let Some(lsn) = r.commit_lsn {
654                if lsn <= floor_lsn {
655                    continue;
656                }
657            }
658        }
659        // v3 records (type 0x01, no LSN) always apply — the
660        // legacy migration path is the only place they appear,
661        // and floor_lsn=0 there.
662        let sql = match std::str::from_utf8(r.sql) {
663            Ok(s) => s,
664            Err(e) => return Err(format!("non-UTF-8 SQL at offset {}: {e}", r.offset)),
665        };
666        // v7.21 — a tx-commit record carries the whole transaction
667        // as a `";\n"`-joined script; auto-commit records are a
668        // single statement, for which split_statements is a no-op.
669        //
670        // v7.30.1 (mailrs round-24 ask 2) — a statement the engine
671        // REJECTS is quarantined, not fatal: "one statement failed
672        // to replay" ≠ "the catalog is corrupt". Framing damage
673        // (parse_wal_records / non-UTF-8 above) still errors — that
674        // IS corruption. Subsequent statements of a tx script keep
675        // applying: the bricking class is a no-op-at-runtime
676        // statement that re-applies non-idempotently, and skipping
677        // just it reconstructs the runtime state.
678        for stmt in split_statements(sql) {
679            if let Err(e) = engine.execute(stmt) {
680                quarantine.push(QuarantinedStmt {
681                    offset: r.offset,
682                    sql: stmt.to_string(),
683                    error: format!("{e:?}"),
684                });
685            }
686        }
687        applied += 1;
688    }
689    Ok(applied)
690}
691
692/// v7.30.1 (mailrs round-24 ask 2) — one statement that failed to
693/// re-apply during boot replay. Kept for forensics in a
694/// `quarantine-*.log` beside the WAL chunks; the boot continues.
695struct QuarantinedStmt {
696    offset: usize,
697    sql: String,
698    error: String,
699}
700
701fn format_quarantine_line(q: &QuarantinedStmt) -> String {
702    format!("offset {}: {}\n  rejected: {}\n", q.offset, q.sql, q.error)
703}
704
705/// v7.19 — WAL chunk filename format. Zero-padded 16-digit
706/// hex on both parts so default lexicographic sort matches
707/// numeric order, with the unix_us prefix coming first so
708/// the on-disk listing is chronological too.
709fn chunk_filename(unix_us: i64, leading_lsn: u64) -> String {
710    // Negative timestamps shouldn't happen in practice (we sit
711    // post-1970), but clamp to 0 so the zero-padded
712    // representation stays sortable.
713    let us = unix_us.max(0) as u64;
714    format!("{us:016x}_{leading_lsn:016x}.wal")
715}
716
717/// v7.19 — filename used for the legacy single-file WAL when
718/// `open_path` migrates a v7.18-layout database into the new
719/// chunk directory. Lexicographically smallest possible value
720/// so subsequent chunks sort after it.
721fn legacy_chunk_filename() -> String {
722    chunk_filename(0, 0)
723}
724
725/// v7.19 — list every `.wal` file in `wal_dir` in
726/// lexicographic order (which doubles as chunk-creation
727/// order thanks to the zero-padded filename format).
728fn sorted_wal_chunks(wal_dir: &Path) -> std::io::Result<Vec<PathBuf>> {
729    let mut paths = Vec::new();
730    let read_dir = match std::fs::read_dir(wal_dir) {
731        Ok(rd) => rd,
732        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(paths),
733        Err(e) => return Err(e),
734    };
735    for entry in read_dir {
736        let entry = entry?;
737        let path = entry.path();
738        if path.extension().and_then(|s| s.to_str()) == Some("wal") {
739            paths.push(path);
740        }
741    }
742    paths.sort();
743    Ok(paths)
744}
745
746/// v7.18 PITR — encode one v4 `checkpoint_marker` record. Layout:
747///
748/// ```text
749/// [u32 LE (payload_len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
750/// [u32 LE crc32 over (type_byte || payload)]
751/// [u8  type = 0x11]
752/// payload:
753///   [u64 LE checkpoint_lsn]
754///   [i64 LE checkpoint_unix_us  (WAL_V4_NO_CLOCK if no clock)]
755///   [u16 LE snapshot_path_len]
756///   [snapshot_path_bytes]
757/// ```
758///
759/// `payload_len` covers only the payload — keeping the framing
760/// uniform across v3 / v4 record types so torn-write detection in
761/// `replay_wal_into_engine` stays trivial.
762fn encode_v4_checkpoint_marker(
763    checkpoint_lsn: u64,
764    checkpoint_unix_us: i64,
765    snapshot_path: &Path,
766) -> Vec<u8> {
767    let snapshot_bytes = snapshot_path.to_string_lossy().into_owned();
768    let snap_payload = snapshot_bytes.as_bytes();
769    let snap_len_u16: u16 = snap_payload.len().min(u16::MAX as usize) as u16;
770    let mut payload = Vec::with_capacity(8 + 8 + 2 + snap_payload.len());
771    payload.extend_from_slice(&checkpoint_lsn.to_le_bytes());
772    payload.extend_from_slice(&checkpoint_unix_us.to_le_bytes());
773    payload.extend_from_slice(&snap_len_u16.to_le_bytes());
774    payload.extend_from_slice(&snap_payload[..snap_len_u16 as usize]);
775    let mut crc_buf = Vec::with_capacity(1 + payload.len());
776    crc_buf.push(WAL_V4_TYPE_CHECKPOINT_MARKER);
777    crc_buf.extend_from_slice(&payload);
778    let crc = spg_crypto::crc32::crc32(&crc_buf);
779    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
780    let mut out = Vec::with_capacity(4 + 4 + 1 + payload.len());
781    out.extend_from_slice(&header);
782    out.extend_from_slice(&crc.to_le_bytes());
783    out.push(WAL_V4_TYPE_CHECKPOINT_MARKER);
784    out.extend_from_slice(&payload);
785    out
786}
787
788/// v7.18 PITR — encode one v4 `auto_commit_sql` record. Layout:
789///
790/// ```text
791/// [u32 LE (sql_len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
792/// [u32 LE crc32 over (type_byte || lsn || ts || sql_bytes)]
793/// [u8  type = 0x10]
794/// [u64 LE commit_lsn]
795/// [i64 LE commit_unix_us  (= WAL_V4_NO_CLOCK when no ClockFn)]
796/// [sql bytes]
797/// ```
798///
799/// `sql_len` field stays the SQL byte count — same shape as v3 — so
800/// replay-buffer torn-write detection compares against
801/// `WAL_V4_EXTRA_HEADER + sql_len`. v3 records (type 0x01) stay
802/// readable by the same loop with their original 9-byte header
803/// arithmetic.
804fn encode_v4_auto_commit(sql: &str, commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
805    encode_v4_sql_record(WAL_V4_TYPE_AUTO_COMMIT_SQL, sql, commit_lsn, commit_unix_us)
806}
807
808/// v7.21 — same envelope, `WAL_V4_TYPE_TX_COMMIT_SQL` type byte.
809/// `script` = the transaction's statements joined with `";\n"`.
810fn encode_v4_tx_commit(script: &str, commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
811    encode_v4_sql_record(
812        WAL_V4_TYPE_TX_COMMIT_SQL,
813        script,
814        commit_lsn,
815        commit_unix_us,
816    )
817}
818
819fn encode_v4_sql_record(type_byte: u8, sql: &str, commit_lsn: u64, commit_unix_us: i64) -> Vec<u8> {
820    let payload = sql.as_bytes();
821    let mut crc_buf = Vec::with_capacity(1 + WAL_V4_EXTRA_HEADER + payload.len());
822    crc_buf.push(type_byte);
823    crc_buf.extend_from_slice(&commit_lsn.to_le_bytes());
824    crc_buf.extend_from_slice(&commit_unix_us.to_le_bytes());
825    crc_buf.extend_from_slice(payload);
826    let crc = spg_crypto::crc32::crc32(&crc_buf);
827    let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
828    let mut out = Vec::with_capacity(4 + 4 + 1 + WAL_V4_EXTRA_HEADER + payload.len());
829    out.extend_from_slice(&header);
830    out.extend_from_slice(&crc.to_le_bytes());
831    out.push(type_byte);
832    out.extend_from_slice(&commit_lsn.to_le_bytes());
833    out.extend_from_slice(&commit_unix_us.to_le_bytes());
834    out.extend_from_slice(payload);
835    out
836}
837
838/// v7.1 — decode + apply every record in `wal_bytes` to `engine`.
839/// Returns the count of records successfully applied. A truncated
840/// trailing record (mid-write torn) is dropped silently — the
841/// same recovery story `spg-server`'s boot path uses.
842fn replay_wal_into_engine(wal_bytes: &[u8], engine: &mut Engine) -> Result<usize, String> {
843    let mut applied = 0usize;
844    let mut cur = 0usize;
845    while cur < wal_bytes.len() {
846        if wal_bytes.len() - cur < 4 {
847            // Trailing partial header — torn write, drop and stop.
848            break;
849        }
850        let raw_len = u32::from_le_bytes(wal_bytes[cur..cur + 4].try_into().unwrap());
851        let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
852        let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
853        let len_mask = if is_v3 {
854            !(WAL_V2_SENTINEL | WAL_V3_FLAG)
855        } else {
856            !WAL_V2_SENTINEL
857        };
858        let rec_len = (raw_len & len_mask) as usize;
859        let header_len = if is_v3 {
860            9
861        } else if is_v2 {
862            8
863        } else {
864            4
865        };
866        if wal_bytes.len() - cur < header_len + rec_len {
867            // Torn record at the tail — drop, stop.
868            break;
869        }
870        if is_v3 {
871            let type_byte = wal_bytes[cur + 8];
872            match type_byte {
873                WAL_V3_TYPE_AUTO_COMMIT_SQL => {}
874                WAL_V3_TYPE_DURABILITY_CHECKPOINT => {
875                    // durability_checkpoint marker — skip, no SQL.
876                    cur += header_len + rec_len;
877                    continue;
878                }
879                WAL_V4_TYPE_CHECKPOINT_MARKER => {
880                    // v7.18 PITR — checkpoint anchor, skip on replay
881                    // (engine state past this point reflects the
882                    // matching snapshot already loaded by the caller).
883                    cur += header_len + rec_len;
884                    continue;
885                }
886                WAL_V4_TYPE_AUTO_COMMIT_SQL | WAL_V4_TYPE_TX_COMMIT_SQL => {
887                    // v7.18 PITR — v4 record carries 16 bytes of
888                    // (commit_lsn, commit_unix_us) between the type
889                    // byte and the SQL payload. Replay reads them but
890                    // does not enforce them — the engine doesn't
891                    // surface LSN/clock here. Restore tooling
892                    // (spgctl) parses them via parse_wal_record below.
893                    //
894                    // v7.21 — tx-commit records (0x12) carry a whole
895                    // transaction as a `";\n"`-joined script;
896                    // split_statements is a no-op on the single-
897                    // statement auto-commit form.
898                    let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
899                    if wal_bytes.len() - cur < v4_total {
900                        // Torn v4 record at the tail — drop, stop.
901                        break;
902                    }
903                    let sql_start = cur + header_len + WAL_V4_EXTRA_HEADER;
904                    let sql_bytes = &wal_bytes[sql_start..sql_start + rec_len];
905                    let sql = std::str::from_utf8(sql_bytes)
906                        .map_err(|e| format!("WAL replay: non-UTF-8 SQL at offset {cur}: {e}"))?;
907                    for stmt in split_statements(sql) {
908                        engine.execute(stmt).map_err(|e| {
909                            format!("WAL replay: apply {stmt:?} at offset {cur} rejected: {e:?}")
910                        })?;
911                    }
912                    applied += 1;
913                    cur += v4_total;
914                    continue;
915                }
916                other => {
917                    return Err(format!(
918                        "WAL replay: unknown v3 type byte {other:#04x} at offset {cur}"
919                    ));
920                }
921            }
922        }
923        let sql_bytes = &wal_bytes[cur + header_len..cur + header_len + rec_len];
924        let sql = std::str::from_utf8(sql_bytes)
925            .map_err(|e| format!("WAL replay: non-UTF-8 SQL at offset {cur}: {e}"))?;
926        engine
927            .execute(sql)
928            .map_err(|e| format!("WAL replay: apply {sql:?} at offset {cur} rejected: {e:?}"))?;
929        applied += 1;
930        cur += header_len + rec_len;
931    }
932    Ok(applied)
933}
934
935/// v7.18 PITR — parsed WAL record, surfaced for restore / verify
936/// tooling. The replay loop above doesn't expose LSN/timestamp;
937/// `spgctl restore --to <timestamp>` and `spgctl verify` need them.
938/// Returned offsets are byte-positions inside the WAL buffer.
939#[derive(Debug, Clone)]
940pub struct WalRecord<'a> {
941    /// Byte offset in the WAL buffer where this record starts.
942    pub offset: usize,
943    /// Type byte (0x01 = v3 auto-commit, 0x10 = v4 auto-commit,
944    /// 0x02 = durability checkpoint marker).
945    pub type_byte: u8,
946    /// `Some(lsn)` for v4 records, `None` for v3.
947    pub commit_lsn: Option<u64>,
948    /// `Some(unix_us)` for v4 records carrying a clock-set timestamp,
949    /// `None` for v3 or for v4 records explicitly written with
950    /// `WAL_V4_NO_CLOCK` (sentinel for "no ClockFn at commit time").
951    pub commit_unix_us: Option<i64>,
952    /// SQL payload as borrowed bytes. Empty for durability markers.
953    pub sql: &'a [u8],
954}
955
956/// v7.18 PITR — iterate over `wal_bytes` yielding one `WalRecord`
957/// per intact record. Torn-tail records terminate iteration
958/// silently (same recovery story as `replay_wal_into_engine`).
959/// Unknown type bytes inside a v3 envelope return `Err` so the
960/// caller knows the WAL was written by a newer SPG.
961pub fn parse_wal_records(wal_bytes: &[u8]) -> Result<Vec<WalRecord<'_>>, String> {
962    let mut out = Vec::new();
963    let mut cur = 0usize;
964    while cur < wal_bytes.len() {
965        if wal_bytes.len() - cur < 4 {
966            break;
967        }
968        let raw_len = u32::from_le_bytes(wal_bytes[cur..cur + 4].try_into().unwrap());
969        let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
970        let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
971        let len_mask = if is_v3 {
972            !(WAL_V2_SENTINEL | WAL_V3_FLAG)
973        } else {
974            !WAL_V2_SENTINEL
975        };
976        let rec_len = (raw_len & len_mask) as usize;
977        let header_len = if is_v3 {
978            9
979        } else if is_v2 {
980            8
981        } else {
982            4
983        };
984        if wal_bytes.len() - cur < header_len + rec_len {
985            break;
986        }
987        if !is_v3 {
988            // v1 / v2 records carry no type byte; treat as legacy
989            // auto-commit SQL with no LSN/time.
990            let sql = &wal_bytes[cur + header_len..cur + header_len + rec_len];
991            out.push(WalRecord {
992                offset: cur,
993                type_byte: WAL_V3_TYPE_AUTO_COMMIT_SQL,
994                commit_lsn: None,
995                commit_unix_us: None,
996                sql,
997            });
998            cur += header_len + rec_len;
999            continue;
1000        }
1001        let type_byte = wal_bytes[cur + 8];
1002        match type_byte {
1003            WAL_V3_TYPE_AUTO_COMMIT_SQL => {
1004                let sql = &wal_bytes[cur + header_len..cur + header_len + rec_len];
1005                out.push(WalRecord {
1006                    offset: cur,
1007                    type_byte,
1008                    commit_lsn: None,
1009                    commit_unix_us: None,
1010                    sql,
1011                });
1012                cur += header_len + rec_len;
1013            }
1014            WAL_V3_TYPE_DURABILITY_CHECKPOINT => {
1015                out.push(WalRecord {
1016                    offset: cur,
1017                    type_byte,
1018                    commit_lsn: None,
1019                    commit_unix_us: None,
1020                    sql: &[],
1021                });
1022                cur += header_len + rec_len;
1023            }
1024            WAL_V4_TYPE_CHECKPOINT_MARKER => {
1025                // v7.18 PITR — payload = (lsn u64)(ts i64)(path_len u16)(path bytes).
1026                // We surface lsn + ts on the WalRecord; the path lives
1027                // in `sql` since the type byte already disambiguates
1028                // record meaning and adding a dedicated field would
1029                // bloat the iterator return type for every variant.
1030                if rec_len < 18 {
1031                    return Err(format!(
1032                        "WAL parse: checkpoint marker at offset {cur} too short ({rec_len} bytes)"
1033                    ));
1034                }
1035                let lsn = u64::from_le_bytes(
1036                    wal_bytes[cur + header_len..cur + header_len + 8]
1037                        .try_into()
1038                        .unwrap(),
1039                );
1040                let ts_raw = i64::from_le_bytes(
1041                    wal_bytes[cur + header_len + 8..cur + header_len + 16]
1042                        .try_into()
1043                        .unwrap(),
1044                );
1045                let path_len = u16::from_le_bytes(
1046                    wal_bytes[cur + header_len + 16..cur + header_len + 18]
1047                        .try_into()
1048                        .unwrap(),
1049                ) as usize;
1050                if rec_len < 18 + path_len {
1051                    return Err(format!(
1052                        "WAL parse: checkpoint marker at offset {cur} truncated path"
1053                    ));
1054                }
1055                let path_start = cur + header_len + 18;
1056                let path_bytes = &wal_bytes[path_start..path_start + path_len];
1057                let commit_unix_us = if ts_raw == WAL_V4_NO_CLOCK {
1058                    None
1059                } else {
1060                    Some(ts_raw)
1061                };
1062                out.push(WalRecord {
1063                    offset: cur,
1064                    type_byte,
1065                    commit_lsn: Some(lsn),
1066                    commit_unix_us,
1067                    sql: path_bytes,
1068                });
1069                cur += header_len + rec_len;
1070            }
1071            WAL_V4_TYPE_AUTO_COMMIT_SQL | WAL_V4_TYPE_TX_COMMIT_SQL => {
1072                let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
1073                if wal_bytes.len() - cur < v4_total {
1074                    break;
1075                }
1076                let lsn = u64::from_le_bytes(
1077                    wal_bytes[cur + header_len..cur + header_len + 8]
1078                        .try_into()
1079                        .unwrap(),
1080                );
1081                let ts_raw = i64::from_le_bytes(
1082                    wal_bytes[cur + header_len + 8..cur + header_len + 16]
1083                        .try_into()
1084                        .unwrap(),
1085                );
1086                let commit_unix_us = if ts_raw == WAL_V4_NO_CLOCK {
1087                    None
1088                } else {
1089                    Some(ts_raw)
1090                };
1091                let sql_start = cur + header_len + WAL_V4_EXTRA_HEADER;
1092                let sql = &wal_bytes[sql_start..sql_start + rec_len];
1093                out.push(WalRecord {
1094                    offset: cur,
1095                    type_byte,
1096                    commit_lsn: Some(lsn),
1097                    commit_unix_us,
1098                    sql,
1099                });
1100                cur += v4_total;
1101            }
1102            other => {
1103                return Err(format!(
1104                    "WAL parse: unknown type byte {other:#04x} at offset {cur}"
1105                ));
1106            }
1107        }
1108    }
1109    Ok(out)
1110}
1111
1112/// v7.1 — predicate for "should the next `execute()` mutate the
1113/// WAL?" Returns `false` for SELECT / SHOW / EXPLAIN / BEGIN /
1114/// COMMIT / ROLLBACK and the SPG-specific verbs that don't go
1115/// through the auto-commit record path on the server (CHECKPOINT,
1116/// COMPACT). Conservative: anything we don't explicitly know is
1117/// read-only falls through to "write a WAL record".
1118fn sql_is_read_only(sql: &str) -> bool {
1119    let t = sql.trim_start();
1120    let head = t
1121        .split(|c: char| c.is_whitespace() || c == ';' || c == '(')
1122        .next()
1123        .unwrap_or("");
1124    matches!(
1125        head.to_ascii_lowercase().as_str(),
1126        "select"
1127            | "show"
1128            | "explain"
1129            | "begin"
1130            | "commit"
1131            | "rollback"
1132            | "checkpoint"
1133            | "compact"
1134            | "wait"
1135            | "with"
1136    )
1137}
1138
1139/// Embedded SPG database handle. Owns an `Engine` + provides
1140/// ergonomic wrappers around `execute` and `query`. Drops the
1141/// engine on `Drop` — no WAL flush / fsync, because v6.10.3
1142/// is in-memory only.
1143#[derive(Debug)]
1144pub struct Database {
1145    engine: Engine,
1146    /// v7.1 — persistence sidecar. When `Some(p)`, every
1147    /// `execute(sql)` that mutates state appends a v4
1148    /// `auto_commit_sql` WAL record + fsyncs before the call
1149    /// returns; `Drop` writes a final catalog snapshot to
1150    /// `<db_path>` so the next session boots from a clean
1151    /// snapshot + an empty WAL. `None` = in-memory only (the
1152    /// v6.10.3 shape).
1153    persistence: Option<PersistenceCtx>,
1154    /// v7.18 PITR — monotonic per-database commit LSN. Increments
1155    /// before each successful WAL append; bootstrapped at
1156    /// open_path from `max(parse_wal_records → commit_lsn)` so
1157    /// reopen never reuses an LSN. In-memory databases start at
1158    /// 0 and never advance (no WAL = no LSN-meaningful records).
1159    commit_lsn: AtomicU64,
1160    /// v7.21 (round-12 polish) — explicit-transaction WAL buffer.
1161    /// `Some` between an engine-accepted BEGIN and its
1162    /// COMMIT / ROLLBACK on a persistent database. In-transaction
1163    /// mutations only touch the engine's shadow catalog and report
1164    /// `modified_catalog: false`, so the per-statement auto-commit
1165    /// append never fires for them; their bind-final SQL collects
1166    /// here instead and COMMIT flushes the lot as ONE atomic
1167    /// `WAL_V4_TYPE_TX_COMMIT_SQL` record (ROLLBACK just drops it).
1168    /// Always `None` for in-memory databases.
1169    tx_wal: Option<TxWalBuffer>,
1170}
1171
1172/// See [`Database::tx_wal`].
1173#[derive(Debug, Default)]
1174struct TxWalBuffer {
1175    /// Bind-final SQL of every non-read-only statement the engine
1176    /// accepted inside the open transaction, in execution order.
1177    statements: Vec<String>,
1178    /// `(savepoint_name, statements.len() at SAVEPOINT time)` —
1179    /// `ROLLBACK TO SAVEPOINT` truncates `statements` back to the
1180    /// recorded mark so the WAL record matches what the engine
1181    /// keeps. PG name-reuse semantics (latest wins).
1182    savepoints: Vec<(String, usize)>,
1183}
1184
1185/// Statement-level transaction-control classification for the WAL
1186/// buffer. Runs AFTER the engine accepted the statement, so the
1187/// engine stays the single validator — this only mirrors state.
1188enum TxControl {
1189    Begin,
1190    Commit,
1191    Rollback,
1192    RollbackToSavepoint(String),
1193    Savepoint(String),
1194    ReleaseSavepoint,
1195}
1196
1197fn tx_control_kind(sql: &str) -> Option<TxControl> {
1198    let mut words = sql
1199        .split(|c: char| c.is_whitespace() || c == ';')
1200        .filter(|w| !w.is_empty())
1201        .map(str::to_ascii_lowercase);
1202    let head = words.next()?;
1203    match head.as_str() {
1204        "begin" | "start" => Some(TxControl::Begin),
1205        "commit" | "end" => Some(TxControl::Commit),
1206        "savepoint" => words.next().map(TxControl::Savepoint),
1207        "release" => Some(TxControl::ReleaseSavepoint),
1208        "rollback" => match words.next().as_deref() {
1209            // ROLLBACK TO [SAVEPOINT] <name>
1210            Some("to") => {
1211                let next = words.next()?;
1212                let name = if next == "savepoint" {
1213                    words.next()?
1214                } else {
1215                    next
1216                };
1217                Some(TxControl::RollbackToSavepoint(name))
1218            }
1219            _ => Some(TxControl::Rollback),
1220        },
1221        _ => None,
1222    }
1223}
1224
1225#[derive(Debug)]
1226#[allow(dead_code)] // `wal_dir`/`current_chunk_path` are read at boot; kept for Drop/diag introspection.
1227struct PersistenceCtx {
1228    db_path: PathBuf,
1229    /// v7.19 — WAL chunk directory at `<db_path>.wal/`.
1230    /// Replaces the v7.18 single-file `<db_path>.wal` layout.
1231    /// Each chunk file inside is named
1232    /// `<unix_us>_<leading_lsn>.wal` (zero-padded to 16 digits
1233    /// so default-lex sort = LSN order).
1234    wal_dir: PathBuf,
1235    /// Path of the currently-open chunk file inside `wal_dir`.
1236    /// Rotated at checkpoint and whenever the chunk crosses
1237    /// `checkpoint_threshold_bytes`.
1238    current_chunk_path: PathBuf,
1239    /// v7.19 P3 — retention sweeper handle. `Some` when
1240    /// `SPG_PITR_RETENTION_HOURS > 0` at open_path time; `None`
1241    /// when retention is disabled (the default; v7.18 behaviour
1242    /// preserved). The thread polls `wal_dir` every
1243    /// `SPG_PITR_RETENTION_CHECK_SEC` seconds, archives via
1244    /// `SPG_PITR_ARCHIVE_CMD` if set, then deletes chunks older
1245    /// than the retention window. Signalled to exit via
1246    /// `retention_shutdown` on Drop.
1247    retention_shutdown: Option<Arc<AtomicBool>>,
1248    retention_thread: Option<std::thread::JoinHandle<()>>,
1249    /// v7.20 — background WAL flusher for
1250    /// `SPG_SYNCHRONOUS_COMMIT=off`. `None` in the default
1251    /// synchronous mode. Flushes the pending batch every
1252    /// `SPG_WAL_WRITER_DELAY_MS`; signalled + joined on Drop
1253    /// before the final checkpoint so clean shutdown never
1254    /// loses confirmed commits.
1255    flusher_shutdown: Option<Arc<AtomicBool>>,
1256    flusher_thread: Option<std::thread::JoinHandle<()>>,
1257    /// v7.20 P2 — group-commit WAL. Shared with WalTickets
1258    /// returned by the buffered write path so `wait()` can run
1259    /// after the engine write lock is released.
1260    wal: Arc<WalGroup>,
1261    checkpoint_threshold_bytes: u64,
1262    /// v7.1.4 — `<db_path>.spg/segments/` directory. Cold-tier
1263    /// segments produced by `freeze_oldest_to_cold` / compaction
1264    /// are persisted here as `seg_<id>.spg` files; the manifest
1265    /// at `<db_path>.spg/manifest.v10` records every active
1266    /// segment + its CRC32 so the next boot can verify + reload.
1267    cold_segments_dir: PathBuf,
1268    cold_segment_paths: BTreeMap<u32, PathBuf>,
1269    /// v7.17.0 Phase 6.2 — cross-process exclusion lock. Acquired
1270    /// via `fs::create_dir` on `<db_path>.lock` at open_path
1271    /// entry; released on Drop by `fs::remove_dir`. atomic on
1272    /// every supported platform. A second process opening the
1273    /// same path while the first is still alive hits the
1274    /// create_dir failure and returns
1275    /// `EngineError::Unsupported("database is locked by another
1276    /// process: …")`. Stale locks (process crashed mid-session)
1277    /// must be cleared via `Database::force_unlock(path)` —
1278    /// SPG can't safely fingerprint who owned a stale directory
1279    /// without a libc dep, which would violate spg-embedded's
1280    /// zero-deps charter.
1281    lock_path: PathBuf,
1282}
1283
1284impl Database {
1285    /// Open a fresh in-memory database. No WAL, no catalog
1286    /// snapshot on disk — perfect for tests + short-lived
1287    /// CLI tools.
1288    #[must_use]
1289    pub fn open_in_memory() -> Self {
1290        Self {
1291            engine: Engine::new().with_clock(wall_clock_micros),
1292            persistence: None,
1293            commit_lsn: AtomicU64::new(0),
1294            tx_wal: None,
1295        }
1296    }
1297
1298    /// v7.1 — Open or create a persistent database backed by
1299    /// the file at `db_path`. The WAL lives at `db_path` +
1300    /// ".wal" (e.g. `./data/spg.db` → `./data/spg.db.wal`). Boot
1301    /// path:
1302    ///
1303    /// 1. If `db_path` exists, restore the catalog snapshot.
1304    /// 2. If the WAL exists, replay every record into the
1305    ///    restored engine — the same recovery story
1306    ///    `spg-server` uses.
1307    /// 3. Open the WAL in append+sync mode so subsequent
1308    ///    `execute()` writes durably commit (one fsync per
1309    ///    mutation).
1310    ///
1311    /// `Drop` writes a final catalog snapshot + truncates the
1312    /// WAL — operators that need a sync barrier at a specific
1313    /// point use `checkpoint()` explicitly.
1314    pub fn open_path(db_path: impl AsRef<Path>) -> Result<Self, EngineError> {
1315        let db_path = db_path.as_ref().to_path_buf();
1316        // v7.19 — WAL is a directory of chunk files. Legacy
1317        // single-file path stays variable-named `wal_path` for
1318        // the backward-compat migration block below.
1319        let wal_path = {
1320            let mut p = db_path.clone();
1321            let name = p
1322                .file_name()
1323                .map(|n| {
1324                    let mut s = n.to_os_string();
1325                    s.push(".wal");
1326                    s
1327                })
1328                .unwrap_or_else(|| std::ffi::OsString::from(".wal"));
1329            p.set_file_name(name);
1330            p
1331        };
1332        let wal_dir = wal_path.clone();
1333        if let Some(parent) = db_path.parent()
1334            && !parent.as_os_str().is_empty()
1335        {
1336            std::fs::create_dir_all(parent).map_err(io_err)?;
1337        }
1338        // v7.17.0 Phase 6.2 — acquire cross-process exclusion
1339        // lock before touching any catalog / WAL bytes. atomic
1340        // mkdir on every supported platform; a second process
1341        // opening the same path while the first is still alive
1342        // hits the create_dir failure and gets a clear error.
1343        let lock_path = {
1344            let mut p = db_path.clone();
1345            let name = p
1346                .file_name()
1347                .map(|n| {
1348                    let mut s = n.to_os_string();
1349                    s.push(".lock");
1350                    s
1351                })
1352                .unwrap_or_else(|| std::ffi::OsString::from(".lock"));
1353            p.set_file_name(name);
1354            p
1355        };
1356        acquire_path_lock(&lock_path)?;
1357        let mut engine = if db_path.exists() {
1358            let bytes = std::fs::read(&db_path).map_err(io_err)?;
1359            let engine = Engine::restore_envelope(&bytes).map_err(|e| {
1360                EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
1361                    "restore from {}: {e}",
1362                    db_path.display()
1363                )))
1364            })?;
1365            engine.with_clock(wall_clock_micros)
1366        } else {
1367            Engine::new().with_clock(wall_clock_micros)
1368        };
1369        // v7.1.4 — manifest-driven cold-segment reload. The
1370        // manifest sidecar pairs the catalog snapshot CRC with a
1371        // list of `(segment_id, path, crc32)` triples; verify
1372        // before loading so a torn or stale manifest doesn't
1373        // surface phantom data.
1374        let cold_segments_dir = {
1375            let parent = db_path.parent().unwrap_or_else(|| Path::new("."));
1376            let stem = db_path
1377                .file_stem()
1378                .unwrap_or_else(|| std::ffi::OsStr::new("db"))
1379                .to_string_lossy()
1380                .into_owned();
1381            parent.join(format!("{stem}.spg")).join("segments")
1382        };
1383        let mut cold_segment_paths: BTreeMap<u32, PathBuf> = BTreeMap::new();
1384        let manifest_pth = spg_manifest_path(&db_path);
1385        if manifest_pth.exists() && db_path.exists() {
1386            let m_bytes = std::fs::read(&manifest_pth).map_err(io_err)?;
1387            if let Ok(m) = CatalogManifest::deserialize(&m_bytes) {
1388                let snap_bytes = std::fs::read(&db_path).map_err(io_err)?;
1389                let snap_crc = spg_crypto::crc32::crc32(&snap_bytes);
1390                if snap_crc == m.catalog_crc32 {
1391                    for entry in &m.cold_segments {
1392                        if let Ok(seg_bytes) = std::fs::read(&entry.path) {
1393                            let computed = spg_crypto::crc32::crc32(&seg_bytes);
1394                            if computed != entry.crc32 {
1395                                eprintln!(
1396                                    "spg-embedded: manifest skip segment {}: CRC mismatch",
1397                                    entry.segment_id
1398                                );
1399                                continue;
1400                            }
1401                            if engine.catalog().cold_segment(entry.segment_id).is_some() {
1402                                // Already loaded via Catalog::clone path (shouldn't happen
1403                                // since Engine::new + restore_envelope don't populate cold).
1404                                continue;
1405                            }
1406                            let mut new_cat = engine.catalog().clone();
1407                            if let Err(e) =
1408                                new_cat.load_segment_bytes_at(entry.segment_id, seg_bytes)
1409                            {
1410                                eprintln!(
1411                                    "spg-embedded: manifest load segment {} failed: {e}",
1412                                    entry.segment_id
1413                                );
1414                                continue;
1415                            }
1416                            engine.replace_catalog(new_cat);
1417                            cold_segment_paths.insert(entry.segment_id, entry.path.clone());
1418                        } else {
1419                            eprintln!(
1420                                "spg-embedded: manifest skip segment {}: file unreadable",
1421                                entry.segment_id
1422                            );
1423                        }
1424                    }
1425                }
1426            }
1427        }
1428        // v7.19 — chunked WAL on-disk layout.
1429        //
1430        // Three cases handled here:
1431        //
1432        // 1. wal_dir exists as a DIRECTORY → scan its
1433        //    `<unix_us>_<leading_lsn>.wal` chunks (sorted
1434        //    lexicographically = chunk-creation order), replay
1435        //    them in sequence, advance the LSN watermark to the
1436        //    max commit_lsn seen.
1437        //
1438        // 2. wal_path exists as a FILE → legacy v7.18 layout.
1439        //    Migrate it: create `wal_dir/`, move the single file
1440        //    inside as `0000000000000000_0000000000000000.wal`,
1441        //    then fall through to case 1's replay loop.
1442        //
1443        // 3. Neither exists → fresh database; create wal_dir.
1444        let mut initial_lsn: u64 = 0;
1445        if wal_path.is_file() {
1446            // Case 2: legacy single-file WAL migration.
1447            let legacy_bytes = std::fs::read(&wal_path).map_err(io_err)?;
1448            std::fs::remove_file(&wal_path).map_err(io_err)?;
1449            std::fs::create_dir_all(&wal_dir).map_err(io_err)?;
1450            if !legacy_bytes.is_empty() {
1451                let migrated = wal_dir.join(legacy_chunk_filename());
1452                std::fs::write(&migrated, &legacy_bytes).map_err(io_err)?;
1453            }
1454        } else if !wal_dir.exists() {
1455            // Case 3: fresh database.
1456            std::fs::create_dir_all(&wal_dir).map_err(io_err)?;
1457        }
1458        // Cases 1 + 2 share replay logic now that wal_dir is
1459        // guaranteed to exist (and may be empty for case 3).
1460        //
1461        // Two-pass replay so we don't double-apply records the
1462        // snapshot already reflects:
1463        //
1464        // 1. Find the highest commit_lsn carried by a
1465        //    checkpoint_marker across all chunks. That LSN is the
1466        //    snapshot's high-water mark — anything ≤ it is
1467        //    already in `<db_path>` and replaying it would
1468        //    DuplicateTable / double-insert.
1469        // 2. Replay only records strictly above that LSN.
1470        //
1471        // Case 2 migration (legacy single-file WAL) lands here
1472        // too: the migrated chunk has no marker so the LSN floor
1473        // is 0 and every record applies — exactly the v7.18
1474        // behaviour the migration is supposed to preserve.
1475        let chunk_paths = sorted_wal_chunks(&wal_dir).map_err(io_err)?;
1476        let mut snapshot_lsn: u64 = 0;
1477        for chunk in &chunk_paths {
1478            let bytes = std::fs::read(chunk).map_err(io_err)?;
1479            if let Ok(records) = parse_wal_records(&bytes) {
1480                for r in &records {
1481                    if r.type_byte == WAL_V4_TYPE_CHECKPOINT_MARKER {
1482                        if let Some(l) = r.commit_lsn {
1483                            if l > snapshot_lsn {
1484                                snapshot_lsn = l;
1485                            }
1486                        }
1487                    }
1488                }
1489            }
1490        }
1491        let mut quarantined: Vec<QuarantinedStmt> = Vec::new();
1492        for chunk in &chunk_paths {
1493            let bytes = std::fs::read(chunk).map_err(io_err)?;
1494            if bytes.is_empty() {
1495                continue;
1496            }
1497            replay_wal_filtered(&bytes, &mut engine, snapshot_lsn, &mut quarantined)
1498                .map_err(|m| EngineError::Storage(spg_storage::StorageError::Corrupt(m)))?;
1499            if let Ok(records) = parse_wal_records(&bytes) {
1500                if let Some(max) = records.iter().filter_map(|r| r.commit_lsn).max() {
1501                    if max > initial_lsn {
1502                        initial_lsn = max;
1503                    }
1504                }
1505            }
1506        }
1507        // v7.30.1 (mailrs round-24 ask 2) — replay rejects no longer
1508        // brick the open. Persist the rejected statements beside the
1509        // WAL chunks for forensics and say so loudly; the boot
1510        // continues with every other record applied.
1511        if !quarantined.is_empty() {
1512            let mut body = String::new();
1513            for q in &quarantined {
1514                body.push_str(&format_quarantine_line(q));
1515            }
1516            let qpath = wal_dir.join(format!(
1517                "quarantine-{:016x}.log",
1518                wall_clock_micros().max(0) as u64
1519            ));
1520            match std::fs::write(&qpath, &body) {
1521                Ok(()) => eprintln!(
1522                    "spg-embedded: WAL replay quarantined {} statement(s) — boot continues; \
1523                     forensics at {}",
1524                    quarantined.len(),
1525                    qpath.display()
1526                ),
1527                Err(e) => eprintln!(
1528                    "spg-embedded: WAL replay quarantined {} statement(s) — boot continues; \
1529                     quarantine file write FAILED ({e}), entries follow:\n{body}",
1530                    quarantined.len()
1531                ),
1532            }
1533        }
1534        // Open the "current" chunk — either the last existing
1535        // chunk file (so subsequent appends extend it until the
1536        // size threshold rotates) or a fresh first chunk.
1537        let now_us = wall_clock_micros();
1538        let current_chunk_path = if let Some(last) = chunk_paths.last() {
1539            last.clone()
1540        } else {
1541            wal_dir.join(chunk_filename(now_us, initial_lsn + 1))
1542        };
1543        let wal_file = OpenOptions::new()
1544            .create(true)
1545            .append(true)
1546            .read(true)
1547            .open(&current_chunk_path)
1548            .map_err(io_err)?;
1549        let wal_len = wal_file.metadata().map_err(io_err)?.len();
1550        let wal = Arc::new(WalGroup::new(wal_file, wal_len));
1551        // v7.19 P3 — spawn retention sweep thread when the
1552        // operator opted in via SPG_PITR_RETENTION_HOURS > 0.
1553        // Otherwise stay on the v7.18 behaviour (chunks accumulate
1554        // until something else — backup-pitr archival, manual
1555        // cleanup — moves them).
1556        let retention_hours = pitr_retention_hours();
1557        let (retention_shutdown, retention_thread) = if retention_hours > 0 {
1558            let shutdown = Arc::new(AtomicBool::new(false));
1559            let shutdown_clone = Arc::clone(&shutdown);
1560            let wal_dir_clone = wal_dir.clone();
1561            let check_interval = std::time::Duration::from_secs(pitr_retention_check_sec());
1562            let archive_cmd = pitr_archive_cmd();
1563            let handle = std::thread::Builder::new()
1564                .name("spg-pitr-retention".into())
1565                .spawn(move || {
1566                    retention_sweep_loop(
1567                        wal_dir_clone,
1568                        retention_hours,
1569                        check_interval,
1570                        archive_cmd,
1571                        shutdown_clone,
1572                    );
1573                })
1574                .map_err(io_err)?;
1575            (Some(shutdown), Some(handle))
1576        } else {
1577            (None, None)
1578        };
1579        // v7.20 — background flusher for SPG_SYNCHRONOUS_COMMIT=off.
1580        let (flusher_shutdown, flusher_thread) = if synchronous_commit_on() {
1581            (None, None)
1582        } else {
1583            let shutdown = Arc::new(AtomicBool::new(false));
1584            let shutdown_clone = Arc::clone(&shutdown);
1585            let group = Arc::clone(&wal);
1586            let interval = std::time::Duration::from_millis(wal_writer_delay_ms());
1587            let handle = std::thread::Builder::new()
1588                .name("spg-wal-flusher".into())
1589                .spawn(move || {
1590                    while !shutdown_clone.load(Ordering::SeqCst) {
1591                        std::thread::sleep(interval);
1592                        if let Err(e) = group.flush_now() {
1593                            eprintln!("spg-embedded: background WAL flush failed: {e:?}");
1594                        }
1595                    }
1596                    // Final drain on shutdown signal.
1597                    let _ = group.flush_now();
1598                })
1599                .map_err(io_err)?;
1600            (Some(shutdown), Some(handle))
1601        };
1602        Ok(Self {
1603            engine,
1604            commit_lsn: AtomicU64::new(initial_lsn),
1605            tx_wal: None,
1606            persistence: Some(PersistenceCtx {
1607                db_path,
1608                wal_dir,
1609                current_chunk_path,
1610                wal,
1611                checkpoint_threshold_bytes: default_checkpoint_threshold_bytes(),
1612                cold_segments_dir,
1613                cold_segment_paths,
1614                lock_path,
1615                retention_shutdown,
1616                retention_thread,
1617                flusher_shutdown,
1618                flusher_thread,
1619            }),
1620        })
1621    }
1622
1623    /// v7.1.4 — freeze the oldest `max_rows` of `table_name`'s
1624    /// hot tier into a brand-new cold-tier segment + persist
1625    /// it to disk. Same semantics as `spg-server`'s freezer
1626    /// thread; embedded just runs the freeze synchronously on
1627    /// the caller's thread. Persistence + manifest update
1628    /// happen as part of the next `checkpoint()` (or on Drop).
1629    pub fn freeze_oldest_to_cold(
1630        &mut self,
1631        table_name: &str,
1632        index_name: &str,
1633        max_rows: usize,
1634    ) -> Result<spg_storage::FreezeReport, EngineError> {
1635        let report = self
1636            .engine
1637            .freeze_oldest_to_cold(table_name, index_name, max_rows)?;
1638        if let Some(p) = &mut self.persistence {
1639            std::fs::create_dir_all(&p.cold_segments_dir).map_err(io_err)?;
1640            let final_path = p
1641                .cold_segments_dir
1642                .join(format!("seg_{}.spg", report.segment_id));
1643            let tmp_path = p
1644                .cold_segments_dir
1645                .join(format!("seg_{}.spg.tmp", report.segment_id));
1646            std::fs::write(&tmp_path, &report.segment_bytes).map_err(io_err)?;
1647            std::fs::rename(&tmp_path, &final_path).map_err(io_err)?;
1648            p.cold_segment_paths.insert(report.segment_id, final_path);
1649        }
1650        Ok(report)
1651    }
1652
1653    /// v7.1 — override the auto-checkpoint WAL-size ceiling for
1654    /// this `Database` instance. Default is
1655    /// `SPG_EMBEDDED_CHECKPOINT_BYTES` env (4 MiB if unset); the
1656    /// setter wins. No-op when the database is in-memory.
1657    pub fn set_checkpoint_threshold_bytes(&mut self, bytes: u64) {
1658        if let Some(p) = &mut self.persistence {
1659            p.checkpoint_threshold_bytes = bytes.max(1);
1660        }
1661    }
1662
1663    /// v7.1 — flush a fresh catalog snapshot to `db_path` and
1664    /// truncate the WAL. Idempotent; cheap when nothing has
1665    /// happened since the last checkpoint. No-op when the
1666    /// database is in-memory (no `db_path` configured).
1667    ///
1668    /// Called automatically when:
1669    /// - the WAL grows past
1670    ///   `SPG_EMBEDDED_CHECKPOINT_BYTES` (default 4 MiB) at the
1671    ///   end of an `execute()`, and
1672    /// - `Drop` runs (best-effort; checkpoint failure on drop is
1673    ///   logged to stderr).
1674    pub fn checkpoint(&mut self) -> Result<(), EngineError> {
1675        let snapshot = self.engine.snapshot();
1676        let Some(p) = &mut self.persistence else {
1677            return Ok(());
1678        };
1679        // Snapshot first (atomic via tmp+rename), then WAL
1680        // truncate. Same order as `spg-server`'s CHECKPOINT —
1681        // a crash between the two leaves the WAL holding
1682        // already-snapshotted ops, which replay cleanly on the
1683        // next boot (idempotent for SPG's standard DDL/DML
1684        // mutations).
1685        let tmp = {
1686            let mut t = p.db_path.clone();
1687            let mut name = t
1688                .file_name()
1689                .map(std::ffi::OsStr::to_os_string)
1690                .unwrap_or_default();
1691            name.push(".tmp");
1692            t.set_file_name(name);
1693            t
1694        };
1695        std::fs::write(&tmp, &snapshot).map_err(io_err)?;
1696        std::fs::rename(&tmp, &p.db_path).map_err(io_err)?;
1697        // v7.1.4 — refresh the manifest so the next boot can
1698        // reload cold segments alongside the snapshot. Bytes
1699        // come from the freshly-written snapshot file (= the
1700        // canonical CRC source).
1701        if !p.cold_segment_paths.is_empty() {
1702            let snap_crc = spg_crypto::crc32::crc32(&snapshot);
1703            let entries: Vec<ColdSegmentEntry> = p
1704                .cold_segment_paths
1705                .iter()
1706                .filter_map(|(&segment_id, path)| {
1707                    let bytes = std::fs::read(path).ok()?;
1708                    Some(ColdSegmentEntry {
1709                        segment_id,
1710                        path: path.clone(),
1711                        crc32: spg_crypto::crc32::crc32(&bytes),
1712                    })
1713                })
1714                .collect();
1715            let manifest = CatalogManifest {
1716                catalog_crc32: snap_crc,
1717                cold_segments: entries,
1718                wal_baseline_offset: 0,
1719            };
1720            let m_bytes = manifest.serialize();
1721            let m_path = spg_manifest_path(&p.db_path);
1722            if let Some(dir) = m_path.parent() {
1723                std::fs::create_dir_all(dir).map_err(io_err)?;
1724            }
1725            let m_tmp = {
1726                let mut t = m_path.clone();
1727                let mut name = t
1728                    .file_name()
1729                    .map(std::ffi::OsStr::to_os_string)
1730                    .unwrap_or_default();
1731                name.push(".tmp");
1732                t.set_file_name(name);
1733                t
1734            };
1735            std::fs::write(&m_tmp, &m_bytes).map_err(io_err)?;
1736            std::fs::rename(&m_tmp, &m_path).map_err(io_err)?;
1737        }
1738        // v7.19 — append a checkpoint marker to the current chunk
1739        // (anchors restore-to-time backups), then rotate to a
1740        // fresh chunk file. Old chunks stay on disk and become
1741        // input to the retention thread (P3) + spgctl backup-pitr
1742        // (P6). The single-file `set_len(0)` truncate the v7.18
1743        // path used is gone — that path silently discarded WAL
1744        // history between checkpoint and the operator's next cron
1745        // run, which is exactly what PITR was meant to fix.
1746        let marker_lsn = self.commit_lsn.load(Ordering::SeqCst);
1747        let marker_ts = wall_clock_micros();
1748        let marker = encode_v4_checkpoint_marker(marker_lsn, marker_ts, &p.db_path);
1749        // v7.20 P2 — checkpoint holds &mut self (engine
1750        // exclusive), so there are no concurrent enqueues: drain
1751        // the pending batch, append the marker, flush, then
1752        // rotate the chunk handle inside the group.
1753        p.wal.enqueue(&marker);
1754        p.wal.flush_now()?;
1755        let new_chunk_path = p.wal_dir.join(chunk_filename(marker_ts, marker_lsn + 1));
1756        let new_handle = OpenOptions::new()
1757            .create(true)
1758            .append(true)
1759            .read(true)
1760            .open(&new_chunk_path)
1761            .map_err(io_err)?;
1762        p.current_chunk_path = new_chunk_path;
1763        p.wal.rotate_file(new_handle);
1764        Ok(())
1765    }
1766
1767    /// Restore a database from a previously-captured catalog
1768    /// snapshot. Pairs with `Database::snapshot()` for
1769    /// round-tripping in-memory state without going through
1770    /// the `spg-server` WAL.
1771    pub fn restore(snapshot: &[u8]) -> Result<Self, EngineError> {
1772        let engine = Engine::restore_envelope(snapshot).map_err(|e| {
1773            EngineError::Storage(spg_storage::StorageError::Corrupt(format!("restore: {e}")))
1774        })?;
1775        Ok(Self {
1776            engine,
1777            persistence: None,
1778            commit_lsn: AtomicU64::new(0),
1779            tx_wal: None,
1780        })
1781    }
1782
1783    /// Take a catalog snapshot suitable for `Database::restore`.
1784    /// The bytes are SPG's canonical catalog envelope (FILE_MAGIC
1785    /// + version + payload); round-trips through every released
1786    /// SPG version per the STABILITY contract.
1787    #[must_use]
1788    pub fn snapshot(&self) -> Vec<u8> {
1789        self.engine.snapshot()
1790    }
1791
1792    /// Execute a SQL statement and return the engine's
1793    /// `QueryResult` verbatim. Pass-through for callers that
1794    /// want to keep PG-flavoured column/row metadata.
1795    ///
1796    /// v7.1 — when the database was opened via `open_path`,
1797    /// successful mutations are appended to the WAL + fsynced
1798    /// before the call returns. A subsequent process crash will
1799    /// recover state up to the last successful return from
1800    /// `execute()`. Read-only statements (SELECT / SHOW /
1801    /// EXPLAIN / BEGIN-COMMIT-ROLLBACK / CHECKPOINT / COMPACT
1802    /// etc.) skip the WAL entirely.
1803    pub fn execute(&mut self, sql: &str) -> Result<QueryResult, EngineError> {
1804        // v7.20 P2 — single-caller convenience over the buffered
1805        // path: enqueue + immediately wait. Batch size is 1 here,
1806        // so the durability behaviour (one fsync before Ok) is
1807        // identical to v7.19. Concurrent callers go through
1808        // `execute_buffered` (AsyncDatabase does) and share the
1809        // leader's fsync.
1810        let (result, ticket) = self.execute_buffered(sql)?;
1811        if let Some(t) = ticket {
1812            t.wait()?;
1813        }
1814        Ok(result)
1815    }
1816
1817    /// v7.20 P2 — group-commit write entry. Runs the engine
1818    /// mutation + encodes/enqueues the WAL record, then RETURNS
1819    /// WITHOUT waiting for the fsync. The caller must call
1820    /// [`WalTicket::wait`] before treating the write as durable
1821    /// — crucially, the caller can (and should) drop whatever
1822    /// lock guards this `Database` first, so the next writer's
1823    /// mutation overlaps this batch's fsync.
1824    ///
1825    /// `None` ticket = nothing hit the WAL (read-only statement,
1826    /// no-op DDL, or in-memory database) — the result is final
1827    /// as returned.
1828    ///
1829    /// # Errors
1830    /// Engine errors propagate unchanged. Auto-checkpoint (when
1831    /// the active chunk crosses the threshold) runs inline and
1832    /// may surface IO errors.
1833    pub fn execute_buffered(
1834        &mut self,
1835        sql: &str,
1836    ) -> Result<(QueryResult, Option<WalTicket>), EngineError> {
1837        let result = self.engine.execute(sql)?;
1838        let modified = matches!(
1839            &result,
1840            QueryResult::CommandOk {
1841                modified_catalog: true,
1842                ..
1843            }
1844        );
1845        let ticket = self.wal_after_ok(sql, modified)?;
1846        Ok((result, ticket))
1847    }
1848
1849    /// v7.21 (round-12 polish) — post-engine WAL bookkeeping shared
1850    /// by the simple ([`Self::execute_buffered`]) and prepared
1851    /// ([`Self::execute_prepared_buffered`]) write paths. `canonical`
1852    /// is the replay text (bind-final for prepared statements);
1853    /// `modified_catalog` comes from the engine result. Three routes:
1854    ///
1855    /// - transaction control → maintain [`Self::tx_wal`]: BEGIN opens
1856    ///   the buffer, COMMIT flushes it as ONE atomic
1857    ///   `WAL_V4_TYPE_TX_COMMIT_SQL` record, ROLLBACK drops it,
1858    ///   SAVEPOINT / ROLLBACK TO mark / truncate it. The engine has
1859    ///   already accepted the statement, so this only mirrors state.
1860    /// - inside an open transaction → buffer the statement (shadow-
1861    ///   catalog mutations report `modified_catalog: false`, so the
1862    ///   auto-commit arm below can't see them).
1863    /// - auto-commit mutation → classic per-statement v4 record.
1864    ///
1865    /// v7.18 PITR — v4 records carry commit LSN + wall-clock micros.
1866    /// The crash window remains one BATCH: replay re-applies
1867    /// idempotently exactly as before, and a torn batch tail drops
1868    /// cleanly (same torn-write handling).
1869    fn wal_after_ok(
1870        &mut self,
1871        canonical: &str,
1872        modified_catalog: bool,
1873    ) -> Result<Option<WalTicket>, EngineError> {
1874        if self.persistence.is_none() {
1875            return Ok(None);
1876        }
1877        let mut record = None;
1878        match tx_control_kind(canonical) {
1879            Some(TxControl::Begin) => {
1880                self.tx_wal = Some(TxWalBuffer::default());
1881            }
1882            Some(TxControl::Commit) => {
1883                if let Some(buf) = self.tx_wal.take()
1884                    && !buf.statements.is_empty()
1885                {
1886                    let script = buf.statements.join(";\n");
1887                    let lsn = self.commit_lsn.fetch_add(1, Ordering::SeqCst) + 1;
1888                    record = Some(encode_v4_tx_commit(&script, lsn, wall_clock_micros()));
1889                }
1890            }
1891            Some(TxControl::Rollback) => {
1892                self.tx_wal = None;
1893            }
1894            Some(TxControl::Savepoint(name)) => {
1895                if let Some(buf) = &mut self.tx_wal {
1896                    // PG name-reuse semantics: latest mark wins.
1897                    buf.savepoints.retain(|(n, _)| n != &name);
1898                    let mark = buf.statements.len();
1899                    buf.savepoints.push((name, mark));
1900                }
1901            }
1902            Some(TxControl::RollbackToSavepoint(name)) => {
1903                if let Some(buf) = &mut self.tx_wal
1904                    && let Some(pos) = buf.savepoints.iter().position(|(n, _)| n == &name)
1905                {
1906                    let mark = buf.savepoints[pos].1;
1907                    buf.statements.truncate(mark);
1908                    // Later savepoints die with the rollback; the
1909                    // target itself survives (PG keeps it
1910                    // re-rollbackable).
1911                    buf.savepoints.truncate(pos + 1);
1912                }
1913            }
1914            Some(TxControl::ReleaseSavepoint) => {
1915                // RELEASE folds the savepoint into the enclosing tx —
1916                // buffered statements stay. The mark also stays:
1917                // marks are only consulted by ROLLBACK TO, which the
1918                // engine validates first, so a dangling mark is
1919                // unreachable.
1920            }
1921            None => {
1922                if let Some(buf) = &mut self.tx_wal {
1923                    if !sql_is_read_only(canonical) {
1924                        buf.statements.push(canonical.to_string());
1925                    }
1926                } else if modified_catalog && !sql_is_read_only(canonical) {
1927                    let lsn = self.commit_lsn.fetch_add(1, Ordering::SeqCst) + 1;
1928                    record = Some(encode_v4_auto_commit(canonical, lsn, wall_clock_micros()));
1929                }
1930            }
1931        }
1932        let mut ticket = None;
1933        if let Some(record) = record {
1934            let p = self.persistence.as_mut().expect("checked above");
1935            let seq = p.wal.enqueue(&record);
1936            ticket = Some(WalTicket {
1937                group: Arc::clone(&p.wal),
1938                seq,
1939            });
1940            if p.wal.written_len() >= p.checkpoint_threshold_bytes {
1941                self.checkpoint()?;
1942            }
1943        }
1944        Ok(ticket)
1945    }
1946
1947    /// v7.3.0 — typed-row variant of [`Database::query`]. Each
1948    /// row decodes into a `T: FromSpgRow` so callers don't
1949    /// pattern-match on `Value` themselves. Use [`spg_row!`] to
1950    /// generate the impl, or write it by hand.
1951    pub fn query_typed<T: FromSpgRow>(&mut self, sql: &str) -> Result<Vec<T>, EngineError> {
1952        let rows = self.query(sql)?;
1953        rows.into_iter().map(|r| T::from_spg_row(&r)).collect()
1954    }
1955
1956    /// Run a SELECT and return rows as a `Vec<Vec<Value>>` —
1957    /// strips the column-schema metadata for read-side
1958    /// ergonomics. Errors on non-Rows results (DML / DDL
1959    /// statements should go through `execute` instead).
1960    pub fn query(&mut self, sql: &str) -> Result<Vec<Vec<Value>>, EngineError> {
1961        match self.engine.execute(sql)? {
1962            QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
1963            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
1964                "query() expects a SELECT — use execute() for DML/DDL".into(),
1965            )),
1966            // v7.5.0 — QueryResult is #[non_exhaustive]; any future
1967            // variant is not a SELECT row stream, treat as Unsupported.
1968            _ => Err(EngineError::Unsupported(
1969                "query() expects a SELECT — use execute() for DML/DDL".into(),
1970            )),
1971        }
1972    }
1973
1974    /// v7.16.0 — column-aware variant of [`Self::query`].
1975    /// Returns the column schema vec alongside the rows so
1976    /// adapters (the spg-sqlx Row impl most notably) can drive
1977    /// name + type-based column lookups. Errors on non-Rows
1978    /// results identically to `query`.
1979    pub fn query_with_columns(
1980        &mut self,
1981        sql: &str,
1982    ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value>>), EngineError> {
1983        match self.engine.execute(sql)? {
1984            QueryResult::Rows { columns, rows } => {
1985                Ok((columns, rows.into_iter().map(|r| r.values).collect()))
1986            }
1987            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
1988                "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
1989            )),
1990            _ => Err(EngineError::Unsupported(
1991                "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
1992            )),
1993        }
1994    }
1995
1996    /// v7.16.0 — column-aware variant of
1997    /// [`Self::query_prepared`]. Same shape as
1998    /// `query_with_columns` but driven from a prepared
1999    /// statement + bound params.
2000    pub fn query_prepared_with_columns(
2001        &mut self,
2002        stmt: &Statement,
2003        params: &[Value],
2004    ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value>>), EngineError> {
2005        match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
2006            QueryResult::Rows { columns, rows } => {
2007                Ok((columns, rows.into_iter().map(|r| r.values).collect()))
2008            }
2009            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2010                "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2011            )),
2012            _ => Err(EngineError::Unsupported(
2013                "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2014            )),
2015        }
2016    }
2017
2018    /// Borrow the underlying engine. Escape hatch for callers
2019    /// that need access to `spg-engine` APIs not yet surfaced
2020    /// here (transactions, EXPLAIN ANALYZE, etc.).
2021    #[must_use]
2022    pub const fn engine(&self) -> &Engine {
2023        &self.engine
2024    }
2025
2026    /// Mutable borrow of the underlying engine. Same intent as
2027    /// `engine()` but for write-side APIs (e.g. inserting
2028    /// directly through `Catalog::insert` for high-throughput
2029    /// bulk loads that bypass SQL parsing).
2030    pub const fn engine_mut(&mut self) -> &mut Engine {
2031        &mut self.engine
2032    }
2033
2034    /// v7.16.0 — parse + plan a SQL string ONCE so subsequent
2035    /// `execute_prepared` / `query_prepared` calls can re-bind
2036    /// parameters without re-parsing. The returned [`Statement`]
2037    /// is a thin handle around the AST + cached source SQL; it's
2038    /// `Clone` so the same plan can drive many bind calls
2039    /// concurrently (each call clones the AST and runs
2040    /// placeholder substitution on the clone — the cached
2041    /// plan stays intact).
2042    ///
2043    /// Plan caching follows the engine's existing version-aware
2044    /// rule: a prepared `Statement` whose statistics version
2045    /// has rolled (ANALYZE ran between prepare and execute)
2046    /// will silently re-prepare under the hood. Callers don't
2047    /// need to detect this.
2048    ///
2049    /// Placeholders in the SQL use PG's `$1`, `$2`, … convention.
2050    /// `bind`-time `Value`s are passed as a slice; arity
2051    /// mismatches surface as `EvalError::PlaceholderOutOfRange`
2052    /// at `execute_prepared` time, not here.
2053    ///
2054    /// # Errors
2055    /// Surfaces `EngineError` (parse error / plan rewrite
2056    /// failure) from the underlying `Engine::prepare`.
2057    pub fn prepare(&mut self, sql: &str) -> Result<Statement, EngineError> {
2058        // Use the cached path so repeated prepares of the same
2059        // SQL are O(1). The engine's plan cache stays shared
2060        // across all callers of this Database — a single
2061        // `PgPool`-shaped consumer (or, later, the spg-sqlx
2062        // adapter) prepares once and reaps the win on every bind.
2063        let stmt = self
2064            .engine
2065            .prepare_cached(sql)
2066            .map_err(EngineError::Parse)?;
2067        Ok(Statement {
2068            stmt,
2069            sql: sql.to_string(),
2070        })
2071    }
2072
2073    /// v7.17.0 Phase 3.P0-66 — describe a SQL string without
2074    /// executing. Returns `(parameter_oid_count, output_columns)`
2075    /// where `output_columns` is empty for non-SELECT statements
2076    /// or for SELECT shapes the describe planner can't resolve
2077    /// (JOIN / subquery / unknown table). Wraps
2078    /// `Engine::describe_prepared` so the spg-sqlx bridge can
2079    /// surface PG-shape Describe replies for
2080    /// `sqlx::query!()` compile-time validation.
2081    ///
2082    /// # Errors
2083    /// Propagates parse errors from the underlying prepare path.
2084    pub fn describe(&mut self, sql: &str) -> Result<(Vec<u32>, Vec<ColumnSchema>), EngineError> {
2085        let stmt = self
2086            .engine
2087            .prepare_cached(sql)
2088            .map_err(EngineError::Parse)?;
2089        Ok(self.engine.describe_prepared(&stmt))
2090    }
2091
2092    /// v7.16.0 — execute a prepared statement with bound
2093    /// parameters. Mirrors `Engine::execute_prepared`: clones
2094    /// the AST, substitutes `$1..$N` → `params[0..N-1]`, runs.
2095    ///
2096    /// Persistence (WAL fsync + auto-checkpoint) follows the
2097    /// same rules as `execute(sql)`: mutating statements get a
2098    /// WAL record AFTER the in-memory exec succeeds. The WAL
2099    /// record carries the substituted, bind-final SQL, so
2100    /// replay reconstructs the same row state without needing
2101    /// the original prepared `Statement` to still be alive.
2102    ///
2103    /// # Errors
2104    /// Propagates engine errors. Param arity mismatch surfaces
2105    /// as `EvalError::PlaceholderOutOfRange`.
2106    pub fn execute_prepared(
2107        &mut self,
2108        stmt: &Statement,
2109        params: &[Value],
2110    ) -> Result<QueryResult, EngineError> {
2111        let (result, ticket) = self.execute_prepared_buffered(stmt, params)?;
2112        if let Some(t) = ticket {
2113            t.wait()?;
2114        }
2115        Ok(result)
2116    }
2117
2118    /// v7.20 P2 — group-commit variant of
2119    /// [`Database::execute_prepared`]. Same contract as
2120    /// [`Database::execute_buffered`]: mutation + enqueue happen
2121    /// here; the caller waits on the ticket AFTER releasing
2122    /// whatever lock guards this `Database`.
2123    ///
2124    /// # Errors
2125    /// Engine errors propagate unchanged; inline auto-checkpoint
2126    /// may surface IO errors.
2127    pub fn execute_prepared_buffered(
2128        &mut self,
2129        stmt: &Statement,
2130        params: &[Value],
2131    ) -> Result<(QueryResult, Option<WalTicket>), EngineError> {
2132        let result = self.engine.execute_prepared(stmt.stmt.clone(), params)?;
2133        let modified = matches!(
2134            &result,
2135            QueryResult::CommandOk {
2136                modified_catalog: true,
2137                ..
2138            }
2139        );
2140        // WAL persistence on the bind-final SQL. Build the
2141        // canonical Display form by re-printing the
2142        // placeholder-substituted statement (cheap — the AST
2143        // is already in hand from execute_prepared's internal
2144        // clone) so replay's path is identical to the
2145        // simple-query path. v7.21: also when a transaction is
2146        // open — in-tx mutations report `modified_catalog: false`
2147        // but must reach the tx WAL buffer (see `wal_after_ok`).
2148        let mut ticket = None;
2149        if self.persistence.is_some()
2150            && (modified
2151                || (self.tx_wal.is_some() && !sql_is_read_only(&stmt.sql))
2152                || tx_control_kind(&stmt.sql).is_some())
2153        {
2154            let mut wal_stmt = stmt.stmt.clone();
2155            crate::wal_render_with_params(&mut wal_stmt, params);
2156            let canonical = format!("{wal_stmt}");
2157            ticket = self.wal_after_ok(&canonical, modified)?;
2158        }
2159        Ok((result, ticket))
2160    }
2161
2162    /// v7.16.0 — run a prepared SELECT with bound params and
2163    /// return rows as `Vec<Vec<Value>>`, matching `query()`
2164    /// shape. SELECTs are read-only so this never writes the
2165    /// WAL.
2166    ///
2167    /// # Errors
2168    /// Returns `Unsupported` if the prepared statement isn't a
2169    /// SELECT (use `execute_prepared` for DML/DDL).
2170    pub fn query_prepared(
2171        &mut self,
2172        stmt: &Statement,
2173        params: &[Value],
2174    ) -> Result<Vec<Vec<Value>>, EngineError> {
2175        match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
2176            QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
2177            QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
2178                "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2179            )),
2180            _ => Err(EngineError::Unsupported(
2181                "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
2182            )),
2183        }
2184    }
2185
2186    /// v7.18 — parse + plan a SQL string against a
2187    /// `CatalogSnapshot`. Mirror of [`Database::prepare`] for the
2188    /// readonly fan-out path: no writer lock taken, no WAL write,
2189    /// no plan-cache mutation. Static-on-`Self` so callers can
2190    /// dispatch against a snapshot without an `&mut Database`
2191    /// borrow — `AsyncReadHandle::prepare` in spg-embedded-tokio
2192    /// is the load-bearing consumer.
2193    ///
2194    /// # Errors
2195    /// Propagates `EngineError::Parse` from the parser.
2196    pub fn prepare_on_snapshot(
2197        snapshot: &CatalogSnapshot,
2198        sql: &str,
2199    ) -> Result<Statement, EngineError> {
2200        let stmt =
2201            spg_engine::Engine::prepare_on_snapshot(snapshot, sql).map_err(EngineError::Parse)?;
2202        Ok(Statement {
2203            stmt,
2204            sql: sql.to_string(),
2205        })
2206    }
2207
2208    /// v7.18 — execute a prepared `Statement` against a
2209    /// `CatalogSnapshot` with bound params. Mirror of
2210    /// [`Database::execute_prepared`] on the readonly path:
2211    /// writes / DDL hit `EngineError::WriteRequired`. No WAL
2212    /// write, no writer lock, multiple snapshots can run
2213    /// concurrently — the snapshot is immutable from prepare time.
2214    ///
2215    /// # Errors
2216    /// Surfaces `EngineError::WriteRequired` for non-readonly
2217    /// statements; propagates other engine errors.
2218    pub fn execute_prepared_on_snapshot(
2219        snapshot: &CatalogSnapshot,
2220        stmt: &Statement,
2221        params: &[Value],
2222    ) -> Result<QueryResult, EngineError> {
2223        spg_engine::Engine::execute_readonly_prepared_on_snapshot(
2224            snapshot,
2225            stmt.stmt.clone(),
2226            params,
2227        )
2228    }
2229
2230    /// v7.28 (round-22) — deadline-bounded variant of
2231    /// [`Database::execute_prepared_on_snapshot`]. Returns
2232    /// `EngineError::Cancelled` once the budget elapses; the
2233    /// sqlx driver uses this to keep readonly-INLINE execution
2234    /// from monopolising the caller's async runtime (four slow
2235    /// inbox queries saturated mailrs's whole tokio pool) and
2236    /// re-runs over the blocking pool on timeout.
2237    ///
2238    /// # Errors
2239    /// `EngineError::Cancelled` on budget expiry; engine errors
2240    /// otherwise.
2241    pub fn execute_prepared_on_snapshot_with_budget(
2242        snapshot: &CatalogSnapshot,
2243        stmt: &Statement,
2244        params: &[Value],
2245        budget_us: u64,
2246    ) -> Result<QueryResult, EngineError> {
2247        fn mono_now_us() -> u64 {
2248            use std::time::{SystemTime, UNIX_EPOCH};
2249            // Monotonic enough for a per-call relative budget: the
2250            // engine only compares (now - start) against the budget
2251            // within one call.
2252            SystemTime::now()
2253                .duration_since(UNIX_EPOCH)
2254                .map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX))
2255                .unwrap_or(0)
2256        }
2257        let deadline = mono_now_us().saturating_add(budget_us);
2258        let token = spg_engine::CancelToken::none().with_deadline(mono_now_us, deadline);
2259        spg_engine::Engine::execute_readonly_prepared_on_snapshot_with_cancel(
2260            snapshot,
2261            stmt.stmt.clone(),
2262            params,
2263            token,
2264        )
2265    }
2266
2267    /// v7.18 — describe a SQL string against a
2268    /// `CatalogSnapshot`. Mirror of [`Database::describe`] on
2269    /// the readonly path. Pure function on the snapshot's
2270    /// catalog; safe to call from any thread.
2271    ///
2272    /// # Errors
2273    /// Propagates `EngineError::Parse` from the parser.
2274    pub fn describe_on_snapshot(
2275        snapshot: &CatalogSnapshot,
2276        sql: &str,
2277    ) -> Result<(Vec<u32>, Vec<ColumnSchema>), EngineError> {
2278        let stmt =
2279            spg_engine::Engine::prepare_on_snapshot(snapshot, sql).map_err(EngineError::Parse)?;
2280        Ok(spg_engine::Engine::describe_prepared_on_snapshot(
2281            snapshot, &stmt,
2282        ))
2283    }
2284
2285    /// v7.21 (round-12 polish) — run a multi-statement SQL script
2286    /// with PG simple-query semantics: the statements execute in
2287    /// order inside ONE implicit transaction, so a mid-script error
2288    /// rolls back the whole script (PG wraps every simple-query
2289    /// message in an implicit transaction). Three exceptions, all
2290    /// PG-faithful:
2291    ///
2292    /// - a script that carries its OWN transaction control
2293    ///   (BEGIN / COMMIT / …) runs statement-by-statement — the
2294    ///   script owns its boundaries;
2295    /// - a script run while the caller already has a transaction
2296    ///   open joins that transaction (no nested BEGIN), and the
2297    ///   caller's COMMIT / ROLLBACK decides its fate;
2298    /// - a single-statement script is plain auto-commit.
2299    ///
2300    /// Returns one `QueryResult` per executed statement. This is the
2301    /// engine behind `sqlx::raw_sql` (mailrs feeds whole
2302    /// `init-schema.sql` files through it) and `spgctl import`.
2303    ///
2304    /// # Errors
2305    /// The first failing statement's error propagates after the
2306    /// implicit ROLLBACK; nothing from the script remains applied.
2307    pub fn execute_script(&mut self, sql: &str) -> Result<Vec<QueryResult>, EngineError> {
2308        let stmts = split_statements(sql);
2309        let script_owns_tx = stmts.iter().any(|s| tx_control_kind(s).is_some());
2310        let wrap = stmts.len() > 1 && !script_owns_tx && !self.engine.in_transaction();
2311        if !wrap {
2312            let mut out = Vec::with_capacity(stmts.len());
2313            for stmt in &stmts {
2314                out.push(self.execute_dump_statement(stmt)?);
2315            }
2316            return Ok(out);
2317        }
2318        self.execute("BEGIN")?;
2319        let mut out = Vec::with_capacity(stmts.len());
2320        for stmt in &stmts {
2321            match self.execute_dump_statement(stmt) {
2322                Ok(r) => out.push(r),
2323                Err(e) => {
2324                    // Best-effort rollback; surface the script error.
2325                    let _ = self.execute("ROLLBACK");
2326                    return Err(e);
2327                }
2328            }
2329        }
2330        self.execute("COMMIT")?;
2331        Ok(out)
2332    }
2333
2334    /// v7.22 (round-13 T2) — execute one `split_statements` chunk,
2335    /// lowering a `COPY … FROM stdin;` block (statement + its data
2336    /// lines, as one chunk) to per-row INSERTs through the shared
2337    /// `spg_engine::copy` helpers. Default-format pg_dump emits
2338    /// COPY blocks, so the zero-change import promise needs this on
2339    /// the embed path; non-COPY statements pass straight through to
2340    /// [`Self::execute`]. Public so `spgctl import` can keep its
2341    /// per-statement error indexing while sharing the lowering.
2342    ///
2343    /// # Errors
2344    /// Engine errors propagate; for COPY the failing row's INSERT
2345    /// error carries the synthesized statement context.
2346    pub fn execute_dump_statement(&mut self, stmt: &str) -> Result<QueryResult, EngineError> {
2347        // Strip pg_dump's `-- Data for Name: …;` banner (it carries
2348        // semicolons of its own) before splitting head from data.
2349        let stmt_clean = strip_leading_sql_noise(stmt);
2350        let head_is_copy = stmt_clean
2351            .get(..4)
2352            .is_some_and(|p| p.eq_ignore_ascii_case("copy"));
2353        if head_is_copy
2354            && let Some((head, data)) = stmt_clean.split_once(';')
2355            && let Some(spec) = spg_engine::copy::parse_copy_from_stdin_head(head)
2356        {
2357            let mut affected: usize = 0;
2358            for line in data.lines() {
2359                // Empty fragments only occur at the chunk boundary
2360                // (the remainder of the COPY line right after `;`);
2361                // data rows are whole non-empty lines.
2362                let line = line.strip_suffix('\r').unwrap_or(line);
2363                if line.is_empty() {
2364                    continue;
2365                }
2366                let values = spg_engine::copy::decode_copy_text_row(line);
2367                let insert = spg_engine::copy::build_copy_insert(
2368                    &spec.table,
2369                    spec.columns.as_deref(),
2370                    &values,
2371                );
2372                match self.execute(&insert)? {
2373                    QueryResult::CommandOk { affected: n, .. } => affected += n,
2374                    _ => affected += 1,
2375                }
2376            }
2377            return Ok(QueryResult::CommandOk {
2378                affected,
2379                modified_catalog: false,
2380            });
2381        }
2382        self.execute(stmt)
2383    }
2384
2385    /// v7.2.0 — run `body` inside an implicit `BEGIN` /
2386    /// `COMMIT` pair. The body receives `&mut Database` so it
2387    /// can `execute()` / `query()` like any other code path;
2388    /// the only difference is that every write in the body
2389    /// lands inside one transaction, and a returned `Err` from
2390    /// the body triggers `ROLLBACK` before the error propagates.
2391    ///
2392    /// Nested calls are not supported — SPG's transaction
2393    /// model is single-writer with explicit `BEGIN` /
2394    /// `COMMIT` / `ROLLBACK`, and a nested `with_transaction`
2395    /// would hit `EngineError::Unsupported("nested
2396    /// transaction")` at the inner `BEGIN`.
2397    pub fn with_transaction<R, F>(&mut self, body: F) -> Result<R, EngineError>
2398    where
2399        F: FnOnce(&mut Self) -> Result<R, EngineError>,
2400    {
2401        self.execute("BEGIN")?;
2402        match body(self) {
2403            Ok(value) => {
2404                self.execute("COMMIT")?;
2405                Ok(value)
2406            }
2407            Err(e) => {
2408                // Best-effort rollback. If ROLLBACK itself
2409                // fails (rare — the engine reports it via
2410                // `Unsupported` only when there's no active
2411                // TX, which can't happen here) we surface the
2412                // original body error, not the rollback error.
2413                let _ = self.execute("ROLLBACK");
2414                Err(e)
2415            }
2416        }
2417    }
2418}
2419
2420impl Default for Database {
2421    fn default() -> Self {
2422        Self::open_in_memory()
2423    }
2424}
2425
2426/// v7.7.5 — observability snapshot returned by
2427/// [`Database::metrics`]. Plain data, no allocations beyond
2428/// what the struct itself takes; cheap to construct and
2429/// cheap to serialise.
2430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2431#[non_exhaustive]
2432pub struct EmbeddedMetrics {
2433    /// Total live row count across every user table (hot
2434    /// tier only — cold-tier rows live in segment files).
2435    pub hot_rows: u64,
2436    /// Sum of `Table::hot_bytes` across every user table.
2437    /// Tracks against the freezer's `hot_tier_bytes` budget.
2438    pub hot_bytes: u64,
2439    /// Number of cold-tier segments registered in the catalog.
2440    /// Includes tombstoned slots (segments retired by
2441    /// compaction whose disk file may still be on disk).
2442    pub cold_segments: u64,
2443    /// User-table count (excludes any future engine-managed
2444    /// internal tables).
2445    pub tables: u64,
2446    /// WAL size at last `execute()` / `checkpoint()`. Zero
2447    /// when the database is in-memory.
2448    pub wal_bytes: u64,
2449    /// `true` when the database was opened with `open_path` —
2450    /// i.e. WAL + checkpoint persistence is active.
2451    pub persistent: bool,
2452}
2453
2454/// v7.2.1 — handle returned by `spawn_background_freezer`.
2455/// Drop signals the worker thread to wind down + joins it,
2456/// so a `Database` (or its shared `Arc<Mutex<Database>>`)
2457/// can safely drop after the handle does.
2458#[must_use = "the background freezer keeps running until this handle is dropped"]
2459#[derive(Debug)]
2460pub struct FreezerHandle {
2461    shutdown: Arc<AtomicBool>,
2462    join: Option<JoinHandle<()>>,
2463}
2464
2465impl FreezerHandle {
2466    /// v7.2.1 — request the worker stop + join. Idempotent;
2467    /// safe to call from `Drop` (which also calls it).
2468    pub fn stop(&mut self) {
2469        self.shutdown.store(true, Ordering::Release);
2470        if let Some(h) = self.join.take() {
2471            let _ = h.join();
2472        }
2473    }
2474}
2475
2476impl Drop for FreezerHandle {
2477    fn drop(&mut self) {
2478        self.stop();
2479    }
2480}
2481
2482/// v7.2.1 — knobs for `Database::spawn_background_freezer`.
2483#[derive(Debug, Clone)]
2484pub struct FreezerOptions {
2485    /// Tick interval. Worker wakes every `tick`, checks the
2486    /// catalog's `hot_tier_bytes`, and freezes if over budget.
2487    pub tick: Duration,
2488    /// Hot-tier byte budget. Exceeded → next tick freezes the
2489    /// largest table's oldest `batch_rows` rows into a new
2490    /// cold segment.
2491    pub hot_tier_bytes: u64,
2492    /// Max rows the freezer demotes per fire.
2493    pub batch_rows: usize,
2494    /// v7.7.4 — auto-compact threshold. When the catalog has
2495    /// at least this many cold segments across all tables, the
2496    /// freezer fires a compaction pass after its next freeze.
2497    /// Set to `usize::MAX` to disable auto-compact entirely;
2498    /// the default is `64`, matching the `spg-server` operating
2499    /// point for SPG_COLD_COMPACT_SEGMENT_THRESHOLD.
2500    pub compact_when_segments_exceed: usize,
2501    /// v7.7.4 — target segment size for compaction merges,
2502    /// in bytes. Default 64 MiB, mirroring `spg-server`. Small
2503    /// segments below this size are merge candidates;
2504    /// segments at or above stay untouched.
2505    pub compact_target_bytes: u64,
2506}
2507
2508impl Default for FreezerOptions {
2509    fn default() -> Self {
2510        // Match the `spg-server` freezer's default operating
2511        // point (SPG_HOT_TIER_BYTES = 4 GiB, batch 1000 rows,
2512        // tick every 1 s) so embedded behaviour is predictable
2513        // for operators familiar with the server.
2514        Self {
2515            tick: Duration::from_secs(1),
2516            hot_tier_bytes: 4 * 1024 * 1024 * 1024,
2517            batch_rows: 1000,
2518            compact_when_segments_exceed: 64,
2519            compact_target_bytes: 64 * 1024 * 1024,
2520        }
2521    }
2522}
2523
2524impl Database {
2525    /// v7.7.4 — observe the catalog's cold-segment count.
2526    /// Useful for tests + dashboards that want to verify
2527    /// auto-compaction is firing.
2528    #[must_use]
2529    pub fn cold_segment_count(&self) -> usize {
2530        self.engine.catalog().cold_segment_count()
2531    }
2532
2533    /// v7.7.5 — observability snapshot. Returns a point-in-time
2534    /// view of the engine + persistence counters. Cheap (no
2535    /// locks beyond the existing `&self` borrow), so safe to
2536    /// call from a hot metrics-scrape path.
2537    ///
2538    /// Fields mirror the operational dashboard
2539    /// [`spg-server`](https://crates.io/crates/spg-server) exposes,
2540    /// minus the network counters that don't apply to embedded.
2541    #[must_use]
2542    pub fn metrics(&self) -> EmbeddedMetrics {
2543        let cat = self.engine.catalog();
2544        let mut hot_rows: u64 = 0;
2545        let mut hot_bytes: u64 = 0;
2546        for name in cat.table_names() {
2547            if let Some(t) = cat.get(&name) {
2548                hot_rows = hot_rows.saturating_add(t.row_count() as u64);
2549                hot_bytes = hot_bytes.saturating_add(t.hot_bytes());
2550            }
2551        }
2552        let (wal_bytes, persistent) = match &self.persistence {
2553            Some(p) => (p.wal.written_len(), true),
2554            None => (0, false),
2555        };
2556        EmbeddedMetrics {
2557            hot_rows,
2558            hot_bytes,
2559            cold_segments: cat.cold_segment_count() as u64,
2560            tables: cat.table_count() as u64,
2561            wal_bytes,
2562            persistent,
2563        }
2564    }
2565
2566    /// v7.2.1 — spawn a background thread that periodically
2567    /// runs `freeze_oldest_to_cold` when the catalog-wide hot
2568    /// tier exceeds `opts.hot_tier_bytes`. The `Arc<Mutex<_>>`
2569    /// pattern matches the v7.2 sharing story: callers wrap
2570    /// their `Database` in `Arc::new(Mutex::new(db))` once,
2571    /// then clone the Arc for the worker + for foreground
2572    /// access. Return value is a handle whose `Drop` joins the
2573    /// worker.
2574    ///
2575    /// Picks the freeze target the same way `spg-server`'s
2576    /// freezer does: largest-`hot_bytes` user table with at
2577    /// least one BTree integer-PK index. Tables without a
2578    /// freezable index are skipped silently.
2579    pub fn spawn_background_freezer(
2580        db: Arc<Mutex<Database>>,
2581        opts: FreezerOptions,
2582    ) -> FreezerHandle {
2583        let shutdown = Arc::new(AtomicBool::new(false));
2584        let shutdown_for_thread = Arc::clone(&shutdown);
2585        let join = thread::Builder::new()
2586            .name("spg-embedded-freezer".into())
2587            .spawn(move || {
2588                background_freezer_loop(db, opts, shutdown_for_thread);
2589            })
2590            .expect("spawn background freezer thread");
2591        FreezerHandle {
2592            shutdown,
2593            join: Some(join),
2594        }
2595    }
2596}
2597
2598/// v7.2.1 — the freezer's main loop, factored out so the
2599/// `Database::spawn_background_freezer` path stays readable.
2600fn background_freezer_loop(
2601    db: Arc<Mutex<Database>>,
2602    opts: FreezerOptions,
2603    shutdown: Arc<AtomicBool>,
2604) {
2605    // Sleep in short slices so a shutdown request resolves
2606    // quickly (vs sleeping the full tick).
2607    let slice = Duration::from_millis(50.min(opts.tick.as_millis() as u64));
2608    let mut last_tick = std::time::Instant::now();
2609    loop {
2610        if shutdown.load(Ordering::Acquire) {
2611            return;
2612        }
2613        thread::sleep(slice);
2614        if last_tick.elapsed() < opts.tick {
2615            continue;
2616        }
2617        last_tick = std::time::Instant::now();
2618        let Ok(mut guard) = db.lock() else {
2619            return;
2620        };
2621        if guard.engine.catalog().hot_tier_bytes() <= opts.hot_tier_bytes {
2622            continue;
2623        }
2624        let Some((table, index)) = pick_freeze_target(&guard) else {
2625            continue;
2626        };
2627        let row_count = guard
2628            .engine
2629            .catalog()
2630            .get(&table)
2631            .map_or(0, spg_storage::Table::row_count);
2632        let to_freeze = opts.batch_rows.min(row_count);
2633        if to_freeze == 0 {
2634            continue;
2635        }
2636        if let Err(e) = guard.freeze_oldest_to_cold(&table, &index, to_freeze) {
2637            eprintln!("spg-embedded: background freeze on {table}.{index} failed: {e:?}");
2638            continue;
2639        }
2640        // v7.7.4 — auto-compact. If the catalog now carries
2641        // more cold segments than the configured threshold,
2642        // run a single compaction pass. Failures are reported
2643        // but don't kill the loop; the next tick will retry.
2644        let count = guard.engine.catalog().cold_segment_count();
2645        if count > opts.compact_when_segments_exceed {
2646            if let Err(e) = guard
2647                .engine
2648                .compact_cold_segments_with_target(opts.compact_target_bytes)
2649            {
2650                eprintln!(
2651                    "spg-embedded: background compact failed (segments={count}, \
2652                     threshold={}): {e:?}",
2653                    opts.compact_when_segments_exceed,
2654                );
2655            }
2656        }
2657    }
2658}
2659
2660/// v7.2.1 — pick the highest-`hot_bytes` user table with a
2661/// BTree integer-PK index. Returns `(table, index_name)` so the
2662/// caller can dispatch through `freeze_oldest_to_cold`.
2663fn pick_freeze_target(db: &Database) -> Option<(String, String)> {
2664    let cat = db.engine.catalog();
2665    let mut best: Option<(String, String, u64)> = None;
2666    for name in cat.table_names() {
2667        let Some(t) = cat.get(&name) else { continue };
2668        if t.row_count() == 0 {
2669            continue;
2670        }
2671        let cols = &t.schema().columns;
2672        let Some(idx) = t.indices().iter().find(|i| {
2673            matches!(i.kind, spg_storage::IndexKind::BTree(_))
2674                && i.column_position < cols.len()
2675                && matches!(
2676                    cols[i.column_position].ty,
2677                    spg_storage::DataType::SmallInt
2678                        | spg_storage::DataType::Int
2679                        | spg_storage::DataType::BigInt
2680                )
2681        }) else {
2682            continue;
2683        };
2684        let hot = t.hot_bytes();
2685        match best {
2686            None => best = Some((name, idx.name.clone(), hot)),
2687            Some((_, _, best_hot)) if hot > best_hot => {
2688                best = Some((name, idx.name.clone(), hot));
2689            }
2690            _ => {}
2691        }
2692    }
2693    best.map(|(t, i, _)| (t, i))
2694}
2695
2696/// v7.7.6 — replay the first `to_seq` records of the WAL at
2697/// `wal_path` into a fresh engine and write the resulting
2698/// catalog snapshot to `out_db_path`. Same semantics as
2699/// `spg revert --wal … --to-seq N --out …` from the CLI:
2700///
2701///   - `to_seq == 0` → snapshot is the empty catalog
2702///   - WAL records beyond `to_seq` are not applied
2703///   - durability-checkpoint markers (v3 type 0x02) are
2704///     consumed without counting against the budget
2705///
2706/// Returns the number of statements actually applied
2707/// (`≤ to_seq`). The output snapshot is byte-identical to
2708/// what `Database::open_path(out_db_path)` would consume on
2709/// a subsequent open.
2710///
2711/// This is the "rewind" operator for an embedded database
2712/// that has been corrupted by a poison statement or a
2713/// half-applied migration. Pair with `cold_segment_paths`
2714/// preservation if your cold-tier files are still on disk.
2715///
2716/// # Errors
2717///
2718/// - `wal_path` unreadable or truncated mid-record
2719/// - WAL record decodes to invalid UTF-8 SQL
2720/// - WAL record's SQL is rejected by the engine
2721/// - `out_db_path` unwritable
2722pub fn revert_wal_to_seq(
2723    wal_path: impl AsRef<Path>,
2724    to_seq: u64,
2725    out_db_path: impl AsRef<Path>,
2726) -> Result<u64, EngineError> {
2727    // v7.19 — accept either a single-file legacy WAL (v7.18 and
2728    // earlier layout) or a chunked WAL directory (v7.19+). For a
2729    // directory, concatenate every `.wal` chunk in sorted order
2730    // — the same order open_path replays them in — so revert
2731    // sees the full record stream.
2732    let path = wal_path.as_ref();
2733    let wal_bytes = if path.is_dir() {
2734        let mut combined = Vec::new();
2735        let chunks = sorted_wal_chunks(path).map_err(io_err)?;
2736        for chunk in chunks {
2737            let bytes = std::fs::read(&chunk).map_err(io_err)?;
2738            combined.extend_from_slice(&bytes);
2739        }
2740        combined
2741    } else {
2742        std::fs::read(path).map_err(io_err)?
2743    };
2744    let mut engine = Engine::new();
2745    let mut applied = 0u64;
2746    let mut cur = 0usize;
2747    while cur < wal_bytes.len() && applied < to_seq {
2748        let (sql_bytes, total) = decode_wal_record(&wal_bytes[cur..])?;
2749        cur += total;
2750        if sql_bytes.is_empty() {
2751            continue;
2752        }
2753        let sql = core::str::from_utf8(&sql_bytes).map_err(|e| {
2754            EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
2755                "WAL record at offset {cur}: non-UTF-8 SQL: {e}"
2756            )))
2757        })?;
2758        // v7.21 — tx-commit records carry a multi-statement script;
2759        // split_statements is a no-op for single-statement records.
2760        for stmt in split_statements(sql) {
2761            engine.execute(stmt)?;
2762        }
2763        applied += 1;
2764    }
2765    let snapshot = engine.snapshot();
2766    std::fs::write(out_db_path.as_ref(), &snapshot).map_err(io_err)?;
2767    Ok(applied)
2768}
2769
2770/// v7.7.6 — decode one WAL record from a byte tail. Returns
2771/// `(sql_bytes, header_plus_payload_len)`. Handles the three
2772/// on-disk formats (v1 / v2 / v3) the same way the CLI
2773/// `decode_one_record` and the engine's `replay_wal_bytes`
2774/// do. CRCs are not re-validated; the caller's intent is
2775/// "apply", not "validate".
2776fn decode_wal_record(tail: &[u8]) -> Result<(Vec<u8>, usize), EngineError> {
2777    if tail.len() < 4 {
2778        return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
2779            format!("WAL truncated record: {} < 4 header bytes", tail.len()),
2780        )));
2781    }
2782    let raw_len = u32::from_le_bytes(tail[..4].try_into().unwrap());
2783    let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
2784    let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
2785    let len_mask = if is_v3 {
2786        !(WAL_V2_SENTINEL | WAL_V3_FLAG)
2787    } else {
2788        !WAL_V2_SENTINEL
2789    };
2790    let rec_len = (raw_len & len_mask) as usize;
2791    let header_len = if is_v3 {
2792        9
2793    } else if is_v2 {
2794        8
2795    } else {
2796        4
2797    };
2798    if tail.len() < header_len + rec_len {
2799        return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
2800            format!(
2801                "WAL truncated record: header+payload {} > available {}",
2802                header_len + rec_len,
2803                tail.len()
2804            ),
2805        )));
2806    }
2807    if is_v3 {
2808        let type_byte = tail[8];
2809        // v3 type 0x01 = auto_commit_sql (payload = SQL).
2810        // v3 type 0x02 = durability marker (no SQL to apply).
2811        // v4 type 0x10 = auto_commit_sql with 16-byte (lsn, ts)
2812        //                prefix between type and SQL — strip
2813        //                the prefix so the caller still sees raw
2814        //                SQL bytes.
2815        // Anything else is unknown.
2816        if type_byte == WAL_V3_TYPE_AUTO_COMMIT_SQL {
2817            let payload = &tail[header_len..header_len + rec_len];
2818            return Ok((payload.to_vec(), header_len + rec_len));
2819        }
2820        if type_byte == WAL_V4_TYPE_AUTO_COMMIT_SQL || type_byte == WAL_V4_TYPE_TX_COMMIT_SQL {
2821            let v4_total = header_len + WAL_V4_EXTRA_HEADER + rec_len;
2822            if tail.len() < v4_total {
2823                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
2824                    format!(
2825                        "WAL truncated v4 record: header+payload {v4_total} > available {}",
2826                        tail.len()
2827                    ),
2828                )));
2829            }
2830            let sql_start = header_len + WAL_V4_EXTRA_HEADER;
2831            let sql_bytes = tail[sql_start..sql_start + rec_len].to_vec();
2832            return Ok((sql_bytes, v4_total));
2833        }
2834        // Caller treats empty payload as a skip-marker.
2835        return Ok((Vec::new(), header_len + rec_len));
2836    }
2837    let payload = &tail[header_len..header_len + rec_len];
2838    Ok((payload.to_vec(), header_len + rec_len))
2839}
2840
2841impl Drop for Database {
2842    fn drop(&mut self) {
2843        // v7.1 — best-effort final checkpoint when a persistent
2844        // Database leaves scope. Failures here go to stderr so
2845        // operators see them, but Drop can't propagate errors —
2846        // the WAL itself is already durable, so a checkpoint
2847        // miss only means the next boot replays a few more
2848        // records than strictly necessary.
2849        if self.persistence.is_some() {
2850            if let Err(e) = self.checkpoint() {
2851                eprintln!(
2852                    "spg-embedded: final checkpoint on Drop failed: {e:?} \
2853                     (WAL is intact; next open_path will replay)"
2854                );
2855            }
2856        }
2857        // v7.19 P3 / v7.20 — signal the retention + flusher
2858        // threads to exit, then wait for them. Done BEFORE the
2859        // lock release so background threads don't outlive the
2860        // database handle. The flusher drains the pending batch
2861        // on its way out (final flush_now in the thread body),
2862        // so `SPG_SYNCHRONOUS_COMMIT=off` never loses confirmed
2863        // commits across a clean shutdown.
2864        if let Some(ctx) = self.persistence.as_mut() {
2865            if let Some(shutdown) = ctx.retention_shutdown.take() {
2866                shutdown.store(true, Ordering::SeqCst);
2867            }
2868            if let Some(handle) = ctx.retention_thread.take() {
2869                let _ = handle.join();
2870            }
2871            if let Some(shutdown) = ctx.flusher_shutdown.take() {
2872                shutdown.store(true, Ordering::SeqCst);
2873            }
2874            if let Some(handle) = ctx.flusher_thread.take() {
2875                let _ = handle.join();
2876            }
2877        }
2878        // v7.17.0 Phase 6.2 — release the cross-process lock on
2879        // clean shutdown. Failure is logged but never panics;
2880        // the operator can clear a stale lock via
2881        // `Database::force_unlock` if a crash kept the
2882        // directory around.
2883        if let Some(ctx) = &self.persistence
2884            && ctx.lock_path.exists()
2885        {
2886            // remove_dir_all: the lock dir carries the owner-pid
2887            // record since round-12.
2888            if let Err(e) = std::fs::remove_dir_all(&ctx.lock_path) {
2889                eprintln!(
2890                    "spg-embedded: lock release on Drop failed for {}: {e:?}",
2891                    ctx.lock_path.display()
2892                );
2893            }
2894        }
2895    }
2896}
2897
2898impl Database {
2899    /// v7.17.0 Phase 6.2 — clear a stale cross-process lock.
2900    /// Use when a previous process crashed mid-session and
2901    /// left `<db_path>.lock` behind. Operators should confirm
2902    /// no other process is currently using the database before
2903    /// calling this — SPG cannot fingerprint stale-vs-live
2904    /// without a libc dep, which would violate spg-embedded's
2905    /// zero-deps charter.
2906    pub fn force_unlock(db_path: impl AsRef<Path>) -> Result<(), EngineError> {
2907        let lock_path = {
2908            let mut p = db_path.as_ref().to_path_buf();
2909            let name = p
2910                .file_name()
2911                .map(|n| {
2912                    let mut s = n.to_os_string();
2913                    s.push(".lock");
2914                    s
2915                })
2916                .unwrap_or_else(|| std::ffi::OsString::from(".lock"));
2917            p.set_file_name(name);
2918            p
2919        };
2920        if !lock_path.exists() {
2921            return Ok(());
2922        }
2923        std::fs::remove_dir_all(&lock_path).map_err(io_err)
2924    }
2925}
2926
2927/// v7.1 — turn a `std::io::Error` into the workspace's
2928/// `EngineError` shape. `EngineError::Storage(Corrupt(_))` is
2929/// the closest existing variant — io failures during boot or
2930/// during a WAL append surface as a storage-layer fault to
2931/// callers, which keeps the public error enum unchanged.
2932fn io_err(e: std::io::Error) -> EngineError {
2933    EngineError::Storage(spg_storage::StorageError::Corrupt(format!("io: {e}")))
2934}
2935
2936/// v7.2.2 — `Database` is `Send`, so the recommended sharing
2937/// pattern for multi-threaded callers is `Arc<Mutex<Database>>`:
2938///
2939/// ```no_run
2940/// use std::sync::{Arc, Mutex};
2941/// use spg_embedded::Database;
2942///
2943/// let db = Database::open_in_memory();
2944/// let shared = Arc::new(Mutex::new(db));
2945/// let shared_for_worker = Arc::clone(&shared);
2946/// std::thread::spawn(move || {
2947///     let mut guard = shared_for_worker.lock().unwrap();
2948///     guard.execute("INSERT INTO t VALUES (1)").unwrap();
2949/// });
2950/// ```
2951///
2952/// Internal `RwLock`-wrapped state — letting many threads
2953/// hold concurrent `&Database` for `SELECT` without contending
2954/// — is parked as STABILITY § "Out of v7.2"; multi-reader
2955/// embedded throughput needs a planner-side change to release
2956/// the engine read lock between scans, which is the v7.x
2957/// "Choice A" line of work already documented in v6.9.1's
2958/// carve-out.
2959#[allow(dead_code)]
2960fn _database_is_send() {
2961    fn assert_send<T: Send>() {}
2962    assert_send::<Database>();
2963}
2964
2965/// v6.10.3 — trait that maps a row's columns onto a user
2966/// struct's fields. v7.3.0 ships the [`spg_row!`] declarative
2967/// macro that generates `impl FromSpgRow for YourStruct` from
2968/// a struct definition (no proc-macro, no syn/quote/
2969/// proc-macro2 deps — the workspace's "0 external deps"
2970/// policy holds).
2971///
2972/// Implementors map a row's columns onto a user struct's
2973/// fields. Errors surface as `EngineError::Unsupported` so the
2974/// caller's error type stays uniform.
2975pub trait FromSpgRow: Sized {
2976    /// Decode one query result row into `Self`. Called once per
2977    /// row by [`Database::query_typed`]. The slice length equals
2978    /// the number of columns in the SELECT projection.
2979    fn from_spg_row(row: &[Value]) -> Result<Self, EngineError>;
2980}
2981
2982/// v7.3.0 — declarative macro that generates `FromSpgRow` impl
2983/// for a user struct. Avoids proc-macro deps
2984/// (syn/quote/proc-macro2) so the workspace's 0-deps policy
2985/// holds; the trade-off vs `#[derive(SpgRow)]` is that the
2986/// macro takes the entire struct definition (fields + types)
2987/// as input rather than annotating an existing struct.
2988///
2989/// ```no_run
2990/// use spg_embedded::{Database, spg_row, FromSpgRow};
2991///
2992/// spg_row! {
2993///     pub struct User {
2994///         pub id: i32,
2995///         pub name: String,
2996///     }
2997/// }
2998///
2999/// let mut db = Database::open_in_memory();
3000/// db.execute("CREATE TABLE users (id INT NOT NULL, name TEXT)").unwrap();
3001/// db.execute("INSERT INTO users VALUES (1, 'alice')").unwrap();
3002/// let users: Vec<User> = db.query_typed("SELECT id, name FROM users").unwrap();
3003/// ```
3004///
3005/// Supported field types: `i16`, `i32`, `i64`, `f32`, `f64`,
3006/// `bool`, `String`, `Vec<f32>` (for `VECTOR(N)` columns),
3007/// `Option<T>` of any of the above.
3008#[macro_export]
3009macro_rules! spg_row {
3010    (
3011        $(#[$meta:meta])*
3012        $vis:vis struct $name:ident {
3013            $(
3014                $(#[$fmeta:meta])*
3015                $fvis:vis $field:ident : $ty:ty,
3016            )*
3017        }
3018    ) => {
3019        $(#[$meta])*
3020        #[derive(Debug, Clone)]
3021        $vis struct $name {
3022            $(
3023                $(#[$fmeta])*
3024                $fvis $field : $ty,
3025            )*
3026        }
3027
3028        impl $crate::FromSpgRow for $name {
3029            fn from_spg_row(row: &[$crate::Value]) -> ::core::result::Result<Self, $crate::EngineError> {
3030                let mut __spg_row_iter = row.iter();
3031                $(
3032                    let $field: $ty = {
3033                        let v = __spg_row_iter
3034                            .next()
3035                            .ok_or_else(|| $crate::EngineError::Unsupported(
3036                                ::std::format!(
3037                                    "spg_row! {}: missing column for field `{}`",
3038                                    ::core::stringify!($name),
3039                                    ::core::stringify!($field)
3040                                )
3041                            ))?;
3042                        <$ty as $crate::FromSpgValue>::from_spg_value(v)
3043                            .map_err(|e| $crate::EngineError::Unsupported(
3044                                ::std::format!(
3045                                    "spg_row! {}: column `{}`: {}",
3046                                    ::core::stringify!($name),
3047                                    ::core::stringify!($field),
3048                                    e
3049                                )
3050                            ))?
3051                    };
3052                )*
3053                Ok(Self { $($field,)* })
3054            }
3055        }
3056    };
3057}
3058
3059/// v7.3.0 — per-column decoder used by `spg_row!`. Surface
3060/// covers every numeric / text / bytes / bool variant in
3061/// `Value`, plus `Option<T>` for nullable columns.
3062pub trait FromSpgValue: Sized {
3063    /// Decode one cell into `Self`. The returned `&'static str`
3064    /// is a short diagnostic for type mismatches (e.g. `"expected
3065    /// integer, got TEXT"`); callers wrap it into their own
3066    /// error type.
3067    fn from_spg_value(v: &Value) -> Result<Self, &'static str>;
3068}
3069
3070macro_rules! impl_from_value_int {
3071    ($($t:ty),* $(,)?) => {
3072        $(
3073            impl FromSpgValue for $t {
3074                fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3075                    match v {
3076                        Value::SmallInt(n) => <$t>::try_from(*n).map_err(|_| "SmallInt does not fit target int type"),
3077                        Value::Int(n)      => <$t>::try_from(*n).map_err(|_| "Int does not fit target int type"),
3078                        Value::BigInt(n)   => <$t>::try_from(*n).map_err(|_| "BigInt does not fit target int type"),
3079                        Value::Null        => Err("NULL in non-Option int column"),
3080                        _ => Err("non-integer value in int column"),
3081                    }
3082                }
3083            }
3084        )*
3085    };
3086}
3087impl_from_value_int!(i16, i32, i64);
3088
3089impl FromSpgValue for f32 {
3090    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3091        match v {
3092            Value::Float(f) => Ok(*f as f32),
3093            Value::Null => Err("NULL in non-Option float column"),
3094            _ => Err("non-float value in float column"),
3095        }
3096    }
3097}
3098
3099impl FromSpgValue for f64 {
3100    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3101        match v {
3102            Value::Float(f) => Ok(*f),
3103            Value::Null => Err("NULL in non-Option float column"),
3104            _ => Err("non-float value in float column"),
3105        }
3106    }
3107}
3108
3109impl FromSpgValue for bool {
3110    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3111        match v {
3112            Value::Bool(b) => Ok(*b),
3113            Value::Null => Err("NULL in non-Option bool column"),
3114            _ => Err("non-bool value in bool column"),
3115        }
3116    }
3117}
3118
3119impl FromSpgValue for String {
3120    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3121        match v {
3122            Value::Text(s) => Ok(s.clone()),
3123            Value::Null => Err("NULL in non-Option text column"),
3124            _ => Err("non-text value in String column"),
3125        }
3126    }
3127}
3128
3129impl FromSpgValue for Vec<f32> {
3130    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3131        match v {
3132            Value::Vector(xs) => Ok(xs.clone()),
3133            Value::Null => Err("NULL in non-Option vector column"),
3134            _ => Err("non-vector value in Vec<f32> column"),
3135        }
3136    }
3137}
3138
3139impl<T: FromSpgValue> FromSpgValue for Option<T> {
3140    fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
3141        match v {
3142            Value::Null => Ok(None),
3143            other => T::from_spg_value(other).map(Some),
3144        }
3145    }
3146}
3147
3148/// Acquire the cross-process exclusion lock at `lock_path` (atomic
3149/// `mkdir`), recording the owner pid inside. If the lock already
3150/// exists, read the recorded pid and probe liveness — a lock left
3151/// behind by a killed process (docker SIGKILL, crash) is reclaimed
3152/// automatically instead of forcing the operator to delete it by
3153/// hand (mailrs embed round-12: a restarted server came up in
3154/// degraded mode because the previous instance's lock survived).
3155/// v7.27 (mailrs round-21 B) — the prober's environment identity:
3156/// `(hostname, boot-or-container id)`. A pid is only meaningful
3157/// inside the PID namespace that recorded it; mailrs's recovery
3158/// window saw "locked by pid 1" from a STOPPED container because
3159/// the prober's pid 1 (its own init) was alive. When the lock's
3160/// identity differs from ours, liveness is UNDECIDABLE and we
3161/// refuse honestly instead of guessing in either direction.
3162fn host_identity() -> (String, String) {
3163    let hostname = std::process::Command::new("hostname")
3164        .output()
3165        .ok()
3166        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
3167        .unwrap_or_default();
3168    // Linux boot id; containers share the host kernel's boot id, so
3169    // hostname (= container id by default) is the namespace
3170    // discriminator and boot id catches host reboots / pid reuse.
3171    let boot_id = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
3172        .map(|s| s.trim().to_string())
3173        .or_else(|_| {
3174            std::process::Command::new("sysctl")
3175                .args(["-n", "kern.bootsessionuuid"])
3176                .output()
3177                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
3178        })
3179        .unwrap_or_default();
3180    (hostname, boot_id)
3181}
3182
3183fn acquire_path_lock(lock_path: &Path) -> Result<(), EngineError> {
3184    for attempt in 0..2 {
3185        match std::fs::create_dir(lock_path) {
3186            Ok(()) => {
3187                // Best-effort owner record; liveness probing treats a
3188                // missing pid file as stale (crash between mkdir and
3189                // write is indistinguishable from an ancient lock).
3190                // v7.27 — lines 2+3 record the owner's environment
3191                // identity (hostname, boot id) so a prober in a
3192                // different namespace refuses instead of misreading
3193                // the pid.
3194                let (host, boot) = host_identity();
3195                let _ = std::fs::write(
3196                    lock_path.join("pid"),
3197                    format!("{}\n{host}\n{boot}\n", std::process::id()),
3198                );
3199                return Ok(());
3200            }
3201            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt == 0 => {
3202                let record = std::fs::read_to_string(lock_path.join("pid")).unwrap_or_default();
3203                let mut lines = record.lines();
3204                let owner = lines.next().and_then(|s| s.trim().parse::<u32>().ok());
3205                let lock_host = lines.next().unwrap_or("").trim().to_string();
3206                let lock_boot = lines.next().unwrap_or("").trim().to_string();
3207                // v7.27 — identity check BEFORE the pid probe. A pid
3208                // recorded in another namespace is undecidable both
3209                // ways (a stale lock can look held, a held lock can
3210                // look stale — the unsafe direction). Old-format
3211                // locks (pid only) keep the legacy same-host
3212                // assumption.
3213                if !lock_host.is_empty() {
3214                    let (my_host, my_boot) = host_identity();
3215                    let same_env = lock_host == my_host
3216                        && (lock_boot.is_empty() || my_boot.is_empty() || lock_boot == my_boot);
3217                    if !same_env {
3218                        return Err(EngineError::Unsupported(format!(
3219                            "database lock {} was taken in a different host/container \
3220                             (owner: pid {} on {:?}; we are {:?}) — liveness is \
3221                             undecidable from here. If you are sure the owner is gone, \
3222                             call Database::force_unlock() or `spg import --force-unlock`.",
3223                            lock_path.display(),
3224                            owner.unwrap_or(0),
3225                            lock_host,
3226                            my_host
3227                        )));
3228                    }
3229                }
3230                let owner_alive = owner.is_some_and(pid_alive);
3231                if owner_alive {
3232                    return Err(EngineError::Unsupported(format!(
3233                        "database is locked by another process (pid {}): {}; \
3234                         stop that process first, or call Database::force_unlock()",
3235                        owner.unwrap_or(0),
3236                        lock_path.display()
3237                    )));
3238                }
3239                // Stale — owner pid dead or unrecorded. Reclaim.
3240                eprintln!(
3241                    "spg-embedded: reclaiming stale lock {} (owner pid {:?} not alive)",
3242                    lock_path.display(),
3243                    owner
3244                );
3245                std::fs::remove_dir_all(lock_path).map_err(io_err)?;
3246                // Loop retries the create_dir; a concurrent reclaimer
3247                // winning the race surfaces as AlreadyExists on
3248                // attempt 1 below.
3249            }
3250            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3251                return Err(EngineError::Unsupported(format!(
3252                    "database is locked by another process: {}; \
3253                     stop that process first, or call Database::force_unlock()",
3254                    lock_path.display()
3255                )));
3256            }
3257            Err(e) => return Err(io_err(e)),
3258        }
3259    }
3260    unreachable!("acquire_path_lock loop covers both attempts")
3261}
3262
3263/// Probe whether `pid` is a live process. Unix: `ps -p` via the
3264/// system binary (std-only — no libc dependency). `ps -p` exits 0
3265/// for ANY live pid regardless of owner; `kill -0` was rejected
3266/// here because it fails with EPERM on another user's live process,
3267/// which would read as "dead" and reclaim a held lock. Probe
3268/// failure (no `ps` binary, exec error) conservatively reports
3269/// alive so locks are never auto-reclaimed on doubt; non-unix
3270/// targets do the same.
3271#[cfg(unix)]
3272fn pid_alive(pid: u32) -> bool {
3273    match std::process::Command::new("ps")
3274        .arg("-p")
3275        .arg(pid.to_string())
3276        .stdout(std::process::Stdio::null())
3277        .stderr(std::process::Stdio::null())
3278        .status()
3279    {
3280        Ok(status) => status.success(),
3281        Err(_) => true,
3282    }
3283}
3284
3285#[cfg(not(unix))]
3286fn pid_alive(_pid: u32) -> bool {
3287    true
3288}
3289
3290/// Strip leading whitespace, `--` line comments and NON-conditional
3291/// block comments from a chunk so statement-head checks (COPY
3292/// detection most notably) see the first real token. pg_dump
3293/// prefixes every data block with a `-- Data for Name: …;` banner —
3294/// which itself contains semicolons, so head checks must run on the
3295/// stripped text. MySQL executable conditional comments (`/*!`) are
3296/// content and stay.
3297/// v7.22 — see `split_statements`' `mysql_escapes` tracking. Only
3298/// short chunks are inspected (the signal statements are one-liners;
3299/// COPY data blocks are skipped by the length guard).
3300fn note_dialect_signals(chunk: &str, mysql_escapes: &mut bool) {
3301    if chunk.len() > 4096 {
3302        return;
3303    }
3304    let lower = chunk.to_ascii_lowercase();
3305    if lower.contains("sql_mode") {
3306        *mysql_escapes = true;
3307    } else if lower.contains("standard_conforming_strings") {
3308        *mysql_escapes = lower.contains("off");
3309    }
3310}
3311
3312fn strip_leading_sql_noise(mut s: &str) -> &str {
3313    loop {
3314        let t = s.trim_start();
3315        if let Some(rest) = t.strip_prefix("--") {
3316            s = rest.split_once('\n').map_or("", |(_, r)| r);
3317            continue;
3318        }
3319        if t.starts_with("/*") && !t.starts_with("/*!") {
3320            match t.find("*/") {
3321                Some(e) => {
3322                    s = &t[e + 2..];
3323                    continue;
3324                }
3325                None => return "",
3326            }
3327        }
3328        return t;
3329    }
3330}
3331
3332/// Split a multi-statement SQL script into individual statements on
3333/// top-level `;`, honouring single-quoted strings (with `''`
3334/// escapes), double-quoted identifiers, dollar-quoted bodies
3335/// (`$tag$ … $tag$`), line comments (`--`) and MySQL executable
3336/// conditional comments (`/*!… */` stay statement content; plain
3337/// nested block comments don't). Chunks that contain no statement
3338/// content (whitespace / comments only) are dropped. PG's
3339/// simple-query protocol does this server-side; the embed path owns
3340/// it here.
3341///
3342/// v7.22 (mailrs round-13 gap 1) — psql meta-command lines are
3343/// dropped for client parity: a line whose first non-whitespace
3344/// byte is `\` BETWEEN statements (PG 18's pg_dump wraps scripts in
3345/// `\restrict` / `\unrestrict`) never reaches the parser, the same
3346/// way psql consumes `\`-lines client-side and never sends them. A
3347/// mid-statement backslash stays an ordinary byte — pg_dump only
3348/// emits meta-commands between statements.
3349pub fn split_statements(sql: &str) -> Vec<&str> {
3350    let bytes = sql.as_bytes();
3351    let mut stmts = Vec::new();
3352    let mut start = 0usize;
3353    let mut has_content = false;
3354    // v7.22 (round-13 T3) — stream-tracked string dialect, mirroring
3355    // the engine's session flag: a statement mentioning `sql_mode`
3356    // (mysqldump preamble, often inside `/*!…*/`) switches plain
3357    // strings to backslash-escape scanning;
3358    // `standard_conforming_strings` (pg_dump preamble) switches
3359    // back. Without this the scanner ends a MySQL `'…\'…'` literal
3360    // early and splits inside data.
3361    let mut mysql_escapes = false;
3362    let mut i = 0usize;
3363    while i < bytes.len() {
3364        match bytes[i] {
3365            b'\\' if !has_content => {
3366                // Start-of-statement `\` = psql meta-command line.
3367                // Consume through end-of-line; restart the chunk
3368                // after it so the line never lands in the output.
3369                while i < bytes.len() && bytes[i] != b'\n' {
3370                    i += 1;
3371                }
3372                start = if i < bytes.len() { i + 1 } else { i };
3373            }
3374            b'\'' => {
3375                has_content = true;
3376                // PG escape-string form `E'...'` honours backslash
3377                // escapes (`E'a\';b'` is ONE literal) — detect via
3378                // the immediately-preceding standalone E/e. MySQL
3379                // dialect sessions treat EVERY plain string that way.
3380                let escape_string = mysql_escapes
3381                    || (i >= 1
3382                        && matches!(bytes[i - 1], b'e' | b'E')
3383                        && !(i >= 2
3384                            && (bytes[i - 2].is_ascii_alphanumeric() || bytes[i - 2] == b'_')));
3385                i += 1;
3386                while i < bytes.len() {
3387                    if escape_string && bytes[i] == b'\\' {
3388                        // Skip the escaped byte (covers \' and \\).
3389                        i += 2;
3390                        continue;
3391                    }
3392                    if bytes[i] == b'\'' {
3393                        // `''` is an escaped quote inside the literal.
3394                        if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
3395                            i += 2;
3396                            continue;
3397                        }
3398                        break;
3399                    }
3400                    i += 1;
3401                }
3402            }
3403            b'"' => {
3404                has_content = true;
3405                i += 1;
3406                while i < bytes.len() && bytes[i] != b'"' {
3407                    i += 1;
3408                }
3409            }
3410            b'$' => {
3411                // Possible dollar-quote opener `$tag$` (tag may be
3412                // empty). If the shape doesn't match, it's a plain
3413                // `$` (positional param) — fall through.
3414                let tag_end = bytes[i + 1..]
3415                    .iter()
3416                    .position(|&b| !(b.is_ascii_alphanumeric() || b == b'_'))
3417                    .map(|off| i + 1 + off);
3418                if let Some(te) = tag_end
3419                    && te < bytes.len()
3420                    && bytes[te] == b'$'
3421                {
3422                    has_content = true;
3423                    let tag = &sql[i..=te];
3424                    // Find the closing `$tag$`.
3425                    if let Some(close) = sql[te + 1..].find(tag) {
3426                        i = te + 1 + close + tag.len();
3427                        continue;
3428                    }
3429                    // Unterminated — consume the rest; the parser
3430                    // will report it.
3431                    i = bytes.len();
3432                    continue;
3433                }
3434                has_content = true;
3435            }
3436            b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => {
3437                while i < bytes.len() && bytes[i] != b'\n' {
3438                    i += 1;
3439                }
3440            }
3441            b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => {
3442                // v7.22 (round-13 T3) — MySQL conditional comments
3443                // `/*!40101 … */` are EXECUTABLE (mysqldump wraps
3444                // its whole preamble + DISABLE KEYS hints in them);
3445                // they must stay statement content for the engine,
3446                // not be skipped as commentary.
3447                if i + 2 < bytes.len() && bytes[i + 2] == b'!' {
3448                    has_content = true;
3449                }
3450                let mut depth = 1usize;
3451                i += 2;
3452                while i < bytes.len() && depth > 0 {
3453                    if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
3454                        depth += 1;
3455                        i += 2;
3456                    } else if bytes[i] == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
3457                        depth -= 1;
3458                        i += 2;
3459                    } else {
3460                        i += 1;
3461                    }
3462                }
3463                continue;
3464            }
3465            b';' => {
3466                if has_content {
3467                    let head = &sql[start..i];
3468                    // v7.22 (round-13 T2) — a `COPY … FROM stdin;`
3469                    // statement owns its following data block
3470                    // through the `\.` terminator line (data lines
3471                    // may contain `;`, so generic splitting would
3472                    // shred them). Swallow head + data into ONE
3473                    // chunk; `execute_script` lowers it to INSERTs.
3474                    // pg_dump prefixes the COPY with a comment
3475                    // banner — strip it before the head check.
3476                    let head_clean = strip_leading_sql_noise(head);
3477                    let is_copy_head = head_clean
3478                        .get(..4)
3479                        .is_some_and(|p| p.eq_ignore_ascii_case("copy"))
3480                        && spg_engine::copy::parse_copy_from_stdin_head(head_clean).is_some();
3481                    if is_copy_head {
3482                        // Scan whole lines after the ';' until the
3483                        // `\.` terminator (or EOF — torn dumps lose
3484                        // their tail, same as psql would error).
3485                        let mut j = i + 1;
3486                        let data_end;
3487                        loop {
3488                            if j >= bytes.len() {
3489                                data_end = bytes.len();
3490                                break;
3491                            }
3492                            let line_end = sql[j..].find('\n').map_or(bytes.len(), |off| j + off);
3493                            if sql[j..line_end].trim_end_matches('\r').trim() == "\\." {
3494                                data_end = j;
3495                                i = line_end; // bottom i += 1 skips \n
3496                                break;
3497                            }
3498                            j = line_end + 1;
3499                        }
3500                        stmts.push(&sql[start..data_end]);
3501                        if data_end == bytes.len() {
3502                            i = bytes.len();
3503                        }
3504                        start = i + 1;
3505                        has_content = false;
3506                        i += 1;
3507                        continue;
3508                    }
3509                    note_dialect_signals(head, &mut mysql_escapes);
3510                    stmts.push(head);
3511                }
3512                start = i + 1;
3513                has_content = false;
3514            }
3515            b => {
3516                if !b.is_ascii_whitespace() {
3517                    has_content = true;
3518                }
3519            }
3520        }
3521        i += 1;
3522    }
3523    if has_content {
3524        stmts.push(&sql[start..]);
3525    }
3526    stmts
3527}
3528
3529#[cfg(test)]
3530mod tests {
3531    use super::*;
3532
3533    #[test]
3534    fn split_statements_basic_and_trailing() {
3535        assert_eq!(
3536            split_statements("CREATE TABLE a (x INT); INSERT INTO a VALUES (1)"),
3537            vec!["CREATE TABLE a (x INT)", " INSERT INTO a VALUES (1)"]
3538        );
3539        // whitespace/comment-only chunks drop
3540        assert!(split_statements("  ;; -- nothing\n;").is_empty());
3541    }
3542
3543    #[test]
3544    fn split_statements_quoting_forms() {
3545        // ';' inside a plain literal, a doubled quote, an E-string
3546        // backslash escape, a quoted identifier, and a dollar-quoted
3547        // body must not split.
3548        let cases = [
3549            "INSERT INTO t VALUES ('a;b')",
3550            "INSERT INTO t VALUES ('it''s; fine')",
3551            r"INSERT INTO t VALUES (E'it\'s; fine')",
3552            "CREATE TABLE \"odd;name\" (x INT)",
3553            "DO $body$ BEGIN PERFORM 1; END $body$",
3554            "DO $$ SELECT 1; $$",
3555        ];
3556        for sql in cases {
3557            assert_eq!(split_statements(sql), vec![sql], "must stay whole: {sql}");
3558        }
3559        // ...and each still splits cleanly from a neighbour.
3560        for sql in cases {
3561            let script = format!("{sql};\nSELECT 2");
3562            assert_eq!(
3563                split_statements(&script),
3564                vec![sql, "\nSELECT 2"],
3565                "must split after: {sql}"
3566            );
3567        }
3568    }
3569
3570    #[test]
3571    fn split_statements_drops_psql_meta_lines() {
3572        // v7.22 round-13 gap 1 — PG 18 pg_dump wraps scripts in
3573        // `\restrict` / `\unrestrict`; psql parity = the lines never
3574        // reach the parser.
3575        let script = "\\restrict TOKEN123\nSELECT 1;\n\\unrestrict TOKEN123\nSELECT 2;\n\\.\n";
3576        assert_eq!(split_statements(script), vec!["SELECT 1", "SELECT 2"]);
3577        // Mid-statement backslash is NOT a meta-command.
3578        let s2 = r"SELECT E'a\\b'";
3579        assert_eq!(split_statements(s2), vec![s2]);
3580    }
3581
3582    #[test]
3583    fn split_statements_comments_hide_semicolons() {
3584        let script = "-- c1 ; still comment\nSELECT 1; /* a ; b /* nested ; */ */ SELECT 2";
3585        let got = split_statements(script);
3586        assert_eq!(got.len(), 2);
3587        assert!(got[0].contains("SELECT 1"));
3588        assert!(got[1].contains("SELECT 2"));
3589    }
3590
3591    #[test]
3592    fn in_memory_create_insert_select() {
3593        let mut db = Database::open_in_memory();
3594        db.execute("CREATE TABLE t (id INT NOT NULL, name TEXT)")
3595            .unwrap();
3596        db.execute("INSERT INTO t VALUES (1, 'alice')").unwrap();
3597        db.execute("INSERT INTO t VALUES (2, 'bob')").unwrap();
3598        let rows = db.query("SELECT id FROM t WHERE id = 1").unwrap();
3599        assert_eq!(rows.len(), 1);
3600        match &rows[0][0] {
3601            Value::Int(1) => {}
3602            other => panic!("expected Int(1), got {other:?}"),
3603        }
3604    }
3605
3606    #[test]
3607    fn query_on_non_select_errors() {
3608        let mut db = Database::open_in_memory();
3609        db.execute("CREATE TABLE t (id INT)").unwrap();
3610        let r = db.query("INSERT INTO t VALUES (1)");
3611        assert!(r.is_err(), "query() on INSERT must error");
3612    }
3613
3614    #[test]
3615    fn snapshot_roundtrip() {
3616        let mut db = Database::open_in_memory();
3617        db.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
3618        db.execute("INSERT INTO t VALUES (42)").unwrap();
3619        let bytes = db.snapshot();
3620        let mut restored = Database::restore(&bytes).unwrap();
3621        let rows = restored.query("SELECT id FROM t WHERE id = 42").unwrap();
3622        assert_eq!(rows.len(), 1);
3623        match &rows[0][0] {
3624            Value::Int(42) => {}
3625            other => panic!("expected Int(42), got {other:?}"),
3626        }
3627    }
3628
3629    #[test]
3630    fn from_spg_row_trait_shape() {
3631        struct User {
3632            _id: i32,
3633        }
3634        impl FromSpgRow for User {
3635            fn from_spg_row(row: &[Value]) -> Result<Self, EngineError> {
3636                match row.first() {
3637                    Some(Value::Int(n)) => Ok(Self { _id: *n }),
3638                    _ => Err(EngineError::Unsupported("bad id".into())),
3639                }
3640            }
3641        }
3642        let row = vec![Value::Int(7)];
3643        let _u = User::from_spg_row(&row).unwrap();
3644    }
3645}