Skip to main content

sql_splitter/generate/
engine.rs

1//! The [`GenerationEngine`]: streams rows from a compiled [`GenerationPlan`].
2//!
3//! The engine walks the plan's tables in dependency order (parents before
4//! children) and, for each table, produces every row by executing its column
5//! owners, then hands the row to a [`RowSink`]. It owns one reusable row buffer
6//! per active table so the hot loop never reallocates the row vector.
7//!
8//! # Foreign keys without spooling
9//!
10//! A foreign-key column cannot be produced from a per-row seed alone: choosing a
11//! parent row needs the parent's *key domain* and row count, cross-table state
12//! only the engine has. The engine therefore drives every FK column from its
13//! [`CompiledRelationship`], regardless of whether the compiler recorded the
14//! column as [`ColumnOwner::Relationship`] (an inferred FK) or
15//! [`ColumnOwner::Generator`] with kind `relation.foreign_key` (an explicit
16//! rule). Both converge here: the compiled generator marker is never executed;
17//! its `distribution` / `null_rate` arguments were folded into the relationship
18//! at compile time.
19//!
20//! # Reproducible key domains
21//!
22//! A parent key referenced by a child is materialized as a [`KeyDomain`]. A bare
23//! integer primary key (the database sequence a child references) compiles to a
24//! [`KeyDomain::DenseInteger`] over `1..=count`: the parent renders that id and
25//! the child regenerates parent row `n`'s key in closed form, without storing
26//! every key. Stateful or non-random-access parent keys are not materializable
27//! yet and report `GEN-KEY-DOMAIN-UNSUPPORTED` (protected key spooling is a
28//! later task).
29
30use std::collections::{BTreeMap, BTreeSet};
31use std::fmt;
32
33use rand::{Rng, RngExt};
34use rand_chacha::ChaCha8Rng;
35
36use super::output::{FamilyBudget, FamilyBuffer, SpillKind, SpooledRow, TempConfig};
37use super::plan::{
38    ColumnOwner, CompiledRelationship, GenerationPlan, PlannedColumn, PlannedTable,
39    RelationshipDistribution, ResolvedTableSeed,
40};
41use super::registry::{KeyRecipe, RowContext, RowView};
42use super::seed::{SeedRoot, StreamId};
43use super::value::{GenerateError, GeneratedValue};
44
45/// A single generated row, handed to a [`RowSink`].
46///
47/// `values` aligns positionally with the table's `columns`. The engine reuses
48/// one allocation across rows, moving the vector in and out of each
49/// `GeneratedRow`, so a sink that needs to retain values must clone them.
50#[derive(Debug, Clone, PartialEq)]
51pub struct GeneratedRow {
52    /// Index of the owning table within the plan's `tables`.
53    pub table_index: usize,
54    /// Zero-based index of this row within its table.
55    pub row_index: u64,
56    /// Column values, positionally aligned with the table's columns.
57    pub values: Vec<GeneratedValue>,
58}
59
60/// A summary of a completed engine run: rows written across every table.
61///
62/// This is the low-level engine-only report; the public
63/// [`crate::generate::Generate`] API wraps it in a richer
64/// [`crate::generate::GenerateReport`] that also carries diagnostics.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
66pub struct EngineReport {
67    /// Total rows written across every table.
68    pub rows_written: u64,
69}
70
71/// A destination for generated rows: notified at each table boundary and given
72/// every row in order.
73pub trait RowSink {
74    /// Called once before any of `table`'s rows are written.
75    fn begin_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError>;
76
77    /// Called once per generated row of `table`, in row order.
78    fn write_row(&mut self, table: &PlannedTable, row: &GeneratedRow) -> Result<(), GenerateError>;
79
80    /// Called once after all of `table`'s rows are written.
81    fn end_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError>;
82}
83
84/// A random-access key generator: reproduces the key of parent row `row_index`
85/// in closed form, without materializing the intervening rows. Used as a
86/// component of a composite [`KeyDomain`].
87pub trait RandomAccessKeyGenerator: Send {
88    /// The key value at parent row `row_index`.
89    fn key_at(&self, row_index: u64) -> GeneratedValue;
90}
91
92/// A dense integer key: `start + step * row_index`. The closed form a bare
93/// integer primary key (a database sequence) reduces to.
94#[derive(Debug, Clone, Copy)]
95pub struct DenseIntegerKey {
96    /// The key of parent row 0.
97    pub start: i128,
98    /// The per-row increment.
99    pub step: i128,
100}
101
102impl RandomAccessKeyGenerator for DenseIntegerKey {
103    fn key_at(&self, row_index: u64) -> GeneratedValue {
104        GeneratedValue::Integer(self.start + self.step * row_index as i128)
105    }
106}
107
108/// A per-row-reseeded random-access UUID key (RFC 4122 v4). Row `n`'s key
109/// derives from the parent table's seed and a `primary_key.row.<n>` stream, so
110/// any parent row's UUID is reproducible by index without storing every key.
111pub struct SeededUuidKey {
112    /// The parent table's resolved seed root.
113    pub seed: SeedRoot,
114    /// The parent table name (stream identity).
115    pub table: String,
116    /// The parent key column name (stream identity).
117    pub column: String,
118}
119
120impl RandomAccessKeyGenerator for SeededUuidKey {
121    fn key_at(&self, row_index: u64) -> GeneratedValue {
122        seeded_uuid(self.seed, &self.table, &self.column, row_index)
123    }
124}
125
126/// Derive the RFC 4122 v4 UUID for parent row `row_index` from a fresh,
127/// row-indexed stream. Shared by [`SeededUuidKey`] and the parent's own key
128/// rendering so a parent PK and the child's reference agree exactly.
129fn seeded_uuid(seed: SeedRoot, table: &str, column: &str, row_index: u64) -> GeneratedValue {
130    let mut rng = seed.stream(StreamId::operator(
131        table,
132        column,
133        format!("primary_key.row.{row_index}"),
134    ));
135    let mut bytes = [0u8; 16];
136    rng.fill_bytes(&mut bytes);
137    bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
138    bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
139    let hex = hex::encode(bytes);
140    GeneratedValue::Text(format!(
141        "{}-{}-{}-{}-{}",
142        &hex[0..8],
143        &hex[8..12],
144        &hex[12..16],
145        &hex[16..20],
146        &hex[20..32]
147    ))
148}
149
150/// A referenced parent key column: the generator's context-free [`KeyRecipe`]
151/// shape plus the parent table/column/seed context the engine supplies, and the
152/// row count. Renders the parent's own key and reconstructs a random-access
153/// generator for child selection — both from the one shared derivation, so a
154/// parent PK and the child's reference agree by construction.
155struct ParentKey {
156    shape: KeyRecipe,
157    seed: SeedRoot,
158    table: String,
159    column: String,
160    count: u64,
161}
162
163impl ParentKey {
164    /// The key value at parent `row_index` (used to render the parent's own PK).
165    fn key_at(&self, row_index: u64) -> GeneratedValue {
166        match self.shape {
167            KeyRecipe::Dense { start, step } => {
168                GeneratedValue::Integer(start + step * row_index as i128)
169            }
170            KeyRecipe::Uuid => seeded_uuid(self.seed, &self.table, &self.column, row_index),
171        }
172    }
173
174    /// A fresh random-access generator realizing this key (for child selection).
175    fn generator(&self) -> Box<dyn RandomAccessKeyGenerator> {
176        match self.shape {
177            KeyRecipe::Dense { start, step } => Box::new(DenseIntegerKey { start, step }),
178            KeyRecipe::Uuid => Box::new(SeededUuidKey {
179                seed: self.seed,
180                table: self.table.clone(),
181                column: self.column.clone(),
182            }),
183        }
184    }
185}
186
187/// A reproducible domain of parent keys a child references, addressable by
188/// parent row index without storing every key.
189pub enum KeyDomain {
190    /// A contiguous integer sequence `start, start+step, …`, `count` rows long.
191    DenseInteger {
192        /// The key of parent row 0.
193        start: i128,
194        /// The per-row increment.
195        step: i128,
196        /// The number of parent rows.
197        count: u64,
198    },
199    /// A single random-access key column (e.g. a seeded UUID/semantic key).
200    Deterministic {
201        /// The number of parent rows.
202        count: u64,
203        /// Reproduces any parent row's key on demand.
204        generator: Box<dyn RandomAccessKeyGenerator>,
205    },
206    /// A composite key: one parent row index yields every component. Selection
207    /// chooses the index once; each component is derived from that same index.
208    Composite {
209        /// The number of parent rows.
210        count: u64,
211        /// One generator per key component, in parent-column order.
212        components: Vec<Box<dyn RandomAccessKeyGenerator>>,
213    },
214    /// A key domain whose value may be `NULL` (a nullable referenced key).
215    Nullable(Box<KeyDomain>),
216}
217
218impl fmt::Debug for KeyDomain {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self {
221            KeyDomain::DenseInteger { start, step, count } => f
222                .debug_struct("DenseInteger")
223                .field("start", start)
224                .field("step", step)
225                .field("count", count)
226                .finish(),
227            KeyDomain::Deterministic { count, .. } => f
228                .debug_struct("Deterministic")
229                .field("count", count)
230                .finish_non_exhaustive(),
231            KeyDomain::Composite { count, components } => f
232                .debug_struct("Composite")
233                .field("count", count)
234                .field("components", &components.len())
235                .finish(),
236            KeyDomain::Nullable(inner) => f.debug_tuple("Nullable").field(inner).finish(),
237        }
238    }
239}
240
241impl KeyDomain {
242    /// The number of parent rows this domain addresses.
243    pub fn count(&self) -> u64 {
244        match self {
245            KeyDomain::DenseInteger { count, .. }
246            | KeyDomain::Deterministic { count, .. }
247            | KeyDomain::Composite { count, .. } => *count,
248            KeyDomain::Nullable(inner) => inner.count(),
249        }
250    }
251
252    /// The single-column key at parent `row_index` (used when a parent key is
253    /// materialized into the parent's own row).
254    fn key_at(&self, row_index: u64) -> GeneratedValue {
255        match self {
256            KeyDomain::DenseInteger { start, step, .. } => {
257                GeneratedValue::Integer(start + step * row_index as i128)
258            }
259            KeyDomain::Deterministic { generator, .. } => generator.key_at(row_index),
260            KeyDomain::Composite { components, .. } => components
261                .first()
262                .map_or(GeneratedValue::Null, |c| c.key_at(row_index)),
263            KeyDomain::Nullable(inner) => inner.key_at(row_index),
264        }
265    }
266
267    /// The full key row (one value per key column) at parent `row_index`.
268    fn key_row(&self, row_index: u64) -> Vec<GeneratedValue> {
269        match self {
270            KeyDomain::Composite { components, .. } => {
271                components.iter().map(|c| c.key_at(row_index)).collect()
272            }
273            KeyDomain::Nullable(inner) => inner.key_row(row_index),
274            _ => vec![self.key_at(row_index)],
275        }
276    }
277}
278
279/// Executes a compiled [`GenerationPlan`], streaming rows to a [`RowSink`].
280pub struct GenerationEngine {
281    plan: GenerationPlan,
282}
283
284impl GenerationEngine {
285    /// Build an engine over a compiled plan.
286    pub fn new(plan: GenerationPlan) -> Self {
287        Self { plan }
288    }
289
290    /// Generate every table's rows in dependency order, writing each to `sink`.
291    pub fn run(mut self, sink: &mut dyn RowSink) -> Result<EngineReport, GenerateError> {
292        let key_domains = build_key_domains(&self.plan)?;
293        let family_budget = FamilyBudget {
294            max_bytes: self.plan.family_budget_bytes,
295        };
296        // A family child table is generated from its parent's spooled family
297        // rows (drained at this position) rather than the ordinary row loop.
298        let table_index_by_name: BTreeMap<String, usize> = self
299            .plan
300            .tables
301            .iter()
302            .enumerate()
303            .map(|(index, table)| (table.name.clone(), index))
304            .collect();
305        let family_children = collect_family_children(&self.plan.tables);
306
307        // Take ownership of the tables so per-column compiled generators can be
308        // advanced mutably while the rest of the plan stays borrowable.
309        let tables = std::mem::take(&mut self.plan.tables);
310        let mut rows_written = 0u64;
311        // Buffered family child rows, keyed by child table name, accumulated as
312        // each parent is generated and drained when the child is reached.
313        let mut family_buffers: BTreeMap<String, FamilyBuffer> = BTreeMap::new();
314
315        for (table_index, mut table) in tables.into_iter().enumerate() {
316            // A family child: render the spooled rows produced by its parent.
317            if let Some(link) = family_children.get(&table.name) {
318                rows_written += render_family_child(
319                    table_index,
320                    &mut table,
321                    link,
322                    &mut family_buffers,
323                    &key_domains,
324                    sink,
325                )?;
326                continue;
327            }
328
329            sink.begin_table(&table)?;
330            let exec = TableExec::build(&table, &key_domains)?;
331            let ncols = table.columns.len();
332            let mut buffer = vec![GeneratedValue::Null; ncols];
333            let mut selectors = exec.selectors;
334            let mut planners = exec.planners;
335            let eval_order = table.eval_order.clone();
336            let mut pass = GeneratorPass::new(&table, &exec.dense_indices);
337
338            for row_index in 0..table.rows {
339                // Non-reading owners first: defaults, materialized parent keys,
340                // then foreign-key selections.
341                for &i in &exec.defaults {
342                    buffer[i] = GeneratedValue::Default;
343                }
344                for (i, key) in &exec.dense {
345                    buffer[*i] = key_domains[key].key_at(row_index);
346                }
347                for selector in selectors.iter_mut() {
348                    selector.assign(row_index, &mut buffer);
349                }
350                // Table planners produce their owned columns together, before
351                // the per-column generator pass (a planner-owned column takes
352                // its value from the planner, not a generator).
353                for exec in planners.iter_mut() {
354                    let planner = &mut table.planners[exec.index];
355                    planner.generate_row(row_index, &mut exec.scratch)?;
356                    for (slot, value) in exec.members.iter().zip(exec.scratch.iter_mut()) {
357                        buffer[*slot] = std::mem::replace(value, GeneratedValue::Null);
358                    }
359                    // A family planner also produced this order's child lines:
360                    // spool them (bounded — spills past the family budget) so
361                    // they can be drained when the child table is reached.
362                    if let Some(child_name) = planner.family_child_table().map(str::to_string) {
363                        let child_index =
364                            table_index_by_name.get(&child_name).copied().unwrap_or(0);
365                        let mut child_rows = planner.take_family_children();
366                        if let Some(first) = child_rows.next() {
367                            let buffer = family_buffers.entry(child_name).or_insert_with(|| {
368                                FamilyBuffer::new(
369                                    family_budget,
370                                    child_index as u32,
371                                    TempConfig::default(),
372                                    SpillKind::Child,
373                                )
374                            });
375                            for values in std::iter::once(first).chain(child_rows) {
376                                let values = values?;
377                                buffer
378                                    .push(SpooledRow {
379                                        table_id: child_index as u32,
380                                        row_index,
381                                        values,
382                                    })
383                                    .map_err(family_spool_error)?;
384                            }
385                        }
386                    }
387                }
388                // Column generators last, in topological read order so a
389                // generator that reads a sibling runs after it regardless of
390                // schema position. A materialized referenced key (in `dense`) is
391                // rendered from its domain, so it is skipped even though it is
392                // generator-owned.
393                pass.run(
394                    &mut table.columns,
395                    &mut buffer,
396                    &eval_order,
397                    &exec.dense_indices,
398                    row_index,
399                )?;
400
401                let generated = GeneratedRow {
402                    table_index,
403                    row_index,
404                    values: std::mem::take(&mut buffer),
405                };
406                sink.write_row(&table, &generated)?;
407                buffer = generated.values;
408                rows_written += 1;
409            }
410
411            sink.end_table(&table)?;
412        }
413
414        Ok(EngineReport { rows_written })
415    }
416}
417
418/// A family child table's link to the parent family: the child columns the
419/// planner produces (in spooled-value order) and the child relationship carrying
420/// the foreign key back to the parent.
421struct FamilyChildLink {
422    child_writes: Vec<String>,
423    relationship: String,
424}
425
426/// Discover every family child table declared by a planner on any parent table.
427fn collect_family_children(tables: &[PlannedTable]) -> BTreeMap<String, FamilyChildLink> {
428    let mut links = BTreeMap::new();
429    for table in tables {
430        for planner in &table.planners {
431            if let (Some(child), Some(relationship)) =
432                (planner.family_child_table(), planner.family_relationship())
433            {
434                links.insert(
435                    child.to_string(),
436                    FamilyChildLink {
437                        child_writes: planner.child_writes().to_vec(),
438                        relationship: relationship.to_string(),
439                    },
440                );
441            }
442        }
443    }
444    links
445}
446
447/// Render a family child table from the rows its parent spooled: each drained
448/// row carries its parent row index (so the foreign key binds to the exact
449/// parent that produced it) and the planner-owned child column values; the
450/// remaining columns (the child primary key, other generators) run their own
451/// owners. Returns the number of child rows written.
452fn render_family_child(
453    table_index: usize,
454    table: &mut PlannedTable,
455    link: &FamilyChildLink,
456    family_buffers: &mut BTreeMap<String, FamilyBuffer>,
457    key_domains: &BTreeMap<(String, String), ParentKey>,
458    sink: &mut dyn RowSink,
459) -> Result<u64, GenerateError> {
460    sink.begin_table(table)?;
461    let mut exec = TableExec::build(table, key_domains)?;
462    let names: Vec<String> = table
463        .columns
464        .iter()
465        .map(|column| column.schema.name.clone())
466        .collect();
467    let ncols = table.columns.len();
468
469    let slot_of = |name: &str| names.iter().position(|candidate| candidate == name);
470    let child_slots: Vec<Option<usize>> =
471        link.child_writes.iter().map(|name| slot_of(name)).collect();
472
473    // The relationship (on this child) whose FK is set from the owning parent.
474    let fk: Vec<(usize, (String, String))> = table
475        .relationships
476        .iter()
477        .find(|relationship| relationship.name.as_deref() == Some(link.relationship.as_str()))
478        .map(|relationship| {
479            relationship
480                .columns
481                .iter()
482                .zip(&relationship.parent_columns)
483                .filter_map(|(child_col, parent_col)| {
484                    slot_of(child_col).map(|slot| {
485                        (
486                            slot,
487                            (relationship.parent_table.clone(), parent_col.clone()),
488                        )
489                    })
490                })
491                .collect()
492        })
493        .unwrap_or_default();
494    // The child column slots carrying the family key, used to skip the family
495    // relationship's own selector (it is bound per-parent, not distributed).
496    let family_member_slots: Vec<usize> = fk.iter().map(|(slot, _)| *slot).collect();
497
498    let mut family_buffer = family_buffers.remove(&table.name);
499    let mut replay = match family_buffer.as_mut() {
500        Some(buffer) => Some(buffer.replay_rows().map_err(family_spool_error)?),
501        None => None,
502    };
503
504    let mut rows_written = 0u64;
505    let mut buffer = vec![GeneratedValue::Null; ncols];
506    let eval_order = table.eval_order.clone();
507    let mut pass = GeneratorPass::new(table, &exec.dense_indices);
508    for (child_index, spooled) in replay.iter_mut().flatten().enumerate() {
509        let spooled = spooled.map_err(family_spool_error)?;
510        let child_index = child_index as u64;
511        let parent_index = spooled.row_index;
512        for value in buffer.iter_mut() {
513            *value = GeneratedValue::Null;
514        }
515        for &i in &exec.defaults {
516            buffer[i] = GeneratedValue::Default;
517        }
518        for (i, key) in &exec.dense {
519            buffer[*i] = key_domains[key].key_at(child_index);
520        }
521        // Planner-owned child columns from the spooled values.
522        for (slot, value) in child_slots.iter().zip(spooled.values) {
523            if let Some(slot) = slot {
524                buffer[*slot] = value;
525            }
526        }
527        // Other relationships on this child (e.g. a `product_id` FK) are assigned
528        // by their selectors, exactly as on a non-family table. The family
529        // relationship's own selector is skipped: its key is bound below to the
530        // exact parent that produced this line, not by the child-row
531        // distribution.
532        for selector in exec.selectors.iter_mut() {
533            if selector.members == family_member_slots {
534                continue;
535            }
536            selector.assign(child_index, &mut buffer);
537        }
538        // Foreign key(s) bound to the exact parent that produced this line.
539        for (slot, key) in &fk {
540            buffer[*slot] = key_domains
541                .get(key)
542                .map_or(GeneratedValue::Null, |parent| parent.key_at(parent_index));
543        }
544        // Remaining generator-owned columns (e.g. the child primary key), in the
545        // same topological read order as the ordinary table path.
546        pass.run(
547            &mut table.columns,
548            &mut buffer,
549            &eval_order,
550            &exec.dense_indices,
551            child_index,
552        )?;
553
554        let generated = GeneratedRow {
555            table_index,
556            row_index: child_index,
557            values: std::mem::take(&mut buffer),
558        };
559        sink.write_row(table, &generated)?;
560        buffer = generated.values;
561        rows_written += 1;
562    }
563
564    sink.end_table(table)?;
565    Ok(rows_written)
566}
567
568/// Wrap a family spool I/O failure as a generation error.
569fn family_spool_error(error: std::io::Error) -> GenerateError {
570    GenerateError::diagnostic(
571        &crate::diagnostic::codes::FAMILY_SPOOL,
572        "runtime.family_spool",
573        format!("buffering family child rows failed: {error}"),
574    )
575}
576
577/// Whether a generator kind is a foreign-key marker driven by the engine rather
578/// than executed as a column generator.
579fn is_fk_kind(kind: &str) -> bool {
580    kind == "relation.foreign_key" || kind == "relation.composite_key"
581}
582
583/// Whether a family is an integer family (materializable as a dense key).
584fn is_integer_family(family: &crate::synthetic::schema::SqlTypeFamily) -> bool {
585    use crate::synthetic::schema::SqlTypeFamily;
586    matches!(family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
587}
588
589/// The concrete [`SeedRoot`] a resolved table seed derives runtime streams
590/// from. Random roots are drawn during compilation so runtime streams match the
591/// roots that compiled the table's operators.
592fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
593    match seed {
594        ResolvedTableSeed::Inherited(root)
595        | ResolvedTableSeed::Fixed(root)
596        | ResolvedTableSeed::Random(root) => *root,
597    }
598}
599
600/// Build a [`ParentKey`] for every parent key column referenced by a
601/// relationship anywhere in the plan. A referenced key must be reproducible by
602/// random access (regenerated from a per-row seed, never spooled): a bare
603/// integer primary key is a dense sequence, and a `uuid`-generator key reseeds
604/// per row. A genuinely stateful or otherwise non-random-access key reports
605/// `GEN-KEY-DOMAIN-UNSUPPORTED` (protected key spooling is a later task).
606fn build_key_domains(
607    plan: &GenerationPlan,
608) -> Result<BTreeMap<(String, String), ParentKey>, GenerateError> {
609    let mut domains: BTreeMap<(String, String), ParentKey> = BTreeMap::new();
610    for table in &plan.tables {
611        for relationship in &table.relationships {
612            for parent_column in &relationship.parent_columns {
613                let key = (relationship.parent_table.clone(), parent_column.clone());
614                if domains.contains_key(&key) {
615                    continue;
616                }
617                let Some(parent) = plan.table(&relationship.parent_table) else {
618                    continue;
619                };
620                let Some(column) = parent
621                    .columns
622                    .iter()
623                    .find(|column| &column.schema.name == parent_column)
624                else {
625                    continue;
626                };
627                let shape = match &column.owner {
628                    // A bare integer primary key is a database sequence:
629                    // children reference 1..=count and the parent renders it.
630                    ColumnOwner::GeneratedByDatabase
631                        if is_integer_family(&column.schema.family) =>
632                    {
633                        KeyRecipe::Dense { start: 1, step: 1 }
634                    }
635                    // Any generator that describes itself as a random-access key
636                    // (`sequence` -> Dense, `uuid` -> Uuid) is materializable.
637                    ColumnOwner::Generator { compiled, .. } => match compiled.key_recipe() {
638                        Some(shape) => shape,
639                        None => {
640                            return Err(unsupported_key(&relationship.parent_table, parent_column))
641                        }
642                    },
643                    _ => return Err(unsupported_key(&relationship.parent_table, parent_column)),
644                };
645                domains.insert(
646                    key,
647                    ParentKey {
648                        shape,
649                        seed: seed_root_of(&parent.seed),
650                        table: parent.name.clone(),
651                        column: parent_column.clone(),
652                        count: parent.rows,
653                    },
654                );
655            }
656        }
657    }
658    Ok(domains)
659}
660
661/// The `GEN-KEY-DOMAIN-UNSUPPORTED` error for a parent key that cannot be
662/// reproduced by random access (a stateful or otherwise non-describable key).
663fn unsupported_key(parent_table: &str, parent_column: &str) -> GenerateError {
664    GenerateError::diagnostic(
665        &crate::diagnostic::codes::KEY_DOMAIN_UNSUPPORTED,
666        format!("tables.{parent_table}.columns.{parent_column}"),
667        format!(
668            "parent key `{parent_table}.{parent_column}` cannot be materialized for random \
669             access; supported: bare integer primary keys, `sequence`, and `uuid` keys \
670             (stateful keys await protected key spooling)"
671        ),
672    )
673}
674
675/// The per-column execution plan for one table: which columns are constant
676/// database placeholders, which are materialized parent keys, and which are
677/// foreign-key selections.
678struct TableExec {
679    /// Columns emitted as `DEFAULT` (database-filled or unmodeled placeholders).
680    defaults: Vec<usize>,
681    /// Materialized referenced parent-key columns, keyed into the domain map.
682    dense: Vec<(usize, (String, String))>,
683    /// The set of `dense` column indices, for quick exclusion from the generator
684    /// pass (a referenced random-access key is rendered from its domain, not its
685    /// column generator).
686    dense_indices: BTreeSet<usize>,
687    /// Foreign-key selectors, one per active relationship.
688    selectors: Vec<FkSelector>,
689    /// Table planners that produce owned columns, one per active planner.
690    planners: Vec<PlannerExec>,
691}
692
693impl TableExec {
694    fn build(
695        table: &PlannedTable,
696        key_domains: &BTreeMap<(String, String), ParentKey>,
697    ) -> Result<Self, GenerateError> {
698        let mut dense: Vec<(usize, (String, String))> = Vec::new();
699        let mut dense_indices: BTreeSet<usize> = BTreeSet::new();
700        for (i, column) in table.columns.iter().enumerate() {
701            let key = (table.name.clone(), column.schema.name.clone());
702            if key_domains.contains_key(&key) {
703                dense.push((i, key));
704                dense_indices.insert(i);
705            }
706        }
707
708        let seed_root = seed_root_of(&table.seed);
709        let mut selectors: Vec<FkSelector> = Vec::new();
710        let mut member_indices: BTreeSet<usize> = BTreeSet::new();
711        for relationship in &table.relationships {
712            if let Some(selector) = FkSelector::build(table, relationship, key_domains, seed_root)?
713            {
714                member_indices.extend(selector.members.iter().copied());
715                selectors.push(selector);
716            }
717        }
718
719        // Map each planner's owned columns (by name) to row-buffer slots so the
720        // engine can scatter the planner's per-row output into place. Slots a
721        // planner owns are excluded from the DEFAULT pass below.
722        let mut planners: Vec<PlannerExec> = Vec::new();
723        let mut planner_indices: BTreeSet<usize> = BTreeSet::new();
724        for (index, planner) in table.planners.iter().enumerate() {
725            let members: Option<Vec<usize>> = planner
726                .writes()
727                .iter()
728                .map(|name| {
729                    table
730                        .columns
731                        .iter()
732                        .position(|column| &column.schema.name == name)
733                })
734                .collect();
735            let Some(members) = members else {
736                continue;
737            };
738            planner_indices.extend(members.iter().copied());
739            let scratch = vec![GeneratedValue::Null; members.len()];
740            planners.push(PlannerExec {
741                index,
742                members,
743                scratch,
744            });
745        }
746
747        let mut defaults: Vec<usize> = Vec::new();
748        for i in 0..table.columns.len() {
749            if dense_indices.contains(&i)
750                || member_indices.contains(&i)
751                || planner_indices.contains(&i)
752            {
753                continue;
754            }
755            match &table.columns[i].owner {
756                // A live column generator is executed in the generator pass.
757                ColumnOwner::Generator { kind, .. } if !is_fk_kind(kind) => {}
758                // Everything else (database-filled, defaults, a planner that
759                // never mapped, or an FK that never resolved a selector) renders
760                // as DEFAULT.
761                _ => defaults.push(i),
762            }
763        }
764
765        Ok(TableExec {
766            defaults,
767            dense,
768            dense_indices,
769            selectors,
770            planners,
771        })
772    }
773}
774
775/// A per-planner execution binding: which compiled planner to invoke and the
776/// row-buffer slots its produced columns scatter into.
777struct PlannerExec {
778    /// Index into [`PlannedTable::planners`].
779    index: usize,
780    /// Row-buffer slots for the planner's written columns, in `writes()` order.
781    members: Vec<usize>,
782    /// Reusable scratch aligned with `members`: the planner writes here each
783    /// row, then the engine moves each value into its buffer slot.
784    scratch: Vec<GeneratedValue>,
785}
786
787/// A per-relationship foreign-key selector: picks a parent row per child row and
788/// writes the resulting key(s) into the child's foreign-key columns.
789struct FkSelector {
790    /// Child column indices carrying the key, in parent-column order.
791    members: Vec<usize>,
792    /// The parent key domain.
793    domain: KeyDomain,
794    /// The number of parent rows.
795    parent_count: u64,
796    /// How children are distributed across parents.
797    distribution: RelationshipDistribution,
798    /// Fraction of children whose key is `NULL` (nullable columns only).
799    null_rate: f64,
800    /// Whether every member column is nullable.
801    nullable: bool,
802    /// The relationship's per-row RNG, advanced sequentially.
803    rng: ChaCha8Rng,
804    /// Cumulative bucket weights for a weighted/observed histogram; empty
805    /// otherwise.
806    histogram: Vec<f64>,
807}
808
809impl FkSelector {
810    fn build(
811        table: &PlannedTable,
812        relationship: &CompiledRelationship,
813        key_domains: &BTreeMap<(String, String), ParentKey>,
814        seed_root: SeedRoot,
815    ) -> Result<Option<Self>, GenerateError> {
816        let Some(members): Option<Vec<usize>> = relationship
817            .columns
818            .iter()
819            .map(|name| {
820                table
821                    .columns
822                    .iter()
823                    .position(|column| &column.schema.name == name)
824            })
825            .collect()
826        else {
827            return Ok(None);
828        };
829
830        // Each parent key column contributes a cloneable recipe; a single index
831        // is chosen per child row and every component is derived from it.
832        let Some(parents): Option<Vec<&ParentKey>> = relationship
833            .parent_columns
834            .iter()
835            .map(|parent_column| {
836                key_domains.get(&(relationship.parent_table.clone(), parent_column.clone()))
837            })
838            .collect()
839        else {
840            return Ok(None);
841        };
842        let Some(parent) = parents.first() else {
843            return Ok(None);
844        };
845        let parent_count = parent.count;
846
847        let domain = if parents.len() == 1 {
848            match parents[0].shape {
849                KeyRecipe::Dense { start, step } => KeyDomain::DenseInteger {
850                    start,
851                    step,
852                    count: parent_count,
853                },
854                KeyRecipe::Uuid => KeyDomain::Deterministic {
855                    count: parent_count,
856                    generator: parents[0].generator(),
857                },
858            }
859        } else {
860            KeyDomain::Composite {
861                count: parent_count,
862                components: parents.iter().map(|p| p.generator()).collect(),
863            }
864        };
865
866        let nullable = relationship.columns.iter().all(|name| {
867            table
868                .columns
869                .iter()
870                .find(|column| &column.schema.name == name)
871                .is_some_and(|column| column.schema.nullable)
872        });
873        if table.rows > 0 && parent_count == 0 && !nullable {
874            return Err(GenerateError::diagnostic(
875                &crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED,
876                format!("tables.{}.relationships", table.name),
877                format!(
878                    "table `{}` has {} row(s), but required relationship `{}` targets empty parent table `{}`",
879                    table.name,
880                    table.rows,
881                    relationship.name.as_deref().unwrap_or("(unnamed)"),
882                    relationship.parent_table
883                ),
884            ));
885        }
886        let null_rate = f64::from(relationship.null_permille) / 1000.0;
887        // TODO(deferred, L4): `columns.join(",")` is an ambiguous stream
888        // identity — a column literally named `a,b` collides with the set
889        // `[a, b]`, and two relationships over the same child columns share a
890        // stream (correlating FK selectors that should be independent). A robust
891        // identity (length-prefixed columns, or the relationship name + parent
892        // table) would change every seeded FK stream, so this is deferred to
893        // avoid churning all reproducible FK output for a pathological case.
894        let rng = seed_root.stream(StreamId::operator(
895            table.name.as_str(),
896            relationship.columns.join(","),
897            "relation.foreign_key",
898        ));
899        let histogram = match relationship.distribution {
900            RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
901                build_histogram(parent_count)
902            }
903            RelationshipDistribution::Uniform | RelationshipDistribution::Sequential => Vec::new(),
904        };
905
906        Ok(Some(FkSelector {
907            members,
908            domain,
909            parent_count,
910            distribution: relationship.distribution,
911            null_rate,
912            nullable,
913            rng,
914            histogram,
915        }))
916    }
917
918    /// Assign this relationship's key(s) for the child at `row_index`.
919    fn assign(&mut self, row_index: u64, buffer: &mut [GeneratedValue]) {
920        // Null is a separate first decision, before any parent is chosen.
921        if self.nullable && self.null_rate > 0.0 && self.rng.random::<f64>() < self.null_rate {
922            self.fill(buffer, |_| GeneratedValue::Null);
923            return;
924        }
925        if self.parent_count == 0 {
926            self.fill(buffer, |_| GeneratedValue::Null);
927            return;
928        }
929        let parent = self.pick(row_index);
930        let keys = self.domain.key_row(parent);
931        for (&member, key) in self.members.iter().zip(keys) {
932            buffer[member] = key;
933        }
934    }
935
936    fn fill(&self, buffer: &mut [GeneratedValue], value: impl Fn(usize) -> GeneratedValue) {
937        for (position, &member) in self.members.iter().enumerate() {
938            buffer[member] = value(position);
939        }
940    }
941
942    /// Choose the parent row index for the child at `row_index`.
943    fn pick(&mut self, row_index: u64) -> u64 {
944        match self.distribution {
945            RelationshipDistribution::Uniform => self.rng.random_range(0..self.parent_count),
946            RelationshipDistribution::Sequential => row_index % self.parent_count,
947            RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
948                self.sample_histogram()
949            }
950        }
951    }
952
953    /// Draw a parent row index from the bounded histogram.
954    fn sample_histogram(&mut self) -> u64 {
955        let buckets = self.histogram.len();
956        if buckets == 0 {
957            return self.rng.random_range(0..self.parent_count);
958        }
959        let total = self.histogram[buckets - 1];
960        let target = self.rng.random::<f64>() * total;
961        let bucket = self
962            .histogram
963            .partition_point(|&cumulative| cumulative <= target)
964            .min(buckets - 1) as u64;
965
966        // Map the bucket back to a parent row index. With one bucket per parent
967        // (the common small-fan-in case) this is the identity.
968        let base = self.parent_count / buckets as u64;
969        let remainder = self.parent_count % buckets as u64;
970        let start = bucket * base + bucket.min(remainder);
971        let size = base + u64::from(bucket < remainder);
972        if size <= 1 {
973            start
974        } else {
975            start + self.rng.random_range(0..size)
976        }
977    }
978}
979
980/// Build a bounded, decaying histogram over `parent_count` parents: earlier
981/// parents carry proportionally more weight, capped at 256 buckets so memory
982/// stays bounded regardless of parent count.
983fn build_histogram(parent_count: u64) -> Vec<f64> {
984    let buckets = parent_count.min(256) as usize;
985    let mut cumulative = Vec::with_capacity(buckets);
986    let mut acc = 0.0;
987    for bucket in 0..buckets {
988        acc += 1.0 / (bucket as f64 + 1.0);
989        cumulative.push(acc);
990    }
991    cumulative
992}
993
994/// A [`RowView`] over the columns produced so far in the current row.
995/// A read-only view over the whole in-progress row, exposing every column that
996/// has already been produced this row. A column is readable once its value is
997/// present: non-generator columns are filled before the generator pass, and
998/// generator columns flip available as the pass produces them in
999/// [`PlannedTable::eval_order`]. A column not yet produced (or the reader's own
1000/// slot) reads back as `None`, preserving the guarantee that a generator can
1001/// only observe values that already exist — regardless of schema position.
1002struct FullRow<'a> {
1003    index: &'a BTreeMap<String, usize>,
1004    values: &'a [GeneratedValue],
1005    available: &'a [bool],
1006}
1007
1008impl RowView for FullRow<'_> {
1009    fn get(&self, column: &str) -> Option<&GeneratedValue> {
1010        let &position = self.index.get(column)?;
1011        self.available[position].then(|| &self.values[position])
1012    }
1013}
1014
1015/// Runs a table's per-row generator pass in topological read order, reused
1016/// across the ordinary table loop and the family-child spool path. Precomputed
1017/// once per table: a column-name index for sibling reads and the base
1018/// availability mask (every column the pass does *not* produce is filled before
1019/// the pass, so it is available from the start; the pass's own columns start
1020/// unavailable and flip as they are produced).
1021struct GeneratorPass {
1022    index: BTreeMap<String, usize>,
1023    base_available: Vec<bool>,
1024    available: Vec<bool>,
1025}
1026
1027impl GeneratorPass {
1028    fn new(table: &PlannedTable, dense_indices: &BTreeSet<usize>) -> Self {
1029        let ncols = table.columns.len();
1030        let index = table
1031            .columns
1032            .iter()
1033            .enumerate()
1034            .map(|(i, column)| (column.schema.name.clone(), i))
1035            .collect();
1036        let mut base_available = vec![true; ncols];
1037        for (i, column) in table.columns.iter().enumerate() {
1038            if dense_indices.contains(&i) {
1039                continue;
1040            }
1041            if let ColumnOwner::Generator { kind, .. } = &column.owner {
1042                if !is_fk_kind(kind) {
1043                    // Produced by this pass, so unavailable until generated.
1044                    base_available[i] = false;
1045                }
1046            }
1047        }
1048        Self {
1049            index,
1050            base_available,
1051            available: vec![true; ncols],
1052        }
1053    }
1054
1055    /// Generate every pass-owned column of `columns` into `buffer` in
1056    /// `eval_order`, letting each generator (and its modifiers) read any sibling
1057    /// already produced this row via a [`FullRow`] view.
1058    fn run(
1059        &mut self,
1060        columns: &mut [PlannedColumn],
1061        buffer: &mut [GeneratedValue],
1062        eval_order: &[usize],
1063        dense_indices: &BTreeSet<usize>,
1064        row_index: u64,
1065    ) -> Result<(), GenerateError> {
1066        self.available.copy_from_slice(&self.base_available);
1067        for &i in eval_order {
1068            if dense_indices.contains(&i) {
1069                continue;
1070            }
1071            let column = &mut columns[i];
1072            let ColumnOwner::Generator { kind, compiled } = &mut column.owner else {
1073                continue;
1074            };
1075            if is_fk_kind(kind) {
1076                continue;
1077            }
1078            // Move the output slot out so the view can borrow the rest of the
1079            // row immutably while the generator writes its own value.
1080            let mut out = std::mem::replace(&mut buffer[i], GeneratedValue::Null);
1081            {
1082                let view = FullRow {
1083                    index: &self.index,
1084                    values: buffer,
1085                    available: &self.available,
1086                };
1087                let context = RowContext::new(row_index, &view);
1088                compiled.generate(&context, &mut out)?;
1089                for modifier in column.modifiers.iter_mut() {
1090                    modifier.apply(&context, &mut out)?;
1091                }
1092            }
1093            buffer[i] = out;
1094            self.available[i] = true;
1095        }
1096        Ok(())
1097    }
1098}