1mod credential;
31mod distribution;
32mod planner;
33mod relationship;
34mod schema;
35mod semantic;
36
37pub fn is_credential_name(name: &str) -> bool {
42 credential::is_high_confidence_credential(name)
43}
44
45use std::collections::{BTreeMap, BTreeSet};
46use std::fmt;
47
48use serde::Serialize;
49
50use crate::diagnostic::{codes, Diagnostic};
51use crate::generate::registry::ExtensionRegistry;
52use crate::profile::evidence::{ColumnEvidence, DumpProfile, TableEvidence};
53use crate::synthetic::model::{
54 ColumnRule, GeneratorConfig, ModelDefaults, ModelKind, ModifierConfig, OutputModel,
55 PlannerConfig, ProfileInference, ProfileMetadata, RelationshipModel, RelationshipReference,
56 RowsModel, SourceModel, SyntheticModel, TableModel, TableSeed,
57};
58use crate::synthetic::schema::{
59 PortableColumn, PortableRelationship, PortableSchema, PortableTable, SqlTypeFamily,
60};
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
67pub enum Precedence {
68 TypeFallback,
70 ObservedDistribution,
72 StrongSemantic,
74 Relationship,
76 CredentialGuard,
78 SchemaConstraint,
80 ExplicitYaml,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
88pub enum Confidence {
89 Low,
90 Medium,
91 High,
92 Certain,
93}
94
95impl Confidence {
96 fn label(self) -> &'static str {
98 match self {
99 Confidence::Low => "low",
100 Confidence::Medium => "medium",
101 Confidence::High => "high",
102 Confidence::Certain => "certain",
103 }
104 }
105}
106
107#[derive(Debug, Clone)]
112pub struct Candidate {
113 precedence: Precedence,
114 confidence: Confidence,
115 reason: &'static str,
117 generator: GeneratorConfig,
118 semantic: Option<String>,
119 source_literals: Vec<String>,
122}
123
124impl Candidate {
125 fn new(
127 precedence: Precedence,
128 confidence: Confidence,
129 reason: &'static str,
130 generator: GeneratorConfig,
131 ) -> Self {
132 Self {
133 precedence,
134 confidence,
135 reason,
136 generator,
137 semantic: None,
138 source_literals: Vec::new(),
139 }
140 }
141
142 fn with_semantic(mut self, semantic: impl Into<String>) -> Self {
144 self.semantic = Some(semantic.into());
145 self
146 }
147
148 fn with_source_literals(mut self, literals: Vec<String>) -> Self {
150 self.source_literals = literals;
151 self
152 }
153
154 fn rank_key(&self) -> (Precedence, Confidence, std::cmp::Reverse<&str>) {
158 (
159 self.precedence,
160 self.confidence,
161 std::cmp::Reverse(self.generator.kind.as_str()),
162 )
163 }
164}
165
166pub(crate) struct ColumnContext<'a> {
172 table: &'a PortableTable,
173 column: &'a PortableColumn,
174 evidence: Option<&'a ColumnEvidence>,
175 row_count: Option<u64>,
176}
177
178impl<'a> ColumnContext<'a> {
179 fn table(&self) -> &'a PortableTable {
180 self.table
181 }
182 fn column(&self) -> &'a PortableColumn {
183 self.column
184 }
185 fn evidence(&self) -> Option<&'a ColumnEvidence> {
186 self.evidence
187 }
188 fn row_count(&self) -> Option<u64> {
189 self.row_count
190 }
191}
192
193#[derive(Debug, Clone)]
198pub struct RejectedCandidate {
199 pub generator_kind: String,
200 pub reason: String,
201 pub precedence: Precedence,
202 pub confidence: Confidence,
203}
204
205#[derive(Debug, Clone)]
208pub struct Decision {
209 pub column: String,
211 pub reason: String,
213 pub confidence: Confidence,
214 pub generator_kind: String,
215 pub source_derived: bool,
217 pub rejected: Vec<RejectedCandidate>,
218}
219
220#[derive(Debug, Clone)]
223pub struct InferenceResult {
224 pub model: SyntheticModel,
225 pub decisions: Vec<Decision>,
226 pub warnings: Vec<Diagnostic>,
227 source_literals: BTreeMap<String, Vec<String>>,
229}
230
231impl InferenceResult {
232 pub fn decision(&self, key: &str) -> Option<&Decision> {
234 self.decisions.iter().find(|d| d.column == key)
235 }
236
237 pub fn column_rule(&self, table: &str, column: &str) -> Option<&ColumnRule> {
239 self.model.tables.get(table)?.columns.get(column)
240 }
241
242 pub fn source_literals(&self, key: &str) -> &[String] {
245 self.source_literals
246 .get(key)
247 .map(Vec::as_slice)
248 .unwrap_or(&[])
249 }
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum InferenceError {
255 NoTables,
257}
258
259impl fmt::Display for InferenceError {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 match self {
262 InferenceError::NoTables => {
263 write!(f, "no profiled table matched the provided schema")
264 }
265 }
266 }
267}
268
269impl std::error::Error for InferenceError {}
270
271#[derive(Debug, Clone)]
275pub struct InferenceOptions {
276 include_profiles: bool,
280}
281
282impl Default for InferenceOptions {
283 fn default() -> Self {
284 Self {
285 include_profiles: true,
286 }
287 }
288}
289
290impl InferenceOptions {
291 pub fn include_profiles(mut self, include: bool) -> Self {
294 self.include_profiles = include;
295 self
296 }
297}
298
299pub struct ModelInference {
305 registry: ExtensionRegistry,
306 options: InferenceOptions,
307}
308
309impl ModelInference {
310 pub fn standard() -> Self {
313 Self {
314 registry: ExtensionRegistry::standard(),
315 options: InferenceOptions::default(),
316 }
317 }
318
319 pub fn new(registry: ExtensionRegistry, options: InferenceOptions) -> Self {
321 Self { registry, options }
322 }
323
324 pub fn infer(
330 &self,
331 schema: &PortableSchema,
332 profile: &DumpProfile,
333 ) -> Result<InferenceResult, InferenceError> {
334 let mut tables = BTreeMap::new();
335 let mut decisions = Vec::new();
336 let mut warnings = Vec::new();
337 let mut profiles = BTreeMap::new();
338 let mut source_literals = BTreeMap::new();
339
340 let referenced: BTreeSet<(String, String)> = schema
344 .tables
345 .values()
346 .flat_map(|table| {
347 table.relationships.iter().flat_map(|fk| {
348 fk.referenced_columns
349 .iter()
350 .map(move |column| (fk.referenced_table.clone(), column.clone()))
351 })
352 })
353 .collect();
354
355 for table_evidence in &profile.tables {
356 let Some(portable) = schema.tables.get(&table_evidence.table) else {
357 warnings.push(Diagnostic::warning(
358 &codes::INFER_TABLE_UNKNOWN,
359 format!("tables.{}", table_evidence.table),
360 format!(
361 "profiled table `{}` is not in the schema; skipped",
362 table_evidence.table
363 ),
364 ));
365 continue;
366 };
367 let table_model = self.infer_table(
368 portable,
369 Some(table_evidence),
370 &referenced,
371 &mut decisions,
372 &mut warnings,
373 &mut profiles,
374 &mut source_literals,
375 );
376 tables.insert(portable.name.clone(), table_model);
377 }
378
379 for (name, portable) in &schema.tables {
382 if tables.contains_key(name) {
383 continue;
384 }
385 let table_model = self.infer_table(
386 portable,
387 None,
388 &referenced,
389 &mut decisions,
390 &mut warnings,
391 &mut profiles,
392 &mut source_literals,
393 );
394 tables.insert(name.clone(), table_model);
395 }
396
397 if tables.is_empty() {
398 return Err(InferenceError::NoTables);
399 }
400
401 let model = SyntheticModel {
402 schema_ref: None,
403 version: 1,
404 kind: ModelKind::Model,
405 imports: Vec::new(),
406 source: Some(SourceModel {
407 dialect: schema.dialect.clone(),
408 fingerprint: None,
409 fingerprint_policy: None,
410 }),
411 defaults: ModelDefaults::default(), seed: None,
413 output: OutputModel::default(),
414 tables,
415 profiles: if self.options.include_profiles {
416 profiles
417 } else {
418 BTreeMap::new()
419 },
420 };
421
422 Ok(InferenceResult {
423 model,
424 decisions,
425 warnings,
426 source_literals,
427 })
428 }
429
430 #[allow(clippy::too_many_arguments)]
431 fn infer_table(
432 &self,
433 portable: &PortableTable,
434 evidence: Option<&TableEvidence>,
435 referenced: &BTreeSet<(String, String)>,
436 decisions: &mut Vec<Decision>,
437 warnings: &mut Vec<Diagnostic>,
438 profiles: &mut BTreeMap<String, ProfileMetadata>,
439 source_literals: &mut BTreeMap<String, Vec<String>>,
440 ) -> TableModel {
441 let row_count = evidence.and_then(|e| e.row_count);
442 let mut columns = BTreeMap::new();
443
444 for column in &portable.columns {
445 let key = format!("{}.{}", portable.name, column.name);
446
447 if relationship::is_foreign_key_column(portable, &column.name) {
451 decisions.push(Decision {
452 column: key,
453 reason: "relationship_declared_fk".to_string(),
454 confidence: Confidence::High,
455 generator_kind: "relation.foreign_key".to_string(),
456 source_derived: false,
457 rejected: Vec::new(),
458 });
459 continue;
460 }
461
462 if column.primary_key
467 && matches!(column.family, SqlTypeFamily::Text | SqlTypeFamily::Other)
468 && referenced.contains(&(portable.name.clone(), column.name.clone()))
469 {
470 decisions.push(Decision {
471 column: key,
472 reason: "referenced_text_key".to_string(),
473 confidence: Confidence::High,
474 generator_kind: "uuid".to_string(),
475 source_derived: false,
476 rejected: Vec::new(),
477 });
478 columns.insert(
479 column.name.clone(),
480 ColumnRule {
481 semantic: None,
482 generator: Some(GeneratorConfig {
483 kind: "uuid".to_string(),
484 args: BTreeMap::new(),
485 }),
486 modifiers: Vec::new(),
487 },
488 );
489 continue;
490 }
491
492 let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
493 let ctx = ColumnContext {
494 table: portable,
495 column,
496 evidence: column_evidence,
497 row_count,
498 };
499
500 let mut candidates = Vec::new();
501 candidates.extend(schema::candidates(&ctx));
502 candidates.extend(credential::candidates(&ctx));
503 candidates.extend(semantic::candidates(&ctx));
504 candidates.extend(distribution::candidates(&ctx));
505
506 candidates
509 .retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
510
511 let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
512
513 let (rule, decision, literals) = if is_single_column_unique(portable, column)
520 && rule
521 .generator
522 .as_ref()
523 .is_some_and(|g| is_bounded_generator(&g.kind))
524 {
525 match high_cardinality_generator(column) {
526 Some(generator) => (
527 ColumnRule {
528 semantic: None,
529 generator: Some(GeneratorConfig {
530 kind: generator.0.clone(),
531 args: generator.1,
532 }),
533 modifiers: Vec::new(),
534 },
535 Decision {
536 column: key.clone(),
537 reason: "unique_high_cardinality".to_string(),
538 confidence: Confidence::High,
539 generator_kind: generator.0,
540 source_derived: false,
541 rejected: Vec::new(),
542 },
543 Vec::new(),
544 ),
545 None => (rule, decision, literals),
546 }
547 } else {
548 (rule, decision, literals)
549 };
550
551 if !literals.is_empty() {
552 warnings.push(Diagnostic::warning(
553 &codes::INFER_SOURCE_DERIVED,
554 key.clone(),
555 format!(
556 "persists {} source-derived literal value(s) required by its `{}` rule",
557 literals.len(),
558 decision.generator_kind
559 ),
560 ));
561 source_literals.insert(key.clone(), literals);
562 }
563
564 if self.options.include_profiles {
565 if let Some(meta) = profile_metadata(&ctx, &decision) {
566 profiles.insert(key.clone(), meta);
567 }
568 }
569
570 decisions.push(decision);
571 columns.insert(column.name.clone(), rule);
572 }
573
574 warnings.extend(planner::nominations(portable, evidence));
579
580 let planners = inferred_planners(portable);
584 if planners.is_empty() {
585 if let Some(column) = distinctness_sequence_column(portable) {
586 columns.insert(
587 column,
588 ColumnRule {
589 semantic: None,
590 generator: Some(GeneratorConfig {
591 kind: "sequence".to_string(),
592 args: [("start".to_string(), yaml(1))].into_iter().collect(),
593 }),
594 modifiers: Vec::new(),
595 },
596 );
597 }
598 }
599
600 TableModel {
601 seed: TableSeed::Inherit,
602 rows: match row_count {
603 Some(count) => RowsModel::Observed { count },
604 None => RowsModel::Fixed { count: 0 },
605 },
606 schema: portable.clone(),
607 columns,
608 relationships: declared_relationships(portable),
609 planners,
610 }
611 }
612}
613
614fn resolve_column(
617 ctx: &ColumnContext<'_>,
618 key: &str,
619 mut candidates: Vec<Candidate>,
620) -> (ColumnRule, Decision, Vec<String>) {
621 if candidates.is_empty() {
623 candidates.push(schema::type_fallback(ctx));
624 }
625
626 let winner_index = candidates
628 .iter()
629 .enumerate()
630 .max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
631 .map(|(index, _)| index)
632 .expect("candidates is non-empty");
633
634 let winner = candidates.swap_remove(winner_index);
635
636 let rejected = candidates
637 .iter()
638 .map(|candidate| RejectedCandidate {
639 generator_kind: candidate.generator.kind.clone(),
640 reason: candidate.reason.to_string(),
641 precedence: candidate.precedence,
642 confidence: candidate.confidence,
643 })
644 .collect();
645
646 let mut modifiers = Vec::new();
647 if let Some(modifier) = sparse_modifier(ctx, &winner) {
648 modifiers.push(modifier);
649 }
650
651 let decision = Decision {
652 column: key.to_string(),
653 reason: winner.reason.to_string(),
654 confidence: winner.confidence,
655 generator_kind: winner.generator.kind.clone(),
656 source_derived: !winner.source_literals.is_empty(),
657 rejected,
658 };
659
660 let rule = ColumnRule {
661 semantic: winner.semantic.clone(),
662 generator: Some(winner.generator.clone()),
663 modifiers,
664 };
665
666 (rule, decision, winner.source_literals)
667}
668
669pub fn schema_inferred_generator(
676 table: &PortableTable,
677 column: &PortableColumn,
678) -> GeneratorConfig {
679 let ctx = ColumnContext {
680 table,
681 column,
682 evidence: None,
683 row_count: None,
684 };
685 let mut candidates = Vec::new();
686 candidates.extend(schema::candidates(&ctx));
687 candidates.extend(credential::candidates(&ctx));
688 candidates.extend(semantic::candidates(&ctx));
689 let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
690 rule.generator
691 .expect("resolve_column always assigns a generator")
692}
693
694fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
697 if !ctx.column().nullable {
698 return None;
699 }
700 if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
701 return None;
702 }
703 let rate = ctx.evidence()?.null_rate;
704 if !(0.005..=0.995).contains(&rate) {
705 return None;
706 }
707 let mut args = BTreeMap::new();
708 args.insert("rate".to_string(), yaml(round4(rate)));
709 Some(ModifierConfig {
710 kind: "null_rate".to_string(),
711 args,
712 })
713}
714
715fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
717 let evidence = ctx.evidence()?;
718 Some(ProfileMetadata {
719 rows: ctx.row_count().unwrap_or(evidence.total_count),
720 null_fraction: round4(evidence.null_rate),
721 distinct_estimate: evidence.distinct_estimate.round() as u64,
722 inference: Some(ProfileInference {
723 selected: decision.generator_kind.clone(),
724 confidence: decision.confidence.label().to_string(),
725 reasons: vec![decision.reason.clone()],
726 }),
727 })
728}
729
730fn is_bounded_generator(kind: &str) -> bool {
735 matches!(
736 kind,
737 "observed_sample"
738 | "choice"
739 | "weighted_choice"
740 | "histogram"
741 | "normal"
742 | "integer"
743 | "decimal"
744 | "boolean"
745 | "constant"
746 | "null"
747 | "database_default"
748 )
749}
750
751fn high_cardinality_generator(
755 column: &PortableColumn,
756) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
757 match column.family {
758 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
759 "sequence".to_string(),
760 [("start".to_string(), yaml(1))].into_iter().collect(),
761 )),
762 SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
763 Some(("uuid".to_string(), BTreeMap::new()))
764 }
765 _ => None,
766 }
767}
768
769fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
774 if column.unique {
775 return true;
776 }
777 let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
778 table
779 .unique_constraints
780 .iter()
781 .any(|constraint| single(&constraint.columns))
782 || table
783 .indexes
784 .iter()
785 .any(|index| index.unique && single(&index.columns))
786}
787
788fn single_column_fk<'a>(
791 table: &'a PortableTable,
792 column: &str,
793) -> Option<&'a PortableRelationship> {
794 table
795 .relationships
796 .iter()
797 .find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
798}
799
800fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
811 let pk = &table.primary_key;
812 if pk.len() < 2 {
813 return Vec::new();
814 }
815 let fk_columns: Vec<(&String, &PortableRelationship)> = pk
817 .iter()
818 .filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
819 .collect();
820 if fk_columns.len() < 2 {
821 return Vec::new();
822 }
823 let (left_col, left) = fk_columns[0];
824 let (right_col, right) = fk_columns[1];
825 let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
826 return Vec::new();
827 };
828
829 let mut columns = serde_yaml_ng::Mapping::new();
830 columns.insert(yaml("left"), yaml(left_col));
831 columns.insert(yaml("right"), yaml(right_col));
832 let mut args = BTreeMap::new();
833 args.insert(
834 "columns".to_string(),
835 serde_yaml_ng::Value::Mapping(columns),
836 );
837 args.insert("left_relationship".to_string(), yaml(left_name));
838 args.insert("right_relationship".to_string(), yaml(right_name));
839
840 vec![PlannerConfig {
841 kind: "relation.junction_pair".to_string(),
842 args,
843 }]
844}
845
846fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
854 if table.primary_key.len() < 2 {
855 return None;
856 }
857 table.primary_key.iter().find_map(|column| {
858 let is_integer = table.columns.iter().any(|c| {
859 &c.name == column
860 && matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
861 });
862 (is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
863 })
864}
865
866fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
867 table
868 .relationships
869 .iter()
870 .map(|fk| RelationshipModel {
871 name: fk.name.clone(),
872 columns: fk.columns.clone(),
873 references: RelationshipReference {
874 table: fk.referenced_table.clone(),
875 columns: fk.referenced_columns.clone(),
876 },
877 distribution: None,
878 })
879 .collect()
880}
881
882fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
883 table.columns.iter().find(|c| c.name == name)
884}
885
886pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
890 serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
891}
892
893pub(crate) fn generator(kind: &str) -> GeneratorConfig {
895 GeneratorConfig {
896 kind: kind.to_string(),
897 args: BTreeMap::new(),
898 }
899}
900
901pub(crate) fn generator_with(
903 kind: &str,
904 args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
905) -> GeneratorConfig {
906 GeneratorConfig {
907 kind: kind.to_string(),
908 args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
909 }
910}
911
912pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
914 let seq = entries
915 .iter()
916 .map(|(value, weight)| {
917 let mut map = serde_yaml_ng::Mapping::new();
918 map.insert(yaml("value"), yaml(value));
919 map.insert(yaml("weight"), yaml(*weight));
920 serde_yaml_ng::Value::Mapping(map)
921 })
922 .collect();
923 serde_yaml_ng::Value::Sequence(seq)
924}
925
926fn round4(value: f64) -> f64 {
928 (value * 10_000.0).round() / 10_000.0
929}