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