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 mut 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                let actual = render_family_child(
319                    table_index,
320                    &mut table,
321                    link,
322                    &mut family_buffers,
323                    &key_domains,
324                    sink,
325                )?;
326                rows_written += actual;
327                // The realized family-child row count differs from the
328                // compile-time estimate in `parent.rows`. Retune this child's
329                // key domains to the count actually generated so a grandchild
330                // FK selects only over keys that exist (no dangling references).
331                for (domain_key, domain) in key_domains.iter_mut() {
332                    if domain_key.0 == table.name {
333                        domain.count = actual;
334                    }
335                }
336                continue;
337            }
338
339            sink.begin_table(&table)?;
340            let exec = TableExec::build(&table, &key_domains)?;
341            let ncols = table.columns.len();
342            let mut buffer = vec![GeneratedValue::Null; ncols];
343            let mut selectors = exec.selectors;
344            let mut planners = exec.planners;
345            let eval_order = table.eval_order.clone();
346            let mut pass = GeneratorPass::new(&table, &exec.dense_indices);
347
348            for row_index in 0..table.rows {
349                // Non-reading owners first: defaults, materialized parent keys,
350                // then foreign-key selections.
351                for &i in &exec.defaults {
352                    buffer[i] = GeneratedValue::Default;
353                }
354                for (i, key) in &exec.dense {
355                    buffer[*i] = key_domains[key].key_at(row_index);
356                }
357                for selector in selectors.iter_mut() {
358                    selector.assign(row_index, &mut buffer);
359                }
360                // Table planners produce their owned columns together, before
361                // the per-column generator pass (a planner-owned column takes
362                // its value from the planner, not a generator).
363                for exec in planners.iter_mut() {
364                    let planner = &mut table.planners[exec.index];
365                    planner.generate_row(row_index, &mut exec.scratch)?;
366                    for (slot, value) in exec.members.iter().zip(exec.scratch.iter_mut()) {
367                        buffer[*slot] = std::mem::replace(value, GeneratedValue::Null);
368                    }
369                    // A family planner also produced this order's child lines:
370                    // spool them (bounded — spills past the family budget) so
371                    // they can be drained when the child table is reached.
372                    if let Some(child_name) = planner.family_child_table().map(str::to_string) {
373                        let child_index =
374                            table_index_by_name.get(&child_name).copied().unwrap_or(0);
375                        let mut child_rows = planner.take_family_children();
376                        if let Some(first) = child_rows.next() {
377                            let buffer = family_buffers.entry(child_name).or_insert_with(|| {
378                                FamilyBuffer::new(
379                                    family_budget,
380                                    child_index as u32,
381                                    TempConfig::default(),
382                                    SpillKind::Child,
383                                )
384                            });
385                            for values in std::iter::once(first).chain(child_rows) {
386                                let values = values?;
387                                buffer
388                                    .push(SpooledRow {
389                                        table_id: child_index as u32,
390                                        row_index,
391                                        values,
392                                    })
393                                    .map_err(family_spool_error)?;
394                            }
395                        }
396                    }
397                }
398                // Column generators last, in topological read order so a
399                // generator that reads a sibling runs after it regardless of
400                // schema position. A materialized referenced key (in `dense`) is
401                // rendered from its domain, so it is skipped even though it is
402                // generator-owned.
403                pass.run(
404                    &mut table.columns,
405                    &mut buffer,
406                    &eval_order,
407                    &exec.dense_indices,
408                    row_index,
409                )?;
410
411                let generated = GeneratedRow {
412                    table_index,
413                    row_index,
414                    values: std::mem::take(&mut buffer),
415                };
416                sink.write_row(&table, &generated)?;
417                buffer = generated.values;
418                rows_written += 1;
419            }
420
421            sink.end_table(&table)?;
422        }
423
424        Ok(EngineReport { rows_written })
425    }
426}
427
428/// A family child table's link to the parent family: the child columns the
429/// planner produces (in spooled-value order) and the child relationship carrying
430/// the foreign key back to the parent.
431struct FamilyChildLink {
432    child_writes: Vec<String>,
433    relationship: String,
434}
435
436/// Discover every family child table declared by a planner on any parent table.
437fn collect_family_children(tables: &[PlannedTable]) -> BTreeMap<String, FamilyChildLink> {
438    let mut links = BTreeMap::new();
439    for table in tables {
440        for planner in &table.planners {
441            if let (Some(child), Some(relationship)) =
442                (planner.family_child_table(), planner.family_relationship())
443            {
444                links.insert(
445                    child.to_string(),
446                    FamilyChildLink {
447                        child_writes: planner.child_writes().to_vec(),
448                        relationship: relationship.to_string(),
449                    },
450                );
451            }
452        }
453    }
454    links
455}
456
457/// Render a family child table from the rows its parent spooled: each drained
458/// row carries its parent row index (so the foreign key binds to the exact
459/// parent that produced it) and the planner-owned child column values; the
460/// remaining columns (the child primary key, other generators) run their own
461/// owners. Returns the number of child rows written.
462fn render_family_child(
463    table_index: usize,
464    table: &mut PlannedTable,
465    link: &FamilyChildLink,
466    family_buffers: &mut BTreeMap<String, FamilyBuffer>,
467    key_domains: &BTreeMap<(String, String), ParentKey>,
468    sink: &mut dyn RowSink,
469) -> Result<u64, GenerateError> {
470    sink.begin_table(table)?;
471    let mut exec = TableExec::build(table, key_domains)?;
472    let names: Vec<String> = table
473        .columns
474        .iter()
475        .map(|column| column.schema.name.clone())
476        .collect();
477    let ncols = table.columns.len();
478
479    let slot_of = |name: &str| names.iter().position(|candidate| candidate == name);
480    let child_slots: Vec<Option<usize>> =
481        link.child_writes.iter().map(|name| slot_of(name)).collect();
482
483    // The relationship (on this child) whose FK is set from the owning parent.
484    let fk: Vec<(usize, (String, String))> = table
485        .relationships
486        .iter()
487        .find(|relationship| relationship.name.as_deref() == Some(link.relationship.as_str()))
488        .map(|relationship| {
489            relationship
490                .columns
491                .iter()
492                .zip(&relationship.parent_columns)
493                .filter_map(|(child_col, parent_col)| {
494                    slot_of(child_col).map(|slot| {
495                        (
496                            slot,
497                            (relationship.parent_table.clone(), parent_col.clone()),
498                        )
499                    })
500                })
501                .collect()
502        })
503        .unwrap_or_default();
504    // The child column slots carrying the family key, used to skip the family
505    // relationship's own selector (it is bound per-parent, not distributed).
506    let family_member_slots: Vec<usize> = fk.iter().map(|(slot, _)| *slot).collect();
507
508    let mut family_buffer = family_buffers.remove(&table.name);
509    let mut replay = match family_buffer.as_mut() {
510        Some(buffer) => Some(buffer.replay_rows().map_err(family_spool_error)?),
511        None => None,
512    };
513
514    let mut rows_written = 0u64;
515    let mut buffer = vec![GeneratedValue::Null; ncols];
516    let eval_order = table.eval_order.clone();
517    let mut pass = GeneratorPass::new(table, &exec.dense_indices);
518    for (child_index, spooled) in replay.iter_mut().flatten().enumerate() {
519        let spooled = spooled.map_err(family_spool_error)?;
520        let child_index = child_index as u64;
521        let parent_index = spooled.row_index;
522        for value in buffer.iter_mut() {
523            *value = GeneratedValue::Null;
524        }
525        for &i in &exec.defaults {
526            buffer[i] = GeneratedValue::Default;
527        }
528        for (i, key) in &exec.dense {
529            buffer[*i] = key_domains[key].key_at(child_index);
530        }
531        // Planner-owned child columns from the spooled values.
532        for (slot, value) in child_slots.iter().zip(spooled.values) {
533            if let Some(slot) = slot {
534                buffer[*slot] = value;
535            }
536        }
537        // Other relationships on this child (e.g. a `product_id` FK) are assigned
538        // by their selectors, exactly as on a non-family table. The family
539        // relationship's own selector is skipped: its key is bound below to the
540        // exact parent that produced this line, not by the child-row
541        // distribution.
542        for selector in exec.selectors.iter_mut() {
543            if selector.members == family_member_slots {
544                continue;
545            }
546            selector.assign(child_index, &mut buffer);
547        }
548        // Foreign key(s) bound to the exact parent that produced this line.
549        for (slot, key) in &fk {
550            buffer[*slot] = key_domains
551                .get(key)
552                .map_or(GeneratedValue::Null, |parent| parent.key_at(parent_index));
553        }
554        // Remaining generator-owned columns (e.g. the child primary key), in the
555        // same topological read order as the ordinary table path.
556        pass.run(
557            &mut table.columns,
558            &mut buffer,
559            &eval_order,
560            &exec.dense_indices,
561            child_index,
562        )?;
563
564        let generated = GeneratedRow {
565            table_index,
566            row_index: child_index,
567            values: std::mem::take(&mut buffer),
568        };
569        sink.write_row(table, &generated)?;
570        buffer = generated.values;
571        rows_written += 1;
572    }
573
574    sink.end_table(table)?;
575    Ok(rows_written)
576}
577
578/// Wrap a family spool I/O failure as a generation error.
579fn family_spool_error(error: std::io::Error) -> GenerateError {
580    GenerateError::diagnostic(
581        &crate::diagnostic::codes::FAMILY_SPOOL,
582        "runtime.family_spool",
583        format!("buffering family child rows failed: {error}"),
584    )
585}
586
587/// Whether a generator kind is a foreign-key marker driven by the engine rather
588/// than executed as a column generator.
589fn is_fk_kind(kind: &str) -> bool {
590    kind == "relation.foreign_key" || kind == "relation.composite_key"
591}
592
593/// Whether a family is an integer family (materializable as a dense key).
594fn is_integer_family(family: &crate::synthetic::schema::SqlTypeFamily) -> bool {
595    use crate::synthetic::schema::SqlTypeFamily;
596    matches!(family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
597}
598
599/// The concrete [`SeedRoot`] a resolved table seed derives runtime streams
600/// from. Random roots are drawn during compilation so runtime streams match the
601/// roots that compiled the table's operators.
602fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
603    match seed {
604        ResolvedTableSeed::Inherited(root)
605        | ResolvedTableSeed::Fixed(root)
606        | ResolvedTableSeed::Random(root) => *root,
607    }
608}
609
610/// Build a [`ParentKey`] for every parent key column referenced by a
611/// relationship anywhere in the plan. A referenced key must be reproducible by
612/// random access (regenerated from a per-row seed, never spooled): a bare
613/// integer primary key is a dense sequence, and a `uuid`-generator key reseeds
614/// per row. A genuinely stateful or otherwise non-random-access key reports
615/// `GEN-KEY-DOMAIN-UNSUPPORTED` (protected key spooling is a later task).
616fn build_key_domains(
617    plan: &GenerationPlan,
618) -> Result<BTreeMap<(String, String), ParentKey>, GenerateError> {
619    let mut domains: BTreeMap<(String, String), ParentKey> = BTreeMap::new();
620    for table in &plan.tables {
621        for relationship in &table.relationships {
622            for parent_column in &relationship.parent_columns {
623                let key = (relationship.parent_table.clone(), parent_column.clone());
624                if domains.contains_key(&key) {
625                    continue;
626                }
627                let Some(parent) = plan.table(&relationship.parent_table) else {
628                    continue;
629                };
630                let Some(column) = parent
631                    .columns
632                    .iter()
633                    .find(|column| &column.schema.name == parent_column)
634                else {
635                    continue;
636                };
637                let shape = match &column.owner {
638                    // A bare integer primary key is a database sequence:
639                    // children reference 1..=count and the parent renders it.
640                    ColumnOwner::GeneratedByDatabase
641                        if is_integer_family(&column.schema.family) =>
642                    {
643                        KeyRecipe::Dense { start: 1, step: 1 }
644                    }
645                    // Any generator that describes itself as a random-access key
646                    // (`sequence` -> Dense, `uuid` -> Uuid) is materializable.
647                    ColumnOwner::Generator { compiled, .. } => match compiled.key_recipe() {
648                        Some(shape) => shape,
649                        None => {
650                            return Err(unsupported_key(&relationship.parent_table, parent_column))
651                        }
652                    },
653                    _ => return Err(unsupported_key(&relationship.parent_table, parent_column)),
654                };
655                domains.insert(
656                    key,
657                    ParentKey {
658                        shape,
659                        seed: seed_root_of(&parent.seed),
660                        table: parent.name.clone(),
661                        column: parent_column.clone(),
662                        count: parent.rows,
663                    },
664                );
665            }
666        }
667    }
668    Ok(domains)
669}
670
671/// The `GEN-KEY-DOMAIN-UNSUPPORTED` error for a parent key that cannot be
672/// reproduced by random access (a stateful or otherwise non-describable key).
673fn unsupported_key(parent_table: &str, parent_column: &str) -> GenerateError {
674    GenerateError::diagnostic(
675        &crate::diagnostic::codes::KEY_DOMAIN_UNSUPPORTED,
676        format!("tables.{parent_table}.columns.{parent_column}"),
677        format!(
678            "parent key `{parent_table}.{parent_column}` cannot be materialized for random \
679             access; supported: bare integer primary keys, `sequence`, and `uuid` keys \
680             (stateful keys await protected key spooling)"
681        ),
682    )
683}
684
685/// The per-column execution plan for one table: which columns are constant
686/// database placeholders, which are materialized parent keys, and which are
687/// foreign-key selections.
688struct TableExec {
689    /// Columns emitted as `DEFAULT` (database-filled or unmodeled placeholders).
690    defaults: Vec<usize>,
691    /// Materialized referenced parent-key columns, keyed into the domain map.
692    dense: Vec<(usize, (String, String))>,
693    /// The set of `dense` column indices, for quick exclusion from the generator
694    /// pass (a referenced random-access key is rendered from its domain, not its
695    /// column generator).
696    dense_indices: BTreeSet<usize>,
697    /// Foreign-key selectors, one per active relationship.
698    selectors: Vec<FkSelector>,
699    /// Table planners that produce owned columns, one per active planner.
700    planners: Vec<PlannerExec>,
701}
702
703impl TableExec {
704    fn build(
705        table: &PlannedTable,
706        key_domains: &BTreeMap<(String, String), ParentKey>,
707    ) -> Result<Self, GenerateError> {
708        let mut dense: Vec<(usize, (String, String))> = Vec::new();
709        let mut dense_indices: BTreeSet<usize> = BTreeSet::new();
710        for (i, column) in table.columns.iter().enumerate() {
711            let key = (table.name.clone(), column.schema.name.clone());
712            if key_domains.contains_key(&key) {
713                dense.push((i, key));
714                dense_indices.insert(i);
715            }
716        }
717
718        let seed_root = seed_root_of(&table.seed);
719        let mut selectors: Vec<FkSelector> = Vec::new();
720        let mut member_indices: BTreeSet<usize> = BTreeSet::new();
721        for relationship in &table.relationships {
722            if let Some(selector) = FkSelector::build(table, relationship, key_domains, seed_root)?
723            {
724                member_indices.extend(selector.members.iter().copied());
725                selectors.push(selector);
726            }
727        }
728
729        // Map each planner's owned columns (by name) to row-buffer slots so the
730        // engine can scatter the planner's per-row output into place. Slots a
731        // planner owns are excluded from the DEFAULT pass below.
732        let mut planners: Vec<PlannerExec> = Vec::new();
733        let mut planner_indices: BTreeSet<usize> = BTreeSet::new();
734        for (index, planner) in table.planners.iter().enumerate() {
735            let members: Option<Vec<usize>> = planner
736                .writes()
737                .iter()
738                .map(|name| {
739                    table
740                        .columns
741                        .iter()
742                        .position(|column| &column.schema.name == name)
743                })
744                .collect();
745            let Some(members) = members else {
746                continue;
747            };
748            planner_indices.extend(members.iter().copied());
749            let scratch = vec![GeneratedValue::Null; members.len()];
750            planners.push(PlannerExec {
751                index,
752                members,
753                scratch,
754            });
755        }
756
757        let mut defaults: Vec<usize> = Vec::new();
758        for i in 0..table.columns.len() {
759            if dense_indices.contains(&i)
760                || member_indices.contains(&i)
761                || planner_indices.contains(&i)
762            {
763                continue;
764            }
765            match &table.columns[i].owner {
766                // A live column generator is executed in the generator pass.
767                ColumnOwner::Generator { kind, .. } if !is_fk_kind(kind) => {}
768                // Everything else (database-filled, defaults, a planner that
769                // never mapped, or an FK that never resolved a selector) renders
770                // as DEFAULT.
771                _ => defaults.push(i),
772            }
773        }
774
775        Ok(TableExec {
776            defaults,
777            dense,
778            dense_indices,
779            selectors,
780            planners,
781        })
782    }
783}
784
785/// A per-planner execution binding: which compiled planner to invoke and the
786/// row-buffer slots its produced columns scatter into.
787struct PlannerExec {
788    /// Index into [`PlannedTable::planners`].
789    index: usize,
790    /// Row-buffer slots for the planner's written columns, in `writes()` order.
791    members: Vec<usize>,
792    /// Reusable scratch aligned with `members`: the planner writes here each
793    /// row, then the engine moves each value into its buffer slot.
794    scratch: Vec<GeneratedValue>,
795}
796
797/// A per-relationship foreign-key selector: picks a parent row per child row and
798/// writes the resulting key(s) into the child's foreign-key columns.
799struct FkSelector {
800    /// Child column indices carrying the key, in parent-column order.
801    members: Vec<usize>,
802    /// The parent key domain.
803    domain: KeyDomain,
804    /// The number of parent rows.
805    parent_count: u64,
806    /// How children are distributed across parents.
807    distribution: RelationshipDistribution,
808    /// Fraction of children whose key is `NULL` (nullable columns only).
809    null_rate: f64,
810    /// Whether every member column is nullable.
811    nullable: bool,
812    /// The relationship's per-row RNG, advanced sequentially.
813    rng: ChaCha8Rng,
814    /// Cumulative bucket weights for a weighted/observed histogram; empty
815    /// otherwise.
816    histogram: Vec<f64>,
817}
818
819impl FkSelector {
820    fn build(
821        table: &PlannedTable,
822        relationship: &CompiledRelationship,
823        key_domains: &BTreeMap<(String, String), ParentKey>,
824        seed_root: SeedRoot,
825    ) -> Result<Option<Self>, GenerateError> {
826        let Some(members): Option<Vec<usize>> = relationship
827            .columns
828            .iter()
829            .map(|name| {
830                table
831                    .columns
832                    .iter()
833                    .position(|column| &column.schema.name == name)
834            })
835            .collect()
836        else {
837            return Ok(None);
838        };
839
840        // Each parent key column contributes a cloneable recipe; a single index
841        // is chosen per child row and every component is derived from it.
842        let Some(parents): Option<Vec<&ParentKey>> = relationship
843            .parent_columns
844            .iter()
845            .map(|parent_column| {
846                key_domains.get(&(relationship.parent_table.clone(), parent_column.clone()))
847            })
848            .collect()
849        else {
850            return Ok(None);
851        };
852        let Some(parent) = parents.first() else {
853            return Ok(None);
854        };
855        let parent_count = parent.count;
856
857        let domain = if parents.len() == 1 {
858            match parents[0].shape {
859                KeyRecipe::Dense { start, step } => KeyDomain::DenseInteger {
860                    start,
861                    step,
862                    count: parent_count,
863                },
864                KeyRecipe::Uuid => KeyDomain::Deterministic {
865                    count: parent_count,
866                    generator: parents[0].generator(),
867                },
868            }
869        } else {
870            KeyDomain::Composite {
871                count: parent_count,
872                components: parents.iter().map(|p| p.generator()).collect(),
873            }
874        };
875
876        let nullable = relationship.columns.iter().all(|name| {
877            table
878                .columns
879                .iter()
880                .find(|column| &column.schema.name == name)
881                .is_some_and(|column| column.schema.nullable)
882        });
883        if table.rows > 0 && parent_count == 0 && !nullable {
884            return Err(GenerateError::diagnostic(
885                &crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED,
886                format!("tables.{}.relationships", table.name),
887                format!(
888                    "table `{}` has {} row(s), but required relationship `{}` targets empty parent table `{}`",
889                    table.name,
890                    table.rows,
891                    relationship.name.as_deref().unwrap_or("(unnamed)"),
892                    relationship.parent_table
893                ),
894            ));
895        }
896        let null_rate = f64::from(relationship.null_permille) / 1000.0;
897        // TODO(deferred, L4): `columns.join(",")` is an ambiguous stream
898        // identity — a column literally named `a,b` collides with the set
899        // `[a, b]`, and two relationships over the same child columns share a
900        // stream (correlating FK selectors that should be independent). A robust
901        // identity (length-prefixed columns, or the relationship name + parent
902        // table) would change every seeded FK stream, so this is deferred to
903        // avoid churning all reproducible FK output for a pathological case.
904        let rng = seed_root.stream(StreamId::operator(
905            table.name.as_str(),
906            relationship.columns.join(","),
907            "relation.foreign_key",
908        ));
909        let histogram = match relationship.distribution {
910            RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
911                build_histogram(parent_count)
912            }
913            RelationshipDistribution::Uniform | RelationshipDistribution::Sequential => Vec::new(),
914        };
915
916        Ok(Some(FkSelector {
917            members,
918            domain,
919            parent_count,
920            distribution: relationship.distribution,
921            null_rate,
922            nullable,
923            rng,
924            histogram,
925        }))
926    }
927
928    /// Assign this relationship's key(s) for the child at `row_index`.
929    fn assign(&mut self, row_index: u64, buffer: &mut [GeneratedValue]) {
930        // Null is a separate first decision, before any parent is chosen.
931        if self.nullable && self.null_rate > 0.0 && self.rng.random::<f64>() < self.null_rate {
932            self.fill(buffer, |_| GeneratedValue::Null);
933            return;
934        }
935        if self.parent_count == 0 {
936            self.fill(buffer, |_| GeneratedValue::Null);
937            return;
938        }
939        let parent = self.pick(row_index);
940        let keys = self.domain.key_row(parent);
941        for (&member, key) in self.members.iter().zip(keys) {
942            buffer[member] = key;
943        }
944    }
945
946    fn fill(&self, buffer: &mut [GeneratedValue], value: impl Fn(usize) -> GeneratedValue) {
947        for (position, &member) in self.members.iter().enumerate() {
948            buffer[member] = value(position);
949        }
950    }
951
952    /// Choose the parent row index for the child at `row_index`.
953    fn pick(&mut self, row_index: u64) -> u64 {
954        match self.distribution {
955            RelationshipDistribution::Uniform => self.rng.random_range(0..self.parent_count),
956            RelationshipDistribution::Sequential => row_index % self.parent_count,
957            RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
958                self.sample_histogram()
959            }
960        }
961    }
962
963    /// Draw a parent row index from the bounded histogram.
964    fn sample_histogram(&mut self) -> u64 {
965        let buckets = self.histogram.len();
966        if buckets == 0 {
967            return self.rng.random_range(0..self.parent_count);
968        }
969        let total = self.histogram[buckets - 1];
970        let target = self.rng.random::<f64>() * total;
971        let bucket = self
972            .histogram
973            .partition_point(|&cumulative| cumulative <= target)
974            .min(buckets - 1) as u64;
975
976        // Map the bucket back to a parent row index. With one bucket per parent
977        // (the common small-fan-in case) this is the identity.
978        let base = self.parent_count / buckets as u64;
979        let remainder = self.parent_count % buckets as u64;
980        let start = bucket * base + bucket.min(remainder);
981        let size = base + u64::from(bucket < remainder);
982        if size <= 1 {
983            start
984        } else {
985            start + self.rng.random_range(0..size)
986        }
987    }
988}
989
990/// Build a bounded, decaying histogram over `parent_count` parents: earlier
991/// parents carry proportionally more weight, capped at 256 buckets so memory
992/// stays bounded regardless of parent count.
993fn build_histogram(parent_count: u64) -> Vec<f64> {
994    let buckets = parent_count.min(256) as usize;
995    let mut cumulative = Vec::with_capacity(buckets);
996    let mut acc = 0.0;
997    for bucket in 0..buckets {
998        acc += 1.0 / (bucket as f64 + 1.0);
999        cumulative.push(acc);
1000    }
1001    cumulative
1002}
1003
1004/// A [`RowView`] over the columns produced so far in the current row.
1005/// A read-only view over the whole in-progress row, exposing every column that
1006/// has already been produced this row. A column is readable once its value is
1007/// present: non-generator columns are filled before the generator pass, and
1008/// generator columns flip available as the pass produces them in
1009/// [`PlannedTable::eval_order`]. A column not yet produced (or the reader's own
1010/// slot) reads back as `None`, preserving the guarantee that a generator can
1011/// only observe values that already exist — regardless of schema position.
1012struct FullRow<'a> {
1013    index: &'a BTreeMap<String, usize>,
1014    values: &'a [GeneratedValue],
1015    available: &'a [bool],
1016}
1017
1018impl RowView for FullRow<'_> {
1019    fn get(&self, column: &str) -> Option<&GeneratedValue> {
1020        let &position = self.index.get(column)?;
1021        self.available[position].then(|| &self.values[position])
1022    }
1023}
1024
1025/// Runs a table's per-row generator pass in topological read order, reused
1026/// across the ordinary table loop and the family-child spool path. Precomputed
1027/// once per table: a column-name index for sibling reads and the base
1028/// availability mask (every column the pass does *not* produce is filled before
1029/// the pass, so it is available from the start; the pass's own columns start
1030/// unavailable and flip as they are produced).
1031struct GeneratorPass {
1032    index: BTreeMap<String, usize>,
1033    base_available: Vec<bool>,
1034    available: Vec<bool>,
1035}
1036
1037impl GeneratorPass {
1038    fn new(table: &PlannedTable, dense_indices: &BTreeSet<usize>) -> Self {
1039        let ncols = table.columns.len();
1040        let index = table
1041            .columns
1042            .iter()
1043            .enumerate()
1044            .map(|(i, column)| (column.schema.name.clone(), i))
1045            .collect();
1046        let mut base_available = vec![true; ncols];
1047        for (i, column) in table.columns.iter().enumerate() {
1048            if dense_indices.contains(&i) {
1049                continue;
1050            }
1051            if let ColumnOwner::Generator { kind, .. } = &column.owner {
1052                if !is_fk_kind(kind) {
1053                    // Produced by this pass, so unavailable until generated.
1054                    base_available[i] = false;
1055                }
1056            }
1057        }
1058        Self {
1059            index,
1060            base_available,
1061            available: vec![true; ncols],
1062        }
1063    }
1064
1065    /// Generate every pass-owned column of `columns` into `buffer` in
1066    /// `eval_order`, letting each generator (and its modifiers) read any sibling
1067    /// already produced this row via a [`FullRow`] view.
1068    fn run(
1069        &mut self,
1070        columns: &mut [PlannedColumn],
1071        buffer: &mut [GeneratedValue],
1072        eval_order: &[usize],
1073        dense_indices: &BTreeSet<usize>,
1074        row_index: u64,
1075    ) -> Result<(), GenerateError> {
1076        self.available.copy_from_slice(&self.base_available);
1077        for &i in eval_order {
1078            if dense_indices.contains(&i) {
1079                continue;
1080            }
1081            let column = &mut columns[i];
1082            let ColumnOwner::Generator { kind, compiled } = &mut column.owner else {
1083                continue;
1084            };
1085            if is_fk_kind(kind) {
1086                continue;
1087            }
1088            // Move the output slot out so the view can borrow the rest of the
1089            // row immutably while the generator writes its own value.
1090            let mut out = std::mem::replace(&mut buffer[i], GeneratedValue::Null);
1091            {
1092                let view = FullRow {
1093                    index: &self.index,
1094                    values: buffer,
1095                    available: &self.available,
1096                };
1097                let context = RowContext::new(row_index, &view);
1098                compiled.generate(&context, &mut out)?;
1099                for modifier in column.modifiers.iter_mut() {
1100                    modifier.apply(&context, &mut out)?;
1101                }
1102            }
1103            buffer[i] = out;
1104            self.available[i] = true;
1105        }
1106        Ok(())
1107    }
1108}