Skip to main content

sql_splitter/profile/heuristics/
mod.rs

1//! Turn a neutral [`DumpProfile`] into an explicit, self-contained
2//! [`SyntheticModel`] through a set of small, registered heuristics.
3//!
4//! Each heuristic (see the submodules) receives the schema + evidence for one
5//! column and proposes zero or more [`Candidate`] rules, each tagged with a
6//! [`Precedence`], a [`Confidence`], a stable reason code, and — for the rare
7//! rule that embeds literal source values — the literals it would persist.
8//! Heuristics never mutate a model and never generate a value; they only
9//! propose.
10//!
11//! The [resolver](ModelInference::resolve_column) applies a strict precedence
12//! order and records both the winner and every rejected alternative (without
13//! their values) so `--explain` can show *why* a rule won. The precedence order,
14//! highest first, is:
15//!
16//! 1. explicit YAML (reserved for the overrides merge; never proposed here)
17//! 2. schema constraint (identity / declared default)
18//! 3. **credential guard** (password/token/secret columns are synthetic-only)
19//! 4. relationship / planner (declared foreign keys)
20//! 5. strong semantic name+shape (email, person, money, ...)
21//! 6. observed distribution (categorical, constant, histogram, sample)
22//! 7. type fallback (a plain generator for the column's family)
23//!
24//! The emitted model is self-contained (audit amendment D3): observed row
25//! counts are frozen to an integer `count` while keeping `kind: observed`,
26//! `defaults.inference` is `disabled`, raw samples are never retained, and any
27//! literal an explicit rule genuinely requires stays in that rule and raises a
28//! source-derived warning — there is no "safe to store" mode.
29
30mod credential;
31mod distribution;
32mod planner;
33mod relationship;
34mod schema;
35mod semantic;
36
37/// Whether a column name denotes credential material (any confidence). The
38/// profiler consults this — together with the column being string-shaped — to
39/// keep raw values of credential columns out of its sketches entirely, so
40/// secret material (hashes, tokens, keys) never enters profiling evidence.
41pub 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    declared_character_length, PortableColumn, PortableRelationship, PortableSchema, PortableTable,
60    SqlTypeFamily,
61};
62
63// --- Precedence & confidence -------------------------------------------------
64
65/// Strict precedence class of a proposed rule. Higher classes always beat
66/// lower ones regardless of confidence; see the module docs for the full order.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
68pub enum Precedence {
69    /// A plain generator for the column's SQL family (lowest).
70    TypeFallback,
71    /// A distribution replayed from observed evidence.
72    ObservedDistribution,
73    /// A strong semantic match on name *and* value shape.
74    StrongSemantic,
75    /// A declared foreign key or nominated planner.
76    Relationship,
77    /// A synthetic-only credential rule (password/token/secret).
78    CredentialGuard,
79    /// A rule forced by a schema constraint (identity / default).
80    SchemaConstraint,
81    /// An explicit YAML rule (reserved for the overrides merge; never proposed
82    /// by inference itself). Highest.
83    ExplicitYaml,
84}
85
86/// How sure a heuristic is about a candidate, used to order candidates that
87/// share a [`Precedence`] and to label the decision for `--explain`.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
89pub enum Confidence {
90    Low,
91    Medium,
92    High,
93    Certain,
94}
95
96impl Confidence {
97    /// Stable lowercase label for [`ProfileInference::confidence`].
98    fn label(self) -> &'static str {
99        match self {
100            Confidence::Low => "low",
101            Confidence::Medium => "medium",
102            Confidence::High => "high",
103            Confidence::Certain => "certain",
104        }
105    }
106}
107
108// --- Candidate ---------------------------------------------------------------
109
110/// A single proposed rule for one column: a typed generator plus the metadata
111/// the resolver needs to rank it and explain the outcome.
112#[derive(Debug, Clone)]
113pub struct Candidate {
114    precedence: Precedence,
115    confidence: Confidence,
116    /// Stable reason code, e.g. `credential_name_guard` or `observed_categorical`.
117    reason: &'static str,
118    generator: GeneratorConfig,
119    semantic: Option<String>,
120    /// Literal source values this rule would persist, if any. Non-empty marks
121    /// the rule source-derived (raises `GEN-INFER-SOURCE-DERIVED`).
122    source_literals: Vec<String>,
123}
124
125impl Candidate {
126    /// A candidate with no embedded source literals and no semantic tag.
127    fn new(
128        precedence: Precedence,
129        confidence: Confidence,
130        reason: &'static str,
131        generator: GeneratorConfig,
132    ) -> Self {
133        Self {
134            precedence,
135            confidence,
136            reason,
137            generator,
138            semantic: None,
139            source_literals: Vec::new(),
140        }
141    }
142
143    /// Tag this candidate with the semantic annotation persisted on the rule.
144    fn with_semantic(mut self, semantic: impl Into<String>) -> Self {
145        self.semantic = Some(semantic.into());
146        self
147    }
148
149    /// Record the literal source values this candidate would persist.
150    fn with_source_literals(mut self, literals: Vec<String>) -> Self {
151        self.source_literals = literals;
152        self
153    }
154
155    /// The registry key ordering tuple: the resolver prefers, in order, higher
156    /// precedence, then higher confidence, then a lexicographically smaller
157    /// generator kind (a stable stand-in for descriptor / registration order).
158    fn rank_key(&self) -> (Precedence, Confidence, std::cmp::Reverse<&str>) {
159        (
160            self.precedence,
161            self.confidence,
162            std::cmp::Reverse(self.generator.kind.as_str()),
163        )
164    }
165}
166
167// --- Column context ----------------------------------------------------------
168
169/// Everything the heuristics for one column see: its schema, the evidence the
170/// profiler gathered for it (absent at schema depth), and the surrounding
171/// table.
172pub(crate) struct ColumnContext<'a> {
173    table: &'a PortableTable,
174    column: &'a PortableColumn,
175    evidence: Option<&'a ColumnEvidence>,
176    row_count: Option<u64>,
177}
178
179impl<'a> ColumnContext<'a> {
180    fn table(&self) -> &'a PortableTable {
181        self.table
182    }
183    fn column(&self) -> &'a PortableColumn {
184        self.column
185    }
186    fn evidence(&self) -> Option<&'a ColumnEvidence> {
187        self.evidence
188    }
189    fn row_count(&self) -> Option<u64> {
190        self.row_count
191    }
192}
193
194// --- Decisions & result ------------------------------------------------------
195
196/// One rejected alternative recorded for `--explain`. Deliberately carries no
197/// values — only the shape of the losing proposal.
198#[derive(Debug, Clone)]
199pub struct RejectedCandidate {
200    pub generator_kind: String,
201    pub reason: String,
202    pub precedence: Precedence,
203    pub confidence: Confidence,
204}
205
206/// Why one column ended up with the rule it did, plus the alternatives that
207/// lost. Values are never recorded here.
208#[derive(Debug, Clone)]
209pub struct Decision {
210    /// `"table.column"`.
211    pub column: String,
212    /// The winning candidate's reason code.
213    pub reason: String,
214    pub confidence: Confidence,
215    pub generator_kind: String,
216    /// Whether the winning rule embeds source-derived literal values.
217    pub source_derived: bool,
218    pub rejected: Vec<RejectedCandidate>,
219}
220
221/// The output of [`ModelInference::infer`]: an explicit, self-contained model,
222/// the per-column decisions, and any warnings raised while inferring.
223#[derive(Debug, Clone)]
224pub struct InferenceResult {
225    pub model: SyntheticModel,
226    pub decisions: Vec<Decision>,
227    pub warnings: Vec<Diagnostic>,
228    /// `"table.column"` -> the literal source values its winning rule persists.
229    source_literals: BTreeMap<String, Vec<String>>,
230}
231
232impl InferenceResult {
233    /// The decision recorded for `"table.column"`, if any.
234    pub fn decision(&self, key: &str) -> Option<&Decision> {
235        self.decisions.iter().find(|d| d.column == key)
236    }
237
238    /// The winning column rule for `table`/`column`, if the model has one.
239    pub fn column_rule(&self, table: &str, column: &str) -> Option<&ColumnRule> {
240        self.model.tables.get(table)?.columns.get(column)
241    }
242
243    /// The literal source values persisted by `"table.column"`'s winning rule
244    /// (empty when the rule embeds none — e.g. a synthetic credential rule).
245    pub fn source_literals(&self, key: &str) -> &[String] {
246        self.source_literals
247            .get(key)
248            .map(Vec::as_slice)
249            .unwrap_or(&[])
250    }
251}
252
253/// Errors from [`ModelInference::infer`].
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum InferenceError {
256    /// The profile referenced no table present in the schema.
257    NoTables,
258}
259
260impl fmt::Display for InferenceError {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        match self {
263            InferenceError::NoTables => {
264                write!(f, "no profiled table matched the provided schema")
265            }
266        }
267    }
268}
269
270impl std::error::Error for InferenceError {}
271
272// --- Options -----------------------------------------------------------------
273
274/// Knobs controlling how a profile is turned into a model.
275#[derive(Debug, Clone)]
276pub struct InferenceOptions {
277    /// Whether to attach the removable `profiles` evidence map to the model.
278    /// Deleting it never changes generation; a library caller that does not
279    /// want the (bounded, non-literal) summaries can turn it off.
280    include_profiles: bool,
281}
282
283impl Default for InferenceOptions {
284    fn default() -> Self {
285        Self {
286            include_profiles: true,
287        }
288    }
289}
290
291impl InferenceOptions {
292    /// Include (or drop) the removable `profiles` evidence map. Mirrors the CLI
293    /// emitter's `--profiles`/library `EmitOptions::include_profiles`.
294    pub fn include_profiles(mut self, include: bool) -> Self {
295        self.include_profiles = include;
296        self
297    }
298}
299
300// --- ModelInference ----------------------------------------------------------
301
302/// Infers explicit generation rules from a dump profile through the registered
303/// heuristics. Build one with [`ModelInference::standard`] (the built-in
304/// registry + default options) or [`ModelInference::new`].
305pub struct ModelInference {
306    registry: ExtensionRegistry,
307    options: InferenceOptions,
308}
309
310impl ModelInference {
311    /// A `ModelInference` over the standard generator registry and default
312    /// options.
313    pub fn standard() -> Self {
314        Self {
315            registry: ExtensionRegistry::standard(),
316            options: InferenceOptions::default(),
317        }
318    }
319
320    /// A `ModelInference` over a caller-supplied registry and options.
321    pub fn new(registry: ExtensionRegistry, options: InferenceOptions) -> Self {
322        Self { registry, options }
323    }
324
325    /// Infer an explicit, self-contained model from a schema and its profile.
326    ///
327    /// The `schema` supplies column types, keys, and relationships; the
328    /// `profile` supplies the observed value evidence. Tables in the profile
329    /// that are absent from the schema are skipped with a warning.
330    pub fn infer(
331        &self,
332        schema: &PortableSchema,
333        profile: &DumpProfile,
334    ) -> Result<InferenceResult, InferenceError> {
335        let mut tables = BTreeMap::new();
336        let mut decisions = Vec::new();
337        let mut warnings = Vec::new();
338        let mut profiles = BTreeMap::new();
339        let mut source_literals = BTreeMap::new();
340
341        // Parent key columns any foreign key points at. A referenced key must be
342        // reproducible by random access at generation time, which constrains how
343        // such a column may be inferred (see `infer_table`).
344        let referenced: BTreeSet<(String, String)> = schema
345            .tables
346            .values()
347            .flat_map(|table| {
348                table.relationships.iter().flat_map(|fk| {
349                    let referenced_table = canonical_table_name(schema, &fk.referenced_table)
350                        .unwrap_or(&fk.referenced_table)
351                        .to_string();
352                    fk.referenced_columns
353                        .iter()
354                        .map(move |column| (referenced_table.clone(), column.clone()))
355                })
356            })
357            .collect();
358
359        for table_evidence in &profile.tables {
360            let Some(portable) = schema.tables.get(&table_evidence.table) else {
361                warnings.push(Diagnostic::warning(
362                    &codes::INFER_TABLE_UNKNOWN,
363                    format!("tables.{}", table_evidence.table),
364                    format!(
365                        "profiled table `{}` is not in the schema; skipped",
366                        table_evidence.table
367                    ),
368                ));
369                continue;
370            };
371            let portable = detach_missing_schema_relationships(schema, portable, &mut warnings);
372            let table_model = self.infer_table(
373                &portable,
374                Some(table_evidence),
375                &referenced,
376                &mut decisions,
377                &mut warnings,
378                &mut profiles,
379                &mut source_literals,
380            );
381            tables.insert(portable.name.clone(), table_model);
382        }
383
384        // Any schema table the profile never mentioned still gets an explicit,
385        // type-fallback model so the output stands alone.
386        for (name, portable) in &schema.tables {
387            if tables.contains_key(name) {
388                continue;
389            }
390            let portable = detach_missing_schema_relationships(schema, portable, &mut warnings);
391            let table_model = self.infer_table(
392                &portable,
393                None,
394                &referenced,
395                &mut decisions,
396                &mut warnings,
397                &mut profiles,
398                &mut source_literals,
399            );
400            tables.insert(name.clone(), table_model);
401        }
402
403        if tables.is_empty() {
404            return Err(InferenceError::NoTables);
405        }
406
407        let model = SyntheticModel {
408            schema_ref: None,
409            version: 1,
410            kind: ModelKind::Model,
411            imports: Vec::new(),
412            source: Some(SourceModel {
413                dialect: schema.dialect.clone(),
414                fingerprint: None,
415                fingerprint_policy: None,
416            }),
417            defaults: ModelDefaults::default(), // inference: disabled
418            seed: None,
419            output: OutputModel::default(),
420            tables,
421            profiles: if self.options.include_profiles {
422                profiles
423            } else {
424                BTreeMap::new()
425            },
426        };
427
428        Ok(InferenceResult {
429            model,
430            decisions,
431            warnings,
432            source_literals,
433        })
434    }
435
436    #[allow(clippy::too_many_arguments)]
437    fn infer_table(
438        &self,
439        portable: &PortableTable,
440        evidence: Option<&TableEvidence>,
441        referenced: &BTreeSet<(String, String)>,
442        decisions: &mut Vec<Decision>,
443        warnings: &mut Vec<Diagnostic>,
444        profiles: &mut BTreeMap<String, ProfileMetadata>,
445        source_literals: &mut BTreeMap<String, Vec<String>>,
446    ) -> TableModel {
447        let row_count = evidence.and_then(|e| e.row_count);
448        let mut columns = BTreeMap::new();
449
450        for column in &portable.columns {
451            let key = format!("{}.{}", portable.name, column.name);
452
453            // A declared foreign-key column is owned structurally by the
454            // compiler (via the table's relationship), so it gets no column
455            // generator at all — only a recorded decision.
456            if relationship::is_foreign_key_column(portable, &column.name) {
457                decisions.push(Decision {
458                    column: key,
459                    reason: "relationship_declared_fk".to_string(),
460                    confidence: Confidence::High,
461                    generator_kind: "relation.foreign_key".to_string(),
462                    source_derived: false,
463                    rejected: Vec::new(),
464                });
465                continue;
466            }
467
468            // A text primary key that a foreign key references must be
469            // reproducible by random access at generation time. A plain `string`
470            // has no key recipe (the engine reports GEN-KEY-DOMAIN-UNSUPPORTED),
471            // so give it a `uuid`, which is a text key that reseeds per row.
472            if column.primary_key
473                && matches!(column.family, SqlTypeFamily::Text | SqlTypeFamily::Other)
474                && referenced.contains(&(portable.name.clone(), column.name.clone()))
475                // Only assign a 36-char UUID key if the column can hold it;
476                // otherwise fall through to normal inference (which surfaces a
477                // clear GEN-KEY-DOMAIN-UNSUPPORTED diagnostic) rather than
478                // silently emitting values that overflow the declared length.
479                && text_column_fits_uuid(&column.source_type)
480            {
481                decisions.push(Decision {
482                    column: key,
483                    reason: "referenced_text_key".to_string(),
484                    confidence: Confidence::High,
485                    generator_kind: "uuid".to_string(),
486                    source_derived: false,
487                    rejected: Vec::new(),
488                });
489                columns.insert(
490                    column.name.clone(),
491                    ColumnRule {
492                        semantic: None,
493                        generator: Some(GeneratorConfig {
494                            kind: "uuid".to_string(),
495                            args: BTreeMap::new(),
496                        }),
497                        modifiers: Vec::new(),
498                    },
499                );
500                continue;
501            }
502
503            let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
504            let ctx = ColumnContext {
505                table: portable,
506                column,
507                evidence: column_evidence,
508                row_count,
509            };
510
511            let mut candidates = Vec::new();
512            candidates.extend(schema::candidates(&ctx));
513            candidates.extend(credential::candidates(&ctx));
514            candidates.extend(semantic::candidates(&ctx));
515            candidates.extend(distribution::candidates(&ctx));
516
517            // Drop any proposal whose generator kind is not actually registered
518            // (a heuristic must never emit an uncompilable rule).
519            candidates
520                .retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
521
522            let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
523
524            // A single-column unique column must produce a distinct value per
525            // row. When inference lands on a bounded or categorical generator
526            // (observed_sample, choice, a bounded integer, …) it would exhaust
527            // the auto-unique modifier at scale, so force a high-cardinality
528            // generator by family — a sequence for integers, a uuid for text.
529            // This also drops any replayed source literals (privacy-positive).
530            let (rule, decision, literals) = if is_single_column_unique(portable, column)
531                && rule
532                    .generator
533                    .as_ref()
534                    .is_some_and(|g| is_bounded_generator(&g.kind))
535            {
536                match high_cardinality_generator(column) {
537                    Some(generator) => (
538                        ColumnRule {
539                            semantic: None,
540                            generator: Some(GeneratorConfig {
541                                kind: generator.0.clone(),
542                                args: generator.1,
543                            }),
544                            modifiers: Vec::new(),
545                        },
546                        Decision {
547                            column: key.clone(),
548                            reason: "unique_high_cardinality".to_string(),
549                            confidence: Confidence::High,
550                            generator_kind: generator.0,
551                            source_derived: false,
552                            rejected: Vec::new(),
553                        },
554                        Vec::new(),
555                    ),
556                    None => (rule, decision, literals),
557                }
558            } else {
559                (rule, decision, literals)
560            };
561
562            if !literals.is_empty() {
563                warnings.push(Diagnostic::warning(
564                    &codes::INFER_SOURCE_DERIVED,
565                    key.clone(),
566                    format!(
567                        "persists {} source-derived literal value(s) required by its `{}` rule",
568                        literals.len(),
569                        decision.generator_kind
570                    ),
571                ));
572                source_literals.insert(key.clone(), literals);
573            }
574
575            if self.options.include_profiles {
576                if let Some(meta) = profile_metadata(&ctx, &decision) {
577                    profiles.insert(key.clone(), meta);
578                }
579            }
580
581            decisions.push(decision);
582            columns.insert(column.name.clone(), rule);
583        }
584
585        // Planner reconnaissance runs at table scope. Name/shape nominations
586        // (temporal, geo) remain informational, but a structural composite-key
587        // match is inserted as real configuration so the generated pivot's
588        // primary key holds by construction.
589        warnings.extend(planner::nominations(portable, evidence));
590
591        // A composite primary key holds by construction one of two ways: a
592        // junction_pair over two of its foreign keys, or — when it has fewer
593        // than two foreign keys — a sequenced non-FK integer column.
594        let planners = inferred_planners(portable);
595        if planners.is_empty() {
596            if let Some(column) = distinctness_sequence_column(portable) {
597                columns.insert(
598                    column,
599                    ColumnRule {
600                        semantic: None,
601                        generator: Some(GeneratorConfig {
602                            kind: "sequence".to_string(),
603                            args: [("start".to_string(), yaml(1))].into_iter().collect(),
604                        }),
605                        modifiers: Vec::new(),
606                    },
607                );
608            }
609        }
610
611        TableModel {
612            seed: TableSeed::Inherit,
613            rows: match row_count {
614                Some(count) => RowsModel::Observed { count },
615                None => RowsModel::Fixed { count: 0 },
616            },
617            schema: portable.clone(),
618            columns,
619            relationships: declared_relationships(portable),
620            planners,
621        }
622    }
623}
624
625/// Remove source-schema foreign keys whose parent table is absent from the
626/// parsed dump. Partial dumps commonly retain these constraints even though
627/// they omit the referenced tables. The missing relationship cannot be
628/// generated or rendered, and its columns must receive ordinary generators.
629fn detach_missing_schema_relationships(
630    schema: &PortableSchema,
631    table: &PortableTable,
632    warnings: &mut Vec<Diagnostic>,
633) -> PortableTable {
634    let mut portable = table.clone();
635    let mut detached = false;
636    portable.relationships = table
637        .relationships
638        .iter()
639        .filter_map(|relationship| {
640            // Table lookup follows the codebase's case-insensitive convention
641            // (`Schema::get_table_id`). Normalize a matching spelling now because
642            // the compiled model uses exact table keys later.
643            if let Some(canonical) =
644                canonical_table_name(schema, &relationship.referenced_table)
645            {
646                let mut relationship = relationship.clone();
647                relationship.referenced_table = canonical.to_string();
648                return Some(relationship);
649            }
650            detached = true;
651            warnings.push(Diagnostic::warning(
652                &codes::DETACHED_DEPENDENCY,
653                format!("tables.{}.relationships", table.name),
654                format!(
655                    "source relationship `{}` on table `{}` references table `{}`, which is absent from the dump; its foreign key is detached and omitted from the rendered DDL",
656                    relationship.name.as_deref().unwrap_or("(unnamed)"),
657                    table.name,
658                    relationship.referenced_table
659                ),
660            ));
661            None
662        })
663        .collect();
664    if detached {
665        portable.create_statement = None;
666    }
667    portable
668}
669
670fn canonical_table_name<'a>(schema: &'a PortableSchema, name: &str) -> Option<&'a str> {
671    schema
672        .tables
673        .get_key_value(name)
674        .map(|(canonical, _)| canonical.as_str())
675        .or_else(|| {
676            schema
677                .tables
678                .keys()
679                .find(|candidate| candidate.eq_ignore_ascii_case(name))
680                .map(String::as_str)
681        })
682}
683
684/// Resolve one column's candidates into a rule + decision, applying precedence
685/// and recording rejected alternatives (without values).
686fn resolve_column(
687    ctx: &ColumnContext<'_>,
688    key: &str,
689    mut candidates: Vec<Candidate>,
690) -> (ColumnRule, Decision, Vec<String>) {
691    // Always have a floor: a bare type fallback, so a column never goes ruleless.
692    if candidates.is_empty() {
693        candidates.push(schema::type_fallback(ctx));
694    }
695
696    // Highest rank_key wins; stable so ties resolve deterministically.
697    let winner_index = candidates
698        .iter()
699        .enumerate()
700        .max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
701        .map(|(index, _)| index)
702        .expect("candidates is non-empty");
703
704    let winner = candidates.swap_remove(winner_index);
705
706    let rejected = candidates
707        .iter()
708        .map(|candidate| RejectedCandidate {
709            generator_kind: candidate.generator.kind.clone(),
710            reason: candidate.reason.to_string(),
711            precedence: candidate.precedence,
712            confidence: candidate.confidence,
713        })
714        .collect();
715
716    let mut modifiers = Vec::new();
717    if let Some(modifier) = character_limit_modifier(ctx, &winner) {
718        modifiers.push(modifier);
719    }
720    if let Some(modifier) = sparse_modifier(ctx, &winner) {
721        modifiers.push(modifier);
722    }
723
724    let decision = Decision {
725        column: key.to_string(),
726        reason: winner.reason.to_string(),
727        confidence: winner.confidence,
728        generator_kind: winner.generator.kind.clone(),
729        source_derived: !winner.source_literals.is_empty(),
730        rejected,
731    };
732
733    let rule = ColumnRule {
734        semantic: winner.semantic.clone(),
735        generator: Some(winner.generator.clone()),
736        modifiers,
737    };
738
739    (rule, decision, winner.source_literals)
740}
741
742/// Keep inferred semantic and credential text within a bounded SQL text type.
743///
744/// The plain `string` fallback already receives a schema-capped range. Literal
745/// replay generators carry values accepted by the source database. Other
746/// inferred text generators have variable output lengths and need an explicit
747/// final cap. This modifier precedes `null_rate`, so a nullable value is
748/// truncated before it can become `NULL`.
749fn character_limit_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
750    if ctx.column().family != SqlTypeFamily::Text {
751        return None;
752    }
753    if matches!(
754        winner.generator.kind.as_str(),
755        "string" | "constant" | "weighted_choice" | "observed_sample" | "database_default" | "null"
756    ) {
757        return None;
758    }
759    let max_length = declared_character_length(&ctx.column().source_type)?;
760    Some(ModifierConfig {
761        kind: "truncate".to_string(),
762        args: [("max_length".to_string(), yaml(max_length))]
763            .into_iter()
764            .collect(),
765    })
766}
767
768/// Infer one column's generator from its schema alone — declared name and type,
769/// with no value evidence — reusing the same schema, credential, and semantic
770/// heuristics (and their precedence) the profiler applies at schema depth. The
771/// `distribution` heuristics need value evidence and contribute nothing here.
772/// A generator is always returned: the type fallback is the guaranteed floor, so
773/// a caller relying on this never leaves a column unowned.
774pub fn schema_inferred_generator(
775    table: &PortableTable,
776    column: &PortableColumn,
777) -> GeneratorConfig {
778    let ctx = ColumnContext {
779        table,
780        column,
781        evidence: None,
782        row_count: None,
783    };
784    let mut candidates = Vec::new();
785    candidates.extend(schema::candidates(&ctx));
786    candidates.extend(credential::candidates(&ctx));
787    candidates.extend(semantic::candidates(&ctx));
788    let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
789    rule.generator
790        .expect("resolve_column always assigns a generator")
791}
792
793/// A `null_rate` modifier replaying an observed null fraction on a nullable
794/// column, unless the winning rule already produces `NULL`/`DEFAULT` itself.
795fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
796    if !ctx.column().nullable {
797        return None;
798    }
799    if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
800        return None;
801    }
802    let rate = ctx.evidence()?.null_rate;
803    if !(0.005..=0.995).contains(&rate) {
804        return None;
805    }
806    let mut args = BTreeMap::new();
807    args.insert("rate".to_string(), yaml(round4(rate)));
808    Some(ModifierConfig {
809        kind: "null_rate".to_string(),
810        args,
811    })
812}
813
814/// Build the removable evidence summary for one column (bounded, non-literal).
815fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
816    let evidence = ctx.evidence()?;
817    Some(ProfileMetadata {
818        rows: ctx.row_count().unwrap_or(evidence.total_count),
819        null_fraction: round4(evidence.null_rate),
820        distinct_estimate: evidence.distinct_estimate.round() as u64,
821        inference: Some(ProfileInference {
822            selected: decision.generator_kind.clone(),
823            confidence: decision.confidence.label().to_string(),
824            reasons: vec![decision.reason.clone()],
825        }),
826    })
827}
828
829/// Declared foreign keys become explicit model relationships so the output
830/// stands alone.
831/// Whether a resolved generator kind draws from a bounded or categorical domain
832/// (so it cannot supply a distinct value per row on a large unique column).
833fn is_bounded_generator(kind: &str) -> bool {
834    matches!(
835        kind,
836        "observed_sample"
837            | "choice"
838            | "weighted_choice"
839            | "histogram"
840            | "normal"
841            | "integer"
842            | "decimal"
843            | "boolean"
844            | "constant"
845            | "null"
846            | "database_default"
847    )
848}
849
850/// Whether a text column declared as `source_type` can hold a 36-char UUID
851/// string. Length-less text types have no cap and so always fit.
852fn text_column_fits_uuid(source_type: &str) -> bool {
853    const UUID_LEN: usize = 36;
854    declared_character_length(source_type).is_none_or(|n| n >= UUID_LEN)
855}
856
857/// A high-cardinality generator (kind + args) for a unique `column` whose
858/// inferred generator was bounded: a `sequence` for an integer, a `uuid` for
859/// text. `None` for families with no obvious high-cardinality synthetic key.
860fn high_cardinality_generator(
861    column: &PortableColumn,
862) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
863    match column.family {
864        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
865            "sequence".to_string(),
866            [("start".to_string(), yaml(1))].into_iter().collect(),
867        )),
868        SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
869            // A UUID string is 36 chars: don't force it into a column too short
870            // to hold it, which would emit values that violate the declared
871            // length. Fall back to the inferred (bounded) generator instead.
872            if text_column_fits_uuid(&column.source_type) {
873                Some(("uuid".to_string(), BTreeMap::new()))
874            } else {
875                None
876            }
877        }
878        _ => None,
879    }
880}
881
882/// Whether `column` is a single-column unique key of `table`: its own `unique`
883/// flag, a single-column UNIQUE constraint, or a single-column unique index.
884/// Mirrors the compiler's single-column-key test so inference and generation
885/// agree on which columns must stay distinct.
886fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
887    if column.unique {
888        return true;
889    }
890    let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
891    table
892        .unique_constraints
893        .iter()
894        .any(|constraint| single(&constraint.columns))
895        || table
896            .indexes
897            .iter()
898            .any(|index| index.unique && single(&index.columns))
899}
900
901/// The single-column declared foreign key whose one column is `column`, if any.
902/// A composite (multi-column) foreign key does not qualify.
903fn single_column_fk<'a>(
904    table: &'a PortableTable,
905    column: &str,
906) -> Option<&'a PortableRelationship> {
907    table
908        .relationships
909        .iter()
910        .find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
911}
912
913/// Infer the planners a pivot table needs so its composite primary key holds by
914/// construction. A composite primary key that contains at least two
915/// single-column foreign keys is a many-to-many junction: emit a
916/// `relation.junction_pair` planner over the first two such foreign-key columns.
917/// Distinct `(left, right)` pairs make the whole composite key distinct, even
918/// when the primary key also carries a discriminator or extra column (the
919/// polymorphic pivot shape). This is a purely structural match — it keys off the
920/// primary-key shape and its foreign keys, not any table or column name — so it
921/// covers any junction table, Laravel or otherwise. A composite key with fewer
922/// than two foreign-key columns is left to other mechanisms.
923fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
924    let pk = &table.primary_key;
925    if pk.len() < 2 {
926        return Vec::new();
927    }
928    // The primary-key columns that are single-column foreign keys, in PK order.
929    let fk_columns: Vec<(&String, &PortableRelationship)> = pk
930        .iter()
931        .filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
932        .collect();
933    if fk_columns.len() < 2 {
934        return Vec::new();
935    }
936    let (left_col, left) = fk_columns[0];
937    let (right_col, right) = fk_columns[1];
938    let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
939        return Vec::new();
940    };
941
942    let mut columns = serde_yaml_ng::Mapping::new();
943    columns.insert(yaml("left"), yaml(left_col));
944    columns.insert(yaml("right"), yaml(right_col));
945    let mut args = BTreeMap::new();
946    args.insert(
947        "columns".to_string(),
948        serde_yaml_ng::Value::Mapping(columns),
949    );
950    args.insert("left_relationship".to_string(), yaml(left_name));
951    args.insert("right_relationship".to_string(), yaml(right_name));
952
953    vec![PlannerConfig {
954        kind: "relation.junction_pair".to_string(),
955        args,
956    }]
957}
958
959/// For a composite-primary-key table that is *not* a two-FK junction, the name
960/// of a non-foreign-key integer primary-key column to sequence so the composite
961/// key stays distinct by construction (its per-row-unique values alone make
962/// every tuple distinct). This is the fallback for polymorphic pivots whose PK
963/// mixes a single foreign key, a discriminator, and a plain integer id (e.g.
964/// `model_has_roles`). Returns `None` when the PK is not composite or has no
965/// such column, leaving the composite key to fail its own verification loudly.
966fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
967    if table.primary_key.len() < 2 {
968        return None;
969    }
970    table.primary_key.iter().find_map(|column| {
971        let is_integer = table.columns.iter().any(|c| {
972            &c.name == column
973                && matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
974        });
975        (is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
976    })
977}
978
979fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
980    table
981        .relationships
982        .iter()
983        .map(|fk| RelationshipModel {
984            name: fk.name.clone(),
985            columns: fk.columns.clone(),
986            references: RelationshipReference {
987                table: fk.referenced_table.clone(),
988                columns: fk.referenced_columns.clone(),
989            },
990            distribution: None,
991        })
992        .collect()
993}
994
995fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
996    table.columns.iter().find(|c| c.name == name)
997}
998
999// --- Shared candidate-building helpers (used by the submodules) --------------
1000
1001/// Serialize a value into a YAML scalar/sequence for a generator argument.
1002pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
1003    serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
1004}
1005
1006/// A generator config with no arguments.
1007pub(crate) fn generator(kind: &str) -> GeneratorConfig {
1008    GeneratorConfig {
1009        kind: kind.to_string(),
1010        args: BTreeMap::new(),
1011    }
1012}
1013
1014/// A generator config with the given `(key, value)` arguments.
1015pub(crate) fn generator_with(
1016    kind: &str,
1017    args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
1018) -> GeneratorConfig {
1019    GeneratorConfig {
1020        kind: kind.to_string(),
1021        args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
1022    }
1023}
1024
1025/// A `[{ value, weight }, ...]` YAML sequence for the weighted generators.
1026pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
1027    let seq = entries
1028        .iter()
1029        .map(|(value, weight)| {
1030            let mut map = serde_yaml_ng::Mapping::new();
1031            map.insert(yaml("value"), yaml(value));
1032            map.insert(yaml("weight"), yaml(*weight));
1033            serde_yaml_ng::Value::Mapping(map)
1034        })
1035        .collect();
1036    serde_yaml_ng::Value::Sequence(seq)
1037}
1038
1039/// Round a fraction to four decimal places for stable, readable emission.
1040fn round4(value: f64) -> f64 {
1041    (value * 10_000.0).round() / 10_000.0
1042}
1043
1044#[cfg(test)]
1045mod uuid_length_tests {
1046    use super::*;
1047
1048    fn text_col(source_type: &str) -> PortableColumn {
1049        PortableColumn {
1050            name: "code".to_string(),
1051            source_type: source_type.to_string(),
1052            family: SqlTypeFamily::Text,
1053            nullable: false,
1054            primary_key: false,
1055            unique: true,
1056            default_sql: None,
1057            generated: false,
1058            identity: false,
1059            collation: None,
1060        }
1061    }
1062
1063    #[test]
1064    fn short_text_unique_not_forced_to_uuid() {
1065        // varchar(8) cannot hold a 36-char UUID; forcing one would emit values
1066        // that violate the declared length.
1067        assert!(
1068            high_cardinality_generator(&text_col("varchar(8)")).is_none(),
1069            "uuid forced into a column too short to hold it"
1070        );
1071    }
1072
1073    #[test]
1074    fn long_and_unbounded_text_unique_get_uuid() {
1075        assert_eq!(
1076            high_cardinality_generator(&text_col("varchar(64)")).map(|(k, _)| k),
1077            Some("uuid".to_string())
1078        );
1079        // Length-less text is unbounded, so a UUID fits.
1080        assert_eq!(
1081            high_cardinality_generator(&text_col("text")).map(|(k, _)| k),
1082            Some("uuid".to_string())
1083        );
1084    }
1085}