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