Skip to main content

sql_splitter/generate/
verify.rs

1//! Post-generation verification: reparse protected output and audit it before
2//! publication.
3//!
4//! `--verify` renders SQL to a protected temporary file, then this module
5//! **reparses that file with the production parser** ([`Parser::visit_events`],
6//! the same visitor the profiler drives) and audits the generated rows against
7//! the declared [`GenerationPlan`]. Only if the full [`VerificationReport`]
8//! passes does the caller atomically publish the temp file over the real
9//! destination; a failed audit leaves the prior destination untouched.
10//!
11//! # What is checked, and how honestly
12//!
13//! Every reported check carries a [`CheckStatus`]:
14//!
15//! * [`CheckStatus::Exact`] — a machine-checkable invariant evaluated on every
16//!   row: row counts, arity, non-null, declared character length, integer
17//!   width, decimal precision/scale, primary-key/unique uniqueness, foreign-key
18//!   and composite-key membership, planner equations/state invariants
19//!   ([`PlannerPredicate`]s from the compiled planners), and cross-table family
20//!   sums ([`FamilySumCheck`]s).
21//! * [`CheckStatus::Sampled`] — an approximate distribution comparison against a
22//!   recorded tolerance. A sampled check is **never** relabeled exact.
23//! * [`CheckStatus::NotChecked`] — a capability the verifier could not evaluate
24//!   (e.g. a table whose DDL never appeared). It is reported as its own status
25//!   and never counted as a silent success.
26//!
27//! [`VerificationReport::passed`] is `true` only when no check failed; a
28//! `NotChecked` capability is surfaced but does not, on its own, fail the run
29//! unless it means a required exact check could not run.
30//!
31//! # Bounded membership
32//!
33//! Uniqueness and membership indexes hold exact keys in memory under a byte
34//! budget and spill their key bytes to a [`ProtectedSpool`] once the budget is
35//! exceeded. Spilled indexes external-sort bounded runs, then use adjacent-key
36//! and linear merge-join checks without retaining an entry per key in memory.
37//! Dense integer key domains stay in memory.
38
39use std::cell::Cell;
40use std::cmp::Ordering;
41use std::collections::{HashMap, HashSet};
42use std::io::{self, BufReader};
43use std::path::{Path, PathBuf};
44
45use smallvec::SmallVec;
46
47use crate::convert::{map_column_type, WarningCollector};
48use crate::parser::mysql_insert::{
49    hash_pk_tuple, parse_insert_tuple, visit_insert_rows_with, InsertRowContext, PkTuple, PkValue,
50    RowExtraction,
51};
52use crate::parser::postgres_copy::{parse_copy_columns, CopyParser};
53use crate::parser::{Parser, ParserEvent, RowFlow, SqlDialect, StatementType};
54use crate::schema::{Column, ColumnId, ColumnType, Schema, SchemaBuilder, TableId, TableSchema};
55use crate::synthetic::schema::{
56    declared_character_length, declared_decimal_shape, declared_integer_bounds,
57};
58use crate::synthetic::OutputMode;
59
60use super::output::{ProtectedSpool, SpoolReader, SpooledRow, TempConfig};
61use super::plan::{ColumnOwner, CompiledRelationship, GenerationPlan, PlannedTable};
62use super::registry::{PlannerPredicate, PredicateGuard};
63use super::value::{GenerateError, GeneratedValue};
64
65/// Nanoseconds per second; timestamps render at second precision, so equations
66/// are checked modulo one second.
67const NANOS_PER_SECOND: i128 = 1_000_000_000;
68
69/// The default in-memory byte budget for one membership/uniqueness index before
70/// it spills its key bytes to a protected spool.
71const DEFAULT_MEMBERSHIP_BUDGET: usize = 64 * 1024 * 1024;
72
73// ---------------------------------------------------------------------------
74// Report types
75// ---------------------------------------------------------------------------
76
77/// How thoroughly a single check was evaluated. A check is never reported under
78/// a status stronger than the evidence supports.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum CheckStatus {
81    /// Evaluated exactly on every row.
82    Exact,
83    /// Compared approximately against a recorded tolerance.
84    Sampled,
85    /// The verifier could not evaluate this capability.
86    NotChecked,
87}
88
89/// One audited invariant and its outcome. `name` is a stable slug (e.g.
90/// `primary_key:orders`, `planner_equation:sessions`) so callers and tests can
91/// locate a specific check; `detail` never contains source or generated values.
92#[derive(Debug, Clone)]
93pub struct CheckOutcome {
94    /// Stable, greppable check name.
95    pub name: String,
96    /// How the check was evaluated.
97    pub status: CheckStatus,
98    /// Whether the check passed. A [`CheckStatus::NotChecked`] check is neither a
99    /// pass nor a failure of the invariant; `passed` is `false` for it so it can
100    /// never be mistaken for a green exact check.
101    pub passed: bool,
102    /// A value-free description of the outcome.
103    pub detail: String,
104}
105
106/// The full audit of a generated SQL file.
107#[derive(Debug, Clone, Default)]
108pub struct VerificationReport {
109    /// Every check performed, in table/kind order.
110    pub checks: Vec<CheckOutcome>,
111}
112
113impl VerificationReport {
114    /// Whether every evaluated check passed. A `NotChecked` capability does not
115    /// by itself fail the report; only an actual failed check does.
116    pub fn passed(&self) -> bool {
117        self.checks
118            .iter()
119            .all(|check| check.passed || check.status == CheckStatus::NotChecked)
120    }
121
122    /// The checks that failed, most useful for diagnostics.
123    pub fn failures(&self) -> impl Iterator<Item = &CheckOutcome> {
124        self.checks
125            .iter()
126            .filter(|check| !check.passed && check.status != CheckStatus::NotChecked)
127    }
128
129    /// Whether a check whose name contains `needle` failed. Convenience for
130    /// tests asserting a specific named exact check caught a corruption.
131    pub fn failed(&self, needle: &str) -> bool {
132        self.failures().any(|check| check.name.contains(needle))
133    }
134
135    /// The status of the first check whose name contains `needle`, if any.
136    pub fn status_of(&self, needle: &str) -> Option<CheckStatus> {
137        self.checks
138            .iter()
139            .find(|check| check.name.contains(needle))
140            .map(|check| check.status)
141    }
142
143    fn record(&mut self, name: String, status: CheckStatus, passed: bool, detail: String) {
144        self.checks.push(CheckOutcome {
145            name,
146            status,
147            passed,
148            detail,
149        });
150    }
151}
152
153/// An approximate categorical-distribution expectation the verifier compares a
154/// generated column against, labeled [`CheckStatus::Sampled`]. Fractions are of
155/// the table's total rows; `tolerance` is the maximum absolute deviation any
156/// category may drift before the sampled check fails.
157#[derive(Debug, Clone)]
158pub struct DistributionExpectation {
159    /// The `table.column` the distribution is measured on.
160    pub table: String,
161    /// The column within `table`.
162    pub column: String,
163    /// Expected `(value, fraction)` pairs; fractions should sum to about 1.0.
164    pub categories: Vec<(String, f64)>,
165    /// Maximum absolute per-category deviation before the check fails.
166    pub tolerance: f64,
167}
168
169// ---------------------------------------------------------------------------
170// The verifier
171// ---------------------------------------------------------------------------
172
173/// Reparses a generated SQL file and audits it against a [`GenerationPlan`].
174///
175/// The verifier extracts everything it needs from the plan up front into an
176/// owned [`PlanSpec`], so it does not borrow the plan — the caller can move the
177/// plan into the [`crate::generate::GenerationEngine`] to render, then verify
178/// the rendered file against the already-captured spec.
179pub struct GenerationVerifier {
180    spec: PlanSpec,
181    plan_schema: Schema,
182    dialect: SqlDialect,
183    source_dialect: Option<SqlDialect>,
184    output_mode: OutputMode,
185    membership_budget: usize,
186    temp: TempConfig,
187    distributions: Vec<DistributionExpectation>,
188}
189
190impl GenerationVerifier {
191    /// A verifier for `plan`, defaulting to the plan's output dialect (or MySQL
192    /// when none is pinned).
193    pub fn new(plan: &GenerationPlan) -> Self {
194        let dialect = plan
195            .output
196            .dialect
197            .or(plan.input_dialect)
198            .unwrap_or(SqlDialect::MySql);
199        let source_dialect = plan.input_dialect;
200        let constraint_dialect = source_dialect.unwrap_or(dialect);
201        Self {
202            spec: PlanSpec::from_plan(plan, constraint_dialect),
203            plan_schema: schema_from_plan(plan),
204            dialect,
205            source_dialect,
206            output_mode: OutputMode::SchemaAndData,
207            membership_budget: DEFAULT_MEMBERSHIP_BUDGET,
208            temp: TempConfig::default(),
209            distributions: Vec::new(),
210        }
211    }
212
213    /// Override the dialect the generated SQL is parsed with.
214    pub fn dialect(mut self, dialect: SqlDialect) -> Self {
215        self.dialect = dialect;
216        self.spec
217            .resolve_integer_limits(self.source_dialect.unwrap_or(dialect));
218        self
219    }
220
221    /// Match verification to the renderer's output mode.
222    ///
223    /// Data-only output uses the compiled plan schema to decode rows because no
224    /// DDL is present. Schema-only output checks DDL and expects no row data.
225    pub fn output_mode(mut self, mode: OutputMode) -> Self {
226        self.output_mode = mode;
227        self
228    }
229
230    /// Set the in-memory byte budget for each membership/uniqueness index before
231    /// it spills to a protected spool. A small budget exercises the spill path.
232    pub fn membership_budget_bytes(mut self, bytes: usize) -> Self {
233        self.membership_budget = bytes;
234        self
235    }
236
237    /// Store protected verification spools in `dir` instead of the OS temp
238    /// directory. The directory must already exist.
239    pub fn temp_directory(mut self, dir: impl Into<PathBuf>) -> Self {
240        self.temp = TempConfig::in_dir(dir);
241        self
242    }
243
244    /// Add an approximate distribution expectation, checked as
245    /// [`CheckStatus::Sampled`].
246    pub fn expect_distribution(mut self, expectation: DistributionExpectation) -> Self {
247        self.distributions.push(expectation);
248        self
249    }
250
251    /// Reparse and audit `path`, returning the full report. Parses the file
252    /// twice: once to reconstruct the schema from the emitted DDL, once to
253    /// audit rows against the plan.
254    pub fn verify_path(&self, path: &Path) -> Result<VerificationReport, GenerateError> {
255        if self.output_mode == OutputMode::DataOnly {
256            self.audit_rows(path, &self.plan_schema, false)
257        } else {
258            let schema = self.build_schema(path)?;
259            self.audit_rows(path, &schema, true)
260        }
261    }
262
263    /// Pass 1: reconstruct the reparsed schema from the file's DDL.
264    fn build_schema(&self, path: &Path) -> Result<Schema, GenerateError> {
265        let mut builder = SchemaBuilder::new();
266        let reader = open_reader(path)?;
267        let mut parser = Parser::with_dialect(reader, 1 << 20, self.dialect);
268        parser
269            .visit_events(|event| {
270                if let ParserEvent::Statement(bytes) = event {
271                    builder.ingest_statement(bytes, self.dialect);
272                }
273                Ok(RowFlow::Continue)
274            })
275            .map_err(parse_error)?;
276        Ok(builder.build())
277    }
278
279    /// Pass 2: stream rows and evaluate every exact + sampled check.
280    fn audit_rows(
281        &self,
282        path: &Path,
283        schema: &Schema,
284        expect_ddl: bool,
285    ) -> Result<VerificationReport, GenerateError> {
286        let mut report = VerificationReport::default();
287        let mut audit = Audit::new(
288            &self.spec,
289            schema,
290            self.source_dialect.unwrap_or(self.dialect),
291            self.dialect,
292            self.membership_budget,
293            self.temp.clone(),
294        );
295        audit.register_distributions(&self.distributions);
296        if expect_ddl {
297            audit.check_expected_tables(&mut report);
298        }
299
300        let reader = open_reader(path)?;
301        let mut parser = Parser::with_dialect(reader, 1 << 20, self.dialect);
302        let dialect = self.dialect;
303        // The parser borrows the current INSERT/COPY context across rows of one
304        // statement; rebuild it whenever a new statement starts. COPY output is
305        // audited through the *same* `observe_row` path as INSERT tuples, so a
306        // Postgres COPY table gets exactly the same exact checks.
307        let mut context: Option<InsertState> = None;
308        let mut copy: Option<CopyState<'_>> = None;
309        let audit_ref = &mut audit;
310        parser
311            .visit_events(|event| {
312                match event {
313                    ParserEvent::InsertRow {
314                        header,
315                        row,
316                        first_in_statement,
317                    } => {
318                        if first_in_statement {
319                            context = InsertState::from_header(header, schema, dialect);
320                        }
321                        if let Some(state) = &context {
322                            if let Some(table) = schema.table(state.table_id_index) {
323                                if let Some(parsed) = parse_insert_tuple(
324                                    row,
325                                    table,
326                                    &state.context,
327                                    dialect,
328                                    RowExtraction::Full,
329                                ) {
330                                    audit_ref.observe_row(
331                                        &state.table_name,
332                                        table,
333                                        &parsed.all_values,
334                                        &parsed.column_map,
335                                    )?;
336                                } else {
337                                    audit_ref.note_undecodable(&state.table_name);
338                                }
339                            }
340                        }
341                    }
342                    ParserEvent::Statement(bytes) => {
343                        // Some dialects (notably MSSQL, whose INSERTs are
344                        // separated by `GO` batch markers) are delivered as a
345                        // whole INSERT statement rather than streamed one tuple
346                        // at a time. Audit those rows through the SAME path by
347                        // parsing the statement's tuples here.
348                        let (stmt_type, name) =
349                            Parser::<&[u8]>::parse_statement_with_dialect(bytes, dialect);
350                        if stmt_type == StatementType::Insert && !name.is_empty() {
351                            if let Some(table_id) = schema.get_table_id(&name) {
352                                if let Some(table) = schema.table(table_id) {
353                                    visit_insert_rows_with(
354                                        bytes,
355                                        table,
356                                        dialect,
357                                        RowExtraction::Full,
358                                        |parsed| {
359                                            if parsed.all_values.is_empty() {
360                                                audit_ref.note_undecodable(&name);
361                                            } else {
362                                                audit_ref.observe_row(
363                                                    &name,
364                                                    table,
365                                                    &parsed.all_values,
366                                                    &parsed.column_map,
367                                                )?;
368                                            }
369                                            Ok(RowFlow::Continue)
370                                        },
371                                    )?;
372                                }
373                            }
374                        }
375                    }
376                    ParserEvent::CopyStart(header) => {
377                        copy = CopyState::from_header(header, schema, dialect);
378                    }
379                    ParserEvent::CopyRow(line) => {
380                        if let Some(state) = &copy {
381                            if let Some(parsed) =
382                                state.parser.parse_line(line, state.empty_line_is_row)
383                            {
384                                if parsed.all_values.is_empty() {
385                                    audit_ref.note_undecodable(&state.table_name);
386                                } else {
387                                    audit_ref.observe_row(
388                                        &state.table_name,
389                                        state.table,
390                                        &parsed.all_values,
391                                        &parsed.column_map,
392                                    )?;
393                                }
394                            }
395                        }
396                    }
397                    ParserEvent::CopyEnd => copy = None,
398                }
399                Ok(RowFlow::Continue)
400            })
401            .map_err(parse_error)?;
402
403        audit.finish(&mut report, &self.distributions, self.output_mode)?;
404        Ok(report)
405    }
406}
407
408/// Build the row-decoding schema used when the renderer intentionally omits
409/// DDL. Verification constraints still come from [`PlanSpec`]; this schema
410/// supplies only stable column identity and value-family parsing.
411fn schema_from_plan(plan: &GenerationPlan) -> Schema {
412    let mut schema = Schema::new();
413    for table in &plan.tables {
414        let mut runtime = TableSchema::new(table.name.clone(), TableId(0));
415        runtime.columns = table
416            .schema
417            .columns
418            .iter()
419            .enumerate()
420            .map(|(ordinal, column)| Column {
421                name: column.name.clone(),
422                col_type: ColumnType::from_sql_type(&column.source_type),
423                source_type: column.source_type.clone(),
424                ordinal: ColumnId(ordinal as u16),
425                is_primary_key: column.primary_key,
426                is_nullable: column.nullable,
427                is_unique: column.unique,
428                default_sql: column.default_sql.clone(),
429                is_generated: column.generated,
430                is_identity: column.identity,
431                collation: column.collation.clone(),
432            })
433            .collect();
434        runtime.primary_key = table
435            .schema
436            .primary_key
437            .iter()
438            .filter_map(|name| runtime.get_column_id(name))
439            .collect();
440        schema.add_table(runtime);
441    }
442    schema
443}
444
445/// The reparsed schema table id plus its per-statement parse context.
446struct InsertState {
447    table_name: String,
448    table_id_index: crate::schema::TableId,
449    context: InsertRowContext,
450}
451
452impl InsertState {
453    fn from_header(header: &[u8], schema: &Schema, dialect: SqlDialect) -> Option<Self> {
454        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, dialect);
455        if name.is_empty() {
456            return None;
457        }
458        let table_id = schema.get_table_id(&name)?;
459        let table = schema.table(table_id)?;
460        Some(Self {
461            table_name: name,
462            table_id_index: table_id,
463            context: InsertRowContext::from_header(header, table, dialect),
464        })
465    }
466}
467
468/// Per-`COPY`-block parse context: the reparsed table schema plus a prepared
469/// [`CopyParser`] that decodes each `CopyRow` line the same way the profiler
470/// does, so COPY rows feed the identical [`Audit::observe_row`] path as INSERT
471/// tuples.
472struct CopyState<'s> {
473    table_name: String,
474    table: &'s TableSchema,
475    parser: CopyParser<'s>,
476    empty_line_is_row: bool,
477}
478
479impl<'s> CopyState<'s> {
480    fn from_header(header: &[u8], schema: &'s Schema, dialect: SqlDialect) -> Option<Self> {
481        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, dialect);
482        if name.is_empty() {
483            return None;
484        }
485        let table_id = schema.get_table_id(&name)?;
486        let table = schema.table(table_id)?;
487        let columns = parse_copy_columns(&String::from_utf8_lossy(header));
488        let (parser, empty_line_is_row) = CopyParser::new(&[])
489            .with_schema(table)
490            .with_column_order(columns)
491            .with_extraction(RowExtraction::Full)
492            .prepared();
493        Some(Self {
494            table_name: name,
495            table,
496            parser,
497            empty_line_is_row,
498        })
499    }
500}
501
502// ---------------------------------------------------------------------------
503// Owned plan spec (extracted so the verifier does not borrow the plan)
504// ---------------------------------------------------------------------------
505
506/// Everything the audit needs from the compiled plan, owned so the plan itself
507/// can be moved into the engine before verification runs.
508struct PlanSpec {
509    tables: Vec<TableSpec>,
510    families: Vec<FamilySpec>,
511}
512
513/// One table's declared surface for verification.
514struct TableSpec {
515    name: String,
516    rows: u64,
517    /// Columns the compiled engine must render on every row. Database-produced
518    /// columns are excluded unless a relationship requires the engine to
519    /// materialize that parent key.
520    rendered_columns: Vec<String>,
521    /// Non-nullable columns whose value must never be `NULL` (database-produced
522    /// columns excluded, since they legitimately render nothing).
523    non_null_columns: Vec<String>,
524    /// The primary key columns (empty when the table has no PK).
525    primary_key: Vec<String>,
526    /// Uniqueness key groups: the PK plus every UNIQUE constraint / column.
527    unique_groups: Vec<Vec<String>>,
528    /// Column declarations used to compare rendered DDL with the plan.
529    ddl_columns: Vec<DdlColumnSpec>,
530    /// UNIQUE groups expected in rendered DDL, excluding the primary key.
531    ddl_unique_groups: Vec<Vec<String>>,
532    /// Foreign keys expected in rendered DDL.
533    ddl_relationships: Vec<RelSpec>,
534    /// Character limits declared by bounded text columns.
535    character_limits: Vec<(String, usize)>,
536    /// Fixed-width integer declarations, retained so a dialect override can
537    /// resolve ambiguous spellings such as bare `tinyint`.
538    integer_declarations: Vec<(String, String)>,
539    /// Exact ranges declared by fixed-width integer columns.
540    integer_limits: Vec<(String, i128, i128)>,
541    /// Precision and scale declared by fixed-point decimal columns.
542    decimal_limits: Vec<(String, u32, u32)>,
543    /// Foreign-key relationships to parent tables.
544    relationships: Vec<RelSpec>,
545    /// Planner invariants the table's planners guarantee.
546    predicates: Vec<PlannerPredicate>,
547    /// Whether a cross-table family planner (a `commerce.order_family` child)
548    /// owns any of this table's columns. Such a child's row count is realized by
549    /// the family planner's per-parent line-count draws, so `rows` is only a
550    /// compile-time estimate and the row-count check is sampled, not exact.
551    family_child: bool,
552}
553
554/// One column declaration needed for exact schema comparison.
555struct DdlColumnSpec {
556    name: String,
557    source_type: String,
558    nullable: bool,
559}
560
561/// A child→parent relationship reduced to the names the audit needs.
562#[derive(Clone)]
563struct RelSpec {
564    name: Option<String>,
565    columns: Vec<String>,
566    parent_table: String,
567    parent_columns: Vec<String>,
568}
569
570/// A resolved cross-table family sum invariant.
571struct FamilySpec {
572    slug: String,
573    parent_table: String,
574    parent_column: String,
575    child_table: String,
576    child_column: String,
577    child_fk_columns: Vec<String>,
578    parent_key_columns: Vec<String>,
579}
580
581impl PlanSpec {
582    fn from_plan(plan: &GenerationPlan, integer_dialect: SqlDialect) -> Self {
583        let materialized_parent_keys: HashSet<(String, String)> = plan
584            .tables
585            .iter()
586            .flat_map(|table| {
587                table.relationships.iter().flat_map(|relationship| {
588                    relationship
589                        .parent_columns
590                        .iter()
591                        .map(|column| (relationship.parent_table.clone(), column.clone()))
592                })
593            })
594            .collect();
595        let tables = plan
596            .tables
597            .iter()
598            .map(|table| TableSpec::from_table(table, &materialized_parent_keys, integer_dialect))
599            .collect();
600        let families = extract_families(plan);
601        Self { tables, families }
602    }
603
604    fn resolve_integer_limits(&mut self, dialect: SqlDialect) {
605        for table in &mut self.tables {
606            table.resolve_integer_limits(dialect);
607        }
608    }
609}
610
611impl TableSpec {
612    fn from_table(
613        table: &PlannedTable,
614        materialized_parent_keys: &HashSet<(String, String)>,
615        integer_dialect: SqlDialect,
616    ) -> Self {
617        let mut unique_groups: Vec<Vec<String>> = Vec::new();
618        if !table.schema.primary_key.is_empty() {
619            unique_groups.push(table.schema.primary_key.clone());
620        }
621        for uc in &table.schema.unique_constraints {
622            if !uc.columns.is_empty() && !unique_groups.contains(&uc.columns) {
623                unique_groups.push(uc.columns.clone());
624            }
625        }
626        for col in &table.schema.columns {
627            let single = vec![col.name.clone()];
628            if col.unique && !unique_groups.contains(&single) {
629                unique_groups.push(single);
630            }
631        }
632        let mut ddl_unique_groups: Vec<Vec<String>> = table
633            .schema
634            .unique_constraints
635            .iter()
636            .map(|constraint| constraint.columns.clone())
637            .collect();
638        for column in table.schema.columns.iter().filter(|column| column.unique) {
639            let group = vec![column.name.clone()];
640            if !ddl_unique_groups
641                .iter()
642                .any(|existing| identifier_groups_equal(existing, &group))
643            {
644                ddl_unique_groups.push(group);
645            }
646        }
647
648        let rendered_columns: Vec<String> = table
649            .columns
650            .iter()
651            .filter(|column| rendered_by_engine(table, column, materialized_parent_keys))
652            .map(|column| column.schema.name.clone())
653            .collect();
654        let non_null_columns = table
655            .schema
656            .columns
657            .iter()
658            .filter(|column| !column.nullable && rendered_columns.contains(&column.name))
659            .map(|column| column.name.clone())
660            .collect();
661        let ddl_columns = table
662            .schema
663            .columns
664            .iter()
665            .map(|column| DdlColumnSpec {
666                name: column.name.clone(),
667                source_type: column.source_type.clone(),
668                nullable: column.nullable,
669            })
670            .collect();
671        let character_limits = table
672            .schema
673            .columns
674            .iter()
675            .filter_map(|column| {
676                declared_character_length(&column.source_type)
677                    .map(|limit| (column.name.clone(), limit))
678            })
679            .collect();
680        let integer_declarations: Vec<(String, String)> = table
681            .schema
682            .columns
683            .iter()
684            .filter(|column| {
685                matches!(
686                    column.family,
687                    crate::synthetic::schema::SqlTypeFamily::Integer
688                        | crate::synthetic::schema::SqlTypeFamily::BigInteger
689                )
690            })
691            .map(|column| (column.name.clone(), column.source_type.clone()))
692            .collect();
693        let integer_limits = resolve_integer_declarations(&integer_declarations, integer_dialect);
694        let decimal_limits = table
695            .schema
696            .columns
697            .iter()
698            .filter_map(|column| {
699                declared_decimal_shape(&column.source_type)
700                    .map(|(precision, scale)| (column.name.clone(), precision, scale))
701            })
702            .collect();
703
704        let relationships = table
705            .relationships
706            .iter()
707            .map(|rel| RelSpec {
708                name: rel.name.clone(),
709                columns: rel.columns.clone(),
710                parent_table: rel.parent_table.clone(),
711                parent_columns: rel.parent_columns.clone(),
712            })
713            .collect();
714        let ddl_relationships = table
715            .schema
716            .relationships
717            .iter()
718            .map(|relationship| RelSpec {
719                name: relationship.name.clone(),
720                columns: relationship.columns.clone(),
721                parent_table: relationship.referenced_table.clone(),
722                parent_columns: relationship.referenced_columns.clone(),
723            })
724            .collect();
725
726        let predicates = table
727            .planners
728            .iter()
729            .flat_map(|planner| planner.verification_predicates())
730            .collect();
731
732        let family_child = table
733            .columns
734            .iter()
735            .any(|column| matches!(column.owner, ColumnOwner::FamilyChild { .. }));
736
737        Self {
738            name: table.name.clone(),
739            rows: table.rows,
740            rendered_columns,
741            non_null_columns,
742            primary_key: table.schema.primary_key.clone(),
743            unique_groups,
744            ddl_columns,
745            ddl_unique_groups,
746            ddl_relationships,
747            character_limits,
748            integer_declarations,
749            integer_limits,
750            decimal_limits,
751            relationships,
752            predicates,
753            family_child,
754        }
755    }
756
757    fn resolve_integer_limits(&mut self, dialect: SqlDialect) {
758        self.integer_limits = resolve_integer_declarations(&self.integer_declarations, dialect);
759    }
760}
761
762fn resolve_integer_declarations(
763    declarations: &[(String, String)],
764    dialect: SqlDialect,
765) -> Vec<(String, i128, i128)> {
766    declarations
767        .iter()
768        .filter_map(|(name, source_type)| {
769            declared_integer_bounds(source_type, Some(dialect))
770                .map(|(min, max)| (name.clone(), min, max))
771        })
772        .collect()
773}
774
775fn compare_table_ddl(
776    planned: &TableSpec,
777    reparsed: &TableSchema,
778    source_dialect: SqlDialect,
779    target_dialect: SqlDialect,
780) -> Vec<String> {
781    let mut mismatches = Vec::new();
782    let mut warnings = WarningCollector::new();
783
784    for expected in &planned.ddl_columns {
785        let Some(actual) = reparsed.get_column(&expected.name) else {
786            mismatches.push(format!("{}.{} is missing", planned.name, expected.name));
787            continue;
788        };
789        let expected_type = map_column_type(
790            &expected.source_type,
791            source_dialect,
792            target_dialect,
793            &mut warnings,
794        );
795        if normalize_sql_type(&actual.source_type) != normalize_sql_type(&expected_type) {
796            mismatches.push(format!(
797                "{}.{} has type `{}` instead of `{expected_type}`",
798                planned.name, expected.name, actual.source_type
799            ));
800        }
801        if actual.is_nullable != expected.nullable {
802            mismatches.push(format!(
803                "{}.{} nullable={} instead of {}",
804                planned.name, expected.name, actual.is_nullable, expected.nullable
805            ));
806        }
807    }
808    for actual in &reparsed.columns {
809        if !planned
810            .ddl_columns
811            .iter()
812            .any(|expected| expected.name.eq_ignore_ascii_case(&actual.name))
813        {
814            mismatches.push(format!("{}.{} is unexpected", planned.name, actual.name));
815        }
816    }
817
818    let actual_primary_key: Vec<String> = reparsed
819        .primary_key
820        .iter()
821        .filter_map(|&id| reparsed.column(id))
822        .map(|column| column.name.clone())
823        .collect();
824    if normalize_identifier_group(&actual_primary_key)
825        != normalize_identifier_group(&planned.primary_key)
826    {
827        mismatches.push(format!(
828            "{} primary key differs from the plan",
829            planned.name
830        ));
831    }
832
833    let mut actual_unique_groups: Vec<Vec<String>> = reparsed
834        .unique_constraints
835        .iter()
836        .map(|constraint| constraint.columns.clone())
837        .collect();
838    for column in reparsed.columns.iter().filter(|column| column.is_unique) {
839        let group = vec![column.name.clone()];
840        if !actual_unique_groups
841            .iter()
842            .any(|existing| identifier_groups_equal(existing, &group))
843        {
844            actual_unique_groups.push(group);
845        }
846    }
847    if normalize_identifier_groups(&actual_unique_groups)
848        != normalize_identifier_groups(&planned.ddl_unique_groups)
849    {
850        mismatches.push(format!(
851            "{} unique constraints differ from the plan",
852            planned.name
853        ));
854    }
855
856    let actual_relationships: Vec<RelSpec> = reparsed
857        .foreign_keys
858        .iter()
859        .map(|relationship| RelSpec {
860            name: relationship.name.clone(),
861            columns: relationship.column_names.clone(),
862            parent_table: relationship.referenced_table.clone(),
863            parent_columns: relationship.referenced_columns.clone(),
864        })
865        .collect();
866    if normalize_relationships(&actual_relationships)
867        != normalize_relationships(&planned.ddl_relationships)
868    {
869        mismatches.push(format!(
870            "{} foreign keys differ from the plan",
871            planned.name
872        ));
873    }
874
875    mismatches
876}
877
878fn normalize_sql_type(source_type: &str) -> String {
879    source_type
880        .chars()
881        .filter(|character| !character.is_ascii_whitespace())
882        .flat_map(char::to_lowercase)
883        .collect()
884}
885
886fn normalize_identifier_group(columns: &[String]) -> Vec<String> {
887    columns
888        .iter()
889        .map(|column| column.to_ascii_lowercase())
890        .collect()
891}
892
893fn identifier_groups_equal(left: &[String], right: &[String]) -> bool {
894    normalize_identifier_group(left) == normalize_identifier_group(right)
895}
896
897fn normalize_identifier_groups(groups: &[Vec<String>]) -> Vec<Vec<String>> {
898    let mut normalized: Vec<Vec<String>> = groups
899        .iter()
900        .map(|group| normalize_identifier_group(group))
901        .collect();
902    normalized.sort();
903    normalized.dedup();
904    normalized
905}
906
907fn normalize_relationships(relationships: &[RelSpec]) -> Vec<(Vec<String>, String, Vec<String>)> {
908    let mut normalized: Vec<_> = relationships
909        .iter()
910        .map(|relationship| {
911            (
912                normalize_identifier_group(&relationship.columns),
913                relationship.parent_table.to_ascii_lowercase(),
914                normalize_identifier_group(&relationship.parent_columns),
915            )
916        })
917        .collect();
918    normalized.sort();
919    normalized.dedup();
920    normalized
921}
922
923/// Whether the compiled engine renders `column` on every row.
924fn rendered_by_engine(
925    table: &PlannedTable,
926    column: &super::plan::PlannedColumn,
927    materialized_parent_keys: &HashSet<(String, String)>,
928) -> bool {
929    match &column.owner {
930        ColumnOwner::Generator { kind, .. } => kind != "database_default",
931        ColumnOwner::Planner { .. }
932        | ColumnOwner::FamilyChild { .. }
933        | ColumnOwner::Relationship { .. } => true,
934        ColumnOwner::DatabaseDefault | ColumnOwner::GeneratedByDatabase => {
935            materialized_parent_keys.contains(&(table.name.clone(), column.schema.name.clone()))
936        }
937    }
938}
939
940/// Resolve every family planner's sum checks into fully-named [`FamilySpec`]s.
941fn extract_families(plan: &GenerationPlan) -> Vec<FamilySpec> {
942    let mut families = Vec::new();
943    for parent in &plan.tables {
944        for planner in &parent.planners {
945            let Some(child_table) = planner.family_child_table() else {
946                continue;
947            };
948            let checks = planner.family_sum_checks();
949            if checks.is_empty() {
950                continue;
951            }
952            let Some(child) = plan.table(child_table) else {
953                continue;
954            };
955            for check in checks {
956                let Some(rel) = find_relationship(child, &check.relationship) else {
957                    continue;
958                };
959                families.push(FamilySpec {
960                    slug: format!(
961                        "family_sum:{}:{}->{}",
962                        parent.name, check.parent_column, check.child_column
963                    ),
964                    parent_table: parent.name.clone(),
965                    parent_column: check.parent_column,
966                    child_table: child_table.to_string(),
967                    child_column: check.child_column,
968                    child_fk_columns: rel.columns.clone(),
969                    parent_key_columns: rel.parent_columns.clone(),
970                });
971            }
972        }
973    }
974    families
975}
976
977// ---------------------------------------------------------------------------
978// Row-by-row audit state
979// ---------------------------------------------------------------------------
980
981/// A membership/uniqueness key group indexed while auditing a table.
982struct GroupKey {
983    /// The columns (by name) forming the key.
984    columns: Vec<String>,
985    /// The exact/spilling index of observed key tuples.
986    index: KeySet,
987    /// Whether any duplicate was observed (uniqueness groups only).
988    duplicate: bool,
989}
990
991/// Per-table audit accumulators.
992struct TableState {
993    /// The plan's declared table.
994    plan_index: usize,
995    /// Observed row count.
996    rows: u64,
997    /// Rows whose values could not be decoded (a renderability failure).
998    undecodable: u64,
999    /// Non-null violations per column name.
1000    null_violations: HashMap<String, u64>,
1001    /// Declared character-width violations per column name.
1002    character_length_violations: HashMap<String, u64>,
1003    /// Fixed-width integer range violations per column name.
1004    integer_range_violations: HashMap<String, u64>,
1005    /// Fixed-point decimal precision/scale violations per column name.
1006    decimal_shape_violations: HashMap<String, u64>,
1007    /// Arity violations (a row that differs from the plan-derived rendered
1008    /// column set).
1009    arity_violations: u64,
1010    /// Uniqueness key groups (PK + unique constraints).
1011    unique_groups: Vec<GroupKey>,
1012    /// Membership indexes this table exposes for children (parent-column groups).
1013    member_groups: Vec<GroupKey>,
1014    /// Child FK occurrences, one append-only index per declared relationship.
1015    foreign_keys: Vec<KeySet>,
1016    /// Planner predicate failures, keyed by a stable check slug.
1017    predicate_failures: HashMap<String, u64>,
1018    /// Rows a planner predicate could not evaluate because a required input was
1019    /// present but unparseable, keyed by the same slug. A non-zero count
1020    /// downgrades the check to `NotChecked` rather than a silent Exact pass.
1021    predicate_unevaluated: HashMap<String, u64>,
1022    /// Sampled category tallies, bounded to categories named by expectations.
1023    categories: CategoryTallies,
1024}
1025
1026/// Expected categorical values and their observed counts. Values absent from
1027/// `expected` are deliberately never retained, so high-cardinality generated
1028/// text cannot turn a sampled check into an unbounded map.
1029#[derive(Default)]
1030struct CategoryTallies {
1031    expected: HashMap<String, HashSet<String>>,
1032    counts: HashMap<String, HashMap<String, u64>>,
1033}
1034
1035impl CategoryTallies {
1036    fn register(&mut self, expectation: &DistributionExpectation) {
1037        self.expected
1038            .entry(expectation.column.clone())
1039            .or_default()
1040            .extend(
1041                expectation
1042                    .categories
1043                    .iter()
1044                    .map(|(value, _)| value.clone()),
1045            );
1046    }
1047
1048    fn record(&mut self, column: &str, value: &str) {
1049        if !self
1050            .expected
1051            .get(column)
1052            .is_some_and(|values| values.contains(value))
1053        {
1054            return;
1055        }
1056        *self
1057            .counts
1058            .entry(column.to_string())
1059            .or_default()
1060            .entry(value.to_string())
1061            .or_insert(0) += 1;
1062    }
1063}
1064
1065/// A single family-sum accumulator across a parent/child pair.
1066struct FamilyAcc {
1067    /// A stable slug for the check.
1068    slug: String,
1069    /// Parent table name.
1070    parent_table: String,
1071    /// Parent aggregate column.
1072    parent_column: String,
1073    /// Child table name.
1074    child_table: String,
1075    /// Child summed column.
1076    child_column: String,
1077    /// Child FK columns pointing back to the parent's referenced columns.
1078    child_fk_columns: Vec<String>,
1079    /// Parent referenced columns forming the join key.
1080    parent_key_columns: Vec<String>,
1081    /// Parent aggregate records in protected, disk-backed exact storage.
1082    parent_values: FamilyValueStore,
1083    /// Individual child values in protected, disk-backed exact storage.
1084    child_values: FamilyValueStore,
1085    /// Whether any decode/scale problem made the check inexact.
1086    inexact: bool,
1087    /// Exact record reads/writes performed by external sorting and merge.
1088    operations: u64,
1089}
1090
1091/// A family aggregate contribution stored without a per-parent memory entry.
1092struct FamilyValueRecord {
1093    hash: u64,
1094    key: Vec<u8>,
1095    minor: (i128, u32),
1096}
1097
1098/// One exact-key record handled by the bounded external sorter. `payload` is
1099/// empty for membership keys and carries `(mantissa, scale)` for family sums.
1100#[derive(Clone)]
1101struct SortRecord {
1102    hash: u64,
1103    key: Vec<u8>,
1104    payload: Vec<GeneratedValue>,
1105}
1106
1107impl SortRecord {
1108    fn from_spooled(row: SpooledRow) -> io::Result<Self> {
1109        let mut values = row.values.into_iter();
1110        let Some(GeneratedValue::Bytes(key)) = values.next() else {
1111            return Err(io::Error::new(
1112                io::ErrorKind::InvalidData,
1113                "sorted spool record has an invalid key",
1114            ));
1115        };
1116        Ok(Self {
1117            hash: row.row_index,
1118            key,
1119            payload: values.collect(),
1120        })
1121    }
1122
1123    fn encoded_size(&self) -> usize {
1124        self.key.len() + self.payload.len() * std::mem::size_of::<GeneratedValue>() + 32
1125    }
1126}
1127
1128fn sort_record_cmp(left: &SortRecord, right: &SortRecord) -> Ordering {
1129    left.hash
1130        .cmp(&right.hash)
1131        .then_with(|| left.key.cmp(&right.key))
1132}
1133
1134fn exact_key_cmp(left_hash: u64, left: &[u8], right_hash: u64, right: &[u8]) -> Ordering {
1135    left_hash.cmp(&right_hash).then_with(|| left.cmp(right))
1136}
1137
1138#[derive(Default)]
1139struct SortStats {
1140    operations: u64,
1141}
1142
1143fn read_sort_record<R: io::Read>(
1144    reader: &mut SpoolReader<R>,
1145    stats: &mut SortStats,
1146) -> io::Result<Option<SortRecord>> {
1147    let Some(row) = reader.read_row()? else {
1148        return Ok(None);
1149    };
1150    stats.operations += 1;
1151    SortRecord::from_spooled(row).map(Some)
1152}
1153
1154fn write_sort_record(
1155    spool: &mut ProtectedSpool,
1156    record: SortRecord,
1157    stats: &mut SortStats,
1158) -> io::Result<()> {
1159    let mut values = Vec::with_capacity(record.payload.len() + 1);
1160    values.push(GeneratedValue::Bytes(record.key));
1161    values.extend(record.payload);
1162    spool.write_row(&SpooledRow {
1163        table_id: 0,
1164        row_index: record.hash,
1165        values,
1166    })?;
1167    stats.operations += 1;
1168    Ok(())
1169}
1170
1171fn write_sorted_chunk(
1172    mut chunk: Vec<SortRecord>,
1173    temp: &TempConfig,
1174    stats: &mut SortStats,
1175) -> io::Result<ProtectedSpool> {
1176    chunk.sort_unstable_by(sort_record_cmp);
1177    let mut run = ProtectedSpool::create(temp)?;
1178    for record in chunk {
1179        write_sort_record(&mut run, record, stats)?;
1180    }
1181    run.flush()?;
1182    Ok(run)
1183}
1184
1185fn merge_sorted_runs(
1186    mut left: ProtectedSpool,
1187    mut right: ProtectedSpool,
1188    temp: &TempConfig,
1189    stats: &mut SortStats,
1190) -> io::Result<ProtectedSpool> {
1191    left.flush()?;
1192    right.flush()?;
1193    let mut left_reader = SpoolReader::new(BufReader::new(std::fs::File::open(left.path())?));
1194    let mut right_reader = SpoolReader::new(BufReader::new(std::fs::File::open(right.path())?));
1195    let mut left_record = read_sort_record(&mut left_reader, stats)?;
1196    let mut right_record = read_sort_record(&mut right_reader, stats)?;
1197    let mut merged = ProtectedSpool::create(temp)?;
1198
1199    while left_record.is_some() || right_record.is_some() {
1200        let take_left = match (&left_record, &right_record) {
1201            (Some(left), Some(right)) => sort_record_cmp(left, right) != Ordering::Greater,
1202            (Some(_), None) => true,
1203            (None, Some(_)) => false,
1204            (None, None) => break,
1205        };
1206        if take_left {
1207            if let Some(record) = left_record.take() {
1208                write_sort_record(&mut merged, record, stats)?;
1209            }
1210            left_record = read_sort_record(&mut left_reader, stats)?;
1211        } else {
1212            if let Some(record) = right_record.take() {
1213                write_sort_record(&mut merged, record, stats)?;
1214            }
1215            right_record = read_sort_record(&mut right_reader, stats)?;
1216        }
1217    }
1218    merged.flush()?;
1219    Ok(merged)
1220}
1221
1222/// Sort an append-only protected spool with bounded record memory. Runs are
1223/// merged eagerly like a binary counter, so at most one run per size level is
1224/// retained and every record participates in `O(log n)` sequential disk I/O.
1225fn external_sort(
1226    mut source: ProtectedSpool,
1227    temp: &TempConfig,
1228    budget: usize,
1229    stats: &mut SortStats,
1230) -> io::Result<Option<ProtectedSpool>> {
1231    source.flush()?;
1232    let mut reader = SpoolReader::new(BufReader::new(std::fs::File::open(source.path())?));
1233    let mut levels: Vec<Option<ProtectedSpool>> = Vec::new();
1234    let mut chunk = Vec::new();
1235    let mut used = 0usize;
1236
1237    while let Some(record) = read_sort_record(&mut reader, stats)? {
1238        let size = record.encoded_size();
1239        if !chunk.is_empty() && used.saturating_add(size) > budget {
1240            let run = write_sorted_chunk(std::mem::take(&mut chunk), temp, stats)?;
1241            add_sorted_run(&mut levels, run, temp, stats)?;
1242            used = 0;
1243        }
1244        used = used.saturating_add(size);
1245        chunk.push(record);
1246    }
1247    if !chunk.is_empty() {
1248        let run = write_sorted_chunk(chunk, temp, stats)?;
1249        add_sorted_run(&mut levels, run, temp, stats)?;
1250    }
1251
1252    let mut result = None;
1253    for run in levels.into_iter().flatten() {
1254        result = Some(match result {
1255            Some(existing) => merge_sorted_runs(existing, run, temp, stats)?,
1256            None => run,
1257        });
1258    }
1259    Ok(result)
1260}
1261
1262fn add_sorted_run(
1263    levels: &mut Vec<Option<ProtectedSpool>>,
1264    mut run: ProtectedSpool,
1265    temp: &TempConfig,
1266    stats: &mut SortStats,
1267) -> io::Result<()> {
1268    let mut level = 0usize;
1269    loop {
1270        if level == levels.len() {
1271            levels.push(Some(run));
1272            return Ok(());
1273        }
1274        match levels[level].take() {
1275            Some(existing) => {
1276                run = merge_sorted_runs(existing, run, temp, stats)?;
1277                level += 1;
1278            }
1279            None => {
1280                levels[level] = Some(run);
1281                return Ok(());
1282            }
1283        }
1284    }
1285}
1286
1287/// Protected disk-backed family records. Appends are externally sorted once;
1288/// final comparison can then merge parents and children in one linear pass.
1289struct FamilyValueStore {
1290    temp: TempConfig,
1291    budget: usize,
1292    spool: Option<ProtectedSpool>,
1293    sorted: Option<ProtectedSpool>,
1294    operations: u64,
1295}
1296
1297impl FamilyValueStore {
1298    fn new(temp: TempConfig, budget: usize) -> Self {
1299        Self {
1300            temp,
1301            budget,
1302            spool: None,
1303            sorted: None,
1304            operations: 0,
1305        }
1306    }
1307
1308    fn append(&mut self, key: &[u8], hash: u64, minor: (i128, u32)) -> io::Result<()> {
1309        if self.sorted.is_some() {
1310            return Err(io::Error::new(
1311                io::ErrorKind::InvalidInput,
1312                "cannot append to a finalized family index",
1313            ));
1314        }
1315        let spool = match &mut self.spool {
1316            Some(spool) => spool,
1317            None => self.spool.insert(ProtectedSpool::create(&self.temp)?),
1318        };
1319        spool.write_row(&SpooledRow {
1320            table_id: 0,
1321            row_index: hash,
1322            values: vec![
1323                GeneratedValue::Bytes(key.to_vec()),
1324                GeneratedValue::Integer(minor.0),
1325                GeneratedValue::Integer(i128::from(minor.1)),
1326            ],
1327        })
1328    }
1329
1330    fn finalize(&mut self) -> io::Result<()> {
1331        if self.sorted.is_some() || self.spool.is_none() {
1332            return Ok(());
1333        }
1334        let mut stats = SortStats::default();
1335        let Some(spool) = self.spool.take() else {
1336            return Ok(());
1337        };
1338        self.sorted = external_sort(spool, &self.temp, self.budget, &mut stats)?;
1339        self.operations += stats.operations;
1340        Ok(())
1341    }
1342
1343    fn replay(&self) -> io::Result<FamilyValueReplay> {
1344        let reader = match &self.sorted {
1345            Some(spool) => Some(SpoolReader::new(BufReader::new(std::fs::File::open(
1346                spool.path(),
1347            )?))),
1348            None => None,
1349        };
1350        Ok(FamilyValueReplay { reader })
1351    }
1352}
1353
1354struct FamilyValueReplay {
1355    reader: Option<SpoolReader<BufReader<std::fs::File>>>,
1356}
1357
1358impl Iterator for FamilyValueReplay {
1359    type Item = io::Result<FamilyValueRecord>;
1360
1361    fn next(&mut self) -> Option<Self::Item> {
1362        let reader = self.reader.as_mut()?;
1363        match reader.read_row() {
1364            Ok(Some(row)) => Some(decode_family_value(row)),
1365            Ok(None) => {
1366                self.reader = None;
1367                None
1368            }
1369            Err(error) => Some(Err(error)),
1370        }
1371    }
1372}
1373
1374fn decode_family_value(row: SpooledRow) -> io::Result<FamilyValueRecord> {
1375    let [GeneratedValue::Bytes(key), GeneratedValue::Integer(mantissa), GeneratedValue::Integer(scale)] =
1376        row.values.as_slice()
1377    else {
1378        return Err(io::Error::new(
1379            io::ErrorKind::InvalidData,
1380            "family spool record has an invalid shape",
1381        ));
1382    };
1383    let scale = u32::try_from(*scale).map_err(|_| {
1384        io::Error::new(
1385            io::ErrorKind::InvalidData,
1386            "family spool record has an invalid scale",
1387        )
1388    })?;
1389    Ok(FamilyValueRecord {
1390        hash: row.row_index,
1391        key: key.clone(),
1392        minor: (*mantissa, scale),
1393    })
1394}
1395
1396impl FamilyAcc {
1397    fn compare(&mut self) -> io::Result<(u64, bool)> {
1398        self.parent_values.finalize()?;
1399        self.child_values.finalize()?;
1400
1401        let mut failed = 0u64;
1402        let mut missing = false;
1403        let mut operations = 0u64;
1404        let mut children = self.child_values.replay()?;
1405        let mut child = next_family_record(&mut children, &mut operations)?;
1406        let mut parents = self.parent_values.replay()?;
1407        let mut parent = next_family_record(&mut parents, &mut operations)?;
1408        while let Some(first_parent) = parent.take() {
1409            while child.as_ref().is_some_and(|child| {
1410                exact_key_cmp(child.hash, &child.key, first_parent.hash, &first_parent.key)
1411                    == Ordering::Less
1412            }) {
1413                child = next_family_record(&mut children, &mut operations)?;
1414            }
1415
1416            let mut sum = None;
1417            while child.as_ref().is_some_and(|child| {
1418                exact_key_cmp(child.hash, &child.key, first_parent.hash, &first_parent.key)
1419                    == Ordering::Equal
1420            }) {
1421                let Some(contribution) = child.take().map(|child| child.minor) else {
1422                    break;
1423                };
1424                match &mut sum {
1425                    Some(acc) => add_minor(acc, contribution),
1426                    None => sum = Some(contribution),
1427                }
1428                child = next_family_record(&mut children, &mut operations)?;
1429            }
1430
1431            let mut current_parent = first_parent;
1432            loop {
1433                match sum {
1434                    Some(child) if !minor_eq(current_parent.minor, child) => failed += 1,
1435                    None if current_parent.minor.0 != 0 => {
1436                        failed += 1;
1437                        missing = true;
1438                    }
1439                    _ => {}
1440                }
1441
1442                parent = next_family_record(&mut parents, &mut operations)?;
1443                let same_key = parent.as_ref().is_some_and(|next| {
1444                    exact_key_cmp(
1445                        next.hash,
1446                        &next.key,
1447                        current_parent.hash,
1448                        &current_parent.key,
1449                    ) == Ordering::Equal
1450                });
1451                if !same_key {
1452                    break;
1453                }
1454                let Some(next_parent) = parent.take() else {
1455                    break;
1456                };
1457                current_parent = next_parent;
1458            }
1459        }
1460        self.operations = self.parent_values.operations + self.child_values.operations + operations;
1461        Ok((failed, missing))
1462    }
1463}
1464
1465fn next_family_record(
1466    replay: &mut FamilyValueReplay,
1467    operations: &mut u64,
1468) -> io::Result<Option<FamilyValueRecord>> {
1469    let Some(record) = replay.next() else {
1470        return Ok(None);
1471    };
1472    *operations += 1;
1473    record.map(Some)
1474}
1475
1476/// The whole-file audit.
1477struct Audit<'a> {
1478    spec: &'a PlanSpec,
1479    tables: HashMap<String, TableState>,
1480    families: Vec<FamilyAcc>,
1481    /// Plan tables whose DDL never appeared in the output.
1482    missing_tables: Vec<String>,
1483    /// Exact DDL disagreements between the plan and reparsed output.
1484    ddl_mismatches: Vec<String>,
1485}
1486
1487impl<'a> Audit<'a> {
1488    fn new(
1489        spec: &'a PlanSpec,
1490        schema: &Schema,
1491        source_dialect: SqlDialect,
1492        target_dialect: SqlDialect,
1493        membership_budget: usize,
1494        temp: TempConfig,
1495    ) -> Self {
1496        let mut tables = HashMap::new();
1497
1498        // Expected tables + DDL: every plan table must appear with its columns.
1499        let mut missing_tables = Vec::new();
1500        let mut ddl_mismatches = Vec::new();
1501        for table in &spec.tables {
1502            match schema.get_table_id(&table.name) {
1503                None => missing_tables.push(table.name.clone()),
1504                Some(id) => {
1505                    if let Some(reparsed) = schema.table(id) {
1506                        ddl_mismatches.extend(compare_table_ddl(
1507                            table,
1508                            reparsed,
1509                            source_dialect,
1510                            target_dialect,
1511                        ));
1512                    }
1513                }
1514            }
1515        }
1516
1517        // Which parent-column groups each table must expose for FK membership.
1518        let mut needed_parent_groups: HashMap<String, Vec<Vec<String>>> = HashMap::new();
1519        for table in &spec.tables {
1520            for rel in &table.relationships {
1521                needed_parent_groups
1522                    .entry(rel.parent_table.clone())
1523                    .or_default()
1524                    .push(rel.parent_columns.clone());
1525            }
1526        }
1527
1528        for (index, table) in spec.tables.iter().enumerate() {
1529            let unique_groups = table
1530                .unique_groups
1531                .iter()
1532                .map(|cols| GroupKey::new(cols.clone(), membership_budget, &temp))
1533                .collect();
1534
1535            let mut member_groups: Vec<GroupKey> = Vec::new();
1536            if let Some(groups) = needed_parent_groups.get(&table.name) {
1537                for cols in groups {
1538                    if !member_groups.iter().any(|g| &g.columns == cols) {
1539                        member_groups.push(GroupKey::new(cols.clone(), membership_budget, &temp));
1540                    }
1541                }
1542            }
1543            let foreign_keys = table
1544                .relationships
1545                .iter()
1546                .map(|_| KeySet::new(membership_budget, temp.clone()))
1547                .collect();
1548
1549            tables.insert(
1550                table.name.clone(),
1551                TableState {
1552                    plan_index: index,
1553                    rows: 0,
1554                    undecodable: 0,
1555                    null_violations: HashMap::new(),
1556                    character_length_violations: HashMap::new(),
1557                    integer_range_violations: HashMap::new(),
1558                    decimal_shape_violations: HashMap::new(),
1559                    arity_violations: 0,
1560                    unique_groups,
1561                    member_groups,
1562                    foreign_keys,
1563                    predicate_failures: HashMap::new(),
1564                    predicate_unevaluated: HashMap::new(),
1565                    categories: CategoryTallies::default(),
1566                },
1567            );
1568        }
1569
1570        let families = spec
1571            .families
1572            .iter()
1573            .map(|family| FamilyAcc {
1574                slug: family.slug.clone(),
1575                parent_table: family.parent_table.clone(),
1576                parent_column: family.parent_column.clone(),
1577                child_table: family.child_table.clone(),
1578                child_column: family.child_column.clone(),
1579                child_fk_columns: family.child_fk_columns.clone(),
1580                parent_key_columns: family.parent_key_columns.clone(),
1581                parent_values: FamilyValueStore::new(temp.clone(), membership_budget),
1582                child_values: FamilyValueStore::new(temp.clone(), membership_budget),
1583                inexact: false,
1584                operations: 0,
1585            })
1586            .collect();
1587
1588        Audit {
1589            spec,
1590            tables,
1591            families,
1592            missing_tables,
1593            ddl_mismatches,
1594        }
1595    }
1596
1597    /// Register the columns each sampled distribution measures so the row pass
1598    /// tallies their category counts.
1599    fn register_distributions(&mut self, distributions: &[DistributionExpectation]) {
1600        for expectation in distributions {
1601            if let Some(state) = self.tables.get_mut(&expectation.table) {
1602                state.categories.register(expectation);
1603            }
1604        }
1605    }
1606
1607    fn note_undecodable(&mut self, table: &str) {
1608        if let Some(state) = self.tables.get_mut(table) {
1609            state.rows += 1;
1610            state.undecodable += 1;
1611        }
1612    }
1613
1614    /// Observe one decoded row of `table`.
1615    fn observe_row(
1616        &mut self,
1617        table_name: &str,
1618        schema: &TableSchema,
1619        all_values: &[PkValue],
1620        column_map: &[Option<usize>],
1621    ) -> Result<(), GenerateError> {
1622        let plan_index = match self.tables.get(table_name) {
1623            Some(state) => state.plan_index,
1624            None => return Ok(()),
1625        };
1626        // Borrow the owned spec (tied to the spec's lifetime, not to `self`), so
1627        // the row-check reads below do not conflict with the mutable `self`
1628        // updates that follow.
1629        let spec = self.spec;
1630        let planned = &spec.tables[plan_index];
1631
1632        // Resolve a plan column name to its value in this row.
1633        let value_of = |name: &str| -> Option<&PkValue> {
1634            let ord = schema.get_column_id(name)?;
1635            let val_idx = column_map.get(ord.0 as usize).copied().flatten()?;
1636            all_values.get(val_idx)
1637        };
1638
1639        // Arity is fixed by compiled ownership, not learned from the first row:
1640        // every non-database-produced column must be present on every row.
1641        let observed_width = all_values.len();
1642        let arity_violation = observed_width != planned.rendered_columns.len()
1643            || planned
1644                .rendered_columns
1645                .iter()
1646                .any(|column| value_of(column).is_none());
1647
1648        // Collect the failures first (immutable borrows of the spec), then apply
1649        // them to the table's mutable state.
1650        let mut null_hits: Vec<String> = Vec::new();
1651        for col in &planned.non_null_columns {
1652            if matches!(value_of(col), None | Some(PkValue::Null)) {
1653                null_hits.push(col.clone());
1654            }
1655        }
1656        let mut character_length_hits: Vec<String> = Vec::new();
1657        for (column, limit) in &planned.character_limits {
1658            if value_of(column).is_some_and(
1659                |value| matches!(value, PkValue::Text(text) if text.chars().count() > *limit),
1660            ) {
1661                character_length_hits.push(column.clone());
1662            }
1663        }
1664        let mut integer_range_hits: Vec<String> = Vec::new();
1665        for (column, min, max) in &planned.integer_limits {
1666            let violates = match value_of(column) {
1667                Some(PkValue::Null) | None => false,
1668                Some(value) => int_of(value).is_none_or(|value| value < *min || value > *max),
1669            };
1670            if violates {
1671                integer_range_hits.push(column.clone());
1672            }
1673        }
1674        let mut decimal_shape_hits: Vec<String> = Vec::new();
1675        for (column, precision, scale) in &planned.decimal_limits {
1676            if value_of(column).is_some_and(|value| !decimal_fits(value, *precision, *scale)) {
1677                decimal_shape_hits.push(column.clone());
1678            }
1679        }
1680
1681        // Predicate evaluation. A predicate that holds but whose required inputs
1682        // include a present-but-unparseable value could not actually be
1683        // evaluated for this row — record it separately so the check is not a
1684        // silent Exact pass.
1685        let mut predicate_hits: Vec<String> = Vec::new();
1686        let mut predicate_unevaluated_hits: Vec<String> = Vec::new();
1687        for predicate in &planned.predicates {
1688            match evaluate_predicate(predicate, table_name, &value_of) {
1689                Some(slug) => predicate_hits.push(slug),
1690                None if predicate_unevaluable(predicate, &value_of) => {
1691                    predicate_unevaluated_hits.push(predicate_slug(predicate, table_name));
1692                }
1693                None => {}
1694            }
1695        }
1696
1697        // Uniqueness keys.
1698        let unique_keys: Vec<Option<(Vec<u8>, u64)>> = {
1699            let state = &self.tables[table_name];
1700            state
1701                .unique_groups
1702                .iter()
1703                .map(|group| encode_group(&group.columns, &value_of))
1704                .collect()
1705        };
1706        // Membership keys this table exposes to children.
1707        let member_keys: Vec<Option<(Vec<u8>, u64)>> = {
1708            let state = &self.tables[table_name];
1709            state
1710                .member_groups
1711                .iter()
1712                .map(|group| encode_group(&group.columns, &value_of))
1713                .collect()
1714        };
1715
1716        // FK keys are appended now and checked in one sorted merge after the
1717        // row pass. NULL composite keys remain optional and are not indexed.
1718        let foreign_keys: Vec<Option<(Vec<u8>, u64)>> = planned
1719            .relationships
1720            .iter()
1721            .map(|rel| {
1722                if is_any_null(&rel.columns, &value_of) {
1723                    None
1724                } else {
1725                    encode_group(&rel.columns, &value_of)
1726                }
1727            })
1728            .collect();
1729
1730        // Family accumulation.
1731        self.accumulate_families(table_name, &value_of)?;
1732
1733        // Sampled category tallies.
1734        let category_hits: Vec<(String, String)> = {
1735            let state = &self.tables[table_name];
1736            state
1737                .categories
1738                .expected
1739                .keys()
1740                .filter_map(|col| {
1741                    value_of(col)
1742                        .and_then(text_of)
1743                        .map(|value| (col.clone(), value))
1744                })
1745                .collect()
1746        };
1747
1748        // Now apply everything mutably.
1749        let state = self.tables.get_mut(table_name).expect("table state exists");
1750        state.rows += 1;
1751        if arity_violation {
1752            state.arity_violations += 1;
1753        }
1754        for name in null_hits {
1755            *state.null_violations.entry(name).or_insert(0) += 1;
1756        }
1757        for name in character_length_hits {
1758            *state.character_length_violations.entry(name).or_insert(0) += 1;
1759        }
1760        for name in integer_range_hits {
1761            *state.integer_range_violations.entry(name).or_insert(0) += 1;
1762        }
1763        for name in decimal_shape_hits {
1764            *state.decimal_shape_violations.entry(name).or_insert(0) += 1;
1765        }
1766        for slug in predicate_hits {
1767            *state.predicate_failures.entry(slug).or_insert(0) += 1;
1768        }
1769        for slug in predicate_unevaluated_hits {
1770            *state.predicate_unevaluated.entry(slug).or_insert(0) += 1;
1771        }
1772        for (group, key) in state.unique_groups.iter_mut().zip(unique_keys) {
1773            if let Some((bytes, hash)) = key {
1774                if !group
1775                    .index
1776                    .insert(&bytes, hash)
1777                    .map_err(membership_index_error)?
1778                {
1779                    group.duplicate = true;
1780                }
1781            }
1782        }
1783        for (group, key) in state.member_groups.iter_mut().zip(member_keys) {
1784            if let Some((bytes, hash)) = key {
1785                group
1786                    .index
1787                    .insert(&bytes, hash)
1788                    .map_err(membership_index_error)?;
1789            }
1790        }
1791        for (index, key) in state.foreign_keys.iter_mut().zip(foreign_keys) {
1792            if let Some((bytes, hash)) = key {
1793                index.append(&bytes, hash).map_err(membership_index_error)?;
1794            }
1795        }
1796        for (col, value) in category_hits {
1797            state.categories.record(&col, &value);
1798        }
1799        Ok(())
1800    }
1801
1802    /// Accumulate parent totals and child sums for every family this row
1803    /// participates in (as parent or child).
1804    fn accumulate_families<'v>(
1805        &mut self,
1806        table_name: &str,
1807        value_of: &impl Fn(&str) -> Option<&'v PkValue>,
1808    ) -> Result<(), GenerateError> {
1809        for family in &mut self.families {
1810            if family.parent_table == table_name {
1811                if let Some((key, hash)) = encode_group(&family.parent_key_columns, value_of) {
1812                    if let Some(minor) = value_of(&family.parent_column).and_then(money_minor) {
1813                        family
1814                            .parent_values
1815                            .append(&key, hash, minor)
1816                            .map_err(family_index_error)?;
1817                    } else {
1818                        family.inexact = true;
1819                    }
1820                }
1821            }
1822            if family.child_table == table_name {
1823                if let Some((key, hash)) = encode_group(&family.child_fk_columns, value_of) {
1824                    if let Some(minor) = value_of(&family.child_column).and_then(money_minor) {
1825                        family
1826                            .child_values
1827                            .append(&key, hash, minor)
1828                            .map_err(family_index_error)?;
1829                    } else {
1830                        family.inexact = true;
1831                    }
1832                }
1833            }
1834        }
1835        Ok(())
1836    }
1837
1838    /// Record the expected-tables / expected-DDL checks.
1839    fn check_expected_tables(&self, report: &mut VerificationReport) {
1840        report.record(
1841            "expected_tables".to_string(),
1842            CheckStatus::Exact,
1843            self.missing_tables.is_empty(),
1844            format!(
1845                "{} expected table(s) missing from output",
1846                self.missing_tables.len()
1847            ),
1848        );
1849        report.record(
1850            "expected_ddl".to_string(),
1851            CheckStatus::Exact,
1852            self.ddl_mismatches.is_empty(),
1853            format!(
1854                "{} DDL declaration mismatch(es) in reparsed output{}",
1855                self.ddl_mismatches.len(),
1856                self.ddl_mismatches
1857                    .first()
1858                    .map_or(String::new(), |first| format!("; first: {first}"))
1859            ),
1860        );
1861    }
1862
1863    /// Finalize every append-only key index, then evaluate child FK indexes
1864    /// against their parent membership indexes by sorted merge join.
1865    /// Returns, per table and per relationship, `Some(missing)` when the parent
1866    /// membership index was available (so the FK was actually checked) or `None`
1867    /// when the parent table was not generated (so membership is unverifiable).
1868    fn finalize_indexes(&mut self) -> Result<Vec<Vec<Option<u64>>>, GenerateError> {
1869        for state in self.tables.values_mut() {
1870            for group in &mut state.unique_groups {
1871                group.duplicate |= group.index.finalize().map_err(membership_index_error)?;
1872            }
1873            for group in &mut state.member_groups {
1874                group.index.finalize().map_err(membership_index_error)?;
1875            }
1876            for index in &mut state.foreign_keys {
1877                index.finalize().map_err(membership_index_error)?;
1878            }
1879        }
1880
1881        let mut failures = Vec::with_capacity(self.spec.tables.len());
1882        for planned in &self.spec.tables {
1883            let child = &self.tables[&planned.name];
1884            let mut relationship_failures = Vec::with_capacity(planned.relationships.len());
1885            for (relationship, child_keys) in planned.relationships.iter().zip(&child.foreign_keys)
1886            {
1887                let parent_keys = self
1888                    .tables
1889                    .get(&relationship.parent_table)
1890                    .and_then(|parent| {
1891                        parent
1892                            .member_groups
1893                            .iter()
1894                            .find(|group| group.columns == relationship.parent_columns)
1895                    });
1896                let missing = match parent_keys {
1897                    Some(parent_keys) => Some(
1898                        child_keys
1899                            .missing_from(&parent_keys.index)
1900                            .map_err(membership_index_error)?,
1901                    ),
1902                    // The parent table was not generated, so its membership index
1903                    // does not exist: the FK cannot be verified (fail-closed as
1904                    // NotChecked in `finish`, never a silent green pass).
1905                    None => None,
1906                };
1907                relationship_failures.push(missing);
1908            }
1909            failures.push(relationship_failures);
1910        }
1911        Ok(failures)
1912    }
1913
1914    /// Emit every accumulated check into the report.
1915    fn finish(
1916        &mut self,
1917        report: &mut VerificationReport,
1918        distributions: &[DistributionExpectation],
1919        output_mode: OutputMode,
1920    ) -> Result<(), GenerateError> {
1921        let foreign_key_failures = self.finalize_indexes()?;
1922        for (plan_index, planned) in self.spec.tables.iter().enumerate() {
1923            let state = &self.tables[&planned.name];
1924
1925            // Row count. INSERT and COPY output are audited the same way, so a
1926            // table that produced zero parseable rows when the plan expected some
1927            // is always a genuine failure — never masked as NotChecked.
1928            //
1929            // A family child (a `commerce.order_family` child) is the exception:
1930            // the family planner draws each parent's line count itself and spools
1931            // a variable total, so `planned.rows` (parents x mean) is only a
1932            // compile-time estimate, not an authoritative target. Its realized
1933            // count legitimately drifts under a stochastic fan-out distribution,
1934            // so the count is reported as sampled and passes whenever it is
1935            // non-empty-as-expected. The exact family-sum, arity, non-null, and
1936            // FK checks still audit that every spooled child is well-formed and
1937            // sums correctly, so a genuinely broken family cannot slip through.
1938            let expected = if output_mode == OutputMode::SchemaOnly {
1939                0
1940            } else {
1941                planned.rows
1942            };
1943            if output_mode == OutputMode::SchemaOnly {
1944                report.record(
1945                    format!("row_count:{}", planned.name),
1946                    CheckStatus::Exact,
1947                    state.rows == 0,
1948                    format!(
1949                        "schema-only output expected 0 rows, observed {}",
1950                        state.rows
1951                    ),
1952                );
1953            } else if planned.family_child {
1954                let passed = if expected == 0 {
1955                    state.rows == 0
1956                } else {
1957                    state.rows > 0
1958                };
1959                report.record(
1960                    format!("row_count:{}", planned.name),
1961                    CheckStatus::Sampled,
1962                    passed,
1963                    format!(
1964                        "planner-realized family child count; observed {} row(s) (estimate {expected})",
1965                        state.rows
1966                    ),
1967                );
1968            } else {
1969                report.record(
1970                    format!("row_count:{}", planned.name),
1971                    CheckStatus::Exact,
1972                    state.rows == expected,
1973                    format!("expected {expected} rows, observed {}", state.rows),
1974                );
1975            }
1976
1977            // Schema-only verification has no row values on which to evaluate
1978            // data invariants. The DDL and zero-row checks above are exact; do
1979            // not label absent row evidence as an exact pass.
1980            if output_mode == OutputMode::SchemaOnly {
1981                continue;
1982            }
1983
1984            // Renderability (undecodable rows).
1985            if state.undecodable > 0 {
1986                report.record(
1987                    format!("renderable:{}", planned.name),
1988                    CheckStatus::Exact,
1989                    false,
1990                    format!("{} row(s) failed to reparse", state.undecodable),
1991                );
1992            }
1993
1994            // Arity.
1995            report.record(
1996                format!("arity:{}", planned.name),
1997                CheckStatus::Exact,
1998                state.arity_violations == 0,
1999                format!(
2000                    "{} row(s) had the wrong column count",
2001                    state.arity_violations
2002                ),
2003            );
2004
2005            // Non-null (one check per non-nullable column that failed, plus an
2006            // overall pass marker).
2007            let null_failed: u64 = state.null_violations.values().sum();
2008            report.record(
2009                format!("non_null:{}", planned.name),
2010                CheckStatus::Exact,
2011                null_failed == 0,
2012                format!("{null_failed} unexpected NULL value(s) in non-nullable columns"),
2013            );
2014
2015            // Declared character limits.
2016            for (column, limit) in &planned.character_limits {
2017                let failed = state
2018                    .character_length_violations
2019                    .get(column)
2020                    .copied()
2021                    .unwrap_or(0);
2022                report.record(
2023                    format!("character_length:{}.{}", planned.name, column),
2024                    CheckStatus::Exact,
2025                    failed == 0,
2026                    format!("{failed} value(s) exceeded the declared {limit}-character limit"),
2027                );
2028            }
2029
2030            // Fixed-width integer ranges.
2031            for (column, min, max) in &planned.integer_limits {
2032                let failed = state
2033                    .integer_range_violations
2034                    .get(column)
2035                    .copied()
2036                    .unwrap_or(0);
2037                report.record(
2038                    format!("integer_range:{}.{}", planned.name, column),
2039                    CheckStatus::Exact,
2040                    failed == 0,
2041                    format!("{failed} value(s) fell outside the declared range {min}..={max}"),
2042                );
2043            }
2044
2045            // Fixed-point decimal precision and scale.
2046            for (column, precision, scale) in &planned.decimal_limits {
2047                let failed = state
2048                    .decimal_shape_violations
2049                    .get(column)
2050                    .copied()
2051                    .unwrap_or(0);
2052                report.record(
2053                    format!("decimal_shape:{}.{}", planned.name, column),
2054                    CheckStatus::Exact,
2055                    failed == 0,
2056                    format!(
2057                        "{failed} value(s) exceeded decimal({precision},{scale}) precision or scale"
2058                    ),
2059                );
2060            }
2061
2062            // Uniqueness (PK + unique constraints).
2063            for group in &state.unique_groups {
2064                let is_pk = planned.primary_key == group.columns;
2065                let kind = if is_pk { "primary_key" } else { "unique" };
2066                let composite = if group.columns.len() > 1 {
2067                    "composite_"
2068                } else {
2069                    ""
2070                };
2071                report.record(
2072                    format!(
2073                        "{composite}{kind}:{}:{}",
2074                        planned.name,
2075                        group.columns.join(",")
2076                    ),
2077                    CheckStatus::Exact,
2078                    !group.duplicate,
2079                    if group.duplicate {
2080                        "duplicate key values found".to_string()
2081                    } else {
2082                        "all key values distinct".to_string()
2083                    },
2084                );
2085            }
2086
2087            // Foreign keys / composite keys.
2088            for (relationship_index, rel) in planned.relationships.iter().enumerate() {
2089                let slug = fk_slug(&planned.name, rel);
2090                let missing = foreign_key_failures
2091                    .get(plan_index)
2092                    .and_then(|failures| failures.get(relationship_index))
2093                    .copied()
2094                    .unwrap_or(Some(0));
2095                let (status, passed, detail) = match missing {
2096                    None => (
2097                        CheckStatus::NotChecked,
2098                        false,
2099                        "parent table not generated; foreign-key membership not verified"
2100                            .to_string(),
2101                    ),
2102                    Some(failed) => (
2103                        CheckStatus::Exact,
2104                        failed == 0,
2105                        format!("{failed} foreign-key value(s) missing from the parent"),
2106                    ),
2107                };
2108                report.record(slug, status, passed, detail);
2109            }
2110
2111            // Planner predicates: report each declared predicate so a passing
2112            // invariant is visible as Exact too.
2113            let mut declared: Vec<String> = planned
2114                .predicates
2115                .iter()
2116                .map(|predicate| predicate_slug(predicate, &planned.name))
2117                .collect();
2118            declared.sort();
2119            declared.dedup();
2120            for slug in declared {
2121                let failed = state.predicate_failures.get(&slug).copied().unwrap_or(0);
2122                let unevaluated = state.predicate_unevaluated.get(&slug).copied().unwrap_or(0);
2123                let (status, passed, detail) = if failed > 0 {
2124                    (
2125                        CheckStatus::Exact,
2126                        false,
2127                        format!("{failed} row(s) violated the planner invariant"),
2128                    )
2129                } else if unevaluated > 0 {
2130                    (
2131                        CheckStatus::NotChecked,
2132                        false,
2133                        format!(
2134                            "{unevaluated} row(s) had unparseable inputs; invariant not verified"
2135                        ),
2136                    )
2137                } else {
2138                    (
2139                        CheckStatus::Exact,
2140                        true,
2141                        "0 row(s) violated the planner invariant".to_string(),
2142                    )
2143                };
2144                report.record(slug, status, passed, detail);
2145            }
2146        }
2147
2148        // Family sum checks. An unparseable/NULL money value makes a family
2149        // `inexact`: those parent groups cannot be evaluated. But `compare`
2150        // still evaluates every group it *can*, so a genuine disagreement
2151        // (`failed > 0`) must fail the check regardless — an inexact row must
2152        // never mask a real violation. Only when no disagreement is found does
2153        // `inexact` downgrade the check to `NotChecked` (couldn't fully verify).
2154        if output_mode != OutputMode::SchemaOnly {
2155            for family in &mut self.families {
2156                let (failed, missing) = family.compare().map_err(family_index_error)?;
2157                let (status, detail) = if failed > 0 {
2158                    (
2159                        CheckStatus::Exact,
2160                        format!(
2161                            "{failed} parent aggregate(s) disagreed with the child sum{}",
2162                            if missing { " (missing children)" } else { "" }
2163                        ),
2164                    )
2165                } else if family.inexact {
2166                    (
2167                        CheckStatus::NotChecked,
2168                        "family sum not evaluated (unparseable money values)".to_string(),
2169                    )
2170                } else {
2171                    (
2172                        CheckStatus::Exact,
2173                        "0 parent aggregate(s) disagreed with the child sum".to_string(),
2174                    )
2175                };
2176                report.record(family.slug.clone(), status, failed == 0, detail);
2177            }
2178        }
2179
2180        // Sampled distributions.
2181        self.finish_distributions(report, distributions, output_mode);
2182        Ok(())
2183    }
2184
2185    fn finish_distributions(
2186        &self,
2187        report: &mut VerificationReport,
2188        distributions: &[DistributionExpectation],
2189        output_mode: OutputMode,
2190    ) {
2191        for expectation in distributions {
2192            if output_mode == OutputMode::SchemaOnly {
2193                report.record(
2194                    format!("distribution:{}.{}", expectation.table, expectation.column),
2195                    CheckStatus::NotChecked,
2196                    false,
2197                    "schema-only output contains no rows to sample".to_string(),
2198                );
2199                continue;
2200            }
2201            let Some(state) = self.tables.get(&expectation.table) else {
2202                report.record(
2203                    format!("distribution:{}.{}", expectation.table, expectation.column),
2204                    CheckStatus::NotChecked,
2205                    false,
2206                    "table not present in output".to_string(),
2207                );
2208                continue;
2209            };
2210            let counts = state.categories.counts.get(&expectation.column);
2211            let total = state.rows.max(1) as f64;
2212            let mut worst = 0.0f64;
2213            if let Some(counts) = counts {
2214                for (value, expected_fraction) in &expectation.categories {
2215                    let observed = counts.get(value).copied().unwrap_or(0) as f64 / total;
2216                    worst = worst.max((observed - expected_fraction).abs());
2217                }
2218            } else {
2219                worst = 1.0;
2220            }
2221            report.record(
2222                format!("distribution:{}.{}", expectation.table, expectation.column),
2223                CheckStatus::Sampled,
2224                worst <= expectation.tolerance,
2225                format!(
2226                    "worst per-category deviation {worst:.4} vs tolerance {:.4}",
2227                    expectation.tolerance
2228                ),
2229            );
2230        }
2231    }
2232}
2233
2234// ---------------------------------------------------------------------------
2235// Predicate evaluation
2236// ---------------------------------------------------------------------------
2237
2238/// Evaluate a planner predicate on one row. Returns the check slug when the row
2239/// **violates** the predicate, or `None` when it holds (or does not apply).
2240fn evaluate_predicate<'v>(
2241    predicate: &PlannerPredicate,
2242    table: &str,
2243    value_of: &impl Fn(&str) -> Option<&'v PkValue>,
2244) -> Option<String> {
2245    let slug = predicate_slug(predicate, table);
2246    let violated = match predicate {
2247        PlannerPredicate::Equation {
2248            start,
2249            end,
2250            duration,
2251            duration_unit_nanos,
2252            end_inclusive,
2253            guard,
2254        } => {
2255            if !guard_selects(guard.as_ref(), value_of) {
2256                false
2257            } else {
2258                let (Some(start_ns), Some(dur)) = (
2259                    value_of(start).and_then(epoch_nanos),
2260                    value_of(duration).and_then(int_of),
2261                ) else {
2262                    return None;
2263                };
2264                match value_of(end).and_then(epoch_nanos) {
2265                    Some(end_ns) => {
2266                        let span = dur.saturating_mul(*duration_unit_nanos);
2267                        let expected = start_ns.saturating_add(span) - i128::from(*end_inclusive);
2268                        floor_sec(expected) != floor_sec(end_ns)
2269                    }
2270                    None => true, // guard says closed, but end is null/unparsed
2271                }
2272            }
2273        }
2274        PlannerPredicate::NullWhen { column, guard } => {
2275            guard_selects(Some(guard), value_of)
2276                && !matches!(value_of(column), Some(PkValue::Null) | None)
2277        }
2278        PlannerPredicate::NotNullWhen { column, guard } => {
2279            guard_selects(Some(guard), value_of)
2280                && matches!(value_of(column), Some(PkValue::Null) | None)
2281        }
2282        PlannerPredicate::InRange {
2283            column,
2284            min_nanos,
2285            max_nanos,
2286        } => match value_of(column).and_then(epoch_nanos) {
2287            Some(ns) => {
2288                floor_sec(ns) < floor_sec(*min_nanos) || floor_sec(ns) > floor_sec(*max_nanos)
2289            }
2290            None => false,
2291        },
2292        PlannerPredicate::CounterSum {
2293            addends,
2294            sum,
2295            guard,
2296        } => {
2297            if !guard_selects(guard.as_ref(), value_of) {
2298                false
2299            } else {
2300                let mut total = 0i128;
2301                let mut ok = true;
2302                for addend in addends {
2303                    match value_of(addend).and_then(int_of) {
2304                        Some(v) => total += v,
2305                        None => ok = false,
2306                    }
2307                }
2308                match (ok, value_of(sum).and_then(int_of)) {
2309                    (true, Some(target)) => total != target,
2310                    _ => false,
2311                }
2312            }
2313        }
2314        PlannerPredicate::NonNegative { columns } => columns
2315            .iter()
2316            .any(|col| matches!(value_of(col).and_then(int_of), Some(v) if v < 0)),
2317        PlannerPredicate::Ordering {
2318            earlier,
2319            later,
2320            guard,
2321        } => {
2322            if !guard_selects(guard.as_ref(), value_of) {
2323                false
2324            } else {
2325                match (
2326                    value_of(earlier).and_then(epoch_nanos),
2327                    value_of(later).and_then(epoch_nanos),
2328                ) {
2329                    (Some(earlier_ns), Some(later_ns)) => {
2330                        floor_sec(earlier_ns) > floor_sec(later_ns)
2331                    }
2332                    _ => false,
2333                }
2334            }
2335        }
2336    };
2337    violated.then_some(slug)
2338}
2339
2340/// Whether a guard-selected row has a required predicate input that is present
2341/// (non-null) but cannot be interpreted as the type the predicate needs. Such a
2342/// row could not actually be evaluated (as opposed to holding), so the check
2343/// must be surfaced as `NotChecked` rather than a silent Exact pass over
2344/// corruption. Predicates that only test presence/nullness (`NullWhen`,
2345/// `NotNullWhen`) and cases already treated as violations (a missing `end` in an
2346/// `Equation`) are never "unevaluable" here.
2347fn predicate_unevaluable<'v>(
2348    predicate: &PlannerPredicate,
2349    value_of: &impl Fn(&str) -> Option<&'v PkValue>,
2350) -> bool {
2351    let bad_int = |col: &str| matches!(value_of(col), Some(v) if !matches!(v, PkValue::Null) && int_of(v).is_none());
2352    let bad_ns = |col: &str| matches!(value_of(col), Some(v) if !matches!(v, PkValue::Null) && epoch_nanos(v).is_none());
2353    match predicate {
2354        PlannerPredicate::Equation {
2355            start,
2356            duration,
2357            guard,
2358            ..
2359        } => guard_selects(guard.as_ref(), value_of) && (bad_ns(start) || bad_int(duration)),
2360        PlannerPredicate::InRange { column, .. } => bad_ns(column),
2361        PlannerPredicate::CounterSum {
2362            addends,
2363            sum,
2364            guard,
2365        } => {
2366            guard_selects(guard.as_ref(), value_of)
2367                && (addends.iter().any(|a| bad_int(a)) || bad_int(sum))
2368        }
2369        PlannerPredicate::NonNegative { columns } => columns.iter().any(|c| bad_int(c)),
2370        PlannerPredicate::Ordering {
2371            earlier,
2372            later,
2373            guard,
2374        } => guard_selects(guard.as_ref(), value_of) && (bad_ns(earlier) || bad_ns(later)),
2375        PlannerPredicate::NullWhen { .. } | PlannerPredicate::NotNullWhen { .. } => false,
2376    }
2377}
2378
2379/// A stable check slug for a predicate on `table`.
2380fn predicate_slug(predicate: &PlannerPredicate, table: &str) -> String {
2381    let kind = match predicate {
2382        PlannerPredicate::Equation { .. } => "equation",
2383        PlannerPredicate::NullWhen { .. } => "null_when",
2384        PlannerPredicate::NotNullWhen { .. } => "not_null_when",
2385        PlannerPredicate::InRange { .. } => "in_range",
2386        PlannerPredicate::CounterSum { .. } => "counter_sum",
2387        PlannerPredicate::NonNegative { .. } => "non_negative",
2388        PlannerPredicate::Ordering { .. } => "ordering",
2389    };
2390    format!("planner_{kind}:{table}")
2391}
2392
2393/// Whether a guard selects the current row (a `None` guard selects every row).
2394fn guard_selects<'v>(
2395    guard: Option<&PredicateGuard>,
2396    value_of: &impl Fn(&str) -> Option<&'v PkValue>,
2397) -> bool {
2398    match guard {
2399        None => true,
2400        Some(PredicateGuard::Flag { column, value }) => {
2401            matches!(value_of(column).and_then(bool_of), Some(b) if b == *value)
2402        }
2403        Some(PredicateGuard::Null { column, is_null }) => {
2404            matches!(value_of(column), Some(PkValue::Null) | None) == *is_null
2405        }
2406        Some(PredicateGuard::Equals { column, value }) => {
2407            matches!(value_of(column).and_then(text_of), Some(v) if &v == value)
2408        }
2409    }
2410}
2411
2412// ---------------------------------------------------------------------------
2413// Value helpers
2414// ---------------------------------------------------------------------------
2415
2416/// Find a child table's relationship by declared name.
2417fn find_relationship<'t>(table: &'t PlannedTable, name: &str) -> Option<&'t CompiledRelationship> {
2418    table
2419        .relationships
2420        .iter()
2421        .find(|rel| rel.name.as_deref() == Some(name))
2422}
2423
2424/// Encode a tuple of a row's column values into canonical key bytes + hash, or
2425/// `None` if any column is missing from the row.
2426fn encode_group<'v>(
2427    columns: &[String],
2428    value_of: &impl Fn(&str) -> Option<&'v PkValue>,
2429) -> Option<(Vec<u8>, u64)> {
2430    let mut tuple: PkTuple = SmallVec::new();
2431    for col in columns {
2432        tuple.push(normalize(value_of(col)?));
2433    }
2434    let hash = hash_pk_tuple(&tuple);
2435    Some((encode_key(&tuple), hash))
2436}
2437
2438/// Whether any component of a (possibly composite) foreign key is NULL. Under
2439/// SQL `MATCH SIMPLE` (the MySQL/PostgreSQL default) a composite FK with any
2440/// NULL component is not enforced, so such a row is not checked for membership.
2441/// For a single-column key this is the same as "the key is NULL".
2442fn is_any_null<'v>(columns: &[String], value_of: &impl Fn(&str) -> Option<&'v PkValue>) -> bool {
2443    columns
2444        .iter()
2445        .any(|c| matches!(value_of(c), Some(PkValue::Null) | None))
2446}
2447
2448/// Normalize integer PkValues to `BigInt` so a parent rendered as `Int` and a
2449/// child parsed as `BigInt` (or vice versa) compare and hash identically.
2450fn normalize(value: &PkValue) -> PkValue {
2451    match value {
2452        PkValue::Int(i) => PkValue::BigInt(i128::from(*i)),
2453        other => other.clone(),
2454    }
2455}
2456
2457/// Canonical byte encoding of a normalized key tuple, for collision confirmation.
2458fn encode_key(tuple: &[PkValue]) -> Vec<u8> {
2459    let mut out = Vec::new();
2460    out.push(tuple.len() as u8);
2461    for value in tuple {
2462        match value {
2463            PkValue::Int(i) => {
2464                out.push(0);
2465                out.extend_from_slice(&i.to_le_bytes());
2466            }
2467            PkValue::BigInt(i) => {
2468                out.push(1);
2469                out.extend_from_slice(&i.to_le_bytes());
2470            }
2471            PkValue::Text(s) => {
2472                out.push(2);
2473                out.extend_from_slice(&(s.len() as u32).to_le_bytes());
2474                out.extend_from_slice(s.as_bytes());
2475            }
2476            PkValue::Null => out.push(3),
2477        }
2478    }
2479    out
2480}
2481
2482fn int_of(value: &PkValue) -> Option<i128> {
2483    match value {
2484        PkValue::Int(i) => Some(i128::from(*i)),
2485        PkValue::BigInt(i) => Some(*i),
2486        PkValue::Text(s) => s.trim().parse::<i128>().ok(),
2487        PkValue::Null => None,
2488    }
2489}
2490
2491fn text_of(value: &PkValue) -> Option<String> {
2492    match value {
2493        PkValue::Text(s) => Some(s.to_string()),
2494        PkValue::Int(i) => Some(i.to_string()),
2495        PkValue::BigInt(i) => Some(i.to_string()),
2496        PkValue::Null => None,
2497    }
2498}
2499
2500fn bool_of(value: &PkValue) -> Option<bool> {
2501    match value {
2502        PkValue::Int(0) | PkValue::BigInt(0) => Some(false),
2503        PkValue::Int(1) | PkValue::BigInt(1) => Some(true),
2504        PkValue::Text(s) => match s.trim().to_ascii_lowercase().as_str() {
2505            "1" | "true" | "t" => Some(true),
2506            "0" | "false" | "f" => Some(false),
2507            _ => None,
2508        },
2509        _ => None,
2510    }
2511}
2512
2513/// Parse a rendered timestamp string into epoch nanoseconds (UTC, second
2514/// precision). Accepts `YYYY-MM-DD HH:MM:SS`, an ISO `T` separator, and a
2515/// trailing offset.
2516fn epoch_nanos(value: &PkValue) -> Option<i128> {
2517    let text = match value {
2518        PkValue::Text(s) => s.as_ref(),
2519        _ => return None,
2520    };
2521    let text = text.trim().trim_matches('\'');
2522    // Try an explicit offset first (…%:z), then a naive UTC timestamp.
2523    for format in ["%Y-%m-%d %H:%M:%S%:z", "%Y-%m-%dT%H:%M:%S%:z"] {
2524        if let Ok(dt) = chrono::DateTime::parse_from_str(text, format) {
2525            return Some(i128::from(dt.timestamp()) * NANOS_PER_SECOND);
2526        }
2527    }
2528    for format in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"] {
2529        if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(text, format) {
2530            return Some(i128::from(dt.and_utc().timestamp()) * NANOS_PER_SECOND);
2531        }
2532    }
2533    None
2534}
2535
2536fn floor_sec(nanos: i128) -> i128 {
2537    nanos.div_euclid(NANOS_PER_SECOND) * NANOS_PER_SECOND
2538}
2539
2540/// Parse a money value into `(mantissa, scale)` minor units: `12.34` → `(1234,
2541/// 2)`, integer `5` → `(5, 0)`.
2542fn money_minor(value: &PkValue) -> Option<(i128, u32)> {
2543    match value {
2544        PkValue::Int(i) => Some((i128::from(*i), 0)),
2545        PkValue::BigInt(i) => Some((*i, 0)),
2546        PkValue::Text(s) => parse_decimal(s.trim().trim_matches('\'')),
2547        PkValue::Null => None,
2548    }
2549}
2550
2551fn decimal_fits(value: &PkValue, precision: u32, scale: u32) -> bool {
2552    // A non-null value that does not parse as a decimal counts as a violation
2553    // by design: rendering unparseable text into a decimal column is broken
2554    // output, not missing evidence (unlike the `NotChecked` downgrades used
2555    // where evidence is genuinely absent).
2556    let Some((minor, actual_scale)) = money_minor(value) else {
2557        return matches!(value, PkValue::Null);
2558    };
2559    if actual_scale > scale {
2560        return false;
2561    }
2562    let Some(rescaled) = rescale(minor, actual_scale, scale) else {
2563        return false;
2564    };
2565    let Some(limit) = 10u128.checked_pow(precision) else {
2566        // The parser's i128 representation already bounds the value more
2567        // tightly than decimal precisions above 38.
2568        return true;
2569    };
2570    rescaled.unsigned_abs() < limit
2571}
2572
2573fn parse_decimal(text: &str) -> Option<(i128, u32)> {
2574    let (sign, digits) = match text.strip_prefix('-') {
2575        Some(rest) => (-1i128, rest),
2576        None => (1, text),
2577    };
2578    match digits.split_once('.') {
2579        Some((whole, frac)) => {
2580            let scale = frac.len() as u32;
2581            let combined = format!("{whole}{frac}");
2582            combined.parse::<i128>().ok().map(|m| (sign * m, scale))
2583        }
2584        None => digits.parse::<i128>().ok().map(|m| (sign * m, 0)),
2585    }
2586}
2587
2588/// Add `add` into a running `(mantissa, scale)` accumulator, rescaling to the
2589/// larger scale so mixed-scale renderings still sum exactly.
2590fn add_minor(acc: &mut (i128, u32), add: (i128, u32)) {
2591    let scale = acc.1.max(add.1);
2592    // Saturate rather than panic on an absurd/corrupt money value; a saturated
2593    // accumulator will simply disagree with the real total (fail-closed).
2594    let a = rescale(acc.0, acc.1, scale).unwrap_or(i128::MAX);
2595    let b = rescale(add.0, add.1, scale).unwrap_or(i128::MAX);
2596    *acc = (a.saturating_add(b), scale);
2597}
2598
2599/// Scale `mantissa` from `from` to `to` decimal places, or `None` if the
2600/// widening overflows i128 (an absurdly wide scale gap or huge mantissa).
2601fn rescale(mantissa: i128, from: u32, to: u32) -> Option<i128> {
2602    10i128
2603        .checked_pow(to - from)
2604        .and_then(|factor| mantissa.checked_mul(factor))
2605}
2606
2607/// Whether two `(mantissa, scale)` money values are numerically equal. An
2608/// unrepresentable (overflowing) rescale compares unequal rather than panicking.
2609fn minor_eq(a: (i128, u32), b: (i128, u32)) -> bool {
2610    let scale = a.1.max(b.1);
2611    match (rescale(a.0, a.1, scale), rescale(b.0, b.1, scale)) {
2612        (Some(x), Some(y)) => x == y,
2613        _ => false,
2614    }
2615}
2616
2617fn fk_slug(child_table: &str, rel: &RelSpec) -> String {
2618    let composite = if rel.columns.len() > 1 {
2619        "composite_foreign_key"
2620    } else {
2621        "foreign_key"
2622    };
2623    let name = rel.name.clone().unwrap_or_else(|| rel.columns.join(","));
2624    format!("{composite}:{child_table}:{name}")
2625}
2626
2627fn open_reader(path: &Path) -> Result<std::fs::File, GenerateError> {
2628    std::fs::File::open(path).map_err(|error| {
2629        GenerateError::diagnostic(
2630            &crate::diagnostic::codes::VERIFY_IO,
2631            path.display().to_string(),
2632            format!("cannot open `{}` for verification: {error}", path.display()),
2633        )
2634    })
2635}
2636
2637fn parse_error(error: anyhow::Error) -> GenerateError {
2638    match error.downcast::<GenerateError>() {
2639        Ok(error) => error,
2640        Err(error) => GenerateError::diagnostic(
2641            &crate::diagnostic::codes::VERIFY_PARSE,
2642            "verification",
2643            error.to_string(),
2644        ),
2645    }
2646}
2647
2648fn membership_index_error(error: io::Error) -> GenerateError {
2649    GenerateError::diagnostic(
2650        &crate::diagnostic::codes::VERIFY_IO,
2651        "verification.membership",
2652        format!("membership index I/O failed: {error}"),
2653    )
2654}
2655
2656fn family_index_error(error: io::Error) -> GenerateError {
2657    GenerateError::diagnostic(
2658        &crate::diagnostic::codes::VERIFY_IO,
2659        "verification.family",
2660        format!("family index I/O failed: {error}"),
2661    )
2662}
2663
2664// ---------------------------------------------------------------------------
2665// Bounded membership/uniqueness index
2666// ---------------------------------------------------------------------------
2667
2668impl GroupKey {
2669    fn new(columns: Vec<String>, budget: usize, temp: &TempConfig) -> Self {
2670        Self {
2671            columns,
2672            index: KeySet::new(budget, temp.clone()),
2673            duplicate: false,
2674        }
2675    }
2676}
2677
2678/// The in-memory hash bucket of exact key bytes (one small-vec of colliding
2679/// keys per 64-bit hash) held while a [`KeySet`] is under budget.
2680type KeyBuckets = HashMap<u64, SmallVec<[Box<[u8]>; 1]>>;
2681
2682enum KeyStorage {
2683    Memory(KeyBuckets),
2684    UnsortedSpool(ProtectedSpool),
2685    SortedMemory(Vec<SortRecord>),
2686    SortedSpool(ProtectedSpool),
2687    Empty,
2688}
2689
2690/// An exact-in-memory, spill-to-disk collection of key tuples.
2691///
2692/// While under `budget` bytes it holds exact key bytes in memory. Once the
2693/// budget is crossed, insertion becomes append-only. Finalization external
2694/// sorts bounded chunks and pairwise-merges protected runs; uniqueness and FK
2695/// membership then use adjacent records or a linear merge join.
2696struct KeySet {
2697    budget: usize,
2698    used: usize,
2699    temp: TempConfig,
2700    storage: KeyStorage,
2701    operations: Cell<u64>,
2702}
2703
2704impl KeySet {
2705    fn new(budget: usize, temp: TempConfig) -> Self {
2706        Self {
2707            budget,
2708            used: 0,
2709            temp,
2710            storage: KeyStorage::Memory(HashMap::new()),
2711            operations: Cell::new(0),
2712        }
2713    }
2714
2715    /// Insert a key; returns `Ok(true)` if newly added, `Ok(false)` if an exact
2716    /// duplicate was already present.
2717    fn insert(&mut self, key: &[u8], hash: u64) -> io::Result<bool> {
2718        let mut spill = false;
2719        match &mut self.storage {
2720            KeyStorage::Memory(memory) => {
2721                let bucket = memory.entry(hash).or_default();
2722                if bucket.iter().any(|existing| existing.as_ref() == key) {
2723                    return Ok(false);
2724                }
2725                bucket.push(key.into());
2726                self.used += key.len() + 24;
2727                spill = self.used > self.budget;
2728            }
2729            KeyStorage::UnsortedSpool(spool) => write_key(spool, hash, key)?,
2730            KeyStorage::SortedMemory(_) | KeyStorage::SortedSpool(_) | KeyStorage::Empty => {
2731                return Err(io::Error::new(
2732                    io::ErrorKind::InvalidInput,
2733                    "cannot insert into a finalized key index",
2734                ));
2735            }
2736        }
2737        if spill {
2738            self.spill()?;
2739        }
2740        Ok(true)
2741    }
2742
2743    /// Append a key while retaining duplicates, used for child FK occurrences.
2744    fn append(&mut self, key: &[u8], hash: u64) -> io::Result<()> {
2745        let mut spill = false;
2746        match &mut self.storage {
2747            KeyStorage::Memory(memory) => {
2748                memory.entry(hash).or_default().push(key.into());
2749                self.used += key.len() + 24;
2750                spill = self.used > self.budget;
2751            }
2752            KeyStorage::UnsortedSpool(spool) => write_key(spool, hash, key)?,
2753            KeyStorage::SortedMemory(_) | KeyStorage::SortedSpool(_) | KeyStorage::Empty => {
2754                return Err(io::Error::new(
2755                    io::ErrorKind::InvalidInput,
2756                    "cannot append to a finalized key index",
2757                ));
2758            }
2759        }
2760        if spill {
2761            self.spill()?;
2762        }
2763        Ok(())
2764    }
2765
2766    /// Move the in-memory keys to a fresh protected spool and switch modes.
2767    fn spill(&mut self) -> io::Result<()> {
2768        let storage = std::mem::replace(&mut self.storage, KeyStorage::Empty);
2769        let KeyStorage::Memory(memory) = storage else {
2770            self.storage = storage;
2771            return Ok(());
2772        };
2773        let mut spool = ProtectedSpool::create(&self.temp)?;
2774        for (hash, bucket) in memory {
2775            for key in bucket {
2776                write_key(&mut spool, hash, &key)?;
2777            }
2778        }
2779        spool.flush()?;
2780        self.storage = KeyStorage::UnsortedSpool(spool);
2781        Ok(())
2782    }
2783
2784    /// Finalize the index and report whether any exact duplicate exists.
2785    fn finalize(&mut self) -> io::Result<bool> {
2786        let storage = std::mem::replace(&mut self.storage, KeyStorage::Empty);
2787        self.storage = match storage {
2788            KeyStorage::Memory(memory) => {
2789                let mut records: Vec<SortRecord> = memory
2790                    .into_iter()
2791                    .flat_map(|(hash, bucket)| {
2792                        bucket.into_iter().map(move |key| SortRecord {
2793                            hash,
2794                            key: key.into_vec(),
2795                            payload: Vec::new(),
2796                        })
2797                    })
2798                    .collect();
2799                records.sort_unstable_by(sort_record_cmp);
2800                KeyStorage::SortedMemory(records)
2801            }
2802            KeyStorage::UnsortedSpool(spool) => {
2803                let mut stats = SortStats::default();
2804                let sorted = external_sort(spool, &self.temp, self.budget, &mut stats)?;
2805                self.operations
2806                    .set(self.operations.get() + stats.operations);
2807                match sorted {
2808                    Some(spool) => KeyStorage::SortedSpool(spool),
2809                    None => KeyStorage::SortedMemory(Vec::new()),
2810                }
2811            }
2812            finalized @ (KeyStorage::SortedMemory(_) | KeyStorage::SortedSpool(_)) => finalized,
2813            KeyStorage::Empty => KeyStorage::SortedMemory(Vec::new()),
2814        };
2815
2816        let mut replay = self.replay()?;
2817        let mut previous: Option<SortRecord> = None;
2818        let mut duplicate = false;
2819        let mut operations = 0u64;
2820        for record in &mut replay {
2821            let record = record?;
2822            operations += 1;
2823            if previous.as_ref().is_some_and(|previous| {
2824                exact_key_cmp(previous.hash, &previous.key, record.hash, &record.key)
2825                    == Ordering::Equal
2826            }) {
2827                duplicate = true;
2828            }
2829            previous = Some(record);
2830        }
2831        self.operations.set(self.operations.get() + operations);
2832        Ok(duplicate)
2833    }
2834
2835    fn replay(&self) -> io::Result<SortedRecordReplay<'_>> {
2836        match &self.storage {
2837            KeyStorage::SortedMemory(records) => Ok(SortedRecordReplay::Memory(records.iter())),
2838            KeyStorage::SortedSpool(spool) => Ok(SortedRecordReplay::Spool(SpoolReader::new(
2839                BufReader::new(std::fs::File::open(spool.path())?),
2840            ))),
2841            _ => Err(io::Error::new(
2842                io::ErrorKind::InvalidInput,
2843                "key index must be finalized before replay",
2844            )),
2845        }
2846    }
2847
2848    /// Count child-key occurrences absent from the finalized parent set.
2849    fn missing_from(&self, parent: &Self) -> io::Result<u64> {
2850        let mut children = self.replay()?;
2851        let mut parents = parent.replay()?;
2852        let mut operations = 0u64;
2853        let mut parent_record = next_sorted_record(&mut parents, &mut operations)?;
2854        let mut missing = 0u64;
2855
2856        while let Some(child) = next_sorted_record(&mut children, &mut operations)? {
2857            while parent_record.as_ref().is_some_and(|parent| {
2858                exact_key_cmp(parent.hash, &parent.key, child.hash, &child.key) == Ordering::Less
2859            }) {
2860                parent_record = next_sorted_record(&mut parents, &mut operations)?;
2861            }
2862            if !parent_record.as_ref().is_some_and(|parent| {
2863                exact_key_cmp(parent.hash, &parent.key, child.hash, &child.key) == Ordering::Equal
2864            }) {
2865                missing += 1;
2866            }
2867        }
2868        self.operations.set(self.operations.get() + operations);
2869        Ok(missing)
2870    }
2871
2872    #[cfg(test)]
2873    fn sort_operations(&self) -> u64 {
2874        self.operations.get()
2875    }
2876
2877    #[cfg(test)]
2878    fn spilled_memory_entries(&self) -> usize {
2879        match &self.storage {
2880            KeyStorage::Memory(buckets) => buckets.values().map(SmallVec::len).sum(),
2881            _ => 0,
2882        }
2883    }
2884}
2885
2886enum SortedRecordReplay<'a> {
2887    Memory(std::slice::Iter<'a, SortRecord>),
2888    Spool(SpoolReader<BufReader<std::fs::File>>),
2889}
2890
2891impl Iterator for SortedRecordReplay<'_> {
2892    type Item = io::Result<SortRecord>;
2893
2894    fn next(&mut self) -> Option<Self::Item> {
2895        match self {
2896            Self::Memory(records) => records.next().cloned().map(Ok),
2897            Self::Spool(reader) => match reader.read_row() {
2898                Ok(Some(row)) => Some(SortRecord::from_spooled(row)),
2899                Ok(None) => None,
2900                Err(error) => Some(Err(error)),
2901            },
2902        }
2903    }
2904}
2905
2906fn next_sorted_record(
2907    replay: &mut SortedRecordReplay<'_>,
2908    operations: &mut u64,
2909) -> io::Result<Option<SortRecord>> {
2910    let Some(record) = replay.next() else {
2911        return Ok(None);
2912    };
2913    *operations += 1;
2914    record.map(Some)
2915}
2916
2917fn write_key(spool: &mut ProtectedSpool, hash: u64, key: &[u8]) -> io::Result<()> {
2918    let row = SpooledRow {
2919        table_id: 0,
2920        row_index: hash,
2921        values: vec![GeneratedValue::Bytes(key.to_vec())],
2922    };
2923    spool.write_row(&row)
2924}
2925
2926#[cfg(test)]
2927mod tests {
2928    use super::*;
2929
2930    #[test]
2931    fn money_comparison_does_not_overflow_on_absurd_values() {
2932        // A huge mantissa or a wide scale gap must not panic; an
2933        // unrepresentable comparison is treated as unequal (fail-closed), never
2934        // a false match.
2935        assert!(!minor_eq((i128::MAX, 0), (1, 18)));
2936        assert!(!minor_eq((1, 0), (1, 40)));
2937        // Ordinary values still compare correctly.
2938        assert!(minor_eq((100, 2), (1000, 3)));
2939        assert!(!minor_eq((100, 2), (200, 2)));
2940    }
2941
2942    #[test]
2943    fn spilled_key_set_does_not_retain_one_memory_entry_per_key() {
2944        let dir = tempfile::tempdir().unwrap();
2945        let mut keys = KeySet::new(0, TempConfig::in_dir(dir.path()));
2946
2947        for key in 0u64..256 {
2948            let bytes = key.to_le_bytes();
2949            keys.insert(&bytes, key).unwrap();
2950        }
2951
2952        assert_eq!(keys.spilled_memory_entries(), 0);
2953        assert!(!keys.finalize().unwrap());
2954    }
2955
2956    #[test]
2957    fn spilled_key_sort_and_fk_merge_work_is_subquadratic() {
2958        let dir = tempfile::tempdir().unwrap();
2959        let temp = TempConfig::in_dir(dir.path());
2960        let count = 1_024u64;
2961        let mut unique = KeySet::new(0, temp.clone());
2962        let mut parents = KeySet::new(0, temp.clone());
2963        let mut children = KeySet::new(0, temp);
2964
2965        for key in 0..count {
2966            let bytes = key.to_le_bytes();
2967            unique.insert(&bytes, key).unwrap();
2968            parents.insert(&bytes, key).unwrap();
2969            children.append(&bytes, key).unwrap();
2970        }
2971        unique
2972            .insert(&(count - 1).to_le_bytes(), count - 1)
2973            .unwrap();
2974        children.append(&count.to_le_bytes(), count).unwrap();
2975
2976        assert!(unique.finalize().unwrap(), "spilled duplicate was missed");
2977        assert!(!parents.finalize().unwrap());
2978        assert!(!children.finalize().unwrap());
2979        assert_eq!(children.missing_from(&parents).unwrap(), 1);
2980
2981        let record_io =
2982            unique.sort_operations() + parents.sort_operations() + children.sort_operations();
2983        assert!(
2984            record_io < count * 3 * 32,
2985            "external sort/merge did {record_io} record operations for {count} keys per set"
2986        );
2987    }
2988
2989    #[test]
2990    fn spilled_family_merge_work_is_subquadratic() {
2991        let dir = tempfile::tempdir().unwrap();
2992        let temp = TempConfig::in_dir(dir.path());
2993        let count = 512u64;
2994        let mut family = FamilyAcc {
2995            slug: "family_sum:orders:total->order_items:total".into(),
2996            parent_table: "orders".into(),
2997            parent_column: "total".into(),
2998            child_table: "order_items".into(),
2999            child_column: "total".into(),
3000            child_fk_columns: vec!["order_id".into()],
3001            parent_key_columns: vec!["id".into()],
3002            parent_values: FamilyValueStore::new(temp.clone(), 0),
3003            child_values: FamilyValueStore::new(temp, 0),
3004            inexact: false,
3005            operations: 0,
3006        };
3007
3008        for key in 0..count {
3009            family
3010                .parent_values
3011                .append(&key.to_le_bytes(), key, (2, 0))
3012                .unwrap();
3013        }
3014        // A corrupt duplicate parent is reported by the independent uniqueness
3015        // check; the family check must still compare the same child sum to both
3016        // parent records, matching the exact pre-sort behavior.
3017        family
3018            .parent_values
3019            .append(&0u64.to_le_bytes(), 0, (2, 0))
3020            .unwrap();
3021        for key in (0..count).rev() {
3022            family
3023                .child_values
3024                .append(&key.to_le_bytes(), key, (1, 0))
3025                .unwrap();
3026            family
3027                .child_values
3028                .append(&key.to_le_bytes(), key, (1, 0))
3029                .unwrap();
3030        }
3031
3032        assert_eq!(family.compare().unwrap(), (0, false));
3033        let records = count * 3 + 1;
3034        assert!(
3035            family.operations < records * 32,
3036            "family external sort/merge did {} record operations for {records} records",
3037            family.operations
3038        );
3039    }
3040
3041    #[test]
3042    fn category_tallies_retain_only_configured_values() {
3043        let mut tallies = CategoryTallies::default();
3044        tallies.register(&DistributionExpectation {
3045            table: "events".into(),
3046            column: "kind".into(),
3047            categories: vec![("configured".into(), 1.0)],
3048            tolerance: 0.1,
3049        });
3050
3051        for value in 0..10_000 {
3052            tallies.record("kind", &value.to_string());
3053        }
3054        tallies.record("kind", "configured");
3055
3056        assert_eq!(tallies.counts["kind"].len(), 1);
3057        assert_eq!(tallies.counts["kind"]["configured"], 1);
3058    }
3059}