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