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            {
470                decisions.push(Decision {
471                    column: key,
472                    reason: "referenced_text_key".to_string(),
473                    confidence: Confidence::High,
474                    generator_kind: "uuid".to_string(),
475                    source_derived: false,
476                    rejected: Vec::new(),
477                });
478                columns.insert(
479                    column.name.clone(),
480                    ColumnRule {
481                        semantic: None,
482                        generator: Some(GeneratorConfig {
483                            kind: "uuid".to_string(),
484                            args: BTreeMap::new(),
485                        }),
486                        modifiers: Vec::new(),
487                    },
488                );
489                continue;
490            }
491
492            let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
493            let ctx = ColumnContext {
494                table: portable,
495                column,
496                evidence: column_evidence,
497                row_count,
498            };
499
500            let mut candidates = Vec::new();
501            candidates.extend(schema::candidates(&ctx));
502            candidates.extend(credential::candidates(&ctx));
503            candidates.extend(semantic::candidates(&ctx));
504            candidates.extend(distribution::candidates(&ctx));
505
506            // Drop any proposal whose generator kind is not actually registered
507            // (a heuristic must never emit an uncompilable rule).
508            candidates
509                .retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
510
511            let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
512
513            // A single-column unique column must produce a distinct value per
514            // row. When inference lands on a bounded or categorical generator
515            // (observed_sample, choice, a bounded integer, …) it would exhaust
516            // the auto-unique modifier at scale, so force a high-cardinality
517            // generator by family — a sequence for integers, a uuid for text.
518            // This also drops any replayed source literals (privacy-positive).
519            let (rule, decision, literals) = if is_single_column_unique(portable, column)
520                && rule
521                    .generator
522                    .as_ref()
523                    .is_some_and(|g| is_bounded_generator(&g.kind))
524            {
525                match high_cardinality_generator(column) {
526                    Some(generator) => (
527                        ColumnRule {
528                            semantic: None,
529                            generator: Some(GeneratorConfig {
530                                kind: generator.0.clone(),
531                                args: generator.1,
532                            }),
533                            modifiers: Vec::new(),
534                        },
535                        Decision {
536                            column: key.clone(),
537                            reason: "unique_high_cardinality".to_string(),
538                            confidence: Confidence::High,
539                            generator_kind: generator.0,
540                            source_derived: false,
541                            rejected: Vec::new(),
542                        },
543                        Vec::new(),
544                    ),
545                    None => (rule, decision, literals),
546                }
547            } else {
548                (rule, decision, literals)
549            };
550
551            if !literals.is_empty() {
552                warnings.push(Diagnostic::warning(
553                    &codes::INFER_SOURCE_DERIVED,
554                    key.clone(),
555                    format!(
556                        "persists {} source-derived literal value(s) required by its `{}` rule",
557                        literals.len(),
558                        decision.generator_kind
559                    ),
560                ));
561                source_literals.insert(key.clone(), literals);
562            }
563
564            if self.options.include_profiles {
565                if let Some(meta) = profile_metadata(&ctx, &decision) {
566                    profiles.insert(key.clone(), meta);
567                }
568            }
569
570            decisions.push(decision);
571            columns.insert(column.name.clone(), rule);
572        }
573
574        // Planner reconnaissance runs at table scope. Name/shape nominations
575        // (temporal, geo) remain informational, but a structural composite-key
576        // match is inserted as real configuration so the generated pivot's
577        // primary key holds by construction.
578        warnings.extend(planner::nominations(portable, evidence));
579
580        // A composite primary key holds by construction one of two ways: a
581        // junction_pair over two of its foreign keys, or — when it has fewer
582        // than two foreign keys — a sequenced non-FK integer column.
583        let planners = inferred_planners(portable);
584        if planners.is_empty() {
585            if let Some(column) = distinctness_sequence_column(portable) {
586                columns.insert(
587                    column,
588                    ColumnRule {
589                        semantic: None,
590                        generator: Some(GeneratorConfig {
591                            kind: "sequence".to_string(),
592                            args: [("start".to_string(), yaml(1))].into_iter().collect(),
593                        }),
594                        modifiers: Vec::new(),
595                    },
596                );
597            }
598        }
599
600        TableModel {
601            seed: TableSeed::Inherit,
602            rows: match row_count {
603                Some(count) => RowsModel::Observed { count },
604                None => RowsModel::Fixed { count: 0 },
605            },
606            schema: portable.clone(),
607            columns,
608            relationships: declared_relationships(portable),
609            planners,
610        }
611    }
612}
613
614/// Resolve one column's candidates into a rule + decision, applying precedence
615/// and recording rejected alternatives (without values).
616fn resolve_column(
617    ctx: &ColumnContext<'_>,
618    key: &str,
619    mut candidates: Vec<Candidate>,
620) -> (ColumnRule, Decision, Vec<String>) {
621    // Always have a floor: a bare type fallback, so a column never goes ruleless.
622    if candidates.is_empty() {
623        candidates.push(schema::type_fallback(ctx));
624    }
625
626    // Highest rank_key wins; stable so ties resolve deterministically.
627    let winner_index = candidates
628        .iter()
629        .enumerate()
630        .max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
631        .map(|(index, _)| index)
632        .expect("candidates is non-empty");
633
634    let winner = candidates.swap_remove(winner_index);
635
636    let rejected = candidates
637        .iter()
638        .map(|candidate| RejectedCandidate {
639            generator_kind: candidate.generator.kind.clone(),
640            reason: candidate.reason.to_string(),
641            precedence: candidate.precedence,
642            confidence: candidate.confidence,
643        })
644        .collect();
645
646    let mut modifiers = Vec::new();
647    if let Some(modifier) = sparse_modifier(ctx, &winner) {
648        modifiers.push(modifier);
649    }
650
651    let decision = Decision {
652        column: key.to_string(),
653        reason: winner.reason.to_string(),
654        confidence: winner.confidence,
655        generator_kind: winner.generator.kind.clone(),
656        source_derived: !winner.source_literals.is_empty(),
657        rejected,
658    };
659
660    let rule = ColumnRule {
661        semantic: winner.semantic.clone(),
662        generator: Some(winner.generator.clone()),
663        modifiers,
664    };
665
666    (rule, decision, winner.source_literals)
667}
668
669/// Infer one column's generator from its schema alone — declared name and type,
670/// with no value evidence — reusing the same schema, credential, and semantic
671/// heuristics (and their precedence) the profiler applies at schema depth. The
672/// `distribution` heuristics need value evidence and contribute nothing here.
673/// A generator is always returned: the type fallback is the guaranteed floor, so
674/// a caller relying on this never leaves a column unowned.
675pub fn schema_inferred_generator(
676    table: &PortableTable,
677    column: &PortableColumn,
678) -> GeneratorConfig {
679    let ctx = ColumnContext {
680        table,
681        column,
682        evidence: None,
683        row_count: None,
684    };
685    let mut candidates = Vec::new();
686    candidates.extend(schema::candidates(&ctx));
687    candidates.extend(credential::candidates(&ctx));
688    candidates.extend(semantic::candidates(&ctx));
689    let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
690    rule.generator
691        .expect("resolve_column always assigns a generator")
692}
693
694/// A `null_rate` modifier replaying an observed null fraction on a nullable
695/// column, unless the winning rule already produces `NULL`/`DEFAULT` itself.
696fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
697    if !ctx.column().nullable {
698        return None;
699    }
700    if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
701        return None;
702    }
703    let rate = ctx.evidence()?.null_rate;
704    if !(0.005..=0.995).contains(&rate) {
705        return None;
706    }
707    let mut args = BTreeMap::new();
708    args.insert("rate".to_string(), yaml(round4(rate)));
709    Some(ModifierConfig {
710        kind: "null_rate".to_string(),
711        args,
712    })
713}
714
715/// Build the removable evidence summary for one column (bounded, non-literal).
716fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
717    let evidence = ctx.evidence()?;
718    Some(ProfileMetadata {
719        rows: ctx.row_count().unwrap_or(evidence.total_count),
720        null_fraction: round4(evidence.null_rate),
721        distinct_estimate: evidence.distinct_estimate.round() as u64,
722        inference: Some(ProfileInference {
723            selected: decision.generator_kind.clone(),
724            confidence: decision.confidence.label().to_string(),
725            reasons: vec![decision.reason.clone()],
726        }),
727    })
728}
729
730/// Declared foreign keys become explicit model relationships so the output
731/// stands alone.
732/// Whether a resolved generator kind draws from a bounded or categorical domain
733/// (so it cannot supply a distinct value per row on a large unique column).
734fn is_bounded_generator(kind: &str) -> bool {
735    matches!(
736        kind,
737        "observed_sample"
738            | "choice"
739            | "weighted_choice"
740            | "histogram"
741            | "normal"
742            | "integer"
743            | "decimal"
744            | "boolean"
745            | "constant"
746            | "null"
747            | "database_default"
748    )
749}
750
751/// A high-cardinality generator (kind + args) for a unique `column` whose
752/// inferred generator was bounded: a `sequence` for an integer, a `uuid` for
753/// text. `None` for families with no obvious high-cardinality synthetic key.
754fn high_cardinality_generator(
755    column: &PortableColumn,
756) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
757    match column.family {
758        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
759            "sequence".to_string(),
760            [("start".to_string(), yaml(1))].into_iter().collect(),
761        )),
762        SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
763            Some(("uuid".to_string(), BTreeMap::new()))
764        }
765        _ => None,
766    }
767}
768
769/// Whether `column` is a single-column unique key of `table`: its own `unique`
770/// flag, a single-column UNIQUE constraint, or a single-column unique index.
771/// Mirrors the compiler's single-column-key test so inference and generation
772/// agree on which columns must stay distinct.
773fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
774    if column.unique {
775        return true;
776    }
777    let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
778    table
779        .unique_constraints
780        .iter()
781        .any(|constraint| single(&constraint.columns))
782        || table
783            .indexes
784            .iter()
785            .any(|index| index.unique && single(&index.columns))
786}
787
788/// The single-column declared foreign key whose one column is `column`, if any.
789/// A composite (multi-column) foreign key does not qualify.
790fn single_column_fk<'a>(
791    table: &'a PortableTable,
792    column: &str,
793) -> Option<&'a PortableRelationship> {
794    table
795        .relationships
796        .iter()
797        .find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
798}
799
800/// Infer the planners a pivot table needs so its composite primary key holds by
801/// construction. A composite primary key that contains at least two
802/// single-column foreign keys is a many-to-many junction: emit a
803/// `relation.junction_pair` planner over the first two such foreign-key columns.
804/// Distinct `(left, right)` pairs make the whole composite key distinct, even
805/// when the primary key also carries a discriminator or extra column (the
806/// polymorphic pivot shape). This is a purely structural match — it keys off the
807/// primary-key shape and its foreign keys, not any table or column name — so it
808/// covers any junction table, Laravel or otherwise. A composite key with fewer
809/// than two foreign-key columns is left to other mechanisms.
810fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
811    let pk = &table.primary_key;
812    if pk.len() < 2 {
813        return Vec::new();
814    }
815    // The primary-key columns that are single-column foreign keys, in PK order.
816    let fk_columns: Vec<(&String, &PortableRelationship)> = pk
817        .iter()
818        .filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
819        .collect();
820    if fk_columns.len() < 2 {
821        return Vec::new();
822    }
823    let (left_col, left) = fk_columns[0];
824    let (right_col, right) = fk_columns[1];
825    let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
826        return Vec::new();
827    };
828
829    let mut columns = serde_yaml_ng::Mapping::new();
830    columns.insert(yaml("left"), yaml(left_col));
831    columns.insert(yaml("right"), yaml(right_col));
832    let mut args = BTreeMap::new();
833    args.insert(
834        "columns".to_string(),
835        serde_yaml_ng::Value::Mapping(columns),
836    );
837    args.insert("left_relationship".to_string(), yaml(left_name));
838    args.insert("right_relationship".to_string(), yaml(right_name));
839
840    vec![PlannerConfig {
841        kind: "relation.junction_pair".to_string(),
842        args,
843    }]
844}
845
846/// For a composite-primary-key table that is *not* a two-FK junction, the name
847/// of a non-foreign-key integer primary-key column to sequence so the composite
848/// key stays distinct by construction (its per-row-unique values alone make
849/// every tuple distinct). This is the fallback for polymorphic pivots whose PK
850/// mixes a single foreign key, a discriminator, and a plain integer id (e.g.
851/// `model_has_roles`). Returns `None` when the PK is not composite or has no
852/// such column, leaving the composite key to fail its own verification loudly.
853fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
854    if table.primary_key.len() < 2 {
855        return None;
856    }
857    table.primary_key.iter().find_map(|column| {
858        let is_integer = table.columns.iter().any(|c| {
859            &c.name == column
860                && matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
861        });
862        (is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
863    })
864}
865
866fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
867    table
868        .relationships
869        .iter()
870        .map(|fk| RelationshipModel {
871            name: fk.name.clone(),
872            columns: fk.columns.clone(),
873            references: RelationshipReference {
874                table: fk.referenced_table.clone(),
875                columns: fk.referenced_columns.clone(),
876            },
877            distribution: None,
878        })
879        .collect()
880}
881
882fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
883    table.columns.iter().find(|c| c.name == name)
884}
885
886// --- Shared candidate-building helpers (used by the submodules) --------------
887
888/// Serialize a value into a YAML scalar/sequence for a generator argument.
889pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
890    serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
891}
892
893/// A generator config with no arguments.
894pub(crate) fn generator(kind: &str) -> GeneratorConfig {
895    GeneratorConfig {
896        kind: kind.to_string(),
897        args: BTreeMap::new(),
898    }
899}
900
901/// A generator config with the given `(key, value)` arguments.
902pub(crate) fn generator_with(
903    kind: &str,
904    args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
905) -> GeneratorConfig {
906    GeneratorConfig {
907        kind: kind.to_string(),
908        args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
909    }
910}
911
912/// A `[{ value, weight }, ...]` YAML sequence for the weighted generators.
913pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
914    let seq = entries
915        .iter()
916        .map(|(value, weight)| {
917            let mut map = serde_yaml_ng::Mapping::new();
918            map.insert(yaml("value"), yaml(value));
919            map.insert(yaml("weight"), yaml(*weight));
920            serde_yaml_ng::Value::Mapping(map)
921        })
922        .collect();
923    serde_yaml_ng::Value::Sequence(seq)
924}
925
926/// Round a fraction to four decimal places for stable, readable emission.
927fn round4(value: f64) -> f64 {
928    (value * 10_000.0).round() / 10_000.0
929}