Skip to main content

sql_splitter/generate/
plan.rs

1//! The immutable [`GenerationPlan`]: the compiler's output.
2//!
3//! A plan is what [`super::compiler::ModelCompiler`] produces from a complete
4//! [`crate::synthetic::model::SyntheticModel`] and a set of CLI
5//! [`CompileOptions`]. It fixes, once and for all, *which* tables are
6//! generated, in *what order*, and with *exactly how many rows* — every later
7//! stage reads a plan rather than re-deriving those decisions.
8//!
9//! Plan fields are public but treated as read-only after construction: the
10//! compiler builds a plan and hands it out; nothing mutates it in place. Most
11//! types here derive `Debug`/`Clone`; [`PlannedTable`] cannot, because it owns
12//! `Box<dyn CompiledPlanner>` trait objects, so it carries a hand-written
13//! [`std::fmt::Debug`] that keeps the plan observable without pretending the
14//! compiled planners are printable.
15//!
16//! The plan also fixes column ownership, relationship assignment strategies,
17//! execution phases for individual tables and correlated families, and cost
18//! estimates used by reporting and execution.
19
20use std::fmt;
21
22use crate::diagnostic::Diagnostic;
23use crate::parser::SqlDialect;
24use crate::synthetic::model::{InsertMode, OutputMode};
25use crate::synthetic::schema::{PortableColumn, PortableTable};
26
27use super::registry::{CompiledGenerator, CompiledModifier, CompiledPlanner};
28use super::seed::SeedRoot;
29
30/// A fully compiled generation plan: the immutable contract every downstream
31/// stage reads.
32#[derive(Debug)]
33pub struct GenerationPlan {
34    /// Dialect the source dump was parsed with, if the model recorded one.
35    pub input_dialect: Option<SqlDialect>,
36    /// Resolved output/rendering configuration.
37    pub output: CompiledOutput,
38    /// The selected tables, in dependency order (parents before children).
39    pub tables: Vec<PlannedTable>,
40    /// Generation phases, in execution order, for individual tables or
41    /// correlated table families.
42    pub phases: Vec<ExecutionPhase>,
43    /// Non-error diagnostics that survive a successful compile: drained merge
44    /// warnings plus compile-stage warnings (e.g. a `--max-rows` cap).
45    pub diagnostics: Vec<Diagnostic>,
46    /// Cost and size estimates for reporting and resource planning.
47    pub estimates: PlanEstimates,
48    /// The exact in-memory byte budget for each correlated family's buffered
49    /// child rows before it spills to a protected spool. The engine's
50    /// `commerce.order_family` execution keys its [`FamilyBuffer`] off this. A
51    /// large default keeps ordinary families in memory; a run may pin a small
52    /// budget (`--family-budget`) to exercise the spill path.
53    pub family_budget_bytes: u64,
54}
55
56impl GenerationPlan {
57    /// Look up a planned table by name.
58    pub fn table(&self, name: &str) -> Option<&PlannedTable> {
59        self.tables.iter().find(|table| table.name == name)
60    }
61}
62
63/// Resolved output/rendering configuration, carried over from the model's
64/// `output:` block with the dialect parsed to a [`SqlDialect`].
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct CompiledOutput {
67    /// Target render dialect, if the model pinned one (else the input dialect).
68    pub dialect: Option<SqlDialect>,
69    /// Whether to render schema, data, or both.
70    pub mode: Option<OutputMode>,
71    /// How PostgreSQL rows are rendered (INSERT vs COPY).
72    pub inserts: Option<InsertMode>,
73    /// Row batch size for multi-row INSERTs.
74    pub batch_size: Option<u32>,
75}
76
77/// One unit of generation work, in execution order.
78///
79/// A [`Table`](Self::Table) phase generates one table on its own. A
80/// [`Family`](Self::Family) phase generates a correlated group of tables
81/// together under a shared memory budget (so cross-table correlations are
82/// coherent), and a [`DeferredConstraints`](Self::DeferredConstraints) phase
83/// records constraints (e.g. self-referential foreign keys, circular
84/// references) that are applied only after the referenced rows exist. The
85/// compiler emits `Family` for correlated parent/child generation; its bounded
86/// buffering uses [`crate::generate::output::FamilyBuffer`].
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum ExecutionPhase {
89    /// Generate a single table's rows, identified by name.
90    Table(String),
91    /// Generate a correlated family of tables together under one budget.
92    Family(FamilyPhase),
93    /// Apply constraints that could only be satisfied after their referents
94    /// were generated.
95    DeferredConstraints(DeferredConstraints),
96}
97
98/// A correlated family of tables generated together under a shared, exact
99/// memory budget.
100///
101/// The budget is fixed at compile time; at run time a
102/// [`crate::generate::output::FamilyBuffer`] keeps the family's buffered rows in
103/// memory only while under `budget_bytes` and spills to a protected spool the
104/// moment a push would cross it, so a family never retains every child row in an
105/// unbounded `Vec`.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct FamilyPhase {
108    /// A stable name for the family (typically its root parent table).
109    pub name: String,
110    /// The member tables, in dependency order (parents before children).
111    pub tables: Vec<String>,
112    /// The exact in-memory byte budget for the family's buffered rows.
113    pub budget_bytes: u64,
114}
115
116/// Constraints deferred until after the rows they reference are generated —
117/// self-referential or circular foreign keys the ordinary parent-before-child
118/// ordering cannot satisfy in one pass.
119#[derive(Debug, Clone, Default, PartialEq, Eq)]
120pub struct DeferredConstraints {
121    /// The tables whose constraints are applied in this phase.
122    pub tables: Vec<String>,
123}
124
125/// A single selected table with its resolved row count and generation surface.
126///
127/// Cannot derive `Debug`/`Clone`: `planners` holds trait objects. See the
128/// module docs for the manual `Debug`.
129pub struct PlannedTable {
130    /// Table name.
131    pub name: String,
132    /// Exact, resolved row count.
133    pub rows: u64,
134    /// The table's portable schema.
135    pub schema: PortableTable,
136    /// The table's resolved seed.
137    pub seed: ResolvedTableSeed,
138    /// Every schema column, paired with the owner that produces its values.
139    pub columns: Vec<PlannedColumn>,
140    /// Compiled relationships to parent tables, including fan-out assignment.
141    pub relationships: Vec<CompiledRelationship>,
142    /// Compiled table-level planners, in declaration order. A
143    /// [`ColumnOwner::Planner`]'s `planner_index` indexes into this vector.
144    /// Declared planners are compiled here so ownership can reference and the
145    /// runtime can execute them without resolving the registry again.
146    pub planners: Vec<Box<dyn CompiledPlanner>>,
147    /// The order in which the engine evaluates generator-owned columns within a
148    /// row: a topological sort of the column read graph (a generator that reads
149    /// a sibling is evaluated after that sibling), tie-broken by schema position.
150    /// A model with no cross-column reads keeps its exact declared order. Indexes
151    /// into [`Self::columns`]; always a total permutation of its length.
152    pub eval_order: Vec<usize>,
153}
154
155impl fmt::Debug for PlannedTable {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        // `CompiledPlanner` is not `Debug`, so describe the planners by count
158        // rather than dropping the field from the plan's observability.
159        f.debug_struct("PlannedTable")
160            .field("name", &self.name)
161            .field("rows", &self.rows)
162            .field("schema", &self.schema)
163            .field("seed", &self.seed)
164            .field("columns", &self.columns)
165            .field("relationships", &self.relationships)
166            .field(
167                "planners",
168                &format_args!("[{} compiled]", self.planners.len()),
169            )
170            .field("eval_order", &self.eval_order)
171            .finish()
172    }
173}
174
175/// A schema column paired with the operator that owns its values and the
176/// compiled modifier pipeline applied after generation.
177///
178/// Cannot derive `Debug`/`Clone`/`PartialEq`: a [`ColumnOwner::Generator`]
179/// holds a `Box<dyn CompiledGenerator>` and `modifiers` holds
180/// `Box<dyn CompiledModifier>` trait objects. The hand-written [`fmt::Debug`]
181/// describes the modifier pipeline by count.
182pub struct PlannedColumn {
183    /// The column's portable schema.
184    pub schema: PortableColumn,
185    /// What produces this column's values.
186    pub owner: ColumnOwner,
187    /// The compiled modifier pipeline, in declared order, applied to the value
188    /// after the owner produces it. Only populated for generator-owned columns;
189    /// empty otherwise (see `ModelCompiler::compile_modifiers`).
190    pub modifiers: Vec<Box<dyn CompiledModifier>>,
191}
192
193impl fmt::Debug for PlannedColumn {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        // `CompiledModifier` is not `Debug`; describe the pipeline by count so
196        // the plan stays observable without pretending the operators print.
197        f.debug_struct("PlannedColumn")
198            .field("schema", &self.schema)
199            .field("owner", &self.owner)
200            .field(
201                "modifiers",
202                &format_args!("[{} compiled]", self.modifiers.len()),
203            )
204            .finish()
205    }
206}
207
208/// What produces a column's values.
209///
210/// Exactly one owner is assigned to every non-omitted column during
211/// compilation. Two generators or planners claiming the same column is a
212/// `GEN-COLUMN-OWNER-CONFLICT`; a column that no rule and no structural schema
213/// fact can supply is a `GEN-COLUMN-OWNER-MISSING`.
214pub enum ColumnOwner {
215    /// An explicit column generator produces the value. Holds the compiled
216    /// generator so the row hot path never re-resolves the registry.
217    Generator {
218        /// The resolved generator kind (canonical, not an alias).
219        kind: String,
220        /// The compiled generator, ready to run per row.
221        compiled: Box<dyn CompiledGenerator>,
222    },
223    /// A table-level planner coordinates this column with others. Indexes
224    /// into [`PlannedTable::planners`].
225    Planner {
226        /// The resolved planner kind.
227        kind: String,
228        /// The owning planner's index in [`PlannedTable::planners`].
229        planner_index: usize,
230    },
231    /// A cross-table family planner declared on *another* table owns this
232    /// column's value (a `commerce.order_family` child column). The engine
233    /// fills it from the spooled family child rows rather than a same-table
234    /// generator, so it needs no local owner and never renders `DEFAULT`.
235    FamilyChild {
236        /// The owning planner's kind, for diagnostics.
237        planner_kind: String,
238    },
239    /// A declared relationship supplies this foreign-key column's value.
240    Relationship {
241        /// The owning relationship's declared name, if any.
242        relationship: Option<String>,
243    },
244    /// The column's own `DEFAULT` expression supplies the value; the renderer
245    /// emits `DEFAULT` and the database fills it.
246    DatabaseDefault,
247    /// The database produces the value itself — an `IDENTITY`/serial sequence,
248    /// a `GENERATED` computed column, or a bare integer primary key.
249    GeneratedByDatabase,
250}
251
252impl fmt::Debug for ColumnOwner {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        // `CompiledGenerator` is not `Debug`; describe the owner by kind so the
255        // plan stays observable without pretending the operator is printable.
256        match self {
257            ColumnOwner::Generator { kind, .. } => f
258                .debug_struct("Generator")
259                .field("kind", kind)
260                .finish_non_exhaustive(),
261            ColumnOwner::Planner {
262                kind,
263                planner_index,
264            } => f
265                .debug_struct("Planner")
266                .field("kind", kind)
267                .field("planner_index", planner_index)
268                .finish(),
269            ColumnOwner::FamilyChild { planner_kind } => f
270                .debug_struct("FamilyChild")
271                .field("planner_kind", planner_kind)
272                .finish(),
273            ColumnOwner::Relationship { relationship } => f
274                .debug_struct("Relationship")
275                .field("relationship", relationship)
276                .finish(),
277            ColumnOwner::DatabaseDefault => f.write_str("DatabaseDefault"),
278            ColumnOwner::GeneratedByDatabase => f.write_str("GeneratedByDatabase"),
279        }
280    }
281}
282
283/// How a relationship distributes children across parent rows.
284///
285/// This is the *value-assignment* distribution (which parent each child points
286/// to), distinct from the *count* distribution ([`crate::synthetic::model::
287/// ChildDistribution`]) that decides how many children a table has. `Weighted`
288/// and `Observed` both compile to a bounded histogram over parent row-index
289/// buckets at run time; they never enumerate a per-value list.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
291pub enum RelationshipDistribution {
292    /// Each child maps a uniformly random index into `[0, parent_count)`.
293    #[default]
294    Uniform,
295    /// Child row `r` references parent `r % parent_count`.
296    Sequential,
297    /// A bounded, seed-derived histogram concentrates children on some parents.
298    Weighted,
299    /// Same mechanism as [`Self::Weighted`]; named for provenance from an
300    /// observed source profile.
301    Observed,
302}
303
304/// A compiled relationship from a child table to a parent table, including the
305/// per-row parent assignment strategy executed by the engine.
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct CompiledRelationship {
308    /// The relationship's declared name, if any.
309    pub name: Option<String>,
310    /// The child columns that carry the foreign key.
311    pub columns: Vec<String>,
312    /// The referenced parent table.
313    pub parent_table: String,
314    /// The referenced parent columns.
315    pub parent_columns: Vec<String>,
316    /// How children are distributed across parent rows.
317    pub distribution: RelationshipDistribution,
318    /// Fraction of children (in parts-per-thousand) whose foreign key is `NULL`,
319    /// applied only when the child columns are nullable. Stored as an integer so
320    /// [`CompiledRelationship`] keeps `Eq`.
321    pub null_permille: u16,
322}
323
324/// A table's seed, resolved against the run's root seed and CLI overrides.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum ResolvedTableSeed {
327    /// Inherits the run's root seed; per-table streams derive from it.
328    Inherited(SeedRoot),
329    /// Pinned to an independent, table-local seed.
330    Fixed(SeedRoot),
331    /// Opted out of deterministic inheritance. The compiler draws and records
332    /// a fresh table-local root so compiled operators and runtime relationship
333    /// streams consume the same entropy for this run.
334    Random(SeedRoot),
335}
336
337/// Cost and size estimates for a plan.
338///
339/// Compilation records `total_rows`; estimates not calculated for the current
340/// plan remain zero.
341#[derive(Debug, Clone, Default, PartialEq, Eq)]
342pub struct PlanEstimates {
343    /// Sum of every selected table's resolved row count.
344    pub total_rows: u64,
345    /// Peak temporary storage for buffered or family state, when estimated.
346    pub temp_storage_bytes: u64,
347    /// Estimated verification cost, when calculated.
348    pub verification_cost: u64,
349}