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 && text_column_fits_uuid(&column.source_type)
474 {
475 decisions.push(Decision {
476 column: key,
477 reason: "referenced_text_key".to_string(),
478 confidence: Confidence::High,
479 generator_kind: "uuid".to_string(),
480 source_derived: false,
481 rejected: Vec::new(),
482 });
483 columns.insert(
484 column.name.clone(),
485 ColumnRule {
486 semantic: None,
487 generator: Some(GeneratorConfig {
488 kind: "uuid".to_string(),
489 args: BTreeMap::new(),
490 }),
491 modifiers: Vec::new(),
492 },
493 );
494 continue;
495 }
496
497 let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
498 let ctx = ColumnContext {
499 table: portable,
500 column,
501 evidence: column_evidence,
502 row_count,
503 };
504
505 let mut candidates = Vec::new();
506 candidates.extend(schema::candidates(&ctx));
507 candidates.extend(credential::candidates(&ctx));
508 candidates.extend(semantic::candidates(&ctx));
509 candidates.extend(distribution::candidates(&ctx));
510
511 candidates
514 .retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
515
516 let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
517
518 let (rule, decision, literals) = if is_single_column_unique(portable, column)
525 && rule
526 .generator
527 .as_ref()
528 .is_some_and(|g| is_bounded_generator(&g.kind))
529 {
530 match high_cardinality_generator(column) {
531 Some(generator) => (
532 ColumnRule {
533 semantic: None,
534 generator: Some(GeneratorConfig {
535 kind: generator.0.clone(),
536 args: generator.1,
537 }),
538 modifiers: Vec::new(),
539 },
540 Decision {
541 column: key.clone(),
542 reason: "unique_high_cardinality".to_string(),
543 confidence: Confidence::High,
544 generator_kind: generator.0,
545 source_derived: false,
546 rejected: Vec::new(),
547 },
548 Vec::new(),
549 ),
550 None => (rule, decision, literals),
551 }
552 } else {
553 (rule, decision, literals)
554 };
555
556 if !literals.is_empty() {
557 warnings.push(Diagnostic::warning(
558 &codes::INFER_SOURCE_DERIVED,
559 key.clone(),
560 format!(
561 "persists {} source-derived literal value(s) required by its `{}` rule",
562 literals.len(),
563 decision.generator_kind
564 ),
565 ));
566 source_literals.insert(key.clone(), literals);
567 }
568
569 if self.options.include_profiles {
570 if let Some(meta) = profile_metadata(&ctx, &decision) {
571 profiles.insert(key.clone(), meta);
572 }
573 }
574
575 decisions.push(decision);
576 columns.insert(column.name.clone(), rule);
577 }
578
579 warnings.extend(planner::nominations(portable, evidence));
584
585 let planners = inferred_planners(portable);
589 if planners.is_empty() {
590 if let Some(column) = distinctness_sequence_column(portable) {
591 columns.insert(
592 column,
593 ColumnRule {
594 semantic: None,
595 generator: Some(GeneratorConfig {
596 kind: "sequence".to_string(),
597 args: [("start".to_string(), yaml(1))].into_iter().collect(),
598 }),
599 modifiers: Vec::new(),
600 },
601 );
602 }
603 }
604
605 TableModel {
606 seed: TableSeed::Inherit,
607 rows: match row_count {
608 Some(count) => RowsModel::Observed { count },
609 None => RowsModel::Fixed { count: 0 },
610 },
611 schema: portable.clone(),
612 columns,
613 relationships: declared_relationships(portable),
614 planners,
615 }
616 }
617}
618
619fn resolve_column(
622 ctx: &ColumnContext<'_>,
623 key: &str,
624 mut candidates: Vec<Candidate>,
625) -> (ColumnRule, Decision, Vec<String>) {
626 if candidates.is_empty() {
628 candidates.push(schema::type_fallback(ctx));
629 }
630
631 let winner_index = candidates
633 .iter()
634 .enumerate()
635 .max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
636 .map(|(index, _)| index)
637 .expect("candidates is non-empty");
638
639 let winner = candidates.swap_remove(winner_index);
640
641 let rejected = candidates
642 .iter()
643 .map(|candidate| RejectedCandidate {
644 generator_kind: candidate.generator.kind.clone(),
645 reason: candidate.reason.to_string(),
646 precedence: candidate.precedence,
647 confidence: candidate.confidence,
648 })
649 .collect();
650
651 let mut modifiers = Vec::new();
652 if let Some(modifier) = sparse_modifier(ctx, &winner) {
653 modifiers.push(modifier);
654 }
655
656 let decision = Decision {
657 column: key.to_string(),
658 reason: winner.reason.to_string(),
659 confidence: winner.confidence,
660 generator_kind: winner.generator.kind.clone(),
661 source_derived: !winner.source_literals.is_empty(),
662 rejected,
663 };
664
665 let rule = ColumnRule {
666 semantic: winner.semantic.clone(),
667 generator: Some(winner.generator.clone()),
668 modifiers,
669 };
670
671 (rule, decision, winner.source_literals)
672}
673
674pub fn schema_inferred_generator(
681 table: &PortableTable,
682 column: &PortableColumn,
683) -> GeneratorConfig {
684 let ctx = ColumnContext {
685 table,
686 column,
687 evidence: None,
688 row_count: None,
689 };
690 let mut candidates = Vec::new();
691 candidates.extend(schema::candidates(&ctx));
692 candidates.extend(credential::candidates(&ctx));
693 candidates.extend(semantic::candidates(&ctx));
694 let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
695 rule.generator
696 .expect("resolve_column always assigns a generator")
697}
698
699fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
702 if !ctx.column().nullable {
703 return None;
704 }
705 if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
706 return None;
707 }
708 let rate = ctx.evidence()?.null_rate;
709 if !(0.005..=0.995).contains(&rate) {
710 return None;
711 }
712 let mut args = BTreeMap::new();
713 args.insert("rate".to_string(), yaml(round4(rate)));
714 Some(ModifierConfig {
715 kind: "null_rate".to_string(),
716 args,
717 })
718}
719
720fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
722 let evidence = ctx.evidence()?;
723 Some(ProfileMetadata {
724 rows: ctx.row_count().unwrap_or(evidence.total_count),
725 null_fraction: round4(evidence.null_rate),
726 distinct_estimate: evidence.distinct_estimate.round() as u64,
727 inference: Some(ProfileInference {
728 selected: decision.generator_kind.clone(),
729 confidence: decision.confidence.label().to_string(),
730 reasons: vec![decision.reason.clone()],
731 }),
732 })
733}
734
735fn is_bounded_generator(kind: &str) -> bool {
740 matches!(
741 kind,
742 "observed_sample"
743 | "choice"
744 | "weighted_choice"
745 | "histogram"
746 | "normal"
747 | "integer"
748 | "decimal"
749 | "boolean"
750 | "constant"
751 | "null"
752 | "database_default"
753 )
754}
755
756fn declared_char_length(source_type: &str) -> Option<usize> {
760 let open = source_type.find('(')?;
761 let close = source_type[open + 1..].find(')')? + open + 1;
762 source_type[open + 1..close]
765 .split(',')
766 .next()?
767 .trim()
768 .parse::<usize>()
769 .ok()
770}
771
772fn text_column_fits_uuid(source_type: &str) -> bool {
775 const UUID_LEN: usize = 36;
776 declared_char_length(source_type).is_none_or(|n| n >= UUID_LEN)
777}
778
779fn high_cardinality_generator(
783 column: &PortableColumn,
784) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
785 match column.family {
786 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
787 "sequence".to_string(),
788 [("start".to_string(), yaml(1))].into_iter().collect(),
789 )),
790 SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
791 if text_column_fits_uuid(&column.source_type) {
795 Some(("uuid".to_string(), BTreeMap::new()))
796 } else {
797 None
798 }
799 }
800 _ => None,
801 }
802}
803
804fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
809 if column.unique {
810 return true;
811 }
812 let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
813 table
814 .unique_constraints
815 .iter()
816 .any(|constraint| single(&constraint.columns))
817 || table
818 .indexes
819 .iter()
820 .any(|index| index.unique && single(&index.columns))
821}
822
823fn single_column_fk<'a>(
826 table: &'a PortableTable,
827 column: &str,
828) -> Option<&'a PortableRelationship> {
829 table
830 .relationships
831 .iter()
832 .find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
833}
834
835fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
846 let pk = &table.primary_key;
847 if pk.len() < 2 {
848 return Vec::new();
849 }
850 let fk_columns: Vec<(&String, &PortableRelationship)> = pk
852 .iter()
853 .filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
854 .collect();
855 if fk_columns.len() < 2 {
856 return Vec::new();
857 }
858 let (left_col, left) = fk_columns[0];
859 let (right_col, right) = fk_columns[1];
860 let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
861 return Vec::new();
862 };
863
864 let mut columns = serde_yaml_ng::Mapping::new();
865 columns.insert(yaml("left"), yaml(left_col));
866 columns.insert(yaml("right"), yaml(right_col));
867 let mut args = BTreeMap::new();
868 args.insert(
869 "columns".to_string(),
870 serde_yaml_ng::Value::Mapping(columns),
871 );
872 args.insert("left_relationship".to_string(), yaml(left_name));
873 args.insert("right_relationship".to_string(), yaml(right_name));
874
875 vec![PlannerConfig {
876 kind: "relation.junction_pair".to_string(),
877 args,
878 }]
879}
880
881fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
889 if table.primary_key.len() < 2 {
890 return None;
891 }
892 table.primary_key.iter().find_map(|column| {
893 let is_integer = table.columns.iter().any(|c| {
894 &c.name == column
895 && matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
896 });
897 (is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
898 })
899}
900
901fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
902 table
903 .relationships
904 .iter()
905 .map(|fk| RelationshipModel {
906 name: fk.name.clone(),
907 columns: fk.columns.clone(),
908 references: RelationshipReference {
909 table: fk.referenced_table.clone(),
910 columns: fk.referenced_columns.clone(),
911 },
912 distribution: None,
913 })
914 .collect()
915}
916
917fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
918 table.columns.iter().find(|c| c.name == name)
919}
920
921pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
925 serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
926}
927
928pub(crate) fn generator(kind: &str) -> GeneratorConfig {
930 GeneratorConfig {
931 kind: kind.to_string(),
932 args: BTreeMap::new(),
933 }
934}
935
936pub(crate) fn generator_with(
938 kind: &str,
939 args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
940) -> GeneratorConfig {
941 GeneratorConfig {
942 kind: kind.to_string(),
943 args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
944 }
945}
946
947pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
949 let seq = entries
950 .iter()
951 .map(|(value, weight)| {
952 let mut map = serde_yaml_ng::Mapping::new();
953 map.insert(yaml("value"), yaml(value));
954 map.insert(yaml("weight"), yaml(*weight));
955 serde_yaml_ng::Value::Mapping(map)
956 })
957 .collect();
958 serde_yaml_ng::Value::Sequence(seq)
959}
960
961fn round4(value: f64) -> f64 {
963 (value * 10_000.0).round() / 10_000.0
964}
965
966#[cfg(test)]
967mod uuid_length_tests {
968 use super::*;
969
970 fn text_col(source_type: &str) -> PortableColumn {
971 PortableColumn {
972 name: "code".to_string(),
973 source_type: source_type.to_string(),
974 family: SqlTypeFamily::Text,
975 nullable: false,
976 primary_key: false,
977 unique: true,
978 default_sql: None,
979 generated: false,
980 identity: false,
981 collation: None,
982 }
983 }
984
985 #[test]
986 fn short_text_unique_not_forced_to_uuid() {
987 assert!(
990 high_cardinality_generator(&text_col("varchar(8)")).is_none(),
991 "uuid forced into a column too short to hold it"
992 );
993 }
994
995 #[test]
996 fn long_and_unbounded_text_unique_get_uuid() {
997 assert_eq!(
998 high_cardinality_generator(&text_col("varchar(64)")).map(|(k, _)| k),
999 Some("uuid".to_string())
1000 );
1001 assert_eq!(
1003 high_cardinality_generator(&text_col("text")).map(|(k, _)| k),
1004 Some("uuid".to_string())
1005 );
1006 }
1007
1008 #[test]
1009 fn declared_char_length_parses_type_lengths() {
1010 assert_eq!(declared_char_length("varchar(8)"), Some(8));
1011 assert_eq!(declared_char_length("VARCHAR(255)"), Some(255));
1012 assert_eq!(declared_char_length("char(10)"), Some(10));
1013 assert_eq!(declared_char_length("text"), None);
1014 assert_eq!(declared_char_length("longtext"), None);
1015 }
1016}