spg_storage/lib.rs
1//! In-memory storage primitives.
2//!
3//! v0.3 is intentionally simple: a flat catalog of tables, each holding rows
4//! as `Vec<Value>` (positional, matching the table's `TableSchema`). No MVCC,
5//! no on-disk format — those land in later milestones.
6#![no_std]
7// v3.3.2 NEON path for l2_distance_sq (aarch64 only). Scoped allow:
8// `unsafe_code = "deny"` at workspace level stays in force for every
9// other crate.
10#![cfg_attr(target_arch = "aarch64", allow(unsafe_code))]
11
12extern crate alloc;
13
14pub mod bloom;
15pub mod fts_simple;
16pub mod halfvec;
17pub mod persistent;
18pub mod persistent_btree;
19pub mod quantize;
20pub mod row_locator;
21pub mod segment;
22pub mod trgm;
23
24pub use self::bloom::{BloomError, BloomFilter};
25pub use self::row_locator::{RowLocator, RowLocatorError};
26pub use self::segment::{
27 BRIN_SIDECAR_MAGIC, BrinSummary, OwnedSegment, SEGMENT_COMPRESS_ALGO_LZSS,
28 SEGMENT_COMPRESS_ALGO_NONE, SEGMENT_MAGIC, SEGMENT_MAGIC_V2, SEGMENT_PAGE_BYTES, SegmentError,
29 SegmentMeta, SegmentReader, derive_brin_summaries, encode_segment, wrap_v2_envelope,
30 wrap_v2_envelope_with_brin,
31};
32
33use alloc::boxed::Box;
34use alloc::collections::{BTreeMap, BTreeSet};
35use alloc::format;
36use alloc::string::{String, ToString};
37use alloc::sync::Arc;
38use alloc::vec::Vec;
39use core::fmt;
40
41use self::persistent::PersistentVec;
42use self::persistent_btree::PersistentBTreeMap;
43
44/// In-cell encoding for `DataType::Vector`. Mirrors
45/// `spg_sql::ast::VecEncoding` — kept here so storage stays
46/// dep-free of `spg-sql`. The engine bridges between the two
47/// at DDL-execution time.
48///
49/// `F32` is the pre-v6 default: each cell holds a raw `Vec<f32>`.
50/// `Sq8` (v6.0.1) stores `Sq8Vector { min, max, bytes: Vec<u8> }`
51/// per cell; 4× compression vs `F32` with recall@10 ≥ 0.95 on
52/// natural embeddings (Gaussian / unit-sphere corpora).
53/// `F16` (v6.0.3, DDL keyword `HALF`) stores each element as
54/// IEEE-754 binary16; 2× compression and bit-exact dequantise.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum VecEncoding {
57 #[default]
58 F32,
59 Sq8,
60 F16,
61}
62
63impl fmt::Display for VecEncoding {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Self::F32 => f.write_str("F32"),
67 Self::Sq8 => f.write_str("SQ8"),
68 Self::F16 => f.write_str("HALF"),
69 }
70 }
71}
72
73/// Runtime type tags. `Vector { dim, encoding }` / `Varchar(max)` /
74/// `Char(size)` are parameterised; the parameter travels with both
75/// the column schema and the on-wire serialised representation.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum DataType {
78 /// 16-bit signed. Backed by `Value::SmallInt(i16)`; arithmetic that
79 /// would overflow surfaces as a type error at INSERT time.
80 SmallInt,
81 Int, // 32-bit signed
82 BigInt, // 64-bit signed
83 Float, // f64 (PG double precision)
84 Text,
85 /// `VARCHAR(n)` — same byte representation as `Text`, but INSERT
86 /// rejects values longer than `n` Unicode characters.
87 Varchar(u32),
88 /// `CHAR(n)` — same representation as `Text`, but INSERT right-pads
89 /// with U+0020 to exactly `n` Unicode characters (or rejects when
90 /// the input is already longer).
91 Char(u32),
92 Bool,
93 /// pgvector-style fixed-dimension vector. `encoding` selects
94 /// the in-cell representation (`F32` = pre-v6 raw f32 buffer;
95 /// `Sq8` = v6.0.1 8-bit scalar-quantised). The DDL grammar
96 /// surfaces encoding via the optional `USING <encoding>`
97 /// clause: `VECTOR(128) USING SQ8`.
98 Vector {
99 dim: u32,
100 encoding: VecEncoding,
101 },
102 /// `NUMERIC(precision, scale)` — exact fixed-point decimal stored as
103 /// a scaled `i128`. `precision` caps total decimal digits, `scale`
104 /// fixes digits after the decimal point. v1.12 supports up to
105 /// precision 38 (the i128-safe ceiling). `NUMERIC` and `NUMERIC(p)`
106 /// surface as `Numeric { precision: p, scale: 0 }`.
107 Numeric {
108 precision: u8,
109 scale: u8,
110 },
111 /// `DATE` — calendar date with day precision, stored as `i32` days
112 /// since the Unix epoch (1970-01-01).
113 Date,
114 /// `TIMESTAMP` (a.k.a. `MySQL` `DATETIME`) — instant with microsecond
115 /// precision, stored as `i64` microseconds since the Unix epoch.
116 Timestamp,
117 /// v7.9.2 `TIMESTAMPTZ` — bit-identical to `Timestamp` on disk
118 /// (i64 microseconds, UTC by convention). Carried as a distinct
119 /// type tag so the PG-wire layer can advertise OID 1184 (PG's
120 /// `timestamp with time zone`) and `sqlx`/`pgx`/JDBC clients
121 /// decode into their TZ-aware datetime types. The internal
122 /// semantics are unchanged: SPG never stored per-row offsets,
123 /// and neither did PG — `TIMESTAMPTZ` in PG is also UTC i64.
124 Timestamptz,
125 /// `INTERVAL` — calendar-aware span (months + microseconds). v2.11
126 /// supports INTERVAL only as a runtime intermediate (literals,
127 /// arithmetic results); on-disk encoding is rejected so this branch
128 /// can't appear in a `ColumnSchema`.
129 Interval,
130 /// v4.9: `JSON` — text-backed JSON document. We don't parse
131 /// the content (no path operators or jsonb functions yet) —
132 /// the column accepts any TEXT-compatible value and round-trips
133 /// it verbatim. PG OID 114 on the wire.
134 Json,
135 /// v7.9.0: `JSONB` — semantically identical to `Json` on
136 /// the storage side (same `Value::Json` cells, same
137 /// row codec), but advertised as PG OID 3802 on the wire
138 /// so `sqlx`-style clients that bind `jsonb` columns
139 /// decode correctly. mailrs migration blocker #3.
140 Jsonb,
141 /// v7.10.4: `BYTES` / `BYTEA` — variable-length raw binary.
142 /// Backed by `Value::Bytes(Vec<u8>)`. PG wire OID 17. Literal
143 /// forms accepted by parser/engine: PG hex form `'\xDEADBEEF'`
144 /// (case-insensitive hex pairs) and escape form
145 /// `'foo\\000bar'` (the latter decoded at coercion time when
146 /// the target column is BYTEA — TEXT columns leave the
147 /// backslash sequence verbatim).
148 Bytes,
149 /// v7.10.9: `TEXT[]` — single-dimension TEXT array. Elements
150 /// may be NULL (PG semantics). PG wire OID 1009. Literal
151 /// forms: `ARRAY['a', 'b', NULL]` and the PG external form
152 /// `'{a,b,NULL}'::TEXT[]`. Engine implements `= ANY(arr)`,
153 /// `<> ALL(arr)`, and 1-based indexing `arr[i]`. Catalog
154 /// FILE_VERSION 18+; older snapshots reject this DataType
155 /// (forward-only by design — TEXT[] columns aren't readable
156 /// on a pre-v7.10 binary).
157 TextArray,
158 /// v7.11.12: `INT[]` — single-dimension i32 array. PG wire
159 /// OID 1007 (_int4). Same `ARRAY[...]` / `'{1,2,3}'::INT[]`
160 /// literal surface as TEXT[]. Catalog FILE_VERSION 19+.
161 IntArray,
162 /// v7.11.12: `BIGINT[]` — single-dimension i64 array. PG
163 /// wire OID 1016 (_int8). Catalog FILE_VERSION 19+.
164 BigIntArray,
165 /// v7.12.0: PG `tsvector` — ordered, deduplicated set of
166 /// `(lexeme, positions, weight)` tuples. PG wire OID 3614.
167 /// Catalog FILE_VERSION 20+. Storage shape is row-codec
168 /// tag 22; the schema-agnostic `write_value` path emits tag
169 /// 18. Literal: `'foo:1 bar:2,3'::tsvector` (PG external
170 /// form). G-CRIT-3 entry — v7.12.0 only ships the type +
171 /// codec; matching `@@` lands in v7.12.2.
172 TsVector,
173 /// v7.12.0: PG `tsquery` — parse tree of lexemes joined by
174 /// `&` `|` `!` and phrase operators. PG wire OID 3615.
175 /// Catalog FILE_VERSION 20+.
176 TsQuery,
177 /// v7.17.0: PG `uuid` — 128-bit identifier stored as
178 /// `Value::Uuid([u8; 16])`. PG wire OID 2950. Canonical
179 /// text form is lowercase 8-4-4-4-12 hyphenated; input
180 /// also accepts uppercase, unhyphenated, and brace-wrapped
181 /// forms (`{xxxx…}`). Catalog FILE_VERSION 36+; tag 24 on
182 /// the dense type-tag side, tag 20 on the schema-agnostic
183 /// value side. The drop-in PG/MySQL surface for Django /
184 /// Rails / Hibernate "id UUID PRIMARY KEY DEFAULT
185 /// gen_random_uuid()" default-PK pattern.
186 Uuid,
187 /// v7.17.0 Phase 3.P0-32: PG `time` (without time zone) — i64
188 /// microseconds since 00:00:00. PG wire OID 1083. Display:
189 /// canonical zero-padded `HH:MM:SS` when fractional is zero,
190 /// `HH:MM:SS.ffffff` otherwise. Catalog FILE_VERSION 37+;
191 /// tag 25 on the dense type-tag side, tag 21 on the schema-
192 /// agnostic value side. The wall-clock-of-day half of PG's
193 /// date/time triplet (date / time / timestamp).
194 Time,
195 /// v7.17.0 Phase 3.P0-33: MySQL `YEAR` — u16 in range
196 /// 1901..=2155 plus the special zero-year sentinel 0. No
197 /// dedicated PG OID (advertised as INT4 / OID 23 on the wire
198 /// — psql renders integers, MySQL CLI renders 4-digit
199 /// zero-padded text). Display always 4 digits: `0000` for the
200 /// zero-year, `1985` / `2007` / etc otherwise. Catalog
201 /// FILE_VERSION 38+; tag 26 on the dense type-tag side, tag
202 /// 22 on the schema-agnostic value side.
203 Year,
204 /// v7.17.0 Phase 3.P0-34: PG `time with time zone` (TIMETZ) —
205 /// i64 microseconds since 00:00:00 in the local wall clock
206 /// PLUS i32 offset-from-UTC in seconds. PG wire OID 1266.
207 /// Display: `HH:MM:SS[.ffffff]±HH[:MM]` (PG `timetz_out`).
208 /// Range: offset in ±50400 seconds (±14 hours). Catalog
209 /// FILE_VERSION 39+; tag 27 on the dense type-tag side, tag
210 /// 23 on the schema-agnostic value side.
211 TimeTz,
212 /// v7.17.0 Phase 3.P0-35: PG `money` — i64 cents (locale-
213 /// independent storage). PG wire OID 790. Display: en_US
214 /// locale (`$N,NNN.CC`, negative → `-$1.23`). Input accepts
215 /// `$N.NN`, `$N,NNN.NN`, bare integer (treated as major
216 /// units), optional leading `-`. Range: full i64. Catalog
217 /// FILE_VERSION 40+; tag 28 on the dense type-tag side, tag
218 /// 24 on the schema-agnostic value side.
219 Money,
220 /// v7.17.0 Phase 3.P0-38: PG range type. The same DataType
221 /// variant covers all six builtin ranges (int4range,
222 /// int8range, numrange, tsrange, tstzrange, daterange) —
223 /// `RangeKind` pins the element type so encode / decode /
224 /// display can route off one switch. Catalog FILE_VERSION
225 /// 43+; tag 29 + a 1-byte RangeKind on the dense type-tag
226 /// side, tag 25 on the schema-agnostic value side.
227 Range(RangeKind),
228 /// v7.17.0 Phase 3.P0-39: PG `hstore` extension type — flat
229 /// `text => text` map with NULL value support. Catalog
230 /// FILE_VERSION 44+; tag 30 on the dense type-tag side, tag
231 /// 26 on the schema-agnostic value side. The contrib OID is
232 /// installation-dependent in real PG; SPG advertises it via
233 /// dynamic lookup, falling back to TEXT (OID 25) on the wire
234 /// when the installed `hstore` extension hasn't claimed an
235 /// OID yet.
236 Hstore,
237 /// v7.17.0 Phase 3.P0-40: PG `int[][]` — 2-dimensional INT
238 /// matrix. Storage: row-major Vec<Vec<Option<i32>>>. All
239 /// rows must share the same column count. Wire OID 1007
240 /// (same as INT[]; the dimension count travels in the data
241 /// header, not the OID). Catalog FILE_VERSION 45+; tag 31
242 /// on the dense type-tag side, tag 27 on the schema-agnostic
243 /// value side.
244 IntArray2D,
245 /// v7.17.0 Phase 3.P0-40: PG `bigint[][]` — 2-dimensional
246 /// BIGINT matrix. Storage / OID / tags mirror IntArray2D.
247 /// Tag 32 dense, tag 28 schema-agnostic.
248 BigIntArray2D,
249 /// v7.17.0 Phase 3.P0-40: PG `text[][]` — 2-dimensional TEXT
250 /// matrix. Storage: row-major Vec<Vec<Option<String>>>.
251 /// Tag 33 dense, tag 29 schema-agnostic.
252 TextArray2D,
253}
254
255/// v7.17.0 Phase 3.P0-38 — pins the element type of a range value
256/// or column. Wire OIDs: Int4=3904, Int8=3926, Num=3906,
257/// Ts=3908, TsTz=3910, Date=3912.
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
259pub enum RangeKind {
260 Int4,
261 Int8,
262 Num,
263 Ts,
264 TsTz,
265 Date,
266}
267
268impl RangeKind {
269 pub const fn tag(self) -> u8 {
270 match self {
271 Self::Int4 => 0,
272 Self::Int8 => 1,
273 Self::Num => 2,
274 Self::Ts => 3,
275 Self::TsTz => 4,
276 Self::Date => 5,
277 }
278 }
279 pub const fn from_tag(t: u8) -> Option<Self> {
280 Some(match t {
281 0 => Self::Int4,
282 1 => Self::Int8,
283 2 => Self::Num,
284 3 => Self::Ts,
285 4 => Self::TsTz,
286 5 => Self::Date,
287 _ => return None,
288 })
289 }
290 pub const fn keyword(self) -> &'static str {
291 match self {
292 Self::Int4 => "INT4RANGE",
293 Self::Int8 => "INT8RANGE",
294 Self::Num => "NUMRANGE",
295 Self::Ts => "TSRANGE",
296 Self::TsTz => "TSTZRANGE",
297 Self::Date => "DATERANGE",
298 }
299 }
300}
301
302impl fmt::Display for DataType {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 match self {
305 Self::SmallInt => f.write_str("SMALLINT"),
306 Self::Int => f.write_str("INT"),
307 Self::BigInt => f.write_str("BIGINT"),
308 Self::Float => f.write_str("FLOAT"),
309 Self::Text => f.write_str("TEXT"),
310 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
311 Self::Char(n) => write!(f, "CHAR({n})"),
312 Self::Bool => f.write_str("BOOL"),
313 Self::Vector { dim, encoding } => match encoding {
314 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
315 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
316 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
317 },
318 Self::Numeric { precision, scale } => {
319 if *scale == 0 {
320 write!(f, "NUMERIC({precision})")
321 } else {
322 write!(f, "NUMERIC({precision}, {scale})")
323 }
324 }
325 Self::Date => f.write_str("DATE"),
326 Self::Timestamp => f.write_str("TIMESTAMP"),
327 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
328 Self::Interval => f.write_str("INTERVAL"),
329 Self::Json => f.write_str("JSON"),
330 Self::Jsonb => f.write_str("JSONB"),
331 Self::Bytes => f.write_str("BYTEA"),
332 Self::TextArray => f.write_str("TEXT[]"),
333 Self::IntArray => f.write_str("INT[]"),
334 Self::BigIntArray => f.write_str("BIGINT[]"),
335 Self::TsVector => f.write_str("TSVECTOR"),
336 Self::TsQuery => f.write_str("TSQUERY"),
337 Self::Uuid => f.write_str("UUID"),
338 Self::Time => f.write_str("TIME"),
339 Self::Year => f.write_str("YEAR"),
340 Self::TimeTz => f.write_str("TIMETZ"),
341 Self::Money => f.write_str("MONEY"),
342 Self::Range(k) => f.write_str(k.keyword()),
343 Self::Hstore => f.write_str("HSTORE"),
344 Self::IntArray2D => f.write_str("INT[][]"),
345 Self::BigIntArray2D => f.write_str("BIGINT[][]"),
346 Self::TextArray2D => f.write_str("TEXT[][]"),
347 }
348 }
349}
350
351/// v7.12.0 — one entry in a `Value::TsVector`. The lexeme is the
352/// (already-tokenised + stemmed in v7.12.1+) word; `positions` is
353/// a strictly-ascending list of 1-based positions; `weight` is the
354/// PG weight letter (A=3, B=2, C=1, D=0) — v7.12.0 defaults every
355/// lexeme to D, the v7.12.2 ranking path consumes the weight.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct TsLexeme {
358 pub word: String,
359 pub positions: Vec<u16>,
360 pub weight: u8,
361}
362
363/// v7.12.0 — parse tree for a PG `tsquery`. v7.12.0 ships the
364/// type + codec only; the `to_tsquery` / `plainto_tsquery` lexer
365/// lands in v7.12.1 and the `@@` evaluator in v7.12.2.
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub enum TsQueryAst {
368 /// Single lexeme term. The `weight_mask` is the PG-style
369 /// bitmask of accepted weights (`A=1<<3`, `B=1<<2`, `C=1<<1`,
370 /// `D=1<<0`); `0` = any weight. v7.12.0 always sets it to 0.
371 Term {
372 word: String,
373 weight_mask: u8,
374 },
375 And(Box<TsQueryAst>, Box<TsQueryAst>),
376 Or(Box<TsQueryAst>, Box<TsQueryAst>),
377 Not(Box<TsQueryAst>),
378 /// `phrase <distance> phrase`. v7.12.0 only persists this; the
379 /// match semantics arrive in v7.12.2 alongside `@@`.
380 Phrase {
381 left: Box<TsQueryAst>,
382 right: Box<TsQueryAst>,
383 distance: u16,
384 },
385}
386
387/// A row-cell value, including SQL `NULL`. `Float` uses `f64`; NaN compares
388/// non-equal to itself (PG behaviour) — `PartialEq` is derived so callers
389/// must opt into NaN-aware comparison if they need stronger guarantees.
390#[derive(Debug, Clone, PartialEq)]
391#[non_exhaustive]
392pub enum Value {
393 SmallInt(i16),
394 Int(i32),
395 BigInt(i64),
396 Float(f64),
397 Text(String),
398 Bool(bool),
399 Vector(Vec<f32>),
400 /// v6.0.1: 8-bit scalar-quantised vector cell. Lives in
401 /// columns declared `VECTOR(N) USING SQ8`. Layout per cell:
402 /// `Sq8Vector { min: f32, max: f32, bytes: Vec<u8> }` —
403 /// 4× compression vs `Vector(Vec<f32>)`. The wire layer
404 /// dequantises to `f32` on SELECT; INSERT path quantises
405 /// incoming `Vector(Vec<f32>)` cells into this variant.
406 Sq8Vector(crate::quantize::Sq8Vector),
407 /// v6.0.3: IEEE-754 binary16 vector cell. Lives in columns
408 /// declared `VECTOR(N) USING HALF`. Stores raw u16 LE bits
409 /// (2× compression vs `Vector(Vec<f32>)`). Wire / display
410 /// paths dequantise to f32 bit-exactly; INSERT path converts
411 /// incoming f32 vectors at the engine boundary.
412 HalfVector(crate::halfvec::HalfVector),
413 /// Exact fixed-point decimal. `scaled` holds the value as
414 /// `actual * 10^scale` so the storage type is always integral —
415 /// arithmetic never falls back to floating-point.
416 Numeric {
417 scaled: i128,
418 scale: u8,
419 },
420 /// Days since the Unix epoch (1970-01-01). Negative for earlier dates.
421 Date(i32),
422 /// Microseconds since the Unix epoch (1970-01-01T00:00:00Z).
423 Timestamp(i64),
424 /// Calendar span: `months` (variable-length) + `micros` (fixed-length).
425 /// Runtime-only — cannot appear in a stored row in v2.11.
426 Interval {
427 months: i32,
428 micros: i64,
429 },
430 /// v4.9 `JSON` — raw JSON text. No structural validation
431 /// happens at the storage layer; whatever the parser hands us
432 /// round-trips verbatim. Equality is byte-wise.
433 Json(String),
434 /// v7.10.4 `BYTEA` — raw binary blob. Equality is byte-wise.
435 /// Layout matches `Text`'s length-prefixed shape (`[u32 LE
436 /// len][bytes]`) under tag 18; the engine accepts PG hex
437 /// literals (`'\xDEADBEEF'`) and escape literals at the
438 /// coercion boundary.
439 Bytes(Vec<u8>),
440 /// v7.10.9 `TEXT[]` — single-dimension TEXT array with
441 /// optional NULL elements. Equality is element-wise. PG's
442 /// NULL-element comparison semantics: NULL ≠ NULL inside
443 /// arrays under `=`, so `[NULL] != [NULL]` (the engine
444 /// honours this).
445 TextArray(Vec<Option<String>>),
446 /// v7.11.12 `INT[]` — single-dimension i32 array with optional
447 /// NULL elements. Codec mirrors TextArray with i32 LE per
448 /// element instead of length-prefixed UTF-8.
449 IntArray(Vec<Option<i32>>),
450 /// v7.11.12 `BIGINT[]` — single-dimension i64 array with optional
451 /// NULL elements.
452 BigIntArray(Vec<Option<i64>>),
453 /// v7.12.0 `tsvector` — sorted-by-word, deduped lexeme set with
454 /// positions + weights. The engine enforces sort/dedup on
455 /// construction; consumers can rely on `lexemes.windows(2)`
456 /// being strictly ascending by `word`.
457 TsVector(Vec<TsLexeme>),
458 /// v7.12.0 `tsquery` — boolean / phrase parse tree over
459 /// lexemes. Engine builds via `to_tsquery` family.
460 TsQuery(TsQueryAst),
461 /// v7.17.0 `uuid` — 128-bit identifier. Stored as 16 bytes
462 /// (big-endian / network-byte order, same as RFC 4122).
463 /// Display normalises to canonical lowercase 8-4-4-4-12
464 /// hyphenated form. Equality is byte-wise.
465 Uuid([u8; 16]),
466 /// v7.17.0 Phase 3.P0-32 — PG `time` (without time zone) —
467 /// i64 microseconds since 00:00:00. Range 0..86_400_000_000.
468 /// Display: `HH:MM:SS` zero-padded, with optional `.ffffff`
469 /// suffix when fractional is non-zero.
470 Time(i64),
471 /// v7.17.0 Phase 3.P0-33 — MySQL `YEAR` — u16 in range
472 /// 1901..=2155 plus the special zero-year sentinel 0.
473 /// Display always 4 digits zero-padded (`0000` for the
474 /// sentinel; `1985`/`2007` otherwise).
475 Year(u16),
476 /// v7.17.0 Phase 3.P0-34 — PG `time with time zone` — i64
477 /// microseconds since 00:00:00 in the LOCAL wall clock PLUS
478 /// an i32 offset-from-UTC in seconds. PG preserves the
479 /// offset on output, so the wall-clock value is NOT shifted
480 /// to UTC at storage time. Offset range: ±50400 seconds
481 /// (±14 hours).
482 TimeTz {
483 us: i64,
484 offset_secs: i32,
485 },
486 /// v7.17.0 Phase 3.P0-35 — PG `money` — i64 cents
487 /// (locale-independent storage; the en_US locale renders on
488 /// display via `$N,NNN.CC`).
489 Money(i64),
490 /// v7.17.0 Phase 3.P0-39 — PG `hstore` value: flat
491 /// `text => text` map with NULL value support. Insertion
492 /// order preserved on input; duplicate keys take last-write-
493 /// wins at parse time.
494 Hstore(Vec<(String, Option<String>)>),
495 /// v7.17.0 Phase 3.P0-40 — 2D INT matrix (row-major).
496 IntArray2D(Vec<Vec<Option<i32>>>),
497 /// v7.17.0 Phase 3.P0-40 — 2D BIGINT matrix (row-major).
498 BigIntArray2D(Vec<Vec<Option<i64>>>),
499 /// v7.17.0 Phase 3.P0-40 — 2D TEXT matrix (row-major).
500 TextArray2D(Vec<Vec<Option<String>>>),
501 /// v7.17.0 Phase 3.P0-38 — PG range value. One shape covers
502 /// all six builtin range types; `kind` pins the element type
503 /// (must match the column's `DataType::Range(kind)`).
504 /// `lower` / `upper` are `None` for the unbounded sides;
505 /// `lower_inc` / `upper_inc` mirror the canonical PG
506 /// `[` / `(` / `]` / `)` bracket inclusivity. `empty=true`
507 /// supersedes all other fields (the empty range has no
508 /// bounds).
509 Range {
510 kind: RangeKind,
511 lower: Option<alloc::boxed::Box<Value>>,
512 upper: Option<alloc::boxed::Box<Value>>,
513 lower_inc: bool,
514 upper_inc: bool,
515 empty: bool,
516 },
517 Null,
518}
519
520impl Value {
521 /// Type tag, or `None` for `NULL` (unknown at value level).
522 pub fn data_type(&self) -> Option<DataType> {
523 match self {
524 Self::SmallInt(_) => Some(DataType::SmallInt),
525 Self::Int(_) => Some(DataType::Int),
526 Self::BigInt(_) => Some(DataType::BigInt),
527 Self::Float(_) => Some(DataType::Float),
528 // `Text` covers both unbounded TEXT and bounded VARCHAR/CHAR
529 // — the constraint lives on the column schema, not the value.
530 Self::Text(_) => Some(DataType::Text),
531 Self::Bool(_) => Some(DataType::Bool),
532 Self::Vector(v) => Some(DataType::Vector {
533 dim: u32::try_from(v.len()).expect("vector dim ≤ u32"),
534 encoding: VecEncoding::F32,
535 }),
536 Self::Sq8Vector(q) => Some(DataType::Vector {
537 dim: u32::try_from(q.bytes.len()).expect("vector dim ≤ u32"),
538 encoding: VecEncoding::Sq8,
539 }),
540 Self::HalfVector(h) => Some(DataType::Vector {
541 dim: u32::try_from(h.dim()).expect("vector dim ≤ u32"),
542 encoding: VecEncoding::F16,
543 }),
544 // `Value::Numeric` doesn't carry its precision (the column
545 // schema does); we surface precision=0 as "unknown" and let
546 // the engine reconcile against the column type at coercion
547 // time.
548 Self::Numeric { scale, .. } => Some(DataType::Numeric {
549 precision: 0,
550 scale: *scale,
551 }),
552 Self::Date(_) => Some(DataType::Date),
553 Self::Timestamp(_) => Some(DataType::Timestamp),
554 Self::Interval { .. } => Some(DataType::Interval),
555 Self::Json(_) => Some(DataType::Json),
556 Self::Bytes(_) => Some(DataType::Bytes),
557 Self::TextArray(_) => Some(DataType::TextArray),
558 Self::IntArray(_) => Some(DataType::IntArray),
559 Self::BigIntArray(_) => Some(DataType::BigIntArray),
560 Self::TsVector(_) => Some(DataType::TsVector),
561 Self::TsQuery(_) => Some(DataType::TsQuery),
562 Self::Uuid(_) => Some(DataType::Uuid),
563 Self::Time(_) => Some(DataType::Time),
564 Self::Year(_) => Some(DataType::Year),
565 Self::TimeTz { .. } => Some(DataType::TimeTz),
566 Self::Money(_) => Some(DataType::Money),
567 Self::Range { kind, .. } => Some(DataType::Range(*kind)),
568 Self::Hstore(_) => Some(DataType::Hstore),
569 Self::IntArray2D(_) => Some(DataType::IntArray2D),
570 Self::BigIntArray2D(_) => Some(DataType::BigIntArray2D),
571 Self::TextArray2D(_) => Some(DataType::TextArray2D),
572 Self::Null => None,
573 }
574 }
575
576 pub const fn is_null(&self) -> bool {
577 matches!(self, Self::Null)
578 }
579}
580
581/// One table row — values are positional and must match
582/// `TableSchema.columns` in length and (modulo NULL) in `DataType`.
583#[derive(Debug, Clone, PartialEq)]
584pub struct Row {
585 pub values: Vec<Value>,
586}
587
588impl Row {
589 pub const fn new(values: Vec<Value>) -> Self {
590 Self { values }
591 }
592
593 pub fn len(&self) -> usize {
594 self.values.len()
595 }
596
597 pub fn is_empty(&self) -> bool {
598 self.values.is_empty()
599 }
600}
601
602#[derive(Debug, Clone, PartialEq)]
603pub struct ColumnSchema {
604 pub name: String,
605 pub ty: DataType,
606 pub nullable: bool,
607 /// Optional `DEFAULT` value, frozen at CREATE TABLE time. `None`
608 /// means "no default" (so omitted columns become NULL, or error
609 /// out when the column is NOT NULL). Literal defaults take this
610 /// path.
611 pub default: Option<Value>,
612 /// v7.9.21 — for DEFAULT expressions that need INSERT-time
613 /// evaluation (e.g. `DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`),
614 /// the Display form of the expression. The engine re-parses
615 /// it on each INSERT default-fill, evaluates against an empty
616 /// row context, and coerces to the column type. mailrs G4.
617 /// Persisted in catalog FILE_VERSION 15+; older catalogs
618 /// deserialise with None.
619 pub runtime_default: Option<String>,
620 /// MySQL-style `AUTO_INCREMENT`. When set, an INSERT that leaves
621 /// this column unbound (or sets it to NULL) gets the next integer
622 /// computed from the column's current max + 1.
623 pub auto_increment: bool,
624 /// v7.17.0 Phase 1.4 — when the column is bound to a user-
625 /// defined ENUM type (the parser saw an unknown type ident
626 /// and the engine resolved it against `catalog.enum_types`),
627 /// this carries the enum name so INSERT/UPDATE can validate
628 /// the cell value against the enum's labels. `ty` is
629 /// `DataType::Text` in that case. Persisted in catalog
630 /// FILE_VERSION 29+; older catalogs deserialise with None.
631 pub user_enum_type: Option<String>,
632 /// v7.17.0 Phase 1.5 — when the column is bound to a user-
633 /// defined DOMAIN (the parser saw an unknown type ident and
634 /// the engine resolved it against `catalog.domain_types`),
635 /// this carries the domain name. `ty` is the domain's base
636 /// type; INSERT/UPDATE re-evaluates the domain's CHECK list
637 /// + NOT NULL against the cell value. Persisted in catalog
638 /// FILE_VERSION 30+; older catalogs deserialise with None.
639 pub user_domain_type: Option<String>,
640 /// v7.17.0 Phase 2.1 — MySQL `ON UPDATE CURRENT_TIMESTAMP`
641 /// column attribute. When `Some(expr_src)`, an UPDATE that
642 /// does NOT bind this column overrides the new value with
643 /// the engine-evaluated expression (always `now()` in
644 /// v7.17.0). Stored as Display-form source so storage
645 /// stays free of spg-sql; the engine re-parses at UPDATE
646 /// time. Persisted in catalog FILE_VERSION 32+; older
647 /// catalogs deserialise with None — preserves the existing
648 /// "silent ignore" behaviour for snapshots written before
649 /// the upgrade.
650 pub on_update_runtime: Option<String>,
651 /// v7.17.0 Phase 2.5 — text collation. Pre-2.5 SPG accepted
652 /// `COLLATE <name>` clauses but discarded the name, so a
653 /// column declared `COLLATE "case_insensitive"` (or any
654 /// MySQL `_ci` collation) still compared byte-wise — a
655 /// Tier-S silent failure where `WHERE name = 'foo'` never
656 /// matched stored `'Foo'`. This carries the parser-derived
657 /// classification so the engine's WHERE evaluator can route
658 /// text equality through a case-aware compare. `Binary` (the
659 /// default) preserves the prior byte-wise behaviour. Only
660 /// CaseInsensitive lands in the catalog appendix — Binary
661 /// columns stay implicit, keeping snapshots compact.
662 /// Persisted in catalog FILE_VERSION 34+; older catalogs
663 /// deserialise every column as `Binary`.
664 pub collation: Collation,
665 /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Drives
666 /// engine-side INSERT / UPDATE range enforcement (rejects
667 /// negative values on UNSIGNED int columns). Pre-4.4 the
668 /// parser consumed and discarded the keyword silently, so
669 /// every UNSIGNED column quietly accepted negatives — a
670 /// Tier-A correctness drift. Sparse: only UNSIGNED columns
671 /// land in the catalog appendix; the default `false` keeps
672 /// snapshots compact for the common signed-int path.
673 /// Persisted in catalog FILE_VERSION 35+; older catalogs
674 /// deserialise every column as `is_unsigned = false`.
675 pub is_unsigned: bool,
676 /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
677 /// value list. Distinct from `user_enum_type` (which points
678 /// to a separately CREATE TYPE'd PG enum); this carries the
679 /// column-local list MySQL DDL declares inline. When `Some`,
680 /// `ty` is `DataType::Text` and INSERT/UPDATE validates the
681 /// cell value against this list. Variant ORDER is preserved
682 /// (MySQL uses it for `ORDER BY col`). Sparse: only ENUM
683 /// columns land in the catalog appendix.
684 /// Persisted in catalog FILE_VERSION 41+; older catalogs
685 /// deserialise with None — preserves silent-drop behaviour
686 /// for snapshots written before P0-36.
687 pub inline_enum_variants: Option<Vec<String>>,
688 /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
689 /// variant list. Storage is TEXT (canonical comma-joined in
690 /// definition order, de-duplicated). INSERT/UPDATE validates
691 /// every comma-separated token against this list. Sparse:
692 /// only SET columns land in the catalog appendix.
693 /// Persisted in catalog FILE_VERSION 42+; older catalogs
694 /// deserialise with None.
695 pub inline_set_variants: Option<Vec<String>>,
696}
697
698/// v7.17.0 Phase 2.5 — column-level text collation. Drives the
699/// engine's WHERE / GROUP BY equality routing for `Value::Text`.
700/// Only two variants are modelled in v7.17:
701/// * `Binary` — byte-wise comparison (the SPG default;
702/// matches PG `COLLATE "C"` / `pg_catalog.default`
703/// and MySQL `*_bin`).
704/// * `CaseInsensitive` — ASCII case-folded comparison
705/// (matches PG `COLLATE "case_insensitive"` and
706/// MySQL `*_ci` collations). Non-ASCII bytes
707/// still compare byte-wise; full ICU folding is
708/// out of v7.17 scope.
709/// New variants append at the end — older catalogs read missing
710/// columns as `Binary`.
711#[derive(Debug, Clone, Copy, PartialEq, Eq)]
712pub enum Collation {
713 Binary,
714 CaseInsensitive,
715}
716
717#[allow(clippy::derivable_impls)]
718impl Default for Collation {
719 fn default() -> Self {
720 Self::Binary
721 }
722}
723
724impl Collation {
725 /// Wire tag persisted in the FILE_VERSION 34+ catalog appendix.
726 /// Stable: future variants append above the recognised range
727 /// and unknown tags read back as `Binary` for forward-compat
728 /// on rollback.
729 pub const TAG_BINARY: u8 = 0;
730 pub const TAG_CASE_INSENSITIVE: u8 = 1;
731}
732
733#[derive(Debug, Clone, PartialEq)]
734pub struct TableSchema {
735 pub name: String,
736 pub columns: Vec<ColumnSchema>,
737 /// v6.7.2 — per-table hot-tier byte budget override. `None`
738 /// falls through to the global `SPG_HOT_TIER_BYTES` setting;
739 /// `Some(n)` overrides it for this specific table. Set via
740 /// `ALTER TABLE t SET hot_tier_bytes = X`. Persisted in
741 /// catalog FILE_VERSION 11+.
742 pub hot_tier_bytes: Option<u64>,
743 /// v7.6.1 — FOREIGN KEY constraints declared on this table.
744 /// Engine maintains this in lock-step with `spg-sql`'s parser
745 /// AST; the storage layer carries the on-disk shape so a
746 /// catalog snapshot round-trips without external mapping.
747 /// Persisted in catalog FILE_VERSION 13+. Older catalogs
748 /// deserialise with an empty vec.
749 pub foreign_keys: Vec<ForeignKeyConstraint>,
750 /// v7.9.19 — composite UNIQUE / PRIMARY KEY constraints
751 /// declared at the table level. Each entry's leading column
752 /// has a BTree index (created via the constraint), and INSERT
753 /// path enforces the full-tuple uniqueness via a scan keyed
754 /// by the leading column. Persisted in catalog FILE_VERSION
755 /// 15+. Older catalogs (≤ 14) deserialise with an empty vec.
756 pub uniqueness_constraints: Vec<UniquenessConstraint>,
757 /// v7.13.0 — `CHECK (<expr>)` predicates declared on this
758 /// table. Both column-level inline `CHECK (…)` and
759 /// table-level `CHECK (…)` fold into this list. Each entry
760 /// is the AST Expr's `Display` form, re-parsed on every
761 /// INSERT/UPDATE and evaluated against the candidate row.
762 /// A false / NULL result rejects the mutation (PG semantics).
763 /// Persisted in catalog FILE_VERSION 23+. Older catalogs
764 /// deserialise with an empty vec.
765 pub checks: Vec<String>,
766}
767
768/// v7.9.19 — composite UNIQUE / PRIMARY KEY constraint persisted
769/// on the table schema. The leading column always has a BTree
770/// index (created at CREATE TABLE time); INSERT enforcement
771/// scans that index for collisions on the full column tuple.
772#[derive(Debug, Clone, PartialEq, Eq)]
773pub struct UniquenessConstraint {
774 /// `true` when this constraint was declared as `PRIMARY KEY`
775 /// (vs `UNIQUE`). Semantically PK implies NOT NULL on all
776 /// referenced columns; the engine enforces that at CREATE
777 /// TABLE time.
778 pub is_primary_key: bool,
779 /// Column positions on the parent table. ≥ 1 element. For
780 /// single-column UNIQUE this is exactly one position; the
781 /// BTree index alone enforces it.
782 pub columns: Vec<usize>,
783 /// v7.13.0 — `UNIQUE NULLS NOT DISTINCT` modifier
784 /// (mailrs round-5 G10; PG 15+ surface). When `true`, two
785 /// rows whose constrained columns are all NULL collide on
786 /// the constraint. Default (`false`) is the SQL-standard
787 /// `NULLS DISTINCT` behaviour where any NULL passes.
788 /// Persisted in catalog FILE_VERSION 23+.
789 pub nulls_not_distinct: bool,
790}
791
792/// v7.6.1 — Storage-layer mirror of `spg_sql::ast::ForeignKeyConstraint`.
793/// The engine's CREATE TABLE path translates between the two; keeping
794/// them separate preserves the no-deps boundary between
795/// `spg-storage` and `spg-sql`.
796#[derive(Debug, Clone, PartialEq, Eq)]
797pub struct ForeignKeyConstraint {
798 /// Optional user-supplied constraint name (`CONSTRAINT <name>`
799 /// prefix). Used by `ALTER TABLE DROP CONSTRAINT <name>` in
800 /// v7.6.8; ignored by enforcement.
801 pub name: Option<String>,
802 /// Positions of local columns in this table's column list.
803 /// Same arity as `parent_columns`.
804 pub local_columns: Vec<usize>,
805 /// Referenced parent table name.
806 pub parent_table: String,
807 /// Positions of parent columns in the parent's column list.
808 /// Engine resolves these at CREATE TABLE time (after the parent
809 /// schema is known) so enforcement paths can skip the name
810 /// lookup on every row.
811 pub parent_columns: Vec<usize>,
812 /// Referential action when a parent row is deleted.
813 pub on_delete: FkAction,
814 /// Referential action when a parent row's referenced columns
815 /// are updated.
816 pub on_update: FkAction,
817}
818
819/// v7.6.1 — referential action tag. Mirrors `spg_sql::ast::FkAction`.
820#[derive(Debug, Clone, Copy, PartialEq, Eq)]
821pub enum FkAction {
822 Restrict,
823 Cascade,
824 SetNull,
825 SetDefault,
826 NoAction,
827}
828
829impl FkAction {
830 /// On-disk tag byte (v13 catalog appendix).
831 pub const fn tag(self) -> u8 {
832 match self {
833 Self::Restrict => 0,
834 Self::Cascade => 1,
835 Self::SetNull => 2,
836 Self::SetDefault => 3,
837 Self::NoAction => 4,
838 }
839 }
840 pub const fn from_tag(b: u8) -> Option<Self> {
841 Some(match b {
842 0 => Self::Restrict,
843 1 => Self::Cascade,
844 2 => Self::SetNull,
845 3 => Self::SetDefault,
846 4 => Self::NoAction,
847 _ => return None,
848 })
849 }
850}
851
852impl TableSchema {
853 pub fn column_position(&self, name: &str) -> Option<usize> {
854 self.columns.iter().position(|c| c.name == name)
855 }
856}
857
858/// Key type accepted by secondary indices. Float / NULL / Vector values
859/// can't participate in a B-tree index — `f64` is only `PartialOrd`, NULL
860/// has SQL-three-valued semantics, and Vector belongs to the (future) HNSW
861/// path. Index lookups on those columns fall back to full scan.
862#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
863pub enum IndexKey {
864 Int(i64),
865 Text(String),
866 Bool(bool),
867 /// v7.17.0 — `Value::Uuid` index key. Comparison is byte-wise
868 /// (RFC 4122 byte order) so PRIMARY KEY UUID lookups land on
869 /// the same fast-path as Int / Text.
870 Uuid([u8; 16]),
871}
872
873impl IndexKey {
874 pub fn from_value(v: &Value) -> Option<Self> {
875 match v {
876 Value::SmallInt(n) => Some(Self::Int(i64::from(*n))),
877 Value::Int(n) => Some(Self::Int(i64::from(*n))),
878 Value::BigInt(n) => Some(Self::Int(*n)),
879 Value::Text(s) => Some(Self::Text(s.clone())),
880 Value::Bool(b) => Some(Self::Bool(*b)),
881 // Date/Timestamp use their integer storage repr as the
882 // index key — same order semantics, same comparison.
883 Value::Date(d) => Some(Self::Int(i64::from(*d))),
884 Value::Timestamp(t) => Some(Self::Int(*t)),
885 // v7.17.0: UUID indexable via byte-wise ordering. Lookup
886 // on `id = '...'::uuid` resolves through the secondary
887 // index rather than full-scan.
888 Value::Uuid(b) => Some(Self::Uuid(*b)),
889 // v7.17.0 Phase 3.P0-32: TIME indexable via i64 — same
890 // order semantics as Date/Timestamp.
891 Value::Time(us) => Some(Self::Int(*us)),
892 // v7.17.0 Phase 3.P0-33: YEAR indexable as i64 — u16
893 // widens losslessly and gives the natural calendar
894 // ordering.
895 Value::Year(y) => Some(Self::Int(i64::from(*y))),
896 // v7.17.0 Phase 3.P0-34: TIMETZ indexable by its
897 // UTC-equivalent microseconds (local wall - offset).
898 // Without normalising, two values for the same
899 // physical instant in different zones would sort
900 // wrong. Matches PG's TIMETZ index behaviour.
901 Value::TimeTz { us, offset_secs } => {
902 Some(Self::Int(us - i64::from(*offset_secs) * 1_000_000))
903 }
904 // v7.17.0 Phase 3.P0-35: MONEY indexable as i64 cents
905 // (no scaling needed — natural numeric ordering).
906 Value::Money(c) => Some(Self::Int(*c)),
907 // v7.17.0 Phase 3.P0-38: ranges are NOT indexable in
908 // v7.17.0 — they'd need a custom comparator (PG uses
909 // SP-GiST for this). Skip.
910 Value::Range { .. } => None,
911 // v7.17.0 Phase 3.P0-39: hstore is NOT indexable in
912 // v7.17.0 — map columns need GIN with bespoke ops.
913 Value::Hstore(_) => None,
914 // v7.17.0 Phase 3.P0-40: 2D arrays aren't indexable.
915 Value::IntArray2D(_) | Value::BigIntArray2D(_) | Value::TextArray2D(_) => None,
916 // Numeric isn't (yet) indexable — exact-decimal index keys
917 // would need a stable scale-normalised representation.
918 // Interval isn't index-eligible either (and can't reach this
919 // path through column storage anyway).
920 Value::Null
921 | Value::Float(_)
922 | Value::Vector(_)
923 | Value::Sq8Vector(_)
924 | Value::HalfVector(_)
925 | Value::Numeric { .. }
926 | Value::Interval { .. }
927 | Value::Json(_)
928 | Value::Bytes(_)
929 | Value::TextArray(_)
930 | Value::IntArray(_)
931 | Value::BigIntArray(_)
932 | Value::TsVector(_)
933 | Value::TsQuery(_) => None,
934 }
935 }
936}
937
938/// A single-column secondary index. v2.0 carries either a B-tree map
939/// (the default — used for equality / range lookups on scalar columns)
940/// or a navigable-small-world graph (used for kNN over vector
941/// columns).
942#[derive(Debug, Clone)]
943pub struct Index {
944 pub name: String,
945 pub column_position: usize,
946 pub kind: IndexKind,
947 /// v6.8.0 — column positions of `INCLUDE (col1, col2, …)`
948 /// non-key columns. Carries the planner's "this query is
949 /// covered by the index" signal; lookup paths still resolve
950 /// via the `RowLocator` to fetch the row body, but EXPLAIN
951 /// surfaces the covered-scan annotation so operators can
952 /// confirm the planner sees the coverage.
953 ///
954 /// Empty `Vec` = no `INCLUDE` clause (the legacy shape). v12
955 /// catalog snapshots deserialise with an empty vec.
956 pub included_columns: Vec<usize>,
957 /// v6.8.1 — partial-index predicate stored as its canonical
958 /// Display form (the engine re-parses it on the maintenance
959 /// path). `None` = unconditional index (the legacy shape).
960 /// Persisted as `[u8 has_pred][u16 LE len][bytes]` on the
961 /// catalog snapshot (FILE_VERSION 12, appended after
962 /// `included_columns`).
963 pub partial_predicate: Option<String>,
964 /// v6.8.2 — expression-index key, stored as the expression's
965 /// canonical Display form. `None` = bare column-reference
966 /// index (the legacy shape). Persisted alongside
967 /// `partial_predicate` on the v12 catalog snapshot.
968 pub expression: Option<String>,
969 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
970 /// rejects INSERTs whose key already appears in this index
971 /// (combined with `partial_predicate` when present — only
972 /// rows matching the predicate enter the uniqueness check).
973 /// Catalog FILE_VERSION 16+; older snapshots deserialise
974 /// with `false`. mailrs K1.
975 pub is_unique: bool,
976 /// v7.9.29 — extra (non-leading) column positions for
977 /// multi-column indexes (`CREATE INDEX … (a, b, c)`). The
978 /// planner today still only uses the leading
979 /// `column_position` for index seeks, but UNIQUE INDEX
980 /// enforcement walks the full tuple so partial-unique
981 /// invariants like CalDAV `(calendar_id, uid,
982 /// recurrence_id)` are enforced correctly. Catalog
983 /// FILE_VERSION 16+; older snapshots deserialise empty.
984 pub extra_column_positions: Vec<usize>,
985}
986
987/// Default neighbor degree (M) for the NSW graph. Picked at construction
988/// time and persisted with the index.
989pub const NSW_DEFAULT_M: usize = 16;
990
991/// v5.2.2: outcome of a successful [`Catalog::freeze_oldest_to_cold`]
992/// call. The catalog state has already been mutated by the time this
993/// is returned (hot rows dropped + segment registered + Cold locators
994/// flipped). The caller's only remaining concern is `segment_bytes` —
995/// persist them to disk under `<db>.spg/segments/seg_<id>.spg` so a
996/// future restart can reload via the v5.1 `SPG_PRELOAD_COLD_SEGMENT`
997/// path. (v5.3's manifest will subsume this manual step.)
998#[derive(Debug, Clone)]
999pub struct FreezeReport {
1000 /// Id allocated by [`Catalog::load_segment_bytes`] for the new
1001 /// cold-tier segment. Stable across the call's success path.
1002 pub segment_id: u32,
1003 /// Number of rows that moved hot → cold. Equals the `max_rows`
1004 /// the caller asked for (the API is strict on the count).
1005 pub frozen_rows: usize,
1006 /// Hot-tier bytes reclaimed by the freeze — the
1007 /// [`Table::hot_bytes`] delta before vs after. Useful to feed
1008 /// back into the freezer's budget check on the next tick.
1009 pub bytes_freed: u64,
1010 /// Encoded segment bytes, byte-identical to what
1011 /// [`encode_segment`] produced. The catalog already owns a
1012 /// copy inside `cold_segments`; this hand-off lets the caller
1013 /// persist them without re-encoding.
1014 pub segment_bytes: Vec<u8>,
1015}
1016
1017/// v6.7.4 — read-only output of [`Catalog::prepare_freeze_slice`].
1018/// Carries every row body + key in a contiguous hot-row range,
1019/// already encoded and sorted by PK so the coordinator's merge
1020/// step is a k-way merge over already-sorted streams.
1021///
1022/// `Vec<FreezeSlice>` from N independent workers feeds
1023/// [`Catalog::commit_freeze_slices`], which concats + encodes the
1024/// merged segment + atomically swaps the catalog state.
1025#[derive(Debug, Clone)]
1026pub struct FreezeSlice {
1027 /// Hot-row index range this slice covered (half-open, in the
1028 /// table's `rows: PersistentVec` ordering at call time). The
1029 /// commit step uses this to compute the union range that
1030 /// gets passed to [`Table::delete_rows`].
1031 pub row_range: core::ops::Range<usize>,
1032 /// `(pk_u64, encoded_row_body, IndexKey)` triples, sorted
1033 /// ascending by `pk_u64`. Per-slice sort happens inside
1034 /// `prepare_freeze_slice`; the coordinator does only a
1035 /// k-way merge to reach the global PK ordering
1036 /// [`encode_segment`] requires.
1037 pub rows: Vec<(u64, Vec<u8>, IndexKey)>,
1038}
1039
1040/// v6.7.3 — outcome of a [`Catalog::compact_cold_segments`] call.
1041/// The catalog state has already been mutated when this is returned:
1042/// the merged segment is loaded into `cold_segments`, the source
1043/// segment slots are tombstoned (`None`), and every BTree-index
1044/// `RowLocator::Cold` that previously pointed at a source now
1045/// points at the merged segment. The caller's remaining job is to
1046/// persist `merged_segment_bytes` under
1047/// `<db>.spg/segments/seg_<merged_segment_id>.spg` and update the
1048/// in-memory `segment_id → path` map (remove the source ids, add
1049/// the merged id) so the next CHECKPOINT writes a manifest that
1050/// no longer lists the retired sources.
1051///
1052/// On a no-op (fewer than 2 candidate segments under the threshold),
1053/// `merged_segment_id` is `None` and `sources` is empty; the
1054/// catalog was not mutated.
1055#[derive(Debug, Clone)]
1056pub struct CompactReport {
1057 /// Source segment ids that were merged + tombstoned.
1058 pub sources: Vec<u32>,
1059 /// Id allocated for the merged segment. `None` on no-op.
1060 pub merged_segment_id: Option<u32>,
1061 /// Encoded merged-segment bytes (empty on no-op).
1062 pub merged_segment_bytes: Vec<u8>,
1063 /// Number of rows that landed in the merged segment.
1064 pub merged_rows: usize,
1065 /// `Σ source.num_rows − merged_rows`. Rows present in source
1066 /// segment payloads but unreferenced by any live BTree
1067 /// `Cold` locator — DELETE'd-but-still-frozen rows that
1068 /// compaction GC'd during the merge.
1069 pub deleted_rows_pruned: usize,
1070 /// `Σ source.bytes() − merged.bytes()`. Estimate of on-disk
1071 /// space the merge will reclaim once the source segment files
1072 /// are GC'd. Saturating subtract — never negative.
1073 pub bytes_reclaimed_estimate: u64,
1074}
1075
1076#[derive(Debug, Clone)]
1077pub enum IndexKind {
1078 /// v4.40: structural-sharing B-tree over `IndexKey`. Replaces the v0.8
1079 /// `BTreeMap<IndexKey, Vec<usize>>` — `Index::clone` is now an `Arc`
1080 /// bump regardless of index size, so `Catalog::clone` inside the
1081 /// v4.34 auto-commit wrap stays O(1) even for tables with secondary
1082 /// indices (the case that bottlenecked v4.39 at 1M rows in the
1083 /// sweep).
1084 ///
1085 /// v5.1: value type widened from `Vec<usize>` to `Vec<RowLocator>` so
1086 /// a single key can point to a mix of hot-tier rows (`RowLocator::Hot`,
1087 /// equivalent to the pre-v5 `usize` row index) and cold-tier rows
1088 /// (`RowLocator::Cold { segment_id, page_offset }`) once the v5.2
1089 /// freezer starts producing them. Pre-v5.2 only `Hot` entries appear
1090 /// — the on-disk encoding stays at `FILE_VERSION` 8 (raw u64 row index)
1091 /// because every locator round-trips through `RowLocator::from_legacy_v8_u64`
1092 /// without information loss. `FILE_VERSION` 9 with tagged encoding lands
1093 /// alongside the first freezer commit (v5.1 step 2b / v5.2).
1094 BTree(PersistentBTreeMap<IndexKey, Vec<RowLocator>>),
1095 /// Navigable-small-world graph for vector kNN search.
1096 Nsw(NswGraph),
1097 /// v6.7.1 — BRIN (Block Range INdex). Pure metadata: BRIN
1098 /// indexes carry NO in-memory key→locator map. The (min,
1099 /// max) summaries live in each cold-tier segment's v2
1100 /// envelope sidecar; the BRIN entry in `Table.indices` only
1101 /// records THAT a BRIN index exists on this column so the
1102 /// segment encoder + planner can opt into the summary path.
1103 Brin {
1104 /// The cell type at `column_position` at CREATE INDEX time.
1105 /// Used by the planner to type-check WHERE-clause range
1106 /// predicates against the BRIN-indexed column.
1107 column_type: DataType,
1108 },
1109 /// v7.12.3 — GIN inverted index over a `tsvector` column.
1110 ///
1111 /// Storage shape: `lexeme word → Vec<RowLocator>`. The posting
1112 /// list per word is appended in row-order, so range scans are
1113 /// O(matching rows) once the per-word lookup is done. Multi-
1114 /// term queries intersect / union posting lists.
1115 ///
1116 /// `IndexKey::from_value(TsVector)` returns `None` — GIN doesn't
1117 /// participate in `try_index_seek` (which is BTree-equality-keyed).
1118 /// The engine consults this index through `try_gin_lookup` on
1119 /// `WHERE col @@ tsquery` predicates instead.
1120 ///
1121 /// Backed by a `PersistentBTreeMap` so `Catalog::clone` (the
1122 /// per-write snapshot) stays O(1) — same structural-sharing
1123 /// invariant as BTree.
1124 Gin(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1125 /// v7.15.0 — `USING gin (col gin_trgm_ops)` over a `TEXT`
1126 /// column. Posting lists map `trigram` (PG-compatible 3-byte
1127 /// shingle on the lower-cased + space-padded input) to row
1128 /// locators. The planner uses this index to accelerate
1129 /// `WHERE col LIKE '…'` / `ILIKE '…'` / `similarity(col, q) >
1130 /// t` — every literal run of length ≥ 1 in the pattern
1131 /// produces a trigram set, the engine intersects the posting
1132 /// lists, and the LIKE / similarity predicate is re-evaluated
1133 /// per candidate row to filter the over-approximation.
1134 /// Persisted via tag-4 index payload in `FILE_VERSION` 24+.
1135 GinTrgm(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1136 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY (col)` over a
1137 /// `TEXT` / `VARCHAR` column. Posting lists map
1138 /// `tsvector('simple') lexeme` to row locators. At insert /
1139 /// build time the engine derives the lexemes from the cell
1140 /// via the same lower-case tokenisation rule as
1141 /// `to_tsvector('simple', ...)` — the column itself stays a
1142 /// plain text type on disk (mysqldump round-trips would be
1143 /// broken otherwise). The planner uses this index to
1144 /// accelerate MySQL-shape `MATCH(col) AGAINST('term')`
1145 /// queries by mapping them onto the existing tsquery `@@`
1146 /// walker. Persisted via tag-5 index payload in
1147 /// `FILE_VERSION` 33+.
1148 GinFulltext(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1149}
1150
1151/// Multi-layer HNSW graph (v2.13). Each node is assigned a `top_level`;
1152/// it appears in layers `0..=top_level`. Higher layers are sparser, so
1153/// search starts from the entry at the top layer, greedy-descends to
1154/// layer 0, and beam-searches there. Layer 0 keeps a larger neighbour
1155/// budget (`m_max_0 = 2 * m` per the HNSW paper); upper layers cap at
1156/// `m`. The struct name stays `NswGraph` so external users / on-disk
1157/// callers don't have to track a rename — the algorithm changed, the
1158/// data slot didn't.
1159#[derive(Debug, Clone)]
1160pub struct NswGraph {
1161 /// Max neighbours per node on layers ≥ 1.
1162 pub m: usize,
1163 /// Max neighbours on layer 0 (the dense bottom layer). HNSW
1164 /// convention: `m_max_0 = 2 * m`.
1165 pub m_max_0: usize,
1166 /// Entry point — the node that sits on the topmost layer. Search
1167 /// always starts here.
1168 pub entry: Option<usize>,
1169 /// Top layer of the entry node (== `layers.len() - 1` when populated).
1170 pub entry_level: u8,
1171 /// `levels[i]` = top layer of node `i`. Nodes whose vector cell is
1172 /// NULL / non-Vector have `levels[i] = 0` and no neighbour entries.
1173 ///
1174 /// v5.5.0: backed by `PersistentVec` so `NswGraph::clone` (and the
1175 /// `Catalog::clone` on every group-commit write that contains it) is O(1)
1176 /// structural-sharing instead of an O(N) element copy.
1177 pub levels: PersistentVec<u8>,
1178 /// `layers[l][i]` = neighbours of node `i` at layer `l`. Inner vec
1179 /// is empty when node `i` doesn't reach layer `l`.
1180 ///
1181 /// v5.5.0: the per-node middle dimension (the O(N) one) is a
1182 /// `PersistentVec`; the outer layer dimension stays a plain `Vec`
1183 /// (layer count ≤ 8, so its clone is O(1) in practice) and the inner
1184 /// neighbour list stays a `Vec` (bounded by `m_max_0`).
1185 ///
1186 /// v6.1.x: neighbour slot widened from `usize` (8 B on 64-bit) to
1187 /// `u32` (4 B). Row indices are catalog-bounded by `u32::MAX` (4G
1188 /// rows per table); the cast at the NSW boundary asserts this. At
1189 /// 1M dim-128 SQ8, layer 0 adjacency alone shrinks by ~128 MiB
1190 /// — the largest single contribution to the v6.0.5-measured
1191 /// 624 MiB ambition gap. On-disk format already used u32 LE, so
1192 /// this is a pure in-memory layout change; no `FILE_VERSION` bump.
1193 pub layers: Vec<PersistentVec<Vec<u32>>>,
1194}
1195
1196impl NswGraph {
1197 fn new(m: usize) -> Self {
1198 Self {
1199 m,
1200 m_max_0: m.saturating_mul(2),
1201 entry: None,
1202 entry_level: 0,
1203 levels: PersistentVec::new(),
1204 layers: alloc::vec![PersistentVec::new()],
1205 }
1206 }
1207
1208 /// Max-neighbour budget for layer `l`.
1209 pub const fn cap_for_layer(&self, layer: u8) -> usize {
1210 if layer == 0 { self.m_max_0 } else { self.m }
1211 }
1212}
1213
1214/// Deterministic level assignment, seeded on the row index so the same
1215/// insert order reproduces the same topology. Distribution is roughly
1216/// HNSW-flavoured with `mL ≈ 1/ln(M) ≈ 0.36` for M=16: each 4-bit
1217/// chunk that comes up zero promotes the node one layer (so P(level ≥
1218/// L) ≈ (1/16)^L).
1219#[allow(clippy::verbose_bit_mask)] // clippy suggests trailing_zeros(); we need an explicit MAX cap and a stable distribution shape.
1220pub fn nsw_assign_level(row_idx: usize) -> u8 {
1221 const MAX_LEVEL: u8 = 7; // 7 ⇒ ~16^7 ≈ 2.7e8 expected nodes between promotions; ample.
1222 // SplitMix-style mixer — cheap and seedable.
1223 let mut x = (row_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
1224 x ^= x >> 30;
1225 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
1226 x ^= x >> 27;
1227 x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
1228 x ^= x >> 31;
1229 // Count contiguous low-end zero nibbles (4-bit chunks). Each zero
1230 // nibble has probability 1/16, mirroring HNSW's `mL ≈ 1/ln(M)` for
1231 // M=16. `trailing_zeros / 4` would lose the ordering when x = 0, so
1232 // a plain loop with a cap is clearer.
1233 let mut level: u8 = 0;
1234 while x & 0xF == 0 && level < MAX_LEVEL {
1235 level += 1;
1236 x >>= 4;
1237 }
1238 level
1239}
1240
1241impl Index {
1242 fn new_btree(name: String, column_position: usize) -> Self {
1243 Self {
1244 name,
1245 column_position,
1246 kind: IndexKind::BTree(PersistentBTreeMap::new()),
1247 included_columns: Vec::new(),
1248 partial_predicate: None,
1249 expression: None,
1250 is_unique: false,
1251 extra_column_positions: Vec::new(),
1252 }
1253 }
1254
1255 fn new_nsw(name: String, column_position: usize, m: usize) -> Self {
1256 Self {
1257 name,
1258 column_position,
1259 kind: IndexKind::Nsw(NswGraph::new(m)),
1260 included_columns: Vec::new(),
1261 partial_predicate: None,
1262 expression: None,
1263 is_unique: false,
1264 extra_column_positions: Vec::new(),
1265 }
1266 }
1267
1268 /// v6.7.1 — BRIN index constructor. BRIN carries no in-memory
1269 /// data; the `column_type` snapshot is used by the segment
1270 /// encoder + planner for type-checking range predicates.
1271 fn new_brin(name: String, column_position: usize, column_type: DataType) -> Self {
1272 Self {
1273 name,
1274 column_position,
1275 kind: IndexKind::Brin { column_type },
1276 included_columns: Vec::new(),
1277 partial_predicate: None,
1278 expression: None,
1279 is_unique: false,
1280 extra_column_positions: Vec::new(),
1281 }
1282 }
1283
1284 /// v7.12.3 — GIN inverted-index constructor. Empty posting-list
1285 /// map; caller (typically [`Table::add_gin_index`] or
1286 /// [`Table::restore_gin_index`]) populates it from existing rows
1287 /// or from a deserialised snapshot.
1288 fn new_gin(name: String, column_position: usize) -> Self {
1289 Self {
1290 name,
1291 column_position,
1292 kind: IndexKind::Gin(PersistentBTreeMap::new()),
1293 included_columns: Vec::new(),
1294 partial_predicate: None,
1295 expression: None,
1296 is_unique: false,
1297 extra_column_positions: Vec::new(),
1298 }
1299 }
1300
1301 /// v7.15.0 — `gin_trgm_ops`-flavoured GIN constructor. Same
1302 /// shape as `new_gin` but the posting-list keys are 3-byte
1303 /// trigram shingles (`pg_trgm`-compatible) and the column
1304 /// type is `TEXT` / `VARCHAR` (not `TSVECTOR`).
1305 fn new_gin_trgm(name: String, column_position: usize) -> Self {
1306 Self {
1307 name,
1308 column_position,
1309 kind: IndexKind::GinTrgm(PersistentBTreeMap::new()),
1310 included_columns: Vec::new(),
1311 partial_predicate: None,
1312 expression: None,
1313 is_unique: false,
1314 extra_column_positions: Vec::new(),
1315 }
1316 }
1317
1318 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN constructor.
1319 /// Same shape as `new_gin_trgm` but the posting-list keys
1320 /// are lower-cased word lexemes (`to_tsvector('simple', col)`
1321 /// equivalent) instead of trigrams, and the column type is
1322 /// `TEXT` / `VARCHAR` (not `TSVECTOR`).
1323 fn new_gin_fulltext(name: String, column_position: usize) -> Self {
1324 Self {
1325 name,
1326 column_position,
1327 kind: IndexKind::GinFulltext(PersistentBTreeMap::new()),
1328 included_columns: Vec::new(),
1329 partial_predicate: None,
1330 expression: None,
1331 is_unique: false,
1332 extra_column_positions: Vec::new(),
1333 }
1334 }
1335
1336 /// Look up the locators stored under `key` (B-tree only). Returns
1337 /// an empty slice when the key is absent or the index isn't a
1338 /// BTree — callers can treat both cases uniformly.
1339 ///
1340 /// v5.1: return type widened from `&[usize]` to `&[RowLocator]`.
1341 /// Pre-v5.2 callers can read the slice and `.as_hot().unwrap()`
1342 /// each entry (no `Cold` variants exist until the freezer lands);
1343 /// post-v5.2 callers dispatch hot vs. cold per locator.
1344 pub fn lookup_eq(&self, key: &IndexKey) -> &[RowLocator] {
1345 match &self.kind {
1346 IndexKind::BTree(m) => m.get(key).map_or(&[][..], Vec::as_slice),
1347 // BRIN / NSW / GIN / trigram-GIN / fulltext-GIN have
1348 // no IndexKey-keyed map; lookup is a no-op. GIN uses
1349 // [`Index::gin_lookup_word`] instead.
1350 IndexKind::Nsw(_)
1351 | IndexKind::Brin { .. }
1352 | IndexKind::Gin(_)
1353 | IndexKind::GinTrgm(_)
1354 | IndexKind::GinFulltext(_) => &[][..],
1355 }
1356 }
1357
1358 /// v7.12.3 — GIN posting-list lookup. Returns the row locators
1359 /// whose `tsvector` cell contains `word`. Empty when the word is
1360 /// absent from the index or this isn't a GIN index.
1361 pub fn gin_lookup_word(&self, word: &str) -> &[RowLocator] {
1362 match &self.kind {
1363 // v7.17.0 Phase 2.2 — fulltext-GIN shares the same
1364 // lexeme-keyed posting list shape as the
1365 // tsvector-typed GIN, so the same lookup applies.
1366 IndexKind::Gin(m) | IndexKind::GinFulltext(m) => {
1367 m.get(&String::from(word)).map_or(&[][..], Vec::as_slice)
1368 }
1369 IndexKind::BTree(_)
1370 | IndexKind::Nsw(_)
1371 | IndexKind::Brin { .. }
1372 | IndexKind::GinTrgm(_) => &[][..],
1373 }
1374 }
1375
1376 /// v7.15.0 — trigram-GIN posting-list lookup. Returns the row
1377 /// locators whose indexed `TEXT` cell contains the trigram
1378 /// `tri`. Empty when the trigram is absent or this isn't a
1379 /// trigram-GIN index.
1380 pub fn gin_trgm_lookup(&self, tri: &str) -> &[RowLocator] {
1381 match &self.kind {
1382 IndexKind::GinTrgm(m) => m.get(&String::from(tri)).map_or(&[][..], Vec::as_slice),
1383 IndexKind::BTree(_)
1384 | IndexKind::Nsw(_)
1385 | IndexKind::Brin { .. }
1386 | IndexKind::Gin(_)
1387 | IndexKind::GinFulltext(_) => &[][..],
1388 }
1389 }
1390
1391 /// Borrow the NSW graph (if this is an NSW index). Callers that need
1392 /// the graph for a kNN search go through here.
1393 pub const fn nsw(&self) -> Option<&NswGraph> {
1394 match &self.kind {
1395 IndexKind::Nsw(g) => Some(g),
1396 IndexKind::BTree(_)
1397 | IndexKind::Brin { .. }
1398 | IndexKind::Gin(_)
1399 | IndexKind::GinTrgm(_)
1400 | IndexKind::GinFulltext(_) => None,
1401 }
1402 }
1403
1404 /// v6.7.1 — true when this index is a BRIN (block range) index.
1405 /// Used by the segment encoder to opt into BRIN sidecar emission
1406 /// at freeze time, and by the planner to opt into page-skipping
1407 /// on range predicates.
1408 pub const fn is_brin(&self) -> bool {
1409 matches!(self.kind, IndexKind::Brin { .. })
1410 }
1411
1412 /// v7.15.0 — true when this index is a trigram GIN
1413 /// (`gin_trgm_ops`-flavoured). Used by the LIKE planner to
1414 /// opt into trigram acceleration.
1415 pub const fn is_gin_trgm(&self) -> bool {
1416 matches!(self.kind, IndexKind::GinTrgm(_))
1417 }
1418
1419 /// v7.12.3 — true when this index is a GIN inverted index.
1420 /// Used by the planner to opt into posting-list acceleration on
1421 /// `WHERE col @@ tsquery` predicates.
1422 pub const fn is_gin(&self) -> bool {
1423 matches!(self.kind, IndexKind::Gin(_))
1424 }
1425
1426 /// v7.17.0 Phase 2.2 — true when this index is a fulltext
1427 /// GIN over a TEXT / VARCHAR column (MySQL `FULLTEXT KEY`
1428 /// surface). Used by the planner to opt the FULLTEXT-indexed
1429 /// column into MATCH AGAINST acceleration.
1430 pub const fn is_gin_fulltext(&self) -> bool {
1431 matches!(self.kind, IndexKind::GinFulltext(_))
1432 }
1433}
1434
1435/// In-memory table: schema + a persistent row vector + secondary indices.
1436///
1437/// v4.39: `rows` is a [`PersistentVec`] (Bitmapped Vector Trie, 32-way) so
1438/// `Table::clone()` is `O(1)` — the whole reason for v4.39's existence is
1439/// to make `Catalog::clone()` cheap inside the v4.34 auto-commit wrap.
1440///
1441/// v5.2.1: `hot_bytes` tracks the encoded byte size of every row currently
1442/// in [`Self::rows`], summed over rows. Updated incrementally by `insert`
1443/// (+= encoded row size), `delete_rows` (-= removed rows' encoded sizes),
1444/// and `update_row` (-= old size, += new size). The value is what the
1445/// v5.2 freezer reads to decide when to demote cold rows — when the
1446/// catalog-wide sum crosses `SPG_HOT_TIER_BYTES` (default 4 GiB) the
1447/// freezer thread wakes. v5.2.1 ships measurement only; the freezer
1448/// itself lands in v5.2.2. Stored as `u64` so a single field clone in
1449/// `Catalog::clone` stays at the O(1) invariant v4.39 built.
1450#[derive(Debug, Clone)]
1451pub struct Table {
1452 schema: TableSchema,
1453 rows: PersistentVec<Row>,
1454 indices: Vec<Index>,
1455 hot_bytes: u64,
1456 /// v6.7.0 — cached count of rows currently materialised in the
1457 /// cold tier via `RowLocator::Cold` entries across THIS table's
1458 /// indices. Populated by `ANALYZE` (walks every BTree index and
1459 /// counts Cold locators); the count survives until the next
1460 /// ANALYZE recomputes it. Surfaced via `spg_statistic.cold_row_count`
1461 /// and `spg_stat_segment.table_name`.
1462 ///
1463 /// Honest scope: this is a CACHED count, not a live one.
1464 /// Freezer / promote / DELETE don't currently update the cache
1465 /// incrementally — they invalidate it by setting the
1466 /// `cold_row_count_stale` flag, and the next ANALYZE re-walks.
1467 /// Incremental maintenance is a v6.7.x candidate if observation
1468 /// shows the ANALYZE walk cost dominates.
1469 cold_row_count: u64,
1470 /// v6.7.0 — set when the cached `cold_row_count` may be wrong
1471 /// because rows moved into / out of the cold tier since the last
1472 /// ANALYZE. The virtual-table surface reports the cached value
1473 /// regardless (operators run ANALYZE to refresh).
1474 cold_row_count_stale: bool,
1475}
1476
1477impl Table {
1478 pub fn new(schema: TableSchema) -> Self {
1479 Self {
1480 schema,
1481 rows: PersistentVec::new(),
1482 indices: Vec::new(),
1483 hot_bytes: 0,
1484 cold_row_count: 0,
1485 cold_row_count_stale: false,
1486 }
1487 }
1488
1489 /// Total encoded byte size of every row currently in the hot tier
1490 /// (`self.rows`). See struct docs for the maintenance contract.
1491 /// Returns 0 for an empty table.
1492 #[must_use]
1493 pub const fn hot_bytes(&self) -> u64 {
1494 self.hot_bytes
1495 }
1496
1497 /// v6.7.0 — cached count of cold-tier rows. See struct field
1498 /// docs for the staleness contract.
1499 #[must_use]
1500 pub const fn cold_row_count(&self) -> u64 {
1501 self.cold_row_count
1502 }
1503
1504 /// v6.7.0 — overwrite the cached count. Called by the engine's
1505 /// `analyze_one_table` after walking the indices.
1506 pub fn set_cold_row_count(&mut self, n: u64) {
1507 self.cold_row_count = n;
1508 self.cold_row_count_stale = false;
1509 }
1510
1511 /// v6.7.0 — mark the cached count as potentially out of date.
1512 /// Called by freezer / promote / DELETE paths so a subsequent
1513 /// `spg_statistic` read knows the number may not reflect the
1514 /// current state.
1515 pub fn mark_cold_row_count_stale(&mut self) {
1516 self.cold_row_count_stale = true;
1517 }
1518
1519 /// v6.7.0 — report whether the cached count is known to be out
1520 /// of date. Exposed for completeness; the virtual table surface
1521 /// returns the cached value regardless.
1522 #[must_use]
1523 pub const fn cold_row_count_stale(&self) -> bool {
1524 self.cold_row_count_stale
1525 }
1526
1527 /// v6.7.0 — walk every BTree index and count `RowLocator::Cold`
1528 /// entries; return the MAX across indices. The freeze path
1529 /// (`freeze_oldest_to_cold`) writes cold locators to ONE
1530 /// designated index — that index ends up with the full per-row
1531 /// count. MAX-across-indices yields the precise count when a
1532 /// PK-style index exists; for multi-index tables without a
1533 /// covering index it's a lower bound (rare in practice).
1534 /// Caller responsibility: only invoke under `engine.write()`
1535 /// or after taking ownership; the walk is O(N) over every
1536 /// (key, locator) pair.
1537 #[must_use]
1538 pub fn count_cold_locators(&self) -> u64 {
1539 let mut best: u64 = 0;
1540 for idx in &self.indices {
1541 if let IndexKind::BTree(map) = &idx.kind {
1542 let n: u64 = map
1543 .iter()
1544 .map(|(_, locs)| locs.iter().filter(|l| l.is_cold()).count() as u64)
1545 .sum();
1546 if n > best {
1547 best = n;
1548 }
1549 }
1550 }
1551 best
1552 }
1553
1554 pub const fn schema(&self) -> &TableSchema {
1555 &self.schema
1556 }
1557
1558 /// v6.7.2 — mutable schema accessor for ALTER TABLE paths.
1559 /// Used by `Engine::exec_alter_table` to flip per-table
1560 /// settings like `hot_tier_bytes`.
1561 pub const fn schema_mut(&mut self) -> &mut TableSchema {
1562 &mut self.schema
1563 }
1564
1565 /// v4.39: returns the persistent row vector by reference. Callers that
1566 /// used to take `&[Row]` should switch to `.iter()` (via
1567 /// `IntoIterator for &PersistentVec`) or `.get(i)` for indexing.
1568 pub const fn rows(&self) -> &PersistentVec<Row> {
1569 &self.rows
1570 }
1571
1572 pub const fn row_count(&self) -> usize {
1573 self.rows.len()
1574 }
1575
1576 /// v6.8.0 — exposed for the engine layer to patch
1577 /// `Index::included_columns` post-creation. Could fold into
1578 /// `add_index` once the engine's IF-NOT-EXISTS guard moves up,
1579 /// but the patch shape is the minimal change for v6.8.0.
1580 pub fn indices_mut(&mut self) -> &mut [Index] {
1581 &mut self.indices
1582 }
1583
1584 pub fn indices(&self) -> &[Index] {
1585 &self.indices
1586 }
1587
1588 /// Compute the next `AUTO_INCREMENT` value for the column at
1589 /// `col_pos`. Defined as `max(existing) + 1`, falling back to `1`
1590 /// when the column currently holds no integer values. NULL / non-
1591 /// integer cells are skipped. Returns `None` when the column isn't
1592 /// an integer type.
1593 pub fn next_auto_value(&self, col_pos: usize) -> Option<i64> {
1594 let ty = self.schema.columns.get(col_pos)?.ty;
1595 if !matches!(ty, DataType::SmallInt | DataType::Int | DataType::BigInt) {
1596 return None;
1597 }
1598 let mut max: Option<i64> = None;
1599 for row in &self.rows {
1600 match row.values.get(col_pos) {
1601 Some(Value::SmallInt(n)) => {
1602 let v = i64::from(*n);
1603 max = Some(max.map_or(v, |m| m.max(v)));
1604 }
1605 Some(Value::Int(n)) => {
1606 let v = i64::from(*n);
1607 max = Some(max.map_or(v, |m| m.max(v)));
1608 }
1609 Some(Value::BigInt(n)) => {
1610 max = Some(max.map_or(*n, |m| m.max(*n)));
1611 }
1612 _ => {}
1613 }
1614 }
1615 Some(max.map_or(1, |m| m + 1))
1616 }
1617
1618 /// Return the first index defined over `column_position`, if any.
1619 /// (`v0.8` supports at most one index per column logically; the search
1620 /// just picks the first match.)
1621 pub fn index_on(&self, column_position: usize) -> Option<&Index> {
1622 // v6.7.1 — prefer BTree (has the key→locator map needed
1623 // for `lookup_eq`) over BRIN (metadata-only). When only a
1624 // BRIN exists on the column, return None so the executor
1625 // falls back to the hot-tier row scan instead of trying
1626 // to use BRIN for an equality lookup (which would always
1627 // return an empty slice and look like "no rows matched").
1628 self.indices
1629 .iter()
1630 .find(|i| i.column_position == column_position && matches!(i.kind, IndexKind::BTree(_)))
1631 .or_else(|| {
1632 self.indices.iter().find(|i| {
1633 i.column_position == column_position && matches!(i.kind, IndexKind::Nsw(_))
1634 })
1635 })
1636 }
1637
1638 /// Insert one row after validating it matches the schema (length + type).
1639 /// Returns `StorageError` on mismatch — the table is left unchanged.
1640 /// Updates every defined index with the new row's key.
1641 pub fn insert(&mut self, row: Row) -> Result<(), StorageError> {
1642 if row.len() != self.schema.columns.len() {
1643 return Err(StorageError::ArityMismatch {
1644 expected: self.schema.columns.len(),
1645 actual: row.len(),
1646 });
1647 }
1648 for (i, (val, col)) in row.values.iter().zip(&self.schema.columns).enumerate() {
1649 if val.is_null() {
1650 if !col.nullable {
1651 return Err(StorageError::NullInNotNull {
1652 column: col.name.clone(),
1653 });
1654 }
1655 continue;
1656 }
1657 let actual = val.data_type().expect("non-null");
1658 // Vector columns require both that the value's variant be Vector
1659 // *and* its dimension match. `actual == col.ty` already encodes
1660 // both because DataType::Vector carries the dim.
1661 //
1662 // VARCHAR(n) / CHAR(n) are storage-equivalent to TEXT — the
1663 // length / padding contract is enforced upstream by
1664 // `coerce_value`. Accept a `Text` value into either.
1665 //
1666 // NUMERIC's `Value::Numeric` carries its actual scale but the
1667 // column declares the *expected* scale (a scale-rescaled
1668 // Value::Numeric is produced upstream by `coerce_value`); the
1669 // structural check here only verifies "value is Numeric and
1670 // its scale equals the column scale".
1671 let compatible = actual == col.ty
1672 || matches!(
1673 (actual, col.ty),
1674 (
1675 DataType::Text,
1676 DataType::Varchar(_) | DataType::Char(_) | DataType::Json | DataType::Jsonb
1677 ) | (DataType::Json | DataType::Jsonb, DataType::Text)
1678 | (DataType::Json, DataType::Jsonb)
1679 | (DataType::Jsonb, DataType::Json)
1680 | (DataType::Timestamp, DataType::Timestamptz)
1681 | (DataType::Timestamptz, DataType::Timestamp)
1682 )
1683 || matches!(
1684 (actual, col.ty),
1685 (
1686 DataType::Numeric { scale: a, .. },
1687 DataType::Numeric { scale: b, .. },
1688 ) if a == b
1689 );
1690 if !compatible {
1691 return Err(StorageError::TypeMismatch {
1692 column: col.name.clone(),
1693 expected: col.ty,
1694 actual,
1695 position: i,
1696 });
1697 }
1698 }
1699 let new_row_idx = self.rows.len();
1700 // Pre-validate before mutating: ensure indices receive an IndexKey.
1701 // For NSW we defer the graph update to *after* the row is pushed
1702 // so the kNN search can see it in `self.rows`.
1703 for idx in &mut self.indices {
1704 match &mut idx.kind {
1705 IndexKind::BTree(map) => {
1706 if let Some(key) = IndexKey::from_value(&row.values[idx.column_position]) {
1707 // v4.40: PersistentBTreeMap has no in-place entry-or-default.
1708 // Clone-then-insert keeps the same semantics — for typical
1709 // unique-key schemas the Vec is 1-element so the clone is
1710 // O(1). For dup-heavy columns it's O(M) per insert, traded
1711 // for the structural-sharing win at clone time.
1712 let mut entries = map.get(&key).cloned().unwrap_or_default();
1713 entries.push(RowLocator::Hot(new_row_idx));
1714 map.insert_mut(key, entries);
1715 }
1716 }
1717 IndexKind::Gin(map) => {
1718 // v7.12.3 — extend posting list per lexeme word.
1719 // NULL or non-TsVector cell → no-op (cell carries
1720 // no lexemes to index).
1721 if let Value::TsVector(lexemes) = &row.values[idx.column_position] {
1722 for lex in lexemes {
1723 let mut entries = map.get(&lex.word).cloned().unwrap_or_default();
1724 entries.push(RowLocator::Hot(new_row_idx));
1725 map.insert_mut(lex.word.clone(), entries);
1726 }
1727 }
1728 }
1729 IndexKind::GinTrgm(map) => {
1730 // v7.15.0 — trigram GIN. Shingle the TEXT cell
1731 // into PG-compatible 3-byte trigrams and extend
1732 // each trigram's posting list.
1733 if let Value::Text(s) = &row.values[idx.column_position] {
1734 for tri in trgm::extract_trigrams(s) {
1735 let mut entries = map.get(&tri).cloned().unwrap_or_default();
1736 entries.push(RowLocator::Hot(new_row_idx));
1737 map.insert_mut(tri, entries);
1738 }
1739 }
1740 }
1741 IndexKind::GinFulltext(map) => {
1742 // v7.17.0 Phase 2.2 — MySQL FULLTEXT-shape
1743 // GIN over a TEXT / VARCHAR cell. Tokenise
1744 // via the storage-local `simple_lex` (same
1745 // rule as `to_tsvector('simple', text)`) and
1746 // extend each lexeme's posting list.
1747 let text_cell = match &row.values[idx.column_position] {
1748 Value::Text(s) => Some(s.as_str()),
1749 // mysqldump-style mediumtext / longtext
1750 // land as Value::Text on insert; varchar
1751 // cells likewise. Anything else (NULL,
1752 // integer, …) contributes no lexemes.
1753 _ => None,
1754 };
1755 if let Some(s) = text_cell {
1756 for lex in fts_simple::simple_lex(s) {
1757 let mut entries = map.get(&lex).cloned().unwrap_or_default();
1758 entries.push(RowLocator::Hot(new_row_idx));
1759 map.insert_mut(lex, entries);
1760 }
1761 }
1762 }
1763 // NSW handled below after the row push (so the new row
1764 // is visible to the kNN-graph connect step). BRIN
1765 // carries no per-row state.
1766 IndexKind::Nsw(_) | IndexKind::Brin { .. } => {}
1767 }
1768 }
1769 // v5.2.1: maintain incremental hot-tier byte counter. Computed
1770 // before the move so we don't need to borrow `row` after push.
1771 self.hot_bytes = self
1772 .hot_bytes
1773 .saturating_add(row_body_encoded_len(&row, &self.schema) as u64);
1774 // v4.39.1: push_mut keeps streaming inserts at Vec::push speed when
1775 // the table is uniquely owned (the spg-embedded path); inside a TX
1776 // wrap where a Catalog snapshot exists, push_mut path-copies the
1777 // tail just like push() and the snapshot stays valid.
1778 self.rows.push_mut(row);
1779 // NSW updates after the push so the new row is visible to the
1780 // greedy search used during connect.
1781 let new_row_idx = self.rows.len() - 1;
1782 let nsw_targets: Vec<usize> = self
1783 .indices
1784 .iter()
1785 .enumerate()
1786 .filter_map(|(i, idx)| {
1787 if matches!(idx.kind, IndexKind::Nsw(_)) {
1788 Some(i)
1789 } else {
1790 None
1791 }
1792 })
1793 .collect();
1794 for idx_pos in nsw_targets {
1795 nsw_insert_at(self, idx_pos, new_row_idx);
1796 }
1797 Ok(())
1798 }
1799
1800 /// Build a new B-tree index over the named column. Rebuilds from
1801 /// existing rows. Errors if `column_name` doesn't exist or the index
1802 /// name is taken.
1803 pub fn add_index(&mut self, name: String, column_name: &str) -> Result<(), StorageError> {
1804 if self.indices.iter().any(|i| i.name == name) {
1805 return Err(StorageError::DuplicateIndex { name });
1806 }
1807 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
1808 StorageError::ColumnNotFound {
1809 column: column_name.into(),
1810 }
1811 })?;
1812 let mut idx = Index::new_btree(name, column_position);
1813 if let IndexKind::BTree(map) = &mut idx.kind {
1814 for (i, row) in self.rows.iter().enumerate() {
1815 if let Some(key) = IndexKey::from_value(&row.values[column_position]) {
1816 let mut entries = map.get(&key).cloned().unwrap_or_default();
1817 entries.push(RowLocator::Hot(i));
1818 map.insert_mut(key, entries);
1819 }
1820 }
1821 }
1822 self.indices.push(idx);
1823 Ok(())
1824 }
1825
1826 /// Build a new NSW (HNSW-flavoured) index over the named column.
1827 /// Required for `ORDER BY col <-> literal LIMIT k` to plan as a
1828 /// graph traversal instead of a full scan. Column must be a Vector
1829 /// type. `m` is the maximum number of neighbours per node.
1830 pub fn add_nsw_index(
1831 &mut self,
1832 name: String,
1833 column_name: &str,
1834 m: usize,
1835 ) -> Result<(), StorageError> {
1836 self.add_nsw_index_inner(name, column_name, m, None)
1837 }
1838
1839 /// v6.0.4 — synchronous rebuild of the named NSW index. If
1840 /// `new_encoding` is `Some(target)` and differs from the column's
1841 /// current encoding, every stored cell at the indexed column is
1842 /// re-coded into the target encoding before the new graph
1843 /// builds. Returns `IndexNotFound` if no index by that name exists
1844 /// and `Unsupported` for non-NSW indexes (`BTree` REBUILD is a no-op
1845 /// the engine layer rejects, not a storage-level concept).
1846 ///
1847 /// Holds the caller's `&mut self` for the duration — no
1848 /// concurrency / staging / WAL-replay machinery in v6.0.4. The
1849 /// "live" optimisation lands as v6.0.4.1.
1850 pub fn rebuild_nsw_index(
1851 &mut self,
1852 name: &str,
1853 new_encoding: Option<VecEncoding>,
1854 ) -> Result<(), StorageError> {
1855 let idx_pos = self
1856 .indices
1857 .iter()
1858 .position(|i| i.name == name)
1859 .ok_or_else(|| StorageError::IndexNotFound {
1860 name: String::from(name),
1861 })?;
1862 let col_pos = self.indices[idx_pos].column_position;
1863 let m = match &self.indices[idx_pos].kind {
1864 IndexKind::Nsw(g) => g.m,
1865 IndexKind::BTree(_)
1866 | IndexKind::Brin { .. }
1867 | IndexKind::Gin(_)
1868 | IndexKind::GinTrgm(_)
1869 | IndexKind::GinFulltext(_) => {
1870 return Err(StorageError::Unsupported(format!(
1871 "ALTER INDEX REBUILD on non-NSW index {name:?} — only NSW indexes can rebuild"
1872 )));
1873 }
1874 };
1875 let col_name = self.schema.columns[col_pos].name.clone();
1876 // 1. Optional re-encoding pass. Done first so the cells
1877 // match the schema before the graph rebuild walks them.
1878 if let Some(target) = new_encoding {
1879 let current = match self.schema.columns[col_pos].ty {
1880 DataType::Vector { encoding, .. } => encoding,
1881 ref other => {
1882 return Err(StorageError::Unsupported(format!(
1883 "ALTER INDEX REBUILD WITH (encoding=…) on non-vector column type {other:?}"
1884 )));
1885 }
1886 };
1887 if target != current {
1888 let DataType::Vector { dim, .. } = self.schema.columns[col_pos].ty else {
1889 unreachable!("checked above")
1890 };
1891 let n = self.rows.len();
1892 for i in 0..n {
1893 let row = self
1894 .rows
1895 .get_mut(i)
1896 .expect("row index in bounds (we iterated up to len())");
1897 let cell = core::mem::replace(&mut row.values[col_pos], Value::Null);
1898 let recoded = recode_vector_cell(cell, target)?;
1899 row.values[col_pos] = recoded;
1900 }
1901 self.schema.columns[col_pos].ty = DataType::Vector {
1902 dim,
1903 encoding: target,
1904 };
1905 }
1906 }
1907 // 2. Drop the existing index slot + rebuild from row payload.
1908 self.indices.remove(idx_pos);
1909 self.add_nsw_index_inner(String::from(name), &col_name, m, None)?;
1910 Ok(())
1911 }
1912
1913 /// Restore an NSW index from a pre-built graph (used on
1914 /// deserialize). Skips the bulk-build pass since the topology is
1915 /// already known. Returns `DuplicateIndex` or `ColumnNotFound` on
1916 /// schema mismatch as usual.
1917 pub fn restore_nsw_index(
1918 &mut self,
1919 name: String,
1920 column_name: &str,
1921 graph: NswGraph,
1922 ) -> Result<(), StorageError> {
1923 self.add_nsw_index_inner(name, column_name, graph.m, Some(graph))
1924 }
1925
1926 /// Restore a `BTree` index from a pre-built `(IndexKey, Vec<RowLocator>)`
1927 /// map. Used by [`Catalog::deserialize`] when reading a v9 (or later)
1928 /// catalog snapshot — the map travels on disk so cold-tier locators
1929 /// survive a round-trip, instead of being rebuilt from `self.rows`
1930 /// (which would lose every Cold entry). Same error contract as
1931 /// [`Table::add_index`].
1932 pub fn restore_btree_index(
1933 &mut self,
1934 name: String,
1935 column_name: &str,
1936 map: PersistentBTreeMap<IndexKey, Vec<RowLocator>>,
1937 ) -> Result<(), StorageError> {
1938 if self.indices.iter().any(|i| i.name == name) {
1939 return Err(StorageError::DuplicateIndex { name });
1940 }
1941 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
1942 StorageError::ColumnNotFound {
1943 column: column_name.into(),
1944 }
1945 })?;
1946 self.indices.push(Index {
1947 name,
1948 column_position,
1949 kind: IndexKind::BTree(map),
1950 included_columns: Vec::new(),
1951 partial_predicate: None,
1952 expression: None,
1953 is_unique: false,
1954 extra_column_positions: Vec::new(),
1955 });
1956 Ok(())
1957 }
1958
1959 /// v6.7.1 — public restore counterpart for BRIN indices. Used
1960 /// by `Catalog::deserialize` when a v10 snapshot carries a
1961 /// BRIN index entry. BRIN carries no in-memory data — only the
1962 /// `column_type` snapshot is restored.
1963 pub fn restore_brin_index(
1964 &mut self,
1965 name: String,
1966 column_name: &str,
1967 column_type: DataType,
1968 ) -> Result<(), StorageError> {
1969 if self.indices.iter().any(|i| i.name == name) {
1970 return Err(StorageError::DuplicateIndex { name });
1971 }
1972 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
1973 StorageError::ColumnNotFound {
1974 column: column_name.into(),
1975 }
1976 })?;
1977 self.indices
1978 .push(Index::new_brin(name, column_position, column_type));
1979 Ok(())
1980 }
1981
1982 /// v6.7.1 — public CREATE INDEX counterpart for BRIN. Creates
1983 /// the index entry with a snapshot of the indexed column's
1984 /// current `DataType`.
1985 pub fn add_brin_index(&mut self, name: String, column_name: &str) -> Result<(), StorageError> {
1986 if self.indices.iter().any(|i| i.name == name) {
1987 return Err(StorageError::DuplicateIndex { name });
1988 }
1989 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
1990 StorageError::ColumnNotFound {
1991 column: column_name.into(),
1992 }
1993 })?;
1994 let column_type = self.schema.columns[column_position].ty;
1995 self.indices
1996 .push(Index::new_brin(name, column_position, column_type));
1997 Ok(())
1998 }
1999
2000 /// v7.12.3 — Build a new GIN inverted index over a `tsvector`
2001 /// column. Populates posting lists from existing rows. Errors
2002 /// if the column doesn't exist, isn't `TsVector`, or the index
2003 /// name is taken.
2004 pub fn add_gin_index(&mut self, name: String, column_name: &str) -> Result<(), StorageError> {
2005 if self.indices.iter().any(|i| i.name == name) {
2006 return Err(StorageError::DuplicateIndex { name });
2007 }
2008 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2009 StorageError::ColumnNotFound {
2010 column: column_name.into(),
2011 }
2012 })?;
2013 if self.schema.columns[column_position].ty != DataType::TsVector {
2014 return Err(StorageError::Corrupt(format!(
2015 "GIN index {name:?} requires a tsvector column; \
2016 {column_name:?} is {:?}",
2017 self.schema.columns[column_position].ty
2018 )));
2019 }
2020 let mut idx = Index::new_gin(name, column_position);
2021 if let IndexKind::Gin(map) = &mut idx.kind {
2022 for (i, row) in self.rows.iter().enumerate() {
2023 if let Value::TsVector(lexemes) = &row.values[column_position] {
2024 for lex in lexemes {
2025 let mut entries = map.get(&lex.word).cloned().unwrap_or_default();
2026 entries.push(RowLocator::Hot(i));
2027 map.insert_mut(lex.word.clone(), entries);
2028 }
2029 }
2030 }
2031 }
2032 self.indices.push(idx);
2033 Ok(())
2034 }
2035
2036 /// v7.12.3 — Restore a GIN index from a deserialised snapshot.
2037 /// Mirrors [`Self::restore_btree_index`] but takes the GIN's
2038 /// `word → Vec<RowLocator>` posting-list map (already populated
2039 /// from the catalog stream) instead of an `IndexKey` map.
2040 pub fn restore_gin_index(
2041 &mut self,
2042 name: String,
2043 column_name: &str,
2044 map: PersistentBTreeMap<String, Vec<RowLocator>>,
2045 ) -> Result<(), StorageError> {
2046 if self.indices.iter().any(|i| i.name == name) {
2047 return Err(StorageError::DuplicateIndex { name });
2048 }
2049 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2050 StorageError::ColumnNotFound {
2051 column: column_name.into(),
2052 }
2053 })?;
2054 let mut idx = Index::new_gin(name, column_position);
2055 idx.kind = IndexKind::Gin(map);
2056 self.indices.push(idx);
2057 Ok(())
2058 }
2059
2060 /// v7.15.0 — `gin_trgm_ops` GIN over a TEXT column. Walks
2061 /// every row, shingles the cell into PG-compatible trigrams,
2062 /// and builds the posting-list map. NULL / non-TEXT cells
2063 /// contribute nothing (no trigrams).
2064 pub fn add_gin_trgm_index(
2065 &mut self,
2066 name: String,
2067 column_name: &str,
2068 ) -> Result<(), StorageError> {
2069 if self.indices.iter().any(|i| i.name == name) {
2070 return Err(StorageError::DuplicateIndex { name });
2071 }
2072 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2073 StorageError::ColumnNotFound {
2074 column: column_name.into(),
2075 }
2076 })?;
2077 if !matches!(
2078 self.schema.columns[column_position].ty,
2079 DataType::Text | DataType::Varchar(_)
2080 ) {
2081 return Err(StorageError::Corrupt(format!(
2082 "trigram-GIN index {name:?} requires a TEXT/VARCHAR column; \
2083 {column_name:?} is {:?}",
2084 self.schema.columns[column_position].ty
2085 )));
2086 }
2087 let mut idx = Index::new_gin_trgm(name, column_position);
2088 if let IndexKind::GinTrgm(map) = &mut idx.kind {
2089 for (i, row) in self.rows.iter().enumerate() {
2090 if let Value::Text(s) = &row.values[column_position] {
2091 for tri in trgm::extract_trigrams(s) {
2092 let mut entries = map.get(&tri).cloned().unwrap_or_default();
2093 entries.push(RowLocator::Hot(i));
2094 map.insert_mut(tri, entries);
2095 }
2096 }
2097 }
2098 }
2099 self.indices.push(idx);
2100 Ok(())
2101 }
2102
2103 /// v7.15.0 — restore a trigram-GIN from its catalog snapshot
2104 /// payload. Mirrors [`Self::restore_gin_index`].
2105 pub fn restore_gin_trgm_index(
2106 &mut self,
2107 name: String,
2108 column_name: &str,
2109 map: PersistentBTreeMap<String, Vec<RowLocator>>,
2110 ) -> Result<(), StorageError> {
2111 if self.indices.iter().any(|i| i.name == name) {
2112 return Err(StorageError::DuplicateIndex { name });
2113 }
2114 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2115 StorageError::ColumnNotFound {
2116 column: column_name.into(),
2117 }
2118 })?;
2119 let mut idx = Index::new_gin_trgm(name, column_position);
2120 idx.kind = IndexKind::GinTrgm(map);
2121 self.indices.push(idx);
2122 Ok(())
2123 }
2124
2125 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN over a TEXT
2126 /// column. Walks every row, tokenises the cell into lower-
2127 /// cased word lexemes (`fts_simple::simple_lex` — same rule
2128 /// as `to_tsvector('simple', text)`), and builds the
2129 /// posting-list map. NULL / non-TEXT cells contribute
2130 /// nothing (no lexemes).
2131 pub fn add_gin_fulltext_index(
2132 &mut self,
2133 name: String,
2134 column_name: &str,
2135 ) -> Result<(), StorageError> {
2136 if self.indices.iter().any(|i| i.name == name) {
2137 return Err(StorageError::DuplicateIndex { name });
2138 }
2139 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2140 StorageError::ColumnNotFound {
2141 column: column_name.into(),
2142 }
2143 })?;
2144 if !matches!(
2145 self.schema.columns[column_position].ty,
2146 DataType::Text | DataType::Varchar(_)
2147 ) {
2148 return Err(StorageError::Corrupt(format!(
2149 "fulltext-GIN index {name:?} requires a TEXT/VARCHAR column; \
2150 {column_name:?} is {:?}",
2151 self.schema.columns[column_position].ty
2152 )));
2153 }
2154 let mut idx = Index::new_gin_fulltext(name, column_position);
2155 if let IndexKind::GinFulltext(map) = &mut idx.kind {
2156 for (i, row) in self.rows.iter().enumerate() {
2157 if let Value::Text(s) = &row.values[column_position] {
2158 for lex in fts_simple::simple_lex(s) {
2159 let mut entries = map.get(&lex).cloned().unwrap_or_default();
2160 entries.push(RowLocator::Hot(i));
2161 map.insert_mut(lex, entries);
2162 }
2163 }
2164 }
2165 }
2166 self.indices.push(idx);
2167 Ok(())
2168 }
2169
2170 /// v7.17.0 Phase 2.2 — restore a fulltext-GIN from its
2171 /// catalog snapshot payload. Mirrors
2172 /// [`Self::restore_gin_trgm_index`].
2173 pub fn restore_gin_fulltext_index(
2174 &mut self,
2175 name: String,
2176 column_name: &str,
2177 map: PersistentBTreeMap<String, Vec<RowLocator>>,
2178 ) -> Result<(), StorageError> {
2179 if self.indices.iter().any(|i| i.name == name) {
2180 return Err(StorageError::DuplicateIndex { name });
2181 }
2182 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2183 StorageError::ColumnNotFound {
2184 column: column_name.into(),
2185 }
2186 })?;
2187 let mut idx = Index::new_gin_fulltext(name, column_position);
2188 idx.kind = IndexKind::GinFulltext(map);
2189 self.indices.push(idx);
2190 Ok(())
2191 }
2192
2193 /// v5.1: register cold-tier locators on a `BTree` index. Used
2194 /// after [`Catalog::load_segment_bytes`] to wire every cold-
2195 /// tier row's PK back to its segment so
2196 /// [`Catalog::lookup_by_pk`] can resolve it. Each call
2197 /// appends to the index — keys that already have hot or cold
2198 /// locators keep them. Returns the number of locators
2199 /// registered.
2200 ///
2201 /// Pre-v5.2 (freezer) this is the only path that adds Cold
2202 /// variants to a PB; post-freezer the background freezer
2203 /// thread produces these as a batch under the engine write
2204 /// lock and this API becomes its in-memory primitive.
2205 ///
2206 /// Errors if `index_name` doesn't exist or names an NSW graph
2207 /// (NSW indices don't carry per-key row locators — they're
2208 /// vector-search structures).
2209 pub fn register_cold_locators<I>(
2210 &mut self,
2211 index_name: &str,
2212 locators: I,
2213 ) -> Result<usize, StorageError>
2214 where
2215 I: IntoIterator<Item = (IndexKey, RowLocator)>,
2216 {
2217 let idx = self
2218 .indices
2219 .iter_mut()
2220 .find(|i| i.name == index_name)
2221 .ok_or_else(|| StorageError::Corrupt(format!("index {index_name:?} not found")))?;
2222 let map = match &mut idx.kind {
2223 IndexKind::BTree(map) => map,
2224 IndexKind::Nsw(_)
2225 | IndexKind::Brin { .. }
2226 | IndexKind::Gin(_)
2227 | IndexKind::GinTrgm(_)
2228 | IndexKind::GinFulltext(_) => {
2229 return Err(StorageError::Corrupt(format!(
2230 "index {index_name:?} is not BTree; cold locators apply only to BTree indices"
2231 )));
2232 }
2233 };
2234 let mut count = 0usize;
2235 for (key, locator) in locators {
2236 let mut entries = map.get(&key).cloned().unwrap_or_default();
2237 entries.push(locator);
2238 map.insert_mut(key, entries);
2239 count += 1;
2240 }
2241 Ok(count)
2242 }
2243
2244 /// v7.12.3 — GIN-side parallel to [`Self::register_cold_locators`].
2245 /// Re-attaches `word → cold RowLocator` posting-list entries after
2246 /// the from-rows rebuild loop. Errors when the index doesn't
2247 /// exist or isn't a GIN. Both tsvector-GIN and trigram-GIN
2248 /// variants share posting-list shape (`String → Vec<RowLocator>`),
2249 /// so this helper accepts either.
2250 pub fn register_gin_cold_locators<I>(
2251 &mut self,
2252 index_name: &str,
2253 locators: I,
2254 ) -> Result<usize, StorageError>
2255 where
2256 I: IntoIterator<Item = (String, RowLocator)>,
2257 {
2258 let idx = self
2259 .indices
2260 .iter_mut()
2261 .find(|i| i.name == index_name)
2262 .ok_or_else(|| StorageError::Corrupt(format!("index {index_name:?} not found")))?;
2263 let map = match &mut idx.kind {
2264 // v7.17.0 Phase 2.2 — fulltext-GIN posting lists are
2265 // shape-compatible with tsvector / trigram GINs, so
2266 // cold-locator re-attach handles all three.
2267 IndexKind::Gin(map) | IndexKind::GinTrgm(map) | IndexKind::GinFulltext(map) => map,
2268 IndexKind::BTree(_) | IndexKind::Nsw(_) | IndexKind::Brin { .. } => {
2269 return Err(StorageError::Corrupt(format!(
2270 "register_gin_cold_locators: index {index_name:?} is not GIN"
2271 )));
2272 }
2273 };
2274 let mut count = 0usize;
2275 for (word, locator) in locators {
2276 let mut entries = map.get(&word).cloned().unwrap_or_default();
2277 entries.push(locator);
2278 map.insert_mut(word, entries);
2279 count += 1;
2280 }
2281 Ok(count)
2282 }
2283
2284 /// v5.2.3: remove every `Cold` locator currently registered on
2285 /// `index_name` under the given `key`. `Hot` locators for the
2286 /// same key are left in place — useful when a row has just been
2287 /// promoted hot-side and the caller wants the old Cold pointer
2288 /// retired without losing the new hot entry.
2289 ///
2290 /// Returns the number of cold locators removed (0 when the key
2291 /// has only hot entries or the key isn't present at all).
2292 /// Errors when the index doesn't exist or isn't a `BTree`.
2293 pub fn remove_cold_locators_for_key(
2294 &mut self,
2295 index_name: &str,
2296 key: &IndexKey,
2297 ) -> Result<usize, StorageError> {
2298 let idx = self
2299 .indices
2300 .iter_mut()
2301 .find(|i| i.name == index_name)
2302 .ok_or_else(|| {
2303 StorageError::Corrupt(format!(
2304 "remove_cold_locators_for_key: index {index_name:?} not found"
2305 ))
2306 })?;
2307 let map = match &mut idx.kind {
2308 IndexKind::BTree(map) => map,
2309 IndexKind::Nsw(_)
2310 | IndexKind::Brin { .. }
2311 | IndexKind::Gin(_)
2312 | IndexKind::GinTrgm(_)
2313 | IndexKind::GinFulltext(_) => {
2314 return Err(StorageError::Corrupt(format!(
2315 "remove_cold_locators_for_key: index {index_name:?} is not BTree; \
2316 cold locators apply only to BTree indices"
2317 )));
2318 }
2319 };
2320 let Some(entries) = map.get(key) else {
2321 return Ok(0);
2322 };
2323 let mut kept: Vec<RowLocator> =
2324 entries.iter().copied().filter(RowLocator::is_hot).collect();
2325 let removed = entries.len() - kept.len();
2326 if removed == 0 {
2327 return Ok(0);
2328 }
2329 kept.shrink_to_fit();
2330 // PersistentBTreeMap has no remove API in v5.2; when every
2331 // locator for `key` was Cold, the key keeps an empty Vec
2332 // entry. `Index::lookup_eq` already treats `Some(&[])` and
2333 // `None` as the same empty slice (via `Vec::as_slice`), so
2334 // callers can't distinguish the two. The space cost is one
2335 // empty Vec per shadowed-then-promoted key — bounded and
2336 // recoverable when the future compaction job lands.
2337 map.insert_mut(key.clone(), kept);
2338 Ok(removed)
2339 }
2340
2341 /// v7.13.0 — append a new column to the schema and back-fill
2342 /// every existing row with `fill_value`. Used by the engine's
2343 /// `ALTER TABLE t ADD COLUMN …` handler (mailrs round-5 G1).
2344 /// Indices on existing columns keep working — column positions
2345 /// don't shift since the new column lands at the end — so no
2346 /// index rebuild is needed.
2347 pub fn add_column(&mut self, col: ColumnSchema, fill_value: Value) {
2348 self.schema.columns.push(col);
2349 let mut new_rows: PersistentVec<Row> = PersistentVec::new();
2350 for row in self.rows.iter() {
2351 let mut values = row.values.clone();
2352 values.push(fill_value.clone());
2353 new_rows.push_mut(Row::new(values));
2354 }
2355 self.rows = new_rows;
2356 }
2357
2358 /// v7.15.0 — replace the partial-index predicate source on
2359 /// the index at slot `idx`. Used by `ALTER TABLE … RENAME
2360 /// COLUMN` after the engine rewrites column-identifier
2361 /// references in the predicate source text. Pure metadata
2362 /// edit; index rows are unaffected (they're keyed by
2363 /// column position, not predicate text).
2364 pub fn set_partial_predicate(&mut self, idx: usize, pred: Option<String>) {
2365 debug_assert!(idx < self.indices.len());
2366 self.indices[idx].partial_predicate = pred;
2367 }
2368
2369 /// v7.15.0 — rename the column at `col_pos` to `new_name`.
2370 /// The on-disk row encoding is positional, so no row rewrite
2371 /// is needed; only the schema's column name changes. Indices,
2372 /// UCs, FKs all key off column positions and are unaffected.
2373 /// Source-text references that hold the column name (CHECK
2374 /// predicates, partial-index predicates, runtime DEFAULT
2375 /// expressions, trigger `UPDATE OF` lists) are rewritten by
2376 /// the engine before this helper is called — the storage
2377 /// layer doesn't depend on `spg-sql` and so can't re-parse the
2378 /// predicate sources itself.
2379 pub fn rename_column(&mut self, col_pos: usize, new_name: &str) {
2380 debug_assert!(col_pos < self.schema.columns.len());
2381 self.schema.columns[col_pos].name = new_name.to_string();
2382 }
2383
2384 /// v7.13.3 — drop the column at `col_pos`. Removes the entry
2385 /// from the schema, the value from every row, any index that
2386 /// references the column (pure drop, not shift), and shifts
2387 /// every remaining index/UC/FK column position that pointed
2388 /// past `col_pos` down by one. Used by `ALTER TABLE t DROP
2389 /// COLUMN <c>` (mailrs round-7 S8). FK dependents on this
2390 /// column must already have been removed by the caller (CASCADE
2391 /// path); the helper assumes only same-column index removal is
2392 /// needed.
2393 pub fn drop_column(&mut self, col_pos: usize) {
2394 debug_assert!(col_pos < self.schema.columns.len());
2395 // Strip the column from the schema.
2396 self.schema.columns.remove(col_pos);
2397 // Rewrite every row to omit the cell at col_pos.
2398 let mut new_rows: PersistentVec<Row> = PersistentVec::new();
2399 for row in self.rows.iter() {
2400 let mut values = row.values.clone();
2401 if col_pos < values.len() {
2402 values.remove(col_pos);
2403 }
2404 new_rows.push_mut(Row::new(values));
2405 }
2406 self.rows = new_rows;
2407 // Drop indices on the column outright; shift the rest.
2408 self.indices.retain(|idx| idx.column_position != col_pos);
2409 for idx in &mut self.indices {
2410 if idx.column_position > col_pos {
2411 idx.column_position -= 1;
2412 }
2413 // Same shift for any included-columns reference.
2414 for inc in &mut idx.included_columns {
2415 if *inc > col_pos {
2416 *inc -= 1;
2417 }
2418 }
2419 }
2420 // Shift uniqueness-constraint column positions (and drop
2421 // entries that lose all columns, though that shouldn't
2422 // happen in practice — caller has already CASCADE-removed
2423 // FKs and there's no general CASCADE for UCs).
2424 let mut surviving_ucs: Vec<UniquenessConstraint> = Vec::new();
2425 for mut uc in core::mem::take(&mut self.schema.uniqueness_constraints) {
2426 uc.columns.retain(|&c| c != col_pos);
2427 if uc.columns.is_empty() {
2428 continue;
2429 }
2430 for c in &mut uc.columns {
2431 if *c > col_pos {
2432 *c -= 1;
2433 }
2434 }
2435 surviving_ucs.push(uc);
2436 }
2437 self.schema.uniqueness_constraints = surviving_ucs;
2438 // Shift FK local_columns (parent-pointing column positions
2439 // are off-table and untouched).
2440 for fk in &mut self.schema.foreign_keys {
2441 for c in &mut fk.local_columns {
2442 if *c > col_pos {
2443 *c -= 1;
2444 }
2445 }
2446 }
2447 // Rebuild remaining indices' payload — the column-position
2448 // shift means existing IndexKey entries are still keyed by
2449 // the same column data but the position numbers changed;
2450 // existing key→locator maps stay valid because they're
2451 // keyed by Value not position. The rebuild is conservative
2452 // — same pattern delete_rows uses post-mutation.
2453 self.rebuild_indices();
2454 }
2455
2456 /// v4.4: delete the rows at the given positions in one pass.
2457 /// `positions` must be unique; ordering doesn't matter. Indices
2458 /// are rebuilt from scratch (cheaper than tracking incremental
2459 /// shifts across both B-tree and NSW). Returns the number of
2460 /// rows removed.
2461 /// v7.17.0 Phase 1.3 — wipe every row. Used by REFRESH
2462 /// MATERIALIZED VIEW; same effect as `delete_rows((0..N).into())`
2463 /// but skips the per-position bookkeeping for the all-removed
2464 /// fast path. Indices are rebuilt (empty).
2465 pub fn truncate(&mut self) {
2466 self.rows = PersistentVec::new();
2467 self.hot_bytes = 0;
2468 self.rebuild_indices();
2469 }
2470
2471 pub fn delete_rows(&mut self, positions: &[usize]) -> usize {
2472 if positions.is_empty() {
2473 return 0;
2474 }
2475 // Mark positions; v4.39: PV has no in-place retain, so we rebuild
2476 // a fresh PV by pushing the survivors. Still O(n log₃₂ n); the
2477 // structural-sharing win shows up at `Catalog::clone()`, not here.
2478 let mut to_remove = alloc::vec![false; self.rows.len()];
2479 let mut removed = 0;
2480 for &p in positions {
2481 if p < to_remove.len() && !to_remove[p] {
2482 to_remove[p] = true;
2483 removed += 1;
2484 }
2485 }
2486 let mut new_rows: PersistentVec<Row> = PersistentVec::new();
2487 let mut removed_bytes: u64 = 0;
2488 for (i, row) in self.rows.iter().enumerate() {
2489 if to_remove[i] {
2490 removed_bytes =
2491 removed_bytes.saturating_add(row_body_encoded_len(row, &self.schema) as u64);
2492 } else {
2493 new_rows.push_mut(row.clone());
2494 }
2495 }
2496 self.rows = new_rows;
2497 self.hot_bytes = self.hot_bytes.saturating_sub(removed_bytes);
2498 self.rebuild_indices();
2499 removed
2500 }
2501
2502 /// v4.4: replace the row at `position` with `new_values` (must
2503 /// match the schema arity + types). Indices are rebuilt for
2504 /// correctness — the affected column might be indexed and its
2505 /// key may have shifted, and a NSW node's vector may have
2506 /// changed, both of which need fresh state.
2507 pub fn update_row(
2508 &mut self,
2509 position: usize,
2510 new_values: Vec<Value>,
2511 ) -> Result<(), StorageError> {
2512 if position >= self.rows.len() {
2513 return Err(StorageError::Corrupt(alloc::format!(
2514 "update_row: position {position} out of bounds (rows={})",
2515 self.rows.len()
2516 )));
2517 }
2518 if new_values.len() != self.schema.columns.len() {
2519 return Err(StorageError::ArityMismatch {
2520 expected: self.schema.columns.len(),
2521 actual: new_values.len(),
2522 });
2523 }
2524 // Reuse the per-cell type-compat validation that `insert`
2525 // applies. The body below mirrors that check intentionally —
2526 // factoring it would be more code than the duplication.
2527 for (i, (val, col)) in new_values.iter().zip(&self.schema.columns).enumerate() {
2528 if val.is_null() {
2529 if !col.nullable {
2530 return Err(StorageError::NullInNotNull {
2531 column: col.name.clone(),
2532 });
2533 }
2534 continue;
2535 }
2536 let actual = val.data_type().expect("non-null");
2537 let compatible = actual == col.ty
2538 || matches!(
2539 (actual, col.ty),
2540 (
2541 DataType::Text,
2542 DataType::Varchar(_) | DataType::Char(_) | DataType::Json | DataType::Jsonb
2543 ) | (DataType::Json | DataType::Jsonb, DataType::Text)
2544 | (DataType::Json, DataType::Jsonb)
2545 | (DataType::Jsonb, DataType::Json)
2546 | (DataType::Timestamp, DataType::Timestamptz)
2547 | (DataType::Timestamptz, DataType::Timestamp)
2548 )
2549 || matches!(
2550 (actual, col.ty),
2551 (
2552 DataType::Numeric { scale: a, .. },
2553 DataType::Numeric { scale: b, .. },
2554 ) if a == b
2555 );
2556 if !compatible {
2557 return Err(StorageError::TypeMismatch {
2558 column: col.name.clone(),
2559 expected: col.ty,
2560 actual,
2561 position: i,
2562 });
2563 }
2564 }
2565 let old_row = self
2566 .rows
2567 .get(position)
2568 .expect("position bounds-checked above");
2569 let old_bytes = row_body_encoded_len(old_row, &self.schema) as u64;
2570 let new_row = Row::new(new_values);
2571 let new_bytes = row_body_encoded_len(&new_row, &self.schema) as u64;
2572 self.rows = self
2573 .rows
2574 .set(position, new_row)
2575 .expect("position bounds-checked above");
2576 self.hot_bytes = self
2577 .hot_bytes
2578 .saturating_sub(old_bytes)
2579 .saturating_add(new_bytes);
2580 self.rebuild_indices();
2581 Ok(())
2582 }
2583
2584 /// v4.4 helper used by `delete_rows` / `update_row`: discard all
2585 /// index payloads and rebuild from `self.rows`. Cheap enough
2586 /// for typical SPG scale (catalogs in the docker-compose
2587 /// deployment shape are small); the alternative — incremental
2588 /// shift bookkeeping across B-tree + NSW — would be far more
2589 /// invasive than the savings justify.
2590 fn rebuild_indices(&mut self) {
2591 // v5.2.3: capture every `Cold` locator on every BTree index
2592 // before the rebuild, so the from-rows re-emission below
2593 // (which only produces `Hot` locators) doesn't drop cold-
2594 // tier entries on keys unrelated to the row that changed.
2595 // Pre-v5.2.3 this was a `freeze_oldest_to_cold` worry only
2596 // and the freezer did its own capture-then-reregister; v5.2.3
2597 // promotes that pattern into the base helper because UPDATE
2598 // / DELETE now run rebuild_indices on tables with cold rows.
2599 let preserved_cold: Vec<(String, Vec<(IndexKey, RowLocator)>)> = self
2600 .indices
2601 .iter()
2602 .filter_map(|idx| match &idx.kind {
2603 IndexKind::BTree(map) => {
2604 let cold: Vec<(IndexKey, RowLocator)> = map
2605 .iter()
2606 .flat_map(|(k, locs)| {
2607 locs.iter()
2608 .filter(|l| l.is_cold())
2609 .copied()
2610 .map(move |l| (k.clone(), l))
2611 })
2612 .collect();
2613 if cold.is_empty() {
2614 None
2615 } else {
2616 Some((idx.name.clone(), cold))
2617 }
2618 }
2619 // BRIN / NSW carry no key→locator map. GIN handles
2620 // its own cold preservation below in `preserved_gin_cold`.
2621 IndexKind::Nsw(_)
2622 | IndexKind::Brin { .. }
2623 | IndexKind::Gin(_)
2624 | IndexKind::GinTrgm(_)
2625 | IndexKind::GinFulltext(_) => None,
2626 })
2627 .collect();
2628
2629 // v7.12.3 — same cold-preservation pattern for GIN's
2630 // `word → Vec<RowLocator>` posting lists. Parallel to the
2631 // BTree pass above (different key type so a separate vec is
2632 // cleaner than a generic merge). v7.15.0: trigram-GIN
2633 // (`gin_trgm_ops`) shares the same posting-list shape, so
2634 // one pass handles both — the `RebuildKind` carries the
2635 // kind tag to drive resurrection.
2636 let preserved_gin_cold: Vec<(String, Vec<(String, RowLocator)>)> = self
2637 .indices
2638 .iter()
2639 .filter_map(|idx| match &idx.kind {
2640 // v7.17.0 Phase 2.2 — fulltext-GIN posting lists
2641 // share the `String → Vec<RowLocator>` shape, so
2642 // cold preservation handles all three GIN flavours
2643 // in one pass.
2644 IndexKind::Gin(map) | IndexKind::GinTrgm(map) | IndexKind::GinFulltext(map) => {
2645 let cold: Vec<(String, RowLocator)> = map
2646 .iter()
2647 .flat_map(|(w, locs)| {
2648 locs.iter()
2649 .filter(|l| l.is_cold())
2650 .copied()
2651 .map(move |l| (w.clone(), l))
2652 })
2653 .collect();
2654 if cold.is_empty() {
2655 None
2656 } else {
2657 Some((idx.name.clone(), cold))
2658 }
2659 }
2660 IndexKind::BTree(_) | IndexKind::Nsw(_) | IndexKind::Brin { .. } => None,
2661 })
2662 .collect();
2663
2664 // v6.7.1 — descriptor needs to capture index kind so the
2665 // rebuild loop can resurrect BTree / NSW / BRIN / GIN exactly
2666 // as they were. (NSW carries m; BRIN carries the column type
2667 // snapshot; BTree / GIN need no extra payload.)
2668 #[derive(Clone)]
2669 enum RebuildKind {
2670 BTree,
2671 Nsw(usize),
2672 Brin(DataType),
2673 Gin,
2674 GinTrgm,
2675 GinFulltext,
2676 }
2677 let descriptors: Vec<(String, usize, RebuildKind)> = self
2678 .indices
2679 .iter()
2680 .map(|idx| {
2681 let kind = match &idx.kind {
2682 IndexKind::Nsw(g) => RebuildKind::Nsw(g.m),
2683 IndexKind::Brin { column_type } => RebuildKind::Brin(*column_type),
2684 IndexKind::BTree(_) => RebuildKind::BTree,
2685 IndexKind::Gin(_) => RebuildKind::Gin,
2686 IndexKind::GinTrgm(_) => RebuildKind::GinTrgm,
2687 IndexKind::GinFulltext(_) => RebuildKind::GinFulltext,
2688 };
2689 (idx.name.clone(), idx.column_position, kind)
2690 })
2691 .collect();
2692 self.indices.clear();
2693 for (name, column_position, rebuild_kind) in descriptors {
2694 match rebuild_kind {
2695 RebuildKind::Nsw(m) => {
2696 let idx = Index::new_nsw(name, column_position, m);
2697 self.indices.push(idx);
2698 let idx_pos = self.indices.len() - 1;
2699 let row_indices: Vec<usize> = (0..self.rows.len()).collect();
2700 for row_idx in row_indices {
2701 nsw_insert_at(self, idx_pos, row_idx);
2702 }
2703 }
2704 RebuildKind::Brin(column_type) => {
2705 // BRIN has no in-memory rebuild — the summaries
2706 // live in cold segments which freeze emits.
2707 self.indices
2708 .push(Index::new_brin(name, column_position, column_type));
2709 }
2710 RebuildKind::BTree => {
2711 let mut idx = Index::new_btree(name, column_position);
2712 if let IndexKind::BTree(map) = &mut idx.kind {
2713 for (i, row) in self.rows.iter().enumerate() {
2714 if let Some(key) = IndexKey::from_value(&row.values[column_position]) {
2715 let mut entries = map.get(&key).cloned().unwrap_or_default();
2716 entries.push(RowLocator::Hot(i));
2717 map.insert_mut(key, entries);
2718 }
2719 }
2720 }
2721 self.indices.push(idx);
2722 }
2723 RebuildKind::Gin => {
2724 let mut idx = Index::new_gin(name, column_position);
2725 if let IndexKind::Gin(map) = &mut idx.kind {
2726 for (i, row) in self.rows.iter().enumerate() {
2727 if let Value::TsVector(lexemes) = &row.values[column_position] {
2728 for lex in lexemes {
2729 let mut entries =
2730 map.get(&lex.word).cloned().unwrap_or_default();
2731 entries.push(RowLocator::Hot(i));
2732 map.insert_mut(lex.word.clone(), entries);
2733 }
2734 }
2735 }
2736 }
2737 self.indices.push(idx);
2738 }
2739 RebuildKind::GinTrgm => {
2740 let mut idx = Index::new_gin_trgm(name, column_position);
2741 if let IndexKind::GinTrgm(map) = &mut idx.kind {
2742 for (i, row) in self.rows.iter().enumerate() {
2743 if let Value::Text(s) = &row.values[column_position] {
2744 for tri in trgm::extract_trigrams(s) {
2745 let mut entries = map.get(&tri).cloned().unwrap_or_default();
2746 entries.push(RowLocator::Hot(i));
2747 map.insert_mut(tri, entries);
2748 }
2749 }
2750 }
2751 }
2752 self.indices.push(idx);
2753 }
2754 RebuildKind::GinFulltext => {
2755 // v7.17.0 Phase 2.2 — re-derive the lexeme
2756 // posting list from each TEXT/VARCHAR cell.
2757 // Mirrors the GinTrgm rebuild shape but
2758 // tokenises via `fts_simple::simple_lex`
2759 // (same rule as `to_tsvector('simple')`).
2760 let mut idx = Index::new_gin_fulltext(name, column_position);
2761 if let IndexKind::GinFulltext(map) = &mut idx.kind {
2762 for (i, row) in self.rows.iter().enumerate() {
2763 if let Value::Text(s) = &row.values[column_position] {
2764 for lex in fts_simple::simple_lex(s) {
2765 let mut entries = map.get(&lex).cloned().unwrap_or_default();
2766 entries.push(RowLocator::Hot(i));
2767 map.insert_mut(lex, entries);
2768 }
2769 }
2770 }
2771 }
2772 self.indices.push(idx);
2773 }
2774 }
2775 }
2776
2777 // Re-attach preserved cold locators after the from-rows
2778 // rebuild. `register_cold_locators` handles the per-key
2779 // entries-vec append; no key collisions arise because the
2780 // rebuild loop above produced only Hot locators.
2781 for (idx_name, locators) in preserved_cold {
2782 // Errors here would only fire if the index disappeared
2783 // between snapshot and rebuild, which can't happen
2784 // because the rebuild restores the same descriptor set.
2785 let _ = self.register_cold_locators(&idx_name, locators);
2786 }
2787 // v7.12.3 — same for GIN posting-list cold locators.
2788 for (idx_name, locators) in preserved_gin_cold {
2789 let _ = self.register_gin_cold_locators(&idx_name, locators);
2790 }
2791 }
2792
2793 fn add_nsw_index_inner(
2794 &mut self,
2795 name: String,
2796 column_name: &str,
2797 m: usize,
2798 restore: Option<NswGraph>,
2799 ) -> Result<(), StorageError> {
2800 if self.indices.iter().any(|i| i.name == name) {
2801 return Err(StorageError::DuplicateIndex { name });
2802 }
2803 let column_position = self.schema.column_position(column_name).ok_or_else(|| {
2804 StorageError::ColumnNotFound {
2805 column: column_name.into(),
2806 }
2807 })?;
2808 if !matches!(
2809 self.schema.columns[column_position].ty,
2810 DataType::Vector { .. }
2811 ) {
2812 return Err(StorageError::TypeMismatch {
2813 column: column_name.into(),
2814 expected: DataType::Vector {
2815 dim: 0,
2816 encoding: VecEncoding::F32,
2817 },
2818 actual: self.schema.columns[column_position].ty,
2819 position: column_position,
2820 });
2821 }
2822 if let Some(graph) = restore {
2823 self.indices.push(Index {
2824 name,
2825 column_position,
2826 kind: IndexKind::Nsw(graph),
2827 included_columns: Vec::new(),
2828 partial_predicate: None,
2829 expression: None,
2830 is_unique: false,
2831 extra_column_positions: Vec::new(),
2832 });
2833 return Ok(());
2834 }
2835 let idx = Index::new_nsw(name, column_position, m);
2836 self.indices.push(idx);
2837 let idx_pos = self.indices.len() - 1;
2838 // Bulk-build by walking the existing rows in order — each insert
2839 // sees the partial graph and links into it.
2840 let row_indices: Vec<usize> = (0..self.rows.len()).collect();
2841 for row_idx in row_indices {
2842 nsw_insert_at(self, idx_pos, row_idx);
2843 }
2844 Ok(())
2845 }
2846}
2847
2848/// v6.0.4 — re-encode a single cell to the target `VecEncoding`.
2849/// Used by `Table::rebuild_nsw_index` when ALTER INDEX REBUILD
2850/// includes the optional `WITH (encoding = …)` clause. Round-trip
2851/// goes through f32: `current → Vec<f32> → target`, leaving NULL
2852/// cells untouched. Returns `Unsupported` on a non-vector cell —
2853/// the caller should have rejected the schema before reaching this.
2854fn recode_vector_cell(cell: Value, target: VecEncoding) -> Result<Value, StorageError> {
2855 if matches!(cell, Value::Null) {
2856 return Ok(cell);
2857 }
2858 // Step 1 — extract the f32 representation of the source cell.
2859 let as_f32: Vec<f32> = match &cell {
2860 Value::Vector(v) => v.clone(),
2861 Value::Sq8Vector(q) => quantize::dequantize(q),
2862 Value::HalfVector(h) => h.to_f32_vec(),
2863 other => {
2864 return Err(StorageError::Unsupported(format!(
2865 "ALTER INDEX REBUILD: cannot recode non-vector cell {:?}",
2866 other.data_type()
2867 )));
2868 }
2869 };
2870 // Step 2 — encode into the target shape. `F32` is the identity
2871 // path (saves one alloc round-trip when the source is already
2872 // F32 — but `Value::Vector(as_f32)` is the right answer
2873 // regardless).
2874 Ok(match target {
2875 VecEncoding::F32 => Value::Vector(as_f32),
2876 VecEncoding::Sq8 => Value::Sq8Vector(quantize::quantize(&as_f32)),
2877 VecEncoding::F16 => Value::HalfVector(halfvec::HalfVector::from_f32_slice(&as_f32)),
2878 })
2879}
2880
2881/// Insert one row into the HNSW graph held by index slot `idx_pos`.
2882/// No-op when the row's value at the indexed column isn't a vector.
2883/// v6.0.1: handles `Value::Sq8Vector` by dequantising into an f32
2884/// "query" surface — the existing greedy + beam-search machinery
2885/// then uses `cell_to_query_metric_distance` to route every
2886/// distance call through the cell's actual encoding.
2887fn nsw_insert_at(table: &mut Table, idx_pos: usize, new_row_idx: usize) {
2888 let col_pos = table.indices[idx_pos].column_position;
2889 let cell_dim: Option<usize> = match &table.rows[new_row_idx].values[col_pos] {
2890 Value::Vector(v) => Some(v.len()),
2891 Value::Sq8Vector(q) => Some(q.bytes.len()),
2892 Value::HalfVector(h) => Some(h.dim()),
2893 _ => None,
2894 };
2895 let Some(dim) = cell_dim else {
2896 // Even non-vector rows occupy a level slot so per-node Vec
2897 // lengths stay aligned with `table.rows.len()`.
2898 ensure_node_slot(table, idx_pos, new_row_idx, 0);
2899 return;
2900 };
2901 if dim == 0 {
2902 ensure_node_slot(table, idx_pos, new_row_idx, 0);
2903 return;
2904 }
2905 let level = nsw_assign_level(new_row_idx);
2906 ensure_node_slot(table, idx_pos, new_row_idx, level);
2907 let (entry, entry_level, m) = match &table.indices[idx_pos].kind {
2908 IndexKind::Nsw(g) => (g.entry, g.entry_level, g.m),
2909 IndexKind::BTree(_)
2910 | IndexKind::Brin { .. }
2911 | IndexKind::Gin(_)
2912 | IndexKind::GinTrgm(_)
2913 | IndexKind::GinFulltext(_) => {
2914 unreachable!("nsw_insert_at on a non-NSW index")
2915 }
2916 };
2917 // First node ever — declare it the entry (it gets its own level).
2918 if entry.is_none() {
2919 if let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind {
2920 g.entry = Some(new_row_idx);
2921 g.entry_level = level;
2922 *g.levels
2923 .get_mut(new_row_idx)
2924 .expect("levels slot padded by ensure_node_slot") = level;
2925 }
2926 return;
2927 }
2928 // Set the node's recorded level.
2929 if let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind {
2930 *g.levels
2931 .get_mut(new_row_idx)
2932 .expect("levels slot padded by ensure_node_slot") = level;
2933 }
2934 let query = match &table.rows[new_row_idx].values[col_pos] {
2935 Value::Vector(v) => v.clone(),
2936 // v6.0.1: dequantise the inserted SQ8 cell into an f32 query
2937 // surface so the existing greedy / beam machinery can route
2938 // distances through `cell_to_query_metric_distance`. The
2939 // small dequantisation error is what the recall@10 ≥ 0.95
2940 // envelope already accounts for (V6_DESIGN deliberation #3).
2941 Value::Sq8Vector(q) => quantize::dequantize(q),
2942 // v6.0.3: halfvec dequant is bit-exact at the storage layer,
2943 // so the inserted query is a faithful representation.
2944 Value::HalfVector(h) => h.to_f32_vec(),
2945 _ => return,
2946 };
2947 // Phase 1: greedy descend from `entry` down to `level + 1`, keeping
2948 // exactly one current best so the next layer starts from it.
2949 let mut current = entry.expect("entry was Some above");
2950 let mut current_d = vec_l2_sq(table, col_pos, current, &query);
2951 if entry_level > level {
2952 for layer in (level + 1..=entry_level).rev() {
2953 (current, current_d) =
2954 greedy_layer_walk(table, idx_pos, layer, current, current_d, &query);
2955 }
2956 }
2957 // Phase 2: from `min(level, entry_level)` down to 0, beam-search
2958 // `ef_construction` candidates, run the HNSW §4 heuristic neighbour
2959 // selection over them, and connect bidirectionally.
2960 let top = level.min(entry_level);
2961 let ef = (m * 2).max(8);
2962 for layer in (0..=top).rev() {
2963 let cap = if layer == 0 { m * 2 } else { m };
2964 let mut candidates = layer_beam_search(
2965 table,
2966 idx_pos,
2967 layer,
2968 current,
2969 current_d,
2970 &query,
2971 ef,
2972 NswMetric::L2,
2973 );
2974 candidates.retain(|&(_, n)| n != new_row_idx);
2975 // Take the closest as the entry for the next layer down — done
2976 // before heuristic narrowing because the heuristic can reorder.
2977 if let Some(&(d, n)) = candidates.first() {
2978 current = n;
2979 current_d = d;
2980 }
2981 let peers = select_neighbours_heuristic(&candidates, cap, table, col_pos);
2982 connect_at_layer(table, idx_pos, layer, new_row_idx, &peers);
2983 }
2984 // Phase 3: if the new node climbed above the current entry, take
2985 // over as entry so future inserts/searches start from the new top.
2986 if level > entry_level
2987 && let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind
2988 {
2989 g.entry = Some(new_row_idx);
2990 g.entry_level = level;
2991 }
2992}
2993
2994/// Make sure `layers[*][new_row_idx]` and `levels[new_row_idx]` exist,
2995/// padding with empty/zero entries as needed. Also grows `layers` to
2996/// accommodate the node's top `level`.
2997fn ensure_node_slot(table: &mut Table, idx_pos: usize, new_row_idx: usize, level: u8) {
2998 let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind else {
2999 unreachable!("ensure_node_slot on a BTree index");
3000 };
3001 while g.layers.len() <= level as usize {
3002 g.layers.push(PersistentVec::new());
3003 }
3004 while g.levels.len() <= new_row_idx {
3005 g.levels.push_mut(0);
3006 }
3007 for layer_vec in &mut g.layers {
3008 while layer_vec.len() <= new_row_idx {
3009 layer_vec.push_mut(Vec::new());
3010 }
3011 }
3012}
3013
3014/// Single-step greedy walk on one layer: from `current` (with cached
3015/// distance `current_d`), inspect that node's neighbours at `layer` and
3016/// hop to the closest if it beats `current_d`. Repeat until no move
3017/// improves the distance. Cheap variant of beam-search used for the
3018/// "descend" phase that only needs one survivor per layer.
3019fn greedy_layer_walk(
3020 table: &Table,
3021 idx_pos: usize,
3022 layer: u8,
3023 mut current: usize,
3024 mut current_d: f32,
3025 query: &[f32],
3026) -> (usize, f32) {
3027 let g = match &table.indices[idx_pos].kind {
3028 IndexKind::Nsw(g) => g,
3029 IndexKind::BTree(_)
3030 | IndexKind::Brin { .. }
3031 | IndexKind::Gin(_)
3032 | IndexKind::GinTrgm(_)
3033 | IndexKind::GinFulltext(_) => {
3034 return (current, current_d);
3035 }
3036 };
3037 let col_pos = table.indices[idx_pos].column_position;
3038 loop {
3039 let neighbours: &[u32] = g
3040 .layers
3041 .get(layer as usize)
3042 .and_then(|layer_v| layer_v.get(current))
3043 .map_or(&[][..], Vec::as_slice);
3044 let mut best = current;
3045 let mut best_d = current_d;
3046 for &n in neighbours {
3047 let n = n as usize;
3048 let d = vec_l2_sq(table, col_pos, n, query);
3049 if d < best_d {
3050 best = n;
3051 best_d = d;
3052 }
3053 }
3054 if best == current {
3055 return (current, current_d);
3056 }
3057 current = best;
3058 current_d = best_d;
3059 }
3060}
3061
3062/// Beam search on one layer starting from `entry_node` with cached
3063/// `entry_d`. Returns the top `ef` candidates in ascending-distance
3064/// order. Caller picks the closest as the next layer's entry and / or
3065/// trims to M for connection.
3066///
3067/// v3.0.1: uses two `BinaryHeap`s (min-heap for the open frontier,
3068/// max-heap for the working top-`ef` results) and a `Vec<bool>` visited
3069/// bitmap, replacing the v2.x `Vec` + `partition_point` + `BTreeSet`
3070/// implementation. Same algorithm shape (HNSW search algorithm 2 from
3071/// the paper); the data-structure swap cuts per-visit cost from
3072/// `O(ef + log row_count)` to amortised `O(log ef)`.
3073#[allow(clippy::too_many_arguments)] // Beam search threads layer, entry, query, ef, metric — each is intrinsic. Bundling them into a config struct hides the call sites.
3074fn layer_beam_search(
3075 table: &Table,
3076 idx_pos: usize,
3077 layer: u8,
3078 entry_node: usize,
3079 entry_d: f32,
3080 query: &[f32],
3081 ef: usize,
3082 metric: NswMetric,
3083) -> Vec<(f32, usize)> {
3084 let g = match &table.indices[idx_pos].kind {
3085 IndexKind::Nsw(g) => g,
3086 IndexKind::BTree(_)
3087 | IndexKind::Brin { .. }
3088 | IndexKind::Gin(_)
3089 | IndexKind::GinTrgm(_)
3090 | IndexKind::GinFulltext(_) => return Vec::new(),
3091 };
3092 let col_pos = table.indices[idx_pos].column_position;
3093 let d0 = if matches!(metric, NswMetric::L2) {
3094 entry_d
3095 } else {
3096 cell_to_query_metric_distance(table, col_pos, entry_node, query, metric)
3097 };
3098 let row_count = table.rows.len();
3099 let mut visited: Vec<bool> = alloc::vec![false; row_count];
3100 if entry_node < row_count {
3101 visited[entry_node] = true;
3102 }
3103 // candidates: min-heap by distance (Closest wrapper) — frontier
3104 // results: max-heap by distance (Furthest wrapper) — top-ef working set
3105 let mut candidates: alloc::collections::BinaryHeap<NodeClosest> =
3106 alloc::collections::BinaryHeap::with_capacity(ef);
3107 let mut results: alloc::collections::BinaryHeap<NodeFurthest> =
3108 alloc::collections::BinaryHeap::with_capacity(ef);
3109 candidates.push(NodeClosest {
3110 dist: d0,
3111 node: entry_node,
3112 });
3113 results.push(NodeFurthest {
3114 dist: d0,
3115 node: entry_node,
3116 });
3117 while let Some(cur) = candidates.pop() {
3118 let worst = results.peek().map_or(f32::INFINITY, |c| c.dist);
3119 if cur.dist > worst && results.len() >= ef {
3120 break;
3121 }
3122 let neighbours: &[u32] = g
3123 .layers
3124 .get(layer as usize)
3125 .and_then(|layer_v| layer_v.get(cur.node))
3126 .map_or(&[][..], Vec::as_slice);
3127 for &n in neighbours {
3128 let n = n as usize;
3129 if n >= row_count || visited[n] {
3130 continue;
3131 }
3132 visited[n] = true;
3133 // v6.0.1: cell-aware distance — F32 cells take the
3134 // existing scalar metric, SQ8 cells route through
3135 // the asymmetric ADC variant for the same metric.
3136 let dn = cell_to_query_metric_distance(table, col_pos, n, query, metric);
3137 if !dn.is_finite() {
3138 continue;
3139 }
3140 let worst = results.peek().map_or(f32::INFINITY, |c| c.dist);
3141 if results.len() < ef || dn < worst {
3142 results.push(NodeFurthest { dist: dn, node: n });
3143 if results.len() > ef {
3144 results.pop();
3145 }
3146 candidates.push(NodeClosest { dist: dn, node: n });
3147 }
3148 }
3149 }
3150 // Drain results (max-heap order) and re-sort ascending so callers
3151 // can take `closest = result[0]` without flipping.
3152 let mut out: Vec<(f32, usize)> = results.into_iter().map(|c| (c.dist, c.node)).collect();
3153 out.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
3154 out
3155}
3156
3157/// Min-heap wrapper: smaller `dist` → higher priority in a `BinaryHeap`
3158/// (which is a max-heap), so we flip the comparison. NaN sorts last
3159/// (lowest priority) to keep the heap total-ordered.
3160#[derive(Debug, Clone, Copy)]
3161struct NodeClosest {
3162 dist: f32,
3163 node: usize,
3164}
3165impl PartialEq for NodeClosest {
3166 fn eq(&self, other: &Self) -> bool {
3167 self.dist == other.dist && self.node == other.node
3168 }
3169}
3170impl Eq for NodeClosest {}
3171impl PartialOrd for NodeClosest {
3172 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
3173 Some(self.cmp(other))
3174 }
3175}
3176impl Ord for NodeClosest {
3177 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
3178 // Reversed: smaller dist = greater priority.
3179 other
3180 .dist
3181 .partial_cmp(&self.dist)
3182 .unwrap_or(core::cmp::Ordering::Equal)
3183 }
3184}
3185
3186/// Max-heap wrapper: larger `dist` sits at the top so the worst result
3187/// can be evicted in O(log n) when a better candidate arrives.
3188#[derive(Debug, Clone, Copy)]
3189struct NodeFurthest {
3190 dist: f32,
3191 node: usize,
3192}
3193impl PartialEq for NodeFurthest {
3194 fn eq(&self, other: &Self) -> bool {
3195 self.dist == other.dist && self.node == other.node
3196 }
3197}
3198impl Eq for NodeFurthest {}
3199impl PartialOrd for NodeFurthest {
3200 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
3201 Some(self.cmp(other))
3202 }
3203}
3204impl Ord for NodeFurthest {
3205 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
3206 self.dist
3207 .partial_cmp(&other.dist)
3208 .unwrap_or(core::cmp::Ordering::Equal)
3209 }
3210}
3211
3212/// HNSW paper §4 algorithm 4: pick `m` neighbours from `candidates` so
3213/// that each chosen point isn't already covered by a closer chosen
3214/// point. Improves graph diversity → fewer hops needed at search time.
3215///
3216/// `candidates` arrives sorted ascending by distance-to-query. We walk
3217/// it in order, keeping a candidate only when no already-chosen point
3218/// is closer to it than the query is. Result is a vector of row
3219/// indices (length ≤ `m`).
3220fn select_neighbours_heuristic(
3221 candidates: &[(f32, usize)],
3222 m: usize,
3223 table: &Table,
3224 col_pos: usize,
3225) -> Vec<usize> {
3226 let mut chosen: Vec<usize> = Vec::with_capacity(m);
3227 for &(d_q, e) in candidates {
3228 if chosen.len() >= m {
3229 break;
3230 }
3231 // v6.0.1: works on either `Value::Vector` (F32) or
3232 // `Value::Sq8Vector` (Sq8) cells — `cell_l2_sq` dispatches
3233 // on encoding. A non-vector cell yields `f32::INFINITY`
3234 // which the `< d_q` test will never accept.
3235 if !matches!(
3236 table.rows.get(e).and_then(|r| r.values.get(col_pos)),
3237 Some(Value::Vector(_) | Value::Sq8Vector(_) | Value::HalfVector(_))
3238 ) {
3239 continue;
3240 }
3241 let mut covered = false;
3242 for &r in &chosen {
3243 // dist(e, r) measured in the same metric the topology was
3244 // built with (L2). If a chosen `r` is closer to `e` than
3245 // the query is, `r` already "covers" `e` for navigation.
3246 if cell_l2_sq(table, col_pos, e, r) < d_q {
3247 covered = true;
3248 break;
3249 }
3250 }
3251 if !covered {
3252 chosen.push(e);
3253 }
3254 }
3255 chosen
3256}
3257
3258/// Bidirectionally connect `new_row_idx` to each of `peers` at `layer`,
3259/// trimming each endpoint's adjacency to that layer's degree cap by
3260/// keeping only the closest neighbours.
3261fn connect_at_layer(
3262 table: &mut Table,
3263 idx_pos: usize,
3264 layer: u8,
3265 new_row_idx: usize,
3266 peers: &[usize],
3267) {
3268 let col_pos = table.indices[idx_pos].column_position;
3269 let cap = match &table.indices[idx_pos].kind {
3270 IndexKind::Nsw(g) => g.cap_for_layer(layer),
3271 IndexKind::BTree(_)
3272 | IndexKind::Brin { .. }
3273 | IndexKind::Gin(_)
3274 | IndexKind::GinTrgm(_)
3275 | IndexKind::GinFulltext(_) => return,
3276 };
3277 // v6.1.x: NSW adjacency stores neighbour row indices as u32 (4 B
3278 // each) rather than usize (8 B on 64-bit). Boundary casts here
3279 // assert the row count fits in u32 — the catalog already enforces
3280 // ≤ 4G rows per table, so the conversion can't lose data.
3281 let new_row_u32 = u32::try_from(new_row_idx).expect("row index fits in u32");
3282 if let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind {
3283 let layer_v = &mut g.layers[layer as usize];
3284 if let Some(slot) = layer_v.get_mut(new_row_idx) {
3285 *slot = peers
3286 .iter()
3287 .map(|&p| u32::try_from(p).expect("row index fits in u32"))
3288 .collect();
3289 }
3290 }
3291 for &peer in peers {
3292 // Skip peers whose indexed cell isn't a vector — same fence
3293 // as the F32 path; SQ8 cells flow through `cell_l2_sq`
3294 // below without dequantising.
3295 if !matches!(
3296 &table.rows[peer].values[col_pos],
3297 Value::Vector(_) | Value::Sq8Vector(_) | Value::HalfVector(_)
3298 ) {
3299 continue;
3300 }
3301 // 1. add the new node to peer's adjacency
3302 if let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind {
3303 let layer_v = &mut g.layers[layer as usize];
3304 if let Some(slot) = layer_v.get_mut(peer)
3305 && !slot.contains(&new_row_u32)
3306 {
3307 slot.push(new_row_u32);
3308 }
3309 }
3310 // 2. if peer is over budget, rebuild its adjacency with the
3311 // HNSW §4 heuristic — same diversity criterion as the
3312 // insert path so connectivity stays consistent.
3313 let needs_trim = match &table.indices[idx_pos].kind {
3314 IndexKind::Nsw(g) => g.layers[layer as usize][peer].len() > cap,
3315 IndexKind::BTree(_)
3316 | IndexKind::Brin { .. }
3317 | IndexKind::Gin(_)
3318 | IndexKind::GinTrgm(_)
3319 | IndexKind::GinFulltext(_) => false,
3320 };
3321 if needs_trim {
3322 let current_peers: Vec<usize> = match &table.indices[idx_pos].kind {
3323 IndexKind::Nsw(g) => g.layers[layer as usize][peer]
3324 .iter()
3325 .map(|&n| n as usize)
3326 .collect(),
3327 IndexKind::BTree(_)
3328 | IndexKind::Brin { .. }
3329 | IndexKind::Gin(_)
3330 | IndexKind::GinTrgm(_)
3331 | IndexKind::GinFulltext(_) => continue,
3332 };
3333 // Sort by distance from `peer`'s cell ascending so the
3334 // heuristic receives candidates closest-first. `cell_l2_sq`
3335 // dispatches on encoding so SQ8 columns trim using
3336 // symmetric ADC.
3337 let mut tagged: Vec<(f32, usize)> = current_peers
3338 .iter()
3339 .map(|&p| (cell_l2_sq(table, col_pos, peer, p), p))
3340 .collect();
3341 tagged.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
3342 let kept = select_neighbours_heuristic(&tagged, cap, table, col_pos);
3343 if let IndexKind::Nsw(g) = &mut table.indices[idx_pos].kind
3344 && let Some(slot) = g.layers[layer as usize].get_mut(peer)
3345 {
3346 *slot = kept
3347 .into_iter()
3348 .map(|p| u32::try_from(p).expect("row index fits in u32"))
3349 .collect();
3350 }
3351 }
3352 }
3353}
3354
3355/// Squared L2 distance from `query` (raw f32) to the cell at
3356/// `(row, col_pos)`. Dispatches on cell encoding: `Value::Vector`
3357/// (F32) uses `l2_distance_sq`; `Value::Sq8Vector` uses
3358/// `sq8_l2_distance_sq_asymmetric` (the v6.0.1 quantised path).
3359/// Returns `f32::INFINITY` for any non-vector cell so callers can
3360/// compare uniformly.
3361fn vec_l2_sq(table: &Table, col_pos: usize, row: usize, query: &[f32]) -> f32 {
3362 match table.rows.get(row).and_then(|r| r.values.get(col_pos)) {
3363 Some(Value::Vector(v)) if v.len() == query.len() => l2_distance_sq(v, query),
3364 Some(Value::Sq8Vector(q)) if q.bytes.len() == query.len() => {
3365 quantize::sq8_l2_distance_sq_asymmetric(q, query)
3366 }
3367 // v6.0.6: halfvec → fused NEON SIMD kernel; no Vec<f32>
3368 // allocation. v6.0.3 used `to_f32_vec()` + f32 NEON which
3369 // was correct but allocated per call (5× slower than F32).
3370 Some(Value::HalfVector(h)) if h.dim() == query.len() => {
3371 halfvec::half_l2_distance_sq_asymmetric(h, query)
3372 }
3373 _ => f32::INFINITY,
3374 }
3375}
3376
3377/// Squared L2 distance between two stored cells (no f32 query in
3378/// sight). Used during HNSW graph build — both endpoints are
3379/// rows already in the table, so symmetric ADC applies for SQ8
3380/// columns. Mixed-encoding cells within one column are a
3381/// schema-level impossibility (INSERT-time coercion enforces
3382/// uniform encoding), so the catch-all is an abort.
3383fn cell_l2_sq(table: &Table, col_pos: usize, row_a: usize, row_b: usize) -> f32 {
3384 let Some(cell_a) = table.rows.get(row_a).and_then(|r| r.values.get(col_pos)) else {
3385 return f32::INFINITY;
3386 };
3387 let Some(cell_b) = table.rows.get(row_b).and_then(|r| r.values.get(col_pos)) else {
3388 return f32::INFINITY;
3389 };
3390 match (cell_a, cell_b) {
3391 (Value::Vector(a), Value::Vector(b)) if a.len() == b.len() => l2_distance_sq(a, b),
3392 (Value::Sq8Vector(a), Value::Sq8Vector(b)) if a.bytes.len() == b.bytes.len() => {
3393 quantize::sq8_l2_distance_sq(a, b)
3394 }
3395 // v6.0.6: halfvec symmetric NEON — fused SIMD kernel that
3396 // loads both cells' raw u16 bits, expands to f32 lanes
3397 // inline, FMA-accumulates the squared diff. No Vec<f32>
3398 // allocation per call.
3399 (Value::HalfVector(a), Value::HalfVector(b)) if a.dim() == b.dim() => {
3400 halfvec::half_l2_distance_sq(a, b)
3401 }
3402 _ => f32::INFINITY,
3403 }
3404}
3405
3406/// kNN-search-time distance: stored cell → f32 query under the
3407/// caller's metric. Dispatches on cell encoding so SQ8 columns
3408/// take the ADC path with the right asymmetric variant. NaN /
3409/// dim-mismatch / non-vector → `f32::INFINITY`.
3410fn cell_to_query_metric_distance(
3411 table: &Table,
3412 col_pos: usize,
3413 row: usize,
3414 query: &[f32],
3415 metric: NswMetric,
3416) -> f32 {
3417 match table.rows.get(row).and_then(|r| r.values.get(col_pos)) {
3418 Some(Value::Vector(v)) if v.len() == query.len() => metric_distance(metric, v, query),
3419 Some(Value::Sq8Vector(q)) if q.bytes.len() == query.len() => match metric {
3420 NswMetric::L2 => quantize::sq8_l2_distance_sq_asymmetric(q, query),
3421 NswMetric::InnerProduct => quantize::sq8_inner_product_asymmetric(q, query),
3422 NswMetric::Cosine => quantize::sq8_cosine_distance_asymmetric(q, query),
3423 },
3424 // v6.0.6: halfvec dispatches by metric to fused NEON
3425 // kernels — no Vec<f32> allocation per call.
3426 Some(Value::HalfVector(h)) if h.dim() == query.len() => match metric {
3427 NswMetric::L2 => halfvec::half_l2_distance_sq_asymmetric(h, query),
3428 NswMetric::InnerProduct => halfvec::half_inner_product_asymmetric(h, query),
3429 NswMetric::Cosine => halfvec::half_cosine_distance_asymmetric(h, query),
3430 },
3431 _ => f32::INFINITY,
3432 }
3433}
3434
3435/// Distance metric used at NSW search time. The graph topology is
3436/// always built with `L2`; querying with `InnerProduct` / `Cosine`
3437/// reuses the same edges but ranks candidates by the chosen metric.
3438/// For the corpus-sized graphs this loses negligible recall vs
3439/// building separate per-metric graphs.
3440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3441pub enum NswMetric {
3442 /// Squared Euclidean — ranks "smaller = closer" (the sqrt is
3443 /// monotonic so we skip it for ordering).
3444 L2,
3445 /// Negated dot product, matching pgvector `<#>` convention so
3446 /// "smaller = more similar" holds across all three metrics.
3447 InnerProduct,
3448 /// Cosine distance `1 - cos(a, b)`. Zero-norm operand yields
3449 /// `f32::INFINITY` so it sorts last.
3450 Cosine,
3451}
3452
3453/// Multi-layer HNSW kNN search: greedy-descend from the entry to layer 0,
3454/// then beam-search there with the requested `ef` to return the top `k`
3455/// results under the caller-chosen metric. Topology was built with L2 —
3456/// upper-layer descent uses L2 as a coarse heuristic; final beam search
3457/// runs in the requested metric so rankings are correct for `<#>` / `<=>`.
3458fn nsw_search(
3459 table: &Table,
3460 idx_pos: usize,
3461 query: &[f32],
3462 k: usize,
3463 ef: usize,
3464 metric: NswMetric,
3465) -> Vec<(f32, usize)> {
3466 let (entry, entry_level) = match &table.indices[idx_pos].kind {
3467 IndexKind::Nsw(g) => (g.entry, g.entry_level),
3468 IndexKind::BTree(_)
3469 | IndexKind::Brin { .. }
3470 | IndexKind::Gin(_)
3471 | IndexKind::GinTrgm(_)
3472 | IndexKind::GinFulltext(_) => return Vec::new(),
3473 };
3474 let Some(entry) = entry else {
3475 return Vec::new();
3476 };
3477 let col_pos = table.indices[idx_pos].column_position;
3478 // v6.0.1 step 5: SQ8 columns over-fetch by `SQ8_RERANK_OVER_FETCH`
3479 // so the rerank pass below sees enough candidates to recover
3480 // recall after the ADC re-ordering. F32 + F16 columns skip the
3481 // over-fetch — F32 distances are exact, F16 dequant is
3482 // bit-exact at the storage layer so the beam search already
3483 // ranks under the column's full precision.
3484 let sq8 = matches!(
3485 table.schema.columns.get(col_pos).map(|c| c.ty),
3486 Some(DataType::Vector {
3487 encoding: VecEncoding::Sq8,
3488 ..
3489 })
3490 );
3491 let ef = if sq8 {
3492 ef.max(k).max(k * SQ8_RERANK_OVER_FETCH)
3493 } else {
3494 ef.max(k)
3495 };
3496 // Descend by L2 (the topology metric) so layers prune consistently.
3497 let entry_d = vec_l2_sq(table, col_pos, entry, query);
3498 let mut current = entry;
3499 let mut current_d = entry_d;
3500 for layer in (1..=entry_level).rev() {
3501 (current, current_d) = greedy_layer_walk(table, idx_pos, layer, current, current_d, query);
3502 }
3503 // Final beam search on layer 0 under the caller's metric.
3504 let mut results = layer_beam_search(table, idx_pos, 0, current, current_d, query, ef, metric);
3505 if sq8 {
3506 results = sq8_rerank(table, col_pos, &results, query, metric);
3507 }
3508 results.truncate(k);
3509 results
3510}
3511
3512/// v6.0.1 step 5: re-score ADC top-`K*3` candidates with the
3513/// dequantised cell vs the f32 query, then re-sort. Recovers the
3514/// recall the SQ8 ADC sacrifices for 4× compression — the design's
3515/// "f32 rerank step is on by default" path (deliberation #3).
3516/// `metric` is the same metric the beam search used; the rerank
3517/// arithmetic re-derives the exact distance under that metric.
3518fn sq8_rerank(
3519 table: &Table,
3520 col_pos: usize,
3521 candidates: &[(f32, usize)],
3522 query: &[f32],
3523 metric: NswMetric,
3524) -> Vec<(f32, usize)> {
3525 let mut out: Vec<(f32, usize)> = candidates
3526 .iter()
3527 .filter_map(|&(adc_d, row)| {
3528 let cell = table.rows.get(row).and_then(|r| r.values.get(col_pos))?;
3529 let Value::Sq8Vector(q) = cell else {
3530 // F32 cells shouldn't reach this path (sq8 fence
3531 // above), but stay defensive: pass through with
3532 // the ADC distance unchanged.
3533 return Some((adc_d, row));
3534 };
3535 let deq = quantize::dequantize(q);
3536 if deq.len() != query.len() {
3537 return None;
3538 }
3539 Some((metric_distance(metric, &deq, query), row))
3540 })
3541 .collect();
3542 out.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
3543 out
3544}
3545
3546/// Multiplier applied to `k` so the SQ8 rerank pass sees a wider
3547/// candidate set. 3× is the design-stage value; v6.0.5 sweep work
3548/// can re-tune once full corpus profiling is in.
3549const SQ8_RERANK_OVER_FETCH: usize = 3;
3550
3551fn metric_distance(metric: NswMetric, a: &[f32], b: &[f32]) -> f32 {
3552 match metric {
3553 NswMetric::L2 => l2_distance_sq(a, b),
3554 NswMetric::InnerProduct => -inner_product_f32(a, b),
3555 NswMetric::Cosine => {
3556 let (dot, na, nb) = cosine_dot_norms_f32(a, b);
3557 if na == 0.0 || nb == 0.0 {
3558 return f32::INFINITY;
3559 }
3560 // `f32::sqrt` lives in std, so hand-roll Newton-Raphson on
3561 // f64 — same trick the L2 binary op already uses.
3562 let denom = sqrt_newton_f32(na) * sqrt_newton_f32(nb);
3563 1.0 - dot / denom
3564 }
3565 }
3566}
3567
3568/// v6.0.2: dispatch wrapper for the f32 dot product (used by `<#>` +
3569/// the cosine numerator). NEON path when `len % 4 == 0 && len >= 4`,
3570/// scalar fallback otherwise. Returns the positive dot — callers
3571/// negate for the pgvector `<#>` "smaller = closer" convention.
3572///
3573/// Public so perf gates + downstream benches can microbenchmark the
3574/// dispatch directly; not part of the STABILITY contract — internal
3575/// SIMD layout can evolve in any release.
3576#[doc(hidden)]
3577#[inline]
3578pub fn inner_product_f32(a: &[f32], b: &[f32]) -> f32 {
3579 #[cfg(target_arch = "aarch64")]
3580 {
3581 if a.len() == b.len() && a.len() >= 4 && a.len().is_multiple_of(4) {
3582 // SAFETY: NEON is a baseline aarch64 feature; preconditions
3583 // (matching lengths, ≥ 1 full lane group) are checked above.
3584 return unsafe { inner_product_neon(a, b) };
3585 }
3586 }
3587 inner_product_scalar(a, b)
3588}
3589
3590fn inner_product_scalar(a: &[f32], b: &[f32]) -> f32 {
3591 let mut dot: f32 = 0.0;
3592 for (x, y) in a.iter().zip(b.iter()) {
3593 dot += x * y;
3594 }
3595 dot
3596}
3597
3598#[cfg(target_arch = "aarch64")]
3599#[target_feature(enable = "neon")]
3600#[allow(clippy::many_single_char_names)] // NEON intrinsics work in single-letter regs by convention
3601unsafe fn inner_product_neon(a: &[f32], b: &[f32]) -> f32 {
3602 use core::arch::aarch64::{
3603 float32x4_t, vaddq_f32, vaddvq_f32, vdupq_n_f32, vfmaq_f32, vld1q_f32,
3604 };
3605 unsafe {
3606 // Two parallel accumulators (same trick as L2 NEON) so the
3607 // FMA dependency chain doesn't serialise.
3608 let zero: float32x4_t = vdupq_n_f32(0.0);
3609 let mut acc0 = zero;
3610 let mut acc1 = zero;
3611 let n = a.len();
3612 let mut i = 0usize;
3613 while i + 8 <= n {
3614 let av0 = vld1q_f32(a.as_ptr().add(i));
3615 let bv0 = vld1q_f32(b.as_ptr().add(i));
3616 acc0 = vfmaq_f32(acc0, av0, bv0);
3617 let av1 = vld1q_f32(a.as_ptr().add(i + 4));
3618 let bv1 = vld1q_f32(b.as_ptr().add(i + 4));
3619 acc1 = vfmaq_f32(acc1, av1, bv1);
3620 i += 8;
3621 }
3622 while i + 4 <= n {
3623 let av = vld1q_f32(a.as_ptr().add(i));
3624 let bv = vld1q_f32(b.as_ptr().add(i));
3625 acc0 = vfmaq_f32(acc0, av, bv);
3626 i += 4;
3627 }
3628 vaddvq_f32(vaddq_f32(acc0, acc1))
3629 }
3630}
3631
3632/// v6.0.2: dispatch wrapper for the three accumulators (`dot`, `||a||²`,
3633/// `||b||²`) cosine needs. Same NEON pre-condition as the L2 / IP
3634/// paths; same scalar fallback shape.
3635///
3636/// Public for benchmarking only (see `inner_product_f32`); not in the
3637/// STABILITY contract.
3638#[doc(hidden)]
3639#[inline]
3640pub fn cosine_dot_norms_f32(a: &[f32], b: &[f32]) -> (f32, f32, f32) {
3641 #[cfg(target_arch = "aarch64")]
3642 {
3643 if a.len() == b.len() && a.len() >= 4 && a.len().is_multiple_of(4) {
3644 // SAFETY: see `inner_product_neon`.
3645 return unsafe { cosine_dot_norms_neon(a, b) };
3646 }
3647 }
3648 cosine_dot_norms_scalar(a, b)
3649}
3650
3651fn cosine_dot_norms_scalar(a: &[f32], b: &[f32]) -> (f32, f32, f32) {
3652 let mut dot: f32 = 0.0;
3653 let mut na: f32 = 0.0;
3654 let mut nb: f32 = 0.0;
3655 for (x, y) in a.iter().zip(b.iter()) {
3656 dot += x * y;
3657 na += x * x;
3658 nb += y * y;
3659 }
3660 (dot, na, nb)
3661}
3662
3663#[cfg(target_arch = "aarch64")]
3664#[target_feature(enable = "neon")]
3665#[allow(clippy::many_single_char_names, clippy::similar_names)]
3666unsafe fn cosine_dot_norms_neon(a: &[f32], b: &[f32]) -> (f32, f32, f32) {
3667 use core::arch::aarch64::{float32x4_t, vaddvq_f32, vdupq_n_f32, vfmaq_f32, vld1q_f32};
3668 unsafe {
3669 let zero: float32x4_t = vdupq_n_f32(0.0);
3670 let mut acc_dot = zero;
3671 let mut acc_na = zero;
3672 let mut acc_nb = zero;
3673 let n = a.len();
3674 let mut i = 0usize;
3675 while i + 4 <= n {
3676 let av = vld1q_f32(a.as_ptr().add(i));
3677 let bv = vld1q_f32(b.as_ptr().add(i));
3678 acc_dot = vfmaq_f32(acc_dot, av, bv);
3679 acc_na = vfmaq_f32(acc_na, av, av);
3680 acc_nb = vfmaq_f32(acc_nb, bv, bv);
3681 i += 4;
3682 }
3683 (vaddvq_f32(acc_dot), vaddvq_f32(acc_na), vaddvq_f32(acc_nb))
3684 }
3685}
3686
3687fn sqrt_newton_f32(x: f32) -> f32 {
3688 if x <= 0.0 {
3689 return 0.0;
3690 }
3691 let mut g = x;
3692 for _ in 0..10 {
3693 g = 0.5 * (g + x / g);
3694 }
3695 g
3696}
3697
3698/// Squared Euclidean distance — used for ordering inside NSW (the sqrt
3699/// preserves the order). Caller takes sqrt before reporting back to SQL.
3700///
3701/// v3.3.2: aarch64 NEON path for `len % 4 == 0` (which covers every
3702/// HNSW-indexed VECTOR(N) where N is a multiple of 4 — i.e. all
3703/// production-shaped embeddings: 64, 128, 256, 384, 512, 768, 1024,
3704/// 1536, ...). Other shapes fall back to the scalar loop.
3705#[inline]
3706fn l2_distance_sq(a: &[f32], b: &[f32]) -> f32 {
3707 #[cfg(target_arch = "aarch64")]
3708 {
3709 if a.len() == b.len() && a.len() >= 4 && a.len().is_multiple_of(4) {
3710 // SAFETY: NEON is a baseline aarch64 feature (ARMv8);
3711 // the precondition is checked above (matching lengths,
3712 // multiple of 4, at least one 128-bit lane group).
3713 return unsafe { l2_distance_sq_neon(a, b) };
3714 }
3715 }
3716 l2_distance_sq_scalar(a, b)
3717}
3718
3719fn l2_distance_sq_scalar(a: &[f32], b: &[f32]) -> f32 {
3720 let mut sum: f32 = 0.0;
3721 for (x, y) in a.iter().zip(b.iter()) {
3722 let d = *x - *y;
3723 sum += d * d;
3724 }
3725 sum
3726}
3727
3728#[cfg(target_arch = "aarch64")]
3729#[target_feature(enable = "neon")]
3730#[allow(clippy::many_single_char_names)] // NEON intrinsics work in single-letter regs by convention
3731unsafe fn l2_distance_sq_neon(a: &[f32], b: &[f32]) -> f32 {
3732 use core::arch::aarch64::{
3733 float32x4_t, vaddq_f32, vaddvq_f32, vdupq_n_f32, vfmaq_f32, vld1q_f32, vsubq_f32,
3734 };
3735 unsafe {
3736 // Two independent accumulator registers so the FMA dependency
3737 // chain doesn't serialise (each FMA depends on prior FMA).
3738 // Pre-conditions checked by caller: `a.len() == b.len()`,
3739 // `a.len() % 4 == 0`, `a.len() >= 4`.
3740 let zero: float32x4_t = vdupq_n_f32(0.0);
3741 let mut acc0 = zero;
3742 let mut acc1 = zero;
3743 let n = a.len();
3744 let mut i = 0usize;
3745 // Process 8 floats per iter when available (two parallel
3746 // accumulators). Tail of 4 falls into the second loop.
3747 while i + 8 <= n {
3748 let d0 = vsubq_f32(vld1q_f32(a.as_ptr().add(i)), vld1q_f32(b.as_ptr().add(i)));
3749 acc0 = vfmaq_f32(acc0, d0, d0);
3750 let d1 = vsubq_f32(
3751 vld1q_f32(a.as_ptr().add(i + 4)),
3752 vld1q_f32(b.as_ptr().add(i + 4)),
3753 );
3754 acc1 = vfmaq_f32(acc1, d1, d1);
3755 i += 8;
3756 }
3757 while i + 4 <= n {
3758 let d = vsubq_f32(vld1q_f32(a.as_ptr().add(i)), vld1q_f32(b.as_ptr().add(i)));
3759 acc0 = vfmaq_f32(acc0, d, d);
3760 i += 4;
3761 }
3762 vaddvq_f32(vaddq_f32(acc0, acc1))
3763 }
3764}
3765
3766/// Public wrapper: run an NSW kNN search and return the top-k row
3767/// indices ordered by ascending distance under the given metric.
3768pub fn nsw_query(
3769 table: &Table,
3770 idx_name: &str,
3771 query: &[f32],
3772 k: usize,
3773 metric: NswMetric,
3774) -> Vec<usize> {
3775 let Some(idx_pos) = table.indices.iter().position(|i| i.name == idx_name) else {
3776 return Vec::new();
3777 };
3778 let ef = (k * 2).max(NSW_DEFAULT_M);
3779 let mut hits = nsw_search(table, idx_pos, query, k, ef, metric);
3780 hits.truncate(k);
3781 hits.into_iter().map(|(_, idx)| idx).collect()
3782}
3783
3784/// Find any NSW index on a column. Used by the planner to decide
3785/// whether an `ORDER BY col <-> literal LIMIT k` query can skip the
3786/// brute-force scan.
3787pub fn nsw_index_on(table: &Table, column_position: usize) -> Option<&Index> {
3788 table
3789 .indices
3790 .iter()
3791 .find(|i| i.column_position == column_position && matches!(i.kind, IndexKind::Nsw(_)))
3792}
3793
3794/// Catalog: insertion-ordered `Vec<Table>` for stable iter / serialize,
3795/// plus a `BTreeMap<String, usize>` sidecar index so `get` / `get_mut`
3796/// run in O(log n) instead of the old linear scan with per-element
3797/// string compares.
3798///
3799/// A pure `BTreeMap<String, Table>` was tried in an interim version
3800/// of v3.1.2 and regressed the single-table catalog benches by ~10%
3801/// (the per-element `BTreeMap` overhead outweighs the lookup win
3802/// when n is small). The sidecar shape preserves the insertion-order
3803/// iteration the on-disk encoding relies on and keeps `last_mut`
3804/// (used by the deserialize hot path) cheap.
3805#[derive(Debug, Clone, Default)]
3806pub struct Catalog {
3807 tables: Vec<Table>,
3808 /// `name → tables[index]`. Kept in lock-step with `tables`.
3809 /// `create_table` is the only write path.
3810 by_name: BTreeMap<String, usize>,
3811 /// v5.1: in-memory cold-tier segments. Side-loaded via
3812 /// [`Catalog::load_segment_bytes`] — they live outside the
3813 /// catalog snapshot (caller persists them as separate files
3814 /// and re-loads on boot, until v5.3's `CatalogManifest` makes
3815 /// that wiring automatic). `RowLocator::Cold { segment_id, .. }`
3816 /// indexes this `Vec`. Cleared on `Catalog::new` / fresh
3817 /// `deserialize`.
3818 ///
3819 /// `Arc` wrap keeps `Catalog::clone` at O(N segments) bumps
3820 /// (rather than O(total segment bytes) memcpy) so the v4.42
3821 /// group-commit pre-image rollback invariant — clone is
3822 /// effectively free — survives the cold-tier addition.
3823 ///
3824 /// v6.7.3 — slots became `Option<…>` so cold-segment compaction
3825 /// can tombstone merged sources without breaking the
3826 /// `segment_id = index_into_vec` contract that on-disk
3827 /// `RowLocator::Cold { segment_id }` already serialized.
3828 /// `None` slot = the segment was retired by compaction; the
3829 /// physical file may still be on disk (next CHECKPOINT writes
3830 /// a manifest that no longer lists it, and the file becomes
3831 /// an orphan eligible for offline cleanup).
3832 cold_segments: Vec<Option<Arc<OwnedSegment>>>,
3833 /// v7.12.4 — user-defined functions (PL/pgSQL + SQL).
3834 /// Keyed by function name (PG overloading is out of scope).
3835 /// Bodies are stored as the raw source text the parser saw
3836 /// between `$$ ... $$`; the engine re-parses on each
3837 /// invocation. This keeps `spg-storage` free of `spg-sql`
3838 /// dependency — same pattern as partial-index predicates.
3839 functions: BTreeMap<String, FunctionDef>,
3840 /// v7.12.4 — triggers in insertion order. Multiple triggers
3841 /// per table / event fire in this order (matching PG's
3842 /// alphabetical-by-default with insertion-stable tie-break
3843 /// behaviour — we just keep insertion order for now).
3844 triggers: Vec<TriggerDef>,
3845 /// v7.17.0 — catalogued SEQUENCE objects (Phase 1.1). Each
3846 /// `nextval(name)` reaches in here, atomically increments
3847 /// `last_value` / flips `is_called`, returns the new value.
3848 /// Persisted in catalog FILE_VERSION 26+; older catalogs
3849 /// deserialise with an empty map.
3850 sequences: BTreeMap<String, SequenceDef>,
3851 /// v7.17.0 — catalogued VIEW objects (Phase 1.2). Each
3852 /// `SELECT FROM v` at engine exec-time looks up `v` here and
3853 /// prepends the view body as a synthetic CTE. Persisted in
3854 /// catalog FILE_VERSION 27+; older catalogs deserialise with
3855 /// an empty map.
3856 views: BTreeMap<String, ViewDef>,
3857 /// v7.17.0 — catalogued MATERIALIZED VIEW source registry
3858 /// (Phase 1.3). Maps name → SELECT source. The materialised
3859 /// rows themselves live as a regular `Table` with the same
3860 /// name; REFRESH re-parses + re-executes the source against
3861 /// the table. Persisted in catalog FILE_VERSION 28+;
3862 /// older catalogs deserialise with an empty map.
3863 materialized_views: BTreeMap<String, String>,
3864 /// v7.17.0 — catalogued user-defined ENUM types (Phase 1.4).
3865 /// Maps name → label list. Columns reference these by name
3866 /// via `ColumnSchema.user_enum_type`. Persisted in catalog
3867 /// FILE_VERSION 29+; older catalogs deserialise with an empty
3868 /// map.
3869 enum_types: BTreeMap<String, EnumDef>,
3870 /// v7.17.0 — catalogued user-defined DOMAIN types (Phase 1.5).
3871 /// Maps name → base + CHECK constraints. Columns reference
3872 /// these by name via `ColumnSchema.user_domain_type`.
3873 /// Persisted in catalog FILE_VERSION 30+; older catalogs
3874 /// deserialise with an empty map.
3875 domain_types: BTreeMap<String, DomainDef>,
3876 /// v7.17.0 — schema-namespace registry (Phase 1.6). Tracks
3877 /// which schemas exist. `public`, `pg_catalog`, and
3878 /// `information_schema` are built-in and always present.
3879 /// Schema-qualified table references still strip the prefix
3880 /// at lookup time per v7.16-and-earlier — full
3881 /// schema-as-isolation is v7.18+ scope. Persisted in catalog
3882 /// FILE_VERSION 31+; older catalogs deserialise with just
3883 /// the built-ins.
3884 schemas: alloc::collections::BTreeSet<String>,
3885}
3886
3887/// v7.12.4 — catalogued user-defined function. `body` is the raw
3888/// source text between `$$ ... $$`; the engine re-parses it on
3889/// invocation. This keeps the storage codec stable when the
3890/// PL/pgSQL surface grows (no breaking-change risk on the disk
3891/// format).
3892#[derive(Debug, Clone, PartialEq, Eq)]
3893pub struct FunctionDef {
3894 pub name: String,
3895 /// Display form of the argument list, e.g.
3896 /// `"(name TEXT, ts TIMESTAMP)"`. Empty `"()"` for the trigger
3897 /// function shape. Parser-side canonicalised before storage.
3898 pub args_repr: String,
3899 /// Display form of the return type, e.g. `"TRIGGER"` /
3900 /// `"INT"` / `"SETOF text"`. The engine special-cases
3901 /// `"TRIGGER"` (case-insensitive) to gate trigger-only
3902 /// semantics (NEW/OLD).
3903 pub returns: String,
3904 /// `LANGUAGE` clause, lowercased. `"plpgsql"` / `"sql"`.
3905 pub language: String,
3906 /// Source body of the function. PL/pgSQL: includes the
3907 /// surrounding `BEGIN ... END;`. SQL: includes the
3908 /// statement(s). The engine re-parses on invocation; bad
3909 /// bodies surface as a parse error at CALL time, not CREATE.
3910 pub body: String,
3911}
3912
3913/// v7.12.4 — catalogued trigger. References its function by
3914/// name; the function must exist at TRIGGER creation time
3915/// (forward references are deferred to v7.12.5+).
3916#[derive(Debug, Clone, PartialEq, Eq)]
3917pub struct TriggerDef {
3918 pub name: String,
3919 /// Watched table. Trigger is dropped when the table drops.
3920 pub table: String,
3921 /// `"BEFORE"` / `"AFTER"` / `"INSTEAD OF"`. Stored as the
3922 /// uppercased keyword so deserialised catalogs round-trip
3923 /// without canonicalisation surprises.
3924 pub timing: String,
3925 /// Each entry is one of `"INSERT"` / `"UPDATE"` / `"DELETE"`
3926 /// / `"TRUNCATE"`. `INSERT OR UPDATE` parses to two entries.
3927 pub events: Vec<String>,
3928 /// `"ROW"` / `"STATEMENT"`. v7.12.4 ships `"ROW"` only;
3929 /// `"STATEMENT"` parses and persists but the executor
3930 /// refuses it at trigger fire time.
3931 pub for_each: String,
3932 /// Name of the PL/pgSQL function to invoke.
3933 pub function: String,
3934 /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
3935 /// (mailrs round-5 G7). Non-empty means the trigger fires
3936 /// only when at least one of these columns appears in the
3937 /// UPDATE's SET list. Empty = no column filter. Stored in
3938 /// catalog FILE_VERSION 23+; older catalogs deserialise with
3939 /// an empty vec.
3940 pub update_columns: Vec<String>,
3941 /// v7.16.1 — whether the trigger fires when its watched
3942 /// event occurs. Toggled by `ALTER TABLE … { ENABLE |
3943 /// DISABLE } TRIGGER …`; pg_dump --disable-triggers wraps
3944 /// every data block with a DISABLE/ENABLE pair so the
3945 /// rows already-computed in prod don't get re-rewritten.
3946 /// Defaults to `true` at CREATE TRIGGER time. Stored in
3947 /// catalog FILE_VERSION 25+; older catalogs deserialise
3948 /// with `enabled = true`.
3949 pub enabled: bool,
3950}
3951
3952/// v7.17.0 — catalogued SEQUENCE. PG semantics: a counter object
3953/// returning monotonically increasing values via `nextval(name)`.
3954/// `last_value` is the most recent value handed out; `is_called`
3955/// is false until the first `nextval`/`setval`. Stored separately
3956/// from tables in the catalog.
3957#[derive(Debug, Clone, PartialEq, Eq)]
3958pub struct SequenceDef {
3959 pub name: String,
3960 /// Data type — narrows the i64 range. PG default BIGINT.
3961 pub data_type: SequenceDataType,
3962 pub start: i64,
3963 pub increment: i64,
3964 pub min_value: i64,
3965 pub max_value: i64,
3966 pub cache: i64,
3967 pub cycle: bool,
3968 /// `OWNED BY` target — `(table, column)` or NONE.
3969 pub owned_by: Option<(String, String)>,
3970 /// Most recently handed-out value. Meaningless when
3971 /// `is_called == false`; in that case the NEXT `nextval`
3972 /// will return `start`.
3973 pub last_value: i64,
3974 pub is_called: bool,
3975}
3976
3977/// v7.17.0 — sequence integer width.
3978#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3979pub enum SequenceDataType {
3980 SmallInt,
3981 Int,
3982 BigInt,
3983}
3984
3985/// v7.17.0 Phase 1.6 — built-in schema names that every Catalog
3986/// understands without an explicit CREATE SCHEMA. Used by
3987/// [`Catalog::schema_exists`] and the engine's schema-qualified
3988/// lookup path.
3989#[must_use]
3990pub fn is_builtin_schema(name: &str) -> bool {
3991 name.eq_ignore_ascii_case("public")
3992 || name.eq_ignore_ascii_case("pg_catalog")
3993 || name.eq_ignore_ascii_case("information_schema")
3994}
3995
3996/// v7.17.0 — parse a PG-canonical UUID text representation into the
3997/// 16-byte network-order layout used by `Value::Uuid`. Accepted input
3998/// shapes (all case-insensitive):
3999/// * Canonical hyphenated 8-4-4-4-12 (`550e8400-e29b-41d4-a716-446655440000`)
4000/// * Unhyphenated 32-char hex (`550e8400e29b41d4a716446655440000`)
4001/// * Either form wrapped in `{ ... }`
4002///
4003/// Returns `None` for any malformed input (wrong length, non-hex
4004/// characters, misplaced hyphens). The caller surfaces a SQL error
4005/// at coercion time — silent acceptance of garbage would mask
4006/// application bugs and is exactly the divergence from PG that
4007/// breaks the 0-change cutover promise.
4008#[must_use]
4009pub fn parse_uuid_str(input: &str) -> Option<[u8; 16]> {
4010 let s = input.trim();
4011 // Strip surrounding braces if present.
4012 let s = if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
4013 inner
4014 } else {
4015 s
4016 };
4017 // Two valid shapes after braces are stripped: 32 hex chars or
4018 // the canonical 36-char hyphenated form.
4019 let hex: String = match s.len() {
4020 32 => s.to_ascii_lowercase(),
4021 36 => {
4022 // Hyphens must be exactly at positions 8, 13, 18, 23.
4023 let b = s.as_bytes();
4024 if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
4025 return None;
4026 }
4027 let mut out = String::with_capacity(32);
4028 out.push_str(&s[0..8]);
4029 out.push_str(&s[9..13]);
4030 out.push_str(&s[14..18]);
4031 out.push_str(&s[19..23]);
4032 out.push_str(&s[24..36]);
4033 out.make_ascii_lowercase();
4034 out
4035 }
4036 _ => return None,
4037 };
4038 let bytes = hex.as_bytes();
4039 let mut out = [0u8; 16];
4040 for i in 0..16 {
4041 let hi = hex_nibble(bytes[i * 2])?;
4042 let lo = hex_nibble(bytes[i * 2 + 1])?;
4043 out[i] = (hi << 4) | lo;
4044 }
4045 Some(out)
4046}
4047
4048fn hex_nibble(b: u8) -> Option<u8> {
4049 match b {
4050 b'0'..=b'9' => Some(b - b'0'),
4051 b'a'..=b'f' => Some(10 + b - b'a'),
4052 b'A'..=b'F' => Some(10 + b - b'A'),
4053 _ => None,
4054 }
4055}
4056
4057/// v7.17.0 — render a `Value::Uuid` payload as the canonical
4058/// lowercase 8-4-4-4-12 hyphenated form PG `text` cast surfaces.
4059#[must_use]
4060pub fn format_uuid(b: &[u8; 16]) -> String {
4061 const HEX: &[u8; 16] = b"0123456789abcdef";
4062 let mut out = String::with_capacity(36);
4063 for (i, byte) in b.iter().enumerate() {
4064 if matches!(i, 4 | 6 | 8 | 10) {
4065 out.push('-');
4066 }
4067 out.push(HEX[(byte >> 4) as usize] as char);
4068 out.push(HEX[(byte & 0x0f) as usize] as char);
4069 }
4070 out
4071}
4072
4073/// v7.17.0 Phase 1.5 — catalogued user-defined DOMAIN. A domain
4074/// is a named CHECK-constrained alias over a built-in type;
4075/// columns bound to it inherit the base type plus the CHECK
4076/// predicates + NOT NULL + DEFAULT at INSERT/UPDATE time.
4077/// `default` / `checks` are stored as Display-form source so
4078/// `spg-storage` stays free of `spg-sql` dependency — same
4079/// pattern as FunctionDef / ViewDef.
4080#[derive(Debug, Clone, PartialEq, Eq)]
4081pub struct DomainDef {
4082 pub name: String,
4083 pub base_type: DataType,
4084 pub nullable: bool,
4085 pub default: Option<String>,
4086 pub checks: Vec<String>,
4087}
4088
4089/// v7.17.0 Phase 1.4 — catalogued user-defined ENUM type. The
4090/// label vector is order-preserving (PG enum ordering follows the
4091/// declared order). At INSERT/UPDATE on a column bound to this
4092/// enum, the engine looks up the value against `labels` and
4093/// rejects non-members.
4094#[derive(Debug, Clone, PartialEq, Eq)]
4095pub struct EnumDef {
4096 pub name: String,
4097 pub labels: Vec<String>,
4098}
4099
4100/// v7.17.0 Phase 1.2 — catalogued VIEW. The body is stored as the
4101/// raw source text the parser saw between `AS` and the statement
4102/// terminator; the engine re-parses on each invocation. Same
4103/// pattern as `FunctionDef` — keeps `spg-storage` free of
4104/// `spg-sql` dependency.
4105#[derive(Debug, Clone, PartialEq, Eq)]
4106pub struct ViewDef {
4107 pub name: String,
4108 /// Optional `(col, col, …)` rename list. Empty when the body's
4109 /// projected names are used directly.
4110 pub columns: Vec<String>,
4111 /// Raw SELECT source. Display-rendered at storage time so the
4112 /// catalog round-trips a deterministic form regardless of
4113 /// whitespace / comments in the original input. Re-parsed at
4114 /// SELECT-from-view time to materialise as a synthetic CTE.
4115 pub body: String,
4116}
4117
4118impl SequenceDataType {
4119 /// PG default min/max per AS clause.
4120 pub fn default_bounds(self, increment_positive: bool) -> (i64, i64) {
4121 match self {
4122 Self::SmallInt => {
4123 if increment_positive {
4124 (1, i64::from(i16::MAX))
4125 } else {
4126 (i64::from(i16::MIN), -1)
4127 }
4128 }
4129 Self::Int => {
4130 if increment_positive {
4131 (1, i64::from(i32::MAX))
4132 } else {
4133 (i64::from(i32::MIN), -1)
4134 }
4135 }
4136 Self::BigInt => {
4137 if increment_positive {
4138 (1, i64::MAX)
4139 } else {
4140 (i64::MIN, -1)
4141 }
4142 }
4143 }
4144 }
4145}
4146
4147impl Catalog {
4148 pub const fn new() -> Self {
4149 Self {
4150 tables: Vec::new(),
4151 by_name: BTreeMap::new(),
4152 cold_segments: Vec::new(),
4153 functions: BTreeMap::new(),
4154 triggers: Vec::new(),
4155 sequences: BTreeMap::new(),
4156 views: BTreeMap::new(),
4157 materialized_views: BTreeMap::new(),
4158 enum_types: BTreeMap::new(),
4159 domain_types: BTreeMap::new(),
4160 schemas: alloc::collections::BTreeSet::new(),
4161 }
4162 }
4163
4164 /// v7.12.4 — read-only view of catalogued user-defined
4165 /// functions. Engine callers go through here to look up the
4166 /// function body before re-parsing it for invocation.
4167 pub const fn functions(&self) -> &BTreeMap<String, FunctionDef> {
4168 &self.functions
4169 }
4170
4171 /// v7.12.4 — register a new user-defined function. With
4172 /// `or_replace = false`, errors if the name is taken. The
4173 /// engine validates the body before passing it here.
4174 pub fn create_function(
4175 &mut self,
4176 def: FunctionDef,
4177 or_replace: bool,
4178 ) -> Result<(), StorageError> {
4179 if !or_replace && self.functions.contains_key(&def.name) {
4180 return Err(StorageError::Corrupt(format!(
4181 "function {:?} already exists (drop or use CREATE OR REPLACE)",
4182 def.name
4183 )));
4184 }
4185 self.functions.insert(def.name.clone(), def);
4186 Ok(())
4187 }
4188
4189 /// v7.12.4 — remove a user-defined function by name. Returns
4190 /// `true` if a function was removed, `false` if none matched.
4191 /// Caller decides whether to surface `if_exists` semantics.
4192 pub fn drop_function(&mut self, name: &str) -> bool {
4193 self.functions.remove(name).is_some()
4194 }
4195
4196 /// v7.17.0 — read-only handle to catalogued sequences.
4197 pub const fn sequences(&self) -> &BTreeMap<String, SequenceDef> {
4198 &self.sequences
4199 }
4200
4201 /// v7.17.0 — register a new SEQUENCE. Errors if `name`
4202 /// collides with an existing sequence and `if_not_exists`
4203 /// is false.
4204 pub fn create_sequence(
4205 &mut self,
4206 def: SequenceDef,
4207 if_not_exists: bool,
4208 ) -> Result<(), StorageError> {
4209 if self.sequences.contains_key(&def.name) {
4210 if if_not_exists {
4211 return Ok(());
4212 }
4213 return Err(StorageError::Corrupt(format!(
4214 "sequence {:?} already exists",
4215 def.name
4216 )));
4217 }
4218 self.sequences.insert(def.name.clone(), def);
4219 Ok(())
4220 }
4221
4222 /// v7.17.0 — remove a SEQUENCE by name. Returns `true` if a
4223 /// sequence was removed, `false` if none matched. Caller
4224 /// surfaces IF EXISTS semantics.
4225 pub fn drop_sequence(&mut self, name: &str) -> bool {
4226 self.sequences.remove(name).is_some()
4227 }
4228
4229 /// v7.17.0 — atomic nextval. Increments `last_value` per
4230 /// `increment`, returns the new value, sets `is_called`.
4231 /// Returns an error on CYCLE-less overflow.
4232 pub fn sequence_next_value(&mut self, name: &str) -> Result<i64, StorageError> {
4233 let Some(seq) = self.sequences.get_mut(name) else {
4234 return Err(StorageError::Corrupt(format!(
4235 "sequence {name:?} does not exist"
4236 )));
4237 };
4238 // PG semantics: when !is_called (fresh sequence or
4239 // setval(_, false)), the next nextval returns the stored
4240 // `last_value`. When is_called, it advances by `increment`
4241 // and CYCLE-wraps on overflow.
4242 let candidate = if seq.is_called {
4243 let next = seq.last_value.checked_add(seq.increment).ok_or_else(|| {
4244 StorageError::Corrupt(format!("sequence {name:?} arithmetic overflow"))
4245 })?;
4246 if seq.increment > 0 {
4247 if next > seq.max_value {
4248 if seq.cycle {
4249 seq.min_value
4250 } else {
4251 return Err(StorageError::Corrupt(format!(
4252 "sequence {name:?} reached MAXVALUE ({})",
4253 seq.max_value
4254 )));
4255 }
4256 } else {
4257 next
4258 }
4259 } else if next < seq.min_value {
4260 if seq.cycle {
4261 seq.max_value
4262 } else {
4263 return Err(StorageError::Corrupt(format!(
4264 "sequence {name:?} reached MINVALUE ({})",
4265 seq.min_value
4266 )));
4267 }
4268 } else {
4269 next
4270 }
4271 } else {
4272 seq.last_value
4273 };
4274 seq.last_value = candidate;
4275 seq.is_called = true;
4276 Ok(candidate)
4277 }
4278
4279 /// v7.17.0 — currval. Errors if the session has never called
4280 /// nextval on this sequence (PG semantics). At the catalog
4281 /// level we approximate "session" with "is_called persisted";
4282 /// the engine session-tracking layer can wrap this for the
4283 /// strict per-session semantics later.
4284 pub fn sequence_current_value(&self, name: &str) -> Result<i64, StorageError> {
4285 let Some(seq) = self.sequences.get(name) else {
4286 return Err(StorageError::Corrupt(format!(
4287 "sequence {name:?} does not exist"
4288 )));
4289 };
4290 if !seq.is_called {
4291 return Err(StorageError::Corrupt(format!(
4292 "currval of sequence {name:?} is not yet defined in this session"
4293 )));
4294 }
4295 Ok(seq.last_value)
4296 }
4297
4298 /// v7.17.0 — setval(name, value [, is_called]). PG returns
4299 /// `value` regardless. `is_called=true` means the NEXT
4300 /// nextval will return `value + increment`; `is_called=false`
4301 /// means the next nextval will return `value`.
4302 pub fn sequence_set_value(
4303 &mut self,
4304 name: &str,
4305 value: i64,
4306 is_called: bool,
4307 ) -> Result<i64, StorageError> {
4308 let Some(seq) = self.sequences.get_mut(name) else {
4309 return Err(StorageError::Corrupt(format!(
4310 "sequence {name:?} does not exist"
4311 )));
4312 };
4313 seq.last_value = value;
4314 seq.is_called = is_called;
4315 Ok(value)
4316 }
4317
4318 /// v7.17.0 Phase 1.2 — read-only handle to catalogued views.
4319 pub const fn views(&self) -> &BTreeMap<String, ViewDef> {
4320 &self.views
4321 }
4322
4323 /// v7.17.0 Phase 1.2 — install a VIEW. `or_replace=true`
4324 /// overwrites an existing entry; `if_not_exists=true` is a
4325 /// silent no-op when the name is taken. Errors if both flags
4326 /// are off and the name collides.
4327 pub fn create_view(
4328 &mut self,
4329 def: ViewDef,
4330 or_replace: bool,
4331 if_not_exists: bool,
4332 ) -> Result<(), StorageError> {
4333 if self.views.contains_key(&def.name) {
4334 if or_replace {
4335 self.views.insert(def.name.clone(), def);
4336 return Ok(());
4337 }
4338 if if_not_exists {
4339 return Ok(());
4340 }
4341 return Err(StorageError::Corrupt(format!(
4342 "view {:?} already exists",
4343 def.name
4344 )));
4345 }
4346 // Reject name collision with tables / sequences — same
4347 // namespace per PG.
4348 if self.by_name.contains_key(&def.name) {
4349 return Err(StorageError::Corrupt(format!(
4350 "view {:?} would shadow an existing table",
4351 def.name
4352 )));
4353 }
4354 if self.sequences.contains_key(&def.name) {
4355 return Err(StorageError::Corrupt(format!(
4356 "view {:?} would shadow an existing sequence",
4357 def.name
4358 )));
4359 }
4360 self.views.insert(def.name.clone(), def);
4361 Ok(())
4362 }
4363
4364 /// v7.17.0 Phase 1.2 — remove a view by name. Returns true if
4365 /// a view was removed.
4366 pub fn drop_view(&mut self, name: &str) -> bool {
4367 self.views.remove(name).is_some()
4368 }
4369
4370 /// v7.17.0 Phase 1.3 — read-only handle to the materialised-
4371 /// view source registry. Each entry pairs with a regular
4372 /// table of the same name that holds the cached rows.
4373 pub const fn materialized_views(&self) -> &BTreeMap<String, String> {
4374 &self.materialized_views
4375 }
4376
4377 /// v7.17.0 Phase 1.3 — register a source for a materialised
4378 /// view. Caller has already created the backing table.
4379 pub fn register_materialized_view(&mut self, name: String, body: String) {
4380 self.materialized_views.insert(name, body);
4381 }
4382
4383 /// v7.17.0 Phase 1.3 — drop the source registry entry. Returns
4384 /// true if a source was unregistered. Caller separately drops
4385 /// the backing table.
4386 pub fn drop_materialized_view_source(&mut self, name: &str) -> bool {
4387 self.materialized_views.remove(name).is_some()
4388 }
4389
4390 /// v7.17.0 Phase 1.4 — read-only handle to user-defined ENUM
4391 /// catalog.
4392 pub const fn enum_types(&self) -> &BTreeMap<String, EnumDef> {
4393 &self.enum_types
4394 }
4395
4396 /// v7.17.0 Phase 1.4 — install a new ENUM type. Errors if
4397 /// `name` collides with an existing enum (no IF NOT EXISTS
4398 /// per PG semantics for CREATE TYPE).
4399 pub fn create_enum_type(&mut self, def: EnumDef) -> Result<(), StorageError> {
4400 if self.enum_types.contains_key(&def.name) {
4401 return Err(StorageError::Corrupt(format!(
4402 "type {:?} already exists",
4403 def.name
4404 )));
4405 }
4406 self.enum_types.insert(def.name.clone(), def);
4407 Ok(())
4408 }
4409
4410 /// v7.17.0 Phase 1.4 — drop an ENUM type by name. Returns
4411 /// true if a type was removed.
4412 pub fn drop_enum_type(&mut self, name: &str) -> bool {
4413 self.enum_types.remove(name).is_some()
4414 }
4415
4416 /// v7.17.0 Phase 1.5 — read-only handle to DOMAIN catalog.
4417 pub const fn domain_types(&self) -> &BTreeMap<String, DomainDef> {
4418 &self.domain_types
4419 }
4420
4421 /// v7.17.0 Phase 1.5 — install a DOMAIN. Errors on collision
4422 /// with an existing domain.
4423 pub fn create_domain_type(&mut self, def: DomainDef) -> Result<(), StorageError> {
4424 if self.domain_types.contains_key(&def.name) {
4425 return Err(StorageError::Corrupt(format!(
4426 "domain {:?} already exists",
4427 def.name
4428 )));
4429 }
4430 self.domain_types.insert(def.name.clone(), def);
4431 Ok(())
4432 }
4433
4434 /// v7.17.0 Phase 1.5 — drop a DOMAIN by name.
4435 pub fn drop_domain_type(&mut self, name: &str) -> bool {
4436 self.domain_types.remove(name).is_some()
4437 }
4438
4439 /// v7.17.0 Phase 1.6 — read-only handle to the user-created
4440 /// schema registry. Built-in schemas (`public`, `pg_catalog`,
4441 /// `information_schema`) are NOT included here; use
4442 /// [`schema_exists`](Self::schema_exists) for the full
4443 /// check.
4444 pub const fn user_schemas(&self) -> &alloc::collections::BTreeSet<String> {
4445 &self.schemas
4446 }
4447
4448 /// v7.17.0 Phase 1.6 — schema-name resolver. Returns true
4449 /// for built-in schemas + every user-CREATEd one. Used by
4450 /// CREATE SCHEMA collision checks and (future) by
4451 /// information_schema.schemata.
4452 pub fn schema_exists(&self, name: &str) -> bool {
4453 is_builtin_schema(name) || self.schemas.contains(name)
4454 }
4455
4456 /// v7.17.0 Phase 1.6 — register a new schema. Errors if the
4457 /// name already exists and `if_not_exists=false`. Built-in
4458 /// names cannot be redeclared.
4459 pub fn create_schema(&mut self, name: String, if_not_exists: bool) -> Result<(), StorageError> {
4460 if is_builtin_schema(&name) {
4461 if if_not_exists {
4462 return Ok(());
4463 }
4464 return Err(StorageError::Corrupt(format!(
4465 "schema {name:?} is built-in and cannot be redeclared"
4466 )));
4467 }
4468 if self.schemas.contains(&name) {
4469 if if_not_exists {
4470 return Ok(());
4471 }
4472 return Err(StorageError::Corrupt(format!(
4473 "schema {name:?} already exists"
4474 )));
4475 }
4476 self.schemas.insert(name);
4477 Ok(())
4478 }
4479
4480 /// v7.17.0 Phase 1.6 — drop a user-created schema. Returns
4481 /// true if a schema was removed. Built-in names always
4482 /// return false (cannot be dropped). Tables that previously
4483 /// used the schema as a prefix keep their bare name and stay
4484 /// queryable — this is the "prefix routing, not isolation"
4485 /// posture documented in v7.17 Phase 1.6.
4486 pub fn drop_schema(&mut self, name: &str) -> Result<bool, StorageError> {
4487 if is_builtin_schema(name) {
4488 return Err(StorageError::Corrupt(format!(
4489 "schema {name:?} is built-in and cannot be dropped"
4490 )));
4491 }
4492 Ok(self.schemas.remove(name))
4493 }
4494
4495 /// v7.17.0 — ALTER SEQUENCE option merge. Caller-provided
4496 /// updates overwrite the matching fields; unset fields keep
4497 /// their stored values. RESTART variants update last_value
4498 /// directly per PG: `RESTART` resets to current `start`;
4499 /// `RESTART WITH n` resets to `n`.
4500 #[allow(clippy::too_many_arguments)]
4501 pub fn alter_sequence(
4502 &mut self,
4503 name: &str,
4504 increment: Option<i64>,
4505 min_value: Option<i64>,
4506 max_value: Option<i64>,
4507 start: Option<i64>,
4508 restart: Option<Option<i64>>,
4509 cache: Option<i64>,
4510 cycle: Option<bool>,
4511 owned_by: Option<Option<(String, String)>>,
4512 ) -> Result<(), StorageError> {
4513 let Some(seq) = self.sequences.get_mut(name) else {
4514 return Err(StorageError::Corrupt(format!(
4515 "sequence {name:?} does not exist"
4516 )));
4517 };
4518 if let Some(v) = increment {
4519 seq.increment = v;
4520 }
4521 if let Some(v) = min_value {
4522 seq.min_value = v;
4523 }
4524 if let Some(v) = max_value {
4525 seq.max_value = v;
4526 }
4527 if let Some(v) = start {
4528 seq.start = v;
4529 }
4530 if let Some(restart_value) = restart {
4531 seq.last_value = restart_value.unwrap_or(seq.start);
4532 seq.is_called = false;
4533 }
4534 if let Some(v) = cache {
4535 seq.cache = v;
4536 }
4537 if let Some(v) = cycle {
4538 seq.cycle = v;
4539 }
4540 if let Some(v) = owned_by {
4541 seq.owned_by = v;
4542 }
4543 Ok(())
4544 }
4545
4546 /// v7.12.4 — read-only slice of all catalogued triggers.
4547 /// Engine row-write paths filter this by (table, event,
4548 /// timing) and fire matches in slice order.
4549 pub fn triggers(&self) -> &[TriggerDef] {
4550 &self.triggers
4551 }
4552
4553 /// v7.15.0 — mutable handle to the trigger slice for
4554 /// `ALTER TABLE … RENAME COLUMN`, which rewrites every
4555 /// `update_columns` entry that referenced the renamed
4556 /// column.
4557 pub fn triggers_mut(&mut self) -> &mut Vec<TriggerDef> {
4558 &mut self.triggers
4559 }
4560
4561 /// v7.12.4 — register a new trigger. With `or_replace = false`,
4562 /// errors when a trigger with the same name already exists on
4563 /// the same table (PG scoping rule — trigger names are
4564 /// per-table, not global). Trigger function must already
4565 /// exist in the catalog at registration time.
4566 pub fn create_trigger(
4567 &mut self,
4568 def: TriggerDef,
4569 or_replace: bool,
4570 ) -> Result<(), StorageError> {
4571 if !self.by_name.contains_key(&def.table) {
4572 return Err(StorageError::TableNotFound {
4573 name: def.table.clone(),
4574 });
4575 }
4576 if !self.functions.contains_key(&def.function) {
4577 return Err(StorageError::Corrupt(format!(
4578 "trigger {:?} references unknown function {:?}",
4579 def.name, def.function
4580 )));
4581 }
4582 let dup = self
4583 .triggers
4584 .iter()
4585 .position(|t| t.name == def.name && t.table == def.table);
4586 match (dup, or_replace) {
4587 (Some(_), false) => Err(StorageError::Corrupt(format!(
4588 "trigger {:?} already exists on table {:?}",
4589 def.name, def.table
4590 ))),
4591 (Some(i), true) => {
4592 self.triggers[i] = def;
4593 Ok(())
4594 }
4595 (None, _) => {
4596 self.triggers.push(def);
4597 Ok(())
4598 }
4599 }
4600 }
4601
4602 /// v7.12.4 — remove a trigger by `(name, table)`. Returns
4603 /// `true` if one was removed.
4604 pub fn drop_trigger(&mut self, name: &str, table: &str) -> bool {
4605 let before = self.triggers.len();
4606 self.triggers
4607 .retain(|t| !(t.name == name && t.table == table));
4608 before != self.triggers.len()
4609 }
4610
4611 pub fn create_table(&mut self, schema: TableSchema) -> Result<(), StorageError> {
4612 if self.by_name.contains_key(&schema.name) {
4613 return Err(StorageError::DuplicateTable {
4614 name: schema.name.clone(),
4615 });
4616 }
4617 let idx = self.tables.len();
4618 let name = schema.name.clone();
4619 self.tables.push(Table::new(schema));
4620 self.by_name.insert(name, idx);
4621 Ok(())
4622 }
4623
4624 pub fn get(&self, name: &str) -> Option<&Table> {
4625 let idx = *self.by_name.get(name)?;
4626 self.tables.get(idx)
4627 }
4628
4629 pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
4630 let idx = *self.by_name.get(name)?;
4631 self.tables.get_mut(idx)
4632 }
4633
4634 pub fn table_count(&self) -> usize {
4635 self.tables.len()
4636 }
4637
4638 /// v7.14.0 — remove a table by name. Returns `true` when the
4639 /// table existed (and is now gone), `false` when it didn't.
4640 /// Used by `DROP TABLE` from pg_dump / mysqldump preambles
4641 /// where the dump re-creates schema and starts with
4642 /// `DROP TABLE IF EXISTS`.
4643 pub fn drop_table(&mut self, name: &str) -> bool {
4644 let Some(idx) = self.by_name.remove(name) else {
4645 return false;
4646 };
4647 // swap_remove invalidates the trailing index → rebuild
4648 // by_name for affected entries.
4649 self.tables.swap_remove(idx);
4650 // Re-stamp moved table's index slot in by_name.
4651 if idx < self.tables.len() {
4652 let moved_name = self.tables[idx].schema.name.clone();
4653 self.by_name.insert(moved_name, idx);
4654 }
4655 true
4656 }
4657
4658 /// v7.16.2 — rename a table (mailrs round-10 A.5). Updates
4659 /// the schema name, the catalog name → index map, and
4660 /// rewrites every reference dangling at the table name:
4661 /// * every FK on every OTHER table whose `parent_table`
4662 /// pointed at the old name now points at the new
4663 /// name, so FK enforcement keeps working
4664 /// * every trigger watching the table updates its `table`
4665 /// field
4666 /// Returns `Ok` on success; `Err(StorageError::TableNotFound)`
4667 /// when the old name isn't in the catalog and
4668 /// `Err(StorageError::DuplicateTable)` when the new name is
4669 /// already taken.
4670 pub fn rename_table(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
4671 if old == new {
4672 return Ok(());
4673 }
4674 if self.by_name.contains_key(new) {
4675 return Err(StorageError::Corrupt(format!(
4676 "rename_table: target name {new:?} already exists"
4677 )));
4678 }
4679 let idx = self
4680 .by_name
4681 .remove(old)
4682 .ok_or_else(|| StorageError::TableNotFound { name: old.into() })?;
4683 self.tables[idx].schema.name = new.to_string();
4684 self.by_name.insert(new.to_string(), idx);
4685 for t in &mut self.tables {
4686 for fk in &mut t.schema.foreign_keys {
4687 if fk.parent_table == old {
4688 fk.parent_table = new.to_string();
4689 }
4690 }
4691 }
4692 for trig in &mut self.triggers {
4693 if trig.table == old {
4694 trig.table = new.to_string();
4695 }
4696 }
4697 Ok(())
4698 }
4699
4700 /// v7.16.2 — rename an index by name. Walks every table
4701 /// since the index lives on its owning table; updates the
4702 /// name in place. Errors with `IndexNotFound` when no
4703 /// index matches. mailrs round-10 A.5.
4704 pub fn rename_index(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
4705 if old == new {
4706 return Ok(());
4707 }
4708 // Reject the new name if it already exists anywhere.
4709 for t in &self.tables {
4710 if t.indices.iter().any(|i| i.name == new) {
4711 return Err(StorageError::Corrupt(format!(
4712 "rename_index: target name {new:?} already exists"
4713 )));
4714 }
4715 }
4716 for t in &mut self.tables {
4717 for i in &mut t.indices {
4718 if i.name == old {
4719 i.name = new.to_string();
4720 return Ok(());
4721 }
4722 }
4723 }
4724 Err(StorageError::IndexNotFound { name: old.into() })
4725 }
4726
4727 /// v7.14.0 — remove a named index across the catalog.
4728 /// Returns `true` when found + dropped.
4729 pub fn drop_named_index(&mut self, name: &str) -> bool {
4730 for t in &mut self.tables {
4731 let before = t.indices.len();
4732 t.indices.retain(|i| i.name != name);
4733 if t.indices.len() != before {
4734 return true;
4735 }
4736 }
4737 false
4738 }
4739
4740 /// Borrow-free copy of every table's name in catalog order
4741 /// (= insertion order, matching the on-disk encoding).
4742 pub fn table_names(&self) -> Vec<String> {
4743 self.tables.iter().map(|t| t.schema.name.clone()).collect()
4744 }
4745
4746 /// v5.1: register a cold-tier segment that already lives in
4747 /// memory (caller did the file read). Returns the
4748 /// `segment_id` that `RowLocator::Cold { segment_id, .. }`
4749 /// will reference — currently this is just the index into
4750 /// `cold_segments`, but treat it as an opaque token.
4751 ///
4752 /// Storage is `no_std`, so file I/O is the caller's
4753 /// responsibility — `spg-server` reads the file and forwards
4754 /// the bytes here. The bytes stay resident in the catalog
4755 /// for the life of the `Catalog`, parsed only once.
4756 pub fn load_segment_bytes(&mut self, bytes: Vec<u8>) -> Result<u32, StorageError> {
4757 let id = u32::try_from(self.cold_segments.len()).map_err(|_| {
4758 StorageError::Corrupt("cold segment count would exceed u32::MAX".into())
4759 })?;
4760 let seg = OwnedSegment::from_bytes(bytes)
4761 .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
4762 self.cold_segments.push(Some(Arc::new(seg)));
4763 Ok(id)
4764 }
4765
4766 /// v6.7.3 — register a cold-tier segment at a specific id. Used
4767 /// by the spg-server manifest-boot path so segments whose
4768 /// neighbouring ids were retired by compaction still get back
4769 /// the same `segment_id` they had pre-restart (the
4770 /// `RowLocator::Cold { segment_id }` baked into the BTree-index
4771 /// snapshot persists across restart and must continue to
4772 /// resolve).
4773 ///
4774 /// Pads the Vec with `None` slots up to `target_id` if needed.
4775 /// Errors when the target slot is already occupied (would
4776 /// stomp another segment), the parse fails, or `target_id`
4777 /// exceeds `u32::MAX`.
4778 pub fn load_segment_bytes_at(
4779 &mut self,
4780 target_id: u32,
4781 bytes: Vec<u8>,
4782 ) -> Result<(), StorageError> {
4783 let seg = OwnedSegment::from_bytes(bytes)
4784 .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
4785 let idx = target_id as usize;
4786 while self.cold_segments.len() <= idx {
4787 self.cold_segments.push(None);
4788 }
4789 if self.cold_segments[idx].is_some() {
4790 return Err(StorageError::Corrupt(format!(
4791 "load_segment_bytes_at: segment_id {target_id} already occupied"
4792 )));
4793 }
4794 self.cold_segments[idx] = Some(Arc::new(seg));
4795 Ok(())
4796 }
4797
4798 /// v6.7.3 — retire a cold-tier segment slot (compaction-driven).
4799 /// The physical file is the caller's concern (typically kept
4800 /// on disk until the next CHECKPOINT writes a manifest that
4801 /// no longer lists it); this just flips the in-memory slot
4802 /// to `None` so later cold lookups for `segment_id` resolve
4803 /// as "unknown" instead of returning a stale row.
4804 ///
4805 /// No-op when the slot is already `None`. Errors only when
4806 /// `segment_id` is out of bounds.
4807 pub fn tombstone_segment(&mut self, segment_id: u32) -> Result<(), StorageError> {
4808 let idx = segment_id as usize;
4809 if idx >= self.cold_segments.len() {
4810 return Err(StorageError::Corrupt(format!(
4811 "tombstone_segment: segment_id {segment_id} out of bounds (len={})",
4812 self.cold_segments.len()
4813 )));
4814 }
4815 self.cold_segments[idx] = None;
4816 Ok(())
4817 }
4818
4819 /// Number of *active* (non-tombstoned) cold segments.
4820 #[must_use]
4821 pub fn cold_segment_count(&self) -> usize {
4822 self.cold_segments.iter().filter(|s| s.is_some()).count()
4823 }
4824
4825 /// Slot count including tombstones (= the next id the
4826 /// no-arg `load_segment_bytes` would allocate).
4827 #[must_use]
4828 pub fn cold_segment_slot_count(&self) -> usize {
4829 self.cold_segments.len()
4830 }
4831
4832 /// v6.2.7 — list every *active* cold-tier segment id known to
4833 /// this catalog (skips compaction tombstones since v6.7.3).
4834 /// Used by EXPLAIN ANALYZE to annotate scan nodes with the
4835 /// segments they could have walked.
4836 #[must_use]
4837 pub fn cold_segment_ids_global(&self) -> Vec<u32> {
4838 self.cold_segments
4839 .iter()
4840 .enumerate()
4841 .filter_map(|(i, s)| s.as_ref().map(|_| i as u32))
4842 .collect()
4843 }
4844
4845 /// v5.2.1: sum of `Table::hot_bytes` across every table. The v5.2
4846 /// freezer compares this against `SPG_HOT_TIER_BYTES` (parsed at
4847 /// server startup; default 4 GiB) and wakes when the budget is
4848 /// crossed. Pre-freezer (v5.2.1) this is measurement-only — the
4849 /// counter exposes whether the budget is being approached without
4850 /// triggering any demotion.
4851 #[must_use]
4852 pub fn hot_tier_bytes(&self) -> u64 {
4853 self.tables
4854 .iter()
4855 .map(Table::hot_bytes)
4856 .fold(0u64, u64::saturating_add)
4857 }
4858
4859 /// v5.2.2: freeze the **first** `max_rows` rows of `table_name`'s
4860 /// hot tier into a brand-new cold-tier segment. The named `BTree`
4861 /// index supplies the per-row PK (its column must be an integer
4862 /// type — v5.2.2 only supports `IndexKey::Int` PKs, matching the
4863 /// `index_key_as_u64` constraint used by the cold-tier lookup
4864 /// path). On success returns a [`FreezeReport`] with the
4865 /// freshly-allocated segment id, the count of rows that moved,
4866 /// the encoded segment bytes (so the caller can persist them to
4867 /// disk for later reload via `SPG_PRELOAD_COLD_SEGMENT`), and the
4868 /// hot-tier byte delta that was reclaimed.
4869 ///
4870 /// **Semantics**:
4871 /// 1. The first `max_rows` rows (by hot-tier position — same as
4872 /// insertion order under v4.39 `PersistentVec`) are read.
4873 /// 2. Rows are sorted ascending by PK and serialised into a new
4874 /// segment via [`encode_segment`].
4875 /// 3. The hot rows are dropped via [`Table::delete_rows`]; the
4876 /// `rebuild_indices` it triggers regenerates `Hot` locators
4877 /// for every remaining row (their positions shift down by
4878 /// `max_rows`). Existing `Cold` locators in this index — from
4879 /// a previous freeze — are also rebuilt **but with empty
4880 /// payload** since rebuild reads only `self.rows`; this
4881 /// routine re-registers them at the end of the call so the
4882 /// user-visible state preserves all prior cold locators.
4883 /// 4. The new segment is loaded into `self.cold_segments` via
4884 /// [`Catalog::load_segment_bytes`] (allocating a fresh
4885 /// `segment_id`). New `Cold` locators are registered on the
4886 /// named index — one per frozen row.
4887 ///
4888 /// **v5.2.2 limits** (relaxed in later sub-versions):
4889 /// - INSERT-only flow: subsequent UPDATE/DELETE on a frozen row
4890 /// returns a stale-locator error (no promote-on-write until
4891 /// v5.2.3).
4892 /// - Single-table scope: callers iterate tables themselves.
4893 /// - All-or-nothing: returns `Err` and leaves catalog unchanged
4894 /// if any step fails before the atomic swap point.
4895 ///
4896 /// Errors:
4897 /// - [`StorageError::Corrupt`] for missing table/index, non-`BTree`
4898 /// index, non-integer PK column, `max_rows == 0`, or
4899 /// `max_rows > row_count`.
4900 /// - The encoder's [`SegmentError`] surfaces as `Corrupt` (the
4901 /// only realistic source is "a single row is larger than the
4902 /// page size"; SPG schemas don't hit it in practice).
4903 pub fn freeze_oldest_to_cold(
4904 &mut self,
4905 table_name: &str,
4906 index_name: &str,
4907 max_rows: usize,
4908 ) -> Result<FreezeReport, StorageError> {
4909 // --- validation phase: never mutates ---------------------
4910 if max_rows == 0 {
4911 return Err(StorageError::Corrupt(
4912 "freeze_oldest_to_cold: max_rows must be > 0".into(),
4913 ));
4914 }
4915 let table = self.get(table_name).ok_or_else(|| {
4916 StorageError::Corrupt(format!(
4917 "freeze_oldest_to_cold: table {table_name:?} not found"
4918 ))
4919 })?;
4920 if max_rows > table.rows.len() {
4921 return Err(StorageError::Corrupt(format!(
4922 "freeze_oldest_to_cold: max_rows {max_rows} > row_count {}",
4923 table.rows.len()
4924 )));
4925 }
4926 let idx = table
4927 .indices
4928 .iter()
4929 .find(|i| i.name == index_name)
4930 .ok_or_else(|| {
4931 StorageError::Corrupt(format!(
4932 "freeze_oldest_to_cold: index {index_name:?} not found on {table_name:?}"
4933 ))
4934 })?;
4935 if !matches!(idx.kind, IndexKind::BTree(_)) {
4936 return Err(StorageError::Corrupt(format!(
4937 "freeze_oldest_to_cold: index {index_name:?} is NSW; only BTree indices may freeze"
4938 )));
4939 }
4940 let column_position = idx.column_position;
4941
4942 // --- segment build phase: reads only --------------------
4943 let schema = table.schema.clone();
4944 let mut to_freeze: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(max_rows);
4945 for row_idx in 0..max_rows {
4946 let row = table.rows.get(row_idx).expect("bounds-checked above");
4947 let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
4948 StorageError::Corrupt(format!(
4949 "freeze_oldest_to_cold: row {row_idx} has NULL / non-key value in index column"
4950 ))
4951 })?;
4952 let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
4953 StorageError::Corrupt(format!(
4954 "freeze_oldest_to_cold: index {index_name:?} column type is non-integer; \
4955 v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
4956 ))
4957 })?;
4958 to_freeze.push((pk_u64, encode_row_body_dense(row, &schema), key));
4959 }
4960 // encode_segment requires ascending u64 keys. Sort by PK
4961 // before encoding; the caller's row-position order is not
4962 // necessarily PK order (e.g. workloads that insert random
4963 // PKs).
4964 to_freeze.sort_by_key(|(k, _, _)| *k);
4965 // Reject duplicate PKs — encode_segment also rejects them
4966 // (`SegmentError::UnsortedKey`), but the resulting error
4967 // message there is misleading. Surface a clearer one.
4968 for w in to_freeze.windows(2) {
4969 if w[0].0 == w[1].0 {
4970 return Err(StorageError::Corrupt(format!(
4971 "freeze_oldest_to_cold: duplicate PK {} in freeze batch",
4972 w[0].0
4973 )));
4974 }
4975 }
4976 // Snapshot the (key, locator) pairs that will be registered
4977 // post-swap. Cloning the IndexKey out before the move makes
4978 // the registration loop borrow-free.
4979 let post_swap_keys: Vec<IndexKey> = to_freeze.iter().map(|(_, _, k)| k.clone()).collect();
4980 // Segment encode is now infallible w.r.t. ordering. Map the
4981 // `SegmentError` into a `StorageError::Corrupt` so the
4982 // public surface stays one error type.
4983 let seg_rows: Vec<(u64, Vec<u8>)> = to_freeze
4984 .into_iter()
4985 .map(|(k, body, _)| (k, body))
4986 .collect();
4987 let frozen_rows = seg_rows.len();
4988 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
4989 .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: encode: {e}")))?;
4990
4991 // --- atomic swap phase: mutations only past this point ---
4992 // v5.2.3 made `Table::rebuild_indices` preserve every Cold
4993 // locator across the per-table rebuild, so `delete_rows`
4994 // below no longer wipes prior-freeze cold entries. The pre-
4995 // v5.2.3 capture-then-re-register that used to live here
4996 // was removed in v5.3.1 — keeping it would double-count
4997 // every prior-frozen key's Cold locator on each subsequent
4998 // freeze.
4999 let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
5000 let positions: Vec<usize> = (0..max_rows).collect();
5001 let t_mut = self
5002 .get_mut(table_name)
5003 .expect("just validated; still present");
5004 let removed = t_mut.delete_rows(&positions);
5005 debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
5006 let bytes_after = t_mut.hot_bytes();
5007 let bytes_freed = bytes_before.saturating_sub(bytes_after);
5008
5009 let segment_id = self
5010 .load_segment_bytes(seg_bytes.clone())
5011 .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: load: {e}")))?;
5012 let new_cold = post_swap_keys.into_iter().map(|k| {
5013 (
5014 k,
5015 RowLocator::Cold {
5016 segment_id,
5017 page_offset: 0,
5018 },
5019 )
5020 });
5021 let t_mut = self.get_mut(table_name).expect("still present");
5022 t_mut.register_cold_locators(index_name, new_cold)?;
5023
5024 Ok(FreezeReport {
5025 segment_id,
5026 frozen_rows,
5027 bytes_freed,
5028 segment_bytes: seg_bytes,
5029 })
5030 }
5031
5032 /// v5.1: borrow the cold segment at `segment_id`. Used by the
5033 /// spg-server preload path to enumerate (key, locator) pairs
5034 /// after loading a segment, so it can call
5035 /// [`Table::register_cold_locators`] without re-parsing the
5036 /// bytes.
5037 #[must_use]
5038 pub fn cold_segment(&self, segment_id: u32) -> Option<&OwnedSegment> {
5039 self.cold_segments
5040 .get(segment_id as usize)
5041 .and_then(|s| s.as_deref())
5042 }
5043
5044 /// v5.1: resolve a single `RowLocator::Cold` to its underlying
5045 /// `Row`. Decoupled from [`Catalog::lookup_by_pk`] so callers
5046 /// iterating a multi-locator slice (e.g. the engine's index
5047 /// seek path) can dispatch per locator instead of getting back
5048 /// only the first row for a key. Returns `None` when the
5049 /// segment isn't registered, the key isn't `u64`-coercible, or
5050 /// the segment doesn't actually carry the key (bloom or page-
5051 /// index reject).
5052 pub fn resolve_cold_locator(
5053 &self,
5054 table_name: &str,
5055 segment_id: u32,
5056 key: &IndexKey,
5057 ) -> Option<Row> {
5058 let t = self.get(table_name)?;
5059 let u64_key = index_key_as_u64(key)?;
5060 let seg = self.cold_segments.get(segment_id as usize)?.as_ref()?;
5061 let payload = seg.lookup(u64_key)?;
5062 let (row, _) = decode_row_body_dense(&payload, &t.schema).ok()?;
5063 Some(row)
5064 }
5065
5066 /// v5.1: indexed PK lookup that dispatches per locator,
5067 /// returning the first matching row from either the hot tier
5068 /// (`Table::rows`) or a registered cold segment.
5069 ///
5070 /// The cold path requires the index column to be coercible to
5071 /// a `u64` (the segment's PK type) and the segment payload to
5072 /// be a [`encode_row_body_dense`]-encoded row body for the
5073 /// same schema. v5.1 ships this for BIGINT / INT / SMALLINT
5074 /// PKs; other types fall through to hot-only behavior.
5075 ///
5076 /// Returns `None` if (a) the table or index doesn't exist,
5077 /// (b) the key isn't in the index at all, or (c) the key was
5078 /// resolved to a stale locator (Hot index out of range, Cold
5079 /// segment id unknown, segment lookup miss). Does not surface
5080 /// segment-decode errors — those would indicate corrupted
5081 /// cold-tier files and should be caught at
5082 /// [`Catalog::load_segment_bytes`] time.
5083 pub fn lookup_by_pk(&self, table: &str, index_name: &str, key: &IndexKey) -> Option<Row> {
5084 let t = self.get(table)?;
5085 let idx = t.indices.iter().find(|i| i.name == index_name)?;
5086 let locators = idx.lookup_eq(key);
5087 let cold_u64_key = index_key_as_u64(key);
5088 for loc in locators {
5089 match *loc {
5090 RowLocator::Hot(i) => {
5091 if let Some(row) = t.rows.get(i) {
5092 return Some(row.clone());
5093 }
5094 }
5095 RowLocator::Cold {
5096 segment_id,
5097 page_offset: _,
5098 } => {
5099 let Some(u64_key) = cold_u64_key else {
5100 // Key type not coercible to u64 — cold tier
5101 // only handles BIGINT/INT/SMALLINT in v5.1.
5102 continue;
5103 };
5104 let Some(seg) = self
5105 .cold_segments
5106 .get(segment_id as usize)
5107 .and_then(|s| s.as_deref())
5108 else {
5109 // v6.7.3 — `None` slot = compaction
5110 // retired this segment; the live locator
5111 // on a freshly-compacted index points to
5112 // the merged segment_id, so a Cold hit
5113 // here against a tombstone means the BTree
5114 // entry hasn't been swapped yet (mid-
5115 // compaction reader race) or the caller is
5116 // looking up a stale snapshot. Skip — the
5117 // next locator in the list, if any, is
5118 // typically the merged segment.
5119 continue;
5120 };
5121 let Some(payload) = seg.lookup(u64_key) else {
5122 continue;
5123 };
5124 let (row, _) = decode_row_body_dense(&payload, &t.schema).ok()?;
5125 return Some(row);
5126 }
5127 }
5128 }
5129 None
5130 }
5131
5132 /// v5.2.3: promote a frozen row back to the hot tier so an
5133 /// UPDATE / DELETE can mutate it. Reads the cold-tier row body
5134 /// (decoded from its registered segment), pushes it into
5135 /// `table.rows` via [`Table::insert`] (which also adds a fresh
5136 /// `Hot(new_idx)` locator on `index_name`), then retires the
5137 /// shadowed `Cold` locator via
5138 /// [`Table::remove_cold_locators_for_key`]. The cold-tier row
5139 /// in the segment file becomes garbage — recoverable when a
5140 /// future cold-segment compaction job lands.
5141 ///
5142 /// Returns:
5143 /// - `Ok(Some(new_hot_idx))` when the key resolved through a
5144 /// cold locator and the promote completed. `new_hot_idx` is
5145 /// the position the row now occupies in `table.rows`.
5146 /// - `Ok(None)` when the key has no Cold locator on the index
5147 /// (already hot, or wasn't present at all). Callers treat this
5148 /// as "nothing to do here, fall back to the hot-only path".
5149 ///
5150 /// Errors when the table / index doesn't exist, the index isn't
5151 /// `BTree`, the cold segment is missing / can't decode the row,
5152 /// or the inferred row body fails `Table::insert` validation.
5153 pub fn promote_cold_row(
5154 &mut self,
5155 table_name: &str,
5156 index_name: &str,
5157 key: &IndexKey,
5158 ) -> Result<Option<usize>, StorageError> {
5159 let cold_loc = self.find_cold_locator(table_name, index_name, key)?;
5160 let Some((segment_id, _page_offset)) = cold_loc else {
5161 return Ok(None);
5162 };
5163 let u64_key = index_key_as_u64(key).ok_or_else(|| {
5164 StorageError::Corrupt(
5165 "promote_cold_row: key type not coercible to u64 (cold tier requires integer PK)"
5166 .into(),
5167 )
5168 })?;
5169 // Read the row body from the segment. Borrow the segment +
5170 // schema short-term so we can then take `&mut self` for the
5171 // hot-side insert.
5172 let schema = self
5173 .get(table_name)
5174 .ok_or_else(|| {
5175 StorageError::Corrupt(format!("promote_cold_row: table {table_name:?} not found"))
5176 })?
5177 .schema
5178 .clone();
5179 let seg = self
5180 .cold_segments
5181 .get(segment_id as usize)
5182 .and_then(|s| s.as_ref())
5183 .ok_or_else(|| {
5184 StorageError::Corrupt(format!(
5185 "promote_cold_row: segment {segment_id} not registered on catalog"
5186 ))
5187 })?;
5188 let payload = seg.lookup(u64_key).ok_or_else(|| {
5189 StorageError::Corrupt(format!(
5190 "promote_cold_row: key {u64_key} resolves to segment {segment_id} \
5191 but the segment's bloom/page lookup didn't return a row"
5192 ))
5193 })?;
5194 let (row, _consumed) = decode_row_body_dense(&payload, &schema)?;
5195 // Insert the promoted row into the hot tier. `Table::insert`
5196 // appends to `self.rows`, adds a `Hot(new_idx)` locator to
5197 // every BTree index covering the row's keyed columns, and
5198 // increments `hot_bytes`.
5199 let t = self
5200 .get_mut(table_name)
5201 .expect("table existed at lookup time");
5202 t.insert(row)?;
5203 let new_hot_idx =
5204 t.rows.len().checked_sub(1).ok_or_else(|| {
5205 StorageError::Corrupt("promote_cold_row: empty after insert".into())
5206 })?;
5207 // The hot insert added Hot(new_idx) alongside the still-
5208 // present Cold locator. Drop the Cold entry so future
5209 // lookups return only the fresh hot row.
5210 t.remove_cold_locators_for_key(index_name, key)?;
5211 Ok(Some(new_hot_idx))
5212 }
5213
5214 /// v5.2.3: shadow a frozen row's index entry. Used by DELETE
5215 /// when the row to remove lives in a cold-tier segment — the
5216 /// row body stays in the segment file (becoming garbage) but
5217 /// every `Cold` locator for `key` on `index_name` is removed
5218 /// so PK lookups stop returning it.
5219 ///
5220 /// Returns the number of cold locators retired (0 when the key
5221 /// has no cold entries — the DELETE fell on a hot row or a
5222 /// key that was already absent). Errors when the table /
5223 /// index doesn't exist or the index isn't `BTree`.
5224 ///
5225 /// Cold-segment compaction (which merges shadowed-heavy
5226 /// segments and reclaims their disk footprint) lands in a
5227 /// later v5.x sub-version; until then, repeated UPDATE/DELETE
5228 /// of cold rows can amplify cold-segment disk usage by up to
5229 /// 1-2× — still well under typical LSM-tree shadowing because
5230 /// SPG segments are bulk-baked, not write-merged.
5231 pub fn shadow_cold_row(
5232 &mut self,
5233 table_name: &str,
5234 index_name: &str,
5235 key: &IndexKey,
5236 ) -> Result<usize, StorageError> {
5237 let t = self.get_mut(table_name).ok_or_else(|| {
5238 StorageError::Corrupt(format!("shadow_cold_row: table {table_name:?} not found"))
5239 })?;
5240 t.remove_cold_locators_for_key(index_name, key)
5241 }
5242
5243 /// v6.7.4 — read-only slice preparation for the parallel
5244 /// freezer. Walks rows in `row_range`, builds the
5245 /// `(pk_u64, encoded_body, IndexKey)` triples that the
5246 /// coordinator's k-way merge consumes, sorts the slice by
5247 /// `pk_u64`, and returns a [`FreezeSlice`].
5248 ///
5249 /// Caller invariants:
5250 /// - `row_range.end <= table.rows.len()` (caller's job to
5251 /// compute the partition).
5252 /// - All slices passed to `commit_freeze_slices` must cover a
5253 /// contiguous half-open range `[0, total_max_rows)` with no
5254 /// gaps and no overlaps. The coordinator validates this
5255 /// invariant before committing.
5256 ///
5257 /// `&self`-only — multiple workers can run this concurrently
5258 /// against the same `Catalog` reference under the engine's
5259 /// write lock (workers don't mutate; the coordinator does).
5260 pub fn prepare_freeze_slice(
5261 &self,
5262 table_name: &str,
5263 index_name: &str,
5264 row_range: core::ops::Range<usize>,
5265 ) -> Result<FreezeSlice, StorageError> {
5266 let table = self.get(table_name).ok_or_else(|| {
5267 StorageError::Corrupt(format!(
5268 "prepare_freeze_slice: table {table_name:?} not found"
5269 ))
5270 })?;
5271 let idx = table
5272 .indices
5273 .iter()
5274 .find(|i| i.name == index_name)
5275 .ok_or_else(|| {
5276 StorageError::Corrupt(format!(
5277 "prepare_freeze_slice: index {index_name:?} not found on {table_name:?}"
5278 ))
5279 })?;
5280 if !matches!(idx.kind, IndexKind::BTree(_)) {
5281 return Err(StorageError::Corrupt(format!(
5282 "prepare_freeze_slice: index {index_name:?} is NSW; only BTree indices may freeze"
5283 )));
5284 }
5285 if row_range.end > table.rows.len() {
5286 return Err(StorageError::Corrupt(format!(
5287 "prepare_freeze_slice: row_range end {} > row_count {}",
5288 row_range.end,
5289 table.rows.len()
5290 )));
5291 }
5292 let column_position = idx.column_position;
5293 let schema = table.schema.clone();
5294 let mut rows: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(row_range.len());
5295 for row_idx in row_range.clone() {
5296 let row = table.rows.get(row_idx).expect("bounds-checked above");
5297 let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
5298 StorageError::Corrupt(format!(
5299 "prepare_freeze_slice: row {row_idx} has NULL / non-key value in index column"
5300 ))
5301 })?;
5302 let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
5303 StorageError::Corrupt(format!(
5304 "prepare_freeze_slice: index {index_name:?} column type is non-integer; \
5305 v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
5306 ))
5307 })?;
5308 rows.push((pk_u64, encode_row_body_dense(row, &schema), key));
5309 }
5310 rows.sort_by_key(|(k, _, _)| *k);
5311 Ok(FreezeSlice { row_range, rows })
5312 }
5313
5314 /// v6.7.4 — coordinator commit step. Merges N
5315 /// [`FreezeSlice`]s into one segment via the standard
5316 /// [`encode_segment`] path, atomically swaps the catalog
5317 /// state (delete the union row range + register Cold
5318 /// locators + load the segment).
5319 ///
5320 /// Validates that the slices cover a contiguous, gap-free,
5321 /// overlap-free half-open range starting at index 0 (the
5322 /// freezer always freezes "oldest first" — same semantics as
5323 /// the single-threaded [`Catalog::freeze_oldest_to_cold`]).
5324 ///
5325 /// Empty `slices` → no-op success (returns a zero-row report
5326 /// without mutating). Total row count = `Σ slice.rows.len()`.
5327 pub fn commit_freeze_slices(
5328 &mut self,
5329 table_name: &str,
5330 index_name: &str,
5331 slices: Vec<FreezeSlice>,
5332 ) -> Result<FreezeReport, StorageError> {
5333 // --- validation phase: never mutates ---------------------
5334 let table = self.get(table_name).ok_or_else(|| {
5335 StorageError::Corrupt(format!(
5336 "commit_freeze_slices: table {table_name:?} not found"
5337 ))
5338 })?;
5339 let idx = table
5340 .indices
5341 .iter()
5342 .find(|i| i.name == index_name)
5343 .ok_or_else(|| {
5344 StorageError::Corrupt(format!(
5345 "commit_freeze_slices: index {index_name:?} not found on {table_name:?}"
5346 ))
5347 })?;
5348 if !matches!(idx.kind, IndexKind::BTree(_)) {
5349 return Err(StorageError::Corrupt(format!(
5350 "commit_freeze_slices: index {index_name:?} is NSW; only BTree indices may freeze"
5351 )));
5352 }
5353 // Validate slice coverage: contiguous from 0, no gaps, no
5354 // overlaps. Allow the caller to pass slices in any order —
5355 // sort by row_range.start first.
5356 let mut ordered = slices;
5357 ordered.sort_by_key(|s| s.row_range.start);
5358 // Drop fully-empty slices that fell out of an uneven
5359 // partition; they carry no data but contribute to the
5360 // contiguity check, so keep them in line.
5361 let mut expected_start = 0usize;
5362 for s in &ordered {
5363 if s.row_range.start != expected_start {
5364 return Err(StorageError::Corrupt(format!(
5365 "commit_freeze_slices: gap/overlap at row {}; expected start {}",
5366 s.row_range.start, expected_start
5367 )));
5368 }
5369 expected_start = s.row_range.end;
5370 }
5371 let max_rows = expected_start;
5372 if max_rows > table.rows.len() {
5373 return Err(StorageError::Corrupt(format!(
5374 "commit_freeze_slices: total row range {} exceeds row_count {}",
5375 max_rows,
5376 table.rows.len()
5377 )));
5378 }
5379 if max_rows == 0 {
5380 return Ok(FreezeReport {
5381 segment_id: u32::MAX,
5382 frozen_rows: 0,
5383 bytes_freed: 0,
5384 segment_bytes: Vec::new(),
5385 });
5386 }
5387
5388 // --- segment build phase: reads only --------------------
5389 // K-way merge of already-sorted slices. Each slice's rows
5390 // are ascending by pk_u64; we keep a per-slice cursor and
5391 // pull the next-smallest head until every cursor drains.
5392 let total_rows: usize = ordered.iter().map(|s| s.rows.len()).sum();
5393 if total_rows != max_rows {
5394 return Err(StorageError::Corrupt(format!(
5395 "commit_freeze_slices: total slice rows {total_rows} ≠ row_range coverage {max_rows}"
5396 )));
5397 }
5398 let mut cursors: Vec<usize> = alloc::vec![0; ordered.len()];
5399 let mut merged: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(total_rows);
5400 loop {
5401 // Pick the slice whose head row has the smallest key
5402 // and isn't yet exhausted.
5403 let mut pick: Option<usize> = None;
5404 for (i, c) in cursors.iter().enumerate() {
5405 let slice = &ordered[i];
5406 if *c >= slice.rows.len() {
5407 continue;
5408 }
5409 match pick {
5410 None => pick = Some(i),
5411 Some(j) => {
5412 if slice.rows[*c].0 < ordered[j].rows[cursors[j]].0 {
5413 pick = Some(i);
5414 }
5415 }
5416 }
5417 }
5418 let Some(i) = pick else { break };
5419 let row = ordered[i].rows[cursors[i]].clone();
5420 cursors[i] += 1;
5421 merged.push(row);
5422 }
5423 // Reject duplicate PKs — same error as the single-threaded
5424 // path so callers get a uniform surface.
5425 for w in merged.windows(2) {
5426 if w[0].0 == w[1].0 {
5427 return Err(StorageError::Corrupt(format!(
5428 "commit_freeze_slices: duplicate PK {} across slices",
5429 w[0].0
5430 )));
5431 }
5432 }
5433 let post_swap_keys: Vec<IndexKey> = merged.iter().map(|(_, _, k)| k.clone()).collect();
5434 let seg_rows: Vec<(u64, Vec<u8>)> =
5435 merged.into_iter().map(|(k, body, _)| (k, body)).collect();
5436 let frozen_rows = seg_rows.len();
5437 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
5438 .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: encode: {e}")))?;
5439
5440 // --- atomic swap phase: mutations only past this point ---
5441 let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
5442 let positions: Vec<usize> = (0..max_rows).collect();
5443 let t_mut = self
5444 .get_mut(table_name)
5445 .expect("just validated; still present");
5446 let removed = t_mut.delete_rows(&positions);
5447 debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
5448 let bytes_after = t_mut.hot_bytes();
5449 let bytes_freed = bytes_before.saturating_sub(bytes_after);
5450
5451 let segment_id = self
5452 .load_segment_bytes(seg_bytes.clone())
5453 .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: load: {e}")))?;
5454 let new_cold = post_swap_keys.into_iter().map(|k| {
5455 (
5456 k,
5457 RowLocator::Cold {
5458 segment_id,
5459 page_offset: 0,
5460 },
5461 )
5462 });
5463 let t_mut = self.get_mut(table_name).expect("still present");
5464 t_mut.register_cold_locators(index_name, new_cold)?;
5465
5466 Ok(FreezeReport {
5467 segment_id,
5468 frozen_rows,
5469 bytes_freed,
5470 segment_bytes: seg_bytes,
5471 })
5472 }
5473
5474 /// v6.7.3 — compact every cold segment on `(table, index)` whose
5475 /// `OwnedSegment::bytes().len()` is below `target_segment_bytes`
5476 /// into a single larger merged segment. Rows present in source
5477 /// segment payloads but no longer referenced by any
5478 /// `RowLocator::Cold` on the index (DELETE'd + frozen rows
5479 /// retired via [`Catalog::shadow_cold_row`]) are GC'd in the
5480 /// merge.
5481 ///
5482 /// **Semantics**:
5483 /// 1. Walk the BTree index to collect every Cold locator that
5484 /// targets a small (< threshold) segment. Each such
5485 /// `(key, segment_id)` becomes a row in the merged segment;
5486 /// payload is looked up from the source segment in-place.
5487 /// 2. Encode the collected rows into one new segment via
5488 /// [`encode_segment`]; register it via
5489 /// [`Catalog::load_segment_bytes`] (allocating a fresh
5490 /// `merged_segment_id` at the end of `cold_segments`).
5491 /// 3. Rewrite the BTree index in one pass: every
5492 /// `RowLocator::Cold { segment_id ∈ sources }` becomes
5493 /// `RowLocator::Cold { segment_id = merged_id, page_offset = 0 }`.
5494 /// Hot locators are untouched.
5495 /// 4. Tombstone every source slot via
5496 /// [`Catalog::tombstone_segment`]. Source segment payloads
5497 /// are no longer reachable through the catalog; the on-disk
5498 /// files are the caller's concern.
5499 ///
5500 /// On fewer than 2 candidate segments the catalog is **not**
5501 /// mutated and a no-op report (`merged_segment_id: None`,
5502 /// `sources: []`) is returned. This is the routine case — a
5503 /// freshly-frozen table has at most 1 small segment, no merge
5504 /// possible.
5505 ///
5506 /// Atomicity: every mutating step runs after the read-only
5507 /// gather phase, so a panic before the merge encode leaves the
5508 /// catalog unchanged. The mutation block itself (load + rewrite +
5509 /// tombstone) takes only `&mut self` — callers serialise the
5510 /// engine write lock outside this function.
5511 ///
5512 /// Errors when the table / index doesn't exist, the index isn't
5513 /// `BTree`, the index column type isn't u64-coercible (cold-tier
5514 /// pre-condition), or a source segment fails its in-place
5515 /// row-body lookup (would indicate prior catalog corruption).
5516 pub fn compact_cold_segments(
5517 &mut self,
5518 table_name: &str,
5519 index_name: &str,
5520 target_segment_bytes: u64,
5521 ) -> Result<CompactReport, StorageError> {
5522 // --- validation phase ----------------------------------
5523 let t = self.get(table_name).ok_or_else(|| {
5524 StorageError::Corrupt(format!(
5525 "compact_cold_segments: table {table_name:?} not found"
5526 ))
5527 })?;
5528 let idx = t
5529 .indices
5530 .iter()
5531 .find(|i| i.name == index_name)
5532 .ok_or_else(|| {
5533 StorageError::Corrupt(format!(
5534 "compact_cold_segments: index {index_name:?} not found on {table_name:?}"
5535 ))
5536 })?;
5537 let map = match &idx.kind {
5538 IndexKind::BTree(m) => m,
5539 IndexKind::Nsw(_)
5540 | IndexKind::Brin { .. }
5541 | IndexKind::Gin(_)
5542 | IndexKind::GinTrgm(_)
5543 | IndexKind::GinFulltext(_) => {
5544 return Err(StorageError::Corrupt(format!(
5545 "compact_cold_segments: index {index_name:?} is not BTree; \
5546 compaction applies only to BTree cold-tier indices"
5547 )));
5548 }
5549 };
5550
5551 // --- gather phase --------------------------------------
5552 // Step A: every segment_id this BTree index Cold-references.
5553 let mut referenced_ids: BTreeSet<u32> = BTreeSet::new();
5554 for (_key, locators) in map.iter() {
5555 for loc in locators {
5556 if let RowLocator::Cold { segment_id, .. } = loc {
5557 referenced_ids.insert(*segment_id);
5558 }
5559 }
5560 }
5561 // Step B: keep only the small + still-active ones.
5562 let candidate_set: BTreeSet<u32> = referenced_ids
5563 .into_iter()
5564 .filter(|id| {
5565 self.cold_segments
5566 .get(*id as usize)
5567 .and_then(|s| s.as_deref())
5568 .is_some_and(|s| (s.bytes().len() as u64) < target_segment_bytes)
5569 })
5570 .collect();
5571 if candidate_set.len() < 2 {
5572 return Ok(CompactReport {
5573 sources: Vec::new(),
5574 merged_segment_id: None,
5575 merged_segment_bytes: Vec::new(),
5576 merged_rows: 0,
5577 deleted_rows_pruned: 0,
5578 bytes_reclaimed_estimate: 0,
5579 });
5580 }
5581 // Step C: pre-count source rows for the deleted-pruned metric.
5582 let mut source_row_count: usize = 0;
5583 let mut source_byte_total: u64 = 0;
5584 for &id in &candidate_set {
5585 let seg = self.cold_segments[id as usize]
5586 .as_ref()
5587 .expect("candidate selected only when slot is Some");
5588 source_row_count = source_row_count.saturating_add(seg.meta().num_rows as usize);
5589 source_byte_total = source_byte_total.saturating_add(seg.bytes().len() as u64);
5590 }
5591 // Step D: collect (key, body) pairs from every live Cold
5592 // locator pointing at a candidate. dedupe by key — one
5593 // BTree key resolves to at most one cold payload (the
5594 // freezer + promote/shadow flow keeps Cold locators
5595 // unique per key).
5596 let mut collected: BTreeMap<u64, (Vec<u8>, IndexKey)> = BTreeMap::new();
5597 for (key, locators) in map.iter() {
5598 for loc in locators {
5599 let RowLocator::Cold { segment_id, .. } = loc else {
5600 continue;
5601 };
5602 if !candidate_set.contains(segment_id) {
5603 continue;
5604 }
5605 let u64_key = index_key_as_u64(key).ok_or_else(|| {
5606 StorageError::Corrupt(format!(
5607 "compact_cold_segments: index {index_name:?} has non-integer Cold key; \
5608 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
5609 ))
5610 })?;
5611 let seg = self.cold_segments[*segment_id as usize]
5612 .as_ref()
5613 .expect("candidate slot guaranteed Some above");
5614 let payload = seg.lookup(u64_key).ok_or_else(|| {
5615 StorageError::Corrupt(format!(
5616 "compact_cold_segments: BTree {index_name:?} points key={u64_key} \
5617 at segment {segment_id} but the segment lookup missed"
5618 ))
5619 })?;
5620 collected.insert(u64_key, (payload, key.clone()));
5621 break;
5622 }
5623 }
5624 let merged_rows = collected.len();
5625 let deleted_rows_pruned = source_row_count.saturating_sub(merged_rows);
5626
5627 // Step E: encode the merged segment. `BTreeMap<u64, _>`
5628 // iteration is ascending by key, which is what
5629 // `encode_segment` requires.
5630 let seg_rows: Vec<(u64, Vec<u8>)> = collected
5631 .iter()
5632 .map(|(k, (body, _))| (*k, body.clone()))
5633 .collect();
5634 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
5635 .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: encode: {e}")))?;
5636 let merged_bytes_len = seg_bytes.len() as u64;
5637
5638 // --- atomic mutation phase ------------------------------
5639 let merged_segment_id = self
5640 .load_segment_bytes(seg_bytes.clone())
5641 .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: load: {e}")))?;
5642
5643 // Rewrite the BTree index: every Cold locator pointing at
5644 // a candidate source becomes a Cold locator pointing at
5645 // the merged segment. Use a flat collect-then-replace
5646 // pattern so we never hold a `&self` borrow across the
5647 // `&mut self` write.
5648 let entries: Vec<(IndexKey, Vec<RowLocator>)> = {
5649 let t = self
5650 .get(table_name)
5651 .expect("table existed at the start of this fn");
5652 let idx = t
5653 .indices
5654 .iter()
5655 .find(|i| i.name == index_name)
5656 .expect("index existed at the start of this fn");
5657 let IndexKind::BTree(map) = &idx.kind else {
5658 unreachable!("validated above");
5659 };
5660 map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
5661 };
5662 let t_mut = self
5663 .get_mut(table_name)
5664 .expect("table existed at the start of this fn");
5665 let idx_mut = t_mut
5666 .indices
5667 .iter_mut()
5668 .find(|i| i.name == index_name)
5669 .expect("index existed at the start of this fn");
5670 let IndexKind::BTree(map_mut) = &mut idx_mut.kind else {
5671 unreachable!("validated above");
5672 };
5673 for (key, locators) in entries {
5674 let mut new_locs: Vec<RowLocator> = Vec::with_capacity(locators.len());
5675 let mut changed = false;
5676 for loc in &locators {
5677 match *loc {
5678 RowLocator::Cold {
5679 segment_id,
5680 page_offset: _,
5681 } if candidate_set.contains(&segment_id) => {
5682 let replacement = RowLocator::Cold {
5683 segment_id: merged_segment_id,
5684 page_offset: 0,
5685 };
5686 if !new_locs.contains(&replacement) {
5687 new_locs.push(replacement);
5688 }
5689 changed = true;
5690 }
5691 other => new_locs.push(other),
5692 }
5693 }
5694 if changed {
5695 map_mut.insert_mut(key, new_locs);
5696 }
5697 }
5698
5699 // Tombstone every source slot. Last step — failures here
5700 // would leave the segment double-referenced in both
5701 // memory + manifest, but `tombstone_segment` only errors
5702 // on out-of-bounds, which we've already validated.
5703 for &id in &candidate_set {
5704 self.tombstone_segment(id)?;
5705 }
5706
5707 let bytes_reclaimed_estimate = source_byte_total.saturating_sub(merged_bytes_len);
5708 Ok(CompactReport {
5709 sources: candidate_set.into_iter().collect(),
5710 merged_segment_id: Some(merged_segment_id),
5711 merged_segment_bytes: seg_bytes,
5712 merged_rows,
5713 deleted_rows_pruned,
5714 bytes_reclaimed_estimate,
5715 })
5716 }
5717
5718 /// Internal helper: scan `(table, index)` for a `Cold` locator
5719 /// keyed by `key`. Returns `Ok(Some((segment_id, page_offset)))`
5720 /// when found, `Ok(None)` when the key has only hot entries
5721 /// or no entries at all, `Err` on the same input-validation
5722 /// errors as the public `promote_cold_row` / `shadow_cold_row`.
5723 fn find_cold_locator(
5724 &self,
5725 table_name: &str,
5726 index_name: &str,
5727 key: &IndexKey,
5728 ) -> Result<Option<(u32, u32)>, StorageError> {
5729 let t = self.get(table_name).ok_or_else(|| {
5730 StorageError::Corrupt(format!("find_cold_locator: table {table_name:?} not found"))
5731 })?;
5732 let idx = t
5733 .indices
5734 .iter()
5735 .find(|i| i.name == index_name)
5736 .ok_or_else(|| {
5737 StorageError::Corrupt(format!(
5738 "find_cold_locator: index {index_name:?} not found on {table_name:?}"
5739 ))
5740 })?;
5741 if !matches!(idx.kind, IndexKind::BTree(_)) {
5742 return Err(StorageError::Corrupt(format!(
5743 "find_cold_locator: index {index_name:?} is NSW; promote-on-write only applies to BTree indices"
5744 )));
5745 }
5746 for loc in idx.lookup_eq(key) {
5747 if let RowLocator::Cold {
5748 segment_id,
5749 page_offset,
5750 } = *loc
5751 {
5752 return Ok(Some((segment_id, page_offset)));
5753 }
5754 }
5755 Ok(None)
5756 }
5757}
5758
5759/// Coerce an [`IndexKey`] to the `u64` that v5.1 cold-tier
5760/// segments use as their on-disk PK. Returns `None` for keys that
5761/// aren't representable as `u64` — Text PKs need a hash mapping
5762/// the segment writer baked in (deferred to v5.2+), Bool PKs are
5763/// almost never wide enough to be sharded into a cold tier.
5764fn index_key_as_u64(key: &IndexKey) -> Option<u64> {
5765 match key {
5766 // Reinterpret the i64 bit pattern as u64. Cold-tier segments
5767 // are sorted by this u64 view, so the chosen interpretation
5768 // only has to match between insert (bake_segment / freezer)
5769 // and lookup — using cast_unsigned keeps both sides honest
5770 // and silences clippy::cast_sign_loss.
5771 IndexKey::Int(n) => Some(n.cast_unsigned()),
5772 // Text / Bool / Uuid PKs aren't representable as u64 and so
5773 // can't participate in the u64-sorted cold-tier segment
5774 // PK layout. Same deferral story as Text — lookup falls
5775 // through the in-memory btree.
5776 IndexKey::Text(_) | IndexKey::Bool(_) | IndexKey::Uuid(_) => None,
5777 }
5778}
5779
5780#[derive(Debug, Clone, PartialEq, Eq)]
5781#[non_exhaustive]
5782pub enum StorageError {
5783 DuplicateTable {
5784 name: String,
5785 },
5786 TableNotFound {
5787 name: String,
5788 },
5789 ArityMismatch {
5790 expected: usize,
5791 actual: usize,
5792 },
5793 TypeMismatch {
5794 column: String,
5795 expected: DataType,
5796 actual: DataType,
5797 position: usize,
5798 },
5799 NullInNotNull {
5800 column: String,
5801 },
5802 /// Index with this name already exists on the table.
5803 DuplicateIndex {
5804 name: String,
5805 },
5806 /// Column referenced by an index doesn't exist on the table.
5807 ColumnNotFound {
5808 column: String,
5809 },
5810 /// On-disk format failed to parse — corrupted file, wrong magic, truncated
5811 /// payload, or unknown tag bytes.
5812 Corrupt(String),
5813 /// v6.0.4 — ALTER INDEX targeted an index name that doesn't
5814 /// exist on any table in this catalog.
5815 IndexNotFound {
5816 name: String,
5817 },
5818 /// v6.0.4 — operation requested isn't supported on this index
5819 /// kind / column type (e.g. ALTER INDEX REBUILD on a `BTree`
5820 /// index, or REBUILD WITH (encoding=…) on a non-vector column).
5821 Unsupported(String),
5822}
5823
5824impl fmt::Display for StorageError {
5825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5826 match self {
5827 Self::DuplicateTable { name } => write!(f, "table already exists: {name}"),
5828 Self::TableNotFound { name } => write!(f, "table not found: {name}"),
5829 Self::ArityMismatch { expected, actual } => write!(
5830 f,
5831 "row arity mismatch: expected {expected} columns, got {actual}"
5832 ),
5833 Self::TypeMismatch {
5834 column,
5835 expected,
5836 actual,
5837 position,
5838 } => write!(
5839 f,
5840 "type mismatch in column {column:?} (position {position}): expected {expected}, got {actual}"
5841 ),
5842 Self::NullInNotNull { column } => {
5843 write!(f, "NULL value in NOT NULL column {column:?}")
5844 }
5845 Self::DuplicateIndex { name } => write!(f, "index already exists: {name}"),
5846 Self::ColumnNotFound { column } => write!(f, "column not found: {column}"),
5847 Self::Corrupt(detail) => write!(f, "corrupt on-disk format: {detail}"),
5848 Self::IndexNotFound { name } => write!(f, "index not found: {name}"),
5849 Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
5850 }
5851 }
5852}
5853
5854impl ColumnSchema {
5855 pub fn new(name: impl Into<String>, ty: DataType, nullable: bool) -> Self {
5856 Self {
5857 name: name.into(),
5858 ty,
5859 nullable,
5860 default: None,
5861 runtime_default: None,
5862 auto_increment: false,
5863 user_enum_type: None,
5864 user_domain_type: None,
5865 on_update_runtime: None,
5866 collation: Collation::Binary,
5867 is_unsigned: false,
5868 inline_enum_variants: None,
5869 inline_set_variants: None,
5870 }
5871 }
5872
5873 /// Builder-style helper to attach a default value to an otherwise
5874 /// plain column schema. Used by the engine when CREATE TABLE
5875 /// specifies `column TYPE DEFAULT <expr>`.
5876 #[must_use]
5877 pub fn with_default(mut self, default: Value) -> Self {
5878 self.default = Some(default);
5879 self
5880 }
5881
5882 /// v7.9.21 — builder for runtime-evaluated defaults
5883 /// (`DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`, …).
5884 /// `expr` is the Expr's `Display` form, re-parsed by the
5885 /// engine at each INSERT.
5886 #[must_use]
5887 pub fn with_runtime_default(mut self, expr: impl Into<String>) -> Self {
5888 self.runtime_default = Some(expr.into());
5889 self
5890 }
5891
5892 /// Builder-style helper to mark a column as `AUTO_INCREMENT`.
5893 #[must_use]
5894 pub const fn with_auto_increment(mut self) -> Self {
5895 self.auto_increment = true;
5896 self
5897 }
5898}
5899
5900impl TableSchema {
5901 pub fn new(name: impl Into<String>, columns: Vec<ColumnSchema>) -> Self {
5902 Self {
5903 name: name.into(),
5904 columns,
5905 hot_tier_bytes: None,
5906 foreign_keys: Vec::new(),
5907 uniqueness_constraints: Vec::new(),
5908 checks: Vec::new(),
5909 }
5910 }
5911}
5912
5913// =========================================================================
5914// Persistent binary format for the catalog.
5915//
5916// Layout (little-endian throughout):
5917//
5918// [magic "SPGDB001" 8 bytes][version u8]
5919// [table_count u32]
5920// for each table:
5921// [name_len u16][name bytes]
5922// [col_count u16]
5923// for each col:
5924// [name_len u16][name bytes]
5925// [type_tag u8 + optional payload]
5926// 1=Int 2=BigInt 3=Float 4=Text 5=Bool
5927// 6=Vector(u32 dim)
5928// 7=SmallInt
5929// 8=Varchar(u32 max)
5930// 9=Char(u32 size)
5931// 10=Numeric(u8 precision, u8 scale)
5932// 11=Date
5933// 12=Timestamp
5934// [nullable u8] 0/1
5935// [default_tag u8] 0=none 1=value (followed by [value_tag u8] + bytes)
5936// [row_count u32]
5937// for each row, for each col, one [value_tag u8] + value bytes:
5938// tag 0 (Null) → no body
5939// tag 1 (Int) → i32 LE
5940// tag 2 (BigInt) → i64 LE
5941// tag 3 (Float) → f64 LE
5942// tag 4 (Text) → u16 LE len + UTF-8 bytes
5943// tag 5 (Bool) → u8 0/1
5944// tag 6 (Vector) → u32 LE dim + dim×f32 LE
5945// tag 7 (SmallInt) → i16 LE
5946// tag 8 (Numeric) → i128 LE (16 bytes) + u8 scale
5947// tag 9 (Date) → i32 LE (days since Unix epoch)
5948// tag 10 (Timestamp) → i64 LE (microseconds since Unix epoch)
5949//
5950// Bumped to version 3 when NUMERIC was added; to version 4 when
5951// AUTO_INCREMENT (per-column flag) + NSW index `kind` byte landed;
5952// to version 5 when DATE / TIMESTAMP were added; to version 6 when
5953// NSW graph topology started travelling on disk (v2.7); to version 7
5954// when the NSW topology became multi-layer HNSW (v2.13); to version 8
5955// when row encoding switched to schema-driven dense layout (v3.0.2 —
5956// per-row NULL bitmap + per-column fixed-width body, no per-cell type
5957// tag).
5958// =========================================================================
5959
5960const FILE_MAGIC: &[u8; 8] = b"SPGDB001";
5961/// Current catalog snapshot format version emitted by [`Catalog::serialize`].
5962///
5963/// v9 (v5.2) extends v8 by serialising `BTree` index entries directly — every
5964/// `(IndexKey, Vec<RowLocator>)` pair travels on disk with the v5.1
5965/// `RowLocator::write_le` tag-prefixed codec. v8 `BTree` indices stored no
5966/// entries at all (the map was rebuilt from `Table::rows` on load); v9
5967/// preserves on-disk Cold locators so freezer-produced cold-tier index
5968/// entries survive a catalog snapshot round-trip. v8 readers are accepted
5969/// by version dispatch in [`Catalog::deserialize`] — every entry decodes
5970/// as `RowLocator::Hot(_)` via `add_index` rebuild, identical to v5.1
5971/// behaviour.
5972/// v6.7.2 — bumped from 10 to 11 to append per-table
5973/// `hot_tier_bytes: Option<u64>` after the per-table indices
5974/// section. v10 catalogs (v6.7.1) load with `hot_tier_bytes =
5975/// None` for every table (the deserialiser short-circuits when
5976/// version < 11). v11 snapshots written by a pre-v6.7.2 binary
5977/// fail loudly at the version check, matching the v6.1.2 /
5978/// v6.1.4 / v6.2.0 / v6.7.1 envelope-bump upgrade fences.
5979///
5980/// v6.8.0 — bumped from 11 to 12: per-index
5981/// `included_columns: Vec<u16>` appended at the tail of each
5982/// index payload. v11 (= v6.7.2) catalogs load with
5983/// `included_columns = Vec::new()` for every index — same
5984/// "older readers, append-only extension" pattern as the v6.7.2
5985/// hot_tier_bytes byte.
5986/// v7.13.0 — bumped from 22 to 23. mailrs round-5 G3 / G10.
5987/// Per-table appendix gains two new sections:
5988/// * `checks: Vec<String>` — CHECK predicate sources (Display
5989/// form of the AST Expr); re-parsed on INSERT/UPDATE to
5990/// enforce against candidate rows. Same persistence pattern
5991/// as `Index::partial_predicate`.
5992/// * Per `UniquenessConstraint`: trailing `nulls_not_distinct:
5993/// u8` flag for PG 15+ `UNIQUE NULLS NOT DISTINCT (cols)`
5994/// semantics.
5995/// v22 catalogs deserialise with empty `checks` and every UC
5996/// at `nulls_not_distinct = false`.
5997/// v24 introduces:
5998/// * Index kind tag 4 = trigram-GIN (`gin_trgm_ops`-flavoured
5999/// `USING gin` over a TEXT/VARCHAR column). Payload shape is
6000/// identical to tag-3 GIN (String → Vec<RowLocator>); the
6001/// keys are PG-compatible 3-byte trigram shingles instead of
6002/// tsvector lexemes. v23 catalogs deserialise unchanged — no
6003/// v23 writer ever emitted tag 4.
6004/// v25 introduces:
6005/// * Per `TriggerDef`: trailing `enabled: u8` flag (mailrs
6006/// round-9 A.2.b — `ALTER TABLE … { ENABLE | DISABLE }
6007/// TRIGGER …`). v24 catalogs deserialise with every trigger
6008/// `enabled = true`, matching pre-v7.16.1 behaviour.
6009/// v26 introduces (v7.17.0 Phase 1.1):
6010/// * Trailing SEQUENCE catalog block after triggers. Encoded
6011/// as `u32 count` followed by per-sequence:
6012/// `name`, `data_type: u8` (0=SmallInt,1=Int,2=BigInt),
6013/// `start i64`, `increment i64`, `min_value i64`,
6014/// `max_value i64`, `cache i64`, `cycle u8`,
6015/// `owned_by_tag u8` (0=NONE, 1=Column → `table`,`column`),
6016/// `last_value i64`, `is_called u8`. v25-and-below catalogs
6017/// deserialise with an empty sequences map.
6018/// v27 introduces (v7.17.0 Phase 1.2):
6019/// * Trailing VIEW catalog block after sequences. Encoded as
6020/// `u32 count` followed by per-view:
6021/// `name`, `column_count u16`, then column names, then
6022/// `body` long-string. v26-and-below catalogs deserialise
6023/// with an empty views map.
6024/// v28 introduces (v7.17.0 Phase 1.3):
6025/// * Trailing MATERIALIZED VIEW source registry block after
6026/// views. Encoded as `u32 count` followed by per-entry:
6027/// `name`, `body` long-string. The materialised rows live
6028/// as a regular Table of the same name (already covered by
6029/// the pre-existing tables block). v27-and-below catalogs
6030/// deserialise with an empty map.
6031/// v29 introduces (v7.17.0 Phase 1.4):
6032/// * Per-table user_enum_type appendix (after the CHECK
6033/// appendix). Layout: `u16 count` followed by per-binding
6034/// `[u16 col_pos][str enum_name]`. Only columns whose
6035/// `user_enum_type` is Some land here; the catalog stays
6036/// compact for the common no-enum case.
6037/// * Trailing ENUM types catalog block after materialized
6038/// views. Encoded as `u32 count` followed by per-entry:
6039/// `name`, `u16 label_count`, then `label_count` short
6040/// strings. v28-and-below catalogs deserialise with an
6041/// empty enum_types map and every column's
6042/// `user_enum_type = None`.
6043/// v30 introduces (v7.17.0 Phase 1.5):
6044/// * Per-table user_domain_type appendix (after the
6045/// user_enum_type appendix). Same shape as the enum one.
6046/// * Trailing DOMAIN types catalog block after the enum
6047/// block. Encoded as `u32 count` followed by per-entry:
6048/// `name`, `data_type` byte, `nullable u8`,
6049/// `default_present u8` + optional default string,
6050/// `u16 check_count` then `check_count` Display-form
6051/// CHECK strings. v29-and-below catalogs deserialise with
6052/// an empty domain_types map and `user_domain_type = None`.
6053/// v31 introduces (v7.17.0 Phase 1.6):
6054/// * Trailing user-schemas block after the DOMAIN block.
6055/// Encoded as `u32 count` followed by `count` schema-name
6056/// short strings. Built-in schemas (`public`, `pg_catalog`,
6057/// `information_schema`) are NOT serialised — they're
6058/// hardcoded in `is_builtin_schema`. v30-and-below catalogs
6059/// deserialise with an empty user-schemas set.
6060/// v32 introduces (v7.17.0 Phase 2.1):
6061/// * Per-table on_update_runtime appendix (after the
6062/// user_domain_type appendix). Layout: `u16 count` followed
6063/// by per-binding `[u16 col_pos][str expr_src]`. Only
6064/// columns whose `on_update_runtime` is Some land here;
6065/// the catalog stays compact when no MySQL-shaped table
6066/// uses the attribute. v31-and-below catalogs deserialise
6067/// with every column's `on_update_runtime = None`.
6068/// v33 introduces (v7.17.0 Phase 2.2):
6069/// * Index kind tag 5 = fulltext-GIN (MySQL `FULLTEXT KEY`
6070/// surface over a TEXT / VARCHAR column). Payload shape is
6071/// identical to tag-3 / tag-4 GIN (`String → Vec<RowLocator>`);
6072/// the keys are lower-cased word lexemes (same rule as
6073/// `to_tsvector('simple', text)`). v32 catalogs deserialise
6074/// unchanged — no v32 writer ever emitted tag 5, and FULLTEXT
6075/// KEY was silently dropped pre-v7.17 so no rebuild shim is
6076/// needed for round-tripped catalogs.
6077/// v34 introduces (v7.17.0 Phase 2.5):
6078/// * Per-table collation appendix (after the on_update_runtime
6079/// appendix). Sparse layout: only columns whose `collation`
6080/// is non-Binary land here. `u16 count` then per-binding
6081/// `[u16 col_pos][u8 collation_tag]` where the tag matches
6082/// `Collation::TAG_*`. Snapshots written by v33-and-below
6083/// readers deserialise every column with `collation =
6084/// Binary`, preserving the prior byte-wise compare
6085/// semantics. Unknown tags read back as Binary too — keeps
6086/// a forward-compat path if a future v35 adds variants
6087/// and someone rolls back to a v34 reader.
6088/// v35 introduces (v7.17.0 Phase 4.4):
6089/// * Per-table is_unsigned appendix (after the collation
6090/// appendix). Sparse layout: only `is_unsigned = true`
6091/// columns land. `u16 count` then per-binding `[u16 col_pos]`.
6092/// v34-and-below catalogs deserialise every column as
6093/// `is_unsigned = false`, preserving the prior silent-
6094/// accept behaviour for negative inserts on UNSIGNED columns.
6095const FILE_VERSION: u8 = 45;
6096/// Oldest format version [`Catalog::deserialize`] still accepts. v8 is the
6097/// v3.0.2 dense-row layout; pre-v8 catalogs require an offline migration.
6098const MIN_SUPPORTED_FILE_VERSION: u8 = 8;
6099
6100// IndexKey wire format (v9):
6101// tag 0 = Int → [i64 LE]
6102// tag 1 = Text → [u16 LE len + UTF-8 bytes] (via write_str / read_str)
6103// tag 2 = Bool → [u8 0/1]
6104const INDEX_KEY_TAG_INT: u8 = 0;
6105const INDEX_KEY_TAG_TEXT: u8 = 1;
6106const INDEX_KEY_TAG_BOOL: u8 = 2;
6107/// v7.17.0 — `IndexKey::Uuid([u8; 16])`. Body = raw 16 bytes
6108/// (RFC 4122 byte order). Persisted only in FILE_VERSION 36+
6109/// catalogs.
6110const INDEX_KEY_TAG_UUID: u8 = 3;
6111
6112impl Catalog {
6113 /// Serialize the whole catalog (schema + every row) into a self-contained
6114 /// byte buffer. Format is documented above the impl block.
6115 pub fn serialize(&self) -> Vec<u8> {
6116 let mut out = Vec::with_capacity(64);
6117 out.extend_from_slice(FILE_MAGIC);
6118 out.push(FILE_VERSION);
6119 write_u32(
6120 &mut out,
6121 u32::try_from(self.tables.len()).expect("≤ 4G tables"),
6122 );
6123 for t in &self.tables {
6124 write_str(&mut out, &t.schema.name);
6125 write_u16(
6126 &mut out,
6127 u16::try_from(t.schema.columns.len()).expect("≤ 65k columns/table"),
6128 );
6129 for c in &t.schema.columns {
6130 write_str(&mut out, &c.name);
6131 write_data_type(&mut out, c.ty);
6132 out.push(u8::from(c.nullable));
6133 match &c.default {
6134 None => out.push(0),
6135 Some(v) => {
6136 out.push(1);
6137 write_value(&mut out, v);
6138 }
6139 }
6140 out.push(u8::from(c.auto_increment));
6141 }
6142 write_u32(
6143 &mut out,
6144 u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
6145 );
6146 // v3.0.2 dense row encoding (FILE_VERSION 8): per-row NULL
6147 // bitmap, then tightly-packed bodies. Identical wire format
6148 // as before — extracted into `encode_row_body_dense` so cold-
6149 // tier segments (v5.1+) can share the encoding.
6150 for row in &t.rows {
6151 out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
6152 }
6153 // Index definitions. Per-index payload:
6154 // [name][col_pos u16][kind u8]
6155 // kind 0 = B-tree (no params — rebuilt on load)
6156 // kind 1 = NSW graph (u16 M + serialized graph)
6157 // For NSW the graph topology travels on disk so startup
6158 // doesn't re-run the O(n²M) rebuild — see v2.7 notes.
6159 write_u16(
6160 &mut out,
6161 u16::try_from(t.indices.len()).expect("≤ 65k indices/table"),
6162 );
6163 for idx in &t.indices {
6164 write_str(&mut out, &idx.name);
6165 write_u16(
6166 &mut out,
6167 u16::try_from(idx.column_position).expect("≤ 65k columns/table"),
6168 );
6169 match &idx.kind {
6170 IndexKind::BTree(map) => {
6171 out.push(0);
6172 // v9: serialise the full PB map. Each entry's
6173 // RowLocator list travels with the tag-prefixed
6174 // codec from `row_locator::write_le`, so freezer-
6175 // produced Cold locators survive a snapshot
6176 // round-trip. v8 BTree wrote nothing here and
6177 // rebuilt from rows — v9 readers tolerate v8 by
6178 // version dispatch in `Catalog::deserialize`.
6179 write_u32(
6180 &mut out,
6181 u32::try_from(map.len()).expect("≤ 4G index entries/index"),
6182 );
6183 for (key, locators) in map {
6184 write_index_key(&mut out, key);
6185 write_u32(
6186 &mut out,
6187 u32::try_from(locators.len()).expect("≤ 4G locators/key"),
6188 );
6189 for loc in locators {
6190 loc.write_le(&mut out);
6191 }
6192 }
6193 }
6194 IndexKind::Nsw(g) => {
6195 out.push(1);
6196 write_u16(&mut out, u16::try_from(g.m).expect("≤ 65k NSW neighbours"));
6197 write_nsw_graph(&mut out, g);
6198 }
6199 IndexKind::Brin { column_type } => {
6200 // v6.7.1 — tag byte 2 = BRIN. Payload is the
6201 // column type code (1 byte mapping to the
6202 // shared DataType numeric encoding); no
6203 // further data — BRIN summaries live in
6204 // cold segments, not the catalog.
6205 out.push(2);
6206 write_data_type(&mut out, *column_type);
6207 }
6208 IndexKind::Gin(map) => {
6209 // v7.12.3 — tag byte 3 = GIN. Payload mirrors
6210 // the BTree encoding but with String (lexeme
6211 // word) keys instead of IndexKey. Tag-prefixed
6212 // RowLocator codec so freezer-produced Cold
6213 // locators survive snapshot round-trip.
6214 // FILE_VERSION 21+; v20 catalogs never wrote a
6215 // GIN index (the AM degraded to BTree fallback
6216 // pre-v7.12.3), so no migration shim is needed.
6217 out.push(3);
6218 write_u32(
6219 &mut out,
6220 u32::try_from(map.len()).expect("≤ 4G GIN posting lists"),
6221 );
6222 for (word, locators) in map {
6223 write_str(&mut out, word);
6224 write_u32(
6225 &mut out,
6226 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
6227 );
6228 for loc in locators {
6229 loc.write_le(&mut out);
6230 }
6231 }
6232 }
6233 IndexKind::GinTrgm(map) => {
6234 // v7.15.0 — tag byte 4 = GinTrgm
6235 // (`gin_trgm_ops` GIN over a TEXT column).
6236 // Payload shape is identical to tag-3 GIN —
6237 // `String → Vec<RowLocator>` posting lists.
6238 // The String keys are 3-byte trigrams instead
6239 // of tsvector lexemes; the deserializer
6240 // dispatches on the tag, not the key shape.
6241 // FILE_VERSION 24+; v23 catalogs never wrote
6242 // a trigram-GIN.
6243 out.push(4);
6244 write_u32(
6245 &mut out,
6246 u32::try_from(map.len()).expect("≤ 4G trigram-GIN posting lists"),
6247 );
6248 for (tri, locators) in map {
6249 write_str(&mut out, tri);
6250 write_u32(
6251 &mut out,
6252 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
6253 );
6254 for loc in locators {
6255 loc.write_le(&mut out);
6256 }
6257 }
6258 }
6259 IndexKind::GinFulltext(map) => {
6260 // v7.17.0 Phase 2.2 — tag byte 5 =
6261 // GinFulltext (MySQL `FULLTEXT KEY` GIN
6262 // over a TEXT/VARCHAR column). Payload
6263 // shape mirrors tag-3 / tag-4 GIN —
6264 // `String → Vec<RowLocator>` posting
6265 // lists keyed by lower-cased word
6266 // lexemes. FILE_VERSION 33+; v32 catalogs
6267 // never wrote a fulltext-GIN (FULLTEXT
6268 // KEY was silently dropped pre-v7.17).
6269 out.push(5);
6270 write_u32(
6271 &mut out,
6272 u32::try_from(map.len()).expect("≤ 4G fulltext-GIN posting lists"),
6273 );
6274 for (lex, locators) in map {
6275 write_str(&mut out, lex);
6276 write_u32(
6277 &mut out,
6278 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
6279 );
6280 for loc in locators {
6281 loc.write_le(&mut out);
6282 }
6283 }
6284 }
6285 }
6286 // v6.8.0 — included_columns appendix per index.
6287 // Layout: [u16 num_included][num × u16 column_position].
6288 // v11 readers stop before this u16 (deserialise loop
6289 // gated on version >= 12); v12+ readers always
6290 // consume it. Empty Vec serialises as a bare 0u16.
6291 write_u16(
6292 &mut out,
6293 u16::try_from(idx.included_columns.len()).expect("≤ 65k INCLUDE columns/index"),
6294 );
6295 for col_pos in &idx.included_columns {
6296 write_u16(
6297 &mut out,
6298 u16::try_from(*col_pos).expect("≤ 65k columns/table"),
6299 );
6300 }
6301 // v6.8.1 — partial_predicate appendix per index.
6302 // Layout: [u8 has_pred][u16 LE len][bytes (if has_pred)].
6303 // Same v12 gate as included_columns.
6304 match &idx.partial_predicate {
6305 None => out.push(0),
6306 Some(pred) => {
6307 out.push(1);
6308 write_str(&mut out, pred);
6309 }
6310 }
6311 // v6.8.2 — expression appendix. Same shape as
6312 // partial_predicate.
6313 match &idx.expression {
6314 None => out.push(0),
6315 Some(expr) => {
6316 out.push(1);
6317 write_str(&mut out, expr);
6318 }
6319 }
6320 // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
6321 // Single byte 0/1. v15-and-below readers stop before
6322 // this byte; v16 readers always consume it. mailrs K1.
6323 out.push(u8::from(idx.is_unique));
6324 // v7.9.29 — extra_column_positions appendix.
6325 // Layout: [u16 count][count × u16 column_position].
6326 write_u16(
6327 &mut out,
6328 u16::try_from(idx.extra_column_positions.len())
6329 .expect("≤ 65k extra cols / index"),
6330 );
6331 for cp in &idx.extra_column_positions {
6332 write_u16(&mut out, u16::try_from(*cp).expect("≤ 65k columns/table"));
6333 }
6334 }
6335 // v6.7.2 — per-table hot_tier_bytes Option<u64>.
6336 // Layout: [u8 has_value][u64 LE value (if has_value)].
6337 // v10 readers stop before this byte (deserialise loop
6338 // gated on version >= 11); v11+ readers always
6339 // consume it.
6340 match t.schema.hot_tier_bytes {
6341 None => out.push(0),
6342 Some(n) => {
6343 out.push(1);
6344 out.extend_from_slice(&n.to_le_bytes());
6345 }
6346 }
6347 // v7.6.1 — FOREIGN KEY appendix (catalog FILE_VERSION 13+).
6348 // Layout: [u16 LE fk_count]
6349 // per fk:
6350 // [u8 has_name] [str name (if has_name)]
6351 // [u16 LE local_arity] [u16 LE local_pos]*arity
6352 // [str parent_table]
6353 // [u16 LE parent_arity] [u16 LE parent_pos]*arity
6354 // [u8 on_delete_tag] [u8 on_update_tag]
6355 // Older catalogs (v12 and below) skip this block entirely;
6356 // their reader stops before this byte.
6357 write_u16(
6358 &mut out,
6359 u16::try_from(t.schema.foreign_keys.len()).expect("≤ 65k FKs/table"),
6360 );
6361 for fk in &t.schema.foreign_keys {
6362 match &fk.name {
6363 None => out.push(0),
6364 Some(n) => {
6365 out.push(1);
6366 write_str(&mut out, n);
6367 }
6368 }
6369 write_u16(
6370 &mut out,
6371 u16::try_from(fk.local_columns.len()).expect("≤ 65k FK columns"),
6372 );
6373 for &p in &fk.local_columns {
6374 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
6375 }
6376 write_str(&mut out, &fk.parent_table);
6377 write_u16(
6378 &mut out,
6379 u16::try_from(fk.parent_columns.len()).expect("≤ 65k FK parent columns"),
6380 );
6381 for &p in &fk.parent_columns {
6382 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
6383 }
6384 out.push(fk.on_delete.tag());
6385 out.push(fk.on_update.tag());
6386 }
6387 // v7.9.19 — UniquenessConstraint appendix (catalog
6388 // FILE_VERSION 15+). Layout per table after the FK
6389 // block:
6390 // [u16 count]
6391 // per constraint:
6392 // [u8 is_primary_key]
6393 // [u16 arity][u16 col_pos]*arity
6394 // Older catalogs (v14 and below) skip this block.
6395 write_u16(
6396 &mut out,
6397 u16::try_from(t.schema.uniqueness_constraints.len())
6398 .expect("≤ 65k uniqueness constraints/table"),
6399 );
6400 for uc in &t.schema.uniqueness_constraints {
6401 out.push(u8::from(uc.is_primary_key));
6402 write_u16(
6403 &mut out,
6404 u16::try_from(uc.columns.len()).expect("≤ 65k cols in uniqueness constraint"),
6405 );
6406 for &p in &uc.columns {
6407 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
6408 }
6409 // v7.13.0 — `nulls_not_distinct` flag
6410 // (FILE_VERSION 23+). Always written by writers at
6411 // version 23+; deserialise gates on `version >= 23`
6412 // so v22-and-below catalogs round-trip cleanly.
6413 out.push(u8::from(uc.nulls_not_distinct));
6414 }
6415 // v7.9.21 — runtime_default appendix per table.
6416 // Layout: [u16 count] then for each:
6417 // [u16 col_pos][str expr]
6418 // Only columns whose runtime_default is Some land here;
6419 // catalog stays compact for the common literal-default
6420 // case.
6421 let mut rt_defaults: Vec<(usize, &str)> = Vec::new();
6422 for (i, c) in t.schema.columns.iter().enumerate() {
6423 if let Some(e) = &c.runtime_default {
6424 rt_defaults.push((i, e.as_str()));
6425 }
6426 }
6427 write_u16(
6428 &mut out,
6429 u16::try_from(rt_defaults.len()).expect("≤ 65k runtime defaults/table"),
6430 );
6431 for (pos, expr) in rt_defaults {
6432 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6433 write_str(&mut out, expr);
6434 }
6435 // v7.13.0 — CHECK constraint appendix per table.
6436 // Layout: [u16 count] then `count` Display-form
6437 // expression strings. Re-parsed on every INSERT/UPDATE
6438 // by the engine. FILE_VERSION 23+ only; v22 readers
6439 // never reach this block because the writer also moves
6440 // to v23 in lock-step.
6441 write_u16(
6442 &mut out,
6443 u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
6444 );
6445 for c in &t.schema.checks {
6446 write_str(&mut out, c.as_str());
6447 }
6448 // v7.17.0 Phase 1.4 — per-table user_enum_type
6449 // appendix. Layout: [u16 count] then
6450 // [u16 col_pos][str enum_name] per binding. Only
6451 // columns whose user_enum_type is Some land here.
6452 let mut enum_bindings: Vec<(usize, &str)> = Vec::new();
6453 for (i, c) in t.schema.columns.iter().enumerate() {
6454 if let Some(e) = &c.user_enum_type {
6455 enum_bindings.push((i, e.as_str()));
6456 }
6457 }
6458 write_u16(
6459 &mut out,
6460 u16::try_from(enum_bindings.len()).expect("≤ 65k enum-typed columns/table"),
6461 );
6462 for (pos, ename) in enum_bindings {
6463 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6464 write_str(&mut out, ename);
6465 }
6466 // v7.17.0 Phase 1.5 — per-table user_domain_type
6467 // appendix. Same layout as the enum one. v29-and-
6468 // below readers stop after the enum appendix.
6469 let mut domain_bindings: Vec<(usize, &str)> = Vec::new();
6470 for (i, c) in t.schema.columns.iter().enumerate() {
6471 if let Some(d) = &c.user_domain_type {
6472 domain_bindings.push((i, d.as_str()));
6473 }
6474 }
6475 write_u16(
6476 &mut out,
6477 u16::try_from(domain_bindings.len()).expect("≤ 65k domain-typed columns/table"),
6478 );
6479 for (pos, dname) in domain_bindings {
6480 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6481 write_str(&mut out, dname);
6482 }
6483 // v7.17.0 Phase 2.1 — per-table on_update_runtime
6484 // appendix. Sparse: only ON UPDATE-bound columns.
6485 let mut on_update_bindings: Vec<(usize, &str)> = Vec::new();
6486 for (i, c) in t.schema.columns.iter().enumerate() {
6487 if let Some(e) = &c.on_update_runtime {
6488 on_update_bindings.push((i, e.as_str()));
6489 }
6490 }
6491 write_u16(
6492 &mut out,
6493 u16::try_from(on_update_bindings.len()).expect("≤ 65k ON UPDATE columns/table"),
6494 );
6495 for (pos, expr_src) in on_update_bindings {
6496 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6497 write_str(&mut out, expr_src);
6498 }
6499 // v7.17.0 Phase 2.5 — per-table collation appendix.
6500 // Sparse: only non-Binary columns land. Layout:
6501 // `[u16 count][u16 col_pos][u8 tag] × count`.
6502 let mut coll_bindings: Vec<(usize, u8)> = Vec::new();
6503 for (i, c) in t.schema.columns.iter().enumerate() {
6504 let tag = match c.collation {
6505 Collation::Binary => continue,
6506 Collation::CaseInsensitive => Collation::TAG_CASE_INSENSITIVE,
6507 };
6508 coll_bindings.push((i, tag));
6509 }
6510 write_u16(
6511 &mut out,
6512 u16::try_from(coll_bindings.len()).expect("≤ 65k collation bindings/table"),
6513 );
6514 for (pos, tag) in coll_bindings {
6515 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6516 out.push(tag);
6517 }
6518 // v7.17.0 Phase 4.4 — per-table is_unsigned appendix.
6519 // Sparse: only UNSIGNED columns land. Layout:
6520 // `[u16 count][u16 col_pos] × count`.
6521 let mut unsigned_bindings: Vec<usize> = Vec::new();
6522 for (i, c) in t.schema.columns.iter().enumerate() {
6523 if c.is_unsigned {
6524 unsigned_bindings.push(i);
6525 }
6526 }
6527 write_u16(
6528 &mut out,
6529 u16::try_from(unsigned_bindings.len()).expect("≤ 65k UNSIGNED columns/table"),
6530 );
6531 for pos in unsigned_bindings {
6532 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6533 }
6534 // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
6535 // appendix. Sparse: only ENUM columns land. Layout:
6536 // `[u16 count] then per binding [u16 col_pos]
6537 // [u16 variant_count] then variant strings`.
6538 // FILE_VERSION 41+; v40 readers never reach this block.
6539 let mut enum_inline_bindings: Vec<(usize, &[String])> = Vec::new();
6540 for (i, c) in t.schema.columns.iter().enumerate() {
6541 if let Some(vs) = &c.inline_enum_variants {
6542 enum_inline_bindings.push((i, vs.as_slice()));
6543 }
6544 }
6545 write_u16(
6546 &mut out,
6547 u16::try_from(enum_inline_bindings.len()).expect("≤ 65k inline-ENUM columns/table"),
6548 );
6549 for (pos, variants) in enum_inline_bindings {
6550 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6551 write_u16(
6552 &mut out,
6553 u16::try_from(variants.len()).expect("≤ 65k variants/ENUM"),
6554 );
6555 for v in variants {
6556 write_str(&mut out, v.as_str());
6557 }
6558 }
6559 // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
6560 // appendix. Same layout as the inline ENUM block.
6561 // FILE_VERSION 42+; v41 readers never reach this block.
6562 let mut set_inline_bindings: Vec<(usize, &[String])> = Vec::new();
6563 for (i, c) in t.schema.columns.iter().enumerate() {
6564 if let Some(vs) = &c.inline_set_variants {
6565 set_inline_bindings.push((i, vs.as_slice()));
6566 }
6567 }
6568 write_u16(
6569 &mut out,
6570 u16::try_from(set_inline_bindings.len()).expect("≤ 65k inline-SET columns/table"),
6571 );
6572 for (pos, variants) in set_inline_bindings {
6573 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
6574 write_u16(
6575 &mut out,
6576 u16::try_from(variants.len()).expect("≤ 65k variants/SET"),
6577 );
6578 for v in variants {
6579 write_str(&mut out, v.as_str());
6580 }
6581 }
6582 }
6583 // v7.12.4 — catalog-wide appendix: user-defined functions
6584 // then triggers. FILE_VERSION 22+ only. v21 and earlier
6585 // readers stop after the last table; v22 readers always
6586 // consume two `u32` counts (possibly zero).
6587 //
6588 // Function entry layout:
6589 // [str name] [str args_repr] [str returns]
6590 // [str language] [str body]
6591 // Trigger entry layout:
6592 // [str name] [str table] [str timing]
6593 // [u16 event_count] (event_count × str)
6594 // [str for_each] [str function]
6595 write_u32(
6596 &mut out,
6597 u32::try_from(self.functions.len()).expect("≤ 4G functions"),
6598 );
6599 for fd in self.functions.values() {
6600 write_str(&mut out, &fd.name);
6601 write_str(&mut out, &fd.args_repr);
6602 write_str(&mut out, &fd.returns);
6603 write_str(&mut out, &fd.language);
6604 write_str_long(&mut out, &fd.body);
6605 }
6606 write_u32(
6607 &mut out,
6608 u32::try_from(self.triggers.len()).expect("≤ 4G triggers"),
6609 );
6610 for td in &self.triggers {
6611 write_str(&mut out, &td.name);
6612 write_str(&mut out, &td.table);
6613 write_str(&mut out, &td.timing);
6614 write_u16(
6615 &mut out,
6616 u16::try_from(td.events.len()).expect("≤ 65k events / trigger"),
6617 );
6618 for ev in &td.events {
6619 write_str(&mut out, ev);
6620 }
6621 write_str(&mut out, &td.for_each);
6622 write_str(&mut out, &td.function);
6623 // v7.13.0 — `UPDATE OF cols` filter
6624 // (FILE_VERSION 23+). v22 readers omit; v23 writers
6625 // always emit (possibly zero).
6626 write_u16(
6627 &mut out,
6628 u16::try_from(td.update_columns.len()).expect("≤ 65k cols / trigger"),
6629 );
6630 for c in &td.update_columns {
6631 write_str(&mut out, c);
6632 }
6633 // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
6634 out.push(u8::from(td.enabled));
6635 }
6636 // v7.17.0 Phase 1.1 — SEQUENCE catalog block (FILE_VERSION 26+).
6637 write_u32(
6638 &mut out,
6639 u32::try_from(self.sequences.len()).expect("≤ 4G sequences"),
6640 );
6641 for seq in self.sequences.values() {
6642 write_str(&mut out, &seq.name);
6643 out.push(match seq.data_type {
6644 SequenceDataType::SmallInt => 0,
6645 SequenceDataType::Int => 1,
6646 SequenceDataType::BigInt => 2,
6647 });
6648 out.extend_from_slice(&seq.start.to_le_bytes());
6649 out.extend_from_slice(&seq.increment.to_le_bytes());
6650 out.extend_from_slice(&seq.min_value.to_le_bytes());
6651 out.extend_from_slice(&seq.max_value.to_le_bytes());
6652 out.extend_from_slice(&seq.cache.to_le_bytes());
6653 out.push(u8::from(seq.cycle));
6654 match &seq.owned_by {
6655 None => out.push(0),
6656 Some((table, column)) => {
6657 out.push(1);
6658 write_str(&mut out, table);
6659 write_str(&mut out, column);
6660 }
6661 }
6662 out.extend_from_slice(&seq.last_value.to_le_bytes());
6663 out.push(u8::from(seq.is_called));
6664 }
6665 // v7.17.0 Phase 1.2 — VIEW catalog block (FILE_VERSION 27+).
6666 write_u32(
6667 &mut out,
6668 u32::try_from(self.views.len()).expect("≤ 4G views"),
6669 );
6670 for view in self.views.values() {
6671 write_str(&mut out, &view.name);
6672 write_u16(
6673 &mut out,
6674 u16::try_from(view.columns.len()).expect("≤ 65k cols / view"),
6675 );
6676 for c in &view.columns {
6677 write_str(&mut out, c);
6678 }
6679 write_str_long(&mut out, &view.body);
6680 }
6681 // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
6682 // (FILE_VERSION 28+). The backing rows live as a regular
6683 // table of the same name already in the tables block.
6684 write_u32(
6685 &mut out,
6686 u32::try_from(self.materialized_views.len()).expect("≤ 4G materialized views"),
6687 );
6688 for (name, body) in &self.materialized_views {
6689 write_str(&mut out, name);
6690 write_str_long(&mut out, body);
6691 }
6692 // v7.17.0 Phase 1.4 — ENUM types catalog block
6693 // (FILE_VERSION 29+).
6694 write_u32(
6695 &mut out,
6696 u32::try_from(self.enum_types.len()).expect("≤ 4G enum types"),
6697 );
6698 for e in self.enum_types.values() {
6699 write_str(&mut out, &e.name);
6700 write_u16(
6701 &mut out,
6702 u16::try_from(e.labels.len()).expect("≤ 65k labels / enum"),
6703 );
6704 for l in &e.labels {
6705 write_str(&mut out, l);
6706 }
6707 }
6708 // v7.17.0 Phase 1.5 — DOMAIN types catalog block
6709 // (FILE_VERSION 30+).
6710 write_u32(
6711 &mut out,
6712 u32::try_from(self.domain_types.len()).expect("≤ 4G domain types"),
6713 );
6714 for d in self.domain_types.values() {
6715 write_str(&mut out, &d.name);
6716 write_data_type(&mut out, d.base_type);
6717 out.push(u8::from(d.nullable));
6718 match &d.default {
6719 None => out.push(0),
6720 Some(s) => {
6721 out.push(1);
6722 write_str(&mut out, s);
6723 }
6724 }
6725 write_u16(
6726 &mut out,
6727 u16::try_from(d.checks.len()).expect("≤ 65k CHECKs / domain"),
6728 );
6729 for c in &d.checks {
6730 write_str(&mut out, c);
6731 }
6732 }
6733 // v7.17.0 Phase 1.6 — user-schemas registry
6734 // (FILE_VERSION 31+). Built-ins are hardcoded in
6735 // `is_builtin_schema` and not persisted.
6736 write_u32(
6737 &mut out,
6738 u32::try_from(self.schemas.len()).expect("≤ 4G schemas"),
6739 );
6740 for name in &self.schemas {
6741 write_str(&mut out, name);
6742 }
6743 out
6744 }
6745
6746 /// Deserialize a previously-serialized catalog. Rejects bad magic, version
6747 /// mismatch, unknown tags, truncation, and trailing bytes.
6748 pub fn deserialize(buf: &[u8]) -> Result<Self, StorageError> {
6749 let mut cur = Cursor::new(buf);
6750 let magic = cur.take(8)?;
6751 if magic != FILE_MAGIC {
6752 return Err(StorageError::Corrupt(format!(
6753 "bad magic: expected SPGDB001, got {magic:?}"
6754 )));
6755 }
6756 let version = cur.read_u8()?;
6757 if !(MIN_SUPPORTED_FILE_VERSION..=FILE_VERSION).contains(&version) {
6758 return Err(StorageError::Corrupt(format!(
6759 "unsupported file version: {version} (supported: {MIN_SUPPORTED_FILE_VERSION}..={FILE_VERSION})"
6760 )));
6761 }
6762 let table_count = cur.read_u32()? as usize;
6763 let mut cat = Self::new();
6764 for _ in 0..table_count {
6765 deserialize_table(&mut cur, &mut cat, version)?;
6766 }
6767 // v7.12.4 — catalog-wide function + trigger appendix.
6768 // FILE_VERSION 22+ only; v21 and earlier catalogs stop
6769 // after the last table.
6770 if version >= 22 {
6771 let fn_count = cur.read_u32()? as usize;
6772 for _ in 0..fn_count {
6773 let name = cur.read_str()?;
6774 let args_repr = cur.read_str()?;
6775 let returns = cur.read_str()?;
6776 let language = cur.read_str()?;
6777 let body = cur.read_str_long()?;
6778 cat.functions.insert(
6779 name.clone(),
6780 FunctionDef {
6781 name,
6782 args_repr,
6783 returns,
6784 language,
6785 body,
6786 },
6787 );
6788 }
6789 let trg_count = cur.read_u32()? as usize;
6790 for _ in 0..trg_count {
6791 let name = cur.read_str()?;
6792 let table = cur.read_str()?;
6793 let timing = cur.read_str()?;
6794 let ev_count = cur.read_u16()? as usize;
6795 let mut events = Vec::with_capacity(ev_count);
6796 for _ in 0..ev_count {
6797 events.push(cur.read_str()?);
6798 }
6799 let for_each = cur.read_str()?;
6800 let function = cur.read_str()?;
6801 // v7.13.0 — trailing `UPDATE OF cols` filter
6802 // (FILE_VERSION 23+ only; v22 catalogs omit and
6803 // deserialise with an empty vec).
6804 let update_columns = if version >= 23 {
6805 let n = cur.read_u16()? as usize;
6806 let mut cols = Vec::with_capacity(n);
6807 for _ in 0..n {
6808 cols.push(cur.read_str()?);
6809 }
6810 cols
6811 } else {
6812 Vec::new()
6813 };
6814 // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
6815 // v24-and-below catalogs deserialise with `true`
6816 // — pre-v7.16.1 every trigger always fired.
6817 let enabled = if version >= 25 {
6818 cur.read_u8()? != 0
6819 } else {
6820 true
6821 };
6822 cat.triggers.push(TriggerDef {
6823 name,
6824 table,
6825 timing,
6826 events,
6827 for_each,
6828 function,
6829 update_columns,
6830 enabled,
6831 });
6832 }
6833 }
6834 // v7.17.0 Phase 1.1 — SEQUENCE block (FILE_VERSION 26+).
6835 // v25-and-below catalogs omit; we leave the map empty.
6836 if version >= 26 {
6837 let seq_count = cur.read_u32()? as usize;
6838 for _ in 0..seq_count {
6839 let name = cur.read_str()?;
6840 let data_type = match cur.read_u8()? {
6841 0 => SequenceDataType::SmallInt,
6842 1 => SequenceDataType::Int,
6843 2 => SequenceDataType::BigInt,
6844 other => {
6845 return Err(StorageError::Corrupt(format!(
6846 "unknown SEQUENCE data-type tag {other}"
6847 )));
6848 }
6849 };
6850 let start = cur.read_i64()?;
6851 let increment = cur.read_i64()?;
6852 let min_value = cur.read_i64()?;
6853 let max_value = cur.read_i64()?;
6854 let cache = cur.read_i64()?;
6855 let cycle = cur.read_u8()? != 0;
6856 let owned_by = match cur.read_u8()? {
6857 0 => None,
6858 1 => {
6859 let t = cur.read_str()?;
6860 let c = cur.read_str()?;
6861 Some((t, c))
6862 }
6863 other => {
6864 return Err(StorageError::Corrupt(format!(
6865 "unknown SEQUENCE owned-by tag {other}"
6866 )));
6867 }
6868 };
6869 let last_value = cur.read_i64()?;
6870 let is_called = cur.read_u8()? != 0;
6871 cat.sequences.insert(
6872 name.clone(),
6873 SequenceDef {
6874 name,
6875 data_type,
6876 start,
6877 increment,
6878 min_value,
6879 max_value,
6880 cache,
6881 cycle,
6882 owned_by,
6883 last_value,
6884 is_called,
6885 },
6886 );
6887 }
6888 }
6889 // v7.17.0 Phase 1.2 — VIEW block (FILE_VERSION 27+).
6890 // v26-and-below catalogs omit; we leave the map empty.
6891 if version >= 27 {
6892 let view_count = cur.read_u32()? as usize;
6893 for _ in 0..view_count {
6894 let name = cur.read_str()?;
6895 let col_count = cur.read_u16()? as usize;
6896 let mut columns = Vec::with_capacity(col_count);
6897 for _ in 0..col_count {
6898 columns.push(cur.read_str()?);
6899 }
6900 let body = cur.read_str_long()?;
6901 cat.views.insert(
6902 name.clone(),
6903 ViewDef {
6904 name,
6905 columns,
6906 body,
6907 },
6908 );
6909 }
6910 }
6911 // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
6912 // (FILE_VERSION 28+). v27-and-below catalogs omit.
6913 if version >= 28 {
6914 let mv_count = cur.read_u32()? as usize;
6915 for _ in 0..mv_count {
6916 let name = cur.read_str()?;
6917 let body = cur.read_str_long()?;
6918 cat.materialized_views.insert(name, body);
6919 }
6920 }
6921 // v7.17.0 Phase 1.4 — ENUM types catalog block
6922 // (FILE_VERSION 29+).
6923 if version >= 29 {
6924 let etype_count = cur.read_u32()? as usize;
6925 for _ in 0..etype_count {
6926 let name = cur.read_str()?;
6927 let label_count = cur.read_u16()? as usize;
6928 let mut labels = Vec::with_capacity(label_count);
6929 for _ in 0..label_count {
6930 labels.push(cur.read_str()?);
6931 }
6932 cat.enum_types
6933 .insert(name.clone(), EnumDef { name, labels });
6934 }
6935 }
6936 // v7.17.0 Phase 1.5 — DOMAIN types catalog block
6937 // (FILE_VERSION 30+).
6938 if version >= 30 {
6939 let dtype_count = cur.read_u32()? as usize;
6940 for _ in 0..dtype_count {
6941 let name = cur.read_str()?;
6942 let base_type = cur.read_data_type()?;
6943 let nullable = cur.read_u8()? != 0;
6944 let default = match cur.read_u8()? {
6945 0 => None,
6946 1 => Some(cur.read_str()?),
6947 other => {
6948 return Err(StorageError::Corrupt(format!(
6949 "unknown DOMAIN default tag {other}"
6950 )));
6951 }
6952 };
6953 let check_count = cur.read_u16()? as usize;
6954 let mut checks = Vec::with_capacity(check_count);
6955 for _ in 0..check_count {
6956 checks.push(cur.read_str()?);
6957 }
6958 cat.domain_types.insert(
6959 name.clone(),
6960 DomainDef {
6961 name,
6962 base_type,
6963 nullable,
6964 default,
6965 checks,
6966 },
6967 );
6968 }
6969 }
6970 // v7.17.0 Phase 1.6 — user-schemas registry
6971 // (FILE_VERSION 31+).
6972 if version >= 31 {
6973 let sch_count = cur.read_u32()? as usize;
6974 for _ in 0..sch_count {
6975 let name = cur.read_str()?;
6976 cat.schemas.insert(name);
6977 }
6978 }
6979 if cur.pos < buf.len() {
6980 return Err(StorageError::Corrupt(format!(
6981 "trailing bytes: {} unread",
6982 buf.len() - cur.pos
6983 )));
6984 }
6985 Ok(cat)
6986 }
6987}
6988
6989/// Per-table deserialize body — schema, rows, indices. Pulled out of
6990/// `Catalog::deserialize` to keep the latter under the line-budget lint
6991/// and to give the row hot loop its own scope (so the borrow on `t`
6992/// stays scoped here rather than across the whole catalog loop).
6993fn deserialize_table(
6994 cur: &mut Cursor<'_>,
6995 cat: &mut Catalog,
6996 version: u8,
6997) -> Result<(), StorageError> {
6998 let table_name = cur.read_str()?;
6999 let name = table_name.clone();
7000 let col_count = cur.read_u16()? as usize;
7001 let mut cols = Vec::with_capacity(col_count);
7002 for _ in 0..col_count {
7003 let c_name = cur.read_str()?;
7004 let ty = cur.read_data_type()?;
7005 let nullable = cur.read_u8()? != 0;
7006 let default = match cur.read_u8()? {
7007 0 => None,
7008 1 => Some(cur.read_value()?),
7009 other => {
7010 return Err(StorageError::Corrupt(format!(
7011 "unknown default tag: {other}"
7012 )));
7013 }
7014 };
7015 let auto_increment = cur.read_u8()? != 0;
7016 // Note: deserialiser sets runtime_default = None for
7017 // older catalogs (≤ v14). v15+ reads it from the
7018 // per-column appendix below.
7019 cols.push(ColumnSchema {
7020 name: c_name,
7021 ty,
7022 nullable,
7023 default,
7024 runtime_default: None,
7025 auto_increment,
7026 user_enum_type: None,
7027 user_domain_type: None,
7028 on_update_runtime: None,
7029 collation: Collation::Binary,
7030 is_unsigned: false,
7031 inline_enum_variants: None,
7032 inline_set_variants: None,
7033 });
7034 }
7035 let n_cols = cols.len();
7036 cat.create_table(TableSchema::new(name, cols))?;
7037 // Vec<Table> with insertion-order semantics — the just-pushed
7038 // table is at the end. Sidecar `by_name` is already wired up but
7039 // we skip the map lookup here since we know the position.
7040 let t = cat.tables.last_mut().expect("create_table just pushed");
7041 deserialize_rows(cur, t, n_cols)?;
7042 deserialize_indices(cur, t, version)?;
7043 // v6.7.2 — per-table hot_tier_bytes appendix. v11+ writes
7044 // `[u8 has_value][u64 LE value (if has_value)]`. v10 / v9 / v8
7045 // catalogs skip this entirely (the deserialiser reads no extra
7046 // bytes; the table's hot_tier_bytes stays None from
7047 // TableSchema::new).
7048 if version >= 11 {
7049 let has = cur.read_u8()?;
7050 let hot_tier_bytes = match has {
7051 0 => None,
7052 1 => Some(cur.read_u64()?),
7053 other => {
7054 return Err(StorageError::Corrupt(format!(
7055 "hot_tier_bytes appendix: unknown has-value byte {other}"
7056 )));
7057 }
7058 };
7059 t.schema_mut().hot_tier_bytes = hot_tier_bytes;
7060 }
7061 // v7.6.1 — FOREIGN KEY appendix (FILE_VERSION 13+). v12 / v11 / …
7062 // catalogs skip this entirely.
7063 if version >= 13 {
7064 let fk_count = cur.read_u16()? as usize;
7065 let mut fks = Vec::with_capacity(fk_count);
7066 for _ in 0..fk_count {
7067 let name = match cur.read_u8()? {
7068 0 => None,
7069 1 => Some(cur.read_str()?),
7070 other => {
7071 return Err(StorageError::Corrupt(format!(
7072 "FK appendix: unknown has-name byte {other}"
7073 )));
7074 }
7075 };
7076 let local_arity = cur.read_u16()? as usize;
7077 let mut local_columns = Vec::with_capacity(local_arity);
7078 for _ in 0..local_arity {
7079 local_columns.push(cur.read_u16()? as usize);
7080 }
7081 let parent_table = cur.read_str()?;
7082 let parent_arity = cur.read_u16()? as usize;
7083 if parent_arity != local_arity {
7084 return Err(StorageError::Corrupt(format!(
7085 "FK arity mismatch in catalog: local {local_arity} vs parent {parent_arity}"
7086 )));
7087 }
7088 let mut parent_columns = Vec::with_capacity(parent_arity);
7089 for _ in 0..parent_arity {
7090 parent_columns.push(cur.read_u16()? as usize);
7091 }
7092 let on_delete = FkAction::from_tag(cur.read_u8()?).ok_or_else(|| {
7093 StorageError::Corrupt("FK appendix: unknown on_delete tag".into())
7094 })?;
7095 let on_update = FkAction::from_tag(cur.read_u8()?).ok_or_else(|| {
7096 StorageError::Corrupt("FK appendix: unknown on_update tag".into())
7097 })?;
7098 fks.push(ForeignKeyConstraint {
7099 name,
7100 local_columns,
7101 parent_table,
7102 parent_columns,
7103 on_delete,
7104 on_update,
7105 });
7106 }
7107 t.schema_mut().foreign_keys = fks;
7108 }
7109 // v7.9.19 — UniquenessConstraint appendix (FILE_VERSION 15+).
7110 // v14 and below skip this entirely.
7111 if version >= 15 {
7112 let uc_count = cur.read_u16()? as usize;
7113 let mut ucs = Vec::with_capacity(uc_count);
7114 for _ in 0..uc_count {
7115 let is_pk = cur.read_u8()? != 0;
7116 let arity = cur.read_u16()? as usize;
7117 let mut cols = Vec::with_capacity(arity);
7118 for _ in 0..arity {
7119 cols.push(cur.read_u16()? as usize);
7120 }
7121 // v7.13.0 — trailing `nulls_not_distinct` flag
7122 // (FILE_VERSION 23+). v22 and below skip — flag
7123 // defaults to false (= NULLS DISTINCT).
7124 let nulls_not_distinct = if version >= 23 {
7125 cur.read_u8()? != 0
7126 } else {
7127 false
7128 };
7129 ucs.push(UniquenessConstraint {
7130 is_primary_key: is_pk,
7131 columns: cols,
7132 nulls_not_distinct,
7133 });
7134 }
7135 t.schema_mut().uniqueness_constraints = ucs;
7136 // v7.9.21 — runtime_default appendix (FILE_VERSION 15+).
7137 let rt_count = cur.read_u16()? as usize;
7138 for _ in 0..rt_count {
7139 let pos = cur.read_u16()? as usize;
7140 let expr = cur.read_str()?;
7141 if let Some(col) = t.schema_mut().columns.get_mut(pos) {
7142 col.runtime_default = Some(expr);
7143 }
7144 }
7145 }
7146 // v7.13.0 — CHECK constraints appendix (FILE_VERSION 23+).
7147 // v22 and below leave the vec empty.
7148 if version >= 23 {
7149 let check_count = cur.read_u16()? as usize;
7150 let mut checks = Vec::with_capacity(check_count);
7151 for _ in 0..check_count {
7152 checks.push(cur.read_str()?);
7153 }
7154 t.schema_mut().checks = checks;
7155 }
7156 // v7.17.0 Phase 1.4 — per-table user_enum_type appendix
7157 // (FILE_VERSION 29+). Layout: [u16 count] then
7158 // [u16 col_pos][str enum_name] per binding.
7159 if version >= 29 {
7160 let binding_count = cur.read_u16()? as usize;
7161 for _ in 0..binding_count {
7162 let col_pos = cur.read_u16()? as usize;
7163 let ename = cur.read_str()?;
7164 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7165 col.user_enum_type = Some(ename);
7166 }
7167 }
7168 }
7169 // v7.17.0 Phase 1.5 — per-table user_domain_type appendix
7170 // (FILE_VERSION 30+). Same shape as the enum one.
7171 if version >= 30 {
7172 let binding_count = cur.read_u16()? as usize;
7173 for _ in 0..binding_count {
7174 let col_pos = cur.read_u16()? as usize;
7175 let dname = cur.read_str()?;
7176 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7177 col.user_domain_type = Some(dname);
7178 }
7179 }
7180 }
7181 // v7.17.0 Phase 2.1 — per-table on_update_runtime appendix
7182 // (FILE_VERSION 32+). Sparse layout matches the enum/
7183 // domain bindings.
7184 if version >= 32 {
7185 let binding_count = cur.read_u16()? as usize;
7186 for _ in 0..binding_count {
7187 let col_pos = cur.read_u16()? as usize;
7188 let expr_src = cur.read_str()?;
7189 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7190 col.on_update_runtime = Some(expr_src);
7191 }
7192 }
7193 }
7194 // v7.17.0 Phase 2.5 — per-table collation appendix
7195 // (FILE_VERSION 34+). Sparse: only non-Binary columns
7196 // land. v33-and-below readers leave every column at its
7197 // ColumnSchema::new default (Binary). Unknown tags from a
7198 // forward-incompat snapshot read back as Binary.
7199 if version >= 34 {
7200 let binding_count = cur.read_u16()? as usize;
7201 for _ in 0..binding_count {
7202 let col_pos = cur.read_u16()? as usize;
7203 let tag = cur.read_u8()?;
7204 let collation = match tag {
7205 Collation::TAG_CASE_INSENSITIVE => Collation::CaseInsensitive,
7206 _ => Collation::Binary,
7207 };
7208 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7209 col.collation = collation;
7210 }
7211 }
7212 }
7213 // v7.17.0 Phase 4.4 — per-table is_unsigned appendix
7214 // (FILE_VERSION 35+). Sparse: only UNSIGNED columns land.
7215 // v34-and-below readers leave every column at
7216 // `is_unsigned = false`.
7217 if version >= 35 {
7218 let binding_count = cur.read_u16()? as usize;
7219 for _ in 0..binding_count {
7220 let col_pos = cur.read_u16()? as usize;
7221 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7222 col.is_unsigned = true;
7223 }
7224 }
7225 }
7226 // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
7227 // appendix (FILE_VERSION 41+). Sparse: only ENUM columns land.
7228 // v40-and-below readers leave every column at
7229 // `inline_enum_variants = None`.
7230 if version >= 41 {
7231 let binding_count = cur.read_u16()? as usize;
7232 for _ in 0..binding_count {
7233 let col_pos = cur.read_u16()? as usize;
7234 let variant_count = cur.read_u16()? as usize;
7235 let mut variants = Vec::with_capacity(variant_count);
7236 for _ in 0..variant_count {
7237 variants.push(cur.read_str()?);
7238 }
7239 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7240 col.inline_enum_variants = Some(variants);
7241 }
7242 }
7243 }
7244 // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
7245 // appendix (FILE_VERSION 42+). Sparse: only SET columns land.
7246 if version >= 42 {
7247 let binding_count = cur.read_u16()? as usize;
7248 for _ in 0..binding_count {
7249 let col_pos = cur.read_u16()? as usize;
7250 let variant_count = cur.read_u16()? as usize;
7251 let mut variants = Vec::with_capacity(variant_count);
7252 for _ in 0..variant_count {
7253 variants.push(cur.read_str()?);
7254 }
7255 if let Some(col) = t.schema_mut().columns.get_mut(col_pos) {
7256 col.inline_set_variants = Some(variants);
7257 }
7258 }
7259 }
7260 let _ = table_name;
7261 Ok(())
7262}
7263
7264fn deserialize_rows(
7265 cur: &mut Cursor<'_>,
7266 t: &mut Table,
7267 _n_cols: usize,
7268) -> Result<(), StorageError> {
7269 let row_count = cur.read_u32()? as usize;
7270 // v4.39: PV has no `reserve` (the BVT doesn't preallocate a
7271 // contiguous buffer); we just push directly and let the trie
7272 // grow. v5.1: row decode reuses `decode_row_body_dense` so the
7273 // catalog and cold-tier segments share one row codec.
7274 let mut hot_bytes: u64 = 0;
7275 for _ in 0..row_count {
7276 let tail = &cur.buf[cur.pos..];
7277 let (row, consumed) = decode_row_body_dense(tail, &t.schema)?;
7278 cur.pos += consumed;
7279 // v5.2.1: account for hot bytes as we go; the snapshot's row
7280 // block bytes are exactly what `encode_row_body_dense` would
7281 // produce, so `consumed` would do too — but going via the
7282 // helper keeps the counter's definition coupled to the
7283 // encoder rather than the snapshot's row prefix layout.
7284 hot_bytes = hot_bytes.saturating_add(row_body_encoded_len(&row, &t.schema) as u64);
7285 t.rows.push_mut(row);
7286 }
7287 t.hot_bytes = hot_bytes;
7288 Ok(())
7289}
7290
7291fn deserialize_indices(
7292 cur: &mut Cursor<'_>,
7293 t: &mut Table,
7294 version: u8,
7295) -> Result<(), StorageError> {
7296 let index_count = cur.read_u16()? as usize;
7297 for _ in 0..index_count {
7298 let idx_name = cur.read_str()?;
7299 let col_pos = cur.read_u16()? as usize;
7300 let column_name = t
7301 .schema
7302 .columns
7303 .get(col_pos)
7304 .ok_or_else(|| {
7305 StorageError::Corrupt(format!(
7306 "index {idx_name:?} points at non-existent column position {col_pos}"
7307 ))
7308 })?
7309 .name
7310 .clone();
7311 let kind_tag = cur.read_u8()?;
7312 match kind_tag {
7313 0 => {
7314 if version >= 9 {
7315 // v9+: BTree entries serialised inline (tag-prefixed
7316 // locator codec). Restore the map directly so any
7317 // freezer-produced Cold locators come back exactly
7318 // as they went out.
7319 let map = read_btree_map(cur)?;
7320 t.restore_btree_index(idx_name, &column_name, map)?;
7321 } else {
7322 // v8: no entries on disk; rebuild from rows. Every
7323 // entry is materialised as `RowLocator::Hot(i)` —
7324 // semantically identical to the v5.1 in-memory state
7325 // since v8 catalogs never produced Cold locators.
7326 t.add_index(idx_name, &column_name)?;
7327 }
7328 }
7329 1 => {
7330 let m = cur.read_u16()? as usize;
7331 let graph = cur.read_nsw_graph(m)?;
7332 t.restore_nsw_index(idx_name, &column_name, graph)?;
7333 }
7334 2 => {
7335 // v6.7.1 — BRIN tag. Payload is the column type
7336 // tag. No further data — summaries live in cold
7337 // segments.
7338 let column_type = cur.read_data_type()?;
7339 t.restore_brin_index(idx_name, &column_name, column_type)?;
7340 }
7341 3 => {
7342 // v7.12.3 — GIN tag. Payload mirrors the BTree
7343 // encoding but with String (lexeme word) keys.
7344 // Only emitted by FILE_VERSION 21+ writers — v20
7345 // and earlier degraded `USING gin` to BTree.
7346 let map = read_gin_map(cur)?;
7347 t.restore_gin_index(idx_name, &column_name, map)?;
7348 }
7349 4 => {
7350 // v7.15.0 — trigram-GIN tag (`gin_trgm_ops`).
7351 // Same payload shape as tag 3 (String → posting
7352 // list); only emitted by FILE_VERSION 24+ writers.
7353 if version < 24 {
7354 return Err(StorageError::Corrupt(format!(
7355 "trigram-GIN index tag 4 found in catalog FILE_VERSION {version}; \
7356 FILE_VERSION 24+ required (v7.15.0 introduced this tag)"
7357 )));
7358 }
7359 let map = read_gin_map(cur)?;
7360 t.restore_gin_trgm_index(idx_name, &column_name, map)?;
7361 }
7362 5 => {
7363 // v7.17.0 Phase 2.2 — fulltext-GIN tag (MySQL
7364 // `FULLTEXT KEY` surface). Same payload shape as
7365 // tag 3 / tag 4 (String → posting list); only
7366 // emitted by FILE_VERSION 33+ writers.
7367 if version < 33 {
7368 return Err(StorageError::Corrupt(format!(
7369 "fulltext-GIN index tag 5 found in catalog FILE_VERSION {version}; \
7370 FILE_VERSION 33+ required (v7.17.0 Phase 2.2 introduced this tag)"
7371 )));
7372 }
7373 let map = read_gin_map(cur)?;
7374 t.restore_gin_fulltext_index(idx_name, &column_name, map)?;
7375 }
7376 other => {
7377 return Err(StorageError::Corrupt(format!(
7378 "unknown index kind tag: {other}"
7379 )));
7380 }
7381 }
7382 // v6.8.0 — included_columns appendix per index. v11- snapshots
7383 // stop before this u16; v12+ always carries it (possibly 0).
7384 if version >= 12 {
7385 let num_included = cur.read_u16()? as usize;
7386 if num_included > 0 {
7387 let mut included: Vec<usize> = Vec::with_capacity(num_included);
7388 for _ in 0..num_included {
7389 let cp = cur.read_u16()? as usize;
7390 if cp >= t.schema.columns.len() {
7391 return Err(StorageError::Corrupt(format!(
7392 "INCLUDE column position {cp} out of range \
7393 ({} schema columns)",
7394 t.schema.columns.len()
7395 )));
7396 }
7397 included.push(cp);
7398 }
7399 if let Some(last) = t.indices.last_mut() {
7400 last.included_columns = included;
7401 }
7402 }
7403 // v6.8.1 — partial_predicate appendix.
7404 match cur.read_u8()? {
7405 0 => {}
7406 1 => {
7407 let pred = cur.read_str()?;
7408 if let Some(last) = t.indices.last_mut() {
7409 last.partial_predicate = Some(pred);
7410 }
7411 }
7412 other => {
7413 return Err(StorageError::Corrupt(format!(
7414 "partial_predicate tag: unknown byte {other}"
7415 )));
7416 }
7417 }
7418 // v6.8.2 — expression appendix.
7419 match cur.read_u8()? {
7420 0 => {}
7421 1 => {
7422 let expr = cur.read_str()?;
7423 if let Some(last) = t.indices.last_mut() {
7424 last.expression = Some(expr);
7425 }
7426 }
7427 other => {
7428 return Err(StorageError::Corrupt(format!(
7429 "expression tag: unknown byte {other}"
7430 )));
7431 }
7432 }
7433 // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
7434 // v15-and-below catalogs stop before this byte. mailrs K1.
7435 if version >= 16 {
7436 match cur.read_u8()? {
7437 0 => {}
7438 1 => {
7439 if let Some(last) = t.indices.last_mut() {
7440 last.is_unique = true;
7441 }
7442 }
7443 other => {
7444 return Err(StorageError::Corrupt(format!(
7445 "is_unique tag: unknown byte {other}"
7446 )));
7447 }
7448 }
7449 // v7.9.29 — extra_column_positions appendix.
7450 let n = cur.read_u16()? as usize;
7451 if n > 0 {
7452 let mut extras: Vec<usize> = Vec::with_capacity(n);
7453 for _ in 0..n {
7454 let cp = cur.read_u16()? as usize;
7455 if cp >= t.schema.columns.len() {
7456 return Err(StorageError::Corrupt(format!(
7457 "extra column position {cp} out of range \
7458 ({} schema columns)",
7459 t.schema.columns.len()
7460 )));
7461 }
7462 extras.push(cp);
7463 }
7464 if let Some(last) = t.indices.last_mut() {
7465 last.extra_column_positions = extras;
7466 }
7467 }
7468 }
7469 }
7470 }
7471 Ok(())
7472}
7473
7474/// Parse a v9 `BTree` index payload — `[u32 entry_count]` followed by
7475/// `entry_count` `(IndexKey, Vec<RowLocator>)` pairs. The locator list
7476/// uses the v5.1 tag-prefixed wire format (`RowLocator::read_le`).
7477fn read_btree_map(
7478 cur: &mut Cursor<'_>,
7479) -> Result<PersistentBTreeMap<IndexKey, Vec<RowLocator>>, StorageError> {
7480 let entry_count = cur.read_u32()? as usize;
7481 let mut map = PersistentBTreeMap::new();
7482 for _ in 0..entry_count {
7483 let key = cur.read_index_key()?;
7484 let locator_count = cur.read_u32()? as usize;
7485 let mut locators = Vec::with_capacity(locator_count);
7486 for _ in 0..locator_count {
7487 let tail = &cur.buf[cur.pos..];
7488 let (loc, consumed) = RowLocator::read_le(tail).map_err(|e| {
7489 StorageError::Corrupt(format!("row_locator decode at offset {}: {e}", cur.pos))
7490 })?;
7491 cur.pos += consumed;
7492 locators.push(loc);
7493 }
7494 map.insert_mut(key, locators);
7495 }
7496 Ok(map)
7497}
7498
7499/// v7.12.3 — parse a `Gin` index payload. Mirrors [`read_btree_map`]
7500/// but with `String` (lexeme word) keys instead of `IndexKey`.
7501/// FILE_VERSION 21+ only.
7502fn read_gin_map(
7503 cur: &mut Cursor<'_>,
7504) -> Result<PersistentBTreeMap<String, Vec<RowLocator>>, StorageError> {
7505 let entry_count = cur.read_u32()? as usize;
7506 let mut map = PersistentBTreeMap::new();
7507 for _ in 0..entry_count {
7508 let word = cur.read_str()?;
7509 let locator_count = cur.read_u32()? as usize;
7510 let mut locators = Vec::with_capacity(locator_count);
7511 for _ in 0..locator_count {
7512 let tail = &cur.buf[cur.pos..];
7513 let (loc, consumed) = RowLocator::read_le(tail).map_err(|e| {
7514 StorageError::Corrupt(format!("row_locator decode at offset {}: {e}", cur.pos))
7515 })?;
7516 cur.pos += consumed;
7517 locators.push(loc);
7518 }
7519 map.insert_mut(word, locators);
7520 }
7521 Ok(map)
7522}
7523
7524// --- low-level binary helpers ---------------------------------------------
7525
7526/// Write a `DataType` as a tag byte + optional payload (Vector carries its
7527/// `u32` dimension). Inverse: [`read_data_type`].
7528/// Serialize an HNSW graph after the `[kind=1][u16 M]` header (v7).
7529/// Layout:
7530/// - `[u16 m_max_0]`
7531/// - `[entry u32]` — `u32::MAX` means `None`, else the entry node index
7532/// - `[u8 entry_level]`
7533/// - `[node_count u32]`
7534/// - for each node: `[u8 level]` (top layer for this node)
7535/// - `[layer_count u8]`
7536/// - for each layer `0..layer_count`:
7537/// - `[u32 layer_node_count]` (== `node_count`; per-layer slot)
7538/// - for each node: `[u16 neighbor_count] [u32 neighbor]*`
7539fn write_nsw_graph(out: &mut Vec<u8>, g: &NswGraph) {
7540 let entry = g.entry.map_or(u32::MAX, |e| {
7541 u32::try_from(e).expect("NSW entry fits in u32")
7542 });
7543 write_u16(
7544 out,
7545 u16::try_from(g.m_max_0).expect("HNSW m_max_0 fits in u16"),
7546 );
7547 out.extend_from_slice(&entry.to_le_bytes());
7548 out.push(g.entry_level);
7549 let node_count = g.levels.len();
7550 write_u32(
7551 out,
7552 u32::try_from(node_count).expect("HNSW node count fits in u32"),
7553 );
7554 for &lvl in &g.levels {
7555 out.push(lvl);
7556 }
7557 let layer_count = u8::try_from(g.layers.len()).expect("HNSW layer count ≤ 255");
7558 out.push(layer_count);
7559 for layer in &g.layers {
7560 write_u32(
7561 out,
7562 u32::try_from(layer.len()).expect("HNSW per-layer node count fits in u32"),
7563 );
7564 for neighbors in layer {
7565 write_u16(
7566 out,
7567 u16::try_from(neighbors.len()).expect("HNSW neighbour list fits in u16"),
7568 );
7569 // v6.1.x: neighbour slot is already u32 in memory; just
7570 // emit the raw bytes. (v6.0 stored usize and converted
7571 // here.)
7572 for &peer in neighbors {
7573 write_u32(out, peer);
7574 }
7575 }
7576 }
7577}
7578
7579fn write_data_type(out: &mut Vec<u8>, t: DataType) {
7580 match t {
7581 DataType::Int => out.push(1),
7582 DataType::BigInt => out.push(2),
7583 DataType::Float => out.push(3),
7584 DataType::Text => out.push(4),
7585 DataType::Bool => out.push(5),
7586 DataType::Vector { dim, encoding } => match encoding {
7587 // Tag 6: pre-v6 F32 vector. Layout unchanged; pre-v6
7588 // binaries continue to deserialise this exactly as
7589 // before.
7590 VecEncoding::F32 => {
7591 out.push(6);
7592 out.extend_from_slice(&dim.to_le_bytes());
7593 }
7594 // v6.0.3: tag 15 for `VECTOR(N) USING HALF`. Same
7595 // forward-compat fence story as SQ8 below.
7596 VecEncoding::F16 => {
7597 out.push(15);
7598 out.extend_from_slice(&dim.to_le_bytes());
7599 }
7600 // v6.0.1: new tag 14 for `VECTOR(N) USING SQ8` column
7601 // type. Pre-v6 readers fall through `read_data_type`'s
7602 // catch-all and surface `Corrupt("unknown data type tag")`
7603 // — the explicit forward-compat fence called out in
7604 // V6_DESIGN deliberation #5.
7605 VecEncoding::Sq8 => {
7606 out.push(14);
7607 out.extend_from_slice(&dim.to_le_bytes());
7608 }
7609 },
7610 DataType::SmallInt => out.push(7),
7611 DataType::Varchar(max) => {
7612 out.push(8);
7613 out.extend_from_slice(&max.to_le_bytes());
7614 }
7615 DataType::Char(size) => {
7616 out.push(9);
7617 out.extend_from_slice(&size.to_le_bytes());
7618 }
7619 DataType::Numeric { precision, scale } => {
7620 out.push(10);
7621 out.push(precision);
7622 out.push(scale);
7623 }
7624 DataType::Date => out.push(11),
7625 DataType::Timestamp => out.push(12),
7626 // v7.9.2 — tag 17 for TIMESTAMPTZ. Body = i64 microseconds
7627 // UTC, identical to tag 12. Only the schema-side type tag
7628 // differs (for wire OID advertisement).
7629 DataType::Timestamptz => out.push(17),
7630 // INTERVAL is runtime-only — CREATE TABLE never produces a
7631 // column with this type, so write_data_type must not be called
7632 // on it. (Disk-format codepoint reserved for a future v3 where
7633 // INTERVAL becomes storable.)
7634 DataType::Interval => {
7635 unreachable!("DataType::Interval has no on-disk encoding in v2.11")
7636 }
7637 DataType::Json => out.push(13),
7638 // v7.9.0: tag 16 for `JSONB`. Same on-disk layout as
7639 // tag 13 — only the wire OID differs.
7640 DataType::Jsonb => out.push(16),
7641 // v7.10.4: tag 18 for `BYTEA`. Body = [u16 len][bytes].
7642 DataType::Bytes => out.push(18),
7643 // v7.10.9: tag 19 for `TEXT[]`. Body = [u16 count][per
7644 // element: u8 null + (if non-null) u16 len + utf-8].
7645 DataType::TextArray => out.push(19),
7646 // v7.11.12: tag 20 for `INT[]`. Body = [u16 count][per
7647 // element: u8 null + (if non-null) i32 LE].
7648 DataType::IntArray => out.push(20),
7649 // v7.11.12: tag 21 for `BIGINT[]`. Body = [u16 count][per
7650 // element: u8 null + (if non-null) i64 LE].
7651 DataType::BigIntArray => out.push(21),
7652 // v7.12.0: tag 22 for `tsvector`. No body — type identity
7653 // alone. Catalog FILE_VERSION 20+.
7654 DataType::TsVector => out.push(22),
7655 // v7.12.0: tag 23 for `tsquery`. No body. Catalog
7656 // FILE_VERSION 20+.
7657 DataType::TsQuery => out.push(23),
7658 // v7.17.0: tag 24 for `UUID`. No body — type identity
7659 // alone. Catalog FILE_VERSION 36+.
7660 DataType::Uuid => out.push(24),
7661 // v7.17.0 Phase 3.P0-32: tag 25 for `TIME`. No body — type
7662 // identity alone. Catalog FILE_VERSION 37+.
7663 DataType::Time => out.push(25),
7664 // v7.17.0 Phase 3.P0-33: tag 26 for `YEAR`. No body — type
7665 // identity alone. Catalog FILE_VERSION 38+.
7666 DataType::Year => out.push(26),
7667 // v7.17.0 Phase 3.P0-34: tag 27 for `TIMETZ`. No body —
7668 // type identity alone. Catalog FILE_VERSION 39+.
7669 DataType::TimeTz => out.push(27),
7670 // v7.17.0 Phase 3.P0-35: tag 28 for `MONEY`. No body —
7671 // type identity alone. Catalog FILE_VERSION 40+.
7672 DataType::Money => out.push(28),
7673 // v7.17.0 Phase 3.P0-38: tag 29 for range types. Body
7674 // = `[u8 RangeKind tag]`. Catalog FILE_VERSION 43+.
7675 DataType::Range(k) => {
7676 out.push(29);
7677 out.push(k.tag());
7678 }
7679 // v7.17.0 Phase 3.P0-39: tag 30 for hstore. No body —
7680 // type identity alone. Catalog FILE_VERSION 44+.
7681 DataType::Hstore => out.push(30),
7682 // v7.17.0 Phase 3.P0-40: tag 31/32/33 for 2D arrays.
7683 // No body — type identity alone. Catalog FILE_VERSION 45+.
7684 DataType::IntArray2D => out.push(31),
7685 DataType::BigIntArray2D => out.push(32),
7686 DataType::TextArray2D => out.push(33),
7687 }
7688}
7689
7690impl Cursor<'_> {
7691 fn read_data_type(&mut self) -> Result<DataType, StorageError> {
7692 let tag = self.read_u8()?;
7693 match tag {
7694 1 => Ok(DataType::Int),
7695 2 => Ok(DataType::BigInt),
7696 3 => Ok(DataType::Float),
7697 4 => Ok(DataType::Text),
7698 5 => Ok(DataType::Bool),
7699 6 => Ok(DataType::Vector {
7700 dim: self.read_u32()?,
7701 encoding: VecEncoding::F32,
7702 }),
7703 7 => Ok(DataType::SmallInt),
7704 8 => Ok(DataType::Varchar(self.read_u32()?)),
7705 9 => Ok(DataType::Char(self.read_u32()?)),
7706 10 => {
7707 let precision = self.read_u8()?;
7708 let scale = self.read_u8()?;
7709 Ok(DataType::Numeric { precision, scale })
7710 }
7711 11 => Ok(DataType::Date),
7712 12 => Ok(DataType::Timestamp),
7713 13 => Ok(DataType::Json),
7714 14 => Ok(DataType::Vector {
7715 dim: self.read_u32()?,
7716 encoding: VecEncoding::Sq8,
7717 }),
7718 // v6.0.3: tag 15 for `VECTOR(N) USING HALF`. Same
7719 // [u32 dim] type-tag payload as F32 / SQ8; the encoding
7720 // lives in the tag byte itself.
7721 15 => Ok(DataType::Vector {
7722 dim: self.read_u32()?,
7723 encoding: VecEncoding::F16,
7724 }),
7725 // v7.9.0: tag 16 for `JSONB`. Storage shape == Json;
7726 // we only carry the type tag so the wire layer can
7727 // emit PG OID 3802 instead of 114.
7728 16 => Ok(DataType::Jsonb),
7729 // v7.9.2: tag 17 for `TIMESTAMPTZ`. Storage shape ==
7730 // Timestamp (i64 microseconds UTC); only the wire OID
7731 // (1184) differs.
7732 17 => Ok(DataType::Timestamptz),
7733 // v7.10.4: tag 18 for `BYTEA`. Catalog FILE_VERSION 17+.
7734 18 => Ok(DataType::Bytes),
7735 // v7.10.9: tag 19 for `TEXT[]`. Catalog FILE_VERSION 18+.
7736 19 => Ok(DataType::TextArray),
7737 // v7.11.12: tags 20/21 for INT[]/BIGINT[]. FILE_VERSION 19+.
7738 20 => Ok(DataType::IntArray),
7739 21 => Ok(DataType::BigIntArray),
7740 // v7.12.0: tags 22/23 for tsvector / tsquery. Catalog
7741 // FILE_VERSION 20+.
7742 22 => Ok(DataType::TsVector),
7743 23 => Ok(DataType::TsQuery),
7744 // v7.17.0: tag 24 — UUID. Catalog FILE_VERSION 36+.
7745 24 => Ok(DataType::Uuid),
7746 // v7.17.0 Phase 3.P0-32: tag 25 — TIME. Catalog
7747 // FILE_VERSION 37+.
7748 25 => Ok(DataType::Time),
7749 // v7.17.0 Phase 3.P0-33: tag 26 — YEAR. Catalog
7750 // FILE_VERSION 38+.
7751 26 => Ok(DataType::Year),
7752 // v7.17.0 Phase 3.P0-34: tag 27 — TIMETZ. Catalog
7753 // FILE_VERSION 39+.
7754 27 => Ok(DataType::TimeTz),
7755 // v7.17.0 Phase 3.P0-35: tag 28 — MONEY. Catalog
7756 // FILE_VERSION 40+.
7757 28 => Ok(DataType::Money),
7758 // v7.17.0 Phase 3.P0-38: tag 29 + RangeKind tag.
7759 29 => {
7760 let kt = self.read_u8()?;
7761 let k = RangeKind::from_tag(kt)
7762 .ok_or_else(|| StorageError::Corrupt(format!("unknown RangeKind tag: {kt}")))?;
7763 Ok(DataType::Range(k))
7764 }
7765 // v7.17.0 Phase 3.P0-39: tag 30 — HSTORE.
7766 30 => Ok(DataType::Hstore),
7767 // v7.17.0 Phase 3.P0-40: tag 31/32/33 — 2D arrays.
7768 31 => Ok(DataType::IntArray2D),
7769 32 => Ok(DataType::BigIntArray2D),
7770 33 => Ok(DataType::TextArray2D),
7771 other => Err(StorageError::Corrupt(format!(
7772 "unknown data type tag: {other}"
7773 ))),
7774 }
7775 }
7776}
7777
7778/// Fast computation of the byte length [`encode_row_body_dense`]
7779/// would produce, without allocating the output buffer. Mirrors the
7780/// encoder's per-column body sizing so the v5.2.1 `Table::hot_bytes`
7781/// incremental counter doesn't pay an alloc-per-insert tax. Returns
7782/// the exact same `usize` as `encode_row_body_dense(row, schema).len()`.
7783pub fn row_body_encoded_len(row: &Row, schema: &TableSchema) -> usize {
7784 debug_assert_eq!(
7785 row.values.len(),
7786 schema.columns.len(),
7787 "row_body_encoded_len: row arity must match schema"
7788 );
7789 let bitmap_bytes = schema.columns.len().div_ceil(8);
7790 let mut n = bitmap_bytes;
7791 for (col_idx, v) in row.values.iter().enumerate() {
7792 if matches!(v, Value::Null) {
7793 continue;
7794 }
7795 n += value_body_encoded_len(v, schema.columns[col_idx].ty);
7796 }
7797 n
7798}
7799
7800/// Byte length a single cell consumes when written by
7801/// `write_value_body`. Used by [`row_body_encoded_len`]; kept in
7802/// lock-step with the encoder. The `_ty` slot is reserved for future
7803/// type-dependent encodings — every variant currently writes a fixed
7804/// body shape regardless of the declared column type.
7805fn value_body_encoded_len(v: &Value, _ty: DataType) -> usize {
7806 match v {
7807 Value::SmallInt(_) => 2,
7808 // 4-byte body: i32 / Date.
7809 Value::Int(_) | Value::Date(_) => 4,
7810 // 8-byte body: i64 / f64 / Timestamp.
7811 Value::BigInt(_) | Value::Float(_) | Value::Timestamp(_) => 8,
7812 Value::Bool(_) => 1,
7813 // Text/Varchar/Char/Json share the [u16 len][utf-8] layout.
7814 Value::Text(s) | Value::Json(s) => 2 + s.len(),
7815 // [u32 dim][f32 * dim]
7816 Value::Vector(vec) => 4 + 4 * vec.len(),
7817 // v6.0.1: SQ8 cell on-disk shape — [u32 dim][f32 min]
7818 // [f32 max][u8 * dim] = 12 + dim bytes. `hot_bytes`
7819 // tracking on `Table::insert` calls this every row, so
7820 // returning the real size now (even though the actual
7821 // `write_value_body` writer lands in step 6) keeps the
7822 // sizing arithmetic honest for in-memory benches.
7823 Value::Sq8Vector(q) => 4 + 4 + 4 + q.bytes.len(),
7824 // v6.0.3: halfvec on-disk shape — [u32 dim][u16 LE * dim]
7825 // = 4 + 2 * dim bytes.
7826 Value::HalfVector(h) => 4 + h.bytes.len(),
7827 // [i128 scaled][u8 scale]
7828 Value::Numeric { .. } => 16 + 1,
7829 // v7.10.4: BYTEA on-disk shape mirrors Text — [u16 len][bytes].
7830 // The 16-bit length cap is the same TEXT/JSON limit (~65 KB);
7831 // larger blobs need toast-style chunking which is a v7.11
7832 // carve-out (kept aligned with TEXT for now so the catalog
7833 // snapshot stays simple).
7834 Value::Bytes(b) => 2 + b.len(),
7835 // v7.10.9: TEXT[] on-disk shape — [u16 count][per element:
7836 // u8 null flag + (when non-null) u16 len + utf-8 bytes].
7837 Value::TextArray(items) => {
7838 let mut n = 2; // count prefix
7839 for item in items {
7840 n += 1; // null flag
7841 if let Some(s) = item {
7842 n += 2 + s.len();
7843 }
7844 }
7845 n
7846 }
7847 // v7.11.12: INT[] / BIGINT[] — [u16 count][per element:
7848 // u8 null + (when non-null) fixed-width LE].
7849 Value::IntArray(items) => {
7850 2 + items
7851 .iter()
7852 .map(|x| if x.is_some() { 5 } else { 1 })
7853 .sum::<usize>()
7854 }
7855 Value::BigIntArray(items) => {
7856 2 + items
7857 .iter()
7858 .map(|x| if x.is_some() { 9 } else { 1 })
7859 .sum::<usize>()
7860 }
7861 // v7.12.0: tsvector dense body — [u16 lexeme_count][per
7862 // lex: u16 word_len + utf-8 word + u16 pos_count + (u16
7863 // LE * pos_count) + u8 weight].
7864 Value::TsVector(lexs) => {
7865 let mut n = 2;
7866 for l in lexs {
7867 n += 2 + l.word.len() + 2 + 2 * l.positions.len() + 1;
7868 }
7869 n
7870 }
7871 // v7.12.0: tsquery dense body — prefix-coded tree.
7872 // Sizing must match `write_tsquery_body` walker.
7873 Value::TsQuery(ast) => tsquery_encoded_len(ast),
7874 // v7.17.0: UUID dense body — fixed 16 bytes, no prefix.
7875 Value::Uuid(_) => 16,
7876 // v7.17.0 Phase 3.P0-32: TIME dense body — fixed i64 LE.
7877 Value::Time(_) => 8,
7878 // v7.17.0 Phase 3.P0-33: YEAR dense body — fixed u16 LE.
7879 Value::Year(_) => 2,
7880 // v7.17.0 Phase 3.P0-34: TIMETZ dense body — i64 LE + i32 LE.
7881 Value::TimeTz { .. } => 12,
7882 // v7.17.0 Phase 3.P0-35: MONEY dense body — i64 LE cents.
7883 Value::Money(_) => 8,
7884 // v7.17.0 Phase 3.P0-38: range dense body — `[u8 flags]
7885 // [if lower: write_value(lower)] [if upper: write_value(upper)]`.
7886 // Element uses the schema-agnostic write_value codec
7887 // (which carries its own tag byte). The flags byte
7888 // captures empty/lower_some/upper_some/lower_inc/upper_inc.
7889 Value::Range { lower, upper, .. } => {
7890 1 + lower
7891 .as_ref()
7892 .map(|v| write_value_encoded_len(v))
7893 .unwrap_or(0)
7894 + upper
7895 .as_ref()
7896 .map(|v| write_value_encoded_len(v))
7897 .unwrap_or(0)
7898 }
7899 // v7.17.0 Phase 3.P0-39: hstore dense body — `[u32 count]
7900 // then per pair [u32 klen][k bytes][u8 has_val][if has_val:
7901 // u32 vlen][v bytes]`.
7902 Value::Hstore(pairs) => {
7903 let mut n = 4;
7904 for (k, v) in pairs {
7905 n += 4 + k.len() + 1;
7906 if let Some(val) = v {
7907 n += 4 + val.len();
7908 }
7909 }
7910 n
7911 }
7912 // v7.17.0 Phase 3.P0-40: 2D arrays dense body — `[u32 rows]
7913 // [u32 cols] then row-major elements with per-element
7914 // `[u8 null_flag][if non-null: element body]`.
7915 Value::IntArray2D(rows) => {
7916 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
7917 8 + rows.len() * cols * (1 + 4)
7918 }
7919 Value::BigIntArray2D(rows) => {
7920 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
7921 8 + rows.len() * cols * (1 + 8)
7922 }
7923 Value::TextArray2D(rows) => {
7924 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
7925 let mut n = 8 + rows.len() * cols;
7926 for row in rows {
7927 for s in row.iter().flatten() {
7928 n += 4 + s.len();
7929 }
7930 }
7931 n
7932 }
7933 // NULL is encoded only in the bitmap, never in the body.
7934 Value::Null => 0,
7935 // INTERVAL has no on-disk encoding (see write_value_body).
7936 Value::Interval { .. } => {
7937 unreachable!("Value::Interval has no on-disk encoding")
7938 }
7939 }
7940}
7941
7942/// Encode one row's body in the v3.0.2 dense format (`FILE_VERSION`
7943/// 8): per-row NULL bitmap (1 bit/col, ceil(cols/8) bytes), then
7944/// each non-NULL cell as `write_value_body`. Same wire shape the
7945/// catalog snapshot writes per row inside its rows-block. Exposed
7946/// pub so v5.1+ cold-tier segment writers can produce row payloads
7947/// that the catalog [`decode_row_body_dense`] decodes 1:1.
7948///
7949/// `row.values.len()` must equal `schema.columns.len()` — the row
7950/// is expected to have been validated by `Table::insert` (the
7951/// engine's INSERT path) before reaching this function.
7952pub fn encode_row_body_dense(row: &Row, schema: &TableSchema) -> Vec<u8> {
7953 debug_assert_eq!(
7954 row.values.len(),
7955 schema.columns.len(),
7956 "dense encode: row arity must match schema"
7957 );
7958 let bitmap_bytes = schema.columns.len().div_ceil(8);
7959 // 8 B per fixed-width cell is a reasonable average; the buffer
7960 // grows past this for variable-width Text/Vector cells.
7961 let mut out = Vec::with_capacity(bitmap_bytes + schema.columns.len() * 8);
7962 let bitmap_offset = out.len();
7963 out.resize(bitmap_offset + bitmap_bytes, 0);
7964 for (i, v) in row.values.iter().enumerate() {
7965 if matches!(v, Value::Null) {
7966 out[bitmap_offset + i / 8] |= 1 << (i % 8);
7967 }
7968 }
7969 for (col_idx, v) in row.values.iter().enumerate() {
7970 if matches!(v, Value::Null) {
7971 continue;
7972 }
7973 write_value_body(&mut out, v, schema.columns[col_idx].ty);
7974 }
7975 out
7976}
7977
7978/// Inverse of [`encode_row_body_dense`]. Reads one row's body from
7979/// `bytes` and returns it plus the number of bytes consumed (so a
7980/// caller decoding a back-to-back stream of rows can advance its
7981/// cursor). Returns `StorageError::Corrupt` on truncation, bad
7982/// UTF-8, or unknown cell tags.
7983pub fn decode_row_body_dense(
7984 bytes: &[u8],
7985 schema: &TableSchema,
7986) -> Result<(Row, usize), StorageError> {
7987 let mut cur = Cursor::new(bytes);
7988 let bitmap_bytes = schema.columns.len().div_ceil(8);
7989 let mut bitmap_buf = [0u8; 32];
7990 if bitmap_bytes > bitmap_buf.len() {
7991 return Err(StorageError::Corrupt(format!(
7992 "row NULL bitmap {bitmap_bytes} B exceeds 32 B cap"
7993 )));
7994 }
7995 let slice = cur.take(bitmap_bytes)?;
7996 bitmap_buf[..bitmap_bytes].copy_from_slice(slice);
7997 let mut values = Vec::with_capacity(schema.columns.len());
7998 for (col_idx, col) in schema.columns.iter().enumerate() {
7999 if (bitmap_buf[col_idx / 8] >> (col_idx % 8)) & 1 == 1 {
8000 values.push(Value::Null);
8001 } else {
8002 values.push(cur.read_value_body(col.ty)?);
8003 }
8004 }
8005 Ok((Row { values }, cur.pos))
8006}
8007
8008/// Schema-driven dense value encoding (`FILE_VERSION` 8). Caller already
8009/// knows the column type and has decided this cell is non-NULL, so we
8010/// skip the per-cell type tag the v7 `write_value` was writing. NULL
8011/// is encoded via the per-row bitmap before this function runs, never
8012/// reaches here. Used only inside the row-encoding hot loop; the
8013/// schema-default path still goes through the legacy `write_value` so
8014/// DEFAULT values keep their self-describing tag and remain decodable
8015/// without consulting a column type.
8016fn write_value_body(out: &mut Vec<u8>, v: &Value, ty: DataType) {
8017 match (v, ty) {
8018 (Value::SmallInt(n), DataType::SmallInt) => out.extend_from_slice(&n.to_le_bytes()),
8019 (Value::Int(n), DataType::Int) => out.extend_from_slice(&n.to_le_bytes()),
8020 (Value::BigInt(n), DataType::BigInt) => out.extend_from_slice(&n.to_le_bytes()),
8021 (Value::Float(x), DataType::Float) => out.extend_from_slice(&x.to_le_bytes()),
8022 (Value::Bool(b), DataType::Bool) => out.push(u8::from(*b)),
8023 (Value::Text(s), DataType::Text | DataType::Varchar(_) | DataType::Char(_)) => {
8024 write_str(out, s);
8025 }
8026 (
8027 Value::Vector(v),
8028 DataType::Vector {
8029 encoding: VecEncoding::F32,
8030 ..
8031 },
8032 ) => {
8033 let dim = u32::try_from(v.len()).expect("vector dim fits in u32");
8034 out.extend_from_slice(&dim.to_le_bytes());
8035 for x in v {
8036 out.extend_from_slice(&x.to_le_bytes());
8037 }
8038 }
8039 // v6.0.1: SQ8 dense body — [u32 dim][f32 min][f32 max]
8040 // [u8 * dim]. Self-describes its length so v6 readers
8041 // walking rows of a v6 catalog stay aligned even if the
8042 // declared column dim drifts (defensive, not normally
8043 // possible since CREATE TABLE pins the dim).
8044 (
8045 Value::Sq8Vector(q),
8046 DataType::Vector {
8047 encoding: VecEncoding::Sq8,
8048 ..
8049 },
8050 ) => {
8051 let dim = u32::try_from(q.bytes.len()).expect("vector dim fits in u32");
8052 out.extend_from_slice(&dim.to_le_bytes());
8053 out.extend_from_slice(&q.min.to_le_bytes());
8054 out.extend_from_slice(&q.max.to_le_bytes());
8055 out.extend_from_slice(&q.bytes);
8056 }
8057 // v6.0.3: halfvec dense body — [u32 dim][u16 LE * dim].
8058 // The raw u16 bytes already live in `h.bytes` little-
8059 // endian, so we just splat them.
8060 (
8061 Value::HalfVector(h),
8062 DataType::Vector {
8063 encoding: VecEncoding::F16,
8064 ..
8065 },
8066 ) => {
8067 let dim = u32::try_from(h.dim()).expect("vector dim fits in u32");
8068 out.extend_from_slice(&dim.to_le_bytes());
8069 out.extend_from_slice(&h.bytes);
8070 }
8071 (Value::Numeric { scaled, .. }, DataType::Numeric { scale, .. }) => {
8072 out.extend_from_slice(&scaled.to_le_bytes());
8073 out.push(scale);
8074 }
8075 (Value::Date(d), DataType::Date) => out.extend_from_slice(&d.to_le_bytes()),
8076 (Value::Timestamp(t), DataType::Timestamp | DataType::Timestamptz) => {
8077 out.extend_from_slice(&t.to_le_bytes())
8078 }
8079 // v4.9: JSON stores as length-prefixed text; same shape as
8080 // Text — the type tag lives in the column schema, not the
8081 // per-cell body.
8082 (Value::Json(s), DataType::Json | DataType::Jsonb) => write_str(out, s),
8083 // v7.10.4: BYTEA shares the [u16 len][bytes] shape with
8084 // Text but writes raw bytes (no UTF-8 invariant).
8085 (Value::Bytes(b), DataType::Bytes) => {
8086 let len = u16::try_from(b.len()).expect("BYTEA cell ≤ 64 KiB");
8087 out.extend_from_slice(&len.to_le_bytes());
8088 out.extend_from_slice(b);
8089 }
8090 // v7.10.9: TEXT[] dense body — [u16 count][per element:
8091 // u8 null flag + (when non-null) u16 len + utf-8 bytes].
8092 (Value::TextArray(items), DataType::TextArray) => {
8093 let count = u16::try_from(items.len()).expect("TEXT[] ≤ 65k elements");
8094 out.extend_from_slice(&count.to_le_bytes());
8095 for item in items {
8096 match item {
8097 None => out.push(1),
8098 Some(s) => {
8099 out.push(0);
8100 let len = u16::try_from(s.len()).expect("TEXT[] element ≤ 64 KiB");
8101 out.extend_from_slice(&len.to_le_bytes());
8102 out.extend_from_slice(s.as_bytes());
8103 }
8104 }
8105 }
8106 }
8107 // v7.11.12: INT[] dense body — [u16 count][per element:
8108 // u8 null + (when non-null) i32 LE].
8109 (Value::IntArray(items), DataType::IntArray) => {
8110 let count = u16::try_from(items.len()).expect("INT[] ≤ 65k elements");
8111 out.extend_from_slice(&count.to_le_bytes());
8112 for item in items {
8113 match item {
8114 None => out.push(1),
8115 Some(n) => {
8116 out.push(0);
8117 out.extend_from_slice(&n.to_le_bytes());
8118 }
8119 }
8120 }
8121 }
8122 // v7.11.12: BIGINT[] dense body — [u16 count][per element:
8123 // u8 null + (when non-null) i64 LE].
8124 (Value::BigIntArray(items), DataType::BigIntArray) => {
8125 let count = u16::try_from(items.len()).expect("BIGINT[] ≤ 65k elements");
8126 out.extend_from_slice(&count.to_le_bytes());
8127 for item in items {
8128 match item {
8129 None => out.push(1),
8130 Some(n) => {
8131 out.push(0);
8132 out.extend_from_slice(&n.to_le_bytes());
8133 }
8134 }
8135 }
8136 }
8137 // v7.12.0: tsvector dense body — see `value_body_encoded_len`
8138 // for layout. Lexemes are written in their already-sorted order.
8139 (Value::TsVector(lexs), DataType::TsVector) => write_tsvector_body(out, lexs),
8140 // v7.12.0: tsquery dense body — prefix-coded tree.
8141 (Value::TsQuery(ast), DataType::TsQuery) => write_tsquery_body(out, ast),
8142 // v7.17.0: UUID dense body — raw 16 bytes (RFC 4122 byte
8143 // order). No length prefix; the type's fixed width makes
8144 // the codec stateless.
8145 (Value::Uuid(b), DataType::Uuid) => out.extend_from_slice(&b[..]),
8146 // v7.17.0 Phase 3.P0-32: TIME dense body — i64 LE
8147 // microseconds since 00:00:00.
8148 (Value::Time(us), DataType::Time) => out.extend_from_slice(&us.to_le_bytes()),
8149 // v7.17.0 Phase 3.P0-33: YEAR dense body — u16 LE.
8150 (Value::Year(y), DataType::Year) => out.extend_from_slice(&y.to_le_bytes()),
8151 // v7.17.0 Phase 3.P0-34: TIMETZ dense body — i64 LE us +
8152 // i32 LE offset_secs.
8153 (Value::TimeTz { us, offset_secs }, DataType::TimeTz) => {
8154 out.extend_from_slice(&us.to_le_bytes());
8155 out.extend_from_slice(&offset_secs.to_le_bytes());
8156 }
8157 // v7.17.0 Phase 3.P0-35: MONEY dense body — i64 LE cents.
8158 (Value::Money(c), DataType::Money) => out.extend_from_slice(&c.to_le_bytes()),
8159 // v7.17.0 Phase 3.P0-38: range dense body — see
8160 // value_body_encoded_len for layout. `kind` is implicit
8161 // from the column DataType.
8162 (
8163 Value::Range {
8164 lower,
8165 upper,
8166 lower_inc,
8167 upper_inc,
8168 empty,
8169 ..
8170 },
8171 DataType::Range(_),
8172 ) => {
8173 let mut flags: u8 = 0;
8174 if *empty {
8175 flags |= 0b0000_0001;
8176 }
8177 if lower.is_some() {
8178 flags |= 0b0000_0010;
8179 }
8180 if upper.is_some() {
8181 flags |= 0b0000_0100;
8182 }
8183 if *lower_inc {
8184 flags |= 0b0000_1000;
8185 }
8186 if *upper_inc {
8187 flags |= 0b0001_0000;
8188 }
8189 out.push(flags);
8190 if let Some(l) = lower {
8191 write_value(out, l);
8192 }
8193 if let Some(u) = upper {
8194 write_value(out, u);
8195 }
8196 }
8197 // v7.17.0 Phase 3.P0-39: hstore dense body — same shape
8198 // as write_value_body for hstore (no leading tag — that
8199 // lives on the data type).
8200 (Value::Hstore(pairs), DataType::Hstore) => write_hstore_body(out, pairs),
8201 // v7.17.0 Phase 3.P0-40: 2D array dense body.
8202 (Value::IntArray2D(rows), DataType::IntArray2D) => write_int_2d_body(out, rows),
8203 (Value::BigIntArray2D(rows), DataType::BigIntArray2D) => write_bigint_2d_body(out, rows),
8204 (Value::TextArray2D(rows), DataType::TextArray2D) => write_text_2d_body(out, rows),
8205 // Type mismatch shouldn't happen — `Table::insert` validates
8206 // value type against column type before pushing. Treat as a
8207 // bug, not a runtime error.
8208 (other, ty) => unreachable!(
8209 "schema-driven encode received mismatched value/type pair: \
8210 value tag={:?}, column type={:?}",
8211 other.data_type(),
8212 ty
8213 ),
8214 }
8215}
8216
8217/// v7.17.0 Phase 3.P0-38 — length the schema-agnostic
8218/// `write_value` would emit for `v`. Used by the range codec to
8219/// pre-size cells. We mirror the tag-byte + body shape from
8220/// `write_value` rather than serialising to a temp Vec.
8221fn write_value_encoded_len(v: &Value) -> usize {
8222 match v {
8223 Value::Null => 1,
8224 Value::SmallInt(_) => 1 + 2,
8225 Value::Int(_) | Value::Date(_) => 1 + 4,
8226 Value::BigInt(_)
8227 | Value::Float(_)
8228 | Value::Timestamp(_)
8229 | Value::Time(_)
8230 | Value::Money(_) => 1 + 8,
8231 Value::Bool(_) => 1 + 1,
8232 Value::Year(_) => 1 + 2,
8233 Value::Text(s) | Value::Json(s) => 1 + 4 + s.len(),
8234 Value::Bytes(b) => 1 + 4 + b.len(),
8235 Value::Numeric { .. } => 1 + 16 + 1,
8236 Value::Uuid(_) => 1 + 16,
8237 Value::TimeTz { .. } => 1 + 12,
8238 Value::Hstore(pairs) => {
8239 let mut n = 1 + 4;
8240 for (k, v) in pairs {
8241 n += 4 + k.len() + 1;
8242 if let Some(val) = v {
8243 n += 4 + val.len();
8244 }
8245 }
8246 n
8247 }
8248 Value::IntArray2D(rows) => {
8249 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
8250 1 + 8 + rows.len() * cols * (1 + 4)
8251 }
8252 Value::BigIntArray2D(rows) => {
8253 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
8254 1 + 8 + rows.len() * cols * (1 + 8)
8255 }
8256 Value::TextArray2D(rows) => {
8257 let cols = rows.first().map(|r| r.len()).unwrap_or(0);
8258 let mut n = 1 + 8 + rows.len() * cols;
8259 for row in rows {
8260 for s in row.iter().flatten() {
8261 n += 4 + s.len();
8262 }
8263 }
8264 n
8265 }
8266 // Range-of-range and other nested cases — not currently
8267 // representable but defensively measured via the dense
8268 // body when the data_type is known.
8269 other => {
8270 let ty = other.data_type().unwrap_or(DataType::Int);
8271 1 + value_body_encoded_len(other, ty)
8272 }
8273 }
8274}
8275
8276fn write_value(out: &mut Vec<u8>, v: &Value) {
8277 match v {
8278 Value::Null => out.push(0),
8279 Value::SmallInt(n) => {
8280 out.push(7);
8281 out.extend_from_slice(&n.to_le_bytes());
8282 }
8283 Value::Int(n) => {
8284 out.push(1);
8285 out.extend_from_slice(&n.to_le_bytes());
8286 }
8287 Value::BigInt(n) => {
8288 out.push(2);
8289 out.extend_from_slice(&n.to_le_bytes());
8290 }
8291 Value::Float(x) => {
8292 out.push(3);
8293 out.extend_from_slice(&x.to_le_bytes());
8294 }
8295 // v4.9: JSON shares the tag-4 (Text) on-disk encoding —
8296 // schema decides which variant comes back on read. The
8297 // bodies are byte-identical so collapsing the match keeps
8298 // clippy::match_same_arms quiet.
8299 Value::Text(s) | Value::Json(s) => {
8300 out.push(4);
8301 write_str(out, s);
8302 }
8303 Value::Bool(b) => {
8304 out.push(5);
8305 out.push(u8::from(*b));
8306 }
8307 Value::Vector(v) => {
8308 out.push(6);
8309 let dim = u32::try_from(v.len()).expect("vector dim fits in u32");
8310 out.extend_from_slice(&dim.to_le_bytes());
8311 for x in v {
8312 out.extend_from_slice(&x.to_le_bytes());
8313 }
8314 }
8315 // v6.0.1: new tag 11 for an SQ8 cell carried with its full
8316 // header. Layout matches the dense row body shape so a
8317 // round-trip through write_value → read_value bit-equals
8318 // the original `Value::Sq8Vector`.
8319 Value::Sq8Vector(q) => {
8320 out.push(11);
8321 let dim = u32::try_from(q.bytes.len()).expect("vector dim fits in u32");
8322 out.extend_from_slice(&dim.to_le_bytes());
8323 out.extend_from_slice(&q.min.to_le_bytes());
8324 out.extend_from_slice(&q.max.to_le_bytes());
8325 out.extend_from_slice(&q.bytes);
8326 }
8327 // v6.0.3: tag 12 for a HalfVector cell.
8328 // Layout: `[u32 dim][u16 LE × dim]` — bit-identical to the
8329 // dense row body so `write_value` / `read_value` bit-equal
8330 // the original `Value::HalfVector`.
8331 Value::HalfVector(h) => {
8332 out.push(12);
8333 let dim = u32::try_from(h.dim()).expect("vector dim fits in u32");
8334 out.extend_from_slice(&dim.to_le_bytes());
8335 out.extend_from_slice(&h.bytes);
8336 }
8337 Value::Numeric { scaled, scale } => {
8338 out.push(8);
8339 out.extend_from_slice(&scaled.to_le_bytes());
8340 out.push(*scale);
8341 }
8342 Value::Date(d) => {
8343 out.push(9);
8344 out.extend_from_slice(&d.to_le_bytes());
8345 }
8346 Value::Timestamp(t) => {
8347 out.push(10);
8348 out.extend_from_slice(&t.to_le_bytes());
8349 }
8350 // Interval is a runtime-only value (no on-disk representation in
8351 // v2.11). CREATE TABLE rejects `DataType::Interval` columns, so a
8352 // Value::Interval here would mean the engine bypassed that gate.
8353 Value::Interval { .. } => {
8354 unreachable!(
8355 "Value::Interval has no on-disk encoding; engine must reject it before write"
8356 )
8357 }
8358 // v7.10.4: BYTEA — [u8 tag=13_b][u16 len][bytes]. Tag
8359 // distinct from Text (4) so the schema-agnostic
8360 // read_value path can disambiguate. (Tag 11 is taken by
8361 // the WAL `auto_commit_sql` shape elsewhere, hence 14.)
8362 Value::Bytes(b) => {
8363 out.push(14);
8364 let len = u16::try_from(b.len()).expect("BYTEA value ≤ 64 KiB");
8365 out.extend_from_slice(&len.to_le_bytes());
8366 out.extend_from_slice(b);
8367 }
8368 // v7.10.9: TEXT[] — [u8 tag=15][u16 count][per elem: u8
8369 // null + (if non-null) u16 len + utf-8 bytes].
8370 Value::TextArray(items) => {
8371 out.push(15);
8372 let count = u16::try_from(items.len()).expect("TEXT[] ≤ 65k elements");
8373 out.extend_from_slice(&count.to_le_bytes());
8374 for item in items {
8375 match item {
8376 None => out.push(1),
8377 Some(s) => {
8378 out.push(0);
8379 let len = u16::try_from(s.len()).expect("TEXT[] element ≤ 64 KiB");
8380 out.extend_from_slice(&len.to_le_bytes());
8381 out.extend_from_slice(s.as_bytes());
8382 }
8383 }
8384 }
8385 }
8386 // v7.11.12: INT[] — tag 16. [u16 count][per elem: u8 null +
8387 // (if non-null) i32 LE].
8388 Value::IntArray(items) => {
8389 out.push(16);
8390 let count = u16::try_from(items.len()).expect("INT[] ≤ 65k elements");
8391 out.extend_from_slice(&count.to_le_bytes());
8392 for item in items {
8393 match item {
8394 None => out.push(1),
8395 Some(n) => {
8396 out.push(0);
8397 out.extend_from_slice(&n.to_le_bytes());
8398 }
8399 }
8400 }
8401 }
8402 // v7.11.12: BIGINT[] — tag 17. [u16 count][per elem: u8 null +
8403 // (if non-null) i64 LE].
8404 Value::BigIntArray(items) => {
8405 out.push(17);
8406 let count = u16::try_from(items.len()).expect("BIGINT[] ≤ 65k elements");
8407 out.extend_from_slice(&count.to_le_bytes());
8408 for item in items {
8409 match item {
8410 None => out.push(1),
8411 Some(n) => {
8412 out.push(0);
8413 out.extend_from_slice(&n.to_le_bytes());
8414 }
8415 }
8416 }
8417 }
8418 // v7.12.0: tsvector — tag 18. Body shape matches
8419 // `write_tsvector_body`.
8420 Value::TsVector(lexs) => {
8421 out.push(18);
8422 write_tsvector_body(out, lexs);
8423 }
8424 // v7.12.0: tsquery — tag 19. Body shape matches
8425 // `write_tsquery_body`.
8426 Value::TsQuery(ast) => {
8427 out.push(19);
8428 write_tsquery_body(out, ast);
8429 }
8430 // v7.17.0: UUID — tag 20. Body = raw 16 bytes (RFC 4122
8431 // byte order).
8432 Value::Uuid(b) => {
8433 out.push(20);
8434 out.extend_from_slice(&b[..]);
8435 }
8436 // v7.17.0 Phase 3.P0-32: TIME — tag 21. Body = i64 LE
8437 // microseconds since 00:00:00.
8438 Value::Time(us) => {
8439 out.push(21);
8440 out.extend_from_slice(&us.to_le_bytes());
8441 }
8442 // v7.17.0 Phase 3.P0-33: YEAR — tag 22. Body = u16 LE.
8443 Value::Year(y) => {
8444 out.push(22);
8445 out.extend_from_slice(&y.to_le_bytes());
8446 }
8447 // v7.17.0 Phase 3.P0-34: TIMETZ — tag 23. Body = i64 LE
8448 // us + i32 LE offset_secs.
8449 Value::TimeTz { us, offset_secs } => {
8450 out.push(23);
8451 out.extend_from_slice(&us.to_le_bytes());
8452 out.extend_from_slice(&offset_secs.to_le_bytes());
8453 }
8454 // v7.17.0 Phase 3.P0-35: MONEY — tag 24. Body = i64 LE cents.
8455 Value::Money(c) => {
8456 out.push(24);
8457 out.extend_from_slice(&c.to_le_bytes());
8458 }
8459 // v7.17.0 Phase 3.P0-38: range — tag 25. Body =
8460 // [u8 RangeKind tag][u8 flags][if lower: write_value(lower)]
8461 // [if upper: write_value(upper)].
8462 Value::Range {
8463 kind,
8464 lower,
8465 upper,
8466 lower_inc,
8467 upper_inc,
8468 empty,
8469 } => {
8470 out.push(25);
8471 out.push(kind.tag());
8472 let mut flags: u8 = 0;
8473 if *empty {
8474 flags |= 0b0000_0001;
8475 }
8476 if lower.is_some() {
8477 flags |= 0b0000_0010;
8478 }
8479 if upper.is_some() {
8480 flags |= 0b0000_0100;
8481 }
8482 if *lower_inc {
8483 flags |= 0b0000_1000;
8484 }
8485 if *upper_inc {
8486 flags |= 0b0001_0000;
8487 }
8488 out.push(flags);
8489 if let Some(l) = lower {
8490 write_value(out, l);
8491 }
8492 if let Some(u) = upper {
8493 write_value(out, u);
8494 }
8495 }
8496 // v7.17.0 Phase 3.P0-39: hstore — tag 26. Body =
8497 // [u32 count] then per pair `[u32 klen][k bytes][u8 has_val]
8498 // [if has_val: u32 vlen][v bytes]`.
8499 Value::Hstore(pairs) => {
8500 out.push(26);
8501 write_hstore_body(out, pairs);
8502 }
8503 // v7.17.0 Phase 3.P0-40: 2D arrays — tag 27/28/29.
8504 Value::IntArray2D(rows) => {
8505 out.push(27);
8506 write_int_2d_body(out, rows);
8507 }
8508 Value::BigIntArray2D(rows) => {
8509 out.push(28);
8510 write_bigint_2d_body(out, rows);
8511 }
8512 Value::TextArray2D(rows) => {
8513 out.push(29);
8514 write_text_2d_body(out, rows);
8515 }
8516 }
8517}
8518
8519/// v7.17.0 Phase 3.P0-40 — shared 2D INT writer.
8520fn write_int_2d_body(out: &mut Vec<u8>, rows: &[Vec<Option<i32>>]) {
8521 let nrows = u32::try_from(rows.len()).expect("≤ 4G rows");
8522 let ncols = u32::try_from(rows.first().map(|r| r.len()).unwrap_or(0)).expect("≤ 4G cols");
8523 out.extend_from_slice(&nrows.to_le_bytes());
8524 out.extend_from_slice(&ncols.to_le_bytes());
8525 for row in rows {
8526 for cell in row {
8527 match cell {
8528 None => out.push(1),
8529 Some(n) => {
8530 out.push(0);
8531 out.extend_from_slice(&n.to_le_bytes());
8532 }
8533 }
8534 }
8535 }
8536}
8537
8538/// v7.17.0 Phase 3.P0-40 — shared 2D BIGINT writer.
8539fn write_bigint_2d_body(out: &mut Vec<u8>, rows: &[Vec<Option<i64>>]) {
8540 let nrows = u32::try_from(rows.len()).expect("≤ 4G rows");
8541 let ncols = u32::try_from(rows.first().map(|r| r.len()).unwrap_or(0)).expect("≤ 4G cols");
8542 out.extend_from_slice(&nrows.to_le_bytes());
8543 out.extend_from_slice(&ncols.to_le_bytes());
8544 for row in rows {
8545 for cell in row {
8546 match cell {
8547 None => out.push(1),
8548 Some(n) => {
8549 out.push(0);
8550 out.extend_from_slice(&n.to_le_bytes());
8551 }
8552 }
8553 }
8554 }
8555}
8556
8557/// v7.17.0 Phase 3.P0-40 — shared 2D TEXT writer. Cells use
8558/// `[u8 null_flag][if non-null: u32 len][utf-8 bytes]` layout.
8559fn write_text_2d_body(out: &mut Vec<u8>, rows: &[Vec<Option<String>>]) {
8560 let nrows = u32::try_from(rows.len()).expect("≤ 4G rows");
8561 let ncols = u32::try_from(rows.first().map(|r| r.len()).unwrap_or(0)).expect("≤ 4G cols");
8562 out.extend_from_slice(&nrows.to_le_bytes());
8563 out.extend_from_slice(&ncols.to_le_bytes());
8564 for row in rows {
8565 for cell in row {
8566 match cell {
8567 None => out.push(1),
8568 Some(s) => {
8569 out.push(0);
8570 let l = u32::try_from(s.len()).expect("≤ 4 GiB cell");
8571 out.extend_from_slice(&l.to_le_bytes());
8572 out.extend_from_slice(s.as_bytes());
8573 }
8574 }
8575 }
8576 }
8577}
8578
8579/// v7.17.0 Phase 3.P0-39 — shared hstore body writer.
8580fn write_hstore_body(out: &mut Vec<u8>, pairs: &[(String, Option<String>)]) {
8581 let count = u32::try_from(pairs.len()).expect("hstore ≤ u32::MAX pairs");
8582 out.extend_from_slice(&count.to_le_bytes());
8583 for (k, v) in pairs {
8584 let klen = u32::try_from(k.len()).expect("hstore key ≤ 4 GiB");
8585 out.extend_from_slice(&klen.to_le_bytes());
8586 out.extend_from_slice(k.as_bytes());
8587 match v {
8588 None => out.push(0),
8589 Some(val) => {
8590 out.push(1);
8591 let vlen = u32::try_from(val.len()).expect("hstore val ≤ 4 GiB");
8592 out.extend_from_slice(&vlen.to_le_bytes());
8593 out.extend_from_slice(val.as_bytes());
8594 }
8595 }
8596 }
8597}
8598
8599/// v7.12.0: shared tsvector body writer (used by both dense and
8600/// schema-agnostic codecs).
8601fn write_tsvector_body(out: &mut Vec<u8>, lexs: &[TsLexeme]) {
8602 let count = u16::try_from(lexs.len()).expect("tsvector ≤ 65k lexemes");
8603 out.extend_from_slice(&count.to_le_bytes());
8604 for l in lexs {
8605 let wlen = u16::try_from(l.word.len()).expect("tsvector word ≤ 64 KiB");
8606 out.extend_from_slice(&wlen.to_le_bytes());
8607 out.extend_from_slice(l.word.as_bytes());
8608 let plen = u16::try_from(l.positions.len()).expect("tsvector pos count ≤ 65k");
8609 out.extend_from_slice(&plen.to_le_bytes());
8610 for p in &l.positions {
8611 out.extend_from_slice(&p.to_le_bytes());
8612 }
8613 out.push(l.weight);
8614 }
8615}
8616
8617/// v7.12.0: shared tsquery body writer. Prefix-coded tree: each
8618/// node starts with `[u8 tag]` then a tag-specific payload. Tags:
8619/// 0=Term, 1=And, 2=Or, 3=Not, 4=Phrase.
8620fn write_tsquery_body(out: &mut Vec<u8>, ast: &TsQueryAst) {
8621 match ast {
8622 TsQueryAst::Term { word, weight_mask } => {
8623 out.push(0);
8624 let len = u16::try_from(word.len()).expect("tsquery term ≤ 64 KiB");
8625 out.extend_from_slice(&len.to_le_bytes());
8626 out.extend_from_slice(word.as_bytes());
8627 out.push(*weight_mask);
8628 }
8629 TsQueryAst::And(a, b) => {
8630 out.push(1);
8631 write_tsquery_body(out, a);
8632 write_tsquery_body(out, b);
8633 }
8634 TsQueryAst::Or(a, b) => {
8635 out.push(2);
8636 write_tsquery_body(out, a);
8637 write_tsquery_body(out, b);
8638 }
8639 TsQueryAst::Not(x) => {
8640 out.push(3);
8641 write_tsquery_body(out, x);
8642 }
8643 TsQueryAst::Phrase {
8644 left,
8645 right,
8646 distance,
8647 } => {
8648 out.push(4);
8649 out.extend_from_slice(&distance.to_le_bytes());
8650 write_tsquery_body(out, left);
8651 write_tsquery_body(out, right);
8652 }
8653 }
8654}
8655
8656/// v7.12.0: byte length that `write_tsquery_body` would emit.
8657fn tsquery_encoded_len(ast: &TsQueryAst) -> usize {
8658 match ast {
8659 TsQueryAst::Term { word, .. } => 1 + 2 + word.len() + 1,
8660 TsQueryAst::And(a, b) | TsQueryAst::Or(a, b) => {
8661 1 + tsquery_encoded_len(a) + tsquery_encoded_len(b)
8662 }
8663 TsQueryAst::Not(x) => 1 + tsquery_encoded_len(x),
8664 TsQueryAst::Phrase { left, right, .. } => {
8665 1 + 2 + tsquery_encoded_len(left) + tsquery_encoded_len(right)
8666 }
8667 }
8668}
8669
8670fn write_u16(out: &mut Vec<u8>, n: u16) {
8671 out.extend_from_slice(&n.to_le_bytes());
8672}
8673fn write_u32(out: &mut Vec<u8>, n: u32) {
8674 out.extend_from_slice(&n.to_le_bytes());
8675}
8676fn write_str(out: &mut Vec<u8>, s: &str) {
8677 let len = u16::try_from(s.len()).expect("identifier / text fits in u16");
8678 write_u16(out, len);
8679 out.extend_from_slice(s.as_bytes());
8680}
8681
8682/// v7.12.4 — long-string variant: `[u32 LE len][bytes]`. For
8683/// payloads that can plausibly exceed 64 KiB (notably PL/pgSQL
8684/// function bodies). Identifiers + short text continue to use
8685/// the u16 [`write_str`] codec.
8686fn write_str_long(out: &mut Vec<u8>, s: &str) {
8687 let len = u32::try_from(s.len()).expect("function body fits in u32");
8688 write_u32(out, len);
8689 out.extend_from_slice(s.as_bytes());
8690}
8691
8692/// Serialise an [`IndexKey`] using the v9 tagged codec. `read_index_key`
8693/// is the inverse. v8 catalogs never wrote index keys (`BTree` entries were
8694/// rebuilt from `Table::rows`), so this codec is v9+ only.
8695fn write_index_key(out: &mut Vec<u8>, key: &IndexKey) {
8696 match key {
8697 IndexKey::Int(n) => {
8698 out.push(INDEX_KEY_TAG_INT);
8699 out.extend_from_slice(&n.to_le_bytes());
8700 }
8701 IndexKey::Text(s) => {
8702 out.push(INDEX_KEY_TAG_TEXT);
8703 write_str(out, s);
8704 }
8705 IndexKey::Bool(b) => {
8706 out.push(INDEX_KEY_TAG_BOOL);
8707 out.push(u8::from(*b));
8708 }
8709 IndexKey::Uuid(b) => {
8710 out.push(INDEX_KEY_TAG_UUID);
8711 out.extend_from_slice(&b[..]);
8712 }
8713 }
8714}
8715
8716struct Cursor<'a> {
8717 buf: &'a [u8],
8718 pos: usize,
8719}
8720
8721impl<'a> Cursor<'a> {
8722 const fn new(buf: &'a [u8]) -> Self {
8723 Self { buf, pos: 0 }
8724 }
8725
8726 fn take(&mut self, n: usize) -> Result<&'a [u8], StorageError> {
8727 let end = self
8728 .pos
8729 .checked_add(n)
8730 .ok_or_else(|| StorageError::Corrupt(format!("length overflow taking {n} bytes")))?;
8731 if end > self.buf.len() {
8732 return Err(StorageError::Corrupt(format!(
8733 "unexpected EOF at offset {} (wanted {n} more bytes)",
8734 self.pos
8735 )));
8736 }
8737 let s = &self.buf[self.pos..end];
8738 self.pos = end;
8739 Ok(s)
8740 }
8741
8742 fn read_u8(&mut self) -> Result<u8, StorageError> {
8743 Ok(self.take(1)?[0])
8744 }
8745 fn read_u16(&mut self) -> Result<u16, StorageError> {
8746 let s = self.take(2)?;
8747 Ok(u16::from_le_bytes([s[0], s[1]]))
8748 }
8749 fn read_u32(&mut self) -> Result<u32, StorageError> {
8750 let s = self.take(4)?;
8751 Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
8752 }
8753 fn read_i32(&mut self) -> Result<i32, StorageError> {
8754 let s = self.take(4)?;
8755 Ok(i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
8756 }
8757 /// v6.7.2 — u64 LE read for the per-table `hot_tier_bytes`
8758 /// catalog appendix.
8759 fn read_u64(&mut self) -> Result<u64, StorageError> {
8760 let s = self.take(8)?;
8761 Ok(u64::from_le_bytes([
8762 s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
8763 ]))
8764 }
8765 fn read_i64(&mut self) -> Result<i64, StorageError> {
8766 let s = self.take(8)?;
8767 let arr: [u8; 8] = s.try_into().expect("checked");
8768 Ok(i64::from_le_bytes(arr))
8769 }
8770 fn read_f64(&mut self) -> Result<f64, StorageError> {
8771 let s = self.take(8)?;
8772 let arr: [u8; 8] = s.try_into().expect("checked");
8773 Ok(f64::from_le_bytes(arr))
8774 }
8775 fn read_f32(&mut self) -> Result<f32, StorageError> {
8776 let s = self.take(4)?;
8777 Ok(f32::from_le_bytes([s[0], s[1], s[2], s[3]]))
8778 }
8779 fn read_str(&mut self) -> Result<String, StorageError> {
8780 let len = self.read_u16()? as usize;
8781 let bytes = self.take(len)?;
8782 core::str::from_utf8(bytes)
8783 .map(String::from)
8784 .map_err(|_| StorageError::Corrupt("invalid UTF-8 in identifier or text".into()))
8785 }
8786
8787 /// v7.12.4 — long-string variant for payloads written via
8788 /// [`write_str_long`] (u32-length prefix). Used for PL/pgSQL
8789 /// function bodies which can plausibly exceed 64 KiB.
8790 fn read_str_long(&mut self) -> Result<String, StorageError> {
8791 let len = self.read_u32()? as usize;
8792 let bytes = self.take(len)?;
8793 core::str::from_utf8(bytes)
8794 .map(String::from)
8795 .map_err(|_| StorageError::Corrupt("invalid UTF-8 in long-string payload".into()))
8796 }
8797
8798 /// Parse an [`IndexKey`] emitted by `write_index_key` (v9 tagged
8799 /// codec). Returns `StorageError::Corrupt` on unknown tag or
8800 /// truncated payload.
8801 fn read_index_key(&mut self) -> Result<IndexKey, StorageError> {
8802 let tag = self.read_u8()?;
8803 match tag {
8804 INDEX_KEY_TAG_INT => Ok(IndexKey::Int(self.read_i64()?)),
8805 INDEX_KEY_TAG_TEXT => Ok(IndexKey::Text(self.read_str()?)),
8806 INDEX_KEY_TAG_BOOL => Ok(IndexKey::Bool(self.read_u8()? != 0)),
8807 INDEX_KEY_TAG_UUID => {
8808 let s = self.take(16)?;
8809 let mut b = [0u8; 16];
8810 b.copy_from_slice(s);
8811 Ok(IndexKey::Uuid(b))
8812 }
8813 other => Err(StorageError::Corrupt(format!(
8814 "unknown index key tag: {other}"
8815 ))),
8816 }
8817 }
8818 /// Schema-driven dense value decode (`FILE_VERSION` 8). Caller has
8819 /// already cleared the NULL bit from the row bitmap; we read the
8820 /// fixed-width body for the given column type. Used inside the row
8821 /// hot loop; column defaults still go through `read_value` (which
8822 /// reads its own type tag) so DEFAULT round-trips without a schema.
8823 fn read_value_body(&mut self, ty: DataType) -> Result<Value, StorageError> {
8824 match ty {
8825 DataType::SmallInt => {
8826 let s = self.take(2)?;
8827 Ok(Value::SmallInt(i16::from_le_bytes([s[0], s[1]])))
8828 }
8829 DataType::Int => Ok(Value::Int(self.read_i32()?)),
8830 DataType::BigInt => Ok(Value::BigInt(self.read_i64()?)),
8831 DataType::Float => Ok(Value::Float(self.read_f64()?)),
8832 DataType::Bool => Ok(Value::Bool(self.read_u8()? != 0)),
8833 DataType::Text | DataType::Varchar(_) | DataType::Char(_) => {
8834 Ok(Value::Text(self.read_str()?))
8835 }
8836 DataType::Vector {
8837 encoding: VecEncoding::F32,
8838 ..
8839 } => {
8840 let dim = self.read_u32()? as usize;
8841 let mut v = Vec::with_capacity(dim);
8842 for _ in 0..dim {
8843 let bytes: [u8; 4] = self.take(4)?.try_into().expect("checked");
8844 v.push(f32::from_le_bytes(bytes));
8845 }
8846 Ok(Value::Vector(v))
8847 }
8848 DataType::Vector {
8849 encoding: VecEncoding::Sq8,
8850 ..
8851 } => {
8852 let dim = self.read_u32()? as usize;
8853 let min = self.read_f32()?;
8854 let max = self.read_f32()?;
8855 let bytes = self.take(dim)?.to_vec();
8856 Ok(Value::Sq8Vector(quantize::Sq8Vector { min, max, bytes }))
8857 }
8858 DataType::Vector {
8859 encoding: VecEncoding::F16,
8860 ..
8861 } => {
8862 let dim = self.read_u32()? as usize;
8863 let bytes = self.take(dim * 2)?.to_vec();
8864 Ok(Value::HalfVector(halfvec::HalfVector { bytes }))
8865 }
8866 DataType::Numeric { .. } => {
8867 let s = self.take(16)?;
8868 let arr: [u8; 16] = s.try_into().expect("checked");
8869 let scaled = i128::from_le_bytes(arr);
8870 let scale = self.read_u8()?;
8871 Ok(Value::Numeric { scaled, scale })
8872 }
8873 DataType::Date => Ok(Value::Date(self.read_i32()?)),
8874 DataType::Timestamp => Ok(Value::Timestamp(self.read_i64()?)),
8875 DataType::Timestamptz => Ok(Value::Timestamp(self.read_i64()?)),
8876 DataType::Jsonb => Ok(Value::Json(self.read_str()?)),
8877 DataType::Interval => {
8878 // Defensive — schema gate (CREATE TABLE rejects Interval
8879 // columns) means this branch can't be hit through normal
8880 // flow; reject corrupt files explicitly rather than
8881 // panic.
8882 Err(StorageError::Corrupt(
8883 "INTERVAL column found on disk — runtime-only type, v3.0.2 rejects it".into(),
8884 ))
8885 }
8886 DataType::Json => Ok(Value::Json(self.read_str()?)),
8887 // v7.10.4: BYTEA on-disk is [u16 len][bytes]. Same wire
8888 // shape as Text, but read as raw Vec<u8>.
8889 DataType::Bytes => {
8890 let len = self.read_u16()? as usize;
8891 let bytes = self.take(len)?.to_vec();
8892 Ok(Value::Bytes(bytes))
8893 }
8894 // v7.10.9: TEXT[] dense body.
8895 DataType::TextArray => {
8896 let count = self.read_u16()? as usize;
8897 let mut items: Vec<Option<String>> = Vec::with_capacity(count);
8898 for _ in 0..count {
8899 match self.read_u8()? {
8900 0 => items.push(Some(self.read_str()?)),
8901 1 => items.push(None),
8902 other => {
8903 return Err(StorageError::Corrupt(format!(
8904 "TEXT[] null flag: unknown byte {other}"
8905 )));
8906 }
8907 }
8908 }
8909 Ok(Value::TextArray(items))
8910 }
8911 // v7.11.12: INT[] dense body.
8912 DataType::IntArray => {
8913 let count = self.read_u16()? as usize;
8914 let mut items: Vec<Option<i32>> = Vec::with_capacity(count);
8915 for _ in 0..count {
8916 match self.read_u8()? {
8917 0 => items.push(Some(self.read_i32()?)),
8918 1 => items.push(None),
8919 other => {
8920 return Err(StorageError::Corrupt(format!(
8921 "INT[] null flag: unknown byte {other}"
8922 )));
8923 }
8924 }
8925 }
8926 Ok(Value::IntArray(items))
8927 }
8928 // v7.11.12: BIGINT[] dense body.
8929 DataType::BigIntArray => {
8930 let count = self.read_u16()? as usize;
8931 let mut items: Vec<Option<i64>> = Vec::with_capacity(count);
8932 for _ in 0..count {
8933 match self.read_u8()? {
8934 0 => items.push(Some(self.read_i64()?)),
8935 1 => items.push(None),
8936 other => {
8937 return Err(StorageError::Corrupt(format!(
8938 "BIGINT[] null flag: unknown byte {other}"
8939 )));
8940 }
8941 }
8942 }
8943 Ok(Value::BigIntArray(items))
8944 }
8945 // v7.12.0: tsvector dense body — [u16 lex_count]
8946 // [per lex: u16 word_len + utf-8 word + u16 pos_count
8947 // + (u16 LE * pos_count) + u8 weight].
8948 DataType::TsVector => Ok(Value::TsVector(self.read_tsvector_body()?)),
8949 DataType::TsQuery => Ok(Value::TsQuery(self.read_tsquery_body()?)),
8950 // v7.17.0: UUID dense body — raw 16 bytes.
8951 DataType::Uuid => {
8952 let s = self.take(16)?;
8953 let mut b = [0u8; 16];
8954 b.copy_from_slice(s);
8955 Ok(Value::Uuid(b))
8956 }
8957 // v7.17.0 Phase 3.P0-32: TIME dense body — i64 LE.
8958 DataType::Time => Ok(Value::Time(self.read_i64()?)),
8959 // v7.17.0 Phase 3.P0-33: YEAR dense body — u16 LE.
8960 DataType::Year => Ok(Value::Year(self.read_u16()?)),
8961 // v7.17.0 Phase 3.P0-34: TIMETZ dense body —
8962 // i64 LE us + i32 LE offset_secs.
8963 DataType::TimeTz => {
8964 let us = self.read_i64()?;
8965 let offset_secs = self.read_i32()?;
8966 Ok(Value::TimeTz { us, offset_secs })
8967 }
8968 // v7.17.0 Phase 3.P0-35: MONEY dense body — i64 LE cents.
8969 DataType::Money => Ok(Value::Money(self.read_i64()?)),
8970 // v7.17.0 Phase 3.P0-39: hstore dense body. Body
8971 // shape == read_hstore_body.
8972 DataType::Hstore => Ok(Value::Hstore(self.read_hstore_body()?)),
8973 // v7.17.0 Phase 3.P0-40: 2D arrays dense body.
8974 DataType::IntArray2D => Ok(Value::IntArray2D(self.read_int_2d_body()?)),
8975 DataType::BigIntArray2D => Ok(Value::BigIntArray2D(self.read_bigint_2d_body()?)),
8976 DataType::TextArray2D => Ok(Value::TextArray2D(self.read_text_2d_body()?)),
8977 // v7.17.0 Phase 3.P0-38: range dense body. Element
8978 // type is determined by the surrounding RangeKind.
8979 DataType::Range(kind) => {
8980 let flags = self.read_u8()?;
8981 let empty = flags & 0b0000_0001 != 0;
8982 let has_lower = flags & 0b0000_0010 != 0;
8983 let has_upper = flags & 0b0000_0100 != 0;
8984 let lower_inc = flags & 0b0000_1000 != 0;
8985 let upper_inc = flags & 0b0001_0000 != 0;
8986 let lower = if has_lower {
8987 Some(alloc::boxed::Box::new(self.read_value()?))
8988 } else {
8989 None
8990 };
8991 let upper = if has_upper {
8992 Some(alloc::boxed::Box::new(self.read_value()?))
8993 } else {
8994 None
8995 };
8996 Ok(Value::Range {
8997 kind,
8998 lower,
8999 upper,
9000 lower_inc,
9001 upper_inc,
9002 empty,
9003 })
9004 }
9005 }
9006 }
9007
9008 /// v7.17.0 Phase 3.P0-40 — read a 2D INT array body emitted
9009 /// by `write_int_2d_body`.
9010 fn read_int_2d_body(&mut self) -> Result<Vec<Vec<Option<i32>>>, StorageError> {
9011 let nrows = self.read_u32()? as usize;
9012 let ncols = self.read_u32()? as usize;
9013 let mut rows = Vec::with_capacity(nrows);
9014 for _ in 0..nrows {
9015 let mut row = Vec::with_capacity(ncols);
9016 for _ in 0..ncols {
9017 let null = self.read_u8()?;
9018 row.push(if null == 1 {
9019 None
9020 } else {
9021 Some(self.read_i32()?)
9022 });
9023 }
9024 rows.push(row);
9025 }
9026 Ok(rows)
9027 }
9028
9029 /// v7.17.0 Phase 3.P0-40 — read a 2D BIGINT array body.
9030 fn read_bigint_2d_body(&mut self) -> Result<Vec<Vec<Option<i64>>>, StorageError> {
9031 let nrows = self.read_u32()? as usize;
9032 let ncols = self.read_u32()? as usize;
9033 let mut rows = Vec::with_capacity(nrows);
9034 for _ in 0..nrows {
9035 let mut row = Vec::with_capacity(ncols);
9036 for _ in 0..ncols {
9037 let null = self.read_u8()?;
9038 row.push(if null == 1 {
9039 None
9040 } else {
9041 Some(self.read_i64()?)
9042 });
9043 }
9044 rows.push(row);
9045 }
9046 Ok(rows)
9047 }
9048
9049 /// v7.17.0 Phase 3.P0-40 — read a 2D TEXT array body. Each
9050 /// cell is `[u8 null_flag][if non-null: u32 len + utf-8 bytes]`.
9051 fn read_text_2d_body(&mut self) -> Result<Vec<Vec<Option<String>>>, StorageError> {
9052 let nrows = self.read_u32()? as usize;
9053 let ncols = self.read_u32()? as usize;
9054 let mut rows = Vec::with_capacity(nrows);
9055 for _ in 0..nrows {
9056 let mut row = Vec::with_capacity(ncols);
9057 for _ in 0..ncols {
9058 let null = self.read_u8()?;
9059 if null == 1 {
9060 row.push(None);
9061 } else {
9062 let l = self.read_u32()? as usize;
9063 let bytes = self.take(l)?.to_vec();
9064 let s = String::from_utf8(bytes).map_err(|_| {
9065 StorageError::Corrupt("2D TEXT cell is not valid UTF-8".into())
9066 })?;
9067 row.push(Some(s));
9068 }
9069 }
9070 rows.push(row);
9071 }
9072 Ok(rows)
9073 }
9074
9075 /// v7.17.0 Phase 3.P0-39 — read a hstore body emitted by
9076 /// `write_hstore_body`.
9077 fn read_hstore_body(&mut self) -> Result<Vec<(String, Option<String>)>, StorageError> {
9078 let count = self.read_u32()? as usize;
9079 let mut out = Vec::with_capacity(count);
9080 for _ in 0..count {
9081 let klen = self.read_u32()? as usize;
9082 let k_bytes = self.take(klen)?.to_vec();
9083 let k = String::from_utf8(k_bytes)
9084 .map_err(|_| StorageError::Corrupt("hstore key is not valid UTF-8".into()))?;
9085 let has_val = self.read_u8()? != 0;
9086 let v =
9087 if has_val {
9088 let vlen = self.read_u32()? as usize;
9089 let v_bytes = self.take(vlen)?.to_vec();
9090 Some(String::from_utf8(v_bytes).map_err(|_| {
9091 StorageError::Corrupt("hstore value is not valid UTF-8".into())
9092 })?)
9093 } else {
9094 None
9095 };
9096 out.push((k, v));
9097 }
9098 Ok(out)
9099 }
9100
9101 /// v7.12.0 — read a tsvector body emitted by `write_tsvector_body`.
9102 fn read_tsvector_body(&mut self) -> Result<Vec<TsLexeme>, StorageError> {
9103 let count = self.read_u16()? as usize;
9104 let mut out = Vec::with_capacity(count);
9105 for _ in 0..count {
9106 let word = self.read_str()?;
9107 let pos_count = self.read_u16()? as usize;
9108 let mut positions = Vec::with_capacity(pos_count);
9109 for _ in 0..pos_count {
9110 positions.push(self.read_u16()?);
9111 }
9112 let weight = self.read_u8()?;
9113 out.push(TsLexeme {
9114 word,
9115 positions,
9116 weight,
9117 });
9118 }
9119 Ok(out)
9120 }
9121
9122 /// v7.12.0 — read a tsquery body emitted by `write_tsquery_body`.
9123 fn read_tsquery_body(&mut self) -> Result<TsQueryAst, StorageError> {
9124 let tag = self.read_u8()?;
9125 match tag {
9126 0 => {
9127 let word = self.read_str()?;
9128 let weight_mask = self.read_u8()?;
9129 Ok(TsQueryAst::Term { word, weight_mask })
9130 }
9131 1 => {
9132 let a = self.read_tsquery_body()?;
9133 let b = self.read_tsquery_body()?;
9134 Ok(TsQueryAst::And(Box::new(a), Box::new(b)))
9135 }
9136 2 => {
9137 let a = self.read_tsquery_body()?;
9138 let b = self.read_tsquery_body()?;
9139 Ok(TsQueryAst::Or(Box::new(a), Box::new(b)))
9140 }
9141 3 => {
9142 let x = self.read_tsquery_body()?;
9143 Ok(TsQueryAst::Not(Box::new(x)))
9144 }
9145 4 => {
9146 let distance = self.read_u16()?;
9147 let left = self.read_tsquery_body()?;
9148 let right = self.read_tsquery_body()?;
9149 Ok(TsQueryAst::Phrase {
9150 left: Box::new(left),
9151 right: Box::new(right),
9152 distance,
9153 })
9154 }
9155 other => Err(StorageError::Corrupt(format!(
9156 "tsquery: unknown node tag {other}"
9157 ))),
9158 }
9159 }
9160
9161 fn read_value(&mut self) -> Result<Value, StorageError> {
9162 let tag = self.read_u8()?;
9163 match tag {
9164 0 => Ok(Value::Null),
9165 1 => Ok(Value::Int(self.read_i32()?)),
9166 2 => Ok(Value::BigInt(self.read_i64()?)),
9167 3 => Ok(Value::Float(self.read_f64()?)),
9168 4 => Ok(Value::Text(self.read_str()?)),
9169 5 => Ok(Value::Bool(self.read_u8()? != 0)),
9170 6 => {
9171 let dim = self.read_u32()? as usize;
9172 let mut v = Vec::with_capacity(dim);
9173 for _ in 0..dim {
9174 let bytes: [u8; 4] = self.take(4)?.try_into().expect("checked");
9175 v.push(f32::from_le_bytes(bytes));
9176 }
9177 Ok(Value::Vector(v))
9178 }
9179 7 => {
9180 let s = self.take(2)?;
9181 Ok(Value::SmallInt(i16::from_le_bytes([s[0], s[1]])))
9182 }
9183 8 => {
9184 let s = self.take(16)?;
9185 let arr: [u8; 16] = s.try_into().expect("checked");
9186 let scaled = i128::from_le_bytes(arr);
9187 let scale = self.read_u8()?;
9188 Ok(Value::Numeric { scaled, scale })
9189 }
9190 9 => Ok(Value::Date(self.read_i32()?)),
9191 10 => Ok(Value::Timestamp(self.read_i64()?)),
9192 // v6.0.1: tag 11 — Sq8Vector. Pre-v6 readers fall
9193 // through to the catch-all and surface
9194 // `Corrupt("unknown value tag")`, matching the
9195 // forward-compat fence on the column-type side.
9196 11 => {
9197 let dim = self.read_u32()? as usize;
9198 let min = self.read_f32()?;
9199 let max = self.read_f32()?;
9200 let bytes = self.take(dim)?.to_vec();
9201 Ok(Value::Sq8Vector(quantize::Sq8Vector { min, max, bytes }))
9202 }
9203 // v6.0.3: tag 12 — HalfVector. Same forward-compat
9204 // fence story as tag 11.
9205 12 => {
9206 let dim = self.read_u32()? as usize;
9207 let bytes = self.take(dim * 2)?.to_vec();
9208 Ok(Value::HalfVector(halfvec::HalfVector { bytes }))
9209 }
9210 // v7.10.4: tag 14 — BYTEA. [u16 len][bytes].
9211 14 => {
9212 let len = self.read_u16()? as usize;
9213 let bytes = self.take(len)?.to_vec();
9214 Ok(Value::Bytes(bytes))
9215 }
9216 // v7.10.9: tag 15 — TEXT[]. [u16 count][per elem: u8
9217 // null + (when non-null) u16 len + utf-8 bytes].
9218 15 => {
9219 let count = self.read_u16()? as usize;
9220 let mut items: Vec<Option<String>> = Vec::with_capacity(count);
9221 for _ in 0..count {
9222 match self.read_u8()? {
9223 0 => items.push(Some(self.read_str()?)),
9224 1 => items.push(None),
9225 other => {
9226 return Err(StorageError::Corrupt(format!(
9227 "TEXT[] null flag in value tag: unknown byte {other}"
9228 )));
9229 }
9230 }
9231 }
9232 Ok(Value::TextArray(items))
9233 }
9234 // v7.11.12: tags 16/17 — INT[] / BIGINT[].
9235 16 => {
9236 let count = self.read_u16()? as usize;
9237 let mut items: Vec<Option<i32>> = Vec::with_capacity(count);
9238 for _ in 0..count {
9239 match self.read_u8()? {
9240 0 => items.push(Some(self.read_i32()?)),
9241 1 => items.push(None),
9242 other => {
9243 return Err(StorageError::Corrupt(format!(
9244 "INT[] null flag in value tag: unknown byte {other}"
9245 )));
9246 }
9247 }
9248 }
9249 Ok(Value::IntArray(items))
9250 }
9251 17 => {
9252 let count = self.read_u16()? as usize;
9253 let mut items: Vec<Option<i64>> = Vec::with_capacity(count);
9254 for _ in 0..count {
9255 match self.read_u8()? {
9256 0 => items.push(Some(self.read_i64()?)),
9257 1 => items.push(None),
9258 other => {
9259 return Err(StorageError::Corrupt(format!(
9260 "BIGINT[] null flag in value tag: unknown byte {other}"
9261 )));
9262 }
9263 }
9264 }
9265 Ok(Value::BigIntArray(items))
9266 }
9267 // v7.12.0: tag 18 — tsvector. Body matches the dense
9268 // form (`read_tsvector_body`).
9269 18 => Ok(Value::TsVector(self.read_tsvector_body()?)),
9270 // v7.12.0: tag 19 — tsquery.
9271 19 => Ok(Value::TsQuery(self.read_tsquery_body()?)),
9272 // v7.17.0: tag 20 — UUID. Raw 16 bytes.
9273 20 => {
9274 let s = self.take(16)?;
9275 let mut b = [0u8; 16];
9276 b.copy_from_slice(s);
9277 Ok(Value::Uuid(b))
9278 }
9279 // v7.17.0 Phase 3.P0-32: tag 21 — TIME. i64 LE.
9280 21 => Ok(Value::Time(self.read_i64()?)),
9281 // v7.17.0 Phase 3.P0-33: tag 22 — YEAR. u16 LE.
9282 22 => Ok(Value::Year(self.read_u16()?)),
9283 // v7.17.0 Phase 3.P0-34: tag 23 — TIMETZ. i64 LE us +
9284 // i32 LE offset_secs.
9285 23 => {
9286 let us = self.read_i64()?;
9287 let offset_secs = self.read_i32()?;
9288 Ok(Value::TimeTz { us, offset_secs })
9289 }
9290 // v7.17.0 Phase 3.P0-35: tag 24 — MONEY. i64 LE cents.
9291 24 => Ok(Value::Money(self.read_i64()?)),
9292 // v7.17.0 Phase 3.P0-39: tag 26 — Hstore. Body shape
9293 // == read_hstore_body.
9294 26 => Ok(Value::Hstore(self.read_hstore_body()?)),
9295 // v7.17.0 Phase 3.P0-40: tag 27/28/29 — 2D arrays.
9296 27 => Ok(Value::IntArray2D(self.read_int_2d_body()?)),
9297 28 => Ok(Value::BigIntArray2D(self.read_bigint_2d_body()?)),
9298 29 => Ok(Value::TextArray2D(self.read_text_2d_body()?)),
9299 // v7.17.0 Phase 3.P0-38: tag 25 — Range.
9300 // [u8 RangeKind tag][u8 flags][opt lower][opt upper].
9301 25 => {
9302 let kt = self.read_u8()?;
9303 let kind = RangeKind::from_tag(kt)
9304 .ok_or_else(|| StorageError::Corrupt(format!("unknown RangeKind tag: {kt}")))?;
9305 let flags = self.read_u8()?;
9306 let empty = flags & 0b0000_0001 != 0;
9307 let has_lower = flags & 0b0000_0010 != 0;
9308 let has_upper = flags & 0b0000_0100 != 0;
9309 let lower_inc = flags & 0b0000_1000 != 0;
9310 let upper_inc = flags & 0b0001_0000 != 0;
9311 let lower = if has_lower {
9312 Some(alloc::boxed::Box::new(self.read_value()?))
9313 } else {
9314 None
9315 };
9316 let upper = if has_upper {
9317 Some(alloc::boxed::Box::new(self.read_value()?))
9318 } else {
9319 None
9320 };
9321 Ok(Value::Range {
9322 kind,
9323 lower,
9324 upper,
9325 lower_inc,
9326 upper_inc,
9327 empty,
9328 })
9329 }
9330 other => Err(StorageError::Corrupt(format!("unknown value tag: {other}"))),
9331 }
9332 }
9333
9334 /// Read an NSW graph that was emitted via `write_nsw_graph`. `m`
9335 /// is passed in because it was already consumed from the per-
9336 /// index header. Returns the reconstituted `NswGraph`.
9337 fn read_nsw_graph(&mut self, m: usize) -> Result<NswGraph, StorageError> {
9338 let m_max_0 = self.read_u16()? as usize;
9339 let entry_raw = self.read_u32()?;
9340 let entry = if entry_raw == u32::MAX {
9341 None
9342 } else {
9343 Some(entry_raw as usize)
9344 };
9345 let entry_level = self.read_u8()?;
9346 let node_count = self.read_u32()? as usize;
9347 // v5.5.0: levels/per-layer are PV-backed in memory, but the wire
9348 // format is unchanged — decode element-by-element into a PV via
9349 // push_mut (transient in-place, no per-element path-copy here since
9350 // the freshly-built PV is uniquely owned).
9351 let mut levels: PersistentVec<u8> = PersistentVec::new();
9352 for _ in 0..node_count {
9353 levels.push_mut(self.read_u8()?);
9354 }
9355 let layer_count = self.read_u8()? as usize;
9356 let mut layers: Vec<PersistentVec<Vec<u32>>> = Vec::with_capacity(layer_count);
9357 for _ in 0..layer_count {
9358 let n = self.read_u32()? as usize;
9359 let mut per_layer: PersistentVec<Vec<u32>> = PersistentVec::new();
9360 for _ in 0..n {
9361 let cnt = self.read_u16()? as usize;
9362 let mut row: Vec<u32> = Vec::with_capacity(cnt);
9363 for _ in 0..cnt {
9364 row.push(self.read_u32()?);
9365 }
9366 per_layer.push_mut(row);
9367 }
9368 layers.push(per_layer);
9369 }
9370 Ok(NswGraph {
9371 m,
9372 m_max_0,
9373 entry,
9374 entry_level,
9375 levels,
9376 layers,
9377 })
9378 }
9379}
9380
9381#[cfg(test)]
9382mod tests {
9383 use super::*;
9384 use alloc::string::ToString;
9385 use alloc::vec;
9386
9387 #[cfg(target_arch = "aarch64")]
9388 #[test]
9389 fn neon_l2_matches_scalar() {
9390 // For every dim that's a multiple of 4 (4, 8, 12, 16, 64,
9391 // 128, 256, 384, 512, 768, 1024, 1536), the NEON impl must
9392 // agree with the scalar reference within tight float
9393 // tolerance (FMA rounding differs from separate * + +).
9394 let dims = [4usize, 8, 12, 16, 64, 128, 256, 384, 512, 768, 1024, 1536];
9395 for &d in &dims {
9396 let mut state: u64 = (d as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
9397 let mut a = Vec::with_capacity(d);
9398 let mut b = Vec::with_capacity(d);
9399 for _ in 0..d {
9400 state = state
9401 .wrapping_mul(6_364_136_223_846_793_005)
9402 .wrapping_add(1);
9403 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9404 let x = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9405 state = state
9406 .wrapping_mul(6_364_136_223_846_793_005)
9407 .wrapping_add(1);
9408 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9409 let y = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9410 a.push(x);
9411 b.push(y);
9412 }
9413 let scalar = l2_distance_sq_scalar(&a, &b);
9414 let neon = unsafe { l2_distance_sq_neon(&a, &b) };
9415 let tol = (scalar.abs().max(1e-6)) * 1e-4;
9416 assert!(
9417 (scalar - neon).abs() <= tol,
9418 "dim={d}: scalar={scalar} neon={neon} diff={}",
9419 (scalar - neon).abs()
9420 );
9421 }
9422 }
9423
9424 #[cfg(target_arch = "aarch64")]
9425 #[test]
9426 fn neon_inner_product_matches_scalar() {
9427 // v6.0.2 step 1: NEON IP must agree with scalar across every
9428 // production-shaped dim. FMA rounding differs from
9429 // separate * + +, so the tolerance scales with magnitude.
9430 let dims = [4usize, 8, 12, 16, 64, 128, 256, 512, 1024];
9431 for &d in &dims {
9432 let mut state: u64 = (d as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
9433 let mut a = Vec::with_capacity(d);
9434 let mut b = Vec::with_capacity(d);
9435 for _ in 0..d {
9436 state = state
9437 .wrapping_mul(6_364_136_223_846_793_005)
9438 .wrapping_add(1);
9439 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9440 let x = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9441 state = state
9442 .wrapping_mul(6_364_136_223_846_793_005)
9443 .wrapping_add(1);
9444 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9445 let y = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9446 a.push(x);
9447 b.push(y);
9448 }
9449 let scalar = inner_product_scalar(&a, &b);
9450 let neon = unsafe { inner_product_neon(&a, &b) };
9451 #[allow(clippy::cast_precision_loss)]
9452 let tol = (scalar.abs().max(1e-6)) * 1e-4 + (d as f32) * 1e-6;
9453 assert!(
9454 (scalar - neon).abs() <= tol,
9455 "IP dim={d}: scalar={scalar} neon={neon} diff={}",
9456 (scalar - neon).abs()
9457 );
9458 }
9459 }
9460
9461 #[cfg(target_arch = "aarch64")]
9462 #[allow(clippy::similar_names)]
9463 #[test]
9464 fn neon_cosine_dot_norms_matches_scalar() {
9465 let dims = [4usize, 8, 12, 16, 64, 128, 256, 512, 1024];
9466 for &d in &dims {
9467 let mut state: u64 = (d as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
9468 let mut a = Vec::with_capacity(d);
9469 let mut b = Vec::with_capacity(d);
9470 for _ in 0..d {
9471 state = state
9472 .wrapping_mul(6_364_136_223_846_793_005)
9473 .wrapping_add(1);
9474 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9475 let x = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9476 state = state
9477 .wrapping_mul(6_364_136_223_846_793_005)
9478 .wrapping_add(1);
9479 #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
9480 let y = (((state >> 32) & 0x00FF_FFFF) as f32) / (0x80_0000_u32 as f32) - 1.0;
9481 a.push(x);
9482 b.push(y);
9483 }
9484 let (dot_s, na_s, nb_s) = cosine_dot_norms_scalar(&a, &b);
9485 let (dot_n, na_n, nb_n) = unsafe { cosine_dot_norms_neon(&a, &b) };
9486 #[allow(clippy::cast_precision_loss)]
9487 let tol_d = (dot_s.abs().max(1e-6)) * 1e-4 + (d as f32) * 1e-6;
9488 #[allow(clippy::cast_precision_loss)]
9489 let tol_n = (na_s.abs().max(1e-6)) * 1e-4 + (d as f32) * 1e-6;
9490 assert!(
9491 (dot_s - dot_n).abs() <= tol_d,
9492 "cosine dot dim={d}: scalar={dot_s} neon={dot_n}"
9493 );
9494 assert!(
9495 (na_s - na_n).abs() <= tol_n,
9496 "cosine na dim={d}: scalar={na_s} neon={na_n}"
9497 );
9498 assert!(
9499 (nb_s - nb_n).abs() <= tol_n,
9500 "cosine nb dim={d}: scalar={nb_s} neon={nb_n}"
9501 );
9502 }
9503 }
9504
9505 fn make_users_schema() -> TableSchema {
9506 TableSchema::new(
9507 "users",
9508 vec![
9509 ColumnSchema::new("id", DataType::Int, false),
9510 ColumnSchema::new("name", DataType::Text, false),
9511 ColumnSchema::new("score", DataType::Float, true),
9512 ],
9513 )
9514 }
9515
9516 #[test]
9517 fn value_type_tag_matches_variant() {
9518 assert_eq!(Value::Int(1).data_type(), Some(DataType::Int));
9519 assert_eq!(Value::BigInt(1).data_type(), Some(DataType::BigInt));
9520 assert_eq!(Value::Float(1.0).data_type(), Some(DataType::Float));
9521 assert_eq!(Value::Text("x".into()).data_type(), Some(DataType::Text));
9522 assert_eq!(Value::Bool(true).data_type(), Some(DataType::Bool));
9523 assert_eq!(Value::Null.data_type(), None);
9524 assert!(Value::Null.is_null());
9525 assert!(!Value::Int(0).is_null());
9526 }
9527
9528 #[test]
9529 fn sq8_value_reports_sq8_data_type() {
9530 // v6.0.1: a `Value::Sq8Vector` cell surfaces its dim
9531 // (= bytes.len()) and encoding through `data_type()` so
9532 // INSERT-time column type-checks (step 3) can route on
9533 // both shape and encoding.
9534 let q = crate::quantize::quantize(&[0.0, 0.25, 0.5, 0.75, 1.0]);
9535 let v = Value::Sq8Vector(q);
9536 assert_eq!(
9537 v.data_type(),
9538 Some(DataType::Vector {
9539 dim: 5,
9540 encoding: VecEncoding::Sq8,
9541 }),
9542 );
9543 }
9544
9545 #[test]
9546 fn datatype_display_matches_pg_keyword() {
9547 assert_eq!(DataType::Int.to_string(), "INT");
9548 assert_eq!(DataType::BigInt.to_string(), "BIGINT");
9549 assert_eq!(DataType::Float.to_string(), "FLOAT");
9550 assert_eq!(DataType::Text.to_string(), "TEXT");
9551 assert_eq!(DataType::Bool.to_string(), "BOOL");
9552 }
9553
9554 #[test]
9555 fn row_len_and_emptiness() {
9556 let r = Row::new(vec![Value::Int(1), Value::Null]);
9557 assert_eq!(r.len(), 2);
9558 assert!(!r.is_empty());
9559 assert!(Row::new(Vec::new()).is_empty());
9560 }
9561
9562 #[test]
9563 fn table_schema_column_position() {
9564 let s = make_users_schema();
9565 assert_eq!(s.column_position("id"), Some(0));
9566 assert_eq!(s.column_position("score"), Some(2));
9567 assert_eq!(s.column_position("missing"), None);
9568 }
9569
9570 #[test]
9571 fn catalog_create_table_then_lookup() {
9572 let mut cat = Catalog::new();
9573 cat.create_table(make_users_schema()).unwrap();
9574 assert_eq!(cat.table_count(), 1);
9575 assert!(cat.get("users").is_some());
9576 assert!(cat.get("nope").is_none());
9577 }
9578
9579 #[test]
9580 fn catalog_duplicate_table_is_rejected() {
9581 let mut cat = Catalog::new();
9582 cat.create_table(make_users_schema()).unwrap();
9583 let err = cat.create_table(make_users_schema()).unwrap_err();
9584 assert!(matches!(err, StorageError::DuplicateTable { ref name } if name == "users"));
9585 }
9586
9587 #[test]
9588 fn table_insert_happy_path_appends_row() {
9589 let mut cat = Catalog::new();
9590 cat.create_table(make_users_schema()).unwrap();
9591 let t = cat.get_mut("users").unwrap();
9592 t.insert(Row::new(vec![
9593 Value::Int(1),
9594 Value::Text("alice".into()),
9595 Value::Float(99.5),
9596 ]))
9597 .unwrap();
9598 assert_eq!(t.row_count(), 1);
9599 assert_eq!(t.rows()[0].values[1], Value::Text("alice".into()));
9600 }
9601
9602 #[test]
9603 fn table_insert_arity_mismatch() {
9604 let mut cat = Catalog::new();
9605 cat.create_table(make_users_schema()).unwrap();
9606 let t = cat.get_mut("users").unwrap();
9607 let err = t.insert(Row::new(vec![Value::Int(1)])).unwrap_err();
9608 assert!(matches!(
9609 err,
9610 StorageError::ArityMismatch {
9611 expected: 3,
9612 actual: 1
9613 }
9614 ));
9615 assert_eq!(t.row_count(), 0);
9616 }
9617
9618 #[test]
9619 fn table_insert_type_mismatch_reports_column() {
9620 let mut cat = Catalog::new();
9621 cat.create_table(make_users_schema()).unwrap();
9622 let t = cat.get_mut("users").unwrap();
9623 let err = t
9624 .insert(Row::new(vec![
9625 Value::Int(1),
9626 Value::Int(42), // name expects Text
9627 Value::Float(0.0),
9628 ]))
9629 .unwrap_err();
9630 match err {
9631 StorageError::TypeMismatch {
9632 ref column,
9633 expected,
9634 actual,
9635 position,
9636 } => {
9637 assert_eq!(column, "name");
9638 assert_eq!(expected, DataType::Text);
9639 assert_eq!(actual, DataType::Int);
9640 assert_eq!(position, 1);
9641 }
9642 other => panic!("unexpected: {other:?}"),
9643 }
9644 assert_eq!(t.row_count(), 0);
9645 }
9646
9647 #[test]
9648 fn table_insert_null_into_not_null_rejected() {
9649 let mut cat = Catalog::new();
9650 cat.create_table(make_users_schema()).unwrap();
9651 let t = cat.get_mut("users").unwrap();
9652 let err = t
9653 .insert(Row::new(vec![
9654 Value::Int(1),
9655 Value::Null, // name is NOT NULL
9656 Value::Float(1.0),
9657 ]))
9658 .unwrap_err();
9659 assert!(matches!(err, StorageError::NullInNotNull { ref column } if column == "name"));
9660 }
9661
9662 #[test]
9663 fn table_insert_null_into_nullable_ok() {
9664 let mut cat = Catalog::new();
9665 cat.create_table(make_users_schema()).unwrap();
9666 let t = cat.get_mut("users").unwrap();
9667 t.insert(Row::new(vec![
9668 Value::Int(1),
9669 Value::Text("bob".into()),
9670 Value::Null,
9671 ]))
9672 .unwrap();
9673 assert_eq!(t.row_count(), 1);
9674 }
9675
9676 #[test]
9677 fn catalog_get_mut_independent_per_table() {
9678 let mut cat = Catalog::new();
9679 cat.create_table(TableSchema::new(
9680 "a",
9681 vec![ColumnSchema::new("v", DataType::Int, false)],
9682 ))
9683 .unwrap();
9684 cat.create_table(TableSchema::new(
9685 "b",
9686 vec![ColumnSchema::new("v", DataType::Int, false)],
9687 ))
9688 .unwrap();
9689 cat.get_mut("a")
9690 .unwrap()
9691 .insert(Row::new(vec![Value::Int(1)]))
9692 .unwrap();
9693 assert_eq!(cat.get("a").unwrap().row_count(), 1);
9694 assert_eq!(cat.get("b").unwrap().row_count(), 0);
9695 }
9696
9697 // --- v0.6 persistence round-trips --------------------------------------
9698
9699 fn assert_round_trip(cat: &Catalog) {
9700 let bytes = cat.serialize();
9701 let restored = Catalog::deserialize(&bytes).expect("deserialize");
9702 // Compare semantic state: same tables in same order, same schema +
9703 // rows in each.
9704 assert_eq!(restored.table_count(), cat.table_count());
9705 for (a, b) in cat.tables.iter().zip(restored.tables.iter()) {
9706 assert_eq!(a.schema, b.schema);
9707 assert_eq!(a.rows, b.rows);
9708 }
9709 }
9710
9711 #[test]
9712 fn serialize_empty_catalog_round_trips() {
9713 assert_round_trip(&Catalog::new());
9714 }
9715
9716 #[test]
9717 fn serialize_single_empty_table_round_trips() {
9718 let mut cat = Catalog::new();
9719 cat.create_table(make_users_schema()).unwrap();
9720 assert_round_trip(&cat);
9721 }
9722
9723 #[test]
9724 fn nsw_clone_is_o1() {
9725 // v5.5.0: NswGraph::clone must be O(1) structural sharing, not the
9726 // pre-v5.5 O(N) element copy — it rides on Catalog::clone for every
9727 // group-commit write on a vector table. Build a non-trivial multi-
9728 // layer graph, clone it, and prove the clone shares the very same PV
9729 // storage (root+tail Arc) for `levels` and every `layers[l]`. Sharing
9730 // ⇒ no per-node element copy ⇒ clone cost independent of N (node
9731 // count); only the outer layer Vec (len ≤ 8) is copied, O(1) in
9732 // practice.
9733 let mut cat = Catalog::new();
9734 cat.create_table(TableSchema::new(
9735 "docs",
9736 alloc::vec![
9737 ColumnSchema::new("id", DataType::Int, false),
9738 ColumnSchema::new(
9739 "v",
9740 DataType::Vector {
9741 dim: 3,
9742 encoding: VecEncoding::F32
9743 },
9744 true
9745 ),
9746 ],
9747 ))
9748 .unwrap();
9749 let t = cat.get_mut("docs").unwrap();
9750 for i in 0..1500_i32 {
9751 #[allow(clippy::cast_precision_loss)] // 0..1500 — no precision lost
9752 let base = (i as f32) * 0.01;
9753 t.insert(Row::new(alloc::vec![
9754 Value::Int(i),
9755 Value::Vector(alloc::vec![base, base + 0.05, base + 0.1]),
9756 ]))
9757 .unwrap();
9758 }
9759 t.add_nsw_index("docs_nsw".into(), "v", NSW_DEFAULT_M)
9760 .unwrap();
9761 let g = match &cat.get("docs").unwrap().indices()[0].kind {
9762 IndexKind::Nsw(g) => g,
9763 IndexKind::BTree(_)
9764 | IndexKind::Brin { .. }
9765 | IndexKind::Gin(_)
9766 | IndexKind::GinTrgm(_)
9767 | IndexKind::GinFulltext(_) => {
9768 panic!("expected NSW")
9769 }
9770 };
9771 // Non-trivial graph: one level slot per row, and the geometric level
9772 // distribution puts some nodes above layer 0.
9773 assert_eq!(g.levels.len(), 1500, "one level slot per inserted row");
9774 assert!(
9775 g.layers.len() >= 2,
9776 "1500 nodes should populate at least two HNSW layers, got {}",
9777 g.layers.len()
9778 );
9779
9780 let cloned = g.clone();
9781
9782 assert!(
9783 g.levels.shares_storage_with(&cloned.levels),
9784 "levels PV not shared after clone — clone copied elements (O(N))"
9785 );
9786 assert_eq!(g.layers.len(), cloned.layers.len());
9787 for (l, (orig, cl)) in g.layers.iter().zip(cloned.layers.iter()).enumerate() {
9788 assert!(
9789 orig.shares_storage_with(cl),
9790 "layer {l} PV not shared after clone — clone copied elements (O(N))"
9791 );
9792 }
9793 }
9794
9795 #[test]
9796 fn sq8_catalog_serialise_roundtrip_preserves_cells_and_index() {
9797 // v6.0.1 step 6 verify: a catalog with an `VECTOR(N)
9798 // USING SQ8` column + NSW index survives a full
9799 // serialise → deserialise cycle. Cells re-decode bit-
9800 // identically (per-vector affine triple), the NSW
9801 // topology stays intact, and kNN search still routes
9802 // through the SQ8 ADC dispatcher after the catalog hop.
9803 let mut cat = Catalog::new();
9804 cat.create_table(TableSchema::new(
9805 "vecs",
9806 alloc::vec![
9807 ColumnSchema::new("id", DataType::Int, false),
9808 ColumnSchema::new(
9809 "v",
9810 DataType::Vector {
9811 dim: 8,
9812 encoding: VecEncoding::Sq8,
9813 },
9814 false,
9815 ),
9816 ],
9817 ))
9818 .unwrap();
9819 let t = cat.get_mut("vecs").unwrap();
9820 for i in 0..32_i32 {
9821 #[allow(clippy::cast_precision_loss)]
9822 let base = (i as f32) * 0.03;
9823 let v: Vec<f32> = (0..8_i32)
9824 .map(|j| {
9825 #[allow(clippy::cast_precision_loss)]
9826 let off = (j as f32) * 0.01;
9827 base + off
9828 })
9829 .collect();
9830 t.insert(Row::new(alloc::vec![
9831 Value::Int(i),
9832 Value::Sq8Vector(quantize::quantize(&v)),
9833 ]))
9834 .unwrap();
9835 }
9836 t.add_nsw_index("v_idx".into(), "v", NSW_DEFAULT_M).unwrap();
9837 // Capture a pre-serialise reference cell + nsw hits to
9838 // compare against the restored catalog.
9839 let query = alloc::vec![0.15_f32, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22];
9840 let (before_cell, before_ty, before_hits) = {
9841 let t_ref = cat.get("vecs").unwrap();
9842 (
9843 t_ref.rows()[5].values[1].clone(),
9844 t_ref.schema().columns[1].ty,
9845 nsw_query(t_ref, "v_idx", &query, 5, NswMetric::L2),
9846 )
9847 };
9848
9849 let bytes = cat.serialize();
9850 let restored = Catalog::deserialize(&bytes).expect("deserialize ok");
9851 let rt = restored.get("vecs").unwrap();
9852 assert_eq!(rt.schema().columns[1].ty, before_ty);
9853 assert_eq!(rt.rows()[5].values[1], before_cell);
9854 let after_hits = nsw_query(rt, "v_idx", &query, 5, NswMetric::L2);
9855 assert_eq!(before_hits, after_hits);
9856 }
9857
9858 #[test]
9859 fn half_catalog_serialise_roundtrip_preserves_cells_and_index() {
9860 // v6.0.3 step 4 verify: a catalog with a `VECTOR(N) USING
9861 // HALF` column + NSW index survives a full serialise →
9862 // deserialise cycle. Cells re-decode bit-identically (raw
9863 // u16 LE bytes), the NSW topology stays intact, and kNN
9864 // search still returns the same hit IDs against the
9865 // restored catalog.
9866 use crate::halfvec;
9867 let mut cat = Catalog::new();
9868 cat.create_table(TableSchema::new(
9869 "vecs",
9870 alloc::vec![
9871 ColumnSchema::new("id", DataType::Int, false),
9872 ColumnSchema::new(
9873 "v",
9874 DataType::Vector {
9875 dim: 8,
9876 encoding: VecEncoding::F16,
9877 },
9878 false,
9879 ),
9880 ],
9881 ))
9882 .unwrap();
9883 let t = cat.get_mut("vecs").unwrap();
9884 for i in 0..32_i32 {
9885 #[allow(clippy::cast_precision_loss)]
9886 let base = (i as f32) * 0.03;
9887 let v: Vec<f32> = (0..8_i32)
9888 .map(|j| {
9889 #[allow(clippy::cast_precision_loss)]
9890 let off = (j as f32) * 0.01;
9891 base + off
9892 })
9893 .collect();
9894 t.insert(Row::new(alloc::vec![
9895 Value::Int(i),
9896 Value::HalfVector(halfvec::HalfVector::from_f32_slice(&v)),
9897 ]))
9898 .unwrap();
9899 }
9900 t.add_nsw_index("v_idx".into(), "v", NSW_DEFAULT_M).unwrap();
9901 let query = alloc::vec![0.15_f32, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22];
9902 let (before_cell, before_ty, before_hits) = {
9903 let t_ref = cat.get("vecs").unwrap();
9904 (
9905 t_ref.rows()[5].values[1].clone(),
9906 t_ref.schema().columns[1].ty,
9907 nsw_query(t_ref, "v_idx", &query, 5, NswMetric::L2),
9908 )
9909 };
9910 let bytes = cat.serialize();
9911 let restored = Catalog::deserialize(&bytes).expect("deserialize ok");
9912 let rt = restored.get("vecs").unwrap();
9913 assert_eq!(rt.schema().columns[1].ty, before_ty);
9914 assert_eq!(rt.rows()[5].values[1], before_cell);
9915 let after_hits = nsw_query(rt, "v_idx", &query, 5, NswMetric::L2);
9916 assert_eq!(before_hits, after_hits);
9917 }
9918
9919 #[test]
9920 #[allow(clippy::similar_names)]
9921 fn hnsw_half_recall_at_10_matches_f32_groundtruth() {
9922 // v6.0.3 step 3 verify: HALF column NSW retrieves ≥ 95%
9923 // top-10 overlap vs brute-force F32 ground truth.
9924 // Half-precision dequantises bit-exactly at the storage
9925 // layer (no rerank pass), so the recall floor is tighter
9926 // than the SQ8 case — only the rounding noise from f32 →
9927 // f16 quantisation contributes.
9928 use crate::halfvec;
9929 fn next(state: &mut u64) -> f32 {
9930 *state = state
9931 .wrapping_add(0x9E37_79B9_7F4A_7C15)
9932 .wrapping_mul(0xBF58_476D_1CE4_E5B9);
9933 #[allow(clippy::cast_precision_loss)]
9934 let u = ((*state >> 32) as u32 as f32) / (u32::MAX as f32);
9935 2.0 * u - 1.0
9936 }
9937 let dim: u32 = 32;
9938 let n: usize = 512;
9939 let dim_us = dim as usize;
9940 let mut seed: u64 = 0xF16_F16_F16_F16_u64;
9941 let corpus: Vec<Vec<f32>> = (0..n)
9942 .map(|_| (0..dim_us).map(|_| next(&mut seed)).collect())
9943 .collect();
9944 let queries: Vec<Vec<f32>> = (0..32)
9945 .map(|_| (0..dim_us).map(|_| next(&mut seed)).collect())
9946 .collect();
9947 let exact_top10: Vec<Vec<usize>> = queries
9948 .iter()
9949 .map(|q| {
9950 let mut scored: Vec<(f32, usize)> = corpus
9951 .iter()
9952 .enumerate()
9953 .map(|(i, v)| (l2_distance_sq(v, q), i))
9954 .collect();
9955 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
9956 scored.into_iter().take(10).map(|(_, i)| i).collect()
9957 })
9958 .collect();
9959 let mut cat = Catalog::new();
9960 cat.create_table(TableSchema::new(
9961 "vecs",
9962 alloc::vec![
9963 ColumnSchema::new("id", DataType::Int, false),
9964 ColumnSchema::new(
9965 "v",
9966 DataType::Vector {
9967 dim,
9968 encoding: VecEncoding::F16,
9969 },
9970 false,
9971 ),
9972 ],
9973 ))
9974 .unwrap();
9975 let t = cat.get_mut("vecs").unwrap();
9976 for (i, v) in corpus.iter().enumerate() {
9977 t.insert(Row::new(alloc::vec![
9978 Value::Int(i32::try_from(i).unwrap()),
9979 Value::HalfVector(halfvec::HalfVector::from_f32_slice(v)),
9980 ]))
9981 .unwrap();
9982 }
9983 t.add_nsw_index("v_idx".into(), "v", NSW_DEFAULT_M).unwrap();
9984 let table = cat.get("vecs").unwrap();
9985 let mut total_overlap = 0_usize;
9986 for (q, exact) in queries.iter().zip(exact_top10.iter()) {
9987 let hits = nsw_query(table, "v_idx", q, 10, NswMetric::L2);
9988 for h in &hits {
9989 if exact.contains(h) {
9990 total_overlap += 1;
9991 }
9992 }
9993 }
9994 #[allow(clippy::cast_precision_loss)]
9995 let recall = total_overlap as f32 / (10.0 * queries.len() as f32);
9996 assert!(
9997 recall >= 0.95,
9998 "HALF HNSW recall@10 = {recall:.3}, below floor 0.95 — \
9999 check halfvec dispatch in `cell_to_query_metric_distance`"
10000 );
10001 }
10002
10003 #[test]
10004 fn hnsw_sq8_recall_at_10_above_0_95_vs_f32_groundtruth() {
10005 // v6.0.1 step 5 verify: build TWO catalogs over the same
10006 // corpus — one F32, one SQ8 — and confirm SQ8 NSW + f32
10007 // rerank retrieves ≥ 95% top-10 overlap vs brute-force F32
10008 // ground truth. The rerank pass (sq8_rerank) re-scores ADC
10009 // candidates with dequantised cells, recovering recall the
10010 // raw ADC sacrifices for 4× compression.
10011 use crate::quantize;
10012 // Deterministic Gaussian-ish corpus via splitmix64. Vectors
10013 // get normalised so SQ8's per-vector `(min, max)` lives in
10014 // a sensible range; matches the v6.0.0 fuzz harness.
10015 fn next(state: &mut u64) -> f32 {
10016 *state = state
10017 .wrapping_add(0x9E37_79B9_7F4A_7C15)
10018 .wrapping_mul(0xBF58_476D_1CE4_E5B9);
10019 #[allow(clippy::cast_precision_loss)]
10020 let u = ((*state >> 32) as u32 as f32) / (u32::MAX as f32);
10021 2.0 * u - 1.0
10022 }
10023 let dim: u32 = 32;
10024 let n: usize = 512;
10025 let dim_us = dim as usize;
10026 let mut seed: u64 = 0xCAFE_BABE_DEAD_BEEFu64;
10027 let corpus: Vec<Vec<f32>> = (0..n)
10028 .map(|_| (0..dim_us).map(|_| next(&mut seed)).collect())
10029 .collect();
10030 let queries: Vec<Vec<f32>> = (0..32)
10031 .map(|_| (0..dim_us).map(|_| next(&mut seed)).collect())
10032 .collect();
10033 // F32 ground truth — pure exact arithmetic, brute force.
10034 let exact_top10: Vec<Vec<usize>> = queries
10035 .iter()
10036 .map(|q| {
10037 let mut scored: Vec<(f32, usize)> = corpus
10038 .iter()
10039 .enumerate()
10040 .map(|(i, v)| (l2_distance_sq(v, q), i))
10041 .collect();
10042 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
10043 scored.into_iter().take(10).map(|(_, i)| i).collect()
10044 })
10045 .collect();
10046 // SQ8 catalog — INSERTs land as `Value::Sq8Vector` cells;
10047 // HNSW build uses the ADC path verified in step 4.
10048 let mut cat = Catalog::new();
10049 cat.create_table(TableSchema::new(
10050 "vecs",
10051 alloc::vec![
10052 ColumnSchema::new("id", DataType::Int, false),
10053 ColumnSchema::new(
10054 "v",
10055 DataType::Vector {
10056 dim,
10057 encoding: VecEncoding::Sq8,
10058 },
10059 false,
10060 ),
10061 ],
10062 ))
10063 .unwrap();
10064 let t = cat.get_mut("vecs").unwrap();
10065 for (i, v) in corpus.iter().enumerate() {
10066 t.insert(Row::new(alloc::vec![
10067 Value::Int(i32::try_from(i).unwrap()),
10068 Value::Sq8Vector(quantize::quantize(v)),
10069 ]))
10070 .unwrap();
10071 }
10072 t.add_nsw_index("v_idx".into(), "v", NSW_DEFAULT_M).unwrap();
10073 let table = cat.get("vecs").unwrap();
10074 let mut total_overlap = 0_usize;
10075 for (q, exact) in queries.iter().zip(exact_top10.iter()) {
10076 let hits = nsw_query(table, "v_idx", q, 10, NswMetric::L2);
10077 for h in &hits {
10078 if exact.contains(h) {
10079 total_overlap += 1;
10080 }
10081 }
10082 }
10083 #[allow(clippy::cast_precision_loss)]
10084 let recall = total_overlap as f32 / (10.0 * queries.len() as f32);
10085 assert!(
10086 recall >= 0.95,
10087 "SQ8 HNSW recall@10 = {recall:.3}, below floor 0.95 — \
10088 check `sq8_rerank` is wired in `nsw_search` for SQ8 columns"
10089 );
10090 }
10091
10092 #[test]
10093 fn nsw_index_topology_persists_through_round_trip() {
10094 // Build an NSW index, capture its (entry, neighbors) tuple, do
10095 // a full serialize → deserialize, and verify the restored
10096 // graph is byte-for-byte identical. The point of v2.7 is that
10097 // startup skips the rebuild, so the topology has to survive
10098 // the disk hop.
10099 let mut cat = Catalog::new();
10100 cat.create_table(TableSchema::new(
10101 "docs",
10102 alloc::vec![
10103 ColumnSchema::new("id", DataType::Int, false),
10104 ColumnSchema::new(
10105 "v",
10106 DataType::Vector {
10107 dim: 3,
10108 encoding: VecEncoding::F32
10109 },
10110 true
10111 ),
10112 ],
10113 ))
10114 .unwrap();
10115 let t = cat.get_mut("docs").unwrap();
10116 for i in 0..6_i32 {
10117 #[allow(clippy::cast_precision_loss)] // 0..6 — no precision lost
10118 let base = (i as f32) * 0.1;
10119 let row = Row::new(alloc::vec![
10120 Value::Int(i),
10121 Value::Vector(alloc::vec![base, base + 0.05, base + 0.1]),
10122 ]);
10123 t.insert(row).unwrap();
10124 }
10125 t.add_nsw_index("docs_nsw".into(), "v", NSW_DEFAULT_M)
10126 .unwrap();
10127 let original = match &cat.get("docs").unwrap().indices()[0].kind {
10128 IndexKind::Nsw(g) => g.clone(),
10129 IndexKind::BTree(_)
10130 | IndexKind::Brin { .. }
10131 | IndexKind::Gin(_)
10132 | IndexKind::GinTrgm(_)
10133 | IndexKind::GinFulltext(_) => {
10134 panic!("expected NSW")
10135 }
10136 };
10137 let bytes = cat.serialize();
10138 let restored = Catalog::deserialize(&bytes).expect("deserialize");
10139 let restored_graph = match &restored.get("docs").unwrap().indices()[0].kind {
10140 IndexKind::Nsw(g) => g.clone(),
10141 IndexKind::BTree(_)
10142 | IndexKind::Brin { .. }
10143 | IndexKind::Gin(_)
10144 | IndexKind::GinTrgm(_)
10145 | IndexKind::GinFulltext(_) => {
10146 panic!("expected NSW")
10147 }
10148 };
10149 assert_eq!(restored_graph.m, original.m);
10150 assert_eq!(restored_graph.m_max_0, original.m_max_0);
10151 assert_eq!(restored_graph.entry, original.entry);
10152 assert_eq!(restored_graph.entry_level, original.entry_level);
10153 assert_eq!(restored_graph.levels, original.levels);
10154 assert_eq!(restored_graph.layers, original.layers);
10155 }
10156
10157 #[test]
10158 fn hnsw_level_assignment_is_deterministic() {
10159 // Same row index always produces the same level — the topology
10160 // must be reproducible (matters for serialize round-trip).
10161 for i in 0..32usize {
10162 assert_eq!(nsw_assign_level(i), nsw_assign_level(i));
10163 }
10164 }
10165
10166 #[test]
10167 fn hnsw_layer_0_dominates_population() {
10168 // Sanity: out of N inserts, the vast majority should land on
10169 // layer 0. The 4-bit-clear promotion rule gives roughly 1/16
10170 // promotion to layer ≥ 1, so under 50 nodes we expect ~3 on
10171 // layer ≥ 1 and the rest on layer 0.
10172 let on_zero = (0..200usize).filter(|&i| nsw_assign_level(i) == 0).count();
10173 assert!(on_zero > 150, "level-0 nodes too few: {on_zero}");
10174 }
10175
10176 #[test]
10177 fn hnsw_search_matches_brute_force_for_l2_top1() {
10178 // Build a small dataset, query it, and confirm the top result
10179 // matches the brute-force nearest by L2. Topology variability
10180 // shouldn't break recall at k=1 for well-separated vectors.
10181 let mut cat = Catalog::new();
10182 cat.create_table(TableSchema::new(
10183 "vecs",
10184 alloc::vec![
10185 ColumnSchema::new("id", DataType::Int, false),
10186 ColumnSchema::new(
10187 "v",
10188 DataType::Vector {
10189 dim: 3,
10190 encoding: VecEncoding::F32
10191 },
10192 true
10193 ),
10194 ],
10195 ))
10196 .unwrap();
10197 let t = cat.get_mut("vecs").unwrap();
10198 let dataset: alloc::vec::Vec<(i32, [f32; 3])> = alloc::vec![
10199 (1, [0.0, 0.0, 0.0]),
10200 (2, [1.0, 0.0, 0.0]),
10201 (3, [0.0, 1.0, 0.0]),
10202 (4, [0.0, 0.0, 1.0]),
10203 (5, [1.0, 1.0, 0.0]),
10204 (6, [1.0, 0.0, 1.0]),
10205 (7, [0.0, 1.0, 1.0]),
10206 (8, [1.0, 1.0, 1.0]),
10207 (9, [0.5, 0.5, 0.5]),
10208 (10, [0.2, 0.8, 0.5]),
10209 ];
10210 for &(id, v) in &dataset {
10211 t.insert(Row::new(alloc::vec![
10212 Value::Int(id),
10213 Value::Vector(alloc::vec![v[0], v[1], v[2]]),
10214 ]))
10215 .unwrap();
10216 }
10217 t.add_nsw_index("v_idx".into(), "v", NSW_DEFAULT_M).unwrap();
10218 let idx_pos = cat
10219 .get("vecs")
10220 .unwrap()
10221 .indices()
10222 .iter()
10223 .position(|i| i.name == "v_idx")
10224 .unwrap();
10225 for query in [[0.4, 0.4, 0.4], [0.9, 0.1, 0.0], [0.0, 0.9, 0.9]] {
10226 let table = cat.get("vecs").unwrap();
10227 let hnsw_top = nsw_search(table, idx_pos, &query, 1, 16, NswMetric::L2);
10228 let mut brute: alloc::vec::Vec<(f32, usize)> = (0..table.rows.len())
10229 .map(|i| {
10230 let Value::Vector(v) = &table.rows[i].values[1] else {
10231 return (f32::INFINITY, i);
10232 };
10233 (l2_distance_sq(v, &query), i)
10234 })
10235 .collect();
10236 brute.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(core::cmp::Ordering::Equal));
10237 assert!(!hnsw_top.is_empty(), "HNSW returned no results");
10238 assert_eq!(
10239 hnsw_top[0].1, brute[0].1,
10240 "HNSW top-1 != brute-force top-1 for {query:?}"
10241 );
10242 }
10243 }
10244
10245 #[test]
10246 fn serialize_table_with_rows_round_trips() {
10247 let mut cat = Catalog::new();
10248 cat.create_table(make_users_schema()).unwrap();
10249 let t = cat.get_mut("users").unwrap();
10250 t.insert(Row::new(vec![
10251 Value::Int(1),
10252 Value::Text("alice".into()),
10253 Value::Float(95.5),
10254 ]))
10255 .unwrap();
10256 t.insert(Row::new(vec![
10257 Value::Int(2),
10258 Value::Text("bob".into()),
10259 Value::Null,
10260 ]))
10261 .unwrap();
10262 assert_round_trip(&cat);
10263 }
10264
10265 #[test]
10266 fn serialize_multiple_tables_round_trips() {
10267 let mut cat = Catalog::new();
10268 cat.create_table(make_users_schema()).unwrap();
10269 cat.create_table(TableSchema::new(
10270 "flags",
10271 vec![
10272 ColumnSchema::new("id", DataType::BigInt, false),
10273 ColumnSchema::new("active", DataType::Bool, false),
10274 ],
10275 ))
10276 .unwrap();
10277 cat.get_mut("flags")
10278 .unwrap()
10279 .insert(Row::new(vec![Value::BigInt(7), Value::Bool(true)]))
10280 .unwrap();
10281 assert_round_trip(&cat);
10282 }
10283
10284 #[test]
10285 fn deserialize_rejects_bad_magic() {
10286 let mut buf = b"BADMAGIC".to_vec();
10287 buf.push(FILE_VERSION);
10288 buf.extend_from_slice(&0u32.to_le_bytes());
10289 let err = Catalog::deserialize(&buf).unwrap_err();
10290 assert!(matches!(err, StorageError::Corrupt(_)));
10291 }
10292
10293 #[test]
10294 fn deserialize_rejects_unsupported_version() {
10295 let mut buf = FILE_MAGIC.to_vec();
10296 buf.push(99); // future version
10297 buf.extend_from_slice(&0u32.to_le_bytes());
10298 let err = Catalog::deserialize(&buf).unwrap_err();
10299 assert!(matches!(err, StorageError::Corrupt(ref s) if s.contains("version")));
10300 }
10301
10302 #[test]
10303 fn deserialize_rejects_truncated_file() {
10304 let mut cat = Catalog::new();
10305 cat.create_table(make_users_schema()).unwrap();
10306 let bytes = cat.serialize();
10307 // Drop the last byte to simulate truncation.
10308 let truncated = &bytes[..bytes.len() - 1];
10309 assert!(matches!(
10310 Catalog::deserialize(truncated),
10311 Err(StorageError::Corrupt(_))
10312 ));
10313 }
10314
10315 #[test]
10316 fn deserialize_rejects_trailing_garbage() {
10317 let cat = Catalog::new();
10318 let mut bytes = cat.serialize();
10319 bytes.push(0xFF);
10320 assert!(matches!(
10321 Catalog::deserialize(&bytes),
10322 Err(StorageError::Corrupt(ref s)) if s.contains("trailing")
10323 ));
10324 }
10325
10326 // --- v0.8 indices ------------------------------------------------------
10327
10328 fn populated_users() -> Catalog {
10329 let mut cat = Catalog::new();
10330 cat.create_table(make_users_schema()).unwrap();
10331 let t = cat.get_mut("users").unwrap();
10332 for (id, name, score) in [
10333 (1, "alice", Some(90.0)),
10334 (2, "bob", None),
10335 (3, "alice", Some(70.0)), // duplicate name → maps to two row idxs
10336 ] {
10337 t.insert(Row::new(vec![
10338 Value::Int(id),
10339 Value::Text(name.into()),
10340 score.map_or(Value::Null, Value::Float),
10341 ]))
10342 .unwrap();
10343 }
10344 cat
10345 }
10346
10347 #[test]
10348 fn add_index_builds_from_existing_rows() {
10349 let mut cat = populated_users();
10350 cat.get_mut("users")
10351 .unwrap()
10352 .add_index("by_id".into(), "id")
10353 .unwrap();
10354 let t = cat.get("users").unwrap();
10355 let idx = t.index_on(0).expect("index_on(0)");
10356 assert_eq!(idx.lookup_eq(&IndexKey::Int(2)), &[RowLocator::Hot(1)]);
10357 assert_eq!(idx.lookup_eq(&IndexKey::Int(99)), &[] as &[RowLocator]);
10358 }
10359
10360 #[test]
10361 fn add_index_dup_name_rejected() {
10362 let mut cat = populated_users();
10363 let t = cat.get_mut("users").unwrap();
10364 t.add_index("ix".into(), "id").unwrap();
10365 let err = t.add_index("ix".into(), "name").unwrap_err();
10366 assert!(matches!(err, StorageError::DuplicateIndex { ref name } if name == "ix"));
10367 }
10368
10369 #[test]
10370 fn add_index_unknown_column_rejected() {
10371 let mut cat = populated_users();
10372 let err = cat
10373 .get_mut("users")
10374 .unwrap()
10375 .add_index("ix".into(), "ghost")
10376 .unwrap_err();
10377 assert!(matches!(err, StorageError::ColumnNotFound { ref column } if column == "ghost"));
10378 }
10379
10380 #[test]
10381 fn insert_after_create_index_updates_it() {
10382 let mut cat = populated_users();
10383 let t = cat.get_mut("users").unwrap();
10384 t.add_index("by_name".into(), "name").unwrap();
10385 t.insert(Row::new(vec![
10386 Value::Int(4),
10387 Value::Text("dave".into()),
10388 Value::Null,
10389 ]))
10390 .unwrap();
10391 let idx = t.index_on(1).unwrap();
10392 assert_eq!(
10393 idx.lookup_eq(&IndexKey::Text("dave".into())),
10394 &[RowLocator::Hot(3)]
10395 );
10396 // Pre-existing duplicates remain mapped to the two original row idxs.
10397 assert_eq!(
10398 idx.lookup_eq(&IndexKey::Text("alice".into())),
10399 &[RowLocator::Hot(0), RowLocator::Hot(2)]
10400 );
10401 }
10402
10403 #[test]
10404 fn null_or_float_values_are_not_indexed() {
10405 let mut cat = populated_users();
10406 let t = cat.get_mut("users").unwrap();
10407 t.add_index("by_score".into(), "score").unwrap();
10408 let idx = t.index_on(2).unwrap();
10409 // bob's score is NULL → no entry for bob.
10410 // Score is Float → the spec says we don't index NaN-prone columns,
10411 // so even the present scores are absent. Lookups via IndexKey::Int(90)
10412 // mis-match the column type and trivially find nothing.
10413 assert_eq!(idx.lookup_eq(&IndexKey::Int(90)), &[] as &[RowLocator]);
10414 }
10415
10416 // --- v0.11 vector type -------------------------------------------------
10417
10418 #[test]
10419 fn vector_value_data_type_carries_dim() {
10420 let v = Value::Vector(vec![1.0, 2.0, 3.0]);
10421 assert_eq!(
10422 v.data_type(),
10423 Some(DataType::Vector {
10424 dim: 3,
10425 encoding: VecEncoding::F32
10426 })
10427 );
10428 }
10429
10430 #[test]
10431 fn vector_column_insert_matching_dim_ok() {
10432 let mut cat = Catalog::new();
10433 cat.create_table(TableSchema::new(
10434 "emb",
10435 vec![ColumnSchema::new(
10436 "v",
10437 DataType::Vector {
10438 dim: 3,
10439 encoding: VecEncoding::F32,
10440 },
10441 false,
10442 )],
10443 ))
10444 .unwrap();
10445 cat.get_mut("emb")
10446 .unwrap()
10447 .insert(Row::new(vec![Value::Vector(vec![1.0, 2.0, 3.0])]))
10448 .unwrap();
10449 }
10450
10451 #[test]
10452 fn vector_column_insert_dim_mismatch_rejected() {
10453 let mut cat = Catalog::new();
10454 cat.create_table(TableSchema::new(
10455 "emb",
10456 vec![ColumnSchema::new(
10457 "v",
10458 DataType::Vector {
10459 dim: 3,
10460 encoding: VecEncoding::F32,
10461 },
10462 false,
10463 )],
10464 ))
10465 .unwrap();
10466 let err = cat
10467 .get_mut("emb")
10468 .unwrap()
10469 .insert(Row::new(vec![Value::Vector(vec![1.0, 2.0])]))
10470 .unwrap_err();
10471 assert!(matches!(err, StorageError::TypeMismatch { .. }));
10472 }
10473
10474 #[test]
10475 fn vector_value_survives_catalog_round_trip() {
10476 let mut cat = Catalog::new();
10477 cat.create_table(TableSchema::new(
10478 "emb",
10479 vec![
10480 ColumnSchema::new("id", DataType::Int, false),
10481 ColumnSchema::new(
10482 "v",
10483 DataType::Vector {
10484 dim: 4,
10485 encoding: VecEncoding::F32,
10486 },
10487 false,
10488 ),
10489 ],
10490 ))
10491 .unwrap();
10492 cat.get_mut("emb")
10493 .unwrap()
10494 .insert(Row::new(vec![
10495 Value::Int(1),
10496 Value::Vector(vec![0.5, -1.25, 3.0, 7.0]),
10497 ]))
10498 .unwrap();
10499 let restored = Catalog::deserialize(&cat.serialize()).expect("round-trip");
10500 let table = restored.get("emb").unwrap();
10501 assert_eq!(
10502 table.schema().columns[1].ty,
10503 DataType::Vector {
10504 dim: 4,
10505 encoding: VecEncoding::F32
10506 }
10507 );
10508 assert_eq!(
10509 table.rows()[0].values[1],
10510 Value::Vector(vec![0.5, -1.25, 3.0, 7.0])
10511 );
10512 }
10513
10514 #[test]
10515 fn index_survives_serialize_deserialize_round_trip() {
10516 let mut cat = populated_users();
10517 cat.get_mut("users")
10518 .unwrap()
10519 .add_index("by_name".into(), "name")
10520 .unwrap();
10521 let restored = Catalog::deserialize(&cat.serialize()).unwrap();
10522 let idx = restored
10523 .get("users")
10524 .unwrap()
10525 .index_on(1)
10526 .expect("index_on(1) after restore");
10527 assert_eq!(idx.name, "by_name");
10528 // Data was rebuilt from rows, not deserialized directly.
10529 assert_eq!(
10530 idx.lookup_eq(&IndexKey::Text("alice".into())),
10531 &[RowLocator::Hot(0), RowLocator::Hot(2)]
10532 );
10533 }
10534
10535 // --- v5.1 cold-tier integration tests ----------------------
10536
10537 /// Schema with a BIGINT PK column matching what the v5.1 cold-
10538 /// tier path supports (`IndexKey::Int` → `u64` cast).
10539 fn bigint_pk_users_schema() -> TableSchema {
10540 TableSchema::new(
10541 "users",
10542 vec![
10543 ColumnSchema::new("id", DataType::BigInt, false),
10544 ColumnSchema::new("name", DataType::Text, false),
10545 ],
10546 )
10547 }
10548
10549 fn make_user_row(id: i64, name: &str) -> Row {
10550 Row::new(vec![Value::BigInt(id), Value::Text(name.into())])
10551 }
10552
10553 #[test]
10554 fn lookup_by_pk_finds_row_via_hot_index() {
10555 let mut cat = Catalog::new();
10556 cat.create_table(bigint_pk_users_schema()).unwrap();
10557 let t = cat.get_mut("users").unwrap();
10558 for (id, name) in [(1i64, "alice"), (2, "bob"), (3, "carol")] {
10559 t.insert(make_user_row(id, name)).unwrap();
10560 }
10561 t.add_index("by_id".into(), "id").unwrap();
10562 // All locators are Hot; cold_segments is empty.
10563 let got = cat
10564 .lookup_by_pk("users", "by_id", &IndexKey::Int(2))
10565 .unwrap();
10566 assert_eq!(got, make_user_row(2, "bob"));
10567 assert_eq!(cat.cold_segment_count(), 0);
10568 }
10569
10570 #[test]
10571 fn lookup_by_pk_returns_none_when_key_missing() {
10572 let mut cat = Catalog::new();
10573 cat.create_table(bigint_pk_users_schema()).unwrap();
10574 let t = cat.get_mut("users").unwrap();
10575 t.insert(make_user_row(1, "alice")).unwrap();
10576 t.add_index("by_id".into(), "id").unwrap();
10577 assert!(
10578 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(999))
10579 .is_none()
10580 );
10581 // Also: unknown table / unknown index name.
10582 assert!(
10583 cat.lookup_by_pk("other_table", "by_id", &IndexKey::Int(1))
10584 .is_none()
10585 );
10586 assert!(
10587 cat.lookup_by_pk("users", "no_such_index", &IndexKey::Int(1))
10588 .is_none()
10589 );
10590 }
10591
10592 #[test]
10593 fn lookup_by_pk_resolves_cold_locator_via_loaded_segment() {
10594 // Build a cold-tier segment whose payloads are dense-encoded
10595 // BIGINT rows. Wire each PK into the BTree index as a Cold
10596 // locator. The hot tier carries no rows for those PKs.
10597 let mut cat = Catalog::new();
10598 cat.create_table(bigint_pk_users_schema()).unwrap();
10599 let t = cat.get_mut("users").unwrap();
10600 t.add_index("by_id".into(), "id").unwrap();
10601 let schema = t.schema.clone();
10602
10603 let cold_rows: Vec<(i64, &str)> =
10604 vec![(100, "ivy"), (200, "joe"), (300, "kim"), (400, "lin")];
10605 let seg_rows: Vec<(u64, Vec<u8>)> = cold_rows
10606 .iter()
10607 .map(|(id, name)| {
10608 let row = make_user_row(*id, name);
10609 ((*id).cast_unsigned(), encode_row_body_dense(&row, &schema))
10610 })
10611 .collect();
10612 let (seg_bytes, _meta) =
10613 encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES).unwrap();
10614 let seg_id = cat.load_segment_bytes(seg_bytes).unwrap();
10615 assert_eq!(seg_id, 0);
10616 assert_eq!(cat.cold_segment_count(), 1);
10617
10618 let pairs: Vec<(IndexKey, RowLocator)> = cold_rows
10619 .iter()
10620 .map(|(id, _)| {
10621 (
10622 IndexKey::Int(*id),
10623 RowLocator::Cold {
10624 segment_id: seg_id,
10625 page_offset: 0,
10626 },
10627 )
10628 })
10629 .collect();
10630 let registered = cat
10631 .get_mut("users")
10632 .unwrap()
10633 .register_cold_locators("by_id", pairs)
10634 .unwrap();
10635 assert_eq!(registered, 4);
10636
10637 for (id, name) in &cold_rows {
10638 let got = cat
10639 .lookup_by_pk("users", "by_id", &IndexKey::Int(*id))
10640 .unwrap_or_else(|| panic!("cold key {id} not found"));
10641 assert_eq!(got, make_user_row(*id, name));
10642 }
10643 // Cold key that isn't in the segment must return None.
10644 assert!(
10645 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(999))
10646 .is_none()
10647 );
10648 }
10649
10650 #[test]
10651 fn lookup_by_pk_mixes_hot_and_cold_tiers() {
10652 // Half the rows live in the hot tier (Table::rows + add_index
10653 // produces Hot locators); half live in a cold segment and have
10654 // Cold locators wired manually. Each lookup hits the right tier.
10655 let mut cat = Catalog::new();
10656 cat.create_table(bigint_pk_users_schema()).unwrap();
10657 let t = cat.get_mut("users").unwrap();
10658 for (id, name) in [(1i64, "alice"), (2, "bob")] {
10659 t.insert(make_user_row(id, name)).unwrap();
10660 }
10661 t.add_index("by_id".into(), "id").unwrap();
10662 let schema = t.schema.clone();
10663
10664 let cold_rows: Vec<(i64, &str)> = vec![(100, "ivy"), (200, "joe")];
10665 let seg_rows: Vec<(u64, Vec<u8>)> = cold_rows
10666 .iter()
10667 .map(|(id, name)| {
10668 let row = make_user_row(*id, name);
10669 ((*id).cast_unsigned(), encode_row_body_dense(&row, &schema))
10670 })
10671 .collect();
10672 let (seg_bytes, _) =
10673 encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES).unwrap();
10674 let seg_id = cat.load_segment_bytes(seg_bytes).unwrap();
10675 let pairs: Vec<(IndexKey, RowLocator)> = cold_rows
10676 .iter()
10677 .map(|(id, _)| {
10678 (
10679 IndexKey::Int(*id),
10680 RowLocator::Cold {
10681 segment_id: seg_id,
10682 page_offset: 0,
10683 },
10684 )
10685 })
10686 .collect();
10687 cat.get_mut("users")
10688 .unwrap()
10689 .register_cold_locators("by_id", pairs)
10690 .unwrap();
10691
10692 // Hot tier hits.
10693 assert_eq!(
10694 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(1))
10695 .unwrap(),
10696 make_user_row(1, "alice")
10697 );
10698 assert_eq!(
10699 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(2))
10700 .unwrap(),
10701 make_user_row(2, "bob")
10702 );
10703 // Cold tier hits.
10704 assert_eq!(
10705 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(100))
10706 .unwrap(),
10707 make_user_row(100, "ivy")
10708 );
10709 assert_eq!(
10710 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(200))
10711 .unwrap(),
10712 make_user_row(200, "joe")
10713 );
10714 // Miss in both tiers.
10715 assert!(
10716 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(50))
10717 .is_none()
10718 );
10719 }
10720
10721 #[test]
10722 fn register_cold_locators_rejects_nsw_index() {
10723 let mut cat = Catalog::new();
10724 cat.create_table(TableSchema::new(
10725 "vecs",
10726 vec![
10727 ColumnSchema::new("id", DataType::Int, false),
10728 ColumnSchema::new(
10729 "v",
10730 DataType::Vector {
10731 dim: 4,
10732 encoding: VecEncoding::F32,
10733 },
10734 false,
10735 ),
10736 ],
10737 ))
10738 .unwrap();
10739 let t = cat.get_mut("vecs").unwrap();
10740 t.insert(Row::new(vec![
10741 Value::Int(1),
10742 Value::Vector(vec![1.0, 0.0, 0.0, 0.0]),
10743 ]))
10744 .unwrap();
10745 t.add_nsw_index("by_v".into(), "v", NSW_DEFAULT_M).unwrap();
10746 let err = t
10747 .register_cold_locators(
10748 "by_v",
10749 vec![(
10750 IndexKey::Int(1),
10751 RowLocator::Cold {
10752 segment_id: 0,
10753 page_offset: 0,
10754 },
10755 )],
10756 )
10757 .unwrap_err();
10758 // v6.7.1: message switched from "is NSW" to "is not BTree"
10759 // when the Brin variant was added.
10760 assert!(matches!(err, StorageError::Corrupt(ref s) if s.contains("not BTree")));
10761 }
10762
10763 #[test]
10764 fn load_segment_bytes_rejects_garbage() {
10765 let mut cat = Catalog::new();
10766 let err = cat.load_segment_bytes(vec![0u8; 10]).unwrap_err();
10767 assert!(matches!(err, StorageError::Corrupt(ref s) if s.contains("segment")));
10768 // Loader doesn't mutate state on error.
10769 assert_eq!(cat.cold_segment_count(), 0);
10770 }
10771
10772 #[test]
10773 fn load_segment_bytes_returns_sequential_ids() {
10774 let mut cat = Catalog::new();
10775 cat.create_table(bigint_pk_users_schema()).unwrap();
10776 let schema = cat.get("users").unwrap().schema.clone();
10777 for batch in 0u32..3 {
10778 let rows: Vec<(u64, Vec<u8>)> = (0u64..4)
10779 .map(|i| {
10780 let id = u64::from(batch) * 100 + i;
10781 let row = make_user_row(id.cast_signed(), "x");
10782 (id, encode_row_body_dense(&row, &schema))
10783 })
10784 .collect();
10785 let (bytes, _) = encode_segment(rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES).unwrap();
10786 assert_eq!(cat.load_segment_bytes(bytes).unwrap(), batch);
10787 }
10788 assert_eq!(cat.cold_segment_count(), 3);
10789 }
10790
10791 // --- v5.2 catalog format v9 ----------------------------------
10792
10793 /// Hand-craft a v8 catalog byte stream and confirm the v9 reader
10794 /// accepts it and surfaces every `BTree` entry as a Hot locator.
10795 /// Guards the backward-compat read path: existing v3.0.2 / v4.x
10796 /// snapshots on disk must keep loading after the v5.2 bump.
10797 #[test]
10798 fn v8_catalog_decodes_as_all_hot_under_v9_reader() {
10799 // Build a populated catalog in memory, snapshot it with the
10800 // v9 serializer, then patch the version byte back to 8 and
10801 // strip the v9 BTree payload bytes so the layout matches what
10802 // a real v8 snapshot would have produced on disk. The v9
10803 // reader's version dispatch path then rebuilds the index
10804 // from rows (every locator becomes Hot).
10805 let mut cat = populated_users();
10806 cat.get_mut("users")
10807 .unwrap()
10808 .add_index("by_name".into(), "name")
10809 .unwrap();
10810
10811 // To produce a faithful v8 byte stream we re-encode the same
10812 // catalog with the v8 layout: identical bytes up to (and
10813 // including) the per-index kind tag, but no inline BTree
10814 // entries.
10815 let v8_bytes = encode_as_v8(&cat);
10816 assert_eq!(v8_bytes[FILE_MAGIC.len()], 8, "version byte must be 8");
10817
10818 let restored = Catalog::deserialize(&v8_bytes).expect("v9 reader accepts v8 stream");
10819 let idx = restored
10820 .get("users")
10821 .unwrap()
10822 .index_on(1)
10823 .expect("index_on(1) after restore");
10824 // v8 path always materialises Hot locators (no cold tier
10825 // existed pre-v5.2).
10826 assert_eq!(
10827 idx.lookup_eq(&IndexKey::Text("alice".into())),
10828 &[RowLocator::Hot(0), RowLocator::Hot(2)]
10829 );
10830 // No accidental Cold leak.
10831 for entry in idx.lookup_eq(&IndexKey::Text("alice".into())) {
10832 assert!(entry.is_hot(), "v8 → v9 read must yield Hot only");
10833 }
10834 }
10835
10836 /// Encode `cat` using the v8 layout (no inline `BTree` entries,
10837 /// version byte = 8). Pure test helper — duplicates just enough
10838 /// of `Catalog::serialize` to produce a faithful v8 stream that
10839 /// real v3.0.2 / v4.x deployments wrote.
10840 fn encode_as_v8(cat: &Catalog) -> Vec<u8> {
10841 let mut out = Vec::with_capacity(64);
10842 out.extend_from_slice(FILE_MAGIC);
10843 out.push(8u8);
10844 write_u32(&mut out, u32::try_from(cat.tables.len()).unwrap());
10845 for t in &cat.tables {
10846 write_str(&mut out, &t.schema.name);
10847 write_u16(&mut out, u16::try_from(t.schema.columns.len()).unwrap());
10848 for c in &t.schema.columns {
10849 write_str(&mut out, &c.name);
10850 write_data_type(&mut out, c.ty);
10851 out.push(u8::from(c.nullable));
10852 match &c.default {
10853 None => out.push(0),
10854 Some(v) => {
10855 out.push(1);
10856 write_value(&mut out, v);
10857 }
10858 }
10859 out.push(u8::from(c.auto_increment));
10860 }
10861 write_u32(&mut out, u32::try_from(t.rows.len()).unwrap());
10862 for row in &t.rows {
10863 out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
10864 }
10865 write_u16(&mut out, u16::try_from(t.indices.len()).unwrap());
10866 for idx in &t.indices {
10867 write_str(&mut out, &idx.name);
10868 write_u16(&mut out, u16::try_from(idx.column_position).unwrap());
10869 match &idx.kind {
10870 // v8 BTree wrote only the kind tag; entries
10871 // rebuild from rows on read.
10872 IndexKind::BTree(_) => out.push(0),
10873 IndexKind::Nsw(g) => {
10874 out.push(1);
10875 write_u16(&mut out, u16::try_from(g.m).unwrap());
10876 write_nsw_graph(&mut out, g);
10877 }
10878 // v8 had no BRIN / GIN; this test-only writer
10879 // can't serialise either into the legacy format.
10880 IndexKind::Brin { .. } => panic!(
10881 "v8 catalog writer cannot serialise BRIN — \
10882 tests with BRIN indices must use the current writer"
10883 ),
10884 IndexKind::Gin(_) => panic!(
10885 "v8 catalog writer cannot serialise GIN — \
10886 tests with GIN indices must use the current writer"
10887 ),
10888 IndexKind::GinTrgm(_) => panic!(
10889 "v8 catalog writer cannot serialise trigram-GIN — \
10890 tests with trgm indices must use the current writer"
10891 ),
10892 IndexKind::GinFulltext(_) => panic!(
10893 "v8 catalog writer cannot serialise fulltext-GIN — \
10894 tests with FULLTEXT KEY must use the current writer"
10895 ),
10896 }
10897 }
10898 }
10899 out
10900 }
10901
10902 /// Build a catalog that carries both hot and cold locators on a
10903 /// `BTree` index, snapshot it through `serialize`, then deserialise
10904 /// and confirm every Cold locator round-trips byte-identical and
10905 /// `lookup_by_pk` resolves through the rebuilt cold-segment
10906 /// registry.
10907 #[test]
10908 fn v9_catalog_round_trip_preserves_cold_locators() {
10909 let mut cat = Catalog::new();
10910 cat.create_table(bigint_pk_users_schema()).unwrap();
10911 let t = cat.get_mut("users").unwrap();
10912 // Hot rows: 1, 2
10913 for (id, name) in [(1i64, "alice"), (2, "bob")] {
10914 t.insert(make_user_row(id, name)).unwrap();
10915 }
10916 t.add_index("by_id".into(), "id").unwrap();
10917 let schema = t.schema.clone();
10918
10919 // Cold rows: 100, 200, 300 — sit in a single segment.
10920 let cold_rows: Vec<(i64, &str)> = vec![(100, "ivy"), (200, "joe"), (300, "kim")];
10921 let seg_rows: Vec<(u64, Vec<u8>)> = cold_rows
10922 .iter()
10923 .map(|(id, name)| {
10924 let row = make_user_row(*id, name);
10925 ((*id).cast_unsigned(), encode_row_body_dense(&row, &schema))
10926 })
10927 .collect();
10928 let (seg_bytes, _) =
10929 encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES).unwrap();
10930 let seg_id = cat.load_segment_bytes(seg_bytes.clone()).unwrap();
10931 let pairs: Vec<(IndexKey, RowLocator)> = cold_rows
10932 .iter()
10933 .map(|(id, _)| {
10934 (
10935 IndexKey::Int(*id),
10936 RowLocator::Cold {
10937 segment_id: seg_id,
10938 page_offset: 0,
10939 },
10940 )
10941 })
10942 .collect();
10943 cat.get_mut("users")
10944 .unwrap()
10945 .register_cold_locators("by_id", pairs)
10946 .unwrap();
10947
10948 // Snapshot + restore via the v9 codec.
10949 let bytes = cat.serialize();
10950 assert_eq!(bytes[FILE_MAGIC.len()], FILE_VERSION);
10951 let mut restored = Catalog::deserialize(&bytes).expect("v9 round-trip parses");
10952
10953 // Catalog::serialize does not yet emit cold segment file
10954 // bytes (v5.3 manifest is the future home for that). For
10955 // this v9 test the caller side-loads the segment again so
10956 // lookup_by_pk can resolve the Cold locator. The point of
10957 // this assertion is that the locator metadata survived the
10958 // catalog round-trip.
10959 let restored_seg_id = restored.load_segment_bytes(seg_bytes).unwrap();
10960 assert_eq!(restored_seg_id, seg_id);
10961
10962 let idx = restored.get("users").unwrap().index_on(0).unwrap();
10963 // Hot locators round-trip.
10964 assert_eq!(idx.lookup_eq(&IndexKey::Int(1)), &[RowLocator::Hot(0)]);
10965 assert_eq!(idx.lookup_eq(&IndexKey::Int(2)), &[RowLocator::Hot(1)]);
10966 // Cold locators round-trip byte-identical.
10967 for (id, _) in &cold_rows {
10968 assert_eq!(
10969 idx.lookup_eq(&IndexKey::Int(*id)),
10970 &[RowLocator::Cold {
10971 segment_id: seg_id,
10972 page_offset: 0,
10973 }]
10974 );
10975 }
10976 // End-to-end: lookup_by_pk resolves both tiers.
10977 assert_eq!(
10978 restored
10979 .lookup_by_pk("users", "by_id", &IndexKey::Int(2))
10980 .unwrap(),
10981 make_user_row(2, "bob")
10982 );
10983 for (id, name) in &cold_rows {
10984 assert_eq!(
10985 restored
10986 .lookup_by_pk("users", "by_id", &IndexKey::Int(*id))
10987 .unwrap(),
10988 make_user_row(*id, name)
10989 );
10990 }
10991 }
10992
10993 // --- v5.2.1 hot tier byte tracking ---------------------------
10994
10995 /// `row_body_encoded_len` is the perf-critical fast path; pin it
10996 /// against `encode_row_body_dense(...).len()` for every
10997 /// representative cell type so an encoder change can't silently
10998 /// desync the counter.
10999 #[test]
11000 fn row_body_encoded_len_matches_actual_encode_for_all_types() {
11001 let schema = TableSchema::new(
11002 "wide",
11003 vec![
11004 ColumnSchema::new("a", DataType::SmallInt, true),
11005 ColumnSchema::new("b", DataType::Int, false),
11006 ColumnSchema::new("c", DataType::BigInt, false),
11007 ColumnSchema::new("d", DataType::Float, false),
11008 ColumnSchema::new("e", DataType::Bool, false),
11009 ColumnSchema::new("f", DataType::Text, false),
11010 ColumnSchema::new(
11011 "g",
11012 DataType::Vector {
11013 dim: 3,
11014 encoding: VecEncoding::F32,
11015 },
11016 false,
11017 ),
11018 ColumnSchema::new(
11019 "h",
11020 DataType::Numeric {
11021 precision: 18,
11022 scale: 2,
11023 },
11024 false,
11025 ),
11026 ColumnSchema::new("i", DataType::Date, false),
11027 ColumnSchema::new("j", DataType::Timestamp, false),
11028 ],
11029 );
11030 let cases: &[Row] = &[
11031 Row::new(vec![
11032 Value::SmallInt(7),
11033 Value::Int(42),
11034 Value::BigInt(1_000_000),
11035 Value::Float(1.5),
11036 Value::Bool(true),
11037 Value::Text("hello".into()),
11038 Value::Vector(vec![1.0, 2.0, 3.0]),
11039 Value::Numeric {
11040 scaled: 12345,
11041 scale: 2,
11042 },
11043 Value::Date(20_000),
11044 Value::Timestamp(1_700_000_000_000_000),
11045 ]),
11046 // NULL in the bitmap, varied text length.
11047 Row::new(vec![
11048 Value::Null,
11049 Value::Int(0),
11050 Value::BigInt(0),
11051 Value::Float(0.0),
11052 Value::Bool(false),
11053 Value::Text(String::new()),
11054 Value::Vector(vec![]),
11055 Value::Numeric {
11056 scaled: 0,
11057 scale: 2,
11058 },
11059 Value::Date(0),
11060 Value::Timestamp(0),
11061 ]),
11062 Row::new(vec![
11063 Value::SmallInt(-1),
11064 Value::Int(-1),
11065 Value::BigInt(-1),
11066 Value::Float(-0.5),
11067 Value::Bool(true),
11068 Value::Text("a much longer payload here".into()),
11069 Value::Vector(vec![0.1, 0.2, 0.3]),
11070 Value::Numeric {
11071 scaled: -999_999_999,
11072 scale: 2,
11073 },
11074 Value::Date(-1),
11075 Value::Timestamp(-1),
11076 ]),
11077 ];
11078 for row in cases {
11079 let actual = encode_row_body_dense(row, &schema).len();
11080 let fast = row_body_encoded_len(row, &schema);
11081 assert_eq!(actual, fast, "row {row:?}");
11082 }
11083 }
11084
11085 #[test]
11086 fn hot_bytes_grows_on_insert_and_matches_encoded_sum() {
11087 let mut cat = Catalog::new();
11088 cat.create_table(bigint_pk_users_schema()).unwrap();
11089 let t = cat.get_mut("users").unwrap();
11090 assert_eq!(t.hot_bytes(), 0);
11091 let mut expected: u64 = 0;
11092 for (id, name) in [(1i64, "alice"), (2, "bob"), (3, "carol")] {
11093 let row = make_user_row(id, name);
11094 expected += encode_row_body_dense(&row, &t.schema).len() as u64;
11095 t.insert(row).unwrap();
11096 }
11097 assert_eq!(t.hot_bytes(), expected);
11098 assert_eq!(cat.hot_tier_bytes(), expected);
11099 }
11100
11101 #[test]
11102 fn hot_bytes_shrinks_on_delete() {
11103 let mut cat = Catalog::new();
11104 cat.create_table(bigint_pk_users_schema()).unwrap();
11105 let t = cat.get_mut("users").unwrap();
11106 for (id, name) in [(1i64, "alice"), (2, "bob"), (3, "carol")] {
11107 t.insert(make_user_row(id, name)).unwrap();
11108 }
11109 let before = t.hot_bytes();
11110 // Delete row at position 1 (bob).
11111 let bob_row = make_user_row(2, "bob");
11112 let bob_bytes = encode_row_body_dense(&bob_row, &t.schema).len() as u64;
11113 let removed = t.delete_rows(&[1]);
11114 assert_eq!(removed, 1);
11115 assert_eq!(t.hot_bytes(), before - bob_bytes);
11116 }
11117
11118 #[test]
11119 fn hot_bytes_diffs_on_update_for_variable_width_columns() {
11120 let mut cat = Catalog::new();
11121 cat.create_table(bigint_pk_users_schema()).unwrap();
11122 let t = cat.get_mut("users").unwrap();
11123 t.insert(make_user_row(1, "alice")).unwrap();
11124 let after_insert = t.hot_bytes();
11125 // Update with a longer text payload — bytes must grow exactly
11126 // by the text-length delta.
11127 let new_row = make_user_row(1, "alice-the-longer-name");
11128 let old_len = encode_row_body_dense(&make_user_row(1, "alice"), &t.schema).len() as u64;
11129 let new_len = encode_row_body_dense(&new_row, &t.schema).len() as u64;
11130 t.update_row(0, new_row.values).unwrap();
11131 assert_eq!(t.hot_bytes(), after_insert - old_len + new_len);
11132 assert!(t.hot_bytes() > after_insert, "longer text grew the counter");
11133 }
11134
11135 #[test]
11136 fn hot_bytes_round_trips_through_serialize_deserialize() {
11137 let mut cat = Catalog::new();
11138 cat.create_table(bigint_pk_users_schema()).unwrap();
11139 let t = cat.get_mut("users").unwrap();
11140 for i in 0..10 {
11141 t.insert(make_user_row(i, &alloc::format!("name-{i}")))
11142 .unwrap();
11143 }
11144 let pre = cat.hot_tier_bytes();
11145 let restored = Catalog::deserialize(&cat.serialize()).unwrap();
11146 assert_eq!(restored.hot_tier_bytes(), pre);
11147 assert_eq!(restored.get("users").unwrap().hot_bytes(), pre);
11148 }
11149
11150 // --- v5.2.2 freezer atomic swap -------------------------------
11151
11152 /// Happy path: freeze the first half of a populated hot tier,
11153 /// confirm row counts shift, `hot_bytes` shrinks, and every frozen
11154 /// PK still resolves via `lookup_by_pk` (now through the cold
11155 /// segment registered by the freeze).
11156 #[test]
11157 fn freeze_oldest_to_cold_moves_rows_and_keeps_lookups_working() {
11158 let mut cat = Catalog::new();
11159 cat.create_table(bigint_pk_users_schema()).unwrap();
11160 let t = cat.get_mut("users").unwrap();
11161 for id in 0..10i64 {
11162 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11163 .unwrap();
11164 }
11165 t.add_index("by_id".into(), "id").unwrap();
11166 let total_bytes_before = t.hot_bytes();
11167
11168 let report = cat
11169 .freeze_oldest_to_cold("users", "by_id", 6)
11170 .expect("freeze succeeds");
11171 assert_eq!(report.frozen_rows, 6);
11172 assert_eq!(report.segment_id, 0);
11173 assert!(report.bytes_freed > 0);
11174 assert!(!report.segment_bytes.is_empty());
11175
11176 let t = cat.get("users").unwrap();
11177 assert_eq!(t.row_count(), 4, "4 hot rows remain (10 - 6 frozen)");
11178 assert_eq!(cat.cold_segment_count(), 1);
11179 // Hot bytes shrank by exactly the freed amount.
11180 assert_eq!(
11181 t.hot_bytes(),
11182 total_bytes_before - report.bytes_freed,
11183 "hot_bytes accounting matches FreezeReport"
11184 );
11185
11186 // Every original PK still resolves — frozen ones via the
11187 // cold segment, kept ones via the (renumbered) hot tier.
11188 for id in 0..10i64 {
11189 let got = cat
11190 .lookup_by_pk("users", "by_id", &IndexKey::Int(id))
11191 .unwrap_or_else(|| panic!("PK {id} disappeared after freeze"));
11192 assert_eq!(got, make_user_row(id, &alloc::format!("u-{id}")));
11193 }
11194 }
11195
11196 /// Two successive freezes on the same index must preserve the
11197 /// first batch's cold locators when the second freeze runs.
11198 /// Catches the `rebuild_indices` wipe-Cold-on-delete bug that
11199 /// `collect_cold_locators` / re-register guards against.
11200 #[test]
11201 fn freeze_twice_preserves_prior_cold_locators() {
11202 let mut cat = Catalog::new();
11203 cat.create_table(bigint_pk_users_schema()).unwrap();
11204 let t = cat.get_mut("users").unwrap();
11205 for id in 0..12i64 {
11206 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11207 .unwrap();
11208 }
11209 t.add_index("by_id".into(), "id").unwrap();
11210
11211 cat.freeze_oldest_to_cold("users", "by_id", 4)
11212 .expect("first freeze ok");
11213 cat.freeze_oldest_to_cold("users", "by_id", 4)
11214 .expect("second freeze ok");
11215
11216 assert_eq!(cat.get("users").unwrap().row_count(), 4);
11217 assert_eq!(cat.cold_segment_count(), 2);
11218 // All 12 PKs still resolve — first 4 via segment 0,
11219 // next 4 via segment 1, last 4 still hot.
11220 for id in 0..12i64 {
11221 let got = cat
11222 .lookup_by_pk("users", "by_id", &IndexKey::Int(id))
11223 .unwrap_or_else(|| panic!("PK {id} not resolvable after two freezes"));
11224 assert_eq!(got, make_user_row(id, &alloc::format!("u-{id}")));
11225 }
11226 }
11227
11228 /// Validation guard tests. Each must return `Err` and **not
11229 /// mutate the catalog** — the API is all-or-nothing.
11230 #[test]
11231 fn freeze_oldest_to_cold_rejects_invalid_input() {
11232 let mut cat = Catalog::new();
11233 cat.create_table(bigint_pk_users_schema()).unwrap();
11234 let t = cat.get_mut("users").unwrap();
11235 for id in 0..3i64 {
11236 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11237 .unwrap();
11238 }
11239 t.add_index("by_id".into(), "id").unwrap();
11240
11241 // max_rows == 0
11242 assert!(matches!(
11243 cat.freeze_oldest_to_cold("users", "by_id", 0),
11244 Err(StorageError::Corrupt(_))
11245 ));
11246 // table missing
11247 assert!(matches!(
11248 cat.freeze_oldest_to_cold("missing", "by_id", 1),
11249 Err(StorageError::Corrupt(_))
11250 ));
11251 // index missing
11252 assert!(matches!(
11253 cat.freeze_oldest_to_cold("users", "no_such_index", 1),
11254 Err(StorageError::Corrupt(_))
11255 ));
11256 // max_rows > row_count
11257 assert!(matches!(
11258 cat.freeze_oldest_to_cold("users", "by_id", 999),
11259 Err(StorageError::Corrupt(_))
11260 ));
11261 // Catalog still untouched.
11262 assert_eq!(cat.get("users").unwrap().row_count(), 3);
11263 assert_eq!(cat.cold_segment_count(), 0);
11264 }
11265
11266 /// Freeze with a non-integer PK column must surface a clear
11267 /// error (Text PKs land in v5.5+).
11268 #[test]
11269 fn freeze_oldest_to_cold_rejects_non_integer_pk() {
11270 let mut cat = Catalog::new();
11271 cat.create_table(TableSchema::new(
11272 "by_name",
11273 vec![
11274 ColumnSchema::new("name", DataType::Text, false),
11275 ColumnSchema::new("payload", DataType::BigInt, false),
11276 ],
11277 ))
11278 .unwrap();
11279 let t = cat.get_mut("by_name").unwrap();
11280 t.insert(Row::new(vec![Value::Text("a".into()), Value::BigInt(1)]))
11281 .unwrap();
11282 t.add_index("by_n".into(), "name").unwrap();
11283 let err = cat
11284 .freeze_oldest_to_cold("by_name", "by_n", 1)
11285 .expect_err("non-integer PK rejected");
11286 match err {
11287 StorageError::Corrupt(s) => assert!(
11288 s.contains("non-integer"),
11289 "error message names the constraint: {s}"
11290 ),
11291 other => panic!("expected Corrupt, got {other:?}"),
11292 }
11293 // Catalog untouched.
11294 assert_eq!(cat.get("by_name").unwrap().row_count(), 1);
11295 assert_eq!(cat.cold_segment_count(), 0);
11296 }
11297
11298 /// Hot-tier rows after the freeze must keep their secondary-
11299 /// index lookups working — `delete_rows` shifts positions, and
11300 /// `rebuild_indices` must regenerate Hot locators at the new
11301 /// indices.
11302 #[test]
11303 fn freeze_keeps_remaining_hot_rows_addressable_via_secondary_index() {
11304 let mut cat = Catalog::new();
11305 cat.create_table(bigint_pk_users_schema()).unwrap();
11306 let t = cat.get_mut("users").unwrap();
11307 for id in 0..6i64 {
11308 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11309 .unwrap();
11310 }
11311 t.add_index("by_id".into(), "id").unwrap();
11312 t.add_index("by_name".into(), "name").unwrap();
11313
11314 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11315
11316 // Remaining hot rows: id 3, 4, 5. They moved to positions
11317 // 0, 1, 2 inside `self.rows`; the `by_name` index must now
11318 // resolve them via fresh Hot locators.
11319 let idx = cat.get("users").unwrap().index_on(1).unwrap();
11320 let got = idx.lookup_eq(&IndexKey::Text("u-4".into()));
11321 assert_eq!(got.len(), 1);
11322 assert!(got[0].is_hot(), "kept-hot rows still surface as Hot");
11323 match got[0] {
11324 RowLocator::Hot(i) => {
11325 // The 4th-inserted row was at position 4; after
11326 // dropping positions 0..3 it sits at position 1.
11327 assert_eq!(i, 1);
11328 }
11329 RowLocator::Cold { .. } => unreachable!(),
11330 }
11331 }
11332
11333 // --- v5.2.3 promote-on-write primitives ----------------------
11334
11335 /// Build a populated catalog with the first N rows frozen, then
11336 /// run `promote_cold_row` and verify the row crossed tiers
11337 /// correctly: the cold locator is retired, a fresh Hot locator
11338 /// appears, `lookup_by_pk` returns the row from the hot tier, and
11339 /// `hot_bytes` grew by the row's encoded byte length.
11340 #[test]
11341 fn promote_cold_row_pulls_frozen_row_back_to_hot_tier() {
11342 let mut cat = Catalog::new();
11343 cat.create_table(bigint_pk_users_schema()).unwrap();
11344 let t = cat.get_mut("users").unwrap();
11345 for id in 0..6i64 {
11346 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11347 .unwrap();
11348 }
11349 t.add_index("by_id".into(), "id").unwrap();
11350 // Freeze first 4 rows (ids 0..3). After: hot rows = 4, 5 at
11351 // positions 0, 1; cold locators for keys 0..3.
11352 cat.freeze_oldest_to_cold("users", "by_id", 4).unwrap();
11353 let hot_bytes_before = cat.get("users").unwrap().hot_bytes();
11354
11355 // Promote PK=2 — it lives in segment 0 as a cold row.
11356 let new_idx = cat
11357 .promote_cold_row("users", "by_id", &IndexKey::Int(2))
11358 .expect("promote ok")
11359 .expect("PK 2 was cold");
11360 assert_eq!(
11361 new_idx, 2,
11362 "promoted row appended after the 2 surviving hot rows"
11363 );
11364
11365 let t = cat.get("users").unwrap();
11366 assert_eq!(t.row_count(), 3, "hot tier grew from 2 to 3");
11367 // Hot-bytes climbed by exactly one row's encoded length.
11368 let row = make_user_row(2, "u-2");
11369 let row_len = encode_row_body_dense(&row, &t.schema).len() as u64;
11370 assert_eq!(t.hot_bytes(), hot_bytes_before + row_len);
11371
11372 // The index now reports a Hot locator (the freshly inserted
11373 // row) — no Cold locator left for PK 2.
11374 let entries = t.index_on(0).unwrap().lookup_eq(&IndexKey::Int(2));
11375 assert_eq!(entries.len(), 1, "exactly one locator per key");
11376 assert!(entries[0].is_hot(), "promote retired the Cold locator");
11377 // End-to-end: lookup_by_pk still returns the row body.
11378 assert_eq!(
11379 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(2))
11380 .unwrap(),
11381 row
11382 );
11383 // Other cold rows untouched — still resolvable through the
11384 // segment.
11385 assert_eq!(
11386 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(0))
11387 .unwrap(),
11388 make_user_row(0, "u-0")
11389 );
11390 }
11391
11392 /// `promote_cold_row` on a key that's already hot (or absent)
11393 /// returns `Ok(None)` — not an error. The caller falls back to
11394 /// the hot-only update/delete path.
11395 #[test]
11396 fn promote_cold_row_returns_none_when_key_is_not_cold() {
11397 let mut cat = Catalog::new();
11398 cat.create_table(bigint_pk_users_schema()).unwrap();
11399 let t = cat.get_mut("users").unwrap();
11400 t.insert(make_user_row(7, "alice")).unwrap();
11401 t.add_index("by_id".into(), "id").unwrap();
11402
11403 // Hot-only key.
11404 assert!(
11405 cat.promote_cold_row("users", "by_id", &IndexKey::Int(7))
11406 .unwrap()
11407 .is_none()
11408 );
11409 // Absent key.
11410 assert!(
11411 cat.promote_cold_row("users", "by_id", &IndexKey::Int(99))
11412 .unwrap()
11413 .is_none()
11414 );
11415 // Catalog untouched on both no-op paths.
11416 assert_eq!(cat.get("users").unwrap().row_count(), 1);
11417 assert_eq!(cat.cold_segment_count(), 0);
11418 }
11419
11420 /// `shadow_cold_row` removes every Cold locator for a key on a
11421 /// `BTree` index. After the shadow, `lookup_by_pk` for that key
11422 /// returns None (the row data still sits in the segment file,
11423 /// but it's now garbage; compaction will reclaim it later).
11424 #[test]
11425 fn shadow_cold_row_removes_cold_locators_and_drops_lookup() {
11426 let mut cat = Catalog::new();
11427 cat.create_table(bigint_pk_users_schema()).unwrap();
11428 let t = cat.get_mut("users").unwrap();
11429 for id in 0..5i64 {
11430 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11431 .unwrap();
11432 }
11433 t.add_index("by_id".into(), "id").unwrap();
11434 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11435
11436 // Shadow PK=1 — pre-shadow lookup hits the cold tier.
11437 assert!(
11438 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(1))
11439 .is_some(),
11440 "frozen PK resolves before shadow"
11441 );
11442 let removed = cat
11443 .shadow_cold_row("users", "by_id", &IndexKey::Int(1))
11444 .unwrap();
11445 assert_eq!(removed, 1, "exactly one cold locator retired");
11446
11447 // Post-shadow: lookup misses, even though the row still
11448 // exists in segment 0.
11449 assert!(
11450 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(1))
11451 .is_none(),
11452 "shadowed key no longer resolves"
11453 );
11454 // Other cold keys still resolve.
11455 assert_eq!(
11456 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(0))
11457 .unwrap(),
11458 make_user_row(0, "u-0")
11459 );
11460 assert_eq!(
11461 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(2))
11462 .unwrap(),
11463 make_user_row(2, "u-2")
11464 );
11465 }
11466
11467 /// `shadow_cold_row` returns 0 (not Err) for keys with only Hot
11468 /// entries or no entries — the engine's DELETE path uses this
11469 /// signal to decide whether the cold-tier shadow path consumed
11470 /// the work.
11471 #[test]
11472 fn shadow_cold_row_returns_zero_when_key_is_not_cold() {
11473 let mut cat = Catalog::new();
11474 cat.create_table(bigint_pk_users_schema()).unwrap();
11475 let t = cat.get_mut("users").unwrap();
11476 t.insert(make_user_row(1, "alice")).unwrap();
11477 t.add_index("by_id".into(), "id").unwrap();
11478 assert_eq!(
11479 cat.shadow_cold_row("users", "by_id", &IndexKey::Int(1))
11480 .unwrap(),
11481 0,
11482 "hot-only key drops no cold locators"
11483 );
11484 assert_eq!(
11485 cat.shadow_cold_row("users", "by_id", &IndexKey::Int(999))
11486 .unwrap(),
11487 0,
11488 "absent key drops no cold locators"
11489 );
11490 assert_eq!(cat.get("users").unwrap().row_count(), 1);
11491 }
11492
11493 /// Validation guards on both promote / shadow primitives.
11494 #[test]
11495 fn promote_and_shadow_reject_invalid_inputs() {
11496 let mut cat = Catalog::new();
11497 cat.create_table(bigint_pk_users_schema()).unwrap();
11498 let t = cat.get_mut("users").unwrap();
11499 t.insert(make_user_row(1, "alice")).unwrap();
11500 t.add_index("by_id".into(), "id").unwrap();
11501
11502 // Missing table.
11503 assert!(matches!(
11504 cat.promote_cold_row("missing", "by_id", &IndexKey::Int(1)),
11505 Err(StorageError::Corrupt(_))
11506 ));
11507 assert!(matches!(
11508 cat.shadow_cold_row("missing", "by_id", &IndexKey::Int(1)),
11509 Err(StorageError::Corrupt(_))
11510 ));
11511 // Missing index.
11512 assert!(matches!(
11513 cat.promote_cold_row("users", "no_such_index", &IndexKey::Int(1)),
11514 Err(StorageError::Corrupt(_))
11515 ));
11516 assert!(matches!(
11517 cat.shadow_cold_row("users", "no_such_index", &IndexKey::Int(1)),
11518 Err(StorageError::Corrupt(_))
11519 ));
11520 }
11521
11522 // --- v6.7.4 parallel-freezer slice/commit API -----------------
11523
11524 /// One slice covering the entire freeze produces the same
11525 /// catalog state as the single-threaded `freeze_oldest_to_cold`
11526 /// — segment id, frozen row count, hot byte delta, and every
11527 /// post-freeze PK lookup match exactly.
11528 #[test]
11529 fn commit_freeze_slices_single_slice_matches_freeze_oldest() {
11530 let mut a = Catalog::new();
11531 let mut b = Catalog::new();
11532 for cat in [&mut a, &mut b] {
11533 cat.create_table(bigint_pk_users_schema()).unwrap();
11534 let t = cat.get_mut("users").unwrap();
11535 for id in 0..10i64 {
11536 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11537 .unwrap();
11538 }
11539 t.add_index("by_id".into(), "id").unwrap();
11540 }
11541 let single = a.freeze_oldest_to_cold("users", "by_id", 6).unwrap();
11542 let slice = b
11543 .prepare_freeze_slice("users", "by_id", 0..6)
11544 .expect("prepare");
11545 let parallel = b
11546 .commit_freeze_slices("users", "by_id", alloc::vec![slice])
11547 .expect("commit");
11548 assert_eq!(single.segment_id, parallel.segment_id);
11549 assert_eq!(single.frozen_rows, parallel.frozen_rows);
11550 assert_eq!(single.bytes_freed, parallel.bytes_freed);
11551 assert_eq!(single.segment_bytes, parallel.segment_bytes);
11552 // Same post-freeze lookup behaviour on both catalogs.
11553 for id in 0..10i64 {
11554 assert_eq!(
11555 a.lookup_by_pk("users", "by_id", &IndexKey::Int(id)),
11556 b.lookup_by_pk("users", "by_id", &IndexKey::Int(id)),
11557 "PK {id} differs after single vs slice freeze"
11558 );
11559 }
11560 }
11561
11562 /// Two slices covering disjoint halves of the freeze produce
11563 /// the same merged segment as one slice covering the full
11564 /// range. The k-way merge preserves PK ordering even when
11565 /// slice halves alternate.
11566 #[test]
11567 fn commit_freeze_slices_two_slices_match_single_slice() {
11568 let mut a = Catalog::new();
11569 let mut b = Catalog::new();
11570 for cat in [&mut a, &mut b] {
11571 cat.create_table(bigint_pk_users_schema()).unwrap();
11572 let t = cat.get_mut("users").unwrap();
11573 // Random-ish PKs so the per-slice sort actually has
11574 // work to do (and slice halves carry interleaved keys).
11575 for id in [3, 7, 1, 9, 5, 0, 8, 4, 2, 6].iter().copied() {
11576 t.insert(make_user_row(id as i64, &alloc::format!("u-{id}")))
11577 .unwrap();
11578 }
11579 t.add_index("by_id".into(), "id").unwrap();
11580 }
11581 let single = a
11582 .prepare_freeze_slice("users", "by_id", 0..8)
11583 .expect("prepare");
11584 let one = a
11585 .commit_freeze_slices("users", "by_id", alloc::vec![single])
11586 .expect("commit one");
11587 let s1 = b
11588 .prepare_freeze_slice("users", "by_id", 0..4)
11589 .expect("prepare s1");
11590 let s2 = b
11591 .prepare_freeze_slice("users", "by_id", 4..8)
11592 .expect("prepare s2");
11593 let two = b
11594 .commit_freeze_slices("users", "by_id", alloc::vec![s1, s2])
11595 .expect("commit two");
11596 assert_eq!(one.segment_bytes, two.segment_bytes);
11597 assert_eq!(one.frozen_rows, two.frozen_rows);
11598 // Every PK that survived freeze (hot or cold) resolves on
11599 // both catalogs.
11600 for id in 0..10i64 {
11601 assert_eq!(
11602 a.lookup_by_pk("users", "by_id", &IndexKey::Int(id)),
11603 b.lookup_by_pk("users", "by_id", &IndexKey::Int(id)),
11604 "PK {id} differs after one-slice vs two-slice freeze"
11605 );
11606 }
11607 }
11608
11609 /// Gap between slices → error before any mutation lands.
11610 #[test]
11611 fn commit_freeze_slices_rejects_gap() {
11612 let mut cat = Catalog::new();
11613 cat.create_table(bigint_pk_users_schema()).unwrap();
11614 let t = cat.get_mut("users").unwrap();
11615 for id in 0..6i64 {
11616 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11617 .unwrap();
11618 }
11619 t.add_index("by_id".into(), "id").unwrap();
11620 let s1 = cat.prepare_freeze_slice("users", "by_id", 0..2).unwrap();
11621 let s2 = cat.prepare_freeze_slice("users", "by_id", 3..5).unwrap();
11622 assert!(matches!(
11623 cat.commit_freeze_slices("users", "by_id", alloc::vec![s1, s2]),
11624 Err(StorageError::Corrupt(_))
11625 ));
11626 // Catalog untouched.
11627 assert_eq!(cat.cold_segment_count(), 0);
11628 assert_eq!(cat.get("users").unwrap().row_count(), 6);
11629 }
11630
11631 /// Empty slice list → no-op success, catalog untouched.
11632 #[test]
11633 fn commit_freeze_slices_empty_is_noop() {
11634 let mut cat = Catalog::new();
11635 cat.create_table(bigint_pk_users_schema()).unwrap();
11636 let t = cat.get_mut("users").unwrap();
11637 for id in 0..3i64 {
11638 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11639 .unwrap();
11640 }
11641 t.add_index("by_id".into(), "id").unwrap();
11642 let report = cat
11643 .commit_freeze_slices("users", "by_id", Vec::new())
11644 .unwrap();
11645 assert_eq!(report.frozen_rows, 0);
11646 assert_eq!(cat.cold_segment_count(), 0);
11647 assert_eq!(cat.get("users").unwrap().row_count(), 3);
11648 }
11649
11650 // --- v6.7.3 cold-segment compaction ---------------------------
11651
11652 /// Two small cold segments merge into a single larger one. The
11653 /// merged segment carries every cold-resident row; the source
11654 /// slots are tombstoned; every PK still resolves through the
11655 /// new merged segment via `lookup_by_pk`.
11656 #[test]
11657 fn compact_merges_small_segments_storage_unit() {
11658 let mut cat = Catalog::new();
11659 cat.create_table(bigint_pk_users_schema()).unwrap();
11660 let t = cat.get_mut("users").unwrap();
11661 for id in 0..8i64 {
11662 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11663 .unwrap();
11664 }
11665 t.add_index("by_id".into(), "id").unwrap();
11666 // Two freezes of 3 rows each → two small cold segments.
11667 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11668 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11669 assert_eq!(cat.cold_segment_count(), 2);
11670 assert_eq!(cat.cold_segment_slot_count(), 2);
11671
11672 // Pick a threshold larger than either segment's size so
11673 // both qualify.
11674 let max_seg_bytes = cat
11675 .cold_segment_ids_global()
11676 .iter()
11677 .map(|id| cat.cold_segment(*id).unwrap().bytes().len() as u64)
11678 .max()
11679 .unwrap();
11680 let target = max_seg_bytes + 1;
11681
11682 let report = cat
11683 .compact_cold_segments("users", "by_id", target)
11684 .expect("compact succeeds");
11685 assert_eq!(report.sources.len(), 2);
11686 let merged_id = report.merged_segment_id.expect("merge happened");
11687 assert_eq!(report.merged_rows, 6);
11688 assert_eq!(report.deleted_rows_pruned, 0);
11689 assert!(!report.merged_segment_bytes.is_empty());
11690
11691 // Active count drops back to 1; slot count grew to 3
11692 // (2 sources tombstoned + 1 merged appended).
11693 assert_eq!(cat.cold_segment_count(), 1);
11694 assert_eq!(cat.cold_segment_slot_count(), 3);
11695 assert_eq!(cat.cold_segment_ids_global(), alloc::vec![merged_id]);
11696
11697 // Every PK that was frozen still resolves (via the merged
11698 // segment); the 2 hot rows still resolve too.
11699 for id in 0..8i64 {
11700 let got = cat
11701 .lookup_by_pk("users", "by_id", &IndexKey::Int(id))
11702 .unwrap_or_else(|| panic!("PK {id} lost after compaction"));
11703 assert_eq!(got, make_user_row(id, &alloc::format!("u-{id}")));
11704 }
11705 }
11706
11707 /// DELETE'd-but-frozen rows are dropped during the merge. Set
11708 /// up two small segments, then shadow one row in each; the
11709 /// merged segment must NOT carry the shadowed rows.
11710 #[test]
11711 fn compact_drops_shadowed_cold_rows() {
11712 let mut cat = Catalog::new();
11713 cat.create_table(bigint_pk_users_schema()).unwrap();
11714 let t = cat.get_mut("users").unwrap();
11715 for id in 0..6i64 {
11716 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11717 .unwrap();
11718 }
11719 t.add_index("by_id".into(), "id").unwrap();
11720 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11721 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11722 // Shadow PK 1 (in seg 0) + PK 4 (in seg 1).
11723 assert_eq!(
11724 cat.shadow_cold_row("users", "by_id", &IndexKey::Int(1))
11725 .unwrap(),
11726 1
11727 );
11728 assert_eq!(
11729 cat.shadow_cold_row("users", "by_id", &IndexKey::Int(4))
11730 .unwrap(),
11731 1
11732 );
11733
11734 let max_seg_bytes = cat
11735 .cold_segment_ids_global()
11736 .iter()
11737 .map(|id| cat.cold_segment(*id).unwrap().bytes().len() as u64)
11738 .max()
11739 .unwrap();
11740 let report = cat
11741 .compact_cold_segments("users", "by_id", max_seg_bytes + 1)
11742 .expect("compact succeeds");
11743 assert_eq!(report.sources.len(), 2);
11744 assert_eq!(report.merged_rows, 4, "6 frozen − 2 shadowed = 4 live");
11745 assert_eq!(report.deleted_rows_pruned, 2);
11746
11747 // PK 1 and 4 stay invisible after compact.
11748 for shadowed in [1i64, 4i64] {
11749 assert!(
11750 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(shadowed))
11751 .is_none(),
11752 "shadowed PK {shadowed} must remain invisible after compact"
11753 );
11754 }
11755 // The other 4 frozen rows resolve.
11756 for live in [0i64, 2, 3, 5] {
11757 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(live))
11758 .unwrap_or_else(|| panic!("live PK {live} lost after compact"));
11759 }
11760 }
11761
11762 /// No-op cases: 0 or 1 candidate segment under the threshold
11763 /// leaves the catalog untouched.
11764 #[test]
11765 fn compact_is_noop_below_two_candidates() {
11766 let mut cat = Catalog::new();
11767 cat.create_table(bigint_pk_users_schema()).unwrap();
11768 let t = cat.get_mut("users").unwrap();
11769 for id in 0..6i64 {
11770 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11771 .unwrap();
11772 }
11773 t.add_index("by_id".into(), "id").unwrap();
11774 // 0 cold segments.
11775 let report = cat
11776 .compact_cold_segments("users", "by_id", 1 << 30)
11777 .expect("noop ok");
11778 assert!(report.merged_segment_id.is_none());
11779 assert!(report.sources.is_empty());
11780
11781 // 1 cold segment — still a no-op (need ≥2 to merge).
11782 cat.freeze_oldest_to_cold("users", "by_id", 4).unwrap();
11783 let report = cat
11784 .compact_cold_segments("users", "by_id", 1 << 30)
11785 .expect("noop ok");
11786 assert!(report.merged_segment_id.is_none());
11787 assert_eq!(cat.cold_segment_count(), 1);
11788
11789 // Threshold too small to cover the single segment → still
11790 // no-op.
11791 let report = cat
11792 .compact_cold_segments("users", "by_id", 1)
11793 .expect("noop ok");
11794 assert!(report.merged_segment_id.is_none());
11795 assert_eq!(cat.cold_segment_count(), 1);
11796 }
11797
11798 /// Manifest-style atomicity: a Catalog snapshot taken AFTER
11799 /// `compact_cold_segments` returns must round-trip with the
11800 /// post-compact BTree state, while the cold-tier registry is
11801 /// re-derived from the source-of-truth manifest (=
11802 /// `load_segment_bytes_at` with the merged id + the still-on-
11803 /// disk merged bytes). This mirrors the boot path: catalog
11804 /// snapshot + cold-segment files = full state.
11805 #[test]
11806 fn compact_swap_survives_catalog_roundtrip_via_load_at() {
11807 let mut cat = Catalog::new();
11808 cat.create_table(bigint_pk_users_schema()).unwrap();
11809 let t = cat.get_mut("users").unwrap();
11810 for id in 0..6i64 {
11811 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11812 .unwrap();
11813 }
11814 t.add_index("by_id".into(), "id").unwrap();
11815 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11816 cat.freeze_oldest_to_cold("users", "by_id", 3).unwrap();
11817 let max_seg_bytes = cat
11818 .cold_segment_ids_global()
11819 .iter()
11820 .map(|id| cat.cold_segment(*id).unwrap().bytes().len() as u64)
11821 .max()
11822 .unwrap();
11823 let report = cat
11824 .compact_cold_segments("users", "by_id", max_seg_bytes + 1)
11825 .expect("compact ok");
11826 let merged_id = report.merged_segment_id.unwrap();
11827
11828 // Serialise the catalog (BTree index points at merged_id
11829 // now) and the merged segment bytes; pretend to crash; on
11830 // restart, re-hydrate the catalog and reload only the
11831 // merged segment at its baked-in id.
11832 let cat_bytes = cat.serialize();
11833 let merged_bytes = report.merged_segment_bytes.clone();
11834
11835 let mut restored = Catalog::deserialize(&cat_bytes).expect("deserialize ok");
11836 restored
11837 .load_segment_bytes_at(merged_id, merged_bytes)
11838 .expect("reload merged ok");
11839
11840 // All 6 PKs still resolve through the restored merged segment.
11841 for id in 0..6i64 {
11842 let got = restored
11843 .lookup_by_pk("users", "by_id", &IndexKey::Int(id))
11844 .unwrap_or_else(|| panic!("PK {id} lost across roundtrip"));
11845 assert_eq!(got, make_user_row(id, &alloc::format!("u-{id}")));
11846 }
11847 // No source slot ever rehydrates — confirmed by
11848 // `cold_segment_count` matching only the merged segment.
11849 assert_eq!(restored.cold_segment_count(), 1);
11850 }
11851
11852 /// `load_segment_bytes_at` refuses to stomp an occupied slot
11853 /// and pads with `None` when the target id is past the end.
11854 #[test]
11855 fn load_segment_bytes_at_pads_and_rejects_collision() {
11856 let mut cat = Catalog::new();
11857 cat.create_table(bigint_pk_users_schema()).unwrap();
11858 let t = cat.get_mut("users").unwrap();
11859 for id in 0..4i64 {
11860 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11861 .unwrap();
11862 }
11863 t.add_index("by_id".into(), "id").unwrap();
11864 let report = cat.freeze_oldest_to_cold("users", "by_id", 2).unwrap();
11865 let bytes_seg0 = report.segment_bytes.clone();
11866
11867 // Pad to id=5 (slots 1..5 are None, slot 5 holds the
11868 // segment loaded back). The slot count jumps, the active
11869 // count is now 2 (seg 0 + seg 5).
11870 cat.load_segment_bytes_at(5, bytes_seg0.clone())
11871 .expect("pad + load ok");
11872 assert_eq!(cat.cold_segment_slot_count(), 6);
11873 assert_eq!(cat.cold_segment_count(), 2);
11874
11875 // Re-loading at the same id collides.
11876 assert!(matches!(
11877 cat.load_segment_bytes_at(5, bytes_seg0.clone()),
11878 Err(StorageError::Corrupt(_))
11879 ));
11880 // Re-loading at id 0 (already occupied) also collides.
11881 assert!(matches!(
11882 cat.load_segment_bytes_at(0, bytes_seg0),
11883 Err(StorageError::Corrupt(_))
11884 ));
11885 }
11886
11887 /// Round trip: freeze → promote → re-freeze. The same PK can
11888 /// migrate hot ↔ cold multiple times. After two cycles only the
11889 /// final Hot locator should be live.
11890 #[test]
11891 fn promote_then_refreeze_does_not_leave_orphan_locators() {
11892 let mut cat = Catalog::new();
11893 cat.create_table(bigint_pk_users_schema()).unwrap();
11894 let t = cat.get_mut("users").unwrap();
11895 for id in 0..4i64 {
11896 t.insert(make_user_row(id, &alloc::format!("u-{id}")))
11897 .unwrap();
11898 }
11899 t.add_index("by_id".into(), "id").unwrap();
11900
11901 // Cycle 1: freeze first 2 rows, then promote PK 0.
11902 cat.freeze_oldest_to_cold("users", "by_id", 2).unwrap();
11903 let promoted = cat
11904 .promote_cold_row("users", "by_id", &IndexKey::Int(0))
11905 .unwrap();
11906 assert!(promoted.is_some());
11907 let entries_after_promote = cat
11908 .get("users")
11909 .unwrap()
11910 .index_on(0)
11911 .unwrap()
11912 .lookup_eq(&IndexKey::Int(0))
11913 .to_vec();
11914 assert_eq!(entries_after_promote.len(), 1);
11915 assert!(entries_after_promote[0].is_hot());
11916
11917 // Cycle 2: freeze the front rows again. PK 0 is now at
11918 // position 2 (after the survivors); it could still go cold
11919 // again on a future freeze depending on policy, but the
11920 // current "first N positions" policy leaves it alone here.
11921 // What matters: prior cold locators for PKs 0..1 are gone,
11922 // PKs 2..3 still resolve through their original segments.
11923 for id in [2i64, 3] {
11924 assert_eq!(
11925 cat.lookup_by_pk("users", "by_id", &IndexKey::Int(id))
11926 .unwrap(),
11927 make_user_row(id, &alloc::format!("u-{id}"))
11928 );
11929 }
11930 }
11931}