mod credential;
mod distribution;
mod planner;
mod relationship;
mod schema;
mod semantic;
pub fn is_credential_name(name: &str) -> bool {
credential::is_high_confidence_credential(name)
}
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use serde::Serialize;
use crate::diagnostic::{codes, Diagnostic};
use crate::generate::registry::ExtensionRegistry;
use crate::profile::evidence::{ColumnEvidence, DumpProfile, TableEvidence};
use crate::synthetic::model::{
ColumnRule, GeneratorConfig, ModelDefaults, ModelKind, ModifierConfig, OutputModel,
PlannerConfig, ProfileInference, ProfileMetadata, RelationshipModel, RelationshipReference,
RowsModel, SourceModel, SyntheticModel, TableModel, TableSeed,
};
use crate::synthetic::schema::{
PortableColumn, PortableRelationship, PortableSchema, PortableTable, SqlTypeFamily,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Precedence {
TypeFallback,
ObservedDistribution,
StrongSemantic,
Relationship,
CredentialGuard,
SchemaConstraint,
ExplicitYaml,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Confidence {
Low,
Medium,
High,
Certain,
}
impl Confidence {
fn label(self) -> &'static str {
match self {
Confidence::Low => "low",
Confidence::Medium => "medium",
Confidence::High => "high",
Confidence::Certain => "certain",
}
}
}
#[derive(Debug, Clone)]
pub struct Candidate {
precedence: Precedence,
confidence: Confidence,
reason: &'static str,
generator: GeneratorConfig,
semantic: Option<String>,
source_literals: Vec<String>,
}
impl Candidate {
fn new(
precedence: Precedence,
confidence: Confidence,
reason: &'static str,
generator: GeneratorConfig,
) -> Self {
Self {
precedence,
confidence,
reason,
generator,
semantic: None,
source_literals: Vec::new(),
}
}
fn with_semantic(mut self, semantic: impl Into<String>) -> Self {
self.semantic = Some(semantic.into());
self
}
fn with_source_literals(mut self, literals: Vec<String>) -> Self {
self.source_literals = literals;
self
}
fn rank_key(&self) -> (Precedence, Confidence, std::cmp::Reverse<&str>) {
(
self.precedence,
self.confidence,
std::cmp::Reverse(self.generator.kind.as_str()),
)
}
}
pub(crate) struct ColumnContext<'a> {
table: &'a PortableTable,
column: &'a PortableColumn,
evidence: Option<&'a ColumnEvidence>,
row_count: Option<u64>,
}
impl<'a> ColumnContext<'a> {
fn table(&self) -> &'a PortableTable {
self.table
}
fn column(&self) -> &'a PortableColumn {
self.column
}
fn evidence(&self) -> Option<&'a ColumnEvidence> {
self.evidence
}
fn row_count(&self) -> Option<u64> {
self.row_count
}
}
#[derive(Debug, Clone)]
pub struct RejectedCandidate {
pub generator_kind: String,
pub reason: String,
pub precedence: Precedence,
pub confidence: Confidence,
}
#[derive(Debug, Clone)]
pub struct Decision {
pub column: String,
pub reason: String,
pub confidence: Confidence,
pub generator_kind: String,
pub source_derived: bool,
pub rejected: Vec<RejectedCandidate>,
}
#[derive(Debug, Clone)]
pub struct InferenceResult {
pub model: SyntheticModel,
pub decisions: Vec<Decision>,
pub warnings: Vec<Diagnostic>,
source_literals: BTreeMap<String, Vec<String>>,
}
impl InferenceResult {
pub fn decision(&self, key: &str) -> Option<&Decision> {
self.decisions.iter().find(|d| d.column == key)
}
pub fn column_rule(&self, table: &str, column: &str) -> Option<&ColumnRule> {
self.model.tables.get(table)?.columns.get(column)
}
pub fn source_literals(&self, key: &str) -> &[String] {
self.source_literals
.get(key)
.map(Vec::as_slice)
.unwrap_or(&[])
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InferenceError {
NoTables,
}
impl fmt::Display for InferenceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InferenceError::NoTables => {
write!(f, "no profiled table matched the provided schema")
}
}
}
}
impl std::error::Error for InferenceError {}
#[derive(Debug, Clone)]
pub struct InferenceOptions {
include_profiles: bool,
}
impl Default for InferenceOptions {
fn default() -> Self {
Self {
include_profiles: true,
}
}
}
impl InferenceOptions {
pub fn include_profiles(mut self, include: bool) -> Self {
self.include_profiles = include;
self
}
}
pub struct ModelInference {
registry: ExtensionRegistry,
options: InferenceOptions,
}
impl ModelInference {
pub fn standard() -> Self {
Self {
registry: ExtensionRegistry::standard(),
options: InferenceOptions::default(),
}
}
pub fn new(registry: ExtensionRegistry, options: InferenceOptions) -> Self {
Self { registry, options }
}
pub fn infer(
&self,
schema: &PortableSchema,
profile: &DumpProfile,
) -> Result<InferenceResult, InferenceError> {
let mut tables = BTreeMap::new();
let mut decisions = Vec::new();
let mut warnings = Vec::new();
let mut profiles = BTreeMap::new();
let mut source_literals = BTreeMap::new();
let referenced: BTreeSet<(String, String)> = schema
.tables
.values()
.flat_map(|table| {
table.relationships.iter().flat_map(|fk| {
fk.referenced_columns
.iter()
.map(move |column| (fk.referenced_table.clone(), column.clone()))
})
})
.collect();
for table_evidence in &profile.tables {
let Some(portable) = schema.tables.get(&table_evidence.table) else {
warnings.push(Diagnostic::warning(
&codes::INFER_TABLE_UNKNOWN,
format!("tables.{}", table_evidence.table),
format!(
"profiled table `{}` is not in the schema; skipped",
table_evidence.table
),
));
continue;
};
let table_model = self.infer_table(
portable,
Some(table_evidence),
&referenced,
&mut decisions,
&mut warnings,
&mut profiles,
&mut source_literals,
);
tables.insert(portable.name.clone(), table_model);
}
for (name, portable) in &schema.tables {
if tables.contains_key(name) {
continue;
}
let table_model = self.infer_table(
portable,
None,
&referenced,
&mut decisions,
&mut warnings,
&mut profiles,
&mut source_literals,
);
tables.insert(name.clone(), table_model);
}
if tables.is_empty() {
return Err(InferenceError::NoTables);
}
let model = SyntheticModel {
schema_ref: None,
version: 1,
kind: ModelKind::Model,
imports: Vec::new(),
source: Some(SourceModel {
dialect: schema.dialect.clone(),
fingerprint: None,
fingerprint_policy: None,
}),
defaults: ModelDefaults::default(), seed: None,
output: OutputModel::default(),
tables,
profiles: if self.options.include_profiles {
profiles
} else {
BTreeMap::new()
},
};
Ok(InferenceResult {
model,
decisions,
warnings,
source_literals,
})
}
#[allow(clippy::too_many_arguments)]
fn infer_table(
&self,
portable: &PortableTable,
evidence: Option<&TableEvidence>,
referenced: &BTreeSet<(String, String)>,
decisions: &mut Vec<Decision>,
warnings: &mut Vec<Diagnostic>,
profiles: &mut BTreeMap<String, ProfileMetadata>,
source_literals: &mut BTreeMap<String, Vec<String>>,
) -> TableModel {
let row_count = evidence.and_then(|e| e.row_count);
let mut columns = BTreeMap::new();
for column in &portable.columns {
let key = format!("{}.{}", portable.name, column.name);
if relationship::is_foreign_key_column(portable, &column.name) {
decisions.push(Decision {
column: key,
reason: "relationship_declared_fk".to_string(),
confidence: Confidence::High,
generator_kind: "relation.foreign_key".to_string(),
source_derived: false,
rejected: Vec::new(),
});
continue;
}
if column.primary_key
&& matches!(column.family, SqlTypeFamily::Text | SqlTypeFamily::Other)
&& referenced.contains(&(portable.name.clone(), column.name.clone()))
{
decisions.push(Decision {
column: key,
reason: "referenced_text_key".to_string(),
confidence: Confidence::High,
generator_kind: "uuid".to_string(),
source_derived: false,
rejected: Vec::new(),
});
columns.insert(
column.name.clone(),
ColumnRule {
semantic: None,
generator: Some(GeneratorConfig {
kind: "uuid".to_string(),
args: BTreeMap::new(),
}),
modifiers: Vec::new(),
},
);
continue;
}
let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
let ctx = ColumnContext {
table: portable,
column,
evidence: column_evidence,
row_count,
};
let mut candidates = Vec::new();
candidates.extend(schema::candidates(&ctx));
candidates.extend(credential::candidates(&ctx));
candidates.extend(semantic::candidates(&ctx));
candidates.extend(distribution::candidates(&ctx));
candidates
.retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
let (rule, decision, literals) = if is_single_column_unique(portable, column)
&& rule
.generator
.as_ref()
.is_some_and(|g| is_bounded_generator(&g.kind))
{
match high_cardinality_generator(column) {
Some(generator) => (
ColumnRule {
semantic: None,
generator: Some(GeneratorConfig {
kind: generator.0.clone(),
args: generator.1,
}),
modifiers: Vec::new(),
},
Decision {
column: key.clone(),
reason: "unique_high_cardinality".to_string(),
confidence: Confidence::High,
generator_kind: generator.0,
source_derived: false,
rejected: Vec::new(),
},
Vec::new(),
),
None => (rule, decision, literals),
}
} else {
(rule, decision, literals)
};
if !literals.is_empty() {
warnings.push(Diagnostic::warning(
&codes::INFER_SOURCE_DERIVED,
key.clone(),
format!(
"persists {} source-derived literal value(s) required by its `{}` rule",
literals.len(),
decision.generator_kind
),
));
source_literals.insert(key.clone(), literals);
}
if self.options.include_profiles {
if let Some(meta) = profile_metadata(&ctx, &decision) {
profiles.insert(key.clone(), meta);
}
}
decisions.push(decision);
columns.insert(column.name.clone(), rule);
}
warnings.extend(planner::nominations(portable, evidence));
let planners = inferred_planners(portable);
if planners.is_empty() {
if let Some(column) = distinctness_sequence_column(portable) {
columns.insert(
column,
ColumnRule {
semantic: None,
generator: Some(GeneratorConfig {
kind: "sequence".to_string(),
args: [("start".to_string(), yaml(1))].into_iter().collect(),
}),
modifiers: Vec::new(),
},
);
}
}
TableModel {
seed: TableSeed::Inherit,
rows: match row_count {
Some(count) => RowsModel::Observed { count },
None => RowsModel::Fixed { count: 0 },
},
schema: portable.clone(),
columns,
relationships: declared_relationships(portable),
planners,
}
}
}
fn resolve_column(
ctx: &ColumnContext<'_>,
key: &str,
mut candidates: Vec<Candidate>,
) -> (ColumnRule, Decision, Vec<String>) {
if candidates.is_empty() {
candidates.push(schema::type_fallback(ctx));
}
let winner_index = candidates
.iter()
.enumerate()
.max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
.map(|(index, _)| index)
.expect("candidates is non-empty");
let winner = candidates.swap_remove(winner_index);
let rejected = candidates
.iter()
.map(|candidate| RejectedCandidate {
generator_kind: candidate.generator.kind.clone(),
reason: candidate.reason.to_string(),
precedence: candidate.precedence,
confidence: candidate.confidence,
})
.collect();
let mut modifiers = Vec::new();
if let Some(modifier) = sparse_modifier(ctx, &winner) {
modifiers.push(modifier);
}
let decision = Decision {
column: key.to_string(),
reason: winner.reason.to_string(),
confidence: winner.confidence,
generator_kind: winner.generator.kind.clone(),
source_derived: !winner.source_literals.is_empty(),
rejected,
};
let rule = ColumnRule {
semantic: winner.semantic.clone(),
generator: Some(winner.generator.clone()),
modifiers,
};
(rule, decision, winner.source_literals)
}
pub fn schema_inferred_generator(
table: &PortableTable,
column: &PortableColumn,
) -> GeneratorConfig {
let ctx = ColumnContext {
table,
column,
evidence: None,
row_count: None,
};
let mut candidates = Vec::new();
candidates.extend(schema::candidates(&ctx));
candidates.extend(credential::candidates(&ctx));
candidates.extend(semantic::candidates(&ctx));
let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
rule.generator
.expect("resolve_column always assigns a generator")
}
fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
if !ctx.column().nullable {
return None;
}
if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
return None;
}
let rate = ctx.evidence()?.null_rate;
if !(0.005..=0.995).contains(&rate) {
return None;
}
let mut args = BTreeMap::new();
args.insert("rate".to_string(), yaml(round4(rate)));
Some(ModifierConfig {
kind: "null_rate".to_string(),
args,
})
}
fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
let evidence = ctx.evidence()?;
Some(ProfileMetadata {
rows: ctx.row_count().unwrap_or(evidence.total_count),
null_fraction: round4(evidence.null_rate),
distinct_estimate: evidence.distinct_estimate.round() as u64,
inference: Some(ProfileInference {
selected: decision.generator_kind.clone(),
confidence: decision.confidence.label().to_string(),
reasons: vec![decision.reason.clone()],
}),
})
}
fn is_bounded_generator(kind: &str) -> bool {
matches!(
kind,
"observed_sample"
| "choice"
| "weighted_choice"
| "histogram"
| "normal"
| "integer"
| "decimal"
| "boolean"
| "constant"
| "null"
| "database_default"
)
}
fn high_cardinality_generator(
column: &PortableColumn,
) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
match column.family {
SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
"sequence".to_string(),
[("start".to_string(), yaml(1))].into_iter().collect(),
)),
SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
Some(("uuid".to_string(), BTreeMap::new()))
}
_ => None,
}
}
fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
if column.unique {
return true;
}
let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
table
.unique_constraints
.iter()
.any(|constraint| single(&constraint.columns))
|| table
.indexes
.iter()
.any(|index| index.unique && single(&index.columns))
}
fn single_column_fk<'a>(
table: &'a PortableTable,
column: &str,
) -> Option<&'a PortableRelationship> {
table
.relationships
.iter()
.find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
}
fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
let pk = &table.primary_key;
if pk.len() < 2 {
return Vec::new();
}
let fk_columns: Vec<(&String, &PortableRelationship)> = pk
.iter()
.filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
.collect();
if fk_columns.len() < 2 {
return Vec::new();
}
let (left_col, left) = fk_columns[0];
let (right_col, right) = fk_columns[1];
let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
return Vec::new();
};
let mut columns = serde_yaml_ng::Mapping::new();
columns.insert(yaml("left"), yaml(left_col));
columns.insert(yaml("right"), yaml(right_col));
let mut args = BTreeMap::new();
args.insert(
"columns".to_string(),
serde_yaml_ng::Value::Mapping(columns),
);
args.insert("left_relationship".to_string(), yaml(left_name));
args.insert("right_relationship".to_string(), yaml(right_name));
vec![PlannerConfig {
kind: "relation.junction_pair".to_string(),
args,
}]
}
fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
if table.primary_key.len() < 2 {
return None;
}
table.primary_key.iter().find_map(|column| {
let is_integer = table.columns.iter().any(|c| {
&c.name == column
&& matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
});
(is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
})
}
fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
table
.relationships
.iter()
.map(|fk| RelationshipModel {
name: fk.name.clone(),
columns: fk.columns.clone(),
references: RelationshipReference {
table: fk.referenced_table.clone(),
columns: fk.referenced_columns.clone(),
},
distribution: None,
})
.collect()
}
fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
table.columns.iter().find(|c| c.name == name)
}
pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
}
pub(crate) fn generator(kind: &str) -> GeneratorConfig {
GeneratorConfig {
kind: kind.to_string(),
args: BTreeMap::new(),
}
}
pub(crate) fn generator_with(
kind: &str,
args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
) -> GeneratorConfig {
GeneratorConfig {
kind: kind.to_string(),
args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
}
}
pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
let seq = entries
.iter()
.map(|(value, weight)| {
let mut map = serde_yaml_ng::Mapping::new();
map.insert(yaml("value"), yaml(value));
map.insert(yaml("weight"), yaml(*weight));
serde_yaml_ng::Value::Mapping(map)
})
.collect();
serde_yaml_ng::Value::Sequence(seq)
}
fn round4(value: f64) -> f64 {
(value * 10_000.0).round() / 10_000.0
}