Skip to main content

spg_engine/
lib.rs

1//! SPG execution engine — v0.3 wires the SQL front-end to the in-memory
2//! storage layer. Implements `CREATE TABLE`, single-row `INSERT VALUES`, and
3//! `SELECT * FROM <table>` (no WHERE yet — that lands in v0.4 alongside
4//! expression evaluation against rows).
5#![no_std]
6
7extern crate alloc;
8
9// v7.37.9 T3 — `bump_counter!(C)` / `bump_counter!(C, N)` macros for the
10// Step VM + aggregate hot-path diagnostic counters. Gated on the
11// `perf-counters` feature so release builds pay zero cost; the
12// `xtests/dogfood_replay/spg-counter-dump` binary turns the feature on
13// to attribute Class A / B / C cascade cost.
14#[cfg(not(feature = "perf-counters"))]
15#[macro_export]
16macro_rules! bump_counter {
17    ($c:path) => {{
18        let _ = &$c;
19    }};
20    ($c:path, $n:expr) => {{
21        let _ = &$c;
22        let _ = &$n;
23    }};
24}
25
26#[cfg(feature = "perf-counters")]
27#[macro_export]
28macro_rules! bump_counter {
29    ($c:path) => {{
30        $c.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
31    }};
32    ($c:path, $n:expr) => {{
33        $c.fetch_add($n, core::sync::atomic::Ordering::Relaxed);
34    }};
35}
36
37mod acl;
38pub mod aggregate;
39pub(crate) mod amcheck;
40pub mod brin;
41mod bytebudget;
42mod cancel;
43mod clock;
44mod collate;
45mod collate_derive;
46mod constfold;
47mod constraints;
48mod conversions;
49pub mod copy;
50mod cursor;
51mod ddl;
52pub mod describe;
53mod distinct;
54mod dml;
55mod dump;
56mod envelope;
57pub mod eval;
58mod execute;
59mod explain;
60mod expr_analysis;
61pub(crate) mod extsort;
62pub mod fts;
63mod guc_catalog;
64mod immutable_fn;
65mod index_access;
66mod join;
67mod join_using;
68mod joinfold;
69pub mod json;
70pub mod largeobject;
71mod limit_expr;
72pub mod locks;
73mod maintenance;
74pub mod memoize;
75mod notify;
76mod numeric;
77mod opclass;
78mod orderby;
79mod partition;
80pub(crate) mod partition_walks;
81pub mod plan_cache;
82mod plpgsql;
83pub mod publications;
84mod qualorder;
85pub mod query_stats;
86mod readonly;
87pub mod reorder;
88mod rls;
89mod rules;
90pub mod scalarsq_streaming;
91mod select;
92pub mod selectivity;
93mod sequence;
94mod session;
95mod show;
96mod spg_admin;
97pub mod statistics;
98pub mod subquery;
99pub mod subscriptions;
100mod substitute;
101mod system_catalog;
102mod table_access;
103pub mod tempstore;
104pub mod testkit;
105mod transaction;
106pub(crate) use transaction::{TxStmtClass, classify_stmt_for_tx};
107pub mod triggers;
108pub mod users;
109mod window;
110
111pub use crate::users::{Role, ScramSecrets, UserError, UserStore};
112pub use cancel::{CancelToken, MonotonicNowFn};
113pub use execute::{RowCells, StreamItem};
114
115use bytebudget::*;
116pub(crate) use clock::{rewrite_clock_calls, value_to_literal};
117use constraints::*;
118pub use constraints::{UNIQ_FOLD_CHOSEN, UNIQ_PROBE_CALLS, UNIQ_PROBE_LOCATORS};
119use conversions::*;
120pub use conversions::{
121    format_bigint_2d_text_pub, format_bit_string, format_circle, format_hstore_text, format_inet,
122    format_int_2d_text_pub, format_line, format_lseg, format_macaddr, format_macaddr8,
123    format_multirange, format_path, format_pg_box, format_pg_lsn, format_point, format_polygon,
124    format_range_text, format_text_2d_text_pub,
125};
126pub(crate) use ddl::{
127    canonicalize_set_value, enforce_enum_label, eval_runtime_default_free,
128    resolve_column_default_free,
129};
130pub(crate) use envelope::{EnvelopeParse, build_envelope, split_envelope};
131use expr_analysis::*;
132use index_access::*;
133pub use join::{ANTI_JOIN_FAST_PATH_FIRED, ANTI_JOIN_FAST_PATH_TRIED};
134pub(crate) use orderby::{
135    OrderKey, apply_offset_and_limit, apply_offset_and_limit_tagged, build_order_keys,
136    canonical_value_repr, cmp_multi_key, expand_group_by_all, order_by_value_cmp,
137    order_by_value_cmp_in, render_histogram_bounds, resolve_order_by_position, sort_by_keys,
138    sort_values_for_histogram, topk_trim, value_cmp, value_to_f64,
139};
140pub use select::{DISTINCT_DUP_DROPPED, PROJ_DIRECT_FIRE, PROJ_ROW_BUILT, SCAN_PATH_ENTERED};
141pub(crate) use select::{build_projection, infer_column_types, value_to_order_key};
142pub use sequence::MUTATING_CALL_NEEDLES;
143pub(crate) use show::render_create_table;
144pub use subquery::{
145    BATCHED_SCALAR_FALL_THROUGH_COUNT, BATCHED_SCALAR_KEYED_FIRE_COUNT,
146    BATCHED_SCALAR_KEYED_PROBE_COUNT, EXISTS_BATCH_FALL_THROUGH_COUNT, EXISTS_BATCH_FIRE_COUNT,
147    EXISTS_PULLUP_BAIL_INNER_FROM, EXISTS_PULLUP_BAIL_INNER_SHAPE,
148    EXISTS_PULLUP_BAIL_MULTICOL_DISABLED, EXISTS_PULLUP_BAIL_NO_CORR, EXISTS_PULLUP_BAIL_NO_WHERE,
149    EXISTS_PULLUP_BAIL_RESIDUAL_NOT_INNER, EXISTS_PULLUP_BAIL_UNIQUE_KEY_MISSING,
150    EXISTS_PULLUP_CANDIDATE_COUNT, EXISTS_PULLUP_FIRE_COUNT, EXISTS_PULLUP_MULTICOL_DISABLE,
151    PULLUP_LIMIT1_FIRE_COUNT, SCALARSQ_PK_PROBE_FIRED, ScalarPkProbeFastPath,
152    expr_tree_has_subquery,
153};
154pub(crate) use subquery::{build_in_list_set, collect_scalar_subqueries, expr_has_subquery};
155pub use substitute::substitute_placeholders;
156use substitute::*;
157use system_catalog::*;
158use window::*;
159
160use alloc::collections::{BTreeMap, BTreeSet};
161use alloc::string::String;
162use alloc::vec::Vec;
163use core::fmt;
164
165// v7.16.0 — re-export the parsed-statement AST so downstream
166// crates (spg-embedded → spg-sqlx) don't need a direct dep on
167// spg-sql for the prepare/bind handle.
168pub use spg_sql::ast::{SelectStatement, Statement as ParsedStatement};
169// v7.37.15 Phase B — re-export the visibility primitives for engine
170// callers so the per-row MVCC types live behind one stable name
171// (`spg_engine::Snapshot` / `spg_engine::RowHeader`) instead of every
172// caller threading through `spg_storage::snapshot::*` directly.
173pub use spg_storage::RowChange;
174pub use spg_storage::row_header::{RowHeader, XMAX_ALIVE, XMIN_FROZEN};
175pub use spg_storage::snapshot::{
176    AllCommitted, InProgressSet, Snapshot, XactStatus, XactStatusOracle,
177};
178
179/// v7.37.15 (Phase C.2) — the engine is its own visibility oracle.
180/// Scans hold `&Engine` while reading, so a scan site can pass `self`
181/// as the [`XactStatusOracle`] alongside its [`Snapshot`] when the
182/// visibility gate migrates from `visible` to `visible_with_status`
183/// (next Phase C step). Delegates to [`Engine::xact_status`].
184impl XactStatusOracle for Engine {
185    fn status(&self, version: u64) -> XactStatus {
186        self.xact_status(version)
187    }
188}
189// v7.37.14 (A2.5-stub) — re-export the silent-FOR-UPDATE telemetry
190// helper through the engine surface so downstream wrappers
191// (spg-embedded / spg-embedded-tokio / spgctl) and their tests
192// don't need a direct `spg-sql` dep.
193use spg_sql::parser::ParseError;
194pub use spg_sql::silent_for_update_count;
195use spg_storage::{Catalog, ColumnSchema, Row, StorageError};
196
197use crate::eval::EvalError;
198
199/// Result of executing one statement.
200#[derive(Debug, Clone, PartialEq)]
201#[non_exhaustive]
202pub enum QueryResult {
203    /// DDL or DML succeeded.
204    ///
205    /// `affected` is the row count for `INSERT` and 0 elsewhere.
206    /// `modified_catalog` tells the server whether this statement
207    /// caused the *committed* catalog to change — it's the signal to
208    /// snapshot/audit. False for `BEGIN`/`ROLLBACK`, false for writeful
209    /// statements executed inside a transaction (those only touch the
210    /// shadow), and true for `COMMIT` and for writes outside a TX.
211    CommandOk {
212        affected: usize,
213        modified_catalog: bool,
214    },
215    /// `SELECT` returned a (possibly empty) row set.
216    Rows {
217        columns: Vec<ColumnSchema>,
218        rows: Vec<Row<'static>>,
219    },
220}
221
222/// All errors the engine can return.
223///
224/// Marked `#[non_exhaustive]` from v7.5.0 onward: external `match`
225/// must include a `_` arm so new variants in subsequent v7.x releases
226/// are not breaking changes.
227#[derive(Debug, Clone, PartialEq)]
228#[non_exhaustive]
229pub enum EngineError {
230    Parse(ParseError),
231    Storage(StorageError),
232    Eval(EvalError),
233    /// Front-end accepted a construct that the v0.x executor doesn't support.
234    Unsupported(String),
235    /// `BEGIN` while another transaction is already open.
236    TransactionAlreadyOpen,
237    /// `COMMIT` / `ROLLBACK` with no active transaction.
238    NoActiveTransaction,
239    /// v7.38 (read01 P3.26) — a statement other than COMMIT / ROLLBACK /
240    /// ROLLBACK TO SAVEPOINT was issued after an earlier statement in the
241    /// same transaction failed. PG aborts the whole transaction on the
242    /// first error and rejects everything until it is ended (SQLSTATE
243    /// 25P02); this mirrors that so partial work can't slip through.
244    InFailedTransaction,
245    /// v7.39 (round 299, E3 Phase 2) — a row lock is held by another
246    /// transaction and the policy is `Wait`.
247    ///
248    /// Its own variant, not an `Unsupported` string: the SERVER has to
249    /// recognise it to retry, and it cannot block inside the engine
250    /// write lock — doing so would stop the whole server, including the
251    /// transaction whose commit would release the lock.
252    LockWouldBlock,
253    /// v7.39 (round 299) — granting the wait would close a wait-for
254    /// cycle. PG's 40P01.
255    LockDeadlock,
256    /// v7.38 (read01 P4.02) — a scalar / row subquery used as an
257    /// expression returned more than one row. PG raises this as
258    /// SQLSTATE 21000 (CARDINALITY_VIOLATION) with a fixed message.
259    CardinalityViolation,
260    /// v7.37.17 (Phase E3) — a REPEATABLE READ / SERIALIZABLE commit
261    /// found a write-write conflict with a concurrently-committed
262    /// transaction (a row this tx wrote was deleted/updated by another
263    /// committed writer, or a unique key this tx inserted was taken).
264    /// PG raises SQLSTATE 40001; the client retries the transaction.
265    /// The failing COMMIT rolls the transaction back, like PG.
266    SerializationFailure(String),
267    /// v4.0 sentinel: `execute_readonly` got a statement that
268    /// mutates engine state (INSERT / CREATE / BEGIN / COMMIT / …).
269    /// The caller should retake the write lock and dispatch through
270    /// `execute(&mut self)` instead.
271    WriteRequired,
272    /// v4.2: a SELECT would have returned more rows than the
273    /// configured `max_query_rows` cap. Carries the cap.
274    RowLimitExceeded(usize),
275    /// v7.30.3 (mailrs round-26): a SELECT's join/filter
276    /// materialisation would have held more (approximate) heap
277    /// bytes than the configured `max_query_bytes` cap. The row
278    /// cap above counts rows; this counts bytes, because one row
279    /// can be a multi-MB mail body — 1000 fat rows pressure the
280    /// host long before any row ceiling trips. Carries the cap.
281    QueryBytesExceeded(usize),
282    /// v4.5: cooperative cancellation — the host (server's
283    /// per-query watchdog) set the cancel flag while a long-running
284    /// SELECT / UPDATE / DELETE was scanning rows. The partial work
285    /// is discarded; the caller should surface this as a timeout
286    /// to the client.
287    Cancelled,
288    /// v7.39 (round 318, V51) — MySQL `KILL <id>` naming an id no live
289    /// connection carries. MariaDB 11: `ERROR 1094 (HY000) Unknown thread
290    /// id: N`.
291    UnknownThreadId(u32),
292    /// v7.39 (round 318, V51) — MySQL `KILL <own id>`. The connection
293    /// really is killed; MariaDB reports it to the victim as
294    /// `ERROR 1927 (70100) Connection was killed` and closes.
295    ConnectionKilled,
296    /// v7.38 Epic P (panic isolation): a panic unwound out of
297    /// statement execution and was caught at the engine's
298    /// `execute_*` boundary (see `execute_in_with_cancel`). The
299    /// in-flight transaction's shadow was discarded (rollback) and
300    /// the engine left consistent; the caller sees this ordinary
301    /// error instead of a crashed process / poisoned lock. NOTE:
302    /// under the release `panic = "abort"` profile the process
303    /// aborts before any unwind, so this variant only ever surfaces
304    /// in dev/test (`panic = "unwind"`) — and in production once a
305    /// later slice flips the release profile to unwind.
306    Internal(String),
307}
308
309impl fmt::Display for EngineError {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        match self {
312            Self::Parse(e) => write!(f, "parse: {e}"),
313            Self::Storage(e) => write!(f, "storage: {e}"),
314            Self::Eval(e) => write!(f, "eval: {e}"),
315            Self::Unsupported(s) => write!(f, "unsupported: {s}"),
316            Self::TransactionAlreadyOpen => f.write_str("a transaction is already open"),
317            Self::NoActiveTransaction => f.write_str("no active transaction"),
318            Self::LockWouldBlock => f.write_str("row is locked by another transaction"),
319            Self::LockDeadlock => f.write_str("deadlock detected"),
320            Self::InFailedTransaction => f.write_str(
321                "current transaction is aborted, commands ignored until end of transaction block",
322            ),
323            Self::CardinalityViolation => {
324                f.write_str("more than one row returned by a subquery used as an expression")
325            }
326            Self::SerializationFailure(detail) => {
327                // v7.39 (round 552) — PG has TWO wordings under 40001 and
328                // they mean different things: "concurrent update" for a
329                // write-write conflict, "read/write dependencies among
330                // transactions" for the antidependency a SERIALIZABLE
331                // transaction hits. A detail that already carries PG's
332                // own sentence is passed through rather than nested
333                // inside the other one.
334                if detail.starts_with("could not serialize access") {
335                    f.write_str(detail)
336                } else {
337                    write!(
338                        f,
339                        "could not serialize access due to concurrent update: {detail}"
340                    )
341                }
342            }
343            Self::WriteRequired => {
344                f.write_str("statement requires a write lock (use execute, not execute_readonly)")
345            }
346            Self::RowLimitExceeded(n) => {
347                write!(f, "query exceeded max_query_rows={n}")
348            }
349            Self::QueryBytesExceeded(n) => {
350                write!(
351                    f,
352                    "query materialisation exceeded max_query_bytes={n} (set SPG_MAX_QUERY_BYTES to raise, 0 to disable)"
353                )
354            }
355            Self::Cancelled => f.write_str("query cancelled (timeout or client request)"),
356            Self::UnknownThreadId(id) => write!(f, "Unknown thread id: {id}"),
357            Self::ConnectionKilled => f.write_str("Connection was killed"),
358            Self::Internal(s) => write!(f, "internal error: {s}"),
359        }
360    }
361}
362
363impl From<ParseError> for EngineError {
364    fn from(e: ParseError) -> Self {
365        Self::Parse(e)
366    }
367}
368impl From<StorageError> for EngineError {
369    fn from(e: StorageError) -> Self {
370        Self::Storage(e)
371    }
372}
373impl From<EvalError> for EngineError {
374    fn from(e: EvalError) -> Self {
375        Self::Eval(e)
376    }
377}
378
379/// The execution engine. Holds the catalog and (later) other server-scope
380/// state. `Engine::new()` is intentionally cheap so callers can construct one
381/// per database, per test.
382/// Function pointer that returns "now" as microseconds since Unix
383/// epoch. The engine is `no_std`, so it can't reach for `std::time`
384/// itself — callers (`spg-server`, the sqllogictest runner) inject a
385/// concrete implementation. `None` means `NOW()` / `CURRENT_*` raise
386/// `Unsupported`.
387pub type ClockFn = fn() -> i64;
388
389/// Backing store for `SPG_TEST_FIXED_CLOCK_MICROS` (test-mode GUC).
390/// Only ever written when that GUC is set; production engines never
391/// touch it.
392static FIXED_CLOCK_MICROS: core::sync::atomic::AtomicI64 = core::sync::atomic::AtomicI64::new(0);
393
394fn fixed_clock_from_env() -> i64 {
395    FIXED_CLOCK_MICROS.load(core::sync::atomic::Ordering::Relaxed)
396}
397
398/// v7.39 (pg_stat knife A) — host-provided live connection count for
399/// `pg_stat_database.numbackends`.
400pub type BackendCountFn = fn() -> u32;
401
402/// v7.39 (read01 pgstatfuncs.c) — host-provided identity of the CALLING
403/// connection for `pg_backend_pid()` / the pg_stat_activity self-join.
404/// The host reads a connection-thread-local set at session start; the
405/// no_std engine just calls through. `None` (embedded) → pid 1.
406pub type BackendPidFn = fn() -> u32;
407
408/// v7.39 (round 476) — the WAL's current byte position, as a PG LSN.
409///
410/// `pg_current_wal_lsn()` answered the literal `0/0` forever, so every
411/// monitor watching WAL progress or replication lag saw an instance that
412/// had never written anything. SPG's WAL is a file and its length IS an
413/// LSN in every sense a monitor uses one: monotonic, byte-denominated, and
414/// comparable — `pg_wal_lsn_diff` over two samples gives real bytes.
415///
416/// `None` (embedded, or a server started without a WAL) keeps `0/0`, which
417/// is the honest answer there: nothing is being written.
418pub type WalLsnFn = fn() -> u64;
419
420/// v7.39 (round 318, V51) — host-provided connection control. `terminate`
421/// false = cancel the target's running statement (PG `pg_cancel_backend`,
422/// MySQL `KILL QUERY`); true = also close the connection (PG
423/// `pg_terminate_backend`, MySQL `KILL CONNECTION`). Returns whether a
424/// connection with that id exists — the engine has no registry of its own,
425/// so the answer has to come from the host that accepted the sockets.
426/// `None` (embedded, no connections) ⇒ nothing to signal.
427pub type BackendSignalFn = fn(pid: u32, terminate: bool) -> bool;
428
429pub use tempstore::{SpillStats, TempRun, TempRunFactory, TempStoreError};
430
431/// v7.39 (tz epic) — host-injected IANA timezone lookups (the no_std
432/// engine can't read the system zoneinfo directory; spg-tzif is the
433/// std-side implementation). All instants are MICROSECONDS.
434/// UTC offset (µs east) of a zone at a UTC instant; None = unknown zone.
435/// v7.39 (round 534) — the compiled-in default PG18 reports for a
436/// configuration parameter, for the wire's own SHOW shortcut.
437///
438/// The pgwire layer answers `SHOW <name>` from a small canned list
439/// before the statement ever reaches the engine, so it needs the same
440/// inventory the engine reads or the two disagree — which they did:
441/// `SHOW fsync` over the wire returned an empty row.
442#[must_use]
443pub fn pg_guc_boot_value(name: &str) -> Option<&'static str> {
444    crate::guc_catalog::guc_boot_value(name)
445}
446
447pub type TzOffsetFn = fn(&str, i64) -> Option<i64>;
448/// Local wall-clock µs -> UTC µs with PG's DST disambiguation.
449pub type TzLocalizeFn = fn(&str, i64) -> Option<i64>;
450/// Canonical zone spelling ("asia/tokyo" -> "Asia/Tokyo").
451pub type TzCanonFn = fn(&str) -> Option<alloc::string::String>;
452/// Zone designation ("JST", "EDT") at a UTC instant.
453pub type TzAbbrevFn = fn(&str, i64) -> Option<alloc::string::String>;
454/// v7.39 (round 502) — every zone the host knows at a UTC instant, as
455/// `(name, abbrev, utc_offset_secs, is_dst)`.
456///
457/// Backs `pg_timezone_names`. SPG resolved named zones correctly — round
458/// 502 measured DST boundaries byte-identical to PG18 — but could not
459/// LIST them, so a client populating a timezone picker got "relation
460/// pg_timezone_names does not exist". The data was there, only
461/// unlistable. No hook, or a host with no tzdata, yields an empty view
462/// rather than an error: that is what such a host honestly has.
463pub type TzAllFn =
464    fn(i64) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String, i64, bool)>;
465
466/// v7.39 (tz epic) — per-statement snapshot of the session TimeZone,
467/// consumed per-VALUE by the timestamptz renderers (a DST zone's
468/// offset depends on the instant being rendered).
469#[derive(Debug, Clone)]
470pub enum SessionTz {
471    Utc,
472    /// Fixed offset, µs east.
473    Fixed(i64),
474    /// IANA zone + the host lookups.
475    Named(alloc::string::String, TzOffsetFn, TzAbbrevFn),
476}
477
478impl SessionTz {
479    #[must_use]
480    pub fn is_utc(&self) -> bool {
481        matches!(self, Self::Utc) || matches!(self, Self::Fixed(0))
482    }
483
484    /// Offset (µs east) at a UTC instant.
485    #[must_use]
486    pub fn offset_at(&self, utc_micros: i64) -> i64 {
487        match self {
488            Self::Utc => 0,
489            Self::Fixed(off) => *off,
490            Self::Named(zone, f, _) => f(zone, utc_micros).unwrap_or(0),
491        }
492    }
493
494    /// Designation for the non-ISO DateStyle suffix: a named zone's
495    /// abbreviation at the instant; None for UTC/fixed (callers spell
496    /// "UTC" / "+09" themselves).
497    #[must_use]
498    pub fn abbrev_at(&self, utc_micros: i64) -> Option<alloc::string::String> {
499        match self {
500            Self::Named(zone, _, f) => f(zone, utc_micros),
501            _ => None,
502        }
503    }
504}
505
506/// Function pointer that produces 16 cryptographically random bytes.
507/// Like `ClockFn`, the engine is `no_std` and can't reach for /dev/urandom
508/// itself — host (`spg-server`) injects an OS-backed source. `None`
509/// means SQL-driven `CREATE USER` falls back to a deterministic salt
510/// derived from the username (acceptable in tests; the server always
511/// installs a real RNG so production paths never see this).
512pub type SaltFn = fn() -> [u8; 16];
513
514/// v4.5 cooperative cancellation token. A long-running SELECT /
515/// UPDATE / DELETE checks `is_cancelled` at row-loop checkpoints
516/// and bails with `EngineError::Cancelled`. The host
517/// (`spg-server`) creates an `AtomicBool` per query, spawns a
518/// watchdog thread that sets it after `SPG_QUERY_TIMEOUT_MS`,
519/// and passes it via `execute_with_cancel` / `execute_readonly_with_cancel`.
520///
521/// `CancelToken::none()` is a no-op — used by the legacy `execute`
522/// and `execute_readonly` entry points so existing callers don't
523/// change.
524/// v4.41.1 opaque transaction handle. Returned by `Engine::alloc_tx_id`,
525/// threaded through `Engine::execute_in` so dispatch can identify which
526/// in-flight TX a statement belongs to. `IMPLICIT_TX` is the reserved
527/// slot every legacy caller — engine self-tests, spg-cli, spg-embedded,
528/// startup replay — implicitly uses through the unchanged
529/// `Engine::execute(sql)` API. v4.41.1 keeps at most one active slot at
530/// runtime (dispatch holds `engine.write()` across the wrap, same as
531/// v4.34); the map shape is here to let v4.42 turn on N in-flight
532/// implicit TXs without reshuffling the engine internals.
533#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
534pub struct TxId(pub u64);
535
536/// Reserved slot used by `Engine::execute(sql)` — the legacy single-
537/// global-shadow path. New `alloc_tx_id` handles start at 1.
538pub const IMPLICIT_TX: TxId = TxId(0);
539
540/// v6.7.3 — default segment-size threshold used by `COMPACT COLD
541/// SEGMENTS` when no explicit target is supplied. Segments whose
542/// `OwnedSegment::bytes().len()` is **strictly** less than this
543/// value are eligible to merge. spg-server reads
544/// `SPG_COMPACTION_TARGET_SEGMENT_BYTES` to override.
545pub const COMPACTION_TARGET_DEFAULT_BYTES: u64 = 4 * 1024 * 1024;
546
547/// Per-slot transaction state. Held inside `tx_catalogs[tx_id]` for the
548/// lifetime of a BEGIN..COMMIT (or BEGIN..ROLLBACK) window. Drops when
549/// the TX commits (its `catalog` is moved over `Engine.catalog`) or
550/// rolls back (slot removed, catalog discarded).
551#[derive(Debug, Default, Clone)]
552struct TxState {
553    /// The TX's shadow copy of the catalog. Started as a clone of
554    /// `Engine.catalog` at BEGIN time; writes flow into it; COMMIT
555    /// installs it over `Engine.catalog`. `Catalog::clone()` is O(1)
556    /// since v4.40 (`PersistentVec` rows + `PersistentBTreeMap` indices).
557    catalog: Catalog,
558    /// v7.37 (round 828) — the TX's shadow copy of the user store,
559    /// following exactly the catalog's model one field up: created
560    /// lazily by the first role DDL inside the TX (an ordinary TX
561    /// never pays the clone), written through for the rest of the TX,
562    /// installed over `Engine.users` at COMMIT, discarded on ROLLBACK.
563    /// PG treats roles as ordinary catalog rows — `BEGIN; CREATE ROLE
564    /// r; ROLLBACK` leaves no role — and SPG used to refuse the
565    /// statement instead, which no drop-in client expects.
566    ///
567    /// Other sessions and the auth path keep reading the committed
568    /// store, so an uncommitted role can neither log in nor be seen
569    /// elsewhere — the isolation PG gives via its catalog MVCC.
570    users: Option<crate::users::UserStore>,
571    /// Per-TX savepoint stack. Each entry pairs the savepoint name with
572    /// a clone of `catalog` (and of the role shadow, which subtransactions
573    /// roll back too) at the moment `SAVEPOINT <name>` fired.
574    /// `ROLLBACK TO <name>` restores from the entry and pops everything
575    /// after it; `RELEASE <name>` discards the entry and everything
576    /// after; COMMIT/ROLLBACK clears the whole stack.
577    savepoints: Vec<(String, Catalog, Option<crate::users::UserStore>)>,
578    /// v7.37.15 (Phase E) — cached MVCC snapshot for REPEATABLE
579    /// READ / SERIALIZABLE. Captured at `exec_begin` time when the
580    /// session's `current_isolation_level` is RR/SER; read paths
581    /// inside the TX use this snapshot rather than calling
582    /// `Engine::current_snapshot` per statement, so a row that
583    /// becomes visible mid-tx (because another writer committed)
584    /// is NOT exposed to this tx — preserving RR's invariant.
585    ///
586    /// `None` for READ COMMITTED (default): each statement gets a
587    /// fresh snapshot via `current_snapshot()`.
588    cached_snapshot: Option<spg_storage::snapshot::Snapshot>,
589    /// v7.37.17 (Phase E2 — RC rebase) — tables this tx has run DML
590    /// against. The per-statement rebase extracts/replays write-sets
591    /// only for these (see `maybe_rc_rebase`).
592    touched_tables: alloc::collections::BTreeSet<String>,
593    /// v7.39 (round 552) — tables this tx has READ. PG's SIREAD locks,
594    /// at table granularity: the coarse end of the same idea, and what
595    /// PG itself falls back to when its per-tuple lock memory runs out.
596    ///
597    /// A SERIALIZABLE tx aborts at COMMIT if any table it read was
598    /// written by a transaction that committed after its snapshot —
599    /// the read/write antidependency SI cannot see. Coarse granularity
600    /// means SPG aborts some transactions PG would let through; it
601    /// never lets through one PG would abort.
602    read_tables: alloc::collections::BTreeSet<String>,
603    /// v7.39 (round 552) — was THIS transaction opened SERIALIZABLE?
604    ///
605    /// `Engine::current_isolation_level` is one field for the whole
606    /// engine, not part of the per-session bag, so with two connections
607    /// open one transaction's COMMIT resets it under the other's feet —
608    /// the shared-engine leak rounds 279 and 283 chased through session
609    /// state and advisory locks. The level a transaction runs at has to
610    /// live on the transaction.
611    serializable: bool,
612    /// The engine's commit sequence when this tx began.
613    begin_commit_seq: u64,
614    /// v7.39 (round 494) — has anything asked for this shadow catalog
615    /// MUTABLY since BEGIN?
616    ///
617    /// COMMIT installs the shadow over the committed catalog, so a
618    /// transaction that changed nothing must install nothing — otherwise
619    /// it reverts whatever other sessions committed while it was open.
620    /// `touched_tables` cannot answer this: it records DML targets for the
621    /// rebase, and a `SELECT lo_write(…)` classifies read-only while
622    /// mutating (the large-object pins caught exactly that).
623    ///
624    /// Set in `active_catalog_mut`, the single place a `&mut Catalog` is
625    /// handed out. A caller that takes the mutable handle without writing
626    /// merely keeps the old install behaviour, so the flag errs toward
627    /// installing.
628    shadow_dirty: bool,
629    /// v7.39 (round 298) — this transaction is in the aborted state.
630    ///
631    /// Per SLOT. It used to be one flag on the shared `Engine`, guarded
632    /// by `in_transaction()` — the GLOBAL "is any transaction open"
633    /// test. So an autocommit statement that failed while a DIFFERENT
634    /// connection happened to hold a transaction set the flag, and
635    /// every other connection was then refused with 25P02. Round 283
636    /// fixed seven sites of this exact shape in the server; this one is
637    /// in the engine and was missed.
638    aborted: bool,
639    /// v7.39 (round 288) — `SET CONSTRAINTS … {DEFERRED|IMMEDIATE}`
640    /// override for this transaction. `None` = each constraint uses
641    /// its own declared timing; `Some(true)` = every DEFERRABLE one is
642    /// deferred; `Some(false)` = every one is immediate.
643    constraints_deferred: Option<bool>,
644    /// v7.39 (round 308) — per-constraint overrides from the NAMED form
645    /// of `SET CONSTRAINTS`. Consulted before `constraints_deferred`, so
646    /// `ALL DEFERRED` followed by `fk_a IMMEDIATE` leaves fk_a immediate
647    /// and everything else deferred. An `ALL` form clears this map,
648    /// which is what makes a later blanket setting win — PG resets the
649    /// whole set the same way.
650    constraints_deferred_by_name: BTreeMap<String, bool>,
651    /// v7.37.17 — the tx executed a statement whose effect on the
652    /// shadow catalog can't be expressed as a versioned row write-set
653    /// (DDL, COPY, anything unclassified). The rebase would lose it,
654    /// so the tx degrades to its frozen BEGIN-time view (SI) for the
655    /// rest of its life — the pre-E2 behaviour, honestly kept.
656    rebase_poisoned: bool,
657    /// v7.37.17 — statements successfully run inside this tx. The
658    /// first statement sees the BEGIN-time clone unchanged (it IS the
659    /// latest base at that point); rebasing starts from the second.
660    stmts_run: u32,
661    /// v7.39 (round 196) — the engine `commit_epoch` this tx last
662    /// rebased against (BEGIN seeds it). When the epoch hasn't moved,
663    /// no other path committed to the base catalog, so the
664    /// per-statement RC rebase — whose write-set extraction is a full
665    /// scan of every touched table — is skipped entirely. The r196
666    /// wire panel traced tx_batch's 2.8× LOSS to exactly that scan
667    /// running before EVERY in-tx statement (~200 µs/stmt on a
668    /// 20k-row table, 58× the statement itself). Over-incrementing
669    /// the epoch is safe (an extra rebase is only slower, never
670    /// wrong); missing an increment would be a correctness bug, so
671    /// the epoch bumps on every completed non-tx statement.
672    rebased_at_epoch: u64,
673    /// v7.37.17 (Phase E4 fix) — (old RowId → new RowId) pairs recorded
674    /// by every in-place UPDATE this tx ran, keyed by table (RowIds are
675    /// per-relation). An UPDATE's write-set is tombstone(old) +
676    /// insert(new); when a rebase skips a CONFLICTING tombstone (the
677    /// row was updated/deleted by a concurrently-committed tx), the
678    /// paired insert must be dropped too — otherwise the row
679    /// DUPLICATES (caught by the E4 isolation matrix).
680    update_pairs: alloc::collections::BTreeMap<
681        String,
682        Vec<(
683            spg_storage::row_header::RowId,
684            spg_storage::row_header::RowId,
685        )>,
686    >,
687}
688
689/// v7.11.0 — frozen read-only view of the engine's committed state.
690/// Constructed via [`Engine::clone_snapshot`]. Holds clones of the
691/// catalog, statistics, clock function, and row-cap config — the
692/// four fields the `execute_readonly` path actually reads. Cheap to
693/// `Clone` (each clone shares the underlying `PersistentVec` row
694/// storage; only the trie root pointers copy). Send + Sync so a
695/// snapshot can be moved across `tokio::task::spawn_blocking`
696/// boundaries without coordination.
697///
698/// The contract: a snapshot reflects the engine's state at the
699/// moment `clone_snapshot()` returned. Subsequent writes to the
700/// engine are NOT visible. Callers who need fresher data take a
701/// new snapshot.
702#[derive(Debug, Clone)]
703pub struct CatalogSnapshot {
704    catalog: Catalog,
705    statistics: statistics::Statistics,
706    clock: Option<ClockFn>,
707    max_query_rows: Option<usize>,
708}
709
710/// CoW-1 (v7.34) — frozen view of the *persisted* committed engine
711/// state. Carries every field the `snapshot()` envelope serializes;
712/// v7.39 (round 279) — the per-CONNECTION state, parked while another
713/// connection holds the engine.
714///
715/// The server runs ONE shared `Engine` behind a `RwLock`
716/// (`ServerState.engine`, built once at startup), so everything the
717/// engine called "session state" was in fact process-wide and leaked
718/// between clients: two connections saw each other's prepared
719/// statements, and one client's `SET sql_mode` re-dialected another's
720/// string literals. PG scopes all of this per session.
721///
722/// Rather than thread a session handle through every call site, the
723/// engine keeps the ACTIVE session's state in its own fields — so the
724/// ~40 existing `self.session_params` / `self.backslash_escapes` uses
725/// are untouched — and swaps the whole bag when the caller announces a
726/// different session. Embedded hosts never announce one and stay on
727/// session 0 forever, exactly as before.
728#[derive(Debug, Default)]
729pub(crate) struct SessionBag {
730    pub(crate) session_params: BTreeMap<String, String>,
731    pub(crate) backslash_escapes: bool,
732    /// v7.39 (round 470) — is the MySQL session in a strict `sql_mode`?
733    ///
734    /// MariaDB's default includes `STRICT_TRANS_TABLES`, so this starts
735    /// true; `SET sql_mode=''` (or any list without a STRICT_ flag) turns
736    /// it off and a value that would otherwise raise is bent to fit
737    /// instead — the same conversion `INSERT IGNORE` uses.
738    pub(crate) mysql_strict: bool,
739    pub(crate) prepared_statements: BTreeMap<String, PreparedSqlStatement>,
740    /// v7.39 (round 499) — the value `nextval` last returned IN THIS
741    /// SESSION, per sequence, and which sequence that was.
742    ///
743    /// PG defines `currval` and `lastval` as session-local: they answer
744    /// the number THIS session was given, and error with 55000 ("not yet
745    /// defined in this session") when it has not called `nextval`. They
746    /// are deliberately not the sequence's current value — another
747    /// session may have advanced it since, and reading that would hand
748    /// back a number this session never owned, which is what a caller
749    /// then uses as a foreign key.
750    ///
751    /// Measured before this (`iso_session` T1/T2): `currval` answered in
752    /// a connection that had never called `nextval`, and `lastval`
753    /// answered across connections, because the tracking lived on the
754    /// shared engine rather than in the bag.
755    pub(crate) seq_currvals: BTreeMap<String, i64>,
756    pub(crate) last_sequence_used: Option<String>,
757    /// v7.39 (round 553) — the isolation level THIS connection is
758    /// running at.
759    ///
760    /// It lived on the shared engine, so it leaked both ways between
761    /// connections. Measured over pgwire against PG18: connection B
762    /// opened a plain BEGIN and `SHOW transaction_isolation` answered
763    /// `serializable` — A's level; and A, still inside its SERIALIZABLE
764    /// block, then read `read committed`, because B's COMMIT reset the
765    /// field under it. PG answers `read committed` and `serializable`
766    /// throughout. So a transaction that asked for SERIALIZABLE ran at
767    /// READ COMMITTED and one that asked for nothing ran at
768    /// SERIALIZABLE, purely because another connection was busy.
769    ///
770    /// Round 552 saw the same field give way and worked around it by
771    /// putting the level on the TRANSACTION; this puts the session's
772    /// own copy where the rest of its state already lives — the place
773    /// r306's comment says every piece of per-connection state belongs
774    /// so it never gets a process-wide version to regress from.
775    pub(crate) isolation_level: spg_sql::ast::IsolationLevel,
776    /// v7.39 (round 306) — open large-object descriptors. Per session
777    /// from the start, deliberately: r277/r279/r283 each landed a piece
778    /// of per-connection state on the process-wide engine first and had
779    /// to be unpicked afterwards, so this one never gets a process-wide
780    /// version to regress from. PG additionally scopes descriptors to
781    /// the transaction, so the table is emptied at COMMIT / ROLLBACK.
782    pub(crate) lo_descriptors: BTreeMap<i32, LargeObjectDescriptor>,
783    /// Next descriptor number to hand out. PG starts at 0 and counts up
784    /// within a transaction, restarting once the transaction ends.
785    pub(crate) lo_next_fd: i32,
786    /// v7.39 (round 321, V54) — open server-side cursors. They lived on
787    /// the shared engine until now, i.e. in ONE namespace for every
788    /// connection: two clients could not both `DECLARE c`, a `FETCH`
789    /// could read another client's rows, and `CLOSE ALL` closed
790    /// everybody's.
791    pub(crate) cursors: BTreeMap<String, cursor::OpenCursor>,
792    /// v7.39 (round 347, M2) — MySQL's `LAST_INSERT_ID()`. Per SESSION
793    /// from the start (r277/r279/r283 each paid for landing per-connection
794    /// state on the shared engine first): one connection's insert must not
795    /// be readable as another's. MariaDB, measured: a fresh session reads
796    /// 0; an insert that generates an AUTO_INCREMENT value sets it to the
797    /// FIRST one generated; a statement that generates none — an explicit
798    /// id, an UPDATE, a DELETE, a plain table — leaves it alone.
799    pub(crate) last_insert_id: i64,
800    /// v7.39 (round 426) — MySQL's `ROW_COUNT()`. Per SESSION like
801    /// `last_insert_id`. MariaDB, measured: a DML statement leaves the
802    /// number of rows it CHANGED (an UPDATE that matched but changed
803    /// nothing leaves 0); a SELECT leaves -1; DDL leaves 0. A FRESH
804    /// session reads 0 (measured), not -1.
805    pub(crate) row_count: i64,
806    /// v7.39 (round 430) — MySQL USER variables (`SET @x = 5`). Per
807    /// SESSION like `last_insert_id` / `row_count`; its own namespace,
808    /// separate from the `@@` session parameters. Reading an unset one
809    /// answers NULL, as MariaDB does.
810    pub(crate) user_vars: BTreeMap<String, spg_storage::Value<'static>>,
811    /// v7.39 (round 436) — the logical names of this session's TEMPORARY
812    /// tables. Each is stored in the catalog under a per-session prefix; this
813    /// set is what says "resolve `t` to my temp one" and what `end_session`
814    /// walks to drop them.
815    pub(crate) temp_tables: alloc::collections::BTreeSet<String>,
816    /// v7.39 (round 469) — the session's TEMPORARY sequences and views, by
817    /// logical name. Separate sets because dropping one at session end has
818    /// to name the catalog map it lives in.
819    pub(crate) temp_sequences: alloc::collections::BTreeSet<String>,
820    pub(crate) temp_views: alloc::collections::BTreeSet<String>,
821}
822
823/// v7.39 (round 306) — one open large-object descriptor.
824#[derive(Debug, Clone, Copy)]
825pub(crate) struct LargeObjectDescriptor {
826    pub(crate) oid: u32,
827    /// Byte offset the next read / write starts at.
828    pub(crate) pos: u64,
829    /// Whether the descriptor was opened with `INV_WRITE`. Reads need no
830    /// permission at all in PG — a write-only descriptor reads fine —
831    /// so only this half is worth remembering.
832    pub(crate) writable: bool,
833}
834
835/// v7.39 (round 277) — one SQL-level prepared statement.
836#[derive(Debug, Clone)]
837pub(crate) struct PreparedSqlStatement {
838    /// The body with its `$N` placeholders still in place.
839    pub(crate) body: spg_sql::ast::Statement,
840    /// Declared parameter type names, in order; empty when PG would
841    /// have inferred them.
842    pub(crate) param_types: alloc::vec::Vec<String>,
843    /// The whole `PREPARE …` text, which `pg_prepared_statements`
844    /// reports verbatim.
845    pub(crate) source: String,
846}
847
848/// `Clone` is O(1) on the catalog (Arc bump) and cheap typed-clones
849/// on the trailers. Decouples "capture state" from "serialize bytes"
850/// so the background-checkpoint worker can hold the snapshot and
851/// produce bytes off the engine write lock.
852#[derive(Debug, Clone)]
853pub struct EngineSnapshot {
854    catalog: Catalog,
855    users: UserStore,
856    publications: publications::Publications,
857    subscriptions: subscriptions::Subscriptions,
858    statistics: statistics::Statistics,
859}
860
861impl EngineSnapshot {
862    /// Same envelope rules as `Engine::snapshot()`: bare catalog when
863    /// every trailer is empty, full envelope otherwise.
864    pub fn serialize(&self) -> Vec<u8> {
865        if self.users.is_empty()
866            && self.publications.is_empty()
867            && self.subscriptions.is_empty()
868            && self.statistics.is_empty()
869        {
870            self.catalog.serialize()
871        } else {
872            build_envelope(
873                &self.catalog.serialize(),
874                &users::serialize_users(&self.users),
875                &self.publications.serialize(),
876                &self.subscriptions.serialize(),
877                &self.statistics.serialize(),
878            )
879        }
880    }
881}
882
883/// v7.39 (parallel-agg P0) — host-injected parallel executor. The
884/// engine is `no_std` and cannot spawn threads; like `ClockFn` /
885/// `RandomFn`, the std-side host (spg-server / embedded-tokio)
886/// injects an implementation at startup. `None` (the default, and
887/// the only option in pure-`no_std` embeddings) keeps every code
888/// path single-threaded and byte-identical to pre-P0 behaviour.
889///
890/// The callback returns `Box<dyn Any + Send>` so one trait serves
891/// any shard-result type; call sites downcast what they produced.
892pub trait ParallelRunner: Send + Sync {
893    /// Run `f(0) .. f(n-1)`, possibly concurrently; return the
894    /// results in shard order. Every call completes before return.
895    fn run_shards(
896        &self,
897        n: usize,
898        f: &(dyn Fn(usize) -> alloc::boxed::Box<dyn core::any::Any + Send> + Sync),
899    ) -> alloc::vec::Vec<alloc::boxed::Box<dyn core::any::Any + Send>>;
900}
901
902/// Engine slot for the injected runner — a newtype so the `Engine`
903/// derive(Debug) keeps working over the non-Debug trait object.
904#[derive(Clone, Default)]
905pub struct ParallelRunnerSlot(pub(crate) Option<alloc::sync::Arc<dyn ParallelRunner>>);
906
907impl core::fmt::Debug for ParallelRunnerSlot {
908    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
909        f.write_str(if self.0.is_some() {
910            "ParallelRunner(<injected>)"
911        } else {
912            "ParallelRunner(none)"
913        })
914    }
915}
916
917/// v7.39 (parallel-agg P0) — below this many input rows a query
918/// never parallelises: thread spin-up beats the win on small scans.
919pub(crate) const PARALLEL_MIN_ROWS: usize = 100_000;
920
921/// v7.39 — diagnostic counter: how many aggregate scans took the
922/// sharded path (read by benches to ground-truth activation).
923/// v7.39 (round 740) — matview delta ground-truth counters (the r735
924/// lesson: a green content pin cannot distinguish "delta applied" from
925/// "silently fell back to full"; these can).
926pub static MATVIEW_FANOUT_BUFFERED: core::sync::atomic::AtomicU64 =
927    core::sync::atomic::AtomicU64::new(0);
928pub static MATVIEW_DELTA_APPLIED: core::sync::atomic::AtomicU64 =
929    core::sync::atomic::AtomicU64::new(0);
930pub static MATVIEW_DELTA_BAILED: core::sync::atomic::AtomicU64 =
931    core::sync::atomic::AtomicU64::new(0);
932pub static PARALLEL_AGG_FIRED: core::sync::atomic::AtomicU64 =
933    core::sync::atomic::AtomicU64::new(0);
934
935// The engine carries several independent session/capture flags (dialect,
936// FK-checks, meta-view materialisation, redo capture); they're orthogonal
937// switches, not a state enum begging to be modelled.
938#[allow(clippy::struct_excessive_bools)]
939#[derive(Debug, Default)]
940pub struct Engine {
941    /// v7.39 (parallel-agg P0) — see [`ParallelRunner`].
942    pub(crate) parallel_runner: ParallelRunnerSlot,
943    /// Committed catalog — what survives `Engine::snapshot()` and what
944    /// outside-TX `SELECT`s read.
945    catalog: Catalog,
946    /// Active TX slots, keyed by `TxId`. Empty when no TX is in flight.
947    /// v4.41.1 runtime invariant: at most one entry (single-writer
948    /// model unchanged). v4.42 will let dispatch hold multiple entries
949    /// concurrently for group commit + engine MVCC.
950    tx_catalogs: BTreeMap<TxId, TxState>,
951    /// v7.39 (round 552) — the COMMIT SEQUENCE at which each table was
952    /// last written. Commit order, not begin order: a transaction that
953    /// began first can commit last, so the writer version allocated at
954    /// BEGIN cannot answer "did this change after I read it".
955    table_last_commit: BTreeMap<String, u64>,
956    /// Monotonic, bumped once per successful COMMIT.
957    commit_seq: u64,
958    /// Which slot the next exec_* call should mutate. Set by
959    /// `execute_in(sql, tx_id)` at the entry point; legacy `execute(sql)`
960    /// sets it to `IMPLICIT_TX`. None when no TX is in flight (read /
961    /// write goes straight against `catalog`).
962    current_tx: Option<TxId>,
963    /// Monotonic counter for `alloc_tx_id`. Starts at 1 — slot 0 is
964    /// reserved for `IMPLICIT_TX`.
965    next_tx_id: u64,
966    /// v7.37.15 (Phase C) — versions allocated by in-flight
967    /// writers. Snapshot construction folds this into the
968    /// `Snapshot.in_progress` set so concurrent readers (or readers
969    /// inside an older snapshot's REPEATABLE READ) don't see
970    /// uncommitted writes.
971    ///
972    /// SPG's single-writer invariant means at most one writer
973    /// version sits here at any moment (the one currently
974    /// executing inside the engine write lock). The set survives
975    /// engine clones because tx-commit removes versions before the
976    /// `Engine::snapshot_data` returns, so a snapshot taken after
977    /// commit observes an empty set.
978    ///
979    /// `BTreeSet` (not Vec) so iteration is sorted — Snapshot
980    /// constructor expects the input sorted for binary-search
981    /// `contains` correctness.
982    active_writer_versions: BTreeSet<u64>,
983    /// v7.37.15 (Phase C.2) — writer versions that ABORTED (rolled
984    /// back). The engine-side visibility oracle ([`Self::xact_status`])
985    /// consults this to report `Aborted` for a version that left the
986    /// in-flight set via rollback rather than commit — the third state
987    /// the abort-aware [`spg_storage::snapshot::Snapshot::visible_with_status`]
988    /// needs once Phase C.3's in-place writes leave aborted stamps in
989    /// place. Pruned below `oldest_active` by vacuum (Phase D); until
990    /// then it grows only with rolled-back transactions (a never-die
991    /// follow-up, not a commit-path leak).
992    aborted_versions: BTreeSet<u64>,
993    /// v7.37.15 (Phase C.4) — row-level lock table keyed on stable
994    /// `(RelId, RowId)`. The in-place write path (C.3) acquires a
995    /// tuple lock before stamping xmax; `exec_commit` / `exec_rollback`
996    /// release the whole transaction's locks at end. No writer acquires
997    /// yet at this commit — the field + delegating methods are the
998    /// plumbing the write path consumes next. Rides on `Engine` like
999    /// `active_writer_versions`; the sharded lock-free manager is C.5.
1000    locks: crate::locks::LockTable,
1001    /// v7.37.15 (Phase C.3) — kill switch for the in-place MVCC write
1002    /// path. `false` (default) = legacy physical semantics (DELETE
1003    /// physically removes the row, UPDATE replaces in place). `true` =
1004    /// the C.3 write path (DELETE tombstones via `mark_row_deleted`,
1005    /// UPDATE tombstones the old version + appends the new one, both
1006    /// keeping dead versions physically present for the now-uniformly-
1007    /// gated readers until vacuum reclaims them). `no_std` engine can't
1008    /// read env; the host (spg-server / spg-embedded) reads
1009    /// `SPG_MVCC_INPLACE` and calls [`Self::set_mvcc_inplace`]. Off
1010    /// until the write path + PG18 differential tests are proven.
1011    mvcc_inplace: bool,
1012    /// v7.37.16 — threshold-triggered synchronous vacuum at DML statement
1013    /// exit (autovacuum-lite; see .claude/state/autovacuum-design.md).
1014    /// Default ON; hosts may disable via `SPG_AUTOVACUUM=0`.
1015    autovacuum: bool,
1016    /// v7.39 (round 173) — whether the statement-exit trigger runs the
1017    /// vacuum **inline**. Default ON (embedded: single-threaded host,
1018    /// the statement path is the only place work can happen). A host
1019    /// with a background autovacuum worker (spg-server) flips this off
1020    /// and drives [`Self::autovacuum_tick`] from its own thread instead
1021    /// — PG's shape, where autovacuum never runs inside a client
1022    /// statement. Only meaningful while `autovacuum` itself is on.
1023    autovacuum_inline: bool,
1024    /// v7.37.15 (Phase C) — TxId → writer version registry. When
1025    /// `exec_begin` opens an explicit transaction it allocates a
1026    /// fresh writer version (via [`Self::begin_writer_version`])
1027    /// and stashes the mapping here so the matching `exec_commit`
1028    /// / `exec_rollback` can call
1029    /// [`Self::commit_writer_version`] on the right entry. Empty
1030    /// when no explicit transactions are open.
1031    /// v7.39 (round 295, E3 Phase 1b) — rows a `SKIP LOCKED` pass found
1032    /// held by another transaction. Set by the locking pre-pass and
1033    /// consulted by the base scan, which is READ-only here: the locks
1034    /// themselves were taken under `&mut self` in the pre-pass, so the
1035    /// `&self` scan never mutates the lock table. (A `RefCell` there
1036    /// would cost `Engine: Sync`, which the server's `RwLock<Engine>`
1037    /// needs — see the RFC's §5.6.)
1038    pub(crate) lock_skip_rows: Option<(String, alloc::collections::BTreeSet<usize>)>,
1039    tx_writer_versions: BTreeMap<TxId, u64>,
1040    /// v7.37.15 (Epic W slice 2) — the current statement's autocommit
1041    /// writer version, memoized. In autocommit
1042    /// [`Self::writer_version_for_current_stmt`] mints a fresh version
1043    /// via `next_version()` (a `fetch_add`), so calling it a second
1044    /// time — e.g. when the redo drain post-stamps `RowChange`s —
1045    /// would allocate a *different* number than the writes actually
1046    /// used. Memoizing the first allocation for the duration of one
1047    /// statement makes the drain stamp read back the exact version the
1048    /// rows were written with, without advancing the counter twice.
1049    /// `None` outside a statement / before the first fetch; saved and
1050    /// reset per `execute_in_with_cancel` so it never leaks across
1051    /// statements. Explicit transactions bypass this (their version is
1052    /// the deterministic `tx_writer_versions` entry).
1053    stmt_writer_version: Option<u64>,
1054    /// v7.22 (round-13 T3) — session string-literal dialect. `false`
1055    /// (default) = PG semantics (backslash literal, `''` escape);
1056    /// `true` = MySQL semantics (`\'` etc.). Flipped by the
1057    /// deterministic session signals each dump emits: `SET sql_mode`
1058    /// (only MySQL clients/dumps send it) turns it on,
1059    /// `SET standard_conforming_strings = on` (every pg_dump
1060    /// preamble) turns it off. The plan cache is cleared on every
1061    /// flip — the same SQL text lexes differently per dialect.
1062    backslash_escapes: bool,
1063    /// v7.39 (round 470) — see [`SessionBag::mysql_strict`].
1064    mysql_strict: bool,
1065    /// v7.39 (round 306) — the live session's open large-object
1066    /// descriptors, swapped in and out with the rest of its bag.
1067    pub(crate) lo_descriptors: BTreeMap<i32, LargeObjectDescriptor>,
1068    pub(crate) lo_next_fd: i32,
1069    /// v7.37.17 — name of the sequence most recently advanced by
1070    /// nextval() in this Engine (session). Backs PG's lastval().
1071    /// None until the first nextval; PG errors in that state.
1072    last_sequence_used: Option<String>,
1073    /// v7.39 (round 499) — per-session `currval` values; see
1074    /// [`SessionBag::seq_currvals`].
1075    seq_currvals: alloc::collections::BTreeMap<String, i64>,
1076    /// v7.39 (round 277) — SQL-level prepared statements, session
1077    /// scoped exactly as in PG. Keyed by name; each entry keeps the
1078    /// parsed body (placeholders intact), the declared parameter type
1079    /// names and the statement text `pg_prepared_statements` reports.
1080    prepared_statements: alloc::collections::BTreeMap<String, PreparedSqlStatement>,
1081    /// v7.39 (round 279) — which connection's state is currently
1082    /// installed in the fields above. 0 is the embedded / default
1083    /// session.
1084    current_session: u32,
1085    /// Parked state for every OTHER connection.
1086    sessions: BTreeMap<u32, SessionBag>,
1087    /// v7.39 (round 279) — advisory locks, held ACROSS sessions and so
1088    /// deliberately NOT part of the swapped bag: the whole purpose of
1089    /// an advisory lock is to be visible to the other connection.
1090    /// key → (owning session, re-entrant depth). PG allows the same
1091    /// session to take a lock it already holds.
1092    advisory_locks: BTreeMap<i64, (u32, u32)>,
1093    /// Optional wall clock used to satisfy `NOW()` / `CURRENT_TIMESTAMP`
1094    /// / `CURRENT_DATE`. Set by the host environment.
1095    clock: Option<ClockFn>,
1096    /// v4.1 cryptographic RNG for per-user password salt. Set by the
1097    /// host. `None` means SQL-driven `CREATE USER` uses a
1098    /// deterministic fallback — see `SaltFn`.
1099    salt_fn: Option<SaltFn>,
1100    /// v4.2 per-query row cap. `None` = unlimited. When set, a
1101    /// SELECT that materialises more than `n` rows returns
1102    /// `EngineError::RowLimitExceeded`. Enforced before the result
1103    /// is shaped into wire frames so a runaway scan can't blow the
1104    /// server's heap.
1105    max_query_rows: Option<usize>,
1106    /// v7.30.3 (mailrs round-26) per-query byte cap on join/filter
1107    /// materialisation. `None` = unlimited. Approximate net
1108    /// accounting (Value heap payloads + per-cell enum overhead)
1109    /// charged at every point the join pipeline clones rows;
1110    /// crossing the cap raises `EngineError::QueryBytesExceeded`
1111    /// instead of pressuring the host into reclaim livelock. The
1112    /// host wires this to `SPG_MAX_QUERY_BYTES` (embed defaults it
1113    /// ON; the server keeps its allocator-precise budget as the
1114    /// outer layer).
1115    pub(crate) max_query_bytes: Option<usize>,
1116    /// v7.39 (round 786, T35 Phase A) — host factory for spill runs.
1117    /// `None` (the default, and every embedded caller that has not opted
1118    /// in) keeps today's behaviour exactly: a sort that outgrows
1119    /// `max_query_bytes` still refuses rather than spilling.
1120    pub(crate) temp_run_factory: Option<crate::TempRunFactory>,
1121    /// v4.1 RBAC user table. Empty means "no RBAC configured yet" —
1122    /// the server decides what that means at the auth boundary
1123    /// (open mode vs legacy single-password mode). User CRUD goes
1124    /// through `create_user`/`drop_user`/`verify_user`; persistence
1125    /// rides the snapshot envelope alongside the catalog.
1126    pub(crate) users: UserStore,
1127    /// v6.1.2 logical-replication publication catalog. Empty until
1128    /// `CREATE PUBLICATION` runs. Persistence rides the v3 envelope
1129    /// trailer (see `build_envelope`).
1130    publications: publications::Publications,
1131    /// v6.1.4 logical-replication subscription catalog. Empty until
1132    /// `CREATE SUBSCRIPTION` runs. Persistence rides the v4 envelope
1133    /// trailer.
1134    subscriptions: subscriptions::Subscriptions,
1135    /// v6.2.0 — per-column statistics for the cost-based optimizer.
1136    /// Populated by `ANALYZE`; queried via `spg_statistic` virtual
1137    /// table. Persistence rides the v5 envelope trailer.
1138    statistics: statistics::Statistics,
1139    /// v6.3.0 — engine-level plan cache. Caches the post-`prepare()`
1140    /// `Statement` keyed on SQL text. In-memory only — does NOT ride
1141    /// the snapshot envelope (rebuilt on demand after restart).
1142    plan_cache: plan_cache::PlanCache,
1143    /// v6.5.1 — per-distinct-SQL execution stats. In-memory only,
1144    /// surfaced via `spg_stat_query` virtual table. Updated by the
1145    /// `execute_*` paths after a successful execute.
1146    query_stats: query_stats::QueryStats,
1147    /// v6.5.2 — connection-state provider callback. spg-server
1148    /// registers a function at startup that snapshots its
1149    /// per-pgwire-connection registry into `ActivityRow`s; engine
1150    /// reads through it on every `SELECT * FROM spg_stat_activity`.
1151    /// `None` ⇒ no-data (returns empty rows; matches the no_std
1152    /// embedded callers that don't run pgwire).
1153    activity_provider: Option<ActivityProvider>,
1154    /// v6.5.3 — audit-chain provider + verifier. Same pattern as
1155    /// activity_provider: spg-server registers both at startup;
1156    /// engine reads through on `SELECT * FROM spg_audit_chain` and
1157    /// `SELECT * FROM spg_audit_verify`. `None` ⇒ no-data.
1158    audit_chain_provider: Option<AuditChainProvider>,
1159    audit_verifier: Option<AuditVerifier>,
1160    /// v6.5.6 — slow-query log threshold in microseconds. When set,
1161    /// every successful execute whose elapsed exceeds the threshold
1162    /// gets fed to the registered slow-query log callback (so
1163    /// spg-server can emit a structured log line). Default `None`
1164    /// = no slow-query logging.
1165    slow_query_threshold_us: Option<u64>,
1166    slow_query_logger: Option<SlowQueryLogger>,
1167    /// v7.12.1 — session parameters set via `SET <name> = <value>`.
1168    /// Only `default_text_search_config` is consumed by the engine
1169    /// today (the FTS function dispatcher reads it when
1170    /// `to_tsvector(text)` is called without an explicit config).
1171    /// All other names are accepted + recorded so PG-dump output
1172    /// loads, but have no behavioural effect.
1173    pub(crate) session_params: BTreeMap<String, String>,
1174    /// v7.39 (round 218) — open server-side cursors (DECLARE … CURSOR),
1175    /// keyed by name. Materialized at DECLARE (INSENSITIVE semantics —
1176    /// PG's only actual behaviour too); FETCH / MOVE walk the stored rows.
1177    /// Lifecycle: created only inside a transaction; COMMIT closes
1178    /// non-HOLD cursors and marks WITH HOLD ones held; ROLLBACK closes
1179    /// everything not already held by an earlier commit. Never serialized.
1180    /// Session-scoped in PG; SPG stores them engine-wide (the same
1181    /// process-level session-state architecture wall as `session_params`).
1182    pub(crate) cursors: BTreeMap<String, cursor::OpenCursor>,
1183    /// v7.39 (round 347, M2) — the current session's LAST_INSERT_ID().
1184    /// Swapped with [`SessionBag`] like every other per-connection slot.
1185    /// An atomic because `LAST_INSERT_ID(expr)` SETS it while evaluation
1186    /// holds only `&Engine` — and `Engine` must stay `Sync`, which a
1187    /// `Cell` would have taken away (spg-embedded-tokio shares one across
1188    /// tasks; clippy caught it there before the tests did).
1189    pub(crate) last_insert_id: core::sync::atomic::AtomicI64,
1190    /// v7.39 (round 426) — the current session's ROW_COUNT(). Swapped
1191    /// with [`SessionBag`] like every other per-connection slot. A plain
1192    /// i64: unlike LAST_INSERT_ID it is only ever WRITTEN from the
1193    /// statement driver, which holds `&mut Engine`.
1194    pub(crate) row_count: i64,
1195    /// v7.39 (round 430) — this session's MySQL USER variables.
1196    /// Swapped with [`SessionBag`] like every other per-connection slot.
1197    pub(crate) user_vars: BTreeMap<String, spg_storage::Value<'static>>,
1198    /// v7.39 (round 436) — the logical names of this session's TEMPORARY
1199    /// tables. Swapped with [`SessionBag`]; see `session_temp_name`.
1200    pub(crate) temp_tables: BTreeSet<String>,
1201    pub(crate) temp_sequences: BTreeSet<String>,
1202    pub(crate) temp_views: BTreeSet<String>,
1203    /// v7.39 (round 222) — channels this session LISTENs on. Engine-wide
1204    /// (the same process-level session-state architecture wall as
1205    /// `session_params`). Never serialized.
1206    pub(crate) listen_channels: BTreeSet<String>,
1207    /// v7.39 (round 222) — NOTIFYs raised inside the current transaction,
1208    /// held until COMMIT (PG: transactional delivery, deduplicated within
1209    /// the tx); dropped at ROLLBACK.
1210    pub(crate) tx_pending_notifies: Vec<(String, String)>,
1211    /// v7.39 (round 222) — committed notifications on LISTENed channels,
1212    /// awaiting a drain by the wire layer ('A' NotificationResponse) or an
1213    /// embedded caller ([`Engine::take_notifications`]).
1214    pub(crate) delivered_notifies: Vec<(String, String)>,
1215    /// v7.39 (read01 round 46) — NOTICEs raised by the statement now
1216    /// executing. PG emits a NoticeResponse whenever an `IF EXISTS` /
1217    /// `IF NOT EXISTS` clause makes it skip work ("table \"t\" does not
1218    /// exist, skipping"). The engine appends the PG-worded text here;
1219    /// the caller drains it with [`Engine::take_notices`] after each
1220    /// statement (pgwire turns each into an 'N' message, embedded
1221    /// callers can ignore or surface them). Cleared at the start of
1222    /// every statement so a notice never leaks into the next one.
1223    pending_notices: Vec<Notice>,
1224    /// v7.38 (read01 P3.12) — cumulative row-write counters feeding
1225    /// `pg_stat_database` (database-wide `tup_inserted` / `tup_updated` /
1226    /// `tup_deleted`). Bumped by the affected-row count of each successful
1227    /// INSERT / UPDATE / DELETE statement. Per-Engine (so tests stay
1228    /// isolated); on the server's shared engine they read as the
1229    /// since-start database totals PG reports.
1230    /// v7.39 (pg_stat knife A) — committed / rolled-back transaction
1231    /// counters for pg_stat_database. Atomics so the read-only
1232    /// autocommit path (&self) can count its implicit commit, matching
1233    /// PG (every successful statement outside a tx block is one
1234    /// xact_commit — SELECTs included).
1235    /// v7.37 (round 884) — what sorts have spilled in this process, for
1236    /// `pg_stat_database` and for EXPLAIN ANALYZE's `Sort Method`.
1237    pub(crate) spill_stats: crate::tempstore::SpillStats,
1238    pub(crate) xact_commit: core::sync::atomic::AtomicU64,
1239    pub(crate) xact_rollback: core::sync::atomic::AtomicU64,
1240    /// v7.39 (pg_stat knife A) — host-injected live backend count for
1241    /// pg_stat_database.numbackends (ClockFn-style fn slot; the server
1242    /// wires its connection registry, embedded stays None -> 1).
1243    pub(crate) backend_count_fn: Option<BackendCountFn>,
1244    pub(crate) backend_pid_fn: Option<BackendPidFn>,
1245    /// v7.39 (round 476) — see [`WalLsnFn`].
1246    pub(crate) wal_lsn_fn: Option<WalLsnFn>,
1247    /// v7.39 (round 318, V51) — host connection-control hook. See
1248    /// [`BackendSignalFn`].
1249    pub(crate) backend_signal_fn: Option<BackendSignalFn>,
1250    /// v7.39 (tz epic) — injected IANA timezone lookups; None on a
1251    /// host without zoneinfo (named zones then fail to SET, honestly).
1252    pub(crate) tz_offset_fn: Option<TzOffsetFn>,
1253    pub(crate) tz_localize_fn: Option<TzLocalizeFn>,
1254    pub(crate) tz_canon_fn: Option<TzCanonFn>,
1255    pub(crate) tz_abbrev_fn: Option<TzAbbrevFn>,
1256    /// v7.39 (round 502) — see [`TzAllFn`].
1257    pub(crate) tz_all_fn: Option<TzAllFn>,
1258    pub(crate) stat_tup_inserted: u64,
1259    pub(crate) stat_tup_updated: u64,
1260    pub(crate) stat_tup_deleted: u64,
1261    /// v7.39 (round 192) — per-table DML counters for
1262    /// pg_stat_user_tables (n_tup_ins / n_tup_upd / n_tup_del).
1263    /// Engine-side and NON-transactional, like PG's stats collector:
1264    /// a rolled-back INSERT still counts, and a tx's counts don't
1265    /// ride the shadow catalog (the RC rebase rebuilt shadow tables
1266    /// from the committed base, silently dropping any counter bumped
1267    /// on the shadow — the r192 probe's tx-wrapped inserts read 0).
1268    /// Keyed by table name; DROP TABLE clears, RENAME re-keys.
1269    pub(crate) table_write_stats: alloc::collections::BTreeMap<String, (u64, u64, u64)>,
1270    /// v7.39 (round 196) — bumped after every completed statement that
1271    /// ran OUTSIDE a transaction block (any autocommit statement, plus
1272    /// COMMIT itself via the post-statement check). An open tx whose
1273    /// `rebased_at_epoch` equals this value knows the committed base
1274    /// hasn't moved and skips the per-statement RC rebase (whose
1275    /// write-set extraction full-scans every touched table).
1276    /// Over-approximation is deliberate: read-only statements bump it
1277    /// too, which only costs an extra (correct) rebase.
1278    pub(crate) commit_epoch: u64,
1279    /// v7.38 (read01 P3.19) — `SET LOCAL` undo log for the current
1280    /// transaction. Each entry is `(param_name, prior_value)` captured
1281    /// just before a `SET LOCAL` overwrote it (`None` = the param had no
1282    /// session value, so restoring means removing it). Replayed in
1283    /// reverse at COMMIT / ROLLBACK to revert transaction-local settings;
1284    /// `savepoint_guc_marks` records the stack depth at each open
1285    /// savepoint so `ROLLBACK TO` can unwind just the later ones.
1286    pub(crate) local_guc_saves: Vec<(String, Option<String>)>,
1287    /// v7.39 (GUC knife 3) — parsed DateStyle / IntervalStyle /
1288    /// extra_float_digits, kept in lockstep with `session_params` so
1289    /// renderers don't re-parse GUC text per cell.
1290    pub(crate) render_style: crate::eval::RenderStyle,
1291    pub(crate) savepoint_guc_marks: Vec<(String, usize)>,
1292    /// v7.12.7 — depth counter for trigger-emitted embedded SQL.
1293    /// Each time the engine executes a `DeferredEmbeddedStmt` it
1294    /// increments this; the recursive `execute_stmt_with_cancel`
1295    /// inside that path checks against [`MAX_TRIGGER_RECURSION`]
1296    /// to bound runaway cascades (trigger A's UPDATE on table B
1297    /// fires trigger B which UPDATEs table A which fires trigger
1298    /// A again…). Reset to 0 once the original DML returns.
1299    trigger_recursion_depth: u32,
1300    /// v7.39 (round 140) — set while a DELETE / UPDATE is being re-run by the
1301    /// DO ALSO rule wrapper so the wrapper's inner call does not re-enter the
1302    /// rule-rewrite path (which would recurse forever). INSERT captures its
1303    /// post-image rows directly and needs no such guard.
1304    rule_rewrite_active: bool,
1305    /// v7.14.0 — when `SET FOREIGN_KEY_CHECKS=0` is in effect
1306    /// (mysqldump preamble), the FK existence + arity check at
1307    /// CREATE TABLE time is deferred. FKs referencing a
1308    /// not-yet-existing parent land in `pending_foreign_keys`
1309    /// keyed by child table; `SET FOREIGN_KEY_CHECKS=1` drains
1310    /// the queue and resolves each FK against the now-complete
1311    /// catalog. Empty by default; the queue is drained on every
1312    /// `RESET ALL` too.
1313    foreign_key_checks: bool,
1314    /// v7.16.2 — true on the temp Engine an outer
1315    /// `exec_select_with_meta_views` builds, telling that
1316    /// temp engine "stop short-circuiting into the meta-view
1317    /// path — your catalog already has the materialised
1318    /// tables; just run the regular SELECT." Without this we'd
1319    /// infinite-loop since the meta-view name (e.g.
1320    /// `__spg_info_columns`) still triggers
1321    /// `select_references_meta_view`.
1322    meta_views_materialised: bool,
1323    pending_foreign_keys: Vec<(alloc::string::String, spg_sql::ast::ForeignKeyConstraint)>,
1324    /// v7.38 元机制 D — frozen snapshot of `SPG_TEST_*` env vars. Read
1325    /// once at construction (`with_env_cfg`) and queried on hot paths
1326    /// via `engine.env_cfg().<field>`. Production builds keep this at
1327    /// `EnvConfig::default()`, so the optimiser can const-fold every
1328    /// `if env_cfg.<field>` gate. See `testkit::env_config` + the
1329    /// `xtests/sigil/test-mode-gucs.md` index.
1330    env_cfg: testkit::EnvConfig,
1331    /// v7.38 P0 元机制 A — per-engine `injection_points` attach
1332    /// table. Only exists when the crate is built with the
1333    /// `injection-points` feature; release builds carry no field.
1334    /// Pushed onto the thread-local stack by
1335    /// `enter_injection_scope()` so the `injection_point!()` macro
1336    /// can find it from anywhere in the executor without rewiring
1337    /// every signature. See
1338    /// `crates/spg-engine/src/testkit/injection.rs`.
1339    #[cfg(feature = "injection-points")]
1340    injection_store: alloc::sync::Arc<crate::testkit::injection::InjectionStore>,
1341    /// v7.34 (crash-recovery P0 #2) — row-level redo capture. When the
1342    /// embedding layer turns this on (persistence enabled), each mutating
1343    /// `execute` records the physical [`RowChange`]s it applied; the
1344    /// engine drains them into `last_redo` on success, and the embedded
1345    /// layer reads them via [`Engine::take_redo`] to write the WAL in
1346    /// place of the SQL text. Off (default) = zero capture overhead.
1347    redo_capture: bool,
1348    /// Redo captured by the most recent successful mutating `execute`,
1349    /// awaiting drain by the embedding layer. Cleared on each capture.
1350    last_redo: Vec<RowChange>,
1351    /// v7.39 (round 735, S14/B3) — per-table change sequence, bumped on
1352    /// every write entry (INSERT / UPDATE / DELETE / TRUNCATE / COPY /
1353    /// table-shape DDL). In-memory only: after a restart the map is
1354    /// empty, every watermark comparison misses, and the next REFRESH
1355    /// is a full one — stale-view-safe by construction. A rolled-back
1356    /// transaction's bump stays too, which can only cause an EXTRA full
1357    /// refresh, never a wrong no-op.
1358    table_change_seq: alloc::collections::BTreeMap<String, u64>,
1359    /// v7.39 (round 735, S14/B3) — per-materialized-view refresh
1360    /// watermark: the (table, change-seq) pairs its last full refresh
1361    /// saw. When every dependency's seq is unchanged, REFRESH is an
1362    /// O(1) no-op — an incremental-maintenance first step PG does not
1363    /// have (its REFRESH always recomputes).
1364    matview_refresh_watermark: alloc::collections::BTreeMap<String, Vec<(String, u64)>>,
1365    /// v7.39 (round 736, S14/B3 knife 2) — delta-maintainable
1366    /// materialized views: mv name -> its single base table. Registered
1367    /// at CREATE MATERIALIZED VIEW / full REFRESH when the body is a
1368    /// single-stored-table pure projection (no aggregates / joins /
1369    /// CTEs / subqueries / DISTINCT / ORDER / LIMIT / windows / SRFs).
1370    matview_maintainable: alloc::collections::BTreeMap<String, String>,
1371    /// Buffered base-table row changes per maintainable view, fanned
1372    /// out from the statement redo drain. Capped (see
1373    /// `MATVIEW_DELTA_CEILING`); an overflowed view falls back to a
1374    /// full refresh — never-die, never-stale.
1375    matview_delta_buf: alloc::collections::BTreeMap<String, Vec<RowChange>>,
1376    matview_delta_overflow: alloc::collections::BTreeSet<String>,
1377    /// v7.39 (round 738, S14/B3 knife 3) — per-view row map: expected
1378    /// PHYSICAL length of the view's backing table, plus base-row
1379    /// RowId -> view row position. Built only by the maintainable full
1380    /// refresh's internal scan (the SQL path cannot see rowids), and
1381    /// consulted by the delete/tombstone delta arms. In-memory: restart
1382    /// or any length mismatch (a vacuum moved rows) -> full refresh.
1383    matview_row_map:
1384        alloc::collections::BTreeMap<String, (usize, alloc::collections::BTreeMap<u64, usize>)>,
1385    /// v7.38 轴 4 — currently-selected SQL isolation level. Set by
1386    /// `SET TRANSACTION ISOLATION LEVEL …`; read by
1387    /// `SHOW transaction_isolation`. v7.37.8 implements the
1388    /// SQL surface; actual semantic differentiation (REPEATABLE READ
1389    /// snapshot / SERIALIZABLE SSI) lands in a separate train.
1390    pub(crate) current_isolation_level: spg_sql::ast::IsolationLevel,
1391}
1392
1393/// v7.12.7 — hard cap on nested trigger-emitted embedded SQL
1394/// fires. 16 deep is well past anything a normal trigger graph
1395/// uses while still preventing infinite-loop wedging.
1396const MAX_TRIGGER_RECURSION: u32 = 16;
1397
1398/// v6.5.6 — callback signature for slow-query log emission. Called
1399/// with `(sql, elapsed_us)` once per successful execute that crosses
1400/// the threshold.
1401pub type SlowQueryLogger = fn(&str, u64);
1402
1403/// v6.5.2 — one row of `spg_stat_activity`. Engine-public so
1404/// spg-server can construct rows without re-exporting internal
1405/// dispatch types.
1406#[derive(Debug, Clone)]
1407pub struct ActivityRow {
1408    pub pid: u32,
1409    pub user: String,
1410    /// v7.39 (round 319, V52) — the peer's IP, empty when the connection
1411    /// has no TCP peer (PG reports NULL there).
1412    pub client_addr: String,
1413    /// v7.39 (round 319, V52) — the peer's port. PG reports **-1**, not
1414    /// NULL, for a connection with no TCP port; measured on PG 18.4.
1415    pub client_port: i32,
1416    /// v7.39 (round 319, V52) — the database this connection named. Empty
1417    /// when it named none; both `pg_stat_activity.datname` and
1418    /// `SHOW PROCESSLIST.db` report that as NULL.
1419    pub database: String,
1420    pub started_at_us: i64,
1421    pub current_sql: String,
1422    /// v7.37.14 (B6.3) — PG-style wait-event categorisation
1423    /// ("Lock", "LWLock", "IPC", "IO", "Timeout", "Client",
1424    /// "BufferPin", "Extension", ""). Empty string means idle.
1425    /// Pair with `wait_event` to identify "what specifically is
1426    /// the backend waiting on" the same way PG does.
1427    pub wait_event_type: String,
1428    pub wait_event: String,
1429    pub elapsed_us: i64,
1430    pub in_transaction: bool,
1431    /// v7.17 Phase 2.4 — startup-param `application_name` (or the
1432    /// last value the client sent via `SET application_name = '...'`).
1433    /// Empty when the client never declared one.
1434    pub application_name: String,
1435    /// v7.39 (round 474) — PG's `backend_type`: `client backend` for a
1436    /// connection, or the worker's own name for a background process.
1437    ///
1438    /// pg_stat_activity used to hardcode `client backend`, so SPG's own
1439    /// background workers — the ones that hold the engine write lock and
1440    /// are exactly what an operator is looking for when a statement
1441    /// stalls — did not appear at all. PG18 lists eight of them beside
1442    /// the single client backend on an idle server.
1443    pub backend_type: String,
1444}
1445
1446impl ActivityRow {
1447    /// The `backend_type` PG gives a background process: no database, no
1448    /// user, no query, and a state PG reports as NULL.
1449    #[must_use]
1450    pub fn background(pid: u32, backend_type: &str) -> Self {
1451        Self {
1452            pid,
1453            user: String::new(),
1454            client_addr: String::new(),
1455            client_port: -1,
1456            database: String::new(),
1457            started_at_us: 0,
1458            current_sql: String::new(),
1459            wait_event_type: String::new(),
1460            wait_event: String::new(),
1461            elapsed_us: 0,
1462            in_transaction: false,
1463            application_name: String::new(),
1464            backend_type: backend_type.into(),
1465        }
1466    }
1467}
1468
1469/// v6.5.2 — provider callback type. Fresh snapshot returned each
1470/// call; engine doesn't cache the slice.
1471pub type ActivityProvider = fn() -> Vec<ActivityRow>;
1472
1473/// v7.39 (round 318, V41) — how loud a diagnostic the statement raised is.
1474/// PG distinguishes them on the wire (`S`/`V` fields of NoticeResponse) and
1475/// clients act on it: psql prints `WARNING:` in a different colour, and
1476/// several drivers surface warnings to the application while dropping
1477/// notices. Emitting everything as NOTICE loses that.
1478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1479pub enum NoticeSeverity {
1480    Notice,
1481    Warning,
1482    /// v7.39 (round 757, F31-B3) — `RAISE INFO`. PG sends INFO to the
1483    /// client ALWAYS, regardless of `client_min_messages`.
1484    Info,
1485}
1486
1487impl NoticeSeverity {
1488    /// The non-localized severity string PG puts in the `V` field.
1489    #[must_use]
1490    pub const fn as_pg_str(self) -> &'static str {
1491        match self {
1492            Self::Notice => "NOTICE",
1493            Self::Warning => "WARNING",
1494            Self::Info => "INFO",
1495        }
1496    }
1497}
1498
1499/// v7.39 (round 318, V41) — one diagnostic the statement raised, in PG's
1500/// exact wording minus the severity banner (the wire layer adds that).
1501#[derive(Debug, Clone)]
1502pub struct Notice {
1503    pub severity: NoticeSeverity,
1504    pub message: String,
1505}
1506
1507/// v6.5.3 — one row of `spg_audit_chain`. Engine-public so
1508/// spg-server can construct rows directly from `AuditEntry`.
1509#[derive(Debug, Clone)]
1510pub struct AuditRow {
1511    pub seq: i64,
1512    pub ts_ms: i64,
1513    pub prev_hash_hex: String,
1514    pub entry_hash_hex: String,
1515    pub sql: String,
1516}
1517
1518/// v6.5.3 — chain-table provider + verifier. spg-server registers
1519/// fn pointers that snapshot / verify the audit log. `verify`
1520/// returns `(verified_count, broken_at_seq)` — `broken_at_seq` is
1521/// `-1` on a clean chain.
1522pub type AuditChainProvider = fn() -> Vec<AuditRow>;
1523pub type AuditVerifier = fn() -> (i64, i64);
1524
1525impl Engine {
1526    pub fn new() -> Self {
1527        Self {
1528            catalog: Catalog::new(),
1529            parallel_runner: ParallelRunnerSlot::default(),
1530            tx_catalogs: BTreeMap::new(),
1531            table_last_commit: BTreeMap::new(),
1532            commit_seq: 0,
1533            current_tx: None,
1534            backslash_escapes: false,
1535            mysql_strict: true,
1536            lo_descriptors: BTreeMap::new(),
1537            lo_next_fd: 0,
1538            prepared_statements: alloc::collections::BTreeMap::new(),
1539            current_session: 0,
1540            sessions: BTreeMap::new(),
1541            advisory_locks: BTreeMap::new(),
1542            last_sequence_used: None,
1543            seq_currvals: alloc::collections::BTreeMap::new(),
1544            next_tx_id: 1,
1545            active_writer_versions: BTreeSet::new(),
1546            aborted_versions: BTreeSet::new(),
1547            locks: crate::locks::LockTable::new(),
1548            mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
1549            autovacuum: true,
1550            autovacuum_inline: true,
1551            lock_skip_rows: None,
1552            tx_writer_versions: BTreeMap::new(),
1553            stmt_writer_version: None,
1554            clock: None,
1555            salt_fn: None,
1556            max_query_rows: None,
1557            max_query_bytes: None,
1558            temp_run_factory: None,
1559            users: UserStore::new(),
1560            publications: publications::Publications::new(),
1561            subscriptions: subscriptions::Subscriptions::new(),
1562            statistics: statistics::Statistics::new(),
1563            plan_cache: plan_cache::PlanCache::new(),
1564            query_stats: query_stats::QueryStats::new(),
1565            activity_provider: None,
1566            audit_chain_provider: None,
1567            audit_verifier: None,
1568            slow_query_threshold_us: None,
1569            slow_query_logger: None,
1570            session_params: BTreeMap::new(),
1571            cursors: BTreeMap::new(),
1572            last_insert_id: core::sync::atomic::AtomicI64::new(0),
1573            row_count: 0,
1574            user_vars: BTreeMap::new(),
1575            temp_tables: BTreeSet::new(),
1576            temp_sequences: BTreeSet::new(),
1577            temp_views: BTreeSet::new(),
1578            listen_channels: BTreeSet::new(),
1579            tx_pending_notifies: Vec::new(),
1580            delivered_notifies: Vec::new(),
1581            pending_notices: Vec::new(),
1582            spill_stats: crate::tempstore::SpillStats::default(),
1583            xact_commit: core::sync::atomic::AtomicU64::new(0),
1584            xact_rollback: core::sync::atomic::AtomicU64::new(0),
1585            backend_count_fn: None,
1586            backend_pid_fn: None,
1587            wal_lsn_fn: None,
1588            backend_signal_fn: None,
1589            tz_offset_fn: None,
1590            tz_localize_fn: None,
1591            tz_canon_fn: None,
1592            tz_abbrev_fn: None,
1593            tz_all_fn: None,
1594            stat_tup_inserted: 0,
1595            table_write_stats: alloc::collections::BTreeMap::new(),
1596            commit_epoch: 0,
1597            stat_tup_updated: 0,
1598            stat_tup_deleted: 0,
1599            local_guc_saves: Vec::new(),
1600            render_style: crate::eval::RenderStyle::default(),
1601            savepoint_guc_marks: Vec::new(),
1602            trigger_recursion_depth: 0,
1603            rule_rewrite_active: false,
1604            foreign_key_checks: true,
1605            meta_views_materialised: false,
1606            pending_foreign_keys: Vec::new(),
1607            env_cfg: testkit::EnvConfig::default(),
1608            #[cfg(feature = "injection-points")]
1609            injection_store: alloc::sync::Arc::new(
1610                crate::testkit::injection::InjectionStore::default(),
1611            ),
1612            redo_capture: false,
1613            current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
1614            last_redo: Vec::new(),
1615            table_change_seq: alloc::collections::BTreeMap::new(),
1616            matview_refresh_watermark: alloc::collections::BTreeMap::new(),
1617            matview_maintainable: alloc::collections::BTreeMap::new(),
1618            matview_delta_buf: alloc::collections::BTreeMap::new(),
1619            matview_delta_overflow: alloc::collections::BTreeSet::new(),
1620            matview_row_map: alloc::collections::BTreeMap::new(),
1621        }
1622    }
1623
1624    /// v7.11.0 — clone the engine's committed catalog + read-time
1625    /// state into a frozen `CatalogSnapshot`. Cheap (`Catalog` is
1626    /// backed by `PersistentVec`; cloning is O(log n) per table).
1627    /// Subsequent writes to this engine are invisible to the
1628    /// snapshot; the snapshot is self-contained and can be moved
1629    /// to another thread for concurrent `execute_readonly_on_snapshot`
1630    /// calls. The basis for [`AsyncReadHandle`] in spg-embedded-tokio
1631    /// and any other read-fanout pattern.
1632    #[must_use]
1633    pub fn clone_snapshot(&self) -> CatalogSnapshot {
1634        CatalogSnapshot {
1635            catalog: self.active_catalog().clone(),
1636            statistics: self.statistics.clone(),
1637            clock: self.clock,
1638            max_query_rows: self.max_query_rows,
1639        }
1640    }
1641
1642    /// v7.39 (round 513) — does this role exist? `'x'::regrole` needs it,
1643    /// and roles live on the engine rather than the catalog.
1644    #[must_use]
1645    pub fn role_exists(&self, name: &str) -> bool {
1646        // v7.39 (round 696) — the SESSION's own identity, same class as the
1647        // `postgres` case below and missed by it. `current_user` reported
1648        // the connected name while this predicate denied it, so `SET ROLE
1649        // <me>` refused the role the session was already running as.
1650        if name == self.session_user() {
1651            return true;
1652        }
1653        // The engine's default identity exists even before any CREATE USER.
1654        //
1655        // v7.39 (round 652) — and so does `postgres`. `synth_pg_roles`
1656        // has always inserted it as the bootstrap superuser when no user
1657        // by that name was created, so this predicate and the catalogue
1658        // it is supposed to reflect disagreed: `pg_roles` listed
1659        // `postgres` while `'postgres'::regrole` said it did not exist.
1660        // Every pg_dump names it (`OWNER TO postgres`), so the ALTER
1661        // TABLE OWNER check added this round would have refused the one
1662        // role that appears in essentially every dump.
1663        self.effective_users().contains(name)
1664            || name.eq_ignore_ascii_case("admin")
1665            || name.eq_ignore_ascii_case("postgres")
1666            // 7.38.1 S5.2 — PG's predefined pg_* roles exist without
1667            // anyone creating them, and pg_dump's ACL section GRANTs
1668            // to `pg_database_owner` on every dump of `public`.
1669            || matches!(
1670                name.to_ascii_lowercase().as_str(),
1671                "pg_database_owner"
1672                    | "pg_read_all_data"
1673                    | "pg_write_all_data"
1674                    | "pg_monitor"
1675                    | "pg_read_all_settings"
1676                    | "pg_read_all_stats"
1677                    | "pg_stat_scan_tables"
1678                    | "pg_signal_backend"
1679                    | "pg_checkpoint"
1680                    | "pg_maintain"
1681                    | "pg_use_reserved_connections"
1682                    | "pg_create_subscription"
1683            )
1684    }
1685
1686    /// v7.39 (round 520) — the role an oid names, as `pg_get_userbyid`
1687    /// reports it. The numbering is `synth_pg_roles`': base 10, one per
1688    /// user in catalog order.
1689    #[must_use]
1690    pub fn role_name_for_oid(&self, oid: i64) -> Option<String> {
1691        // Oid 10 is the bootstrap superuser, which `synth_pg_roles` always
1692        // publishes as `postgres`. Following the catalogue rather than the
1693        // session is the point: a join on `relowner = pg_roles.oid` and
1694        // `pg_get_userbyid(relowner)` have to name the same role.
1695        if oid == 10 {
1696            return Some(alloc::string::String::from("postgres"));
1697        }
1698        let idx = usize::try_from(oid - 11).ok()?;
1699        self.users
1700            .iter()
1701            .nth(idx)
1702            .map(|(n, _)| alloc::string::String::from(n))
1703    }
1704
1705    /// v7.37.15 (Phase B / C / E) — current per-row visibility
1706    /// snapshot for in-engine scans. Captures the live writer-
1707    /// version cursor + active-writer set; readers built from this
1708    /// Snapshot see committed state through the moment of capture
1709    /// and DO NOT observe uncommitted writes still inside
1710    /// `active_writer_versions`.
1711    ///
1712    /// Phase E: if there's an explicit transaction in flight under
1713    /// REPEATABLE READ or SERIALIZABLE isolation, returns the
1714    /// snapshot the tx cached at BEGIN time — every statement in
1715    /// the tx sees the same coherent prior-committed view. READ
1716    /// COMMITTED (the default) returns a fresh snapshot per call,
1717    /// matching PG's per-statement visibility semantics.
1718    ///
1719    /// `oldest_active = version` when no writer is in flight (== no
1720    /// dead row could still be observed); else == min of active
1721    /// versions (vacuum-floor).
1722    #[must_use]
1723    pub fn current_snapshot(&self) -> spg_storage::snapshot::Snapshot {
1724        // v7.39 (round 297, E3 Phase 1b) — carry the SKIP LOCKED
1725        // exclusions on the snapshot. Every row source threads a
1726        // snapshot through `is_row_visible`, so this is the one place
1727        // that cannot be routed around; adding the filter per scan site
1728        // missed the live path three times.
1729        let locked_out = self.lock_skip_rows.as_ref().and_then(|(t, set)| {
1730            self.active_catalog()
1731                .get(t)
1732                .map(|tbl| (tbl.rel_id(), set.clone()))
1733        });
1734        let mut snap = self.current_snapshot_inner();
1735        snap.locked_out = locked_out;
1736        snap
1737    }
1738
1739    fn current_snapshot_inner(&self) -> spg_storage::snapshot::Snapshot {
1740        // Phase E — if we're inside a RR/SER tx, return its
1741        // cached snapshot so the whole tx sees one frozen view.
1742        if let Some(tx_id) = self.current_tx
1743            && let Some(state) = self.tx_catalogs.get(&tx_id)
1744            && let Some(s) = state.cached_snapshot.as_ref()
1745        {
1746            return s.clone();
1747        }
1748        // v7.37.15 (Phase C.3, step 1) — carry the current tx's writer
1749        // version as the snapshot's `tx_id` so the visibility gate's
1750        // self-write branch (`visible` step 1) recognises rows this
1751        // transaction stamped (`xmin == v`, with `v` in
1752        // `active_writer_versions`). Without this the tx's own
1753        // uncommitted rows fall to the in-progress step and become
1754        // invisible to itself on the gated read paths. Autocommit reads
1755        // (no `tx_writer_versions` entry) keep `tx_id = 0`.
1756        let reader_tx_id = self
1757            .current_tx
1758            .and_then(|t| self.tx_writer_versions.get(&t).copied())
1759            .unwrap_or(0);
1760        let version = spg_storage::row_header::current_version();
1761        if self.active_writer_versions.is_empty() {
1762            // Hot path: no writer in flight. Snapshot::unbounded()
1763            // would also work, but pinning to the live cursor
1764            // means the snapshot's oldest_active is accurate
1765            // (= version) so subsequent vacuum can advance.
1766            return spg_storage::snapshot::Snapshot::new(
1767                version,
1768                spg_storage::snapshot::InProgressSet::empty(),
1769                version,
1770                reader_tx_id,
1771            );
1772        }
1773        let sorted: alloc::vec::Vec<u64> = self.active_writer_versions.iter().copied().collect();
1774        let oldest = *sorted.first().unwrap_or(&version);
1775        spg_storage::snapshot::Snapshot::new(
1776            version,
1777            spg_storage::snapshot::InProgressSet::from_sorted(sorted),
1778            oldest,
1779            reader_tx_id,
1780        )
1781    }
1782
1783    /// v7.37.15 (Phase C) — allocate the next writer version AND
1784    /// add it to the in-flight set so concurrent snapshots hide
1785    /// the resulting writes until [`Self::commit_writer_version`]
1786    /// removes the entry. Returns the allocated version so the
1787    /// writer can stamp it on `xmin` / `xmax`.
1788    pub fn begin_writer_version(&mut self) -> u64 {
1789        let v = spg_storage::row_header::next_version();
1790        self.active_writer_versions.insert(v);
1791        v
1792    }
1793
1794    /// v7.37.15 (Phase C) — mark a previously-allocated writer
1795    /// version as committed. Subsequent snapshots stop including
1796    /// it in `in_progress`, so the writes the version stamped
1797    /// become visible to new readers.
1798    ///
1799    /// No-op if the version was never allocated; matches PG's
1800    /// idempotent `TransactionIdCommitTree` semantics.
1801    pub fn commit_writer_version(&mut self, v: u64) {
1802        self.active_writer_versions.remove(&v);
1803    }
1804
1805    /// v7.37.15 (Phase C.2) — mark a previously-allocated writer
1806    /// version as ABORTED (rolled back). Removes it from the in-flight
1807    /// set and records it in `aborted_versions` so the visibility
1808    /// oracle ([`Self::xact_status`]) reports `Aborted` rather than
1809    /// silently treating it as committed once it leaves the in-flight
1810    /// set. Phase C.3's in-place write path relies on this: a
1811    /// rolled-back version's xmin/xmax stamps stay physically present
1812    /// until vacuum reclaims them, and readers must NOT see them.
1813    ///
1814    /// Idempotent; a no-op if the version was never allocated.
1815    pub fn abort_writer_version(&mut self, v: u64) {
1816        self.active_writer_versions.remove(&v);
1817        self.aborted_versions.insert(v);
1818    }
1819
1820    /// v7.37.15 (Phase C.2) — the visibility oracle's terminal-status
1821    /// lookup for one version. In-flight if still allocated, Aborted
1822    /// if it rolled back, otherwise Committed (the default for a
1823    /// version that left the in-flight set the normal way, and for
1824    /// every frozen / pruned old version the engine no longer tracks).
1825    ///
1826    /// `aborted_versions` is bounded by pruning below `oldest_active`
1827    /// during vacuum (Phase D): once no live snapshot can still see an
1828    /// aborted version's stamps, its entry is dropped. Until Phase D
1829    /// lands the set only grows with rolled-back transactions — noted
1830    /// as a never-die follow-up, not a steady-state leak on the
1831    /// commit path.
1832    #[must_use]
1833    pub fn xact_status(&self, v: u64) -> spg_storage::snapshot::XactStatus {
1834        use spg_storage::snapshot::XactStatus;
1835        if self.active_writer_versions.contains(&v) {
1836            XactStatus::InProgress
1837        } else if self.aborted_versions.contains(&v) {
1838            XactStatus::Aborted
1839        } else {
1840            XactStatus::Committed
1841        }
1842    }
1843
1844    /// v7.37.15 (Phase C.4) — acquire a tuple lock on a stable
1845    /// `(RelId, RowId)` for writer `version`. The in-place write path
1846    /// (C.3) calls this before stamping xmax; `SELECT ... FOR UPDATE`
1847    /// wires here via the parser's lock-strength clause (C.4). Returns
1848    /// the [`LockOutcome`](crate::locks::LockOutcome) the caller acts on
1849    /// (grant / park / skip / fail / deadlock-abort).
1850    pub fn acquire_row_lock(
1851        &mut self,
1852        rel: spg_storage::row_header::RelId,
1853        row: spg_storage::row_header::RowId,
1854        mode: crate::locks::LockMode,
1855        version: u64,
1856        policy: crate::locks::WaitPolicy,
1857    ) -> crate::locks::LockOutcome {
1858        self.locks.acquire(rel, row, mode, version, policy)
1859    }
1860
1861    /// v7.37.15 (Phase C.4) — release every lock + wait held by
1862    /// `version` at transaction end. Called from `exec_commit` /
1863    /// `exec_rollback` alongside the writer-version bookkeeping.
1864    pub fn release_tx_locks(&mut self, version: u64) {
1865        self.locks.release_all(version);
1866    }
1867
1868    /// 7.38.1 S2.1 — drop the tuple locks an AUTOCOMMIT statement took
1869    /// (its implicit transaction ends with it). A no-op inside an open
1870    /// transaction (those release at COMMIT/ROLLBACK) and when the
1871    /// statement allocated no writer version.
1872    pub(crate) fn release_autocommit_stmt_locks(&mut self) {
1873        let in_tx = self
1874            .current_tx
1875            .is_some_and(|tx| self.tx_writer_versions.contains_key(&tx));
1876        if in_tx {
1877            return;
1878        }
1879        if let Some(v) = self.stmt_writer_version {
1880            self.locks.release_all(v);
1881        }
1882    }
1883
1884    /// v7.37.15 (Phase C.4) — number of rows currently locked, for the
1885    /// `pg_locks` enumeration and tests.
1886    #[must_use]
1887    pub fn locked_row_count(&self) -> usize {
1888        self.locks.locked_row_count()
1889    }
1890
1891    /// v7.37.15 (Phase C.3) — is the in-place MVCC write path enabled?
1892    /// `false` (default) keeps legacy physical DELETE/UPDATE. The C.3
1893    /// writers consult this to choose tombstone-vs-physical.
1894    #[must_use]
1895    pub fn mvcc_inplace(&self) -> bool {
1896        self.mvcc_inplace
1897    }
1898
1899    /// v7.37.15 (Phase C.3) — enable/disable the in-place MVCC write
1900    /// path. Called by the host after reading `SPG_MVCC_INPLACE` (the
1901    /// `no_std` engine can't read the environment itself). Off until
1902    /// the write path is proven against PG18 differential tests.
1903    pub fn set_mvcc_inplace(&mut self, on: bool) {
1904        self.mvcc_inplace = on;
1905    }
1906
1907    /// v7.39 (parallel-agg P0) — inject the host's parallel executor
1908    /// (see [`ParallelRunner`]). Called once at host startup; the
1909    /// engine stays single-threaded without it.
1910    /// v7.39 (pg_stat knife A) — inject the host's live backend count.
1911    pub fn set_backend_count_fn(&mut self, f: BackendCountFn) {
1912        self.backend_count_fn = Some(f);
1913    }
1914
1915    /// v7.39 (read01 pgstatfuncs.c) — inject the host's calling-connection
1916    /// identity for pg_backend_pid().
1917    /// v7.39 (round 476) — register the WAL byte-position provider.
1918    pub fn set_wal_lsn_fn(&mut self, f: WalLsnFn) {
1919        self.wal_lsn_fn = Some(f);
1920    }
1921
1922    pub fn set_backend_pid_fn(&mut self, f: BackendPidFn) {
1923        self.backend_pid_fn = Some(f);
1924    }
1925
1926    /// v7.39 (round 318, V51) — inject the host's connection-control hook,
1927    /// so `pg_cancel_backend` / `pg_terminate_backend` / `KILL` act instead
1928    /// of answering a constant.
1929    pub fn set_backend_signal_fn(&mut self, f: BackendSignalFn) {
1930        self.backend_signal_fn = Some(f);
1931    }
1932
1933    /// v7.39 (round 786, T35 Phase A) — install the host's spill-run
1934    /// factory. Without one the engine cannot spill and a sort that
1935    /// outgrows `max_query_bytes` keeps refusing, which is exactly the
1936    /// behaviour every caller has today.
1937    pub fn set_temp_run_factory(&mut self, f: crate::TempRunFactory) {
1938        self.temp_run_factory = Some(f);
1939    }
1940
1941    /// Whether spilling is available in this process.
1942    #[must_use]
1943    pub fn can_spill(&self) -> bool {
1944        self.temp_run_factory.is_some()
1945    }
1946
1947    /// v7.39 (round 786) — open a fresh spill run, or `None` when no
1948    /// host factory is installed. Phase B's run generation calls this;
1949    /// it lives here so the `None` path stays a single decision point.
1950    pub(crate) fn open_temp_run(
1951        &self,
1952    ) -> Option<Result<alloc::boxed::Box<dyn crate::TempRun>, crate::TempStoreError>> {
1953        self.temp_run_factory.map(|f| f())
1954    }
1955
1956    /// v7.39 (tz epic) — inject the host's IANA timezone lookups
1957    /// (spg-tzif's fn family on std hosts).
1958    pub fn set_tz_fns(
1959        &mut self,
1960        offset: TzOffsetFn,
1961        localize: TzLocalizeFn,
1962        canon: TzCanonFn,
1963        abbrev: TzAbbrevFn,
1964    ) {
1965        self.tz_offset_fn = Some(offset);
1966        self.tz_localize_fn = Some(localize);
1967        self.tz_canon_fn = Some(canon);
1968        self.tz_abbrev_fn = Some(abbrev);
1969    }
1970
1971    /// v7.39 (round 502) — the zone enumerator behind `pg_timezone_names`.
1972    /// Separate from `set_tz_fns` so an embedder that already calls that
1973    /// one keeps compiling.
1974    pub fn set_tz_all_fn(&mut self, all: TzAllFn) {
1975        self.tz_all_fn = Some(all);
1976    }
1977
1978    /// Every zone the host knows at `utc_micros`; empty without a hook.
1979    pub(crate) fn tz_all_at(
1980        &self,
1981        utc_micros: i64,
1982    ) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String, i64, bool)> {
1983        self.tz_all_fn
1984            .map_or_else(alloc::vec::Vec::new, |f| f(utc_micros))
1985    }
1986
1987    pub fn set_parallel_runner(&mut self, runner: alloc::sync::Arc<dyn ParallelRunner>) {
1988        self.parallel_runner = ParallelRunnerSlot(Some(runner));
1989    }
1990
1991    /// v7.37.15 (Phase C) — allocate a fresh version number for
1992    /// the next write. Always strictly monotonic + process-wide
1993    /// shared so concurrent engines on the same process agree on
1994    /// "tx 17 commits before tx 18". Phase C writer paths call
1995    /// this once per INSERT / UPDATE / DELETE statement to obtain
1996    /// the version they'll stamp on the new row's `xmin` (or the
1997    /// existing row's `xmax`).
1998    ///
1999    /// Returns [`XMIN_FROZEN`] when MVCC stamping is intentionally
2000    /// off (legacy `in_memory` flow / WAL replay): the writer
2001    /// then takes the legacy frozen-insert short-circuit path
2002    /// inside `Table::insert_with_xmin`.
2003    #[must_use]
2004    pub fn next_writer_version(&self) -> u64 {
2005        spg_storage::row_header::next_version()
2006    }
2007
2008    /// v7.37.15 (Phase C) — version a writer should stamp on
2009    /// rows produced by the current statement. Inside an explicit
2010    /// transaction the version is the tx's pre-allocated one (so
2011    /// every statement in the tx commits atomically at COMMIT);
2012    /// in autocommit it allocates a fresh version per statement.
2013    ///
2014    /// This is the canonical helper engine writers should call
2015    /// — using it instead of `next_writer_version` ensures
2016    /// explicit-tx semantics where every row produced by the tx
2017    /// shares one xmin and concurrent readers don't see partial
2018    /// state until COMMIT.
2019    ///
2020    /// v7.37.15 (Epic W slice 2) — takes `&mut self` so the autocommit
2021    /// branch can **memoize** its freshly-minted version in
2022    /// `stmt_writer_version`. `next_writer_version()` is a `fetch_add`,
2023    /// so without memoization a second call within one statement (the
2024    /// redo drain post-stamps the captured `RowChange`s) would allocate
2025    /// a *different* version than the writes used. Memoizing makes the
2026    /// value stable for the statement's lifetime; it is reset per
2027    /// `execute_in_with_cancel`, so the counter still advances exactly
2028    /// once per autocommit statement — identical to before.
2029    pub fn writer_version_for_current_stmt(&mut self) -> u64 {
2030        if let Some(tx_id) = self.current_tx
2031            && let Some(&v) = self.tx_writer_versions.get(&tx_id)
2032        {
2033            return v;
2034        }
2035        // Autocommit shape: fresh version, immediately "committed"
2036        // (no entry in active_writer_versions, so subsequent
2037        // readers see the row). Memoized for the statement so the
2038        // redo drain reads back the same version the writes used.
2039        if let Some(v) = self.stmt_writer_version {
2040            return v;
2041        }
2042        let v = self.next_writer_version();
2043        self.stmt_writer_version = Some(v);
2044        v
2045    }
2046
2047    /// Construct an engine restored from a previously-snapshotted catalog
2048    /// (see `snapshot()`).
2049    pub fn restore(catalog: Catalog) -> Self {
2050        Self {
2051            lock_skip_rows: None,
2052            catalog,
2053            parallel_runner: ParallelRunnerSlot::default(),
2054            tx_catalogs: BTreeMap::new(),
2055            table_last_commit: BTreeMap::new(),
2056            commit_seq: 0,
2057            current_tx: None,
2058            backslash_escapes: false,
2059            mysql_strict: true,
2060            lo_descriptors: BTreeMap::new(),
2061            lo_next_fd: 0,
2062            prepared_statements: alloc::collections::BTreeMap::new(),
2063            current_session: 0,
2064            sessions: BTreeMap::new(),
2065            advisory_locks: BTreeMap::new(),
2066            last_sequence_used: None,
2067            seq_currvals: alloc::collections::BTreeMap::new(),
2068            next_tx_id: 1,
2069            active_writer_versions: BTreeSet::new(),
2070            aborted_versions: BTreeSet::new(),
2071            locks: crate::locks::LockTable::new(),
2072            mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
2073            autovacuum: true,
2074            autovacuum_inline: true,
2075            tx_writer_versions: BTreeMap::new(),
2076            stmt_writer_version: None,
2077            clock: None,
2078            salt_fn: None,
2079            max_query_rows: None,
2080            max_query_bytes: None,
2081            temp_run_factory: None,
2082            users: UserStore::new(),
2083            publications: publications::Publications::new(),
2084            subscriptions: subscriptions::Subscriptions::new(),
2085            statistics: statistics::Statistics::new(),
2086            plan_cache: plan_cache::PlanCache::new(),
2087            query_stats: query_stats::QueryStats::new(),
2088            activity_provider: None,
2089            audit_chain_provider: None,
2090            audit_verifier: None,
2091            slow_query_threshold_us: None,
2092            slow_query_logger: None,
2093            session_params: BTreeMap::new(),
2094            cursors: BTreeMap::new(),
2095            last_insert_id: core::sync::atomic::AtomicI64::new(0),
2096            row_count: 0,
2097            user_vars: BTreeMap::new(),
2098            temp_tables: BTreeSet::new(),
2099            temp_sequences: BTreeSet::new(),
2100            temp_views: BTreeSet::new(),
2101            listen_channels: BTreeSet::new(),
2102            tx_pending_notifies: Vec::new(),
2103            delivered_notifies: Vec::new(),
2104            pending_notices: Vec::new(),
2105            spill_stats: crate::tempstore::SpillStats::default(),
2106            xact_commit: core::sync::atomic::AtomicU64::new(0),
2107            xact_rollback: core::sync::atomic::AtomicU64::new(0),
2108            backend_count_fn: None,
2109            backend_pid_fn: None,
2110            wal_lsn_fn: None,
2111            backend_signal_fn: None,
2112            tz_offset_fn: None,
2113            tz_localize_fn: None,
2114            tz_canon_fn: None,
2115            tz_abbrev_fn: None,
2116            tz_all_fn: None,
2117            stat_tup_inserted: 0,
2118            table_write_stats: alloc::collections::BTreeMap::new(),
2119            commit_epoch: 0,
2120            stat_tup_updated: 0,
2121            stat_tup_deleted: 0,
2122            local_guc_saves: Vec::new(),
2123            render_style: crate::eval::RenderStyle::default(),
2124            savepoint_guc_marks: Vec::new(),
2125            trigger_recursion_depth: 0,
2126            rule_rewrite_active: false,
2127            foreign_key_checks: true,
2128            meta_views_materialised: false,
2129            pending_foreign_keys: Vec::new(),
2130            env_cfg: testkit::EnvConfig::default(),
2131            #[cfg(feature = "injection-points")]
2132            injection_store: alloc::sync::Arc::new(
2133                crate::testkit::injection::InjectionStore::default(),
2134            ),
2135            redo_capture: false,
2136            current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
2137            last_redo: Vec::new(),
2138            table_change_seq: alloc::collections::BTreeMap::new(),
2139            matview_refresh_watermark: alloc::collections::BTreeMap::new(),
2140            matview_maintainable: alloc::collections::BTreeMap::new(),
2141            matview_delta_buf: alloc::collections::BTreeMap::new(),
2142            matview_delta_overflow: alloc::collections::BTreeSet::new(),
2143            matview_row_map: alloc::collections::BTreeMap::new(),
2144        }
2145    }
2146
2147    /// Restore an engine + user table from a v4.1 envelope produced
2148    /// by `snapshot_with_users()`. Falls back to plain catalog-only
2149    /// restore if the envelope magic isn't present (so v3.x snapshot
2150    /// files still load). v6.1.2 adds the optional publications
2151    /// trailer (envelope v3); a v1/v2 envelope deserialises to an
2152    /// empty publication table.
2153    pub fn restore_envelope(buf: &[u8]) -> Result<Self, EngineError> {
2154        match split_envelope(buf) {
2155            EnvelopeParse::Pair {
2156                catalog: catalog_bytes,
2157                users: user_bytes,
2158                publications: pub_bytes,
2159                subscriptions: sub_bytes,
2160                statistics: stats_bytes,
2161            } => {
2162                let mut catalog =
2163                    Catalog::deserialize(catalog_bytes).map_err(EngineError::Storage)?;
2164                crate::ddl::rebuild_all_excl_indexes(&mut catalog);
2165                let users = users::deserialize_users(user_bytes)
2166                    .map_err(|e| EngineError::Unsupported(alloc::format!("users restore: {e}")))?;
2167                let publications = match pub_bytes {
2168                    Some(b) => publications::Publications::deserialize(b).map_err(|e| {
2169                        EngineError::Unsupported(alloc::format!("publications restore: {e:?}"))
2170                    })?,
2171                    None => publications::Publications::new(),
2172                };
2173                let subscriptions = match sub_bytes {
2174                    Some(b) => subscriptions::Subscriptions::deserialize(b).map_err(|e| {
2175                        EngineError::Unsupported(alloc::format!("subscriptions restore: {e:?}"))
2176                    })?,
2177                    None => subscriptions::Subscriptions::new(),
2178                };
2179                let statistics = match stats_bytes {
2180                    Some(b) => statistics::Statistics::deserialize(b).map_err(|e| {
2181                        EngineError::Unsupported(alloc::format!("statistics restore: {e:?}"))
2182                    })?,
2183                    None => statistics::Statistics::new(),
2184                };
2185                Ok(Self {
2186                    lock_skip_rows: None,
2187                    catalog,
2188                    parallel_runner: ParallelRunnerSlot::default(),
2189                    tx_catalogs: BTreeMap::new(),
2190                    table_last_commit: BTreeMap::new(),
2191                    commit_seq: 0,
2192                    current_tx: None,
2193                    backslash_escapes: false,
2194                    mysql_strict: true,
2195                    lo_descriptors: BTreeMap::new(),
2196                    lo_next_fd: 0,
2197                    prepared_statements: alloc::collections::BTreeMap::new(),
2198                    current_session: 0,
2199                    sessions: BTreeMap::new(),
2200                    advisory_locks: BTreeMap::new(),
2201                    last_sequence_used: None,
2202                    seq_currvals: alloc::collections::BTreeMap::new(),
2203                    next_tx_id: 1,
2204                    active_writer_versions: BTreeSet::new(),
2205                    aborted_versions: BTreeSet::new(),
2206                    locks: crate::locks::LockTable::new(),
2207                    mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
2208                    autovacuum: true,
2209                    autovacuum_inline: true,
2210                    tx_writer_versions: BTreeMap::new(),
2211                    stmt_writer_version: None,
2212                    clock: None,
2213                    salt_fn: None,
2214                    max_query_rows: None,
2215                    max_query_bytes: None,
2216                    temp_run_factory: None,
2217                    users,
2218                    publications,
2219                    subscriptions,
2220                    statistics,
2221                    plan_cache: plan_cache::PlanCache::new(),
2222                    query_stats: query_stats::QueryStats::new(),
2223                    activity_provider: None,
2224                    audit_chain_provider: None,
2225                    audit_verifier: None,
2226                    slow_query_threshold_us: None,
2227                    slow_query_logger: None,
2228                    session_params: BTreeMap::new(),
2229                    cursors: BTreeMap::new(),
2230                    last_insert_id: core::sync::atomic::AtomicI64::new(0),
2231                    row_count: 0,
2232                    user_vars: BTreeMap::new(),
2233                    temp_tables: BTreeSet::new(),
2234                    temp_sequences: BTreeSet::new(),
2235                    temp_views: BTreeSet::new(),
2236                    listen_channels: BTreeSet::new(),
2237                    tx_pending_notifies: Vec::new(),
2238                    delivered_notifies: Vec::new(),
2239                    pending_notices: Vec::new(),
2240                    spill_stats: crate::tempstore::SpillStats::default(),
2241                    xact_commit: core::sync::atomic::AtomicU64::new(0),
2242                    xact_rollback: core::sync::atomic::AtomicU64::new(0),
2243                    backend_count_fn: None,
2244                    backend_pid_fn: None,
2245                    wal_lsn_fn: None,
2246                    backend_signal_fn: None,
2247                    tz_offset_fn: None,
2248                    tz_localize_fn: None,
2249                    tz_canon_fn: None,
2250                    tz_abbrev_fn: None,
2251                    tz_all_fn: None,
2252                    stat_tup_inserted: 0,
2253                    table_write_stats: alloc::collections::BTreeMap::new(),
2254                    commit_epoch: 0,
2255                    stat_tup_updated: 0,
2256                    stat_tup_deleted: 0,
2257                    local_guc_saves: Vec::new(),
2258                    render_style: crate::eval::RenderStyle::default(),
2259                    savepoint_guc_marks: Vec::new(),
2260                    trigger_recursion_depth: 0,
2261                    rule_rewrite_active: false,
2262                    foreign_key_checks: true,
2263                    meta_views_materialised: false,
2264                    pending_foreign_keys: Vec::new(),
2265                    env_cfg: testkit::EnvConfig::default(),
2266                    #[cfg(feature = "injection-points")]
2267                    injection_store: alloc::sync::Arc::new(
2268                        crate::testkit::injection::InjectionStore::default(),
2269                    ),
2270                    redo_capture: false,
2271                    current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
2272                    last_redo: Vec::new(),
2273                    table_change_seq: alloc::collections::BTreeMap::new(),
2274                    matview_refresh_watermark: alloc::collections::BTreeMap::new(),
2275                    matview_maintainable: alloc::collections::BTreeMap::new(),
2276                    matview_delta_buf: alloc::collections::BTreeMap::new(),
2277                    matview_delta_overflow: alloc::collections::BTreeSet::new(),
2278                    matview_row_map: alloc::collections::BTreeMap::new(),
2279                })
2280            }
2281            EnvelopeParse::CrcMismatch { expected, computed } => {
2282                Err(EngineError::Storage(StorageError::Corrupt(alloc::format!(
2283                    "snapshot envelope CRC32 mismatch (expected={expected:#010x}, computed={computed:#010x})"
2284                ))))
2285            }
2286            EnvelopeParse::Bare => {
2287                let mut catalog = Catalog::deserialize(buf).map_err(EngineError::Storage)?;
2288                crate::ddl::rebuild_all_excl_indexes(&mut catalog);
2289                Ok(Self::restore(catalog))
2290            }
2291        }
2292    }
2293
2294    pub const fn users(&self) -> &UserStore {
2295        &self.users
2296    }
2297
2298    /// Builder: attach a wall clock so `NOW()` / `CURRENT_TIMESTAMP` /
2299    /// `CURRENT_DATE` evaluate to a real value instead of erroring out.
2300    /// v7.39 (round 279) — announce which connection is about to run.
2301    /// The server calls this before every statement; embedded hosts
2302    /// never do and stay on session 0.
2303    ///
2304    /// Swapping parks the outgoing connection's state and installs the
2305    /// incoming one's, creating it on first sight. The plan cache is
2306    /// cleared because the string-literal dialect is part of what
2307    /// swaps and the same SQL text lexes differently under it.
2308    pub fn set_current_session(&mut self, id: u32) {
2309        if id == self.current_session {
2310            return;
2311        }
2312        let outgoing = SessionBag {
2313            session_params: core::mem::take(&mut self.session_params),
2314            backslash_escapes: self.backslash_escapes,
2315            mysql_strict: self.mysql_strict,
2316            prepared_statements: core::mem::take(&mut self.prepared_statements),
2317            lo_descriptors: core::mem::take(&mut self.lo_descriptors),
2318            lo_next_fd: self.lo_next_fd,
2319            cursors: core::mem::take(&mut self.cursors),
2320            last_insert_id: self
2321                .last_insert_id
2322                .load(core::sync::atomic::Ordering::Relaxed),
2323            row_count: self.row_count,
2324            user_vars: core::mem::take(&mut self.user_vars),
2325            temp_tables: core::mem::take(&mut self.temp_tables),
2326            temp_sequences: core::mem::take(&mut self.temp_sequences),
2327            temp_views: core::mem::take(&mut self.temp_views),
2328            seq_currvals: core::mem::take(&mut self.seq_currvals),
2329            last_sequence_used: self.last_sequence_used.take(),
2330            isolation_level: self.current_isolation_level,
2331        };
2332        self.sessions.insert(self.current_session, outgoing);
2333        let incoming = self.sessions.remove(&id).unwrap_or_default();
2334        self.session_params = incoming.session_params;
2335        self.backslash_escapes = incoming.backslash_escapes;
2336        self.mysql_strict = incoming.mysql_strict;
2337        self.prepared_statements = incoming.prepared_statements;
2338        self.lo_descriptors = incoming.lo_descriptors;
2339        self.lo_next_fd = incoming.lo_next_fd;
2340        self.cursors = incoming.cursors;
2341        self.last_insert_id.store(
2342            incoming.last_insert_id,
2343            core::sync::atomic::Ordering::Relaxed,
2344        );
2345        self.row_count = incoming.row_count;
2346        self.user_vars = incoming.user_vars;
2347        self.temp_tables = incoming.temp_tables;
2348        self.temp_sequences = incoming.temp_sequences;
2349        self.temp_views = incoming.temp_views;
2350        self.seq_currvals = incoming.seq_currvals;
2351        self.last_sequence_used = incoming.last_sequence_used;
2352        self.current_isolation_level = incoming.isolation_level;
2353        self.current_session = id;
2354        // The incoming session's temp namespace must be live before its very
2355        // first statement resolves a name.
2356        self.refresh_temp_prefix();
2357        self.plan_cache.clear();
2358    }
2359
2360    /// v7.39 (round 436) — the catalog-name prefix session `id` stores its
2361    /// TEMPORARY tables under. Mirrors PG's per-session `pg_temp_N` schema;
2362    /// the leading underscores keep it out of any name a client can write.
2363    fn temp_prefix_for(id: u32) -> String {
2364        alloc::format!("__spg_temp_{id}__")
2365    }
2366
2367    /// The catalog name this session's TEMPORARY table `logical` takes.
2368    pub(crate) fn session_temp_name(&self, logical: &str) -> String {
2369        alloc::format!("{}{logical}", Self::temp_prefix_for(self.current_session))
2370    }
2371
2372    /// v7.39 (round 436) — point every catalog this session can reach at its
2373    /// temp namespace, or at none when it owns no temporary tables (so a
2374    /// session that never made one pays a single `Option` check per lookup).
2375    /// Both the committed catalog and any open transaction's shadow are set:
2376    /// a temp table created inside a transaction must resolve there too.
2377    pub(crate) fn refresh_temp_prefix(&mut self) {
2378        let prefix = if self.temp_tables.is_empty()
2379            && self.temp_sequences.is_empty()
2380            && self.temp_views.is_empty()
2381        {
2382            None
2383        } else {
2384            Some(Self::temp_prefix_for(self.current_session))
2385        };
2386        self.catalog.set_temp_prefix(prefix.clone());
2387        for shadow in self.tx_catalogs.values_mut() {
2388            shadow.catalog.set_temp_prefix(prefix.clone());
2389        }
2390    }
2391
2392    /// v7.39 (round 279) — a connection has gone away: drop its parked
2393    /// state and release every advisory lock it still held, which is
2394    /// what PG does at backend exit.
2395    pub fn end_session(&mut self, id: u32) {
2396        // v7.39 (round 436) — a TEMPORARY table dies with its session, in
2397        // both PG and MySQL. Done before the bag is dropped, since the bag
2398        // is what knows which tables the session owns.
2399        let owned: Vec<String> = if id == self.current_session {
2400            self.temp_tables.iter().cloned().collect()
2401        } else {
2402            self.sessions
2403                .get(&id)
2404                .map(|b| b.temp_tables.iter().cloned().collect())
2405                .unwrap_or_default()
2406        };
2407        // v7.39 (round 469) — the same for TEMPORARY sequences and views,
2408        // which PG also drops at backend exit.
2409        let owned_seqs: Vec<String> = if id == self.current_session {
2410            self.temp_sequences.iter().cloned().collect()
2411        } else {
2412            self.sessions
2413                .get(&id)
2414                .map(|b| b.temp_sequences.iter().cloned().collect())
2415                .unwrap_or_default()
2416        };
2417        let owned_views: Vec<String> = if id == self.current_session {
2418            self.temp_views.iter().cloned().collect()
2419        } else {
2420            self.sessions
2421                .get(&id)
2422                .map(|b| b.temp_views.iter().cloned().collect())
2423                .unwrap_or_default()
2424        };
2425        if !owned.is_empty() || !owned_seqs.is_empty() || !owned_views.is_empty() {
2426            let prefix = Self::temp_prefix_for(id);
2427            for logical in owned {
2428                let mangled = alloc::format!("{prefix}{logical}");
2429                self.catalog.drop_table(&mangled);
2430            }
2431            for logical in owned_seqs {
2432                let mangled = alloc::format!("{prefix}{logical}");
2433                self.catalog.drop_sequence(&mangled);
2434            }
2435            for logical in owned_views {
2436                let mangled = alloc::format!("{prefix}{logical}");
2437                self.catalog.drop_view(&mangled);
2438            }
2439            if id == self.current_session {
2440                self.temp_tables.clear();
2441                self.temp_sequences.clear();
2442                self.temp_views.clear();
2443                self.refresh_temp_prefix();
2444            }
2445        }
2446        self.sessions.remove(&id);
2447        self.advisory_locks.retain(|_, (owner, _)| *owner != id);
2448        if id == self.current_session {
2449            self.session_params.clear();
2450            self.prepared_statements.clear();
2451            self.backslash_escapes = false;
2452            self.mysql_strict = true;
2453            self.lo_descriptors.clear();
2454            self.lo_next_fd = 0;
2455            self.cursors.clear();
2456            self.current_session = 0;
2457        }
2458    }
2459
2460    /// v7.39 (round 302, V15) — force the current session's string-literal
2461    /// dialect. A MySQL-protocol connection defaults to MySQL semantics
2462    /// (backslash is an escape: `'\n'` is a newline), which PG's own
2463    /// default (`standard_conforming_strings = on`) does not do. The
2464    /// mysql-wire shim calls this once, right after installing its
2465    /// session, so a client that never sends `SET sql_mode` still gets
2466    /// MySQL string handling; a later `SET sql_mode='NO_BACKSLASH_ESCAPES'`
2467    /// flips it back through the normal SET path. Clearing the plan cache
2468    /// mirrors [`set_current_session`] — the same SQL text lexes
2469    /// differently once the flag moves.
2470    pub fn set_backslash_escapes(&mut self, flag: bool) {
2471        if flag != self.backslash_escapes {
2472            self.backslash_escapes = flag;
2473            self.plan_cache.clear();
2474        }
2475    }
2476
2477    /// v7.39 (round 279) — take an advisory lock. Returns false only
2478    /// when ANOTHER session holds it; re-taking one this session
2479    /// already holds bumps a depth counter, as in PG.
2480    pub(crate) fn advisory_try_lock(&mut self, key: i64) -> bool {
2481        let me = self.current_session;
2482        match self.advisory_locks.get_mut(&key) {
2483            Some((owner, depth)) if *owner == me => {
2484                *depth += 1;
2485                true
2486            }
2487            Some(_) => false,
2488            None => {
2489                self.advisory_locks.insert(key, (me, 1));
2490                true
2491            }
2492        }
2493    }
2494
2495    /// Release one level. False when this session does not hold it —
2496    /// PG answers false and emits a warning; SPG answers false.
2497    pub(crate) fn advisory_unlock(&mut self, key: i64) -> bool {
2498        let me = self.current_session;
2499        match self.advisory_locks.get_mut(&key) {
2500            Some((owner, depth)) if *owner == me => {
2501                *depth -= 1;
2502                if *depth == 0 {
2503                    self.advisory_locks.remove(&key);
2504                }
2505                true
2506            }
2507            _ => false,
2508        }
2509    }
2510
2511    /// Release every advisory lock this session holds.
2512    pub(crate) fn advisory_unlock_all(&mut self) {
2513        let me = self.current_session;
2514        self.advisory_locks.retain(|_, (owner, _)| *owner != me);
2515    }
2516
2517    /// v7.39 (round 417) — the current session's id (for MySQL
2518    /// `IS_USED_LOCK`, which reports the connection that holds a lock).
2519    /// v7.39 (round 430) — read one of this session's MySQL USER
2520    /// variables. `None` when it was never set, which the caller turns
2521    /// into NULL (MariaDB reads an unset user variable as NULL).
2522    pub(crate) fn user_var(&self, name: &str) -> Option<&spg_storage::Value<'static>> {
2523        self.user_vars.get(name)
2524    }
2525
2526    pub(crate) const fn current_session_id(&self) -> u32 {
2527        self.current_session
2528    }
2529
2530    /// v7.39 (round 417) — who holds an advisory-lock key (any session id),
2531    /// or `None` when nobody holds it. Used by MySQL `IS_USED_LOCK` and to
2532    /// separate `RELEASE_LOCK`'s "not held by anyone" (returns NULL) from
2533    /// "held by someone else" (returns 0).
2534    pub(crate) fn advisory_holder(&self, key: i64) -> Option<u32> {
2535        self.advisory_locks.get(&key).map(|(owner, _)| *owner)
2536    }
2537
2538    /// v7.39 (round 417) — MySQL `RELEASE_ALL_LOCKS()` returns the number of
2539    /// locks it released; PG's `pg_advisory_unlock_all()` returns void.
2540    pub(crate) fn advisory_unlock_all_count(&mut self) -> i32 {
2541        let me = self.current_session;
2542        // Total depth held by this session, so re-locked keys count as many.
2543        let mut n: i32 = 0;
2544        for (_, (owner, depth)) in &self.advisory_locks {
2545            if *owner == me {
2546                n = n.saturating_add(*depth as i32);
2547            }
2548        }
2549        self.advisory_locks.retain(|_, (owner, _)| *owner != me);
2550        n
2551    }
2552
2553    #[must_use]
2554    pub const fn with_clock(mut self, clock: ClockFn) -> Self {
2555        self.clock = Some(clock);
2556        self
2557    }
2558
2559    /// Builder: attach an OS-backed RNG for per-user password salts.
2560    /// The host (`spg-server`) typically wires this to `/dev/urandom`.
2561    #[must_use]
2562    pub const fn with_salt_fn(mut self, f: SaltFn) -> Self {
2563        self.salt_fn = Some(f);
2564        self
2565    }
2566
2567    /// v7.38 元机制 D — install a frozen [`testkit::EnvConfig`] snapshot.
2568    ///
2569    /// Hosts (spg-server, spg-embedded, tests) call this once at engine
2570    /// init with either `EnvConfig::from_env()` (production-with-test-vars)
2571    /// or `EnvConfig::builder()....build()` (programmatic). After
2572    /// construction the engine never reads env vars; all test-mode
2573    /// behaviour flows through `self.env_cfg()`.
2574    #[must_use]
2575    pub fn with_env_cfg(mut self, env_cfg: testkit::EnvConfig) -> Self {
2576        // r1051 — a configured seed reaches `random()` too, not only
2577        // the `rng_seed()` accessor: the D-mechanism's "single seed
2578        // source" claim, made true at the SQL level (first pin_v738_
2579        // catch). Production engines carry no seed and never touch
2580        // the PRNG state here.
2581        if let Some(seed) = env_cfg.random_seed {
2582            crate::eval::math::prng_install_seed(seed);
2583        }
2584        // r1058 — `SPG_TEST_FIXED_CLOCK_MICROS` pins the clock for
2585        // hosts that read GUCs from env instead of calling
2586        // `with_clock` (the server). Process-global by necessity: a
2587        // `ClockFn` is a plain fn pointer and cannot capture.
2588        if let Some(micros) = env_cfg.fixed_clock_micros {
2589            FIXED_CLOCK_MICROS.store(micros, core::sync::atomic::Ordering::Relaxed);
2590            self = self.with_clock(fixed_clock_from_env);
2591        }
2592        self.env_cfg = env_cfg;
2593        self
2594    }
2595
2596    /// v7.38 元机制 D — frozen test-mode GUC snapshot. Hot paths gate
2597    /// nondeterministic surfaces on fields of this struct; production
2598    /// default keeps every field at `false / None / Auto` so the
2599    /// optimiser can const-fold the gate.
2600    pub fn env_cfg(&self) -> &testkit::EnvConfig {
2601        &self.env_cfg
2602    }
2603
2604    /// v7.38 元机制 D acceptor — single seed source for every
2605    /// nondeterministic engine subsystem (hash builders, randomised
2606    /// tie-breakers, …). Honour `SPG_TEST_RANDOM_SEED=N` when set;
2607    /// otherwise derive from the engine's wall clock (production) or
2608    /// fall back to a fixed sentinel when the host hasn't installed
2609    /// a clock. Two engines built with the same builder seed return
2610    /// byte-equal output for the same query.
2611    /// See `xtests/sigil/test-mode-gucs.md`.
2612    pub fn rng_seed(&self) -> u64 {
2613        if let Some(seed) = self.env_cfg.random_seed {
2614            return seed;
2615        }
2616        match self.clock {
2617            Some(f) => f() as u64,
2618            // Production engines without a clock installed get a fixed
2619            // non-zero sentinel; same shape as PG's `random()` start
2620            // state under a `setseed(0)`.
2621            None => 0xBAD_5EED_DEAD_BEEF,
2622        }
2623    }
2624
2625    /// v7.38 P0 元机制 A — push this engine's `InjectionStore` onto
2626    /// the thread-local stack so any `injection_point!()` reached
2627    /// during the returned guard's lifetime resolves against this
2628    /// engine. Mirrors PG's per-backend injection table.
2629    ///
2630    /// Returns a no-op guard when the `injection-points` feature is
2631    /// off so call sites don't need `#[cfg]`.
2632    pub fn enter_injection_scope(&self) -> crate::testkit::injection::InjectionGuard {
2633        #[cfg(feature = "injection-points")]
2634        {
2635            crate::testkit::injection::enter_scope(&self.injection_store)
2636        }
2637        #[cfg(not(feature = "injection-points"))]
2638        {
2639            crate::testkit::injection::new_guard()
2640        }
2641    }
2642
2643    /// v7.38 P0 元机制 A — expose the per-engine store so tests can
2644    /// query notice counts / detach actions without parsing SQL
2645    /// output. Only present when the feature is on.
2646    #[cfg(feature = "injection-points")]
2647    pub fn injection_store(&self) -> alloc::sync::Arc<crate::testkit::injection::InjectionStore> {
2648        self.injection_store.clone()
2649    }
2650
2651    /// Builder: cap the number of rows a single SELECT may return.
2652    /// Exceeding the cap raises `EngineError::RowLimitExceeded` —
2653    /// the bound is checked inside the executor so a runaway
2654    /// catalog scan can't allocate millions of rows before the
2655    /// server gets a chance to reject the result.
2656    #[must_use]
2657    pub const fn with_max_query_rows(mut self, n: usize) -> Self {
2658        self.max_query_rows = Some(n);
2659        self
2660    }
2661
2662    /// Builder: cap the approximate heap bytes a single SELECT's
2663    /// join/filter materialisation may hold. Exceeding the cap
2664    /// raises `EngineError::QueryBytesExceeded`. Rows are the wrong
2665    /// unit when one row carries a multi-MB body (mailrs round-26:
2666    /// 1000-row batches of full mail text walked a 15 GiB host into
2667    /// reclaim livelock without ever tripping a row ceiling).
2668    #[must_use]
2669    pub const fn with_max_query_bytes(mut self, n: usize) -> Self {
2670        self.max_query_bytes = Some(n);
2671        self
2672    }
2673
2674    /// The *committed* catalog. Note: during a transaction this returns the
2675    /// pre-TX state — `SELECT` inside a TX goes through `execute()` and reads
2676    /// the shadow. Tests that inspect outside-TX state should use this.
2677    pub const fn catalog(&self) -> &Catalog {
2678        &self.catalog
2679    }
2680
2681    /// Capture a frozen view of the committed engine state. Catalog
2682    /// is O(1) Arc bump; trailers are cheap clones. Decouples "capture"
2683    /// (needs &Engine) from "serialize" (CPU, no engine access) — the
2684    /// seam the background-checkpoint worker rides in CoW-2.
2685    pub fn snapshot_data(&self) -> EngineSnapshot {
2686        EngineSnapshot {
2687            catalog: self.catalog.clone(),
2688            users: self.users.clone(),
2689            publications: self.publications.clone(),
2690            subscriptions: self.subscriptions.clone(),
2691            statistics: self.statistics.clone(),
2692        }
2693    }
2694
2695    /// Serialize the *committed* catalog to bytes. v0.6 was full-snapshot; v0.9
2696    /// adds the rule that an open TX's shadow is never snapshotted — only the
2697    /// post-COMMIT state is persisted. v4.1 wraps the catalog in an envelope
2698    /// when there are users to persist; an empty user table snapshots as the
2699    /// bare catalog format (backwards-compat with v3.x readers). v6.1.2
2700    /// adds publications to the envelope condition: either non-empty
2701    /// users OR non-empty publications now triggers the envelope path.
2702    pub fn snapshot(&self) -> Vec<u8> {
2703        self.snapshot_data().serialize()
2704    }
2705
2706    /// True when at least one TX slot is in flight. v4.41.1 runtime
2707    /// invariant: at most one slot active at a time (dispatch holds
2708    /// `engine.write()` across the entire wrap). v4.42 will let this
2709    /// return true with multiple slots concurrently.
2710    pub fn in_transaction(&self) -> bool {
2711        !self.tx_catalogs.is_empty()
2712    }
2713
2714    /// v7.37 C.5 (A.2) — per-connection in-transaction test. A given
2715    /// connection is "in a transaction" iff its own `tx_id` has an open
2716    /// shadow slot. Unlike [`in_transaction`] (which is true if *any* tx is
2717    /// open), this lets concurrent connections each carry their own explicit
2718    /// transaction without colliding on the global slot. `IMPLICIT_TX` never
2719    /// has a persistent slot (autocommit reads/writes the main catalog), so
2720    /// this is false for the autocommit id.
2721    pub fn is_tx_open(&self, tx_id: TxId) -> bool {
2722        self.tx_catalogs.contains_key(&tx_id)
2723    }
2724
2725    /// v7.37 (round 828) — the user store THIS session should read:
2726    /// its transaction's role shadow when one exists, the committed
2727    /// store otherwise. The auth path and other sessions read
2728    /// `self.users` directly on purpose — an uncommitted role must not
2729    /// be visible to them, let alone able to log in.
2730    pub(crate) fn effective_users(&self) -> &crate::users::UserStore {
2731        if let Some(tx) = self.current_tx
2732            && let Some(state) = self.tx_catalogs.get(&tx)
2733            && let Some(shadow) = &state.users
2734        {
2735            return shadow;
2736        }
2737        &self.users
2738    }
2739
2740    /// v7.37 (round 828) — the store role DDL writes to: the TX's role
2741    /// shadow (created from the committed store on first use) inside a
2742    /// transaction, the committed store in autocommit. Every mutation
2743    /// of roles or memberships goes through here, so `BEGIN; CREATE
2744    /// ROLE r; ROLLBACK` leaves nothing behind — the shadow drops with
2745    /// the TxState — and COMMIT installs the shadow wholesale.
2746    pub(crate) fn role_ddl_users_mut(&mut self) -> &mut crate::users::UserStore {
2747        let tx_slot = self
2748            .current_tx
2749            .filter(|tx| self.tx_catalogs.contains_key(tx));
2750        match tx_slot {
2751            Some(tx) => {
2752                if self
2753                    .tx_catalogs
2754                    .get(&tx)
2755                    .is_some_and(|state| state.users.is_none())
2756                {
2757                    let committed = self.users.clone();
2758                    if let Some(state) = self.tx_catalogs.get_mut(&tx) {
2759                        state.users = Some(committed);
2760                    }
2761                }
2762                self.tx_catalogs
2763                    .get_mut(&tx)
2764                    .and_then(|state| state.users.as_mut())
2765                    .expect("role shadow ensured just above for an open tx slot")
2766            }
2767            None => &mut self.users,
2768        }
2769    }
2770
2771    /// v4.41.1 allocate a fresh TX handle. Used by spg-server dispatch
2772    /// to scope each implicit-wrap BEGIN..stmt..COMMIT to its own slot
2773    /// in `tx_catalogs`. v4.42 — the commit-barrier leader allocates
2774    /// one of these per task in its group, runs `BEGIN`+sql+`COMMIT`
2775    /// sequentially under a single `engine.write()` so each task's
2776    /// mutations accumulate into shared state, then either keeps the
2777    /// accumulated state (fsync OK) or restores the pre-image via
2778    /// `replace_catalog` (fsync err).
2779    pub fn alloc_tx_id(&mut self) -> TxId {
2780        let id = TxId(self.next_tx_id);
2781        self.next_tx_id = self.next_tx_id.saturating_add(1);
2782        id
2783    }
2784
2785    /// v4.42 — atomically replace the live catalog. Used by the
2786    /// commit-barrier leader to roll back a group whose batched
2787    /// fsync failed: the leader snapshots `engine.catalog().clone()`
2788    /// (O(1) Arc bump after the v4.39/v4.40 persistent migration)
2789    /// at group start, sequentially applies each task's BEGIN+sql+
2790    /// COMMIT under the same write lock to accumulate mutations
2791    /// into shared state, batches the WAL bytes, fsyncs once, and
2792    /// on failure calls this with the pre-image to undo every
2793    /// task in the group at once.
2794    ///
2795    /// **Does NOT touch `tx_catalogs` / `current_tx`.** Any
2796    /// explicit-TX slot from a concurrent client (created via the
2797    /// legacy `IMPLICIT_TX`-less dispatch path or via the future
2798    /// MVCC-readers v5+ work) has its own snapshot baked into the
2799    /// slot — restoring `self.catalog` to the pre-image leaves
2800    /// those slots untouched, exactly as they were when the leader
2801    /// took the lock. The leader's own implicit-TX slots are all
2802    /// already discarded (`exec_commit` removed them as each
2803    /// task's COMMIT ran) by the time this is reached.
2804    pub fn replace_catalog(&mut self, catalog: Catalog) {
2805        self.catalog = catalog;
2806    }
2807
2808    /// v6.7.0 — public shim around `Catalog::freeze_oldest_to_cold`
2809    /// so tests + the spg-server freezer can drive a freeze without
2810    /// reaching into the private `active_catalog_mut`. v6.7.4
2811    /// parallel freezer will build on this surface.
2812    ///
2813    /// Marks the table's cached `cold_row_count` stale because the
2814    /// freeze added cold locators that ANALYZE hasn't yet refreshed.
2815    pub fn freeze_oldest_to_cold(
2816        &mut self,
2817        table_name: &str,
2818        index_name: &str,
2819        max_rows: usize,
2820    ) -> Result<spg_storage::FreezeReport, EngineError> {
2821        let report = self
2822            .active_catalog_mut()
2823            .freeze_oldest_to_cold(table_name, index_name, max_rows)
2824            .map_err(EngineError::Storage)?;
2825        if let Some(t) = self.active_catalog_mut().get_mut(table_name) {
2826            t.mark_cold_row_count_stale();
2827        }
2828        Ok(report)
2829    }
2830
2831    /// v6.7.5 — public shim used by the spg-server follower's
2832    /// segment-forwarding receiver. Registers a cold-tier segment
2833    /// at a specific id (the master's id, as transmitted on the
2834    /// wire) so the follower's BTree-Cold locators stay byte-
2835    /// identical with the master's. Wraps
2836    /// `Catalog::load_segment_bytes_at` under the standard
2837    /// clone-mutate-replace pattern.
2838    ///
2839    /// Returns `Ok(())` on success **and** on the "slot already
2840    /// occupied" case — a follower mid-reconnect may receive a
2841    /// segment chunk for a segment_id it already has on disk
2842    /// (forwarded last session); the caller should treat that
2843    /// path as a no-op rather than a fatal error.
2844    pub fn receive_cold_segment(
2845        &mut self,
2846        segment_id: u32,
2847        bytes: Vec<u8>,
2848    ) -> Result<(), EngineError> {
2849        let mut new_cat = self.catalog.clone();
2850        match new_cat.load_segment_bytes_at(segment_id, bytes) {
2851            Ok(()) => {
2852                self.replace_catalog(new_cat);
2853                Ok(())
2854            }
2855            Err(StorageError::Corrupt(msg)) if msg.contains("already occupied") => Ok(()),
2856            Err(e) => Err(EngineError::Storage(e)),
2857        }
2858    }
2859
2860    /// v7.39 (round 598) — mutable access to the base catalog, for the
2861    /// recursive-CTE loop.
2862    ///
2863    /// It built a whole `Engine` per iteration to hold the working set:
2864    /// `Engine::restore` initialises 82 fields, and a counting allocator put
2865    /// the loop at 63 allocations and 104 kB PER ITERATION — 1 GB for a
2866    /// 10,000-row recursive CTE, none of it dependent on how much else was
2867    /// in the catalog. One engine, whose CTE table is refilled each round,
2868    /// needs this.
2869    pub(crate) fn base_catalog_mut(&mut self) -> &mut Catalog {
2870        &mut self.catalog
2871    }
2872
2873    pub(crate) fn active_catalog(&self) -> &Catalog {
2874        match self.current_tx {
2875            Some(t) => self
2876                .tx_catalogs
2877                .get(&t)
2878                .map_or(&self.catalog, |s| &s.catalog),
2879            None => &self.catalog,
2880        }
2881    }
2882
2883    fn active_catalog_mut(&mut self) -> &mut Catalog {
2884        let tx = self.current_tx;
2885        match tx {
2886            Some(t) => match self.tx_catalogs.get_mut(&t) {
2887                Some(s) => {
2888                    // v7.39 (round 494) — see `TxState::shadow_dirty`.
2889                    s.shadow_dirty = true;
2890                    &mut s.catalog
2891                }
2892                None => &mut self.catalog,
2893            },
2894            None => &mut self.catalog,
2895        }
2896    }
2897
2898    /// v7.34 (crash-recovery P0 #2) — turn row-level redo capture on/off.
2899    /// The embedding layer enables it when persistence is on so each
2900    /// mutating `execute` records the physical [`RowChange`]s it applied
2901    /// (drained via [`Engine::take_redo`]). Off = zero capture overhead.
2902    pub fn set_redo_capture(&mut self, on: bool) {
2903        self.redo_capture = on;
2904    }
2905
2906    /// v7.39 (round 735, S14/B3) — record that `table`'s rows (or shape)
2907    /// changed. Cheap (one BTreeMap bump), called from every write entry;
2908    /// the materialized-view refresh watermark reads it.
2909    /// v7.39 (round 736) — per-view buffered-delta ceiling. Past this,
2910    /// the view's next REFRESH is a full one (the buffer is the
2911    /// optimisation, not the truth).
2912    pub(crate) const MATVIEW_DELTA_CEILING: usize = 65_536;
2913
2914    /// v7.39 (round 736) — fan the drained redo out to every
2915    /// maintainable view whose base table it touches.
2916    pub(crate) fn fan_out_matview_deltas(&mut self, drained: &[RowChange]) {
2917        if self.matview_maintainable.is_empty() {
2918            return;
2919        }
2920        for ch in drained {
2921            let t = ch.table_name().to_ascii_lowercase();
2922            let hit: Vec<String> = self
2923                .matview_maintainable
2924                .iter()
2925                .filter(|(_, base)| **base == t)
2926                .map(|(mv, _)| mv.clone())
2927                .collect();
2928            for mv in hit {
2929                if self.matview_delta_overflow.contains(&mv) {
2930                    continue;
2931                }
2932                let buf = self.matview_delta_buf.entry(mv.clone()).or_default();
2933                if buf.len() >= Self::MATVIEW_DELTA_CEILING {
2934                    self.matview_delta_overflow.insert(mv.clone());
2935                    self.matview_delta_buf.remove(&mv);
2936                } else {
2937                    buf.push(ch.clone());
2938                    MATVIEW_FANOUT_BUFFERED.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2939                }
2940            }
2941        }
2942    }
2943
2944    pub(crate) fn bump_table_change(&mut self, table: &str) {
2945        let k = table.to_ascii_lowercase();
2946        *self.table_change_seq.entry(k).or_insert(0) += 1;
2947    }
2948
2949    /// v7.37.8 — read accessor for tests / observability. The
2950    /// embedding layer flips this on once per `open_path` (after
2951    /// replay completes) when `SPG_WAL_ROW_REDO` is enabled (now
2952    /// default in v7.37.8). A consumer that wants to verify the
2953    /// post-upgrade contract ("writes go to V5 ROW_REDO by default")
2954    /// reads this through `Database::engine_redo_capture()` instead
2955    /// of inspecting WAL bytes (which the auto-checkpoint truncates
2956    /// on `Drop`).
2957    pub fn redo_capture_enabled(&self) -> bool {
2958        self.redo_capture
2959    }
2960
2961    /// v7.38 轴 4 — currently-selected SQL isolation level. Default
2962    /// `ReadCommitted` after construction; updated by
2963    /// `SET TRANSACTION ISOLATION LEVEL …`. Read by
2964    /// `SHOW transaction_isolation` and any future MVCC/SSI gate.
2965    pub fn current_isolation_level(&self) -> spg_sql::ast::IsolationLevel {
2966        self.current_isolation_level
2967    }
2968
2969    /// v7.34 — take the redo captured by the most recent successful
2970    /// mutating `execute` (empty when capture is off, the statement was a
2971    /// read, or it changed nothing). The embedding layer writes these to
2972    /// the WAL in place of the SQL text.
2973    pub fn take_redo(&mut self) -> Vec<RowChange> {
2974        core::mem::take(&mut self.last_redo)
2975    }
2976
2977    /// v7.34 (crash-recovery P0 #2) — replay a row-level redo log onto the
2978    /// committed catalog (the row-level WAL recovery primitive: apply the
2979    /// captured physical changes from a checkpoint baseline, in place of
2980    /// re-executing the SQL). Trusts the log — no uniqueness/FK/parse.
2981    pub fn apply_redo(&mut self, changes: &[RowChange]) -> Result<(), EngineError> {
2982        self.catalog
2983            .apply_redo(changes)
2984            .map_err(EngineError::Storage)
2985    }
2986
2987    /// Read-only execute path. Succeeds for `SELECT` / `SHOW TABLES`
2988    /// / `SHOW COLUMNS`; returns `EngineError::WriteRequired` for
2989    /// every other statement, so the caller can fall through to the
2990    /// `&mut self` `execute` path under a write lock. Engine state is
2991    /// not mutated even on the success path (`rewrite_clock_calls`
2992    /// and `resolve_order_by_position` both mutate the locally-owned
2993    /// AST, not `self`).
2994    ///
2995    /// v4.2: cap result-set size. Applied after the executor
2996    /// materialises rows but before they leave the engine — wrapping
2997    /// every Rows-returning exec_* function would scatter the check.
2998    ///
2999    /// v7.31 (memory campaign, bucket A) — the same choke point now
3000    /// also enforces the BYTE budget on the final result set, so
3001    /// single-table and aggregate paths (which don't route through
3002    /// the join materialiser's incremental accounting) still cannot
3003    /// hand the host an unbounded result. Intermediate single-table
3004    /// clones are the 7.31.x follow-up (design doc, bucket A).
3005    fn enforce_row_limit(
3006        &self,
3007        result: Result<QueryResult, EngineError>,
3008    ) -> Result<QueryResult, EngineError> {
3009        if let Ok(QueryResult::Rows { rows, .. }) = &result {
3010            if let Some(cap) = self.max_query_rows
3011                && rows.len() > cap
3012            {
3013                return Err(EngineError::RowLimitExceeded(cap));
3014            }
3015            if let Some(byte_cap) = self.max_query_bytes
3016                && approx_rows_bytes(rows) > byte_cap
3017            {
3018                return Err(EngineError::QueryBytesExceeded(byte_cap));
3019            }
3020        }
3021        result
3022    }
3023}
3024
3025/// v7.31 (memory campaign — ceiling-first / never-die, design v1) —
3026/// per-table slice of the engine's resident-memory accounting.
3027/// `hot_encoded_bytes` is the storage layer's maintained meter (what
3028/// the rows encode to); `approx_resident_bytes` is what they COST in
3029/// RAM (per-cell enum slots + heap payloads via `approx_row_bytes`)
3030/// — the gap between the two is the representation multiplier the
3031/// round-26 report measured at ~11× end-to-end.
3032#[derive(Debug, Clone)]
3033pub struct TableMemoryStats {
3034    pub name: String,
3035    pub hot_rows: u64,
3036    /// Cached cold-row count (refreshed by ANALYZE — see
3037    /// `Table::cold_row_count`'s staleness contract).
3038    pub cold_rows: u64,
3039    pub hot_encoded_bytes: u64,
3040    pub approx_resident_bytes: u64,
3041    pub index_count: u64,
3042    /// v7.31 C2 — sum of `IndexKind::approx_resident_bytes()` over the
3043    /// table's indices: every variant (BTree / NSW / BRIN / GIN family)
3044    /// walks its own structure, so the GIN posting lists and NSW layer
3045    /// adjacency that dominate text/vector tables are counted honestly
3046    /// instead of the old flat-token estimate.
3047    pub approx_index_bytes: u64,
3048}
3049
3050/// v7.31 — whole-engine memory snapshot: the polling form of the
3051/// round-26 ask-4 watermark signal. Hosts compare
3052/// `total_approx_resident_bytes` (+ their own WAL/file accounting)
3053/// against their deployment ceiling and shed/shrink before the
3054/// kernel does it for them.
3055#[derive(Debug, Clone)]
3056pub struct MemoryStats {
3057    pub tables: Vec<TableMemoryStats>,
3058    pub total_hot_encoded_bytes: u64,
3059    pub total_approx_resident_bytes: u64,
3060    pub total_approx_index_bytes: u64,
3061    /// The active per-query materialisation budget (bucket A), so a
3062    /// monitoring host sees ceiling and usage through one call.
3063    pub max_query_bytes: Option<usize>,
3064    /// v7.31 C2 — bucket D: live WAL bytes (active chunk + buffered,
3065    /// uncheckpointed). `None` from the engine itself — it has no WAL;
3066    /// the durable hosts (embed `Database`, server) fill it in from
3067    /// their own WAL accounting. `Some(0)` means "host has a WAL and
3068    /// it is empty"; `None` means "no WAL on this path" (in-memory).
3069    pub wal_bytes: Option<u64>,
3070}
3071
3072/// v6.2.0 — true for engine-managed catalog tables that the bare
3073/// `ANALYZE` (no target) should skip. v6.2.0 has no internal
3074/// tables yet (publications / subscriptions / users / statistics
3075/// all live as engine fields, not catalog tables), so this is a
3076/// reserved future-proofing hook — every existing user table is
3077/// analysed.
3078const fn is_internal_table_name(_name: &str) -> bool {
3079    false
3080}
3081
3082#[cfg(test)]
3083mod tests;