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    PortableColumn, PortableRelationship, PortableSchema, PortableTable, SqlTypeFamily,
60};
61
62// --- Precedence & confidence -------------------------------------------------
63
64/// Strict precedence class of a proposed rule. Higher classes always beat
65/// lower ones regardless of confidence; see the module docs for the full order.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
67pub enum Precedence {
68    /// A plain generator for the column's SQL family (lowest).
69    TypeFallback,
70    /// A distribution replayed from observed evidence.
71    ObservedDistribution,
72    /// A strong semantic match on name *and* value shape.
73    StrongSemantic,
74    /// A declared foreign key or nominated planner.
75    Relationship,
76    /// A synthetic-only credential rule (password/token/secret).
77    CredentialGuard,
78    /// A rule forced by a schema constraint (identity / default).
79    SchemaConstraint,
80    /// An explicit YAML rule (reserved for the overrides merge; never proposed
81    /// by inference itself). Highest.
82    ExplicitYaml,
83}
84
85/// How sure a heuristic is about a candidate, used to order candidates that
86/// share a [`Precedence`] and to label the decision for `--explain`.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
88pub enum Confidence {
89    Low,
90    Medium,
91    High,
92    Certain,
93}
94
95impl Confidence {
96    /// Stable lowercase label for [`ProfileInference::confidence`].
97    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// --- Candidate ---------------------------------------------------------------
108
109/// A single proposed rule for one column: a typed generator plus the metadata
110/// the resolver needs to rank it and explain the outcome.
111#[derive(Debug, Clone)]
112pub struct Candidate {
113    precedence: Precedence,
114    confidence: Confidence,
115    /// Stable reason code, e.g. `credential_name_guard` or `observed_categorical`.
116    reason: &'static str,
117    generator: GeneratorConfig,
118    semantic: Option<String>,
119    /// Literal source values this rule would persist, if any. Non-empty marks
120    /// the rule source-derived (raises `GEN-INFER-SOURCE-DERIVED`).
121    source_literals: Vec<String>,
122}
123
124impl Candidate {
125    /// A candidate with no embedded source literals and no semantic tag.
126    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    /// Tag this candidate with the semantic annotation persisted on the rule.
143    fn with_semantic(mut self, semantic: impl Into<String>) -> Self {
144        self.semantic = Some(semantic.into());
145        self
146    }
147
148    /// Record the literal source values this candidate would persist.
149    fn with_source_literals(mut self, literals: Vec<String>) -> Self {
150        self.source_literals = literals;
151        self
152    }
153
154    /// The registry key ordering tuple: the resolver prefers, in order, higher
155    /// precedence, then higher confidence, then a lexicographically smaller
156    /// generator kind (a stable stand-in for descriptor / registration order).
157    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
166// --- Column context ----------------------------------------------------------
167
168/// Everything the heuristics for one column see: its schema, the evidence the
169/// profiler gathered for it (absent at schema depth), and the surrounding
170/// table.
171pub(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// --- Decisions & result ------------------------------------------------------
194
195/// One rejected alternative recorded for `--explain`. Deliberately carries no
196/// values — only the shape of the losing proposal.
197#[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/// Why one column ended up with the rule it did, plus the alternatives that
206/// lost. Values are never recorded here.
207#[derive(Debug, Clone)]
208pub struct Decision {
209    /// `"table.column"`.
210    pub column: String,
211    /// The winning candidate's reason code.
212    pub reason: String,
213    pub confidence: Confidence,
214    pub generator_kind: String,
215    /// Whether the winning rule embeds source-derived literal values.
216    pub source_derived: bool,
217    pub rejected: Vec<RejectedCandidate>,
218}
219
220/// The output of [`ModelInference::infer`]: an explicit, self-contained model,
221/// the per-column decisions, and any warnings raised while inferring.
222#[derive(Debug, Clone)]
223pub struct InferenceResult {
224    pub model: SyntheticModel,
225    pub decisions: Vec<Decision>,
226    pub warnings: Vec<Diagnostic>,
227    /// `"table.column"` -> the literal source values its winning rule persists.
228    source_literals: BTreeMap<String, Vec<String>>,
229}
230
231impl InferenceResult {
232    /// The decision recorded for `"table.column"`, if any.
233    pub fn decision(&self, key: &str) -> Option<&Decision> {
234        self.decisions.iter().find(|d| d.column == key)
235    }
236
237    /// The winning column rule for `table`/`column`, if the model has one.
238    pub fn column_rule(&self, table: &str, column: &str) -> Option<&ColumnRule> {
239        self.model.tables.get(table)?.columns.get(column)
240    }
241
242    /// The literal source values persisted by `"table.column"`'s winning rule
243    /// (empty when the rule embeds none — e.g. a synthetic credential rule).
244    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/// Errors from [`ModelInference::infer`].
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum InferenceError {
255    /// The profile referenced no table present in the schema.
256    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// --- Options -----------------------------------------------------------------
272
273/// Knobs controlling how a profile is turned into a model.
274#[derive(Debug, Clone)]
275pub struct InferenceOptions {
276    /// Whether to attach the removable `profiles` evidence map to the model.
277    /// Deleting it never changes generation; a library caller that does not
278    /// want the (bounded, non-literal) summaries can turn it off.
279    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    /// Include (or drop) the removable `profiles` evidence map. Mirrors the CLI
292    /// emitter's `--profiles`/library `EmitOptions::include_profiles`.
293    pub fn include_profiles(mut self, include: bool) -> Self {
294        self.include_profiles = include;
295        self
296    }
297}
298
299// --- ModelInference ----------------------------------------------------------
300
301/// Infers explicit generation rules from a dump profile through the registered
302/// heuristics. Build one with [`ModelInference::standard`] (the built-in
303/// registry + default options) or [`ModelInference::new`].
304pub struct ModelInference {
305    registry: ExtensionRegistry,
306    options: InferenceOptions,
307}
308
309impl ModelInference {
310    /// A `ModelInference` over the standard generator registry and default
311    /// options.
312    pub fn standard() -> Self {
313        Self {
314            registry: ExtensionRegistry::standard(),
315            options: InferenceOptions::default(),
316        }
317    }
318
319    /// A `ModelInference` over a caller-supplied registry and options.
320    pub fn new(registry: ExtensionRegistry, options: InferenceOptions) -> Self {
321        Self { registry, options }
322    }
323
324    /// Infer an explicit, self-contained model from a schema and its profile.
325    ///
326    /// The `schema` supplies column types, keys, and relationships; the
327    /// `profile` supplies the observed value evidence. Tables in the profile
328    /// that are absent from the schema are skipped with a warning.
329    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        // Parent key columns any foreign key points at. A referenced key must be
341        // reproducible by random access at generation time, which constrains how
342        // such a column may be inferred (see `infer_table`).
343        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        // Any schema table the profile never mentioned still gets an explicit,
380        // type-fallback model so the output stands alone.
381        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(), // inference: disabled
412            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            // A declared foreign-key column is owned structurally by the
448            // compiler (via the table's relationship), so it gets no column
449            // generator at all — only a recorded decision.
450            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            // A text primary key that a foreign key references must be
463            // reproducible by random access at generation time. A plain `string`
464            // has no key recipe (the engine reports GEN-KEY-DOMAIN-UNSUPPORTED),
465            // so give it a `uuid`, which is a text key that reseeds per row.
466            if column.primary_key
467                && matches!(column.family, SqlTypeFamily::Text | SqlTypeFamily::Other)
468                && referenced.contains(&(portable.name.clone(), column.name.clone()))
469                // Only assign a 36-char UUID key if the column can hold it;
470                // otherwise fall through to normal inference (which surfaces a
471                // clear GEN-KEY-DOMAIN-UNSUPPORTED diagnostic) rather than
472                // silently emitting values that overflow the declared length.
473                && 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            // Drop any proposal whose generator kind is not actually registered
512            // (a heuristic must never emit an uncompilable rule).
513            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            // A single-column unique column must produce a distinct value per
519            // row. When inference lands on a bounded or categorical generator
520            // (observed_sample, choice, a bounded integer, …) it would exhaust
521            // the auto-unique modifier at scale, so force a high-cardinality
522            // generator by family — a sequence for integers, a uuid for text.
523            // This also drops any replayed source literals (privacy-positive).
524            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        // Planner reconnaissance runs at table scope. Name/shape nominations
580        // (temporal, geo) remain informational, but a structural composite-key
581        // match is inserted as real configuration so the generated pivot's
582        // primary key holds by construction.
583        warnings.extend(planner::nominations(portable, evidence));
584
585        // A composite primary key holds by construction one of two ways: a
586        // junction_pair over two of its foreign keys, or — when it has fewer
587        // than two foreign keys — a sequenced non-FK integer column.
588        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
619/// Resolve one column's candidates into a rule + decision, applying precedence
620/// and recording rejected alternatives (without values).
621fn resolve_column(
622    ctx: &ColumnContext<'_>,
623    key: &str,
624    mut candidates: Vec<Candidate>,
625) -> (ColumnRule, Decision, Vec<String>) {
626    // Always have a floor: a bare type fallback, so a column never goes ruleless.
627    if candidates.is_empty() {
628        candidates.push(schema::type_fallback(ctx));
629    }
630
631    // Highest rank_key wins; stable so ties resolve deterministically.
632    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
674/// Infer one column's generator from its schema alone — declared name and type,
675/// with no value evidence — reusing the same schema, credential, and semantic
676/// heuristics (and their precedence) the profiler applies at schema depth. The
677/// `distribution` heuristics need value evidence and contribute nothing here.
678/// A generator is always returned: the type fallback is the guaranteed floor, so
679/// a caller relying on this never leaves a column unowned.
680pub 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
699/// A `null_rate` modifier replaying an observed null fraction on a nullable
700/// column, unless the winning rule already produces `NULL`/`DEFAULT` itself.
701fn 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
720/// Build the removable evidence summary for one column (bounded, non-literal).
721fn 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
735/// Declared foreign keys become explicit model relationships so the output
736/// stands alone.
737/// Whether a resolved generator kind draws from a bounded or categorical domain
738/// (so it cannot supply a distinct value per row on a large unique column).
739fn 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
756/// The maximum character length declared by a text type such as `varchar(8)`,
757/// `char(10)` or `nvarchar(255)`. `None` for length-less text types (`text`,
758/// `longtext`, a bare `varchar`), which impose no fixed cap.
759fn 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    // A precision/scale pair (e.g. `decimal(10,2)`) keeps the first number;
763    // text length declarations are a single number anyway.
764    source_type[open + 1..close]
765        .split(',')
766        .next()?
767        .trim()
768        .parse::<usize>()
769        .ok()
770}
771
772/// Whether a text column declared as `source_type` can hold a 36-char UUID
773/// string. Length-less text types have no cap and so always fit.
774fn 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
779/// A high-cardinality generator (kind + args) for a unique `column` whose
780/// inferred generator was bounded: a `sequence` for an integer, a `uuid` for
781/// text. `None` for families with no obvious high-cardinality synthetic key.
782fn 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            // A UUID string is 36 chars: don't force it into a column too short
792            // to hold it, which would emit values that violate the declared
793            // length. Fall back to the inferred (bounded) generator instead.
794            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
804/// Whether `column` is a single-column unique key of `table`: its own `unique`
805/// flag, a single-column UNIQUE constraint, or a single-column unique index.
806/// Mirrors the compiler's single-column-key test so inference and generation
807/// agree on which columns must stay distinct.
808fn 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
823/// The single-column declared foreign key whose one column is `column`, if any.
824/// A composite (multi-column) foreign key does not qualify.
825fn 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
835/// Infer the planners a pivot table needs so its composite primary key holds by
836/// construction. A composite primary key that contains at least two
837/// single-column foreign keys is a many-to-many junction: emit a
838/// `relation.junction_pair` planner over the first two such foreign-key columns.
839/// Distinct `(left, right)` pairs make the whole composite key distinct, even
840/// when the primary key also carries a discriminator or extra column (the
841/// polymorphic pivot shape). This is a purely structural match — it keys off the
842/// primary-key shape and its foreign keys, not any table or column name — so it
843/// covers any junction table, Laravel or otherwise. A composite key with fewer
844/// than two foreign-key columns is left to other mechanisms.
845fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
846    let pk = &table.primary_key;
847    if pk.len() < 2 {
848        return Vec::new();
849    }
850    // The primary-key columns that are single-column foreign keys, in PK order.
851    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
881/// For a composite-primary-key table that is *not* a two-FK junction, the name
882/// of a non-foreign-key integer primary-key column to sequence so the composite
883/// key stays distinct by construction (its per-row-unique values alone make
884/// every tuple distinct). This is the fallback for polymorphic pivots whose PK
885/// mixes a single foreign key, a discriminator, and a plain integer id (e.g.
886/// `model_has_roles`). Returns `None` when the PK is not composite or has no
887/// such column, leaving the composite key to fail its own verification loudly.
888fn 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
921// --- Shared candidate-building helpers (used by the submodules) --------------
922
923/// Serialize a value into a YAML scalar/sequence for a generator argument.
924pub(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
928/// A generator config with no arguments.
929pub(crate) fn generator(kind: &str) -> GeneratorConfig {
930    GeneratorConfig {
931        kind: kind.to_string(),
932        args: BTreeMap::new(),
933    }
934}
935
936/// A generator config with the given `(key, value)` arguments.
937pub(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
947/// A `[{ value, weight }, ...]` YAML sequence for the weighted generators.
948pub(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
961/// Round a fraction to four decimal places for stable, readable emission.
962fn 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        // varchar(8) cannot hold a 36-char UUID; forcing one would emit values
988        // that violate the declared length.
989        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        // Length-less text is unbounded, so a UUID fits.
1002        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}