use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use rand::{Rng, RngExt};
use rand_chacha::ChaCha8Rng;
use super::output::{FamilyBudget, FamilyBuffer, SpillKind, SpooledRow, TempConfig};
use super::plan::{
ColumnOwner, CompiledRelationship, GenerationPlan, PlannedColumn, PlannedTable,
RelationshipDistribution, ResolvedTableSeed,
};
use super::registry::{KeyRecipe, RowContext, RowView};
use super::seed::{SeedRoot, StreamId};
use super::value::{GenerateError, GeneratedValue};
#[derive(Debug, Clone, PartialEq)]
pub struct GeneratedRow {
pub table_index: usize,
pub row_index: u64,
pub values: Vec<GeneratedValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EngineReport {
pub rows_written: u64,
}
pub trait RowSink {
fn begin_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError>;
fn write_row(&mut self, table: &PlannedTable, row: &GeneratedRow) -> Result<(), GenerateError>;
fn end_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError>;
}
pub trait RandomAccessKeyGenerator: Send {
fn key_at(&self, row_index: u64) -> GeneratedValue;
}
#[derive(Debug, Clone, Copy)]
pub struct DenseIntegerKey {
pub start: i128,
pub step: i128,
}
impl RandomAccessKeyGenerator for DenseIntegerKey {
fn key_at(&self, row_index: u64) -> GeneratedValue {
GeneratedValue::Integer(self.start + self.step * row_index as i128)
}
}
pub struct SeededUuidKey {
pub seed: SeedRoot,
pub table: String,
pub column: String,
}
impl RandomAccessKeyGenerator for SeededUuidKey {
fn key_at(&self, row_index: u64) -> GeneratedValue {
seeded_uuid(self.seed, &self.table, &self.column, row_index)
}
}
fn seeded_uuid(seed: SeedRoot, table: &str, column: &str, row_index: u64) -> GeneratedValue {
let mut rng = seed.stream(StreamId::operator(
table,
column,
format!("primary_key.row.{row_index}"),
));
let mut bytes = [0u8; 16];
rng.fill_bytes(&mut bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; let hex = hex::encode(bytes);
GeneratedValue::Text(format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
))
}
struct ParentKey {
shape: KeyRecipe,
seed: SeedRoot,
table: String,
column: String,
count: u64,
}
impl ParentKey {
fn key_at(&self, row_index: u64) -> GeneratedValue {
match self.shape {
KeyRecipe::Dense { start, step } => {
GeneratedValue::Integer(start + step * row_index as i128)
}
KeyRecipe::Uuid => seeded_uuid(self.seed, &self.table, &self.column, row_index),
}
}
fn generator(&self) -> Box<dyn RandomAccessKeyGenerator> {
match self.shape {
KeyRecipe::Dense { start, step } => Box::new(DenseIntegerKey { start, step }),
KeyRecipe::Uuid => Box::new(SeededUuidKey {
seed: self.seed,
table: self.table.clone(),
column: self.column.clone(),
}),
}
}
}
pub enum KeyDomain {
DenseInteger {
start: i128,
step: i128,
count: u64,
},
Deterministic {
count: u64,
generator: Box<dyn RandomAccessKeyGenerator>,
},
Composite {
count: u64,
components: Vec<Box<dyn RandomAccessKeyGenerator>>,
},
Nullable(Box<KeyDomain>),
}
impl fmt::Debug for KeyDomain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
KeyDomain::DenseInteger { start, step, count } => f
.debug_struct("DenseInteger")
.field("start", start)
.field("step", step)
.field("count", count)
.finish(),
KeyDomain::Deterministic { count, .. } => f
.debug_struct("Deterministic")
.field("count", count)
.finish_non_exhaustive(),
KeyDomain::Composite { count, components } => f
.debug_struct("Composite")
.field("count", count)
.field("components", &components.len())
.finish(),
KeyDomain::Nullable(inner) => f.debug_tuple("Nullable").field(inner).finish(),
}
}
}
impl KeyDomain {
pub fn count(&self) -> u64 {
match self {
KeyDomain::DenseInteger { count, .. }
| KeyDomain::Deterministic { count, .. }
| KeyDomain::Composite { count, .. } => *count,
KeyDomain::Nullable(inner) => inner.count(),
}
}
fn key_at(&self, row_index: u64) -> GeneratedValue {
match self {
KeyDomain::DenseInteger { start, step, .. } => {
GeneratedValue::Integer(start + step * row_index as i128)
}
KeyDomain::Deterministic { generator, .. } => generator.key_at(row_index),
KeyDomain::Composite { components, .. } => components
.first()
.map_or(GeneratedValue::Null, |c| c.key_at(row_index)),
KeyDomain::Nullable(inner) => inner.key_at(row_index),
}
}
fn key_row(&self, row_index: u64) -> Vec<GeneratedValue> {
match self {
KeyDomain::Composite { components, .. } => {
components.iter().map(|c| c.key_at(row_index)).collect()
}
KeyDomain::Nullable(inner) => inner.key_row(row_index),
_ => vec![self.key_at(row_index)],
}
}
}
pub struct GenerationEngine {
plan: GenerationPlan,
}
impl GenerationEngine {
pub fn new(plan: GenerationPlan) -> Self {
Self { plan }
}
pub fn run(mut self, sink: &mut dyn RowSink) -> Result<EngineReport, GenerateError> {
let mut key_domains = build_key_domains(&self.plan)?;
let family_budget = FamilyBudget {
max_bytes: self.plan.family_budget_bytes,
};
let table_index_by_name: BTreeMap<String, usize> = self
.plan
.tables
.iter()
.enumerate()
.map(|(index, table)| (table.name.clone(), index))
.collect();
let family_children = collect_family_children(&self.plan.tables);
let tables = std::mem::take(&mut self.plan.tables);
let mut rows_written = 0u64;
let mut family_buffers: BTreeMap<String, FamilyBuffer> = BTreeMap::new();
for (table_index, mut table) in tables.into_iter().enumerate() {
if let Some(link) = family_children.get(&table.name) {
let actual = render_family_child(
table_index,
&mut table,
link,
&mut family_buffers,
&key_domains,
sink,
)?;
rows_written += actual;
for (domain_key, domain) in key_domains.iter_mut() {
if domain_key.0 == table.name {
domain.count = actual;
}
}
continue;
}
sink.begin_table(&table)?;
let exec = TableExec::build(&table, &key_domains)?;
let ncols = table.columns.len();
let mut buffer = vec![GeneratedValue::Null; ncols];
let mut selectors = exec.selectors;
let mut planners = exec.planners;
let eval_order = table.eval_order.clone();
let mut pass = GeneratorPass::new(&table, &exec.dense_indices);
for row_index in 0..table.rows {
for &i in &exec.defaults {
buffer[i] = GeneratedValue::Default;
}
for (i, key) in &exec.dense {
buffer[*i] = key_domains[key].key_at(row_index);
}
for selector in selectors.iter_mut() {
selector.assign(row_index, &mut buffer);
}
for exec in planners.iter_mut() {
let planner = &mut table.planners[exec.index];
planner.generate_row(row_index, &mut exec.scratch)?;
for (slot, value) in exec.members.iter().zip(exec.scratch.iter_mut()) {
buffer[*slot] = std::mem::replace(value, GeneratedValue::Null);
}
if let Some(child_name) = planner.family_child_table().map(str::to_string) {
let child_index =
table_index_by_name.get(&child_name).copied().unwrap_or(0);
let mut child_rows = planner.take_family_children();
if let Some(first) = child_rows.next() {
let buffer = family_buffers.entry(child_name).or_insert_with(|| {
FamilyBuffer::new(
family_budget,
child_index as u32,
TempConfig::default(),
SpillKind::Child,
)
});
for values in std::iter::once(first).chain(child_rows) {
let values = values?;
buffer
.push(SpooledRow {
table_id: child_index as u32,
row_index,
values,
})
.map_err(family_spool_error)?;
}
}
}
}
pass.run(
&mut table.columns,
&mut buffer,
&eval_order,
&exec.dense_indices,
row_index,
)?;
let generated = GeneratedRow {
table_index,
row_index,
values: std::mem::take(&mut buffer),
};
sink.write_row(&table, &generated)?;
buffer = generated.values;
rows_written += 1;
}
sink.end_table(&table)?;
}
Ok(EngineReport { rows_written })
}
}
struct FamilyChildLink {
child_writes: Vec<String>,
relationship: String,
}
fn collect_family_children(tables: &[PlannedTable]) -> BTreeMap<String, FamilyChildLink> {
let mut links = BTreeMap::new();
for table in tables {
for planner in &table.planners {
if let (Some(child), Some(relationship)) =
(planner.family_child_table(), planner.family_relationship())
{
links.insert(
child.to_string(),
FamilyChildLink {
child_writes: planner.child_writes().to_vec(),
relationship: relationship.to_string(),
},
);
}
}
}
links
}
fn render_family_child(
table_index: usize,
table: &mut PlannedTable,
link: &FamilyChildLink,
family_buffers: &mut BTreeMap<String, FamilyBuffer>,
key_domains: &BTreeMap<(String, String), ParentKey>,
sink: &mut dyn RowSink,
) -> Result<u64, GenerateError> {
sink.begin_table(table)?;
let mut exec = TableExec::build(table, key_domains)?;
let names: Vec<String> = table
.columns
.iter()
.map(|column| column.schema.name.clone())
.collect();
let ncols = table.columns.len();
let slot_of = |name: &str| names.iter().position(|candidate| candidate == name);
let child_slots: Vec<Option<usize>> =
link.child_writes.iter().map(|name| slot_of(name)).collect();
let fk: Vec<(usize, (String, String))> = table
.relationships
.iter()
.find(|relationship| relationship.name.as_deref() == Some(link.relationship.as_str()))
.map(|relationship| {
relationship
.columns
.iter()
.zip(&relationship.parent_columns)
.filter_map(|(child_col, parent_col)| {
slot_of(child_col).map(|slot| {
(
slot,
(relationship.parent_table.clone(), parent_col.clone()),
)
})
})
.collect()
})
.unwrap_or_default();
let family_member_slots: Vec<usize> = fk.iter().map(|(slot, _)| *slot).collect();
let mut family_buffer = family_buffers.remove(&table.name);
let mut replay = match family_buffer.as_mut() {
Some(buffer) => Some(buffer.replay_rows().map_err(family_spool_error)?),
None => None,
};
let mut rows_written = 0u64;
let mut buffer = vec![GeneratedValue::Null; ncols];
let eval_order = table.eval_order.clone();
let mut pass = GeneratorPass::new(table, &exec.dense_indices);
for (child_index, spooled) in replay.iter_mut().flatten().enumerate() {
let spooled = spooled.map_err(family_spool_error)?;
let child_index = child_index as u64;
let parent_index = spooled.row_index;
for value in buffer.iter_mut() {
*value = GeneratedValue::Null;
}
for &i in &exec.defaults {
buffer[i] = GeneratedValue::Default;
}
for (i, key) in &exec.dense {
buffer[*i] = key_domains[key].key_at(child_index);
}
for (slot, value) in child_slots.iter().zip(spooled.values) {
if let Some(slot) = slot {
buffer[*slot] = value;
}
}
for selector in exec.selectors.iter_mut() {
if selector.members == family_member_slots {
continue;
}
selector.assign(child_index, &mut buffer);
}
for (slot, key) in &fk {
buffer[*slot] = key_domains
.get(key)
.map_or(GeneratedValue::Null, |parent| parent.key_at(parent_index));
}
pass.run(
&mut table.columns,
&mut buffer,
&eval_order,
&exec.dense_indices,
child_index,
)?;
let generated = GeneratedRow {
table_index,
row_index: child_index,
values: std::mem::take(&mut buffer),
};
sink.write_row(table, &generated)?;
buffer = generated.values;
rows_written += 1;
}
sink.end_table(table)?;
Ok(rows_written)
}
fn family_spool_error(error: std::io::Error) -> GenerateError {
GenerateError::diagnostic(
&crate::diagnostic::codes::FAMILY_SPOOL,
"runtime.family_spool",
format!("buffering family child rows failed: {error}"),
)
}
fn is_fk_kind(kind: &str) -> bool {
kind == "relation.foreign_key" || kind == "relation.composite_key"
}
fn is_integer_family(family: &crate::synthetic::schema::SqlTypeFamily) -> bool {
use crate::synthetic::schema::SqlTypeFamily;
matches!(family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
}
fn seed_root_of(seed: &ResolvedTableSeed) -> SeedRoot {
match seed {
ResolvedTableSeed::Inherited(root)
| ResolvedTableSeed::Fixed(root)
| ResolvedTableSeed::Random(root) => *root,
}
}
fn build_key_domains(
plan: &GenerationPlan,
) -> Result<BTreeMap<(String, String), ParentKey>, GenerateError> {
let mut domains: BTreeMap<(String, String), ParentKey> = BTreeMap::new();
for table in &plan.tables {
for relationship in &table.relationships {
for parent_column in &relationship.parent_columns {
let key = (relationship.parent_table.clone(), parent_column.clone());
if domains.contains_key(&key) {
continue;
}
let Some(parent) = plan.table(&relationship.parent_table) else {
continue;
};
let Some(column) = parent
.columns
.iter()
.find(|column| &column.schema.name == parent_column)
else {
continue;
};
let shape = match &column.owner {
ColumnOwner::GeneratedByDatabase
if is_integer_family(&column.schema.family) =>
{
KeyRecipe::Dense { start: 1, step: 1 }
}
ColumnOwner::Generator { compiled, .. } => match compiled.key_recipe() {
Some(shape) => shape,
None => {
return Err(unsupported_key(&relationship.parent_table, parent_column))
}
},
_ => return Err(unsupported_key(&relationship.parent_table, parent_column)),
};
domains.insert(
key,
ParentKey {
shape,
seed: seed_root_of(&parent.seed),
table: parent.name.clone(),
column: parent_column.clone(),
count: parent.rows,
},
);
}
}
}
Ok(domains)
}
fn unsupported_key(parent_table: &str, parent_column: &str) -> GenerateError {
GenerateError::diagnostic(
&crate::diagnostic::codes::KEY_DOMAIN_UNSUPPORTED,
format!("tables.{parent_table}.columns.{parent_column}"),
format!(
"parent key `{parent_table}.{parent_column}` cannot be materialized for random \
access; supported: bare integer primary keys, `sequence`, and `uuid` keys \
(stateful keys await protected key spooling)"
),
)
}
struct TableExec {
defaults: Vec<usize>,
dense: Vec<(usize, (String, String))>,
dense_indices: BTreeSet<usize>,
selectors: Vec<FkSelector>,
planners: Vec<PlannerExec>,
}
impl TableExec {
fn build(
table: &PlannedTable,
key_domains: &BTreeMap<(String, String), ParentKey>,
) -> Result<Self, GenerateError> {
let mut dense: Vec<(usize, (String, String))> = Vec::new();
let mut dense_indices: BTreeSet<usize> = BTreeSet::new();
for (i, column) in table.columns.iter().enumerate() {
let key = (table.name.clone(), column.schema.name.clone());
if key_domains.contains_key(&key) {
dense.push((i, key));
dense_indices.insert(i);
}
}
let seed_root = seed_root_of(&table.seed);
let mut selectors: Vec<FkSelector> = Vec::new();
let mut member_indices: BTreeSet<usize> = BTreeSet::new();
for relationship in &table.relationships {
if let Some(selector) = FkSelector::build(table, relationship, key_domains, seed_root)?
{
member_indices.extend(selector.members.iter().copied());
selectors.push(selector);
}
}
let mut planners: Vec<PlannerExec> = Vec::new();
let mut planner_indices: BTreeSet<usize> = BTreeSet::new();
for (index, planner) in table.planners.iter().enumerate() {
let members: Option<Vec<usize>> = planner
.writes()
.iter()
.map(|name| {
table
.columns
.iter()
.position(|column| &column.schema.name == name)
})
.collect();
let Some(members) = members else {
continue;
};
planner_indices.extend(members.iter().copied());
let scratch = vec![GeneratedValue::Null; members.len()];
planners.push(PlannerExec {
index,
members,
scratch,
});
}
let mut defaults: Vec<usize> = Vec::new();
for i in 0..table.columns.len() {
if dense_indices.contains(&i)
|| member_indices.contains(&i)
|| planner_indices.contains(&i)
{
continue;
}
match &table.columns[i].owner {
ColumnOwner::Generator { kind, .. } if !is_fk_kind(kind) => {}
_ => defaults.push(i),
}
}
Ok(TableExec {
defaults,
dense,
dense_indices,
selectors,
planners,
})
}
}
struct PlannerExec {
index: usize,
members: Vec<usize>,
scratch: Vec<GeneratedValue>,
}
struct FkSelector {
members: Vec<usize>,
domain: KeyDomain,
parent_count: u64,
distribution: RelationshipDistribution,
null_rate: f64,
nullable: bool,
rng: ChaCha8Rng,
histogram: Vec<f64>,
}
impl FkSelector {
fn build(
table: &PlannedTable,
relationship: &CompiledRelationship,
key_domains: &BTreeMap<(String, String), ParentKey>,
seed_root: SeedRoot,
) -> Result<Option<Self>, GenerateError> {
let Some(members): Option<Vec<usize>> = relationship
.columns
.iter()
.map(|name| {
table
.columns
.iter()
.position(|column| &column.schema.name == name)
})
.collect()
else {
return Ok(None);
};
let Some(parents): Option<Vec<&ParentKey>> = relationship
.parent_columns
.iter()
.map(|parent_column| {
key_domains.get(&(relationship.parent_table.clone(), parent_column.clone()))
})
.collect()
else {
return Ok(None);
};
let Some(parent) = parents.first() else {
return Ok(None);
};
let parent_count = parent.count;
let domain = if parents.len() == 1 {
match parents[0].shape {
KeyRecipe::Dense { start, step } => KeyDomain::DenseInteger {
start,
step,
count: parent_count,
},
KeyRecipe::Uuid => KeyDomain::Deterministic {
count: parent_count,
generator: parents[0].generator(),
},
}
} else {
KeyDomain::Composite {
count: parent_count,
components: parents.iter().map(|p| p.generator()).collect(),
}
};
let nullable = relationship.columns.iter().all(|name| {
table
.columns
.iter()
.find(|column| &column.schema.name == name)
.is_some_and(|column| column.schema.nullable)
});
if table.rows > 0 && parent_count == 0 && !nullable {
return Err(GenerateError::diagnostic(
&crate::diagnostic::codes::FOREIGN_KEY_UNRESOLVED,
format!("tables.{}.relationships", table.name),
format!(
"table `{}` has {} row(s), but required relationship `{}` targets empty parent table `{}`",
table.name,
table.rows,
relationship.name.as_deref().unwrap_or("(unnamed)"),
relationship.parent_table
),
));
}
let null_rate = f64::from(relationship.null_permille) / 1000.0;
let rng = seed_root.stream(StreamId::operator(
table.name.as_str(),
relationship.columns.join(","),
"relation.foreign_key",
));
let histogram = match relationship.distribution {
RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
build_histogram(parent_count)
}
RelationshipDistribution::Uniform | RelationshipDistribution::Sequential => Vec::new(),
};
Ok(Some(FkSelector {
members,
domain,
parent_count,
distribution: relationship.distribution,
null_rate,
nullable,
rng,
histogram,
}))
}
fn assign(&mut self, row_index: u64, buffer: &mut [GeneratedValue]) {
if self.nullable && self.null_rate > 0.0 && self.rng.random::<f64>() < self.null_rate {
self.fill(buffer, |_| GeneratedValue::Null);
return;
}
if self.parent_count == 0 {
self.fill(buffer, |_| GeneratedValue::Null);
return;
}
let parent = self.pick(row_index);
let keys = self.domain.key_row(parent);
for (&member, key) in self.members.iter().zip(keys) {
buffer[member] = key;
}
}
fn fill(&self, buffer: &mut [GeneratedValue], value: impl Fn(usize) -> GeneratedValue) {
for (position, &member) in self.members.iter().enumerate() {
buffer[member] = value(position);
}
}
fn pick(&mut self, row_index: u64) -> u64 {
match self.distribution {
RelationshipDistribution::Uniform => self.rng.random_range(0..self.parent_count),
RelationshipDistribution::Sequential => row_index % self.parent_count,
RelationshipDistribution::Weighted | RelationshipDistribution::Observed => {
self.sample_histogram()
}
}
}
fn sample_histogram(&mut self) -> u64 {
let buckets = self.histogram.len();
if buckets == 0 {
return self.rng.random_range(0..self.parent_count);
}
let total = self.histogram[buckets - 1];
let target = self.rng.random::<f64>() * total;
let bucket = self
.histogram
.partition_point(|&cumulative| cumulative <= target)
.min(buckets - 1) as u64;
let base = self.parent_count / buckets as u64;
let remainder = self.parent_count % buckets as u64;
let start = bucket * base + bucket.min(remainder);
let size = base + u64::from(bucket < remainder);
if size <= 1 {
start
} else {
start + self.rng.random_range(0..size)
}
}
}
fn build_histogram(parent_count: u64) -> Vec<f64> {
let buckets = parent_count.min(256) as usize;
let mut cumulative = Vec::with_capacity(buckets);
let mut acc = 0.0;
for bucket in 0..buckets {
acc += 1.0 / (bucket as f64 + 1.0);
cumulative.push(acc);
}
cumulative
}
struct FullRow<'a> {
index: &'a BTreeMap<String, usize>,
values: &'a [GeneratedValue],
available: &'a [bool],
}
impl RowView for FullRow<'_> {
fn get(&self, column: &str) -> Option<&GeneratedValue> {
let &position = self.index.get(column)?;
self.available[position].then(|| &self.values[position])
}
}
struct GeneratorPass {
index: BTreeMap<String, usize>,
base_available: Vec<bool>,
available: Vec<bool>,
}
impl GeneratorPass {
fn new(table: &PlannedTable, dense_indices: &BTreeSet<usize>) -> Self {
let ncols = table.columns.len();
let index = table
.columns
.iter()
.enumerate()
.map(|(i, column)| (column.schema.name.clone(), i))
.collect();
let mut base_available = vec![true; ncols];
for (i, column) in table.columns.iter().enumerate() {
if dense_indices.contains(&i) {
continue;
}
if let ColumnOwner::Generator { kind, .. } = &column.owner {
if !is_fk_kind(kind) {
base_available[i] = false;
}
}
}
Self {
index,
base_available,
available: vec![true; ncols],
}
}
fn run(
&mut self,
columns: &mut [PlannedColumn],
buffer: &mut [GeneratedValue],
eval_order: &[usize],
dense_indices: &BTreeSet<usize>,
row_index: u64,
) -> Result<(), GenerateError> {
self.available.copy_from_slice(&self.base_available);
for &i in eval_order {
if dense_indices.contains(&i) {
continue;
}
let column = &mut columns[i];
let ColumnOwner::Generator { kind, compiled } = &mut column.owner else {
continue;
};
if is_fk_kind(kind) {
continue;
}
let mut out = std::mem::replace(&mut buffer[i], GeneratedValue::Null);
{
let view = FullRow {
index: &self.index,
values: buffer,
available: &self.available,
};
let context = RowContext::new(row_index, &view);
compiled.generate(&context, &mut out)?;
for modifier in column.modifiers.iter_mut() {
modifier.apply(&context, &mut out)?;
}
}
buffer[i] = out;
self.available[i] = true;
}
Ok(())
}
}