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