Skip to main content

sql_splitter/generate/
compiler.rs

1//! The [`ModelCompiler`]: turns a complete model plus CLI options into an
2//! immutable [`GenerationPlan`].
3//!
4//! Compilation is two concerns woven together:
5//!
6//! * **Selection** — `--tables`/`--exclude` globs choose the tables to
7//!   generate; a selected table whose required parent was excluded is a
8//!   `GEN-EXCLUDED-DEPENDENCY` error reporting the full dependency path.
9//! * **Exact counts** — every selected table gets a single resolved integer
10//!   row count. Roots resolve from their model count through the global
11//!   `--scale`/`--rows` control, a per-table `--table-rows`/`--table-scale`
12//!   override, and finally the `--max-rows` cap. Relationship children derive
13//!   from their *final* parent count times the stored fan-out mean — the
14//!   global control is never applied a second time — then take their own
15//!   override and cap. Fractional targets are stochastically rounded on a
16//!   stable per-table [`StreamId::rounding`] stream, so a run is reproducible.
17//!
18//! * **Ownership, types, and dependencies** — every column gets exactly one
19//!   owner: an explicit generator, a table planner, a declared relationship, a
20//!   database default, or the database itself (identity/serial, computed, or a
21//!   bare integer primary key). Two owners claiming one column is a
22//!   `GEN-COLUMN-OWNER-CONFLICT`; a column no rule or structural schema fact can
23//!   supply is a `GEN-COLUMN-OWNER-MISSING`. Generators/modifiers are
24//!   type-checked against their descriptor's accepted families, and the
25//!   column/planner read→write graph is scanned for cycles
26//!   (`GEN-COLUMN-CYCLE`), except a cycle a single planner owns end-to-end.
27//!
28//! Errors are gathered, not short-circuited: a model with a count conflict and
29//! three excluded dependencies reports all four. Warnings (e.g. a `--max-rows`
30//! cap) survive a successful compile via [`GenerationPlan::diagnostics`].
31
32use std::cmp::Reverse;
33use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
34
35use glob::Pattern;
36use rand::RngExt;
37
38use crate::diagnostic::{DiagnosticBag, Severity, SourceLocation};
39use crate::parser::SqlDialect;
40use crate::synthetic::model::{
41    ChildDistribution, InferenceMode, ModifierConfig, PlannerConfig, RelationshipModel, RowsModel,
42    SyntheticModel, TableModel, TableSeed, MAX_OUTPUT_BATCH_SIZE,
43};
44use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
45
46use super::plan::{
47    ColumnOwner, CompiledOutput, CompiledRelationship, ExecutionPhase, FamilyPhase, GenerationPlan,
48    PlanEstimates, PlannedColumn, PlannedTable, RelationshipDistribution, ResolvedTableSeed,
49};
50use super::registry::{
51    ColumnScope, CompileContext, CompiledModifier, CompiledPlanner, ExtensionRegistry,
52};
53use super::seed::{SeedRoot, StreamId};
54
55/// A single per-table count override from the CLI (`--table-rows` or
56/// `--table-scale`).
57#[derive(Debug, Clone, PartialEq)]
58pub struct TableCountOverride {
59    /// The table the override targets.
60    pub table: String,
61    /// Whether it pins an absolute count or a table-local scale.
62    pub kind: TableCountKind,
63}
64
65/// The two shapes of a per-table count override.
66#[derive(Debug, Clone, PartialEq)]
67pub enum TableCountKind {
68    /// `--table-rows`: an absolute row count that is never re-scaled.
69    Rows(u64),
70    /// `--table-scale`: a table-local scale that replaces the global control
71    /// on a root, or multiplies the derived count on a child.
72    Scale(f64),
73}
74
75impl TableCountOverride {
76    /// A `--table-rows` override pinning `table` to an absolute count.
77    pub fn rows(table: impl Into<String>, rows: u64) -> Self {
78        Self {
79            table: table.into(),
80            kind: TableCountKind::Rows(rows),
81        }
82    }
83
84    /// A `--table-scale` override applying `scale` to `table`.
85    pub fn scale(table: impl Into<String>, scale: f64) -> Self {
86        Self {
87            table: table.into(),
88            kind: TableCountKind::Scale(scale),
89        }
90    }
91}
92
93/// The CLI-supplied knobs a compile honors, mapping one-to-one onto the
94/// generation command's count and selection flags.
95#[derive(Debug, Clone, Default)]
96pub struct CompileOptions {
97    /// Run root seed (`--seed`); overrides the model's `seed`.
98    pub seed: Option<u64>,
99    /// Global multiplicative scale (`--scale`); conflicts with `rows`.
100    pub scale: Option<f64>,
101    /// Global absolute root count (`--rows`); conflicts with `scale`.
102    pub rows: Option<u64>,
103    /// Upper bound applied to every table last (`--max-rows`).
104    pub max_rows: Option<u64>,
105    /// Per-table count overrides (`--table-rows`/`--table-scale`).
106    pub table_rows: Vec<TableCountOverride>,
107    /// Table-selection globs (`--tables`); empty selects every table.
108    pub tables: Vec<String>,
109    /// Table-exclusion globs (`--exclude`).
110    pub exclude: Vec<String>,
111    /// The exact in-memory byte budget for each correlated family's buffered
112    /// child rows (`--family-budget`). `None` uses a large default; a small
113    /// value forces the family spill path. Byte-for-byte output is independent
114    /// of this budget — only where child rows are held changes.
115    pub family_budget_bytes: Option<u64>,
116}
117
118/// The default per-family in-memory budget when none is pinned.
119const DEFAULT_FAMILY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
120
121/// Compiles a [`SyntheticModel`] into a [`GenerationPlan`].
122///
123/// Holds the [`ExtensionRegistry`] used to resolve column generators and
124/// planners while compiling structure, counts, ownership, and dependencies.
125pub struct ModelCompiler {
126    registry: ExtensionRegistry,
127}
128
129impl ModelCompiler {
130    /// A compiler backed by an explicit registry.
131    pub fn new(registry: ExtensionRegistry) -> Self {
132        Self { registry }
133    }
134
135    /// A compiler backed by [`ExtensionRegistry::standard`].
136    pub fn standard() -> Self {
137        Self::new(ExtensionRegistry::standard())
138    }
139
140    /// The registry this compiler resolves operators against.
141    pub fn registry(&self) -> &ExtensionRegistry {
142        &self.registry
143    }
144
145    /// Compile `model` under `options`, gathering every independent error
146    /// before returning `Err`. On success, warnings survive in
147    /// [`GenerationPlan::diagnostics`].
148    pub fn compile(
149        &self,
150        model: SyntheticModel,
151        options: CompileOptions,
152    ) -> Result<GenerationPlan, DiagnosticBag> {
153        let mut bag = DiagnosticBag::default();
154
155        if let Some(source) = &model.source {
156            if source.dialect.parse::<SqlDialect>().is_err() {
157                bag.error(
158                    crate::diagnostic::codes::DIALECT_INVALID.code,
159                    "source.dialect",
160                    format!(
161                        "unsupported source dialect `{}`; expected mysql, postgres, sqlite, or mssql",
162                        source.dialect
163                    ),
164                );
165            }
166        }
167        if let Some(dialect) = &model.output.dialect {
168            if dialect.parse::<SqlDialect>().is_err() {
169                bag.error(
170                    crate::diagnostic::codes::DIALECT_INVALID.code,
171                    "output.dialect",
172                    format!(
173                        "unsupported output dialect `{dialect}`; expected mysql, postgres, sqlite, or mssql"
174                    ),
175                );
176            }
177        }
178        if let Some(batch_size) = model.output.batch_size {
179            if batch_size == 0 || batch_size > MAX_OUTPUT_BATCH_SIZE {
180                bag.error(
181                    crate::diagnostic::codes::OUTPUT_BATCH_SIZE.code,
182                    "output.batch_size",
183                    format!(
184                        "output batch size must be between 1 and {MAX_OUTPUT_BATCH_SIZE} (got {batch_size})"
185                    ),
186                );
187            }
188        }
189
190        if options.scale.is_some() && options.rows.is_some() {
191            bag.error(
192                crate::diagnostic::codes::COUNT_CONTROL_CONFLICT.code,
193                "options",
194                "`--scale` and `--rows` are mutually exclusive global row controls",
195            );
196        }
197        if let Some(scale) = options.scale {
198            // A negative or non-finite global scale would silently floor every
199            // table to zero rows; reject it instead.
200            if !scale.is_finite() || scale < 0.0 {
201                bag.error(
202                    crate::diagnostic::codes::TABLE_SCALE_INVALID.code,
203                    "options",
204                    format!("`--scale` must be a finite, non-negative number (got {scale})"),
205                );
206            }
207        }
208
209        let overrides = self.collect_table_overrides(&options, &mut bag);
210        let selected = self.select_tables(&model, &options, &mut bag);
211        // Ordering edges (`All`) include every foreign key so a present parent is
212        // still generated before its child; only *required* edges (non-null FKs,
213        // relation.children parents, polymorphic targets) make an excluded
214        // dependency a hard `GEN-EXCLUDED-DEPENDENCY`. A nullable FK to an
215        // excluded table is detached (with a warning) in `plan_table` instead.
216        let all_parents = parent_edges(&model, EdgeKind::All);
217        let required = parent_edges(&model, EdgeKind::Required);
218        self.report_excluded_dependencies(&selected, &required, &mut bag);
219        // Preserve original DDL byte-for-byte only when the ENTIRE source schema
220        // survives selection; once any table is excluded, every retained table is
221        // rendered from its normalized schema (see `plan_table`).
222        let schema_changed = selected.len() < model.tables.len();
223
224        // Resolve an omitted model seed once per compilation so every inherited
225        // table shares one fresh run root. Explicit `seed: null` tables draw
226        // their own independent roots in `resolve_seed` below.
227        let root_seed = options.seed.or(model.seed).unwrap_or_else(rand::random);
228        let rounding_root = SeedRoot::new(root_seed);
229        let (mut order, mut cyclic) = topo_order(&selected, &all_parents);
230        if !cyclic.is_empty() {
231            // A cycle under the full edge set may consist only of nullable
232            // foreign keys, which do not constrain generation order (values index
233            // into the parent key domain, and the FK can be NULL/deferred at
234            // load). Retry using only *required* edges — non-null FKs,
235            // relation.children parents, polymorphic targets. If that graph is
236            // acyclic, the cycle was purely nullable FKs: order by required edges
237            // and warn that the cyclic tables are not parent-before-child.
238            let (required_order, required_cyclic) = topo_order(&selected, &required);
239            if required_cyclic.is_empty() {
240                order = required_order;
241                cyclic = Vec::new();
242                bag.warning(
243                    crate::diagnostic::codes::FOREIGN_KEY_CYCLE.code,
244                    "tables",
245                    "nullable foreign keys form a dependency cycle; the cyclic tables cannot all be ordered parent-before-child in the output",
246                );
247            }
248        }
249        if !cyclic.is_empty() {
250            // A cycle remains among required dependencies: either mutual
251            // relation.children counts (each table's count derives from a parent
252            // that ultimately derives from it, which would silently yield zero
253            // rows) or a non-null foreign-key cycle. Neither can be resolved in a
254            // single ordered pass.
255            bag.error(
256                crate::diagnostic::codes::ROWS_CYCLE.code,
257                "tables",
258                format!(
259                    "required dependencies (non-null foreign keys or relation.children row counts) form a cycle among tables: {}; each derives from a parent that ultimately derives from it",
260                    cyclic.join(", ")
261                ),
262            );
263        }
264
265        let family_ctx = self.collect_family_facts(&model, &mut bag);
266        let family_budget_bytes = options
267            .family_budget_bytes
268            .unwrap_or(DEFAULT_FAMILY_BUDGET_BYTES);
269
270        let mut resolved: BTreeMap<String, u64> = BTreeMap::new();
271        let mut tables: Vec<PlannedTable> = Vec::with_capacity(order.len());
272
273        for name in &order {
274            let table = &model.tables[name];
275            let count = self.resolve_count(
276                &model,
277                name,
278                table,
279                &options,
280                overrides.get(name),
281                rounding_root,
282                &resolved,
283                &mut bag,
284            );
285            resolved.insert(name.clone(), count);
286            tables.push(self.plan_table(
287                &model,
288                name,
289                table,
290                count,
291                root_seed,
292                model.defaults.inference,
293                &family_ctx,
294                &resolved,
295                &selected,
296                !schema_changed,
297                options.max_rows,
298                &mut bag,
299            ));
300        }
301
302        let phases = build_phases(&order, &family_ctx, family_budget_bytes, &mut bag);
303
304        let estimates = PlanEstimates {
305            total_rows: resolved.values().copied().fold(0u64, u64::saturating_add),
306            ..PlanEstimates::default()
307        };
308
309        if bag.has_errors() {
310            return Err(bag);
311        }
312
313        // Drain warnings so they reach the CLI/JSON report even though the
314        // compile succeeded. (A merge, when wired ahead of the compiler, feeds
315        // its warning-only bag through this same channel.)
316        let diagnostics = bag
317            .diagnostics
318            .into_iter()
319            .filter(|diagnostic| diagnostic.severity == Severity::Warning)
320            .collect();
321
322        Ok(GenerationPlan {
323            input_dialect: model
324                .source
325                .as_ref()
326                .and_then(|source| source.dialect.parse().ok()),
327            output: compile_output(&model),
328            tables,
329            phases,
330            diagnostics,
331            estimates,
332            family_budget_bytes,
333        })
334    }
335
336    /// Fold the flat `--table-rows`/`--table-scale` list into a per-table
337    /// view, reporting `--table-rows` + `--table-scale` on the same table as
338    /// `GEN-TABLE-COUNT-CONFLICT`.
339    fn collect_table_overrides(
340        &self,
341        options: &CompileOptions,
342        bag: &mut DiagnosticBag,
343    ) -> BTreeMap<String, TableOverride> {
344        let mut map: BTreeMap<String, TableOverride> = BTreeMap::new();
345        for over in &options.table_rows {
346            let entry = map.entry(over.table.clone()).or_default();
347            match over.kind {
348                TableCountKind::Rows(rows) => entry.rows = Some(rows),
349                TableCountKind::Scale(scale) => entry.scale = Some(scale),
350            }
351        }
352        for (table, over) in &map {
353            if over.rows.is_some() && over.scale.is_some() {
354                bag.error(
355                    crate::diagnostic::codes::TABLE_COUNT_CONFLICT.code,
356                    format!("tables.{table}"),
357                    format!(
358                        "table `{table}` has both `--table-rows` and `--table-scale`; they are mutually exclusive"
359                    ),
360                );
361            }
362        }
363        map
364    }
365
366    /// Apply the `--tables`/`--exclude` globs to choose the generated set.
367    fn select_tables(
368        &self,
369        model: &SyntheticModel,
370        options: &CompileOptions,
371        bag: &mut DiagnosticBag,
372    ) -> BTreeSet<String> {
373        let includes = compile_globs(&options.tables, bag);
374        let excludes = compile_globs(&options.exclude, bag);
375        model
376            .tables
377            .keys()
378            .filter(|name| {
379                let included =
380                    includes.is_empty() || includes.iter().any(|pattern| pattern.matches(name));
381                let excluded = excludes.iter().any(|pattern| pattern.matches(name));
382                included && !excluded
383            })
384            .cloned()
385            .collect()
386    }
387
388    /// Report, for each selected table, any required dependency that is not in
389    /// the selected set — with the full path from the table to the excluded
390    /// dependency. Never re-adds an excluded table.
391    fn report_excluded_dependencies(
392        &self,
393        selected: &BTreeSet<String>,
394        parents: &BTreeMap<String, BTreeSet<String>>,
395        bag: &mut DiagnosticBag,
396    ) {
397        for start in selected {
398            let mut reported: BTreeSet<String> = BTreeSet::new();
399            let mut visited: BTreeSet<String> = BTreeSet::new();
400            let mut stack: Vec<Vec<String>> = vec![vec![start.clone()]];
401            while let Some(path) = stack.pop() {
402                let node = path.last().expect("path is never empty");
403                let Some(node_parents) = parents.get(node) else {
404                    continue;
405                };
406                for parent in node_parents {
407                    let mut extended = path.clone();
408                    extended.push(parent.clone());
409                    if selected.contains(parent) {
410                        if visited.insert(parent.clone()) {
411                            stack.push(extended);
412                        }
413                    } else if reported.insert(parent.clone()) {
414                        bag.error(
415                            crate::diagnostic::codes::EXCLUDED_DEPENDENCY.code,
416                            format!("tables.{start}"),
417                            format!(
418                                "table `{start}` requires excluded table `{parent}` via dependency path {}",
419                                extended.join(" -> ")
420                            ),
421                        );
422                    }
423                }
424            }
425        }
426    }
427
428    /// Resolve one table's exact row count, appending any diagnostics.
429    #[allow(clippy::too_many_arguments)]
430    fn resolve_count(
431        &self,
432        model: &SyntheticModel,
433        name: &str,
434        table: &TableModel,
435        options: &CompileOptions,
436        over: Option<&TableOverride>,
437        rounding_root: SeedRoot,
438        resolved: &BTreeMap<String, u64>,
439        bag: &mut DiagnosticBag,
440    ) -> u64 {
441        match &table.rows {
442            RowsModel::RelationChildren {
443                parent,
444                distribution,
445                ..
446            } => self.resolve_child_count(
447                name,
448                parent,
449                distribution,
450                options,
451                over,
452                rounding_root,
453                resolved,
454                bag,
455            ),
456            rows => self.resolve_root_count(model, name, rows, options, over, rounding_root, bag),
457        }
458    }
459
460    #[allow(clippy::too_many_arguments)]
461    fn resolve_root_count(
462        &self,
463        model: &SyntheticModel,
464        name: &str,
465        rows: &RowsModel,
466        options: &CompileOptions,
467        over: Option<&TableOverride>,
468        rounding_root: SeedRoot,
469        bag: &mut DiagnosticBag,
470    ) -> u64 {
471        if matches!(rows, RowsModel::Observed { .. }) && !has_observed_provenance(model, name) {
472            bag.error(
473                crate::diagnostic::codes::ROWS_OBSERVED_MISSING.code,
474                format!("tables.{name}.rows"),
475                format!(
476                    "table `{name}` uses `rows.kind: observed` but the model has no attached source or profile to resolve the observed count from"
477                ),
478            );
479        }
480
481        let base = declared_count(rows).unwrap_or(0) as f64;
482
483        // Global control (scale XOR rows); conflict already reported upstream.
484        let mut target = match (options.scale, options.rows) {
485            (Some(scale), _) => base * scale,
486            (None, Some(rows)) => rows as f64,
487            (None, None) => base,
488        };
489
490        // Root per-table override: absolute rows win outright; a table-scale
491        // replaces the global control and re-scales the untouched base.
492        match over.map(TableOverride::effective) {
493            Some(EffectiveOverride::Rows(rows)) => target = rows as f64,
494            Some(EffectiveOverride::Scale(scale)) => target = base * scale,
495            None | Some(EffectiveOverride::Conflict) => {}
496        }
497
498        let count = stochastic_round(target, rounding_root, name);
499        apply_max_rows(count, options.max_rows, name, bag)
500    }
501
502    #[allow(clippy::too_many_arguments)]
503    fn resolve_child_count(
504        &self,
505        name: &str,
506        parent: &str,
507        distribution: &ChildDistribution,
508        options: &CompileOptions,
509        over: Option<&TableOverride>,
510        rounding_root: SeedRoot,
511        resolved: &BTreeMap<String, u64>,
512        bag: &mut DiagnosticBag,
513    ) -> u64 {
514        // A missing parent means it was excluded/cyclic; that error is already
515        // recorded, so resolve to zero and let the compile fail.
516        let Some(&parent_count) = resolved.get(parent) else {
517            return 0;
518        };
519        let (mean, min, _max) = distribution_bounds(distribution);
520
521        // Children derive from the FINAL parent count and stored fan-out; the
522        // global control is deliberately NOT reapplied (no double-scale).
523        let derived = parent_count as f64 * mean;
524        let target = match over.map(TableOverride::effective) {
525            Some(EffectiveOverride::Rows(rows)) => rows as f64,
526            Some(EffectiveOverride::Scale(scale)) => derived * scale,
527            None | Some(EffectiveOverride::Conflict) => derived,
528        };
529
530        let count = stochastic_round(target, rounding_root, name);
531        let count = apply_max_rows(count, options.max_rows, name, bag);
532
533        let minimum = (parent_count as f64 * min).ceil() as u64;
534        if count < minimum {
535            bag.error(
536                crate::diagnostic::codes::CHILD_COUNT_IMPOSSIBLE.code,
537                format!("tables.{name}.rows"),
538                format!(
539                    "table `{name}` resolves to {count} rows, but its {parent_count} parents in `{parent}` each require at least {min} child(ren) ({minimum} total)"
540                ),
541            );
542        }
543        count
544    }
545
546    /// Build a [`PlannedTable`]: resolve seed and relationships, compile every
547    /// declared planner, assign exactly one owner to each column, type-check
548    /// generators/modifiers, and report read/write dependency cycles. All
549    /// diagnostics are appended to `bag`.
550    #[allow(clippy::too_many_arguments)]
551    fn plan_table(
552        &self,
553        model: &SyntheticModel,
554        name: &str,
555        table: &TableModel,
556        rows: u64,
557        root_seed: u64,
558        inference: InferenceMode,
559        family_ctx: &FamilyContext,
560        resolved: &BTreeMap<String, u64>,
561        selected: &BTreeSet<String>,
562        preserve_raw: bool,
563        max_rows: Option<u64>,
564        bag: &mut DiagnosticBag,
565    ) -> PlannedTable {
566        let seed = resolve_seed(&table.seed, root_seed);
567        let compile_seed = seed_root_of(&seed);
568        // Reject a table that declares the same column name more than once — a
569        // schema authoring error that otherwise surfaces as a confusing
570        // owner-missing error or a bare DEFAULT at render time.
571        let mut seen_columns: BTreeSet<&str> = BTreeSet::new();
572        for column in &table.schema.columns {
573            if !seen_columns.insert(column.name.as_str()) {
574                bag.error(
575                    crate::diagnostic::codes::DUPLICATE_COLUMN.code,
576                    format!("tables.{name}.schema.columns"),
577                    format!(
578                        "table `{name}` declares column `{}` more than once",
579                        column.name
580                    ),
581                );
582            }
583        }
584        self.validate_column_operator_arguments(name, table, bag);
585        let mut relationships: Vec<CompiledRelationship> = table
586            .relationships
587            .iter()
588            .map(compile_relationship)
589            .collect();
590        // Foreign keys declared only in the portable schema (the common shape
591        // for FKs recovered from a parsed dump) are compiled too, so the engine
592        // can assign their values. A generation relationship on the same columns
593        // wins, since it can carry an explicit assignment distribution.
594        for schema_rel in &table.schema.relationships {
595            if relationships
596                .iter()
597                .any(|existing| existing.columns == schema_rel.columns)
598            {
599                continue;
600            }
601            relationships.push(CompiledRelationship {
602                name: schema_rel.name.clone(),
603                columns: schema_rel.columns.clone(),
604                parent_table: schema_rel.referenced_table.clone(),
605                parent_columns: schema_rel.referenced_columns.clone(),
606                distribution: RelationshipDistribution::default(),
607                null_permille: 0,
608            });
609        }
610        fold_foreign_key_generators(name, table, &mut relationships, bag);
611
612        // Detach any compiled relationship whose parent table was excluded, so
613        // the output never references an absent table. A required (non-null) FK
614        // to an excluded table already produced a `GEN-EXCLUDED-DEPENDENCY`
615        // error; a nullable one is deliberately detachable, so warn (and let
616        // `--strict` promote it) rather than fail.
617        relationships.retain(|relationship| {
618            if selected.contains(&relationship.parent_table) {
619                return true;
620            }
621            if !fk_columns_all_non_null(table, &relationship.columns) {
622                bag.warning(
623                    crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
624                    format!("tables.{name}"),
625                    format!(
626                        "optional relationship `{}` on table `{name}` references excluded table `{}`; its foreign key is detached and omitted from the rendered DDL",
627                        relationship.name.as_deref().unwrap_or("(unnamed)"),
628                        relationship.parent_table
629                    ),
630                );
631            }
632            false
633        });
634
635        for relationship in &relationships {
636            let parent_is_empty = resolved
637                .get(&relationship.parent_table)
638                .is_some_and(|count| *count == 0);
639            if rows > 0 && parent_is_empty && !fk_columns_all_nullable(table, &relationship.columns)
640            {
641                bag.error(
642                    crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
643                    format!("tables.{name}.relationships"),
644                    format!(
645                        "table `{name}` resolves to {rows} row(s), but required relationship `{}` targets empty parent table `{}`",
646                        relationship.name.as_deref().unwrap_or("(unnamed)"),
647                        relationship.parent_table
648                    ),
649                );
650            }
651        }
652
653        let planners = self.compile_planners(
654            model,
655            name,
656            table,
657            compile_seed,
658            family_ctx,
659            resolved,
660            rows,
661            max_rows,
662            bag,
663        );
664        let claims = collect_claims(table, &planners);
665
666        let columns: Vec<PlannedColumn> = table
667            .schema
668            .columns
669            .iter()
670            .map(|column| {
671                let owner = self.resolve_owner(
672                    name,
673                    table,
674                    column,
675                    claims.get(&column.name).map(Vec::as_slice).unwrap_or(&[]),
676                    &planners,
677                    family_ctx,
678                    compile_seed,
679                    inference,
680                    bag,
681                );
682                let modifiers =
683                    self.compile_modifiers(name, table, column, &owner, compile_seed, bag);
684                PlannedColumn {
685                    schema: column.clone(),
686                    owner,
687                    modifiers,
688                }
689            })
690            .collect();
691
692        report_dependency_cycles(name, table, &columns, &planners, bag);
693        let eval_order = column_eval_order(table, &columns);
694
695        // On a successful compile every planner resolved and compiled, so this
696        // filter keeps them all in declaration order and a `ColumnOwner::
697        // Planner`'s `planner_index` stays valid. If any planner failed, the
698        // bag holds an error and the plan is discarded before it is observed.
699        let compiled_planners = planners.into_iter().filter_map(|p| p.compiled).collect();
700
701        // The normalized portable schema the renderer sees: drop every foreign
702        // key to an absent table, and any index that references an object that no
703        // longer exists (columns are never dropped here, so the index guard is a
704        // no-op today but keeps the invariant explicit). Clear the raw
705        // `create_statement` whenever the schema set changed, so a filtered run
706        // renders normalized DDL instead of stale original DDL.
707        let present_columns: BTreeSet<&str> = table
708            .schema
709            .columns
710            .iter()
711            .map(|c| c.name.as_str())
712            .collect();
713        let mut schema = table.schema.clone();
714        schema
715            .relationships
716            .retain(|relationship| selected.contains(&relationship.referenced_table));
717        schema.indexes.retain(|index| {
718            index
719                .columns
720                .iter()
721                .all(|c| present_columns.contains(c.as_str()))
722        });
723        if !preserve_raw {
724            schema.create_statement = None;
725        }
726
727        PlannedTable {
728            name: name.to_string(),
729            rows,
730            schema,
731            seed,
732            columns,
733            relationships,
734            planners: compiled_planners,
735            eval_order,
736        }
737    }
738
739    /// Resolve and compile every declared planner, collecting `GEN-PLANNER-*`
740    /// diagnostics and the read/write column sets each planner declares.
741    #[allow(clippy::too_many_arguments)]
742    fn compile_planners(
743        &self,
744        model: &SyntheticModel,
745        table_name: &str,
746        table: &TableModel,
747        seed: SeedRoot,
748        family_ctx: &FamilyContext,
749        resolved: &BTreeMap<String, u64>,
750        parent_rows: u64,
751        max_rows: Option<u64>,
752        bag: &mut DiagnosticBag,
753    ) -> Vec<PlannerInfo> {
754        let relationship_names = relationship_names(table);
755        // Cross-table FK-side planners (junction/tenant/polymorphic) reference
756        // OTHER tables' keys but the planner only sees its own table at compile.
757        // The compiler has the whole model plus the resolved counts (parents
758        // precede children in dependency order), so it injects the referenced
759        // tables' resolved counts and dense key recipes as facts — the same
760        // pattern the family planner uses, driven off the `cross_table`
761        // capability rather than any specific `kind`.
762        let relation_facts = build_relation_facts(model, table, resolved);
763        table
764            .planners
765            .iter()
766            .enumerate()
767            .map(|(index, config)| {
768                let path = format!("tables.{table_name}.planners[{index}]");
769                let Some(factory) = self.registry.planner(&config.kind) else {
770                    bag.error(
771                        crate::diagnostic::codes::PLANNER_UNKNOWN.code,
772                        path,
773                        format!("no planner registered for kind `{}`", config.kind),
774                    );
775                    return PlannerInfo::unresolved(&config.kind);
776                };
777                let descriptor = factory.descriptor();
778                validate_operator_arguments(
779                    &config.args,
780                    descriptor.arguments,
781                    &path,
782                    "planner",
783                    &config.kind,
784                    bag,
785                );
786                // A cross-table family planner (`children:`) carries its
787                // relationship on the *child* table; the compiler injected the
788                // child facts to validate it there, so skip the same-table
789                // relationship check that would otherwise falsely reject it.
790                let is_family = config.args.contains_key("children");
791                let is_cross_table = descriptor.cross_table;
792                let injected;
793                let config = if let Some(facts) =
794                    family_ctx.facts.get(&(table_name.to_string(), index))
795                {
796                    let mut cloned = config.clone();
797                    let mut facts = facts.clone();
798                    if let (Some(max_rows), serde_yaml_ng::Value::Mapping(mapping)) =
799                        (max_rows, &mut facts)
800                    {
801                        mapping.insert("child_row_limit".into(), max_rows.into());
802                    }
803                    if let serde_yaml_ng::Value::Mapping(mapping) = &mut facts {
804                        mapping.insert("parent_rows".into(), parent_rows.into());
805                    }
806                    cloned.args.insert(
807                        super::planners::order_family::FAMILY_FACTS_KEY.to_string(),
808                        facts,
809                    );
810                    injected = cloned;
811                    &injected
812                } else if !is_family
813                    && (is_cross_table || config.args.contains_key("relationship"))
814                {
815                    // A planner that references another table's (or its own
816                    // self-FK) key domain by relationship name: inject the
817                    // resolved parent counts and dense key recipes so it can
818                    // produce valid keys. This covers the FK-side cross-table
819                    // planners (junction/tenant/polymorphic) and the same-table
820                    // `hierarchy.tree`, which derives its emitted parent_id key
821                    // from the referenced primary key's generator.
822                    let mut cloned = config.clone();
823                    cloned.args.insert(
824                        super::planners::structural::RELATION_FACTS_KEY.to_string(),
825                        relation_facts.clone(),
826                    );
827                    injected = cloned;
828                    &injected
829                } else {
830                    config
831                };
832                let writes = match descriptor.writes {
833                    ColumnScope::Configured => configured_columns(config, &["columns", "writes"]),
834                    _ => Vec::new(),
835                };
836                let reads = match descriptor.reads {
837                    ColumnScope::Configured => configured_columns(config, &["reads"]),
838                    _ => Vec::new(),
839                };
840
841                if !is_family {
842                    if let Some(referenced) = string_arg(config, "relationship") {
843                        if !relationship_names.iter().any(|n| n == referenced) {
844                            bag.error(
845                                crate::diagnostic::codes::RELATIONSHIP_UNKNOWN.code,
846                                format!("{path}.relationship"),
847                                format!(
848                                    "planner `{}` references relationship `{referenced}`, which is not declared on table `{table_name}`",
849                                    config.kind
850                                ),
851                            );
852                        }
853                    }
854                }
855
856                let context = CompileContext::for_table(&table.schema, seed, &path);
857                let compiled = match factory.compile(config, &context) {
858                    Ok(compiled) => Some(compiled),
859                    Err(errors) => {
860                        bag.diagnostics.extend(errors.diagnostics);
861                        None
862                    }
863                };
864
865                PlannerInfo {
866                    kind: descriptor.kind.to_string(),
867                    writes,
868                    reads,
869                    compiled,
870                }
871            })
872            .collect()
873    }
874
875    /// Validate descriptor-owned generator/modifier keys before ownership
876    /// resolution. This includes relationship marker generators that the
877    /// engine consumes structurally instead of compiling as value operators.
878    fn validate_column_operator_arguments(
879        &self,
880        table_name: &str,
881        table: &TableModel,
882        bag: &mut DiagnosticBag,
883    ) {
884        for (column_name, rule) in &table.columns {
885            if let Some(config) = &rule.generator {
886                if let Some(factory) = self.registry.generator(&config.kind) {
887                    validate_operator_arguments(
888                        &config.args,
889                        factory.descriptor().arguments,
890                        &format!("tables.{table_name}.columns.{column_name}.generator"),
891                        "generator",
892                        &config.kind,
893                        bag,
894                    );
895                }
896            }
897            for (index, config) in rule.modifiers.iter().enumerate() {
898                if let Some(factory) = self.registry.modifier(&config.kind) {
899                    validate_operator_arguments(
900                        &config.args,
901                        factory.descriptor().arguments,
902                        &format!("tables.{table_name}.columns.{column_name}.modifiers[{index}]"),
903                        "modifier",
904                        &config.kind,
905                        bag,
906                    );
907                }
908            }
909        }
910    }
911
912    /// Assign the single owner for `column`, given its recorded claimants.
913    #[allow(clippy::too_many_arguments)]
914    fn resolve_owner(
915        &self,
916        table_name: &str,
917        table: &TableModel,
918        column: &PortableColumn,
919        claimants: &[Claim],
920        planners: &[PlannerInfo],
921        family_ctx: &FamilyContext,
922        seed: SeedRoot,
923        inference: InferenceMode,
924        bag: &mut DiagnosticBag,
925    ) -> ColumnOwner {
926        if claimants.len() > 1 {
927            let diagnostic = bag.error(
928                crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
929                format!("tables.{table_name}.columns.{}", column.name),
930                format!(
931                    "tables.{table_name}.columns.{} is produced by more than one owner",
932                    column.name
933                ),
934            );
935            diagnostic.related = claimants
936                .iter()
937                .map(|claim| SourceLocation {
938                    path: claim.path.clone(),
939                    description: claim.description.clone(),
940                })
941                .collect();
942            diagnostic.help = Some(format!(
943                "keep a single owner for `{}`: remove the column generator or drop it from the planner mapping",
944                column.name
945            ));
946            return ColumnOwner::GeneratedByDatabase;
947        }
948
949        if let Some(claim) = claimants.first() {
950            return match &claim.source {
951                ClaimSource::Generator => {
952                    self.compile_generator(table_name, table, column, seed, bag)
953                }
954                ClaimSource::Planner { index } => ColumnOwner::Planner {
955                    kind: planners[*index].kind.clone(),
956                    planner_index: *index,
957                },
958            };
959        }
960
961        // A cross-table family planner (declared on another table) may own this
962        // column; that ownership was recorded when its parent table was planned.
963        if let Some(external) = family_ctx
964            .external_owners
965            .get(&(table_name.to_string(), column.name.clone()))
966        {
967            return ColumnOwner::FamilyChild {
968                planner_kind: external.planner_kind.clone(),
969            };
970        }
971
972        self.infer_structural_owner(table_name, table, column, inference, seed, bag)
973    }
974
975    /// Resolve, type-check, and compile the explicit generator on `column`.
976    fn compile_generator(
977        &self,
978        table_name: &str,
979        table: &TableModel,
980        column: &PortableColumn,
981        seed: SeedRoot,
982        bag: &mut DiagnosticBag,
983    ) -> ColumnOwner {
984        let path = format!("tables.{table_name}.columns.{}.generator", column.name);
985        let config = table.columns[&column.name]
986            .generator
987            .as_ref()
988            .expect("generator claim implies a generator rule");
989        self.compile_generator_config(table, column, config, path, seed, bag)
990    }
991
992    /// Look up, type-check, and compile `config` into a generator owner for
993    /// `column`, attaching unknown-kind and type-mismatch diagnostics to `path`.
994    /// Shared by the explicit-generator path and schema inference.
995    fn compile_generator_config(
996        &self,
997        table: &TableModel,
998        column: &PortableColumn,
999        config: &crate::synthetic::model::GeneratorConfig,
1000        path: String,
1001        seed: SeedRoot,
1002        bag: &mut DiagnosticBag,
1003    ) -> ColumnOwner {
1004        let Some(factory) = self.registry.generator(&config.kind) else {
1005            bag.error(
1006                crate::diagnostic::codes::GENERATOR_UNKNOWN.code,
1007                path,
1008                format!("no generator registered for kind `{}`", config.kind),
1009            );
1010            return ColumnOwner::GeneratedByDatabase;
1011        };
1012        let descriptor = factory.descriptor();
1013
1014        if !descriptor.accepts.contains(&column.family) {
1015            bag.error(
1016                crate::diagnostic::codes::GENERATOR_TYPE.code,
1017                path,
1018                format!(
1019                    "generator `{}` cannot produce column `{}` of type family {:?}",
1020                    config.kind, column.name, column.family
1021                ),
1022            );
1023            return ColumnOwner::GeneratedByDatabase;
1024        }
1025
1026        let context = CompileContext::for_column(&table.schema, column, seed, &path);
1027        match factory.compile(config, &context) {
1028            Ok(compiled) => ColumnOwner::Generator {
1029                kind: descriptor.kind.to_string(),
1030                compiled,
1031            },
1032            Err(errors) => {
1033                bag.diagnostics.extend(errors.diagnostics);
1034                ColumnOwner::GeneratedByDatabase
1035            }
1036        }
1037    }
1038
1039    /// Owner for a column with no generator and no planner claim, from
1040    /// structural schema facts alone (no data observation). A column that no
1041    /// structural rule can supply is `GEN-COLUMN-OWNER-MISSING`.
1042    fn infer_structural_owner(
1043        &self,
1044        table_name: &str,
1045        table: &TableModel,
1046        column: &PortableColumn,
1047        inference: InferenceMode,
1048        seed: SeedRoot,
1049        bag: &mut DiagnosticBag,
1050    ) -> ColumnOwner {
1051        // HARD schema facts — genuine database-supplied values, honored in BOTH
1052        // `disabled` and `schema` modes because they are declared in the DDL,
1053        // not inferred by convention.
1054        if column.generated || column.identity {
1055            return ColumnOwner::GeneratedByDatabase;
1056        }
1057        if foreign_key_columns(table).contains(&column.name) {
1058            return ColumnOwner::Relationship {
1059                relationship: relationship_of(table, &column.name),
1060            };
1061        }
1062        if column.default_sql.is_some() {
1063            return ColumnOwner::DatabaseDefault;
1064        }
1065
1066        // CONVENTION — a bare integer primary key (no identity/serial flag, no
1067        // explicit owner) is treated as a database sequence. This is inference,
1068        // not a declared fact, so it runs ONLY under `schema` mode; under
1069        // `disabled` every generated column needs an explicit owner, so a bare
1070        // PK falls through to `GEN-COLUMN-OWNER-MISSING`.
1071        //
1072        // `GeneratedByDatabase` here means "the DB fills it", but a plain integer
1073        // PK has no sequence to fill from. Schema inference currently classifies
1074        // it this way without attaching the registered `sequence` generator, so
1075        // rendered output relies on database behavior for the value.
1076        if matches!(inference, InferenceMode::Schema)
1077            && column.primary_key
1078            && matches!(
1079                column.family,
1080                SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
1081            )
1082        {
1083            return ColumnOwner::GeneratedByDatabase;
1084        }
1085
1086        // Nothing structural applies. Under `schema` inference, derive a
1087        // generator from the column's name and declared type (email ->
1088        // internet.email, created_at -> datetime, a plain text column ->
1089        // string, ...) using the same name/type heuristics the profiler applies
1090        // at schema depth. The type fallback is the guaranteed floor, so this
1091        // never leaves a column unowned. Under `disabled` inference every
1092        // generated column needs an explicit owner, so the column is reported
1093        // as `GEN-COLUMN-OWNER-MISSING`.
1094        match inference {
1095            InferenceMode::Schema => {
1096                let config =
1097                    crate::profile::heuristics::schema_inferred_generator(&table.schema, column);
1098                let path = format!(
1099                    "tables.{table_name}.columns.{}.generator[inferred]",
1100                    column.name
1101                );
1102                self.compile_generator_config(table, column, &config, path, seed, bag)
1103            }
1104            InferenceMode::Disabled => {
1105                bag.error(
1106                    crate::diagnostic::codes::COLUMN_OWNER_MISSING.code,
1107                    format!("tables.{table_name}.columns.{}", column.name),
1108                    format!(
1109                        "column `{}` on table `{table_name}` has no generator, planner, relationship, or database default to produce its value",
1110                        column.name
1111                    ),
1112                );
1113                ColumnOwner::GeneratedByDatabase
1114            }
1115        }
1116    }
1117
1118    /// Type-check every modifier declared on `column`, and compile the pipeline
1119    /// into runnable operators (in declared order) for a generator-owned column
1120    /// so the engine can apply it after generation.
1121    ///
1122    /// Modifiers are compiled only for [`ColumnOwner::Generator`] columns: a
1123    /// `DatabaseDefault`/`GeneratedByDatabase`/`Relationship`/`Planner` column
1124    /// does not run a per-column generator pipeline (its value is a database
1125    /// placeholder, a materialized key, or planner-coordinated). Type-checking
1126    /// still runs for every column so a misapplied modifier is reported
1127    /// regardless of owner.
1128    fn compile_modifiers(
1129        &self,
1130        table_name: &str,
1131        table: &TableModel,
1132        column: &PortableColumn,
1133        owner: &ColumnOwner,
1134        seed: SeedRoot,
1135        bag: &mut DiagnosticBag,
1136    ) -> Vec<Box<dyn CompiledModifier>> {
1137        // A column inferred under `schema` mode has no explicit rule in the
1138        // model; treat it as one with no declared modifiers so its generator
1139        // still reaches `enforce_key_uniqueness` (an inferred key column must
1140        // still be deduplicated).
1141        let empty_rule;
1142        let rule = match table.columns.get(&column.name) {
1143            Some(rule) => rule,
1144            None => {
1145                empty_rule = crate::synthetic::model::ColumnRule {
1146                    semantic: None,
1147                    generator: None,
1148                    modifiers: Vec::new(),
1149                };
1150                &empty_rule
1151            }
1152        };
1153        let is_generator = matches!(owner, ColumnOwner::Generator { .. });
1154        let mut compiled: Vec<Box<dyn CompiledModifier>> = Vec::new();
1155        for (index, modifier) in rule.modifiers.iter().enumerate() {
1156            let path = format!(
1157                "tables.{table_name}.columns.{}.modifiers[{index}]",
1158                column.name
1159            );
1160            let Some(factory) = self.registry.modifier(&modifier.kind) else {
1161                bag.error(
1162                    crate::diagnostic::codes::MODIFIER_UNKNOWN.code,
1163                    path,
1164                    format!("no modifier registered for kind `{}`", modifier.kind),
1165                );
1166                continue;
1167            };
1168            if !factory.descriptor().accepts.contains(&column.family) {
1169                bag.error(
1170                    crate::diagnostic::codes::MODIFIER_TYPE.code,
1171                    path,
1172                    format!(
1173                        "modifier `{}` cannot transform column `{}` of type family {:?}",
1174                        modifier.kind, column.name, column.family
1175                    ),
1176                );
1177                continue;
1178            }
1179            if !is_generator {
1180                continue;
1181            }
1182            let context = CompileContext::for_column(&table.schema, column, seed, &path);
1183            match factory.compile(modifier, &context) {
1184                Ok(operator) => compiled.push(operator),
1185                Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1186            }
1187        }
1188
1189        self.enforce_key_uniqueness(
1190            table_name,
1191            table,
1192            column,
1193            owner,
1194            rule,
1195            seed,
1196            &mut compiled,
1197            bag,
1198        );
1199
1200        compiled
1201    }
1202
1203    /// Guarantee a single-column primary/unique key is unique BY CONSTRUCTION:
1204    /// auto-attach a `unique` modifier (with `on_exhaustion: error`) to a
1205    /// generator-owned key column whose generator is not already inherently
1206    /// unique. A `sequence`/`Dense` generator is unique by construction and a
1207    /// `uuid` collision is astronomically negligible, so both are left alone;
1208    /// `monotonic` (a row-indexed sequence with no key recipe) is treated as
1209    /// inherently unique too. Everything else (`string`, `pattern`, `choice`,
1210    /// semantic text, …) could collide on a key column, so it gets the modifier
1211    /// — which either de-duplicates the value or fails loudly, never silently
1212    /// emitting a duplicate key. A user-declared `unique` modifier is honored as
1213    /// is and never doubled. Composite (multi-column) keys are deliberately not
1214    /// enforced here (per-column dedup cannot guarantee composite uniqueness).
1215    #[allow(clippy::too_many_arguments)]
1216    fn enforce_key_uniqueness(
1217        &self,
1218        table_name: &str,
1219        table: &TableModel,
1220        column: &PortableColumn,
1221        owner: &ColumnOwner,
1222        rule: &crate::synthetic::model::ColumnRule,
1223        seed: SeedRoot,
1224        compiled: &mut Vec<Box<dyn CompiledModifier>>,
1225        bag: &mut DiagnosticBag,
1226    ) {
1227        let ColumnOwner::Generator {
1228            compiled: generator,
1229            ..
1230        } = owner
1231        else {
1232            return;
1233        };
1234        if !is_single_column_key(&table.schema, column) {
1235            return;
1236        }
1237        if generator.is_inherently_unique() {
1238            return;
1239        }
1240        // A user-declared `unique` modifier already enforces distinctness (with
1241        // whatever `on_exhaustion` they chose); do not add a second one.
1242        if rule
1243            .modifiers
1244            .iter()
1245            .any(|modifier| modifier.kind == "unique")
1246        {
1247            return;
1248        }
1249        let Some(factory) = self.registry.modifier("unique") else {
1250            return;
1251        };
1252        let path = format!(
1253            "tables.{table_name}.columns.{}.modifiers[auto-unique]",
1254            column.name
1255        );
1256        let config = ModifierConfig {
1257            kind: "unique".to_string(),
1258            args: [(
1259                "on_exhaustion".to_string(),
1260                serde_yaml_ng::Value::from("error"),
1261            )]
1262            .into_iter()
1263            .collect(),
1264        };
1265        let context = CompileContext::for_column(&table.schema, column, seed, &path);
1266        match factory.compile(&config, &context) {
1267            Ok(operator) => compiled.push(operator),
1268            Err(errors) => bag.diagnostics.extend(errors.diagnostics),
1269        }
1270    }
1271}
1272
1273/// Reject keys the registered descriptor does not publish. Factories remain
1274/// responsible for required arguments and value semantics; this common pass
1275/// only closes the permissive flattened-map gap shared by every operator kind.
1276fn validate_operator_arguments(
1277    args: &BTreeMap<String, serde_yaml_ng::Value>,
1278    expected: &[super::registry::ArgumentSpec],
1279    path: &str,
1280    operator_type: &str,
1281    kind: &str,
1282    bag: &mut DiagnosticBag,
1283) {
1284    for argument in args.keys() {
1285        if expected.iter().any(|spec| spec.name == argument) {
1286            continue;
1287        }
1288        let diagnostic = bag.error(
1289            crate::diagnostic::codes::OPERATOR_UNKNOWN_ARGUMENT.code,
1290            format!("{path}.{argument}"),
1291            format!("{operator_type} `{kind}` does not accept argument `{argument}`"),
1292        );
1293        if !expected.is_empty() {
1294            diagnostic.help = Some(format!(
1295                "supported arguments: {}",
1296                expected
1297                    .iter()
1298                    .map(|spec| spec.name)
1299                    .collect::<Vec<_>>()
1300                    .join(", ")
1301            ));
1302        }
1303    }
1304}
1305
1306/// The union of every column that participates in the table's primary key,
1307/// from both the table-level `primary_key` list and column-level flags.
1308fn primary_key_columns(table: &PortableTable) -> BTreeSet<&str> {
1309    let mut columns: BTreeSet<&str> = table.primary_key.iter().map(String::as_str).collect();
1310    columns.extend(
1311        table
1312            .columns
1313            .iter()
1314            .filter(|column| column.primary_key)
1315            .map(|column| column.name.as_str()),
1316    );
1317    columns
1318}
1319
1320/// Whether `column` is enforced-unique by a SINGLE-COLUMN key: it is the sole
1321/// primary-key column, or it carries a one-column UNIQUE constraint (a
1322/// column-level `unique` flag, a single-column unique constraint, or a
1323/// single-column unique index). Composite keys (2+ columns) are excluded — per
1324/// column deduplication cannot guarantee composite uniqueness.
1325fn is_single_column_key(table: &PortableTable, column: &PortableColumn) -> bool {
1326    let primary = primary_key_columns(table);
1327    if primary.len() == 1 && primary.contains(column.name.as_str()) {
1328        return true;
1329    }
1330    if column.unique {
1331        return true;
1332    }
1333    let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
1334    table
1335        .unique_constraints
1336        .iter()
1337        .any(|constraint| single(&constraint.columns))
1338        || table
1339            .indexes
1340            .iter()
1341            .any(|index| index.unique && single(&index.columns))
1342}
1343
1344/// The per-table override view folded from the flat CLI list.
1345#[derive(Debug, Default, Clone, Copy)]
1346struct TableOverride {
1347    rows: Option<u64>,
1348    scale: Option<f64>,
1349}
1350
1351/// The override actually applied once conflicts are accounted for.
1352enum EffectiveOverride {
1353    Rows(u64),
1354    Scale(f64),
1355    Conflict,
1356}
1357
1358impl TableOverride {
1359    fn effective(&self) -> EffectiveOverride {
1360        match (self.rows, self.scale) {
1361            (Some(_), Some(_)) => EffectiveOverride::Conflict,
1362            (Some(rows), None) => EffectiveOverride::Rows(rows),
1363            (None, Some(scale)) => EffectiveOverride::Scale(scale),
1364            (None, None) => EffectiveOverride::Conflict,
1365        }
1366    }
1367}
1368
1369/// Cap `count` at `max_rows` (the last step of count resolution), emitting a
1370/// surviving warning when the cap actually reduces the count.
1371fn apply_max_rows(count: u64, max_rows: Option<u64>, name: &str, bag: &mut DiagnosticBag) -> u64 {
1372    match max_rows {
1373        Some(max) if count > max => {
1374            bag.warning(
1375                crate::diagnostic::codes::MAX_ROWS_CAPPED.code,
1376                format!("tables.{name}.rows"),
1377                format!("table `{name}` row count capped from {count} to {max} by `--max-rows`"),
1378            );
1379            max
1380        }
1381        _ => count,
1382    }
1383}
1384
1385/// Stochastically round `value` to an integer on the table's stable
1386/// `rows.rounding` stream: round up with probability equal to the fraction.
1387fn stochastic_round(value: f64, root: SeedRoot, table: &str) -> u64 {
1388    if value <= 0.0 {
1389        return 0;
1390    }
1391    let floor = value.floor();
1392    let fraction = value - floor;
1393    let mut count = floor as u64;
1394    if fraction > 0.0 {
1395        let mut rng = root.stream(StreamId::rounding(table));
1396        if rng.random::<f64>() < fraction {
1397            count += 1;
1398        }
1399    }
1400    count
1401}
1402
1403/// The declared row count for the count-carrying `RowsModel` variants;
1404/// `relation.children` carries no standalone count (it derives from a parent).
1405fn declared_count(rows: &RowsModel) -> Option<u64> {
1406    match rows {
1407        RowsModel::Fixed { count }
1408        | RowsModel::Observed { count }
1409        | RowsModel::Scale { count, .. } => Some(*count),
1410        RowsModel::RelationChildren { .. } => None,
1411    }
1412}
1413
1414/// The kind name of a child fan-out distribution, so a family planner can honor
1415/// its *shape* (not just its bounds) when drawing per-order line counts.
1416fn distribution_kind(distribution: &ChildDistribution) -> &'static str {
1417    match distribution {
1418        ChildDistribution::Observed { .. } => "observed",
1419        ChildDistribution::Fixed { .. } => "fixed",
1420        ChildDistribution::Uniform { .. } => "uniform",
1421        ChildDistribution::Poisson { .. } => "poisson",
1422        ChildDistribution::Histogram { .. } => "histogram",
1423    }
1424}
1425
1426/// The `(mean, min, max)` fan-out bounds of any child distribution.
1427fn distribution_bounds(distribution: &ChildDistribution) -> (f64, f64, f64) {
1428    match distribution {
1429        ChildDistribution::Observed { mean, min, max }
1430        | ChildDistribution::Fixed { mean, min, max }
1431        | ChildDistribution::Uniform { mean, min, max }
1432        | ChildDistribution::Poisson { mean, min, max }
1433        | ChildDistribution::Histogram { mean, min, max } => (*mean, *min, *max),
1434    }
1435}
1436
1437/// Whether an `observed` row count has a source or profile to resolve from.
1438fn has_observed_provenance(model: &SyntheticModel, table: &str) -> bool {
1439    model.source.is_some()
1440        || model
1441            .profiles
1442            .keys()
1443            .filter_map(|key| key.split_once('.'))
1444            .any(|(profiled_table, _)| profiled_table == table)
1445}
1446
1447/// Which parent edges [`parent_edges`] collects.
1448#[derive(Clone, Copy, PartialEq, Eq)]
1449enum EdgeKind {
1450    /// Every ordering edge: relation.children parents, polymorphic targets, and
1451    /// every foreign key regardless of nullability.
1452    All,
1453    /// Only edges whose absence is fatal: relation.children parents, polymorphic
1454    /// targets, and non-null foreign keys. A nullable FK is detachable, so it is
1455    /// not required.
1456    Required,
1457}
1458
1459/// Whether every column of a foreign key is declared `NOT NULL`; a nullable
1460/// component makes the whole relationship optional (detachable). An unknown
1461/// column is treated conservatively as required.
1462fn fk_columns_all_non_null(table: &TableModel, columns: &[String]) -> bool {
1463    columns.iter().all(|column| {
1464        table
1465            .schema
1466            .columns
1467            .iter()
1468            .find(|candidate| &candidate.name == column)
1469            .map(|candidate| !candidate.nullable)
1470            .unwrap_or(true)
1471    })
1472}
1473
1474/// Whether every column of a foreign key can represent the all-NULL composite
1475/// used when its parent domain is empty. Unknown columns are not nullable.
1476fn fk_columns_all_nullable(table: &TableModel, columns: &[String]) -> bool {
1477    columns.iter().all(|column| {
1478        table
1479            .schema
1480            .columns
1481            .iter()
1482            .find(|candidate| &candidate.name == column)
1483            .is_some_and(|candidate| candidate.nullable)
1484    })
1485}
1486
1487/// Parent edges per table for the requested [`EdgeKind`]: the `relation.children`
1488/// parent plus every declared relationship's referenced table (generation
1489/// relationships and portable-schema foreign keys). Under [`EdgeKind::Required`]
1490/// a nullable foreign key is omitted, since it may be detached rather than
1491/// forcing its parent to be retained.
1492fn parent_edges(model: &SyntheticModel, kind: EdgeKind) -> BTreeMap<String, BTreeSet<String>> {
1493    model
1494        .tables
1495        .iter()
1496        .map(|(name, table)| {
1497            let generation = table
1498                .relationships
1499                .iter()
1500                .map(|relationship| (relationship.references.table.clone(), &relationship.columns));
1501            let schema =
1502                table.schema.relationships.iter().map(|relationship| {
1503                    (relationship.referenced_table.clone(), &relationship.columns)
1504                });
1505            let mut parents: BTreeSet<String> = BTreeSet::new();
1506            for (parent, columns) in generation.chain(schema) {
1507                if kind == EdgeKind::All || fk_columns_all_non_null(table, columns) {
1508                    parents.insert(parent);
1509                }
1510            }
1511            if let RowsModel::RelationChildren { parent, .. } = &table.rows {
1512                parents.insert(parent.clone());
1513            }
1514            // A polymorphic planner references its target tables by name (with no
1515            // `relationships:` entry), so those targets are ordering dependencies
1516            // too: their counts must be resolved before this table is planned.
1517            for planner in &table.planners {
1518                if let Some(serde_yaml_ng::Value::Sequence(items)) = planner.args.get("targets") {
1519                    for item in items {
1520                        if let Some(target) =
1521                            item.get("table").and_then(serde_yaml_ng::Value::as_str)
1522                        {
1523                            parents.insert(target.to_string());
1524                        }
1525                    }
1526                }
1527            }
1528            // A table never depends on itself for ordering purposes.
1529            parents.remove(name);
1530            (name.clone(), parents)
1531        })
1532        .collect()
1533}
1534
1535/// Topologically order the selected tables, parents before children, using
1536/// only edges between selected tables. Deterministic via sorted `BTreeMap`s.
1537///
1538/// Returns `(order, cyclic)`: `order` is the tables that could be sequenced
1539/// parents-first, and `cyclic` is any tables trapped in a mutual dependency
1540/// cycle (in name order). The caller turns a non-empty `cyclic` into a
1541/// `GEN-ROWS-CYCLE` error rather than resolving those tables to zero rows.
1542fn topo_order(
1543    selected: &BTreeSet<String>,
1544    parents: &BTreeMap<String, BTreeSet<String>>,
1545) -> (Vec<String>, Vec<String>) {
1546    let mut in_degree: BTreeMap<String, usize> = BTreeMap::new();
1547    let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
1548    for name in selected {
1549        let selected_parents: Vec<&String> = parents
1550            .get(name)
1551            .into_iter()
1552            .flatten()
1553            .filter(|parent| selected.contains(*parent))
1554            .collect();
1555        in_degree.insert(name.clone(), selected_parents.len());
1556        for parent in selected_parents {
1557            children
1558                .entry(parent.clone())
1559                .or_default()
1560                .push(name.clone());
1561        }
1562    }
1563
1564    // Ready tables are drained smallest-name-first. The queue is kept sorted
1565    // descending and popped from the back so the emitted order is stable and
1566    // alphabetical within each dependency level.
1567    let mut queue: Vec<String> = in_degree
1568        .iter()
1569        .filter(|(_, &degree)| degree == 0)
1570        .map(|(name, _)| name.clone())
1571        .collect();
1572    queue.sort();
1573    queue.reverse();
1574    let mut order: Vec<String> = Vec::with_capacity(selected.len());
1575    while let Some(name) = queue.pop() {
1576        order.push(name.clone());
1577        if let Some(kids) = children.get(&name) {
1578            for kid in kids {
1579                let degree = in_degree.get_mut(kid).expect("child has an in-degree");
1580                *degree -= 1;
1581                if *degree == 0 {
1582                    queue.push(kid.clone());
1583                }
1584            }
1585        }
1586        queue.sort();
1587        queue.reverse();
1588    }
1589
1590    // Any selected table the Kahn drain never reached is trapped in a cycle.
1591    let cyclic: Vec<String> = selected
1592        .iter()
1593        .filter(|name| !order.contains(name))
1594        .cloned()
1595        .collect();
1596    (order, cyclic)
1597}
1598
1599/// A declared planner after resolution: its resolved kind, the column sets it
1600/// reads and writes, and its compiled form (absent if resolution or compile
1601/// failed — the corresponding diagnostic is already recorded).
1602struct PlannerInfo {
1603    kind: String,
1604    writes: Vec<String>,
1605    reads: Vec<String>,
1606    compiled: Option<Box<dyn CompiledPlanner>>,
1607}
1608
1609impl PlannerInfo {
1610    /// A planner whose kind did not resolve in the registry.
1611    fn unresolved(kind: &str) -> Self {
1612        Self {
1613            kind: kind.to_string(),
1614            writes: Vec::new(),
1615            reads: Vec::new(),
1616            compiled: None,
1617        }
1618    }
1619}
1620
1621/// One recorded claim of ownership over a column, for conflict reporting.
1622struct Claim {
1623    source: ClaimSource,
1624    path: String,
1625    description: Option<String>,
1626}
1627
1628/// Who a [`Claim`] comes from.
1629enum ClaimSource {
1630    /// The column's own explicit generator rule.
1631    Generator,
1632    /// A planner, by its index in the table's compiled planner list.
1633    Planner { index: usize },
1634}
1635
1636/// Record every ownership claim over each column: an explicit generator plus
1637/// each planner that names the column in its `columns`/`writes` set. A column
1638/// with more than one claim is a `GEN-COLUMN-OWNER-CONFLICT`.
1639fn collect_claims(table: &TableModel, planners: &[PlannerInfo]) -> BTreeMap<String, Vec<Claim>> {
1640    let mut claims: BTreeMap<String, Vec<Claim>> = BTreeMap::new();
1641    for (name, rule) in &table.columns {
1642        if rule.generator.is_some() {
1643            claims.entry(name.clone()).or_default().push(Claim {
1644                source: ClaimSource::Generator,
1645                path: format!("columns.{name}.generator"),
1646                description: None,
1647            });
1648        }
1649    }
1650    for (index, planner) in planners.iter().enumerate() {
1651        // A single planner claims each column once, even if it lists the column
1652        // under more than one config key (`columns` and `writes`); otherwise it
1653        // would falsely conflict with itself.
1654        let mut claimed: BTreeSet<&str> = BTreeSet::new();
1655        for column in &planner.writes {
1656            if !claimed.insert(column.as_str()) {
1657                continue;
1658            }
1659            claims.entry(column.clone()).or_default().push(Claim {
1660                source: ClaimSource::Planner { index },
1661                path: format!("planners[{index}]"),
1662                description: Some(planner.kind.clone()),
1663            });
1664        }
1665    }
1666    claims
1667}
1668
1669/// The column names a planner config names under any of `keys`. Each key's
1670/// value may be a sequence of names or a mapping whose values are names (the
1671/// `role: column` planner mapping shape).
1672fn configured_columns(config: &PlannerConfig, keys: &[&str]) -> Vec<String> {
1673    let mut columns = Vec::new();
1674    for key in keys {
1675        match config.args.get(*key) {
1676            Some(serde_yaml_ng::Value::Sequence(items)) => columns.extend(
1677                items
1678                    .iter()
1679                    .filter_map(serde_yaml_ng::Value::as_str)
1680                    .map(str::to_string),
1681            ),
1682            Some(serde_yaml_ng::Value::Mapping(map)) => columns.extend(
1683                map.values()
1684                    .filter_map(serde_yaml_ng::Value::as_str)
1685                    .map(str::to_string),
1686            ),
1687            _ => {}
1688        }
1689    }
1690    columns
1691}
1692
1693/// A single string-valued planner argument, if present.
1694fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
1695    config.args.get(key).and_then(serde_yaml_ng::Value::as_str)
1696}
1697
1698/// Every declared relationship name on a table, from both the generation
1699/// relationships and the portable schema's foreign keys.
1700fn relationship_names(table: &TableModel) -> Vec<String> {
1701    table
1702        .relationships
1703        .iter()
1704        .filter_map(|relationship| relationship.name.clone())
1705        .chain(
1706            table
1707                .schema
1708                .relationships
1709                .iter()
1710                .filter_map(|relationship| relationship.name.clone()),
1711        )
1712        .collect()
1713}
1714
1715/// Every column that participates in a declared foreign key, from both the
1716/// generation relationships and the portable schema.
1717fn foreign_key_columns(table: &TableModel) -> BTreeSet<String> {
1718    table
1719        .relationships
1720        .iter()
1721        .flat_map(|relationship| relationship.columns.iter().cloned())
1722        .chain(
1723            table
1724                .schema
1725                .relationships
1726                .iter()
1727                .flat_map(|relationship| relationship.columns.iter().cloned()),
1728        )
1729        .collect()
1730}
1731
1732/// The name of the first relationship that covers `column`, if any.
1733fn relationship_of(table: &TableModel, column: &str) -> Option<String> {
1734    table
1735        .relationships
1736        .iter()
1737        .find(|relationship| relationship.columns.iter().any(|c| c == column))
1738        .and_then(|relationship| relationship.name.clone())
1739        .or_else(|| {
1740            table
1741                .schema
1742                .relationships
1743                .iter()
1744                .find(|relationship| relationship.columns.iter().any(|c| c == column))
1745                .and_then(|relationship| relationship.name.clone())
1746        })
1747}
1748
1749/// The concrete [`SeedRoot`] a resolved seed compiles operators against.
1750fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
1751    match seed {
1752        ResolvedTableSeed::Inherited(root)
1753        | ResolvedTableSeed::Fixed(root)
1754        | ResolvedTableSeed::Random(root) => *root,
1755    }
1756}
1757
1758/// A node in a table's column/planner dependency graph.
1759#[derive(Clone, PartialEq, Eq)]
1760enum DepNode {
1761    Column(String),
1762    Planner(usize),
1763}
1764
1765/// Build the read/write dependency graph and report each strongly connected
1766/// component that forms a real cycle as `GEN-COLUMN-CYCLE` — unless a single
1767/// registered planner owns every column in it (the planner resolves those
1768/// values jointly).
1769fn report_dependency_cycles(
1770    table_name: &str,
1771    table: &TableModel,
1772    columns: &[PlannedColumn],
1773    planners: &[PlannerInfo],
1774    bag: &mut DiagnosticBag,
1775) {
1776    let mut nodes: Vec<DepNode> = columns
1777        .iter()
1778        .map(|column| DepNode::Column(column.schema.name.clone()))
1779        .collect();
1780    nodes.extend((0..planners.len()).map(DepNode::Planner));
1781
1782    let index_of = |node: &DepNode| nodes.iter().position(|candidate| candidate == node);
1783    let mut edges: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
1784    let add_edge = |from: &DepNode, to: &DepNode, edges: &mut Vec<Vec<usize>>| {
1785        if let (Some(from), Some(to)) = (index_of(from), index_of(to)) {
1786            edges[from].push(to);
1787        }
1788    };
1789
1790    // A generator that reads sibling columns depends on them: read -> column.
1791    for planned in columns {
1792        if matches!(planned.owner, ColumnOwner::Generator { .. }) {
1793            for read in generator_reads(table, &planned.schema.name) {
1794                add_edge(
1795                    &DepNode::Column(read),
1796                    &DepNode::Column(planned.schema.name.clone()),
1797                    &mut edges,
1798                );
1799            }
1800        }
1801    }
1802    // A planner depends on the columns it reads and produces the ones it
1803    // writes: read -> planner -> write.
1804    for (index, planner) in planners.iter().enumerate() {
1805        for read in &planner.reads {
1806            add_edge(
1807                &DepNode::Column(read.clone()),
1808                &DepNode::Planner(index),
1809                &mut edges,
1810            );
1811        }
1812        for write in &planner.writes {
1813            add_edge(
1814                &DepNode::Planner(index),
1815                &DepNode::Column(write.clone()),
1816                &mut edges,
1817            );
1818        }
1819    }
1820
1821    for component in strongly_connected_components(&edges) {
1822        let self_loop = component.len() == 1 && edges[component[0]].contains(&component[0]);
1823        if component.len() <= 1 && !self_loop {
1824            continue;
1825        }
1826        let cycle_columns: Vec<String> = component
1827            .iter()
1828            .filter_map(|&node| match &nodes[node] {
1829                DepNode::Column(name) => Some(name.clone()),
1830                DepNode::Planner(_) => None,
1831            })
1832            .collect();
1833        if owned_by_single_planner(&cycle_columns, columns) {
1834            continue;
1835        }
1836        bag.error(
1837            crate::diagnostic::codes::COLUMN_CYCLE.code,
1838            format!("tables.{table_name}.columns"),
1839            format!(
1840                "columns on table `{table_name}` form a read/write dependency cycle: {}",
1841                cycle_columns.join(", ")
1842            ),
1843        );
1844    }
1845}
1846
1847/// The order in which the engine evaluates generator-owned columns within a
1848/// row: a topological sort of the column read graph (an edge `source -> reader`
1849/// for every sibling a generator reads), tie-broken by schema position so an
1850/// acyclic model with no cross-column reads keeps its declared order exactly.
1851///
1852/// Non-generator columns carry no read constraints — the engine fills them
1853/// before the generator pass — so they float to their schema position. Any
1854/// columns trapped in a cycle (which [`report_dependency_cycles`] already
1855/// rejects, save the single-planner-owned exception) are appended in schema
1856/// order, so the result is always a total permutation of `0..columns.len()`.
1857fn column_eval_order(table: &TableModel, columns: &[PlannedColumn]) -> Vec<usize> {
1858    let n = columns.len();
1859    let index_of: BTreeMap<&str, usize> = columns
1860        .iter()
1861        .enumerate()
1862        .map(|(index, column)| (column.schema.name.as_str(), index))
1863        .collect();
1864
1865    let mut successors: Vec<Vec<usize>> = vec![Vec::new(); n];
1866    let mut in_degree = vec![0usize; n];
1867    for (reader, column) in columns.iter().enumerate() {
1868        if !matches!(column.owner, ColumnOwner::Generator { .. }) {
1869            continue;
1870        }
1871        for read in generator_reads(table, &column.schema.name) {
1872            if let Some(&source) = index_of.get(read.as_str()) {
1873                if source != reader {
1874                    successors[source].push(reader);
1875                    in_degree[reader] += 1;
1876                }
1877            }
1878        }
1879    }
1880
1881    // Kahn's algorithm; the min-heap yields the lowest ready index first, so
1882    // independent columns emerge in schema order.
1883    let mut ready: BinaryHeap<Reverse<usize>> = (0..n)
1884        .filter(|&index| in_degree[index] == 0)
1885        .map(Reverse)
1886        .collect();
1887    let mut order = Vec::with_capacity(n);
1888    while let Some(Reverse(node)) = ready.pop() {
1889        order.push(node);
1890        for &next in &successors[node] {
1891            in_degree[next] -= 1;
1892            if in_degree[next] == 0 {
1893                ready.push(Reverse(next));
1894            }
1895        }
1896    }
1897
1898    // Cyclic remnants (already a reported error) get a deterministic slot so the
1899    // permutation stays total and the engine never panics on a missing index.
1900    if order.len() < n {
1901        let mut placed = vec![false; n];
1902        for &node in &order {
1903            placed[node] = true;
1904        }
1905        for (node, &is_placed) in placed.iter().enumerate() {
1906            if !is_placed {
1907                order.push(node);
1908            }
1909        }
1910    }
1911    order
1912}
1913
1914/// The sibling columns a compiled column generator reads on the same row. This
1915/// is the single source of truth for column read edges, feeding both cycle
1916/// detection ([`report_dependency_cycles`]) and the row-evaluation topological
1917/// order ([`column_eval_order`]).
1918///
1919/// Reads come from two places: an explicit `reads:` sequence (any generator may
1920/// declare one, meaningful when the descriptor declares `reads: Configured`),
1921/// plus the implicit sibling reads baked into specific built-in kinds — `copy`,
1922/// `slug`, `before`, and `after` read their `source`, and `template` reads each
1923/// `{ field: ... }`. These built-ins have no aliases, so matching the primary
1924/// kind is exact.
1925/// Duplicate names are collapsed so a repeated edge cannot skew the toposort's
1926/// in-degree accounting.
1927fn generator_reads(table: &TableModel, column: &str) -> Vec<String> {
1928    let Some(config) = table
1929        .columns
1930        .get(column)
1931        .and_then(|rule| rule.generator.as_ref())
1932    else {
1933        return Vec::new();
1934    };
1935
1936    let mut reads = Vec::new();
1937    let mut push = |name: &str| {
1938        let name = name.to_string();
1939        if !reads.contains(&name) {
1940            reads.push(name);
1941        }
1942    };
1943
1944    if let Some(serde_yaml_ng::Value::Sequence(items)) = config.args.get("reads") {
1945        for name in items.iter().filter_map(serde_yaml_ng::Value::as_str) {
1946            push(name);
1947        }
1948    }
1949
1950    match config.kind.as_str() {
1951        "copy" | "slug" | "before" | "after" => {
1952            if let Some(source) = config
1953                .args
1954                .get("source")
1955                .and_then(serde_yaml_ng::Value::as_str)
1956            {
1957                push(source);
1958            }
1959        }
1960        "template" => {
1961            if let Some(serde_yaml_ng::Value::Sequence(parts)) = config.args.get("parts") {
1962                for part in parts {
1963                    if let Some(field) = part.get("field").and_then(serde_yaml_ng::Value::as_str) {
1964                        push(field);
1965                    }
1966                }
1967            }
1968        }
1969        _ => {}
1970    }
1971
1972    reads
1973}
1974
1975/// Whether every column in a cycle is owned by one and the same planner.
1976fn owned_by_single_planner(cycle_columns: &[String], columns: &[PlannedColumn]) -> bool {
1977    let mut planner: Option<usize> = None;
1978    for name in cycle_columns {
1979        let owner = columns
1980            .iter()
1981            .find(|planned| &planned.schema.name == name)
1982            .map(|planned| &planned.owner);
1983        match owner {
1984            Some(ColumnOwner::Planner { planner_index, .. }) => {
1985                if planner.is_some_and(|existing| existing != *planner_index) {
1986                    return false;
1987                }
1988                planner = Some(*planner_index);
1989            }
1990            _ => return false,
1991        }
1992    }
1993    planner.is_some()
1994}
1995
1996/// Tarjan's strongly connected components over an adjacency list. Returns one
1997/// vector of node indices per component.
1998fn strongly_connected_components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
1999    struct State<'a> {
2000        edges: &'a [Vec<usize>],
2001        index: usize,
2002        indices: Vec<Option<usize>>,
2003        low: Vec<usize>,
2004        on_stack: Vec<bool>,
2005        stack: Vec<usize>,
2006        components: Vec<Vec<usize>>,
2007    }
2008
2009    fn connect(state: &mut State, v: usize) {
2010        state.indices[v] = Some(state.index);
2011        state.low[v] = state.index;
2012        state.index += 1;
2013        state.stack.push(v);
2014        state.on_stack[v] = true;
2015
2016        for &w in &state.edges[v] {
2017            match state.indices[w] {
2018                None => {
2019                    connect(state, w);
2020                    state.low[v] = state.low[v].min(state.low[w]);
2021                }
2022                Some(w_index) if state.on_stack[w] => {
2023                    state.low[v] = state.low[v].min(w_index);
2024                }
2025                Some(_) => {}
2026            }
2027        }
2028
2029        if state.low[v] == state.indices[v].expect("v was assigned an index") {
2030            let mut component = Vec::new();
2031            while let Some(w) = state.stack.pop() {
2032                state.on_stack[w] = false;
2033                component.push(w);
2034                if w == v {
2035                    break;
2036                }
2037            }
2038            state.components.push(component);
2039        }
2040    }
2041
2042    let n = edges.len();
2043    let mut state = State {
2044        edges,
2045        index: 0,
2046        indices: vec![None; n],
2047        low: vec![0; n],
2048        on_stack: vec![false; n],
2049        stack: Vec::new(),
2050        components: Vec::new(),
2051    };
2052    for v in 0..n {
2053        if state.indices[v].is_none() {
2054            connect(&mut state, v);
2055        }
2056    }
2057    state.components
2058}
2059
2060// --- Cross-table family (commerce.order_family) -----------------------------
2061
2062/// The child-facts a parent-scoped family planner cannot see on its own,
2063/// gathered by the compiler (which has the whole model) and injected into the
2064/// planner config, plus the child-column ownership the family planner asserts
2065/// across the table boundary.
2066#[derive(Default)]
2067struct FamilyContext {
2068    /// `(parent_table, planner_index)` → injected child facts.
2069    facts: BTreeMap<(String, usize), serde_yaml_ng::Value>,
2070    /// `(child_table, child_column)` → the family planner that owns it.
2071    external_owners: BTreeMap<(String, String), ExternalChildOwner>,
2072    /// Every discovered parent→child family membership.
2073    families: Vec<FamilyMembership>,
2074}
2075
2076/// A child column owned by a family planner declared on another table.
2077struct ExternalChildOwner {
2078    planner_kind: String,
2079}
2080
2081/// One discovered parent/child family, used to emit the [`ExecutionPhase::Family`].
2082struct FamilyMembership {
2083    parent: String,
2084    child: String,
2085}
2086
2087/// Whether a planner participates in the cross-table family child-spool pre-pass:
2088/// its descriptor advertises the `cross_table` capability AND it declares a
2089/// `children:` table (it produces that child's rows alongside its own). This is
2090/// driven off the registered capability rather than any specific planner `kind`,
2091/// so a new family planner joins the pre-pass by setting `cross_table` and
2092/// declaring `children`. Cross-table planners that only *reference* other tables
2093/// (junction/tenant/polymorphic FK-side planners) set `cross_table` too but do
2094/// not declare `children`, so they receive parent-key facts in
2095/// [`ModelCompiler::inject_relation_facts`] instead of spooling children here.
2096fn is_family_producer(registry: &ExtensionRegistry, config: &PlannerConfig) -> bool {
2097    registry
2098        .planner(&config.kind)
2099        .is_some_and(|factory| factory.descriptor().cross_table)
2100        && config.args.contains_key("children")
2101}
2102
2103impl ModelCompiler {
2104    /// Scan the model for cross-table family planners, validate the child-side
2105    /// facts each one cannot see (child existence and ownership conflicts on the
2106    /// child columns it claims), and gather the facts to inject plus the child
2107    /// column ownership the planner asserts. The parent-side and remaining
2108    /// child-side validation runs in the planner's own `compile`.
2109    ///
2110    /// Which planners take part is decided by the [`is_family_producer`]
2111    /// capability check, not a hardcoded `kind`.
2112    fn collect_family_facts(
2113        &self,
2114        model: &SyntheticModel,
2115        bag: &mut DiagnosticBag,
2116    ) -> FamilyContext {
2117        collect_family_facts(&self.registry, model, bag)
2118    }
2119}
2120
2121fn collect_family_facts(
2122    registry: &ExtensionRegistry,
2123    model: &SyntheticModel,
2124    bag: &mut DiagnosticBag,
2125) -> FamilyContext {
2126    let mut ctx = FamilyContext::default();
2127    for (parent_name, table) in &model.tables {
2128        for (index, config) in table.planners.iter().enumerate() {
2129            if !is_family_producer(registry, config) {
2130                continue;
2131            }
2132            let child_name = config.args.get("children").and_then(|v| v.as_str());
2133            let child = child_name.and_then(|name| model.tables.get(name).map(|t| (name, t)));
2134
2135            let mut facts = serde_yaml_ng::Mapping::new();
2136            facts.insert("child_found".into(), (child.is_some()).into());
2137
2138            if let Some((child_name, child_model)) = child {
2139                let mut columns = serde_yaml_ng::Mapping::new();
2140                for column in &child_model.schema.columns {
2141                    columns.insert(
2142                        column.name.clone().into(),
2143                        column.source_type.clone().into(),
2144                    );
2145                }
2146                facts.insert(
2147                    "child_columns".into(),
2148                    serde_yaml_ng::Value::Mapping(columns),
2149                );
2150
2151                if let RowsModel::RelationChildren { distribution, .. } = &child_model.rows {
2152                    let (mean, min, max) = distribution_bounds(distribution);
2153                    facts.insert("dist_kind".into(), distribution_kind(distribution).into());
2154                    facts.insert("dist_mean".into(), mean.into());
2155                    facts.insert("dist_min".into(), min.into());
2156                    facts.insert("dist_max".into(), max.into());
2157                }
2158
2159                let rel_name = config.args.get("relationship").and_then(|v| v.as_str());
2160                let rel_on_child = rel_name.is_some_and(|name| {
2161                    child_relationship_references(child_model, name, parent_name)
2162                });
2163                facts.insert("rel_on_child".into(), rel_on_child.into());
2164
2165                // Record ownership of every child column the planner maps, and
2166                // report a conflict with any competing generator on the child.
2167                if let Some(serde_yaml_ng::Value::Mapping(mapping)) =
2168                    config.args.get("child_columns")
2169                {
2170                    for column_name in mapping.values().filter_map(|v| v.as_str()) {
2171                        let exists = child_model
2172                            .schema
2173                            .columns
2174                            .iter()
2175                            .any(|column| column.name == column_name);
2176                        if !exists {
2177                            continue;
2178                        }
2179                        let has_generator = child_model
2180                            .columns
2181                            .get(column_name)
2182                            .is_some_and(|rule| rule.generator.is_some());
2183                        if has_generator {
2184                            bag.error(
2185                                crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2186                                format!("tables.{child_name}.columns.{column_name}"),
2187                                format!(
2188                                    "column `{column_name}` on table `{child_name}` is produced by both its own generator and the `commerce.order_family` planner on table `{parent_name}`"
2189                                ),
2190                            );
2191                        }
2192                        ctx.external_owners.insert(
2193                            (child_name.to_string(), column_name.to_string()),
2194                            ExternalChildOwner {
2195                                planner_kind: config.kind.clone(),
2196                            },
2197                        );
2198                    }
2199                }
2200
2201                if ctx.families.iter().any(|f| f.child == child_name) {
2202                    // A child produced by two family planners would be emitted
2203                    // twice (a Family phase per parent). Reject the ambiguity.
2204                    bag.error(
2205                        crate::diagnostic::codes::COLUMN_OWNER_CONFLICT.code,
2206                        format!("tables.{child_name}"),
2207                        format!(
2208                            "child table `{child_name}` is claimed as a family child by more than one parent; a family child must have a single producing parent"
2209                        ),
2210                    );
2211                } else {
2212                    ctx.families.push(FamilyMembership {
2213                        parent: parent_name.clone(),
2214                        child: child_name.to_string(),
2215                    });
2216                }
2217            }
2218
2219            ctx.facts.insert(
2220                (parent_name.clone(), index),
2221                serde_yaml_ng::Value::Mapping(facts),
2222            );
2223        }
2224    }
2225    ctx
2226}
2227
2228/// The dense integer key recipe `(start, step)` a parent column materializes as
2229/// — row `n`'s key is `start + n * step`. Mirrors the engine's
2230/// [`super::engine`] key-domain rules: a `sequence` generator carries its own
2231/// `start`/`step`, and a bare integer primary key (no generator, not
2232/// identity/generated) is the database sequence `1, 2, …`. Any other column
2233/// (a UUID, a text key, a non-key) has no dense integer recipe and returns
2234/// `None`, so an FK-side cross-table planner referencing it can reject the
2235/// incompatible key at compile time.
2236/// Parse a YAML value as an `i128`, matching the `sequence` generator's own
2237/// `parse_i128`: a Number (widening beyond i64 via f64), or a numeric String.
2238fn yaml_to_i128(value: &serde_yaml_ng::Value) -> Option<i128> {
2239    match value {
2240        serde_yaml_ng::Value::Number(n) => n
2241            .as_i64()
2242            .map(i128::from)
2243            .or_else(|| n.as_f64().map(|f| f as i128)),
2244        serde_yaml_ng::Value::String(s) => s.trim().parse::<i128>().ok(),
2245        _ => None,
2246    }
2247}
2248
2249fn dense_key_recipe(table: &TableModel, column: &str) -> Option<(i128, i128)> {
2250    if let Some(rule) = table.columns.get(column) {
2251        if let Some(generator) = &rule.generator {
2252            if generator.kind == "sequence" {
2253                // Parse with the same semantics the `sequence` generator itself
2254                // uses (accepting string- and float-form values), so the FK-side
2255                // recipe matches the keys the generator actually emits. Using
2256                // `as_i64` here returned None for e.g. `start: "1000"` and fell
2257                // back to 0, producing dangling foreign keys.
2258                let start = generator
2259                    .args
2260                    .get("start")
2261                    .and_then(yaml_to_i128)
2262                    .unwrap_or(0);
2263                let step = generator
2264                    .args
2265                    .get("step")
2266                    .and_then(yaml_to_i128)
2267                    .unwrap_or(1);
2268                return Some((start, step));
2269            }
2270            // Any other explicit generator is not a dense integer key.
2271            return None;
2272        }
2273    }
2274    let column = table.schema.columns.iter().find(|c| c.name == column)?;
2275    // A bare integer primary key OR an identity integer primary key is a
2276    // database sequence rendered as `1..=count` — the engine's FK key-domain
2277    // path (`build_key_domains`) treats both the same, so cross-table planners
2278    // must accept both as the dense recipe `(1, 1)` too. (A `generated`/computed
2279    // column has no such closed form.)
2280    if column.primary_key
2281        && !column.generated
2282        && matches!(
2283            column.family,
2284            SqlTypeFamily::Integer | SqlTypeFamily::BigInteger
2285        )
2286    {
2287        return Some((1, 1));
2288    }
2289    None
2290}
2291
2292/// Build the `__relation_facts` payload injected into an FK-side cross-table
2293/// planner: for every relationship the child declares, the resolved parent
2294/// count and dense key recipe; and for every model table, its resolved count
2295/// and the dense recipe of each of its columns (so a polymorphic planner can
2296/// resolve a target table referenced only by name). Counts come from the
2297/// already-resolved parents, which precede the child in dependency order.
2298fn build_relation_facts(
2299    model: &SyntheticModel,
2300    table: &TableModel,
2301    resolved: &BTreeMap<String, u64>,
2302) -> serde_yaml_ng::Value {
2303    use serde_yaml_ng::{Mapping, Value};
2304
2305    let recipe_map = |recipe: Option<(i128, i128)>| -> Mapping {
2306        let mut m = Mapping::new();
2307        match recipe {
2308            Some((start, step)) => {
2309                m.insert("dense".into(), true.into());
2310                m.insert("start".into(), (start as i64).into());
2311                m.insert("step".into(), (step as i64).into());
2312            }
2313            None => {
2314                m.insert("dense".into(), false.into());
2315            }
2316        }
2317        m
2318    };
2319
2320    let mut relationships = Mapping::new();
2321    let generation = table.relationships.iter().map(|rel| {
2322        (
2323            rel.name.clone(),
2324            rel.references.table.clone(),
2325            rel.references.columns.clone(),
2326        )
2327    });
2328    let schema = table.schema.relationships.iter().map(|rel| {
2329        (
2330            rel.name.clone(),
2331            rel.referenced_table.clone(),
2332            rel.referenced_columns.clone(),
2333        )
2334    });
2335    for (name, parent_table, parent_columns) in generation.chain(schema) {
2336        let Some(name) = name else { continue };
2337        let parent_column = parent_columns.first().cloned().unwrap_or_default();
2338        let recipe = model
2339            .tables
2340            .get(&parent_table)
2341            .and_then(|parent| dense_key_recipe(parent, &parent_column));
2342        let mut entry = recipe_map(recipe);
2343        entry.insert("parent_table".into(), parent_table.clone().into());
2344        entry.insert("parent_column".into(), parent_column.into());
2345        entry.insert(
2346            "count".into(),
2347            resolved.get(&parent_table).copied().unwrap_or(0).into(),
2348        );
2349        relationships.insert(name.into(), Value::Mapping(entry));
2350    }
2351
2352    let mut tables = Mapping::new();
2353    for (name, target) in &model.tables {
2354        let count = resolved.get(name).copied().unwrap_or(0);
2355        let mut keys = Mapping::new();
2356        for column in &target.schema.columns {
2357            if let Some(recipe) = dense_key_recipe(target, &column.name) {
2358                let mut key_entry = recipe_map(Some(recipe));
2359                // Carry the owning table's row count on each key entry so a
2360                // polymorphic target resolved by column name still knows its
2361                // domain size.
2362                key_entry.insert("count".into(), count.into());
2363                keys.insert(column.name.clone().into(), Value::Mapping(key_entry));
2364            }
2365        }
2366        let mut entry = Mapping::new();
2367        entry.insert("count".into(), count.into());
2368        entry.insert("keys".into(), Value::Mapping(keys));
2369        // The primary-key column: an explicit table-level PK, else a column
2370        // flagged `primary_key` (the common single-column-PK shape).
2371        let primary_key = target.schema.primary_key.first().cloned().or_else(|| {
2372            target
2373                .schema
2374                .columns
2375                .iter()
2376                .find(|column| column.primary_key)
2377                .map(|column| column.name.clone())
2378        });
2379        if let Some(primary_key) = primary_key {
2380            entry.insert("primary_key".into(), primary_key.into());
2381        }
2382        tables.insert(name.clone().into(), Value::Mapping(entry));
2383    }
2384
2385    let mut root = Mapping::new();
2386    root.insert("relationships".into(), Value::Mapping(relationships));
2387    root.insert("tables".into(), Value::Mapping(tables));
2388    // The child's own resolved count (it is inserted into `resolved` before this
2389    // table is planned), so a junction planner can reject a row count that
2390    // exceeds the number of distinct parent pairs.
2391    root.insert(
2392        "self_count".into(),
2393        resolved
2394            .get(&table.schema.name)
2395            .copied()
2396            .unwrap_or(0)
2397            .into(),
2398    );
2399    Value::Mapping(root)
2400}
2401
2402/// Whether `child` declares a relationship named `name` that references
2403/// `parent`, via either a generation relationship or a portable-schema foreign
2404/// key. A name that resolves to a relationship referencing a *different* table
2405/// (or is absent) does not count — the family FK must bind the child to its
2406/// parent.
2407fn child_relationship_references(child: &TableModel, name: &str, parent: &str) -> bool {
2408    let generation = child.relationships.iter().any(|relationship| {
2409        relationship.name.as_deref() == Some(name) && relationship.references.table == parent
2410    });
2411    let schema = child.schema.relationships.iter().any(|relationship| {
2412        relationship.name.as_deref() == Some(name) && relationship.referenced_table == parent
2413    });
2414    generation || schema
2415}
2416
2417/// Build the execution phases: a family parent and its child collapse into one
2418/// [`ExecutionPhase::Family`] (the child's own `Table` phase is omitted, since it
2419/// is generated inside the family), and every other table stays a `Table` phase.
2420fn build_phases(
2421    order: &[String],
2422    family_ctx: &FamilyContext,
2423    budget_bytes: u64,
2424    bag: &mut DiagnosticBag,
2425) -> Vec<ExecutionPhase> {
2426    let ordered: BTreeSet<&str> = order.iter().map(String::as_str).collect();
2427    let child_tables: BTreeSet<&str> = family_ctx
2428        .families
2429        .iter()
2430        .map(|family| family.child.as_str())
2431        .collect();
2432    let mut phases = Vec::with_capacity(order.len());
2433    for name in order {
2434        if child_tables.contains(name.as_str()) {
2435            continue;
2436        }
2437        match family_ctx
2438            .families
2439            .iter()
2440            .find(|family| &family.parent == name)
2441        {
2442            // Only pair the parent with its child when the child is actually
2443            // generated; otherwise the family phase would name an ungenerated
2444            // table (and mis-route its spooled rows).
2445            Some(family) if ordered.contains(family.child.as_str()) => {
2446                phases.push(ExecutionPhase::Family(FamilyPhase {
2447                    name: name.clone(),
2448                    tables: vec![name.clone(), family.child.clone()],
2449                    budget_bytes,
2450                }));
2451            }
2452            Some(family) => {
2453                bag.warning(
2454                    crate::diagnostic::codes::DETACHED_DEPENDENCY.code,
2455                    format!("tables.{name}.planners"),
2456                    format!(
2457                        "family child `{}` of `{name}` was excluded; generating `{name}` without its correlated child rows",
2458                        family.child
2459                    ),
2460                );
2461                phases.push(ExecutionPhase::Table(name.clone()));
2462            }
2463            None => phases.push(ExecutionPhase::Table(name.clone())),
2464        }
2465    }
2466    phases
2467}
2468
2469/// Capture a declared relationship's referential shape and value-assignment
2470/// distribution. The generation engine executes the per-row parent assignment.
2471fn compile_relationship(relationship: &RelationshipModel) -> CompiledRelationship {
2472    CompiledRelationship {
2473        name: relationship.name.clone(),
2474        columns: relationship.columns.clone(),
2475        parent_table: relationship.references.table.clone(),
2476        parent_columns: relationship.references.columns.clone(),
2477        distribution: parse_distribution(relationship.distribution.as_deref()),
2478        null_permille: 0,
2479    }
2480}
2481
2482/// Parse a relationship's assignment distribution name. An absent or
2483/// unrecognized name falls back to [`RelationshipDistribution::Uniform`].
2484fn parse_distribution(name: Option<&str>) -> RelationshipDistribution {
2485    match name {
2486        Some("sequential") => RelationshipDistribution::Sequential,
2487        Some("weighted") => RelationshipDistribution::Weighted,
2488        Some("observed") => RelationshipDistribution::Observed,
2489        _ => RelationshipDistribution::Uniform,
2490    }
2491}
2492
2493/// Fold the arguments of any explicit `relation.foreign_key` /
2494/// `relation.composite_key` column generator into the matching relationship, so
2495/// an inferred FK (owner `Relationship`) and an explicit FK generator (owner
2496/// `Generator`) converge on the same compiled relationship the engine executes.
2497/// Recognizes `distribution` (a name) and `null_rate` (a `0.0..=1.0` fraction).
2498/// An FK generator whose column no relationship covers is a
2499/// `GEN-FOREIGN-KEY-UNRESOLVED` error: it would otherwise render `DEFAULT`
2500/// silently at run time.
2501fn fold_foreign_key_generators(
2502    table_name: &str,
2503    table: &TableModel,
2504    relationships: &mut [CompiledRelationship],
2505    bag: &mut DiagnosticBag,
2506) {
2507    for (column, rule) in &table.columns {
2508        let Some(generator) = &rule.generator else {
2509            continue;
2510        };
2511        if generator.kind != "relation.foreign_key" && generator.kind != "relation.composite_key" {
2512            continue;
2513        }
2514        let Some(relationship) = relationships
2515            .iter_mut()
2516            .find(|relationship| relationship.columns.iter().any(|c| c == column))
2517        else {
2518            bag.error(
2519                crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED.code,
2520                format!("tables.{table_name}.columns.{column}.generator"),
2521                format!(
2522                    "column `{column}` on table `{table_name}` uses generator `{}` but no relationship declares it as a foreign key; declare a `relationships:` entry covering it",
2523                    generator.kind
2524                ),
2525            );
2526            continue;
2527        };
2528        if let Some(name) = generator.args.get("distribution").and_then(|v| v.as_str()) {
2529            relationship.distribution = parse_distribution(Some(name));
2530        }
2531        if let Some(rate) = generator.args.get("null_rate").and_then(|v| v.as_f64()) {
2532            relationship.null_permille = (rate.clamp(0.0, 1.0) * 1000.0).round() as u16;
2533        }
2534    }
2535}
2536
2537/// Resolve a table's seed against the run's root seed.
2538fn resolve_seed(seed: &TableSeed, root_seed: u64) -> ResolvedTableSeed {
2539    match seed {
2540        TableSeed::Inherit => ResolvedTableSeed::Inherited(SeedRoot::new(root_seed)),
2541        TableSeed::Random => ResolvedTableSeed::Random(SeedRoot::new(rand::random())),
2542        TableSeed::Fixed(seed) => ResolvedTableSeed::Fixed(SeedRoot::new(*seed)),
2543    }
2544}
2545
2546/// Carry the model's `output:` block into the plan, parsing the render dialect.
2547fn compile_output(model: &SyntheticModel) -> CompiledOutput {
2548    CompiledOutput {
2549        dialect: model.output.dialect.as_ref().and_then(|d| d.parse().ok()),
2550        mode: model.output.mode,
2551        inserts: model.output.inserts,
2552        batch_size: model.output.batch_size,
2553    }
2554}
2555
2556/// Compile a list of glob strings once, reporting `GEN-INVALID-GLOB` for any
2557/// that fail to parse.
2558fn compile_globs(patterns: &[String], bag: &mut DiagnosticBag) -> Vec<Pattern> {
2559    patterns
2560        .iter()
2561        .filter_map(|pattern| match Pattern::new(pattern) {
2562            Ok(compiled) => Some(compiled),
2563            Err(error) => {
2564                bag.error(
2565                    crate::diagnostic::codes::INVALID_GLOB.code,
2566                    "options",
2567                    format!("invalid table glob `{pattern}`: {error}"),
2568                );
2569                None
2570            }
2571        })
2572        .collect()
2573}