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