Skip to main content

sql_splitter/synthetic/
model.rs

1//! The `kind: model` YAML document: a self-contained synthetic data model.
2//!
3//! A [`SyntheticModel`] carries a complete normalized schema, an exact row
4//! count for every table, and every generation rule needed to produce data
5//! without its source dump. [`SyntheticFile`] is the entry point: it reads
6//! the `version`/`kind` envelope first, then deserializes into the
7//! role-specific, unknown-field-safe struct for that role.
8
9use std::collections::{BTreeMap, HashSet};
10use std::path::PathBuf;
11
12use schemars::JsonSchema;
13use serde::de::Error as SerdeDeError;
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16use super::overrides::SyntheticOverrides;
17use super::schema::PortableTable;
18
19/// The schema version this crate understands. `SyntheticFile::parse_str`
20/// rejects any other value so a future breaking change can add an upgrader
21/// rather than silently misreading old documents.
22const SUPPORTED_VERSION: u32 = 1;
23
24/// A parsed YAML document, tagged by its declared `kind`.
25///
26/// `parse_str` peeks the `version`/`kind` envelope before committing to a
27/// role-specific `#[serde(deny_unknown_fields)]` struct, so a typo in
28/// `kind` produces a clear role error instead of a confusing field error.
29#[derive(Debug, Clone)]
30pub enum SyntheticFile {
31    Model(SyntheticModel),
32    Overrides(SyntheticOverrides),
33}
34
35/// Minimal envelope used only to determine `version` and `kind` before
36/// picking which role-specific struct to deserialize into. Unknown fields
37/// are intentionally allowed here; the role-specific struct enforces them.
38#[derive(Debug, Deserialize)]
39struct DocumentEnvelope {
40    version: u32,
41    kind: String,
42}
43
44impl SyntheticFile {
45    /// Parse a YAML document, validating its `version`/`kind` envelope
46    /// before deserializing into the matching role-specific struct.
47    ///
48    /// `serde_yaml_ng` rejects duplicate mapping keys while parsing into
49    /// [`serde_yaml_ng::Value`], so that check happens for free here.
50    pub fn parse_str(input: &str) -> anyhow::Result<Self> {
51        let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input)?;
52        Self::parse_value(value)
53    }
54
55    /// Parse an already-constructed YAML [`serde_yaml_ng::Value`], such as
56    /// one produced by merging a root document with its resolved local
57    /// imports (see [`crate::synthetic::config::ConfigLoader`]).
58    ///
59    /// Validates the same `version`/`kind` envelope as [`Self::parse_str`];
60    /// the only difference is that parsing from text is skipped because
61    /// the caller already has a `Value`.
62    pub fn parse_value(value: serde_yaml_ng::Value) -> anyhow::Result<Self> {
63        let envelope: DocumentEnvelope = serde_yaml_ng::from_value(value.clone())?;
64
65        if envelope.version != SUPPORTED_VERSION {
66            return Err(serde_yaml_ng::Error::custom(format!(
67                "unsupported version: {} (expected {SUPPORTED_VERSION})",
68                envelope.version
69            ))
70            .into());
71        }
72
73        match envelope.kind.as_str() {
74            "model" => Ok(SyntheticFile::Model(serde_yaml_ng::from_value(value)?)),
75            "overrides" => Ok(SyntheticFile::Overrides(serde_yaml_ng::from_value(value)?)),
76            other => Err(serde_yaml_ng::Error::custom(format!(
77                "unknown document kind: {other} (expected `model` or `overrides`)"
78            ))
79            .into()),
80        }
81    }
82
83    /// Consume this document as a `model`, or error if it is `overrides`.
84    pub fn into_model(self) -> anyhow::Result<SyntheticModel> {
85        match self {
86            SyntheticFile::Model(model) => Ok(model),
87            SyntheticFile::Overrides(_) => Err(anyhow::anyhow!(
88                "expected a `kind: model` document, found `kind: overrides`"
89            )),
90        }
91    }
92
93    /// Consume this document as `overrides`, or error if it is a `model`.
94    pub fn into_overrides(self) -> anyhow::Result<SyntheticOverrides> {
95        match self {
96            SyntheticFile::Overrides(overrides) => Ok(overrides),
97            SyntheticFile::Model(_) => Err(anyhow::anyhow!(
98                "expected a `kind: overrides` document, found `kind: model`"
99            )),
100        }
101    }
102}
103
104/// Marker type accepting only the literal `kind: model` tag.
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
106#[serde(rename_all = "snake_case")]
107pub enum ModelKind {
108    Model,
109}
110
111/// A complete, self-contained synthetic data model.
112#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
113#[serde(deny_unknown_fields)]
114pub struct SyntheticModel {
115    /// Editor-only schema pointer (e.g. `# yaml-language-server: $schema=...`
116    /// promoted into the document body, or a literal `$schema:` key). Purely
117    /// documentation metadata: recognized so an editor-annotated document
118    /// doesn't trip `deny_unknown_fields`, never read by the parser.
119    #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")]
120    pub schema_ref: Option<String>,
121    pub version: u32,
122    pub kind: ModelKind,
123    #[serde(default)]
124    pub imports: Vec<PathBuf>,
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub source: Option<SourceModel>,
127    #[serde(default)]
128    pub defaults: ModelDefaults,
129    #[serde(default)]
130    pub seed: Option<u64>,
131    #[serde(default)]
132    pub output: OutputModel,
133    pub tables: BTreeMap<String, TableModel>,
134    #[serde(default)]
135    pub profiles: BTreeMap<String, ProfileMetadata>,
136}
137
138/// Provenance and fingerprint policy for the source dump a model was
139/// derived from (`source:` in the complete model example).
140#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
141#[serde(deny_unknown_fields)]
142pub struct SourceModel {
143    pub dialect: String,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub fingerprint: Option<String>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub fingerprint_policy: Option<FingerprintPolicy>,
148}
149
150/// How strictly a model requires the source fingerprint to match.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
152#[serde(rename_all = "snake_case")]
153pub enum FingerprintPolicy {
154    Ignore,
155    Warn,
156    Require,
157}
158
159/// Inherited table/column behavior defaults.
160///
161/// Both `output` and `defaults` are spec-optional on a `kind: model`
162/// document (see the "Top-level fields" table); a model that omits
163/// `defaults` gets [`InferenceMode::Disabled`], matching what
164/// `--emit-config` always writes explicitly.
165#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
166#[serde(deny_unknown_fields)]
167pub struct ModelDefaults {
168    #[serde(default)]
169    pub inference: InferenceMode,
170}
171
172/// Whether columns without an explicit owner may fall back to schema-based
173/// heuristics, or must always be explicit.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
175#[serde(rename_all = "snake_case")]
176pub enum InferenceMode {
177    Schema,
178    #[default]
179    Disabled,
180}
181
182/// Dialect and renderer defaults (`output:` in the complete model example).
183///
184/// A model that omits `output` entirely preserves the source/base dialect
185/// (`dialect: None`); see [`ModelDefaults`] for why this field is
186/// `#[serde(default)]` on [`SyntheticModel`].
187#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
188#[serde(deny_unknown_fields)]
189pub struct OutputModel {
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub dialect: Option<String>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub mode: Option<OutputMode>,
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub inserts: Option<InsertMode>,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub batch_size: Option<u32>,
198}
199
200/// Whether rendering emits DDL, rows, or both.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
202#[serde(rename_all = "snake_case")]
203pub enum OutputMode {
204    SchemaAndData,
205    SchemaOnly,
206    DataOnly,
207}
208
209/// How PostgreSQL row output is rendered.
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
211#[serde(rename_all = "snake_case")]
212pub enum InsertMode {
213    Auto,
214    Insert,
215    Copy,
216}
217
218/// A single table's complete generation rules.
219#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
220#[serde(deny_unknown_fields)]
221pub struct TableModel {
222    /// Tri-state seed: omitted inherits the model seed, `null` opts out of
223    /// determinism, and an integer pins an independent seed. Schema'd as
224    /// `Option<u64>` (the same shape [`deserialize_table_seed`] reads)
225    /// since [`TableSeed`] itself has no direct YAML representation.
226    #[serde(
227        default,
228        deserialize_with = "deserialize_table_seed",
229        serialize_with = "serialize_table_seed",
230        skip_serializing_if = "TableSeed::is_inherit"
231    )]
232    #[schemars(with = "Option<u64>")]
233    pub seed: TableSeed,
234    pub rows: RowsModel,
235    pub schema: PortableTable,
236    #[serde(default)]
237    pub columns: BTreeMap<String, ColumnRule>,
238    #[serde(default)]
239    pub relationships: Vec<RelationshipModel>,
240    #[serde(default)]
241    pub planners: Vec<PlannerConfig>,
242}
243
244/// A table's seed relative to the model's top-level seed: inherit it,
245/// opt out of determinism entirely, or pin an independent seed.
246///
247/// YAML semantics: omitted means [`TableSeed::Inherit`], `null` means
248/// [`TableSeed::Random`], and an integer means [`TableSeed::Fixed`].
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
250pub enum TableSeed {
251    #[default]
252    Inherit,
253    Random,
254    Fixed(u64),
255}
256
257impl TableSeed {
258    /// Used by `skip_serializing_if` to omit the field for the common case.
259    pub fn is_inherit(&self) -> bool {
260        matches!(self, TableSeed::Inherit)
261    }
262}
263
264/// Deserialize the tri-state seed shared by `TableModel::seed`: absent
265/// (handled by `#[serde(default)]`) is `Inherit`, `null` is `Random`, and an
266/// integer is `Fixed`.
267pub(super) fn deserialize_table_seed<'de, D>(deserializer: D) -> Result<TableSeed, D::Error>
268where
269    D: Deserializer<'de>,
270{
271    Ok(match Option::<u64>::deserialize(deserializer)? {
272        None => TableSeed::Random,
273        Some(seed) => TableSeed::Fixed(seed),
274    })
275}
276
277pub(super) fn serialize_table_seed<S>(seed: &TableSeed, serializer: S) -> Result<S::Ok, S::Error>
278where
279    S: Serializer,
280{
281    match seed {
282        TableSeed::Inherit => serializer.serialize_none(),
283        TableSeed::Random => serializer.serialize_none(),
284        TableSeed::Fixed(value) => serializer.serialize_u64(*value),
285    }
286}
287
288/// How many rows a table produces, and how those rows are derived.
289#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
290#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
291pub enum RowsModel {
292    Fixed {
293        count: u64,
294    },
295    Observed {
296        count: u64,
297    },
298    Scale {
299        base: u64,
300        factor: f64,
301        count: u64,
302    },
303    #[serde(rename = "relation.children")]
304    RelationChildren {
305        parent: String,
306        count: u64,
307        distribution: ChildDistribution,
308    },
309}
310
311/// The fan-out distribution used to allocate a relationship child's rows
312/// across its parents.
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
314#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
315pub enum ChildDistribution {
316    Observed { mean: f64, min: f64, max: f64 },
317    Fixed { mean: f64, min: f64, max: f64 },
318    Uniform { mean: f64, min: f64, max: f64 },
319    Poisson { mean: f64, min: f64, max: f64 },
320    Histogram { mean: f64, min: f64, max: f64 },
321}
322
323/// A single column's generation rule: an optional semantic annotation, an
324/// optional generator owner, and an ordered modifier pipeline.
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
326#[serde(deny_unknown_fields)]
327pub struct ColumnRule {
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub semantic: Option<String>,
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub generator: Option<GeneratorConfig>,
332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
333    pub modifiers: Vec<ModifierConfig>,
334}
335
336/// A registry-resolved generator invocation. `kind` selects the registered
337/// generator; the remaining fields are its typed arguments, opaque to the
338/// document model and resolved later by `ExtensionRegistry`.
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
340pub struct GeneratorConfig {
341    pub kind: String,
342    /// Registry-owned arguments, opaque to the document model.
343    /// Schema'd permissively as an arbitrary JSON object here;
344    /// `json_schema::generate_config_schema` replaces this
345    /// definition with a `oneOf` composed from the standard
346    /// registry's descriptors (see that function's doc comment).
347    #[serde(flatten)]
348    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
349    pub args: BTreeMap<String, serde_yaml_ng::Value>,
350}
351
352/// A registry-resolved modifier invocation; see [`GeneratorConfig`].
353#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
354pub struct ModifierConfig {
355    pub kind: String,
356    /// Registry-owned arguments, opaque to the document model.
357    /// Schema'd permissively as an arbitrary JSON object here;
358    /// `json_schema::generate_config_schema` replaces this
359    /// definition with a `oneOf` composed from the standard
360    /// registry's descriptors (see that function's doc comment).
361    #[serde(flatten)]
362    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
363    pub args: BTreeMap<String, serde_yaml_ng::Value>,
364}
365
366/// A registry-resolved planner invocation; see [`GeneratorConfig`].
367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
368pub struct PlannerConfig {
369    pub kind: String,
370    /// Registry-owned arguments, opaque to the document model.
371    /// Schema'd permissively as an arbitrary JSON object here;
372    /// `json_schema::generate_config_schema` replaces this
373    /// definition with a `oneOf` composed from the standard
374    /// registry's descriptors (see that function's doc comment).
375    #[serde(flatten)]
376    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
377    pub args: BTreeMap<String, serde_yaml_ng::Value>,
378}
379
380/// A declared generation relationship to another table.
381///
382/// This covers the common named foreign-key shape used throughout the
383/// complete model example. Self-referential, polymorphic, and shaped
384/// (tree/junction) relationships are a documented follow-up; see the
385/// task report for why they are out of scope here.
386#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
387#[serde(deny_unknown_fields)]
388pub struct RelationshipModel {
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub name: Option<String>,
391    pub columns: Vec<String>,
392    pub references: RelationshipReference,
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub distribution: Option<String>,
395}
396
397/// The `references:` half of a [`RelationshipModel`].
398#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
399#[serde(deny_unknown_fields)]
400pub struct RelationshipReference {
401    pub table: String,
402    pub columns: Vec<String>,
403}
404
405/// Removable evidence recorded for one profiled column
406/// (`profiles."table.column"` in the complete model example). Deleting a
407/// model's `profiles` map cannot change generation.
408#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
409#[serde(deny_unknown_fields)]
410pub struct ProfileMetadata {
411    pub rows: u64,
412    pub null_fraction: f64,
413    pub distinct_estimate: u64,
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub inference: Option<ProfileInference>,
416}
417
418/// The inference explanation attached to a [`ProfileMetadata`] entry.
419#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
420#[serde(deny_unknown_fields)]
421pub struct ProfileInference {
422    pub selected: String,
423    pub confidence: String,
424    #[serde(default)]
425    pub reasons: Vec<String>,
426}
427
428/// One place a resolved model's rules persist literal values that originated in
429/// the source dump. Carries only the *location* and the *rule kind* — never the
430/// values themselves — so it is always safe to surface in a report.
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct SourceValueUse {
433    /// Path to the rule, e.g. `tables.users.columns.status`.
434    pub path: String,
435    /// The rule kind that carries the literal(s): a generator kind such as
436    /// `weighted_choice`/`constant`/`observed_sample`, or the synthetic kinds
437    /// `source_default`/`check_constraint`.
438    pub rule_kind: String,
439}
440
441impl SyntheticModel {
442    /// Generator kinds that persist literal values drawn from the source dump.
443    /// A rule using one of these replays real observed values, so it must raise
444    /// the conservative source-derived safety notice.
445    pub const SOURCE_LITERAL_GENERATORS: &'static [&'static str] =
446        &["constant", "weighted_choice", "observed_sample"];
447
448    /// Scan every explicit and inferred rule for source-derived literal uses.
449    ///
450    /// This never returns the literal values themselves — only where they live
451    /// and what kind of rule carries them — so the result is safe to print or
452    /// serialize into a JSON report. Categorical/constant/observed-sample
453    /// generators, source `DEFAULT`s a column defers to, and verbatim CHECK
454    /// constraints all count.
455    pub fn source_value_uses(&self) -> Vec<SourceValueUse> {
456        let mut uses = Vec::new();
457        for (table_name, table) in &self.tables {
458            for (column_name, rule) in &table.columns {
459                let Some(generator) = &rule.generator else {
460                    continue;
461                };
462                let path = format!("tables.{table_name}.columns.{column_name}");
463                if Self::SOURCE_LITERAL_GENERATORS.contains(&generator.kind.as_str()) {
464                    uses.push(SourceValueUse {
465                        path,
466                        rule_kind: generator.kind.clone(),
467                    });
468                } else if generator.kind == "database_default"
469                    && column_has_source_default(table, column_name)
470                {
471                    uses.push(SourceValueUse {
472                        path,
473                        rule_kind: "source_default".to_string(),
474                    });
475                }
476            }
477            if !table.schema.check_constraints.is_empty() {
478                uses.push(SourceValueUse {
479                    path: format!("tables.{table_name}.schema.check_constraints"),
480                    rule_kind: "check_constraint".to_string(),
481                });
482            }
483        }
484        uses
485    }
486
487    /// Rewrite each table's `rows` count to the resolved value from a compiled
488    /// plan. Already-authoritative `fixed`/`observed` counts keep their kind;
489    /// derived `scale`/`relation.children` policies become `fixed` so a reload
490    /// cannot derive a different count, except for named relation children whose
491    /// distribution is still consumed by a cross-table family planner.
492    ///
493    /// An `observed` table stays `kind: observed` with a frozen integer count,
494    /// which is what `--emit-config` needs for a self-contained model that
495    /// reproduces the same row counts on reload without re-passing volume
496    /// flags. Tables absent from `resolved` are left untouched.
497    pub fn freeze_row_counts(
498        &mut self,
499        resolved: &BTreeMap<String, u64>,
500        family_children: &HashSet<String>,
501    ) {
502        for (name, table) in &mut self.tables {
503            let Some(&count) = resolved.get(name) else {
504                continue;
505            };
506            match &mut table.rows {
507                RowsModel::Fixed { count: current } | RowsModel::Observed { count: current } => {
508                    *current = count;
509                }
510                RowsModel::RelationChildren { count: current, .. }
511                    if family_children.contains(name) =>
512                {
513                    *current = count;
514                }
515                RowsModel::Scale { .. } | RowsModel::RelationChildren { .. } => {
516                    table.rows = RowsModel::Fixed { count };
517                }
518            }
519        }
520    }
521}
522
523/// Whether `column` in `table` has a source `DEFAULT` recorded on its schema.
524fn column_has_source_default(table: &TableModel, column: &str) -> bool {
525    table
526        .schema
527        .columns
528        .iter()
529        .any(|c| c.name == column && c.default_sql.is_some())
530}