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/// Upper bound for `output.batch_size`; compilation rejects zero and larger
183/// values so rendered batches stay allocation-bounded.
184pub const MAX_OUTPUT_BATCH_SIZE: u32 = 1_000_000;
185
186/// Dialect and renderer defaults (`output:` in the complete model example).
187///
188/// A model that omits `output` entirely preserves the source/base dialect
189/// (`dialect: None`); see [`ModelDefaults`] for why this field is
190/// `#[serde(default)]` on [`SyntheticModel`].
191#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
192#[serde(deny_unknown_fields)]
193pub struct OutputModel {
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub dialect: Option<String>,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub mode: Option<OutputMode>,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub inserts: Option<InsertMode>,
200    /// Rows per rendered batch. Compilation accepts `1..=MAX_OUTPUT_BATCH_SIZE`.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    #[schemars(range(min = 1, max = 1000000))]
203    pub batch_size: Option<u32>,
204}
205
206/// Whether rendering emits DDL, rows, or both.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
208#[serde(rename_all = "snake_case")]
209pub enum OutputMode {
210    SchemaAndData,
211    SchemaOnly,
212    DataOnly,
213}
214
215/// How PostgreSQL row output is rendered.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
217#[serde(rename_all = "snake_case")]
218pub enum InsertMode {
219    Auto,
220    Insert,
221    Copy,
222}
223
224/// A single table's complete generation rules.
225#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
226#[serde(deny_unknown_fields)]
227pub struct TableModel {
228    /// Tri-state seed: omitted inherits the model seed, `null` opts out of
229    /// determinism, and an integer pins an independent seed. Schema'd as
230    /// `Option<u64>` (the same shape [`deserialize_table_seed`] reads)
231    /// since [`TableSeed`] itself has no direct YAML representation.
232    #[serde(
233        default,
234        deserialize_with = "deserialize_table_seed",
235        serialize_with = "serialize_table_seed",
236        skip_serializing_if = "TableSeed::is_inherit"
237    )]
238    #[schemars(with = "Option<u64>")]
239    pub seed: TableSeed,
240    pub rows: RowsModel,
241    pub schema: PortableTable,
242    #[serde(default)]
243    pub columns: BTreeMap<String, ColumnRule>,
244    #[serde(default)]
245    pub relationships: Vec<RelationshipModel>,
246    #[serde(default)]
247    pub planners: Vec<PlannerConfig>,
248}
249
250/// A table's seed relative to the model's top-level seed: inherit it,
251/// opt out of determinism entirely, or pin an independent seed.
252///
253/// YAML semantics: omitted means [`TableSeed::Inherit`], `null` means
254/// [`TableSeed::Random`], and an integer means [`TableSeed::Fixed`].
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
256pub enum TableSeed {
257    #[default]
258    Inherit,
259    Random,
260    Fixed(u64),
261}
262
263impl TableSeed {
264    /// Used by `skip_serializing_if` to omit the field for the common case.
265    pub fn is_inherit(&self) -> bool {
266        matches!(self, TableSeed::Inherit)
267    }
268}
269
270/// Deserialize the tri-state seed shared by `TableModel::seed`: absent
271/// (handled by `#[serde(default)]`) is `Inherit`, `null` is `Random`, and an
272/// integer is `Fixed`.
273pub(super) fn deserialize_table_seed<'de, D>(deserializer: D) -> Result<TableSeed, D::Error>
274where
275    D: Deserializer<'de>,
276{
277    Ok(match Option::<u64>::deserialize(deserializer)? {
278        None => TableSeed::Random,
279        Some(seed) => TableSeed::Fixed(seed),
280    })
281}
282
283pub(super) fn serialize_table_seed<S>(seed: &TableSeed, serializer: S) -> Result<S::Ok, S::Error>
284where
285    S: Serializer,
286{
287    match seed {
288        TableSeed::Inherit => serializer.serialize_none(),
289        TableSeed::Random => serializer.serialize_none(),
290        TableSeed::Fixed(value) => serializer.serialize_u64(*value),
291    }
292}
293
294/// How many rows a table produces, and how those rows are derived.
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
296#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
297pub enum RowsModel {
298    Fixed {
299        count: u64,
300    },
301    Observed {
302        count: u64,
303    },
304    Scale {
305        base: u64,
306        factor: f64,
307        count: u64,
308    },
309    #[serde(rename = "relation.children")]
310    RelationChildren {
311        parent: String,
312        count: u64,
313        distribution: ChildDistribution,
314    },
315}
316
317/// The fan-out distribution used to allocate a relationship child's rows
318/// across its parents.
319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
320#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
321pub enum ChildDistribution {
322    Observed { mean: f64, min: f64, max: f64 },
323    Fixed { mean: f64, min: f64, max: f64 },
324    Uniform { mean: f64, min: f64, max: f64 },
325    Poisson { mean: f64, min: f64, max: f64 },
326    Histogram { mean: f64, min: f64, max: f64 },
327}
328
329/// A single column's generation rule: an optional semantic annotation, an
330/// optional generator owner, and an ordered modifier pipeline.
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
332#[serde(deny_unknown_fields)]
333pub struct ColumnRule {
334    #[serde(default, skip_serializing_if = "Option::is_none")]
335    pub semantic: Option<String>,
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub generator: Option<GeneratorConfig>,
338    #[serde(default, skip_serializing_if = "Vec::is_empty")]
339    pub modifiers: Vec<ModifierConfig>,
340}
341
342/// A registry-resolved generator invocation. `kind` selects the registered
343/// generator; the remaining fields are its typed arguments, opaque to the
344/// document model and resolved later by `ExtensionRegistry`.
345#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
346pub struct GeneratorConfig {
347    pub kind: String,
348    /// Registry-owned arguments, opaque to the document model.
349    /// Schema'd permissively as an arbitrary JSON object here;
350    /// `json_schema::generate_config_schema` replaces this
351    /// definition with a `oneOf` composed from the standard
352    /// registry's descriptors (see that function's doc comment).
353    #[serde(flatten)]
354    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
355    pub args: BTreeMap<String, serde_yaml_ng::Value>,
356}
357
358/// A registry-resolved modifier invocation; see [`GeneratorConfig`].
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
360pub struct ModifierConfig {
361    pub kind: String,
362    /// Registry-owned arguments, opaque to the document model.
363    /// Schema'd permissively as an arbitrary JSON object here;
364    /// `json_schema::generate_config_schema` replaces this
365    /// definition with a `oneOf` composed from the standard
366    /// registry's descriptors (see that function's doc comment).
367    #[serde(flatten)]
368    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
369    pub args: BTreeMap<String, serde_yaml_ng::Value>,
370}
371
372/// A registry-resolved planner invocation; see [`GeneratorConfig`].
373#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
374pub struct PlannerConfig {
375    pub kind: String,
376    /// Registry-owned arguments, opaque to the document model.
377    /// Schema'd permissively as an arbitrary JSON object here;
378    /// `json_schema::generate_config_schema` replaces this
379    /// definition with a `oneOf` composed from the standard
380    /// registry's descriptors (see that function's doc comment).
381    #[serde(flatten)]
382    #[schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")]
383    pub args: BTreeMap<String, serde_yaml_ng::Value>,
384}
385
386/// A declared generation relationship to another table.
387///
388/// This covers the common named foreign-key shape used throughout the
389/// complete model example. Self-referential, polymorphic, and shaped
390/// (tree/junction) relationships are a documented follow-up; see the
391/// task report for why they are out of scope here.
392#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
393#[serde(deny_unknown_fields)]
394pub struct RelationshipModel {
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub name: Option<String>,
397    pub columns: Vec<String>,
398    pub references: RelationshipReference,
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub distribution: Option<String>,
401}
402
403/// The `references:` half of a [`RelationshipModel`].
404#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
405#[serde(deny_unknown_fields)]
406pub struct RelationshipReference {
407    pub table: String,
408    pub columns: Vec<String>,
409}
410
411/// Removable evidence recorded for one profiled column
412/// (`profiles."table.column"` in the complete model example). Deleting a
413/// model's `profiles` map cannot change generation.
414#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
415#[serde(deny_unknown_fields)]
416pub struct ProfileMetadata {
417    pub rows: u64,
418    pub null_fraction: f64,
419    pub distinct_estimate: u64,
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub inference: Option<ProfileInference>,
422}
423
424/// The inference explanation attached to a [`ProfileMetadata`] entry.
425#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
426#[serde(deny_unknown_fields)]
427pub struct ProfileInference {
428    pub selected: String,
429    pub confidence: String,
430    #[serde(default)]
431    pub reasons: Vec<String>,
432}
433
434/// One place a resolved model's rules persist literal values that originated in
435/// the source dump. Carries only the *location* and the *rule kind* — never the
436/// values themselves — so it is always safe to surface in a report.
437#[derive(Debug, Clone, PartialEq, Eq)]
438pub struct SourceValueUse {
439    /// Path to the rule, e.g. `tables.users.columns.status`.
440    pub path: String,
441    /// The rule kind that carries the literal(s): a generator kind such as
442    /// `weighted_choice`/`constant`/`observed_sample`, or the synthetic kinds
443    /// `source_default`/`check_constraint`.
444    pub rule_kind: String,
445}
446
447impl SyntheticModel {
448    /// Generator kinds that persist literal values drawn from the source dump.
449    /// A rule using one of these replays real observed values, so it must raise
450    /// the conservative source-derived safety notice.
451    pub const SOURCE_LITERAL_GENERATORS: &'static [&'static str] =
452        &["constant", "weighted_choice", "observed_sample"];
453
454    /// Scan every explicit and inferred rule for source-derived literal uses.
455    ///
456    /// This never returns the literal values themselves — only where they live
457    /// and what kind of rule carries them — so the result is safe to print or
458    /// serialize into a JSON report. Categorical/constant/observed-sample
459    /// generators, source `DEFAULT`s a column defers to, and verbatim CHECK
460    /// constraints all count.
461    pub fn source_value_uses(&self) -> Vec<SourceValueUse> {
462        let mut uses = Vec::new();
463        for (table_name, table) in &self.tables {
464            for (column_name, rule) in &table.columns {
465                let Some(generator) = &rule.generator else {
466                    continue;
467                };
468                let path = format!("tables.{table_name}.columns.{column_name}");
469                if Self::SOURCE_LITERAL_GENERATORS.contains(&generator.kind.as_str()) {
470                    uses.push(SourceValueUse {
471                        path,
472                        rule_kind: generator.kind.clone(),
473                    });
474                } else if generator.kind == "database_default"
475                    && column_has_source_default(table, column_name)
476                {
477                    uses.push(SourceValueUse {
478                        path,
479                        rule_kind: "source_default".to_string(),
480                    });
481                }
482            }
483            if !table.schema.check_constraints.is_empty() {
484                uses.push(SourceValueUse {
485                    path: format!("tables.{table_name}.schema.check_constraints"),
486                    rule_kind: "check_constraint".to_string(),
487                });
488            }
489        }
490        uses
491    }
492
493    /// Rewrite each table's `rows` count to the resolved value from a compiled
494    /// plan. Already-authoritative `fixed`/`observed` counts keep their kind;
495    /// derived `scale`/`relation.children` policies become `fixed` so a reload
496    /// cannot derive a different count, except for named relation children whose
497    /// distribution is still consumed by a cross-table family planner.
498    ///
499    /// An `observed` table stays `kind: observed` with a frozen integer count,
500    /// which is what `--emit-config` needs for a self-contained model that
501    /// reproduces the same row counts on reload without re-passing volume
502    /// flags. Tables absent from `resolved` are left untouched.
503    pub fn freeze_row_counts(
504        &mut self,
505        resolved: &BTreeMap<String, u64>,
506        family_children: &HashSet<String>,
507    ) {
508        for (name, table) in &mut self.tables {
509            let Some(&count) = resolved.get(name) else {
510                continue;
511            };
512            match &mut table.rows {
513                RowsModel::Fixed { count: current } | RowsModel::Observed { count: current } => {
514                    *current = count;
515                }
516                RowsModel::RelationChildren { count: current, .. }
517                    if family_children.contains(name) =>
518                {
519                    *current = count;
520                }
521                RowsModel::Scale { .. } | RowsModel::RelationChildren { .. } => {
522                    table.rows = RowsModel::Fixed { count };
523                }
524            }
525        }
526    }
527}
528
529/// Whether `column` in `table` has a source `DEFAULT` recorded on its schema.
530fn column_has_source_default(table: &TableModel, column: &str) -> bool {
531    table
532        .schema
533        .columns
534        .iter()
535        .any(|c| c.name == column && c.default_sql.is_some())
536}