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