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