Skip to main content

sql_splitter/generate/
mod.rs

1//! Synthetic data generation engine.
2//!
3//! This module hosts the pieces generators are built from: stable, seedable
4//! RNG streams ([`seed`]) so a run is fully reproducible from a single root
5//! seed, and a dialect-agnostic value representation ([`value`]) that
6//! generators produce instead of writing SQL literals directly.
7//!
8//! # The public builder
9//!
10//! [`Generate`] is the one-call facade: it loads a `kind: model` document,
11//! compiles it, runs the generation engine, and renders SQL to a file — the
12//! complete pipeline behind a single [`GenerateBuilder`].
13//!
14//! ```
15//! use sql_splitter::generate::Generate;
16//!
17//! # fn main() -> anyhow::Result<()> {
18//! let dir = tempfile::tempdir()?;
19//! let output = dir.path().join("synthetic.sql");
20//!
21//! let report = Generate::builder()
22//!     .config("tests/fixtures/generate/simple.yaml")
23//!     .output(&output)
24//!     .seed(42)
25//!     .run()?;
26//!
27//! assert!(report.rows_written > 0);
28//! assert!(std::fs::read_to_string(&output)?.contains("INSERT INTO"));
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! See `builder_generates_from_a_complete_model` in `tests/generate_api_test.rs`
34//! for more builder-driven workflows (dump profiling, `--check`, `--dry-run`,
35//! `--verify`, table/seed overrides).
36//!
37//! # The staged API
38//!
39//! Callers that need to drive an individual stage directly — a custom
40//! statically linked [`ExtensionRegistry`], mid-pipeline inspection, or a
41//! destination that is not a plain file — can assemble the same four stages
42//! [`Generate`] wires together: an [`ExtensionRegistry`] feeds a
43//! [`ModelCompiler`], which produces a [`GenerationPlan`] that a
44//! [`GenerationEngine`] drives against any [`RowSink`], most commonly a
45//! [`crate::render::SqlRenderer`].
46//!
47//! ```
48//! use sql_splitter::generate::{CompileOptions, ExtensionRegistry, GenerationEngine, ModelCompiler};
49//! use sql_splitter::render::{RenderOptions, SqlRenderer};
50//! use sql_splitter::synthetic::SyntheticFile;
51//!
52//! # fn main() -> anyhow::Result<()> {
53//! let model = SyntheticFile::parse_str(
54//!     r#"
55//! version: 1
56//! kind: model
57//! defaults: { inference: disabled }
58//! seed: 1
59//! tables:
60//!   users:
61//!     rows: { kind: fixed, count: 3 }
62//!     schema:
63//!       name: users
64//!       primary_key: [id]
65//!       columns:
66//!         - { name: id, type: bigint, nullable: false, primary_key: true }
67//!         - { name: name, type: "varchar(50)", nullable: false }
68//!     columns:
69//!       id:
70//!         generator: { kind: sequence, start: 1 }
71//!       name:
72//!         generator: { kind: string, min_length: 3, max_length: 8 }
73//! "#,
74//! )?
75//! .into_model()
76//! .expect("is a complete model");
77//!
78//! let registry = ExtensionRegistry::standard();
79//! let plan = ModelCompiler::new(registry).compile(model, CompileOptions::default())?;
80//!
81//! let mut renderer = SqlRenderer::new(Vec::new(), RenderOptions::default());
82//! GenerationEngine::new(plan).run(&mut renderer)?;
83//! let bytes = renderer.finish()?;
84//!
85//! assert!(String::from_utf8(bytes)?.contains("INSERT INTO"));
86//! # Ok(())
87//! # }
88//! ```
89//!
90//! (Profiling a model from a dump — a `DumpProfiler`/`ModelInference` stage
91//! ahead of the compiler — is wired into [`Generate::run`] itself: pass
92//! [`GenerateBuilder::input`] to profile a dump into a base model, optionally
93//! merging a `kind: overrides` `.config()` on top.)
94//!
95//! See `staged_api_renders_inserts` in `tests/generate_engine_test.rs` for a
96//! worked example of assembling the stages by hand, including a custom
97//! [`ExtensionRegistry`].
98
99pub mod compiler;
100pub mod engine;
101pub mod generators;
102pub mod output;
103pub mod plan;
104pub mod planners;
105pub mod registry;
106pub mod seed;
107pub mod value;
108pub mod verify;
109
110use std::collections::{BTreeMap, HashSet};
111use std::io::{self, Write};
112use std::path::{Path, PathBuf};
113
114use crate::convert::ConvertWarning;
115use crate::diagnostic::{codes, Diagnostic, DiagnosticBag, SourceLocation};
116use crate::parser::SqlDialect;
117use crate::profile::evidence::DumpProfile;
118use crate::profile::{
119    Confidence, Decision, DumpProfiler, ModelInference, Precedence, ProfileBudget, ProfileDepth,
120};
121use crate::synthetic::model::{InferenceMode, InsertMode, OutputMode};
122use crate::synthetic::{ConfigLoader, ModelMerger, SourceValueUse, SyntheticFile};
123
124// Re-exported so the staged API (registry -> compiler -> engine -> renderer)
125// is fully usable from `crate::generate` alone, without also reaching into
126// `crate::render`/`crate::synthetic`.
127pub use crate::render::{RenderOptions, SqlRenderer};
128pub use crate::synthetic::SyntheticModel;
129pub use compiler::{CompileOptions, ModelCompiler, TableCountKind, TableCountOverride};
130pub use engine::{
131    DenseIntegerKey, EngineReport, GeneratedRow, GenerationEngine, KeyDomain,
132    RandomAccessKeyGenerator, RowSink,
133};
134pub use generators::ConstantFactory;
135pub use output::{
136    install_interrupt_handler, publish_in_order, AtomicOutput, CancellationToken, FamilyBudget,
137    FamilyBuffer, FamilyState, PartialPublication, ProtectedSpool, PublicationSet, SpillKind,
138    SpoolReader, SpoolWriter, SpooledRow, TempConfig,
139};
140pub use plan::{
141    ColumnOwner, CompiledOutput, CompiledRelationship, DeferredConstraints, ExecutionPhase,
142    FamilyPhase, GenerationPlan, PlanEstimates, PlannedColumn, PlannedTable,
143    RelationshipDistribution, ResolvedTableSeed,
144};
145pub use registry::{
146    ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledGenerator, CompiledModifier,
147    CompiledPlanner, Determinism, ExtensionRegistry, FamilySumCheck, GeneratorDescriptor,
148    GeneratorFactory, KeyRecipe, ModifierDescriptor, ModifierFactory, PlanContext,
149    PlannerDescriptor, PlannerFactory, PlannerPredicate, PredicateGuard, RowContext, RowView,
150    Verification,
151};
152pub use seed::{derive_seed, SeedRoot, StreamId};
153pub use value::{GenerateError, GeneratedValue};
154pub use verify::{
155    CheckOutcome, CheckStatus, DistributionExpectation, GenerationVerifier, VerificationReport,
156};
157
158/// How a [`Generate::run`] call should treat the compiled model.
159///
160/// `Check`, `DryRun`, and `EmitModel` never write SQL; they exist so a caller
161/// can validate a model, preview its resolved row counts, or serialize the
162/// resolved model without paying for a full render. `--emit-config` is an
163/// orthogonal side output: it fires in *any* mode whose request carries an
164/// emit target, and [`RunMode::EmitModel`] is simply the mode selected when
165/// emitting the resolved model is the sole requested output (no SQL).
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum RunMode {
168    /// Compile and generate a complete run, rendering SQL to `output`.
169    #[default]
170    Generate,
171    /// Parse and compile a complete model; no generation, no SQL output.
172    /// Fails the same way `Generate` would on a structurally invalid model.
173    Check,
174    /// Compile the model and report the resolved plan (its estimated row
175    /// counts) without running generation or writing SQL.
176    DryRun,
177    /// Compile the model and emit the resolved, self-contained model (via the
178    /// request's emit target); no generation, no SQL output.
179    EmitModel,
180}
181
182/// Where a [`Generate::run`] renders its SQL, or whether it renders none.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub enum OutputTarget {
185    /// Publish to this path atomically after generation succeeds. An existing
186    /// file remains untouched if staging, generation, rendering, or flushing
187    /// fails.
188    Path(PathBuf),
189    /// Produce no SQL output (the default under [`RunMode::Check`] and
190    /// [`RunMode::DryRun`] when no output path was given).
191    Discard,
192}
193
194/// Controls for profiling a source dump named by [`GenerateRequest::input`].
195#[derive(Debug, Clone, Default)]
196pub struct SourceOptions {
197    /// Dialect the source dump is written in; auto-detected when `None`.
198    pub dialect: Option<SqlDialect>,
199    /// How deep to profile; the profiler's default (full) when `None`.
200    pub depth: Option<ProfileDepth>,
201    /// Per-column retained sample size; the profiler's default when `None`.
202    pub sample: Option<usize>,
203}
204
205/// One fully-specified generation request: everything [`Generate::run`]
206/// needs, assembled by a [`GenerateBuilder`] (or constructed directly by a
207/// caller that wants to bypass the builder).
208#[derive(Debug, Clone)]
209pub struct GenerateRequest {
210    /// A source dump to profile into a base model.
211    pub input: Option<PathBuf>,
212    /// A `kind: model` or `kind: overrides` YAML document.
213    pub config: Option<PathBuf>,
214    /// Where rendered SQL is written.
215    pub output: OutputTarget,
216    /// Where the resolved, self-contained model is serialized (`--emit-config`),
217    /// or `None` to emit nothing.
218    pub emit: Option<OutputTarget>,
219    /// Row-count and table-selection controls passed to [`ModelCompiler`].
220    pub compile: CompileOptions,
221    /// Dialect and formatting controls passed to [`crate::render::SqlRenderer`].
222    pub render: RenderOptions,
223    /// The explicitly requested output dialect (`--dialect` /
224    /// [`GenerateBuilder::output_dialect`]), or `None` to resolve the dialect
225    /// from the model. Precedence (see `resolve_render_options`): this explicit
226    /// value > the model's `output.dialect` > the model's captured source/input
227    /// dialect (preserve-source) > [`SqlDialect::MySql`]. When the dialect is
228    /// chosen deliberately (here or via the model's `output` block) and differs
229    /// from the model's source, the renderer maps every type across dialects and
230    /// reports lossy conversions; a preserve-source run renders the schema
231    /// verbatim so a model's optional `source:` block stays removable metadata.
232    pub output_dialect: Option<SqlDialect>,
233    /// Whether to fully generate, only validate, only report the plan, or only
234    /// emit the resolved model.
235    pub mode: RunMode,
236    /// Whether to build the `--explain` inference report.
237    pub explain: bool,
238    /// Whether to verify the generated SQL against the compiled plan and publish
239    /// atomically only if the audit passes (`--verify`). Requires a filesystem
240    /// SQL destination under [`RunMode::Generate`].
241    pub verify: bool,
242    /// Treat warnings as fatal and publish no SQL or emitted model when any
243    /// compile-, render-, or verification-stage warning is produced.
244    pub strict: bool,
245    /// How to profile `input`, if given.
246    pub source: SourceOptions,
247}
248
249/// A summary of a completed [`Generate::run`].
250///
251/// Diagnostics collected while loading, merging, and compiling the model
252/// survive here even on success: a `--max-rows` cap or a source-fingerprint
253/// mismatch is a warning, not an error, and a caller still deserves to see
254/// it.
255#[derive(Debug, Clone, Default)]
256pub struct GenerateReport {
257    /// Rows written across every table (`Generate` mode), or the compiled
258    /// plan's estimated total (`DryRun`); always `0` for `Check`/`EmitModel`.
259    pub rows_written: u64,
260    /// The root seed the run actually used. Always `Some` — an unseeded run
261    /// draws a fresh random seed and records it here so the run is reproducible
262    /// after the fact, even though its emitted model records no seed.
263    pub effective_seed: Option<u64>,
264    /// Every diagnostic collected while loading, merging, and compiling the
265    /// model. Non-error diagnostics only on success; see
266    /// [`GenerateError::Diagnostics`]
267    /// for the failure path.
268    pub diagnostics: DiagnosticBag,
269    /// Every place the resolved model's rules replay literal values derived
270    /// from the source dump. Locations and rule kinds only, never values — the
271    /// `GEN-SOURCE-VALUES` advisory is built from this.
272    pub source_values: Vec<SourceValueUse>,
273    /// The per-column inference explanation, populated only when the request
274    /// asked for it (`--explain`). Never carries observed values.
275    pub explain: Vec<ExplainColumn>,
276}
277
278/// One column's inference decision, reshaped for `--explain` reporting. Carries
279/// the winning rule's reason/confidence and the rejected alternatives — never
280/// any observed values.
281#[derive(Debug, Clone)]
282pub struct ExplainColumn {
283    /// `"table.column"`.
284    pub column: String,
285    /// The winning candidate's stable reason code.
286    pub reason: String,
287    /// The winning candidate's confidence label.
288    pub confidence: String,
289    /// The resolved generator kind.
290    pub generator_kind: String,
291    /// Whether the winning rule embeds source-derived literal values.
292    pub source_derived: bool,
293    /// The alternatives that lost, most-relevant first.
294    pub rejected: Vec<ExplainRejected>,
295}
296
297/// One rejected alternative recorded for [`ExplainColumn`].
298#[derive(Debug, Clone)]
299pub struct ExplainRejected {
300    pub generator_kind: String,
301    pub reason: String,
302    pub precedence: String,
303    pub confidence: String,
304}
305
306/// The public generation facade: loads a model, compiles it, and — under
307/// [`RunMode::Generate`] — runs the engine and renders SQL. Build a request
308/// with [`Generate::builder`].
309#[derive(Debug, Clone, Copy)]
310pub struct Generate;
311
312impl Generate {
313    /// A fresh [`GenerateBuilder`] with default options (`RunMode::Generate`,
314    /// [`RenderOptions::default`], no seed/scale/table overrides).
315    pub fn builder() -> GenerateBuilder {
316        GenerateBuilder::default()
317    }
318
319    /// Run one fully-specified request end to end.
320    ///
321    /// Resolves the model — profiling and inferring a base from `request.input`
322    /// when given, then merging a `kind: overrides` `request.config` on top —
323    /// compiles it **exactly once**, optionally serializes the resolved model
324    /// (`request.emit`) from that same plan, and optionally executes the same
325    /// plan under `request.mode`.
326    ///
327    /// Structured problems discovered during loading, compilation, or runtime
328    /// come back as [`GenerateError::Diagnostics`] or
329    /// [`GenerateError::Diagnostic`].
330    pub fn run(request: GenerateRequest) -> Result<GenerateReport, GenerateError> {
331        let GenerateRequest {
332            input,
333            config,
334            output,
335            emit,
336            mut compile,
337            render,
338            output_dialect,
339            mode,
340            explain,
341            verify,
342            strict,
343            source,
344        } = request;
345
346        if mode == RunMode::Generate {
347            if let (OutputTarget::Path(sql), Some(OutputTarget::Path(model))) = (&output, &emit) {
348                let sql_identity = normalized_destination(sql)
349                    .map_err(|error| output_identity_error(sql, error))?;
350                let model_identity = normalized_destination(model)
351                    .map_err(|error| output_identity_error(model, error))?;
352                if sql_identity == model_identity {
353                    return Err(GenerateError::diagnostic(
354                        &codes::REQUEST_OUTPUT,
355                        sql.display().to_string(),
356                        "generated SQL and the resolved model require different destinations",
357                    ));
358                }
359            }
360        }
361
362        let had_source_dump = input.is_some();
363
364        let ResolvedModel {
365            model,
366            mut diagnostics,
367            decisions,
368        } = assemble_model(input.as_deref(), config.as_deref(), &source)?;
369
370        // Resolve the effective seed once so emit and execute share it. An
371        // unseeded run draws a fresh random root (kept reproducible-after-the
372        // -fact via the report) but its emitted model records no seed, so
373        // re-running that model is intentionally fresh again.
374        let explicit_seed = compile.seed.or(model.seed);
375        let effective_seed = explicit_seed.unwrap_or_else(rand::random);
376        compile.seed = Some(effective_seed);
377
378        // Compile EXACTLY once; both emit and execute read this one plan.
379        let plan = ModelCompiler::standard()
380            .compile(model.clone(), compile)
381            .map_err(GenerateError::Diagnostics)?;
382        diagnostics.diagnostics.extend(plan.diagnostics.clone());
383
384        // Fold the compiled model `output:` block into the render settings under
385        // any explicit CLI/builder flags (dialect, mode, inserts, batch size).
386        // The precedence and the "deliberate cross-dialect maps types" rule live
387        // in `resolve_render_options`.
388        let mut render = render;
389        resolve_render_options(&mut render, output_dialect, &plan);
390
391        // Scan the final resolved model (explicit + inferred rules) for
392        // source-derived literals.
393        let source_values = model.source_value_uses();
394        if !source_values.is_empty() {
395            let message = if had_source_dump {
396                format!(
397                    "{} rule(s) replay literal values that may have been derived from the source \
398                     dump; review the listed rules before sharing the output",
399                    source_values.len()
400                )
401            } else {
402                format!(
403                    "{} rule(s) replay hand-authored literal values; the output is synthetic, \
404                     not anonymized source data",
405                    source_values.len()
406                )
407            };
408            let diagnostic = diagnostics.advisory(&codes::SOURCE_VALUES, "tables", message);
409            diagnostic.related = source_values
410                .iter()
411                .map(|used| SourceLocation {
412                    path: used.path.clone(),
413                    description: Some(used.rule_kind.clone()),
414                })
415                .collect();
416        }
417
418        let explain = if explain {
419            build_explain(&decisions)
420        } else {
421            Vec::new()
422        };
423
424        let report = GenerateReport {
425            rows_written: 0,
426            effective_seed: Some(effective_seed),
427            diagnostics,
428            source_values,
429            explain,
430        };
431
432        // Compile/profile warnings are already known, so strict mode can stop
433        // before staging or generating anything. Render and verification
434        // warnings are gated inside their staged paths below, before publish.
435        if strict && has_warnings(&report.diagnostics) {
436            return Err(GenerateError::Diagnostics(report.diagnostics));
437        }
438
439        if verify {
440            let diagnostics = report.diagnostics.clone();
441            let VerifiedRun {
442                rows_written,
443                diagnostics,
444            } = run_verified(
445                &model,
446                plan,
447                diagnostics,
448                VerifiedOptions {
449                    explicit_seed,
450                    output,
451                    emit,
452                    render,
453                    strict,
454                },
455            )?;
456            let out = GenerateReport {
457                rows_written,
458                diagnostics,
459                ..report
460            };
461            return Ok(out);
462        }
463
464        // Serialize and stage the emitted model before generation, but do not
465        // publish it yet. A later staging, generation, rendering, or flush
466        // failure drops this protected temp and leaves every destination at
467        // its previous bytes.
468        let model_output = stage_model(&model, &plan, explicit_seed, emit.as_ref())?;
469
470        match mode {
471            RunMode::Check | RunMode::EmitModel => {
472                publish_model(model_output)?;
473                Ok(report)
474            }
475            RunMode::DryRun => {
476                let rows_written = plan.estimates.total_rows;
477                publish_model(model_output)?;
478                Ok(GenerateReport {
479                    rows_written,
480                    ..report
481                })
482            }
483            RunMode::Generate => {
484                let diagnostics = report.diagnostics.clone();
485                let (engine_report, diagnostics) = run_generate(
486                    GenerationEngine::new(plan),
487                    output,
488                    model_output,
489                    render,
490                    diagnostics,
491                    strict,
492                )?;
493                let out = GenerateReport {
494                    rows_written: engine_report.rows_written,
495                    diagnostics,
496                    ..report
497                };
498                Ok(out)
499            }
500        }
501    }
502}
503
504/// Resolve a requested output to the filesystem identity it would publish to.
505///
506/// Canonicalize the deepest existing parent directory (resolving directory
507/// symlinks and `..`) and append the missing suffix plus filename. The final
508/// filename itself is kept lexical because atomic publication replaces that
509/// directory entry rather than following a final symlink.
510fn normalized_destination(path: &Path) -> io::Result<PathBuf> {
511    let absolute = if path.is_absolute() {
512        path.to_path_buf()
513    } else {
514        std::env::current_dir()?.join(path)
515    };
516    let filename = absolute.file_name().ok_or_else(|| {
517        io::Error::new(
518            io::ErrorKind::InvalidInput,
519            format!("`{}` has no output filename", path.display()),
520        )
521    })?;
522    let mut ancestor = absolute.parent().ok_or_else(|| {
523        io::Error::new(
524            io::ErrorKind::InvalidInput,
525            format!("`{}` has no parent destination", path.display()),
526        )
527    })?;
528    let mut suffix = Vec::new();
529    while !ancestor.try_exists()? {
530        let name = ancestor.file_name().ok_or_else(|| {
531            io::Error::new(
532                io::ErrorKind::InvalidInput,
533                format!("`{}` has no existing filesystem ancestor", path.display()),
534            )
535        })?;
536        suffix.push(name.to_os_string());
537        ancestor = ancestor.parent().ok_or_else(|| {
538            io::Error::new(
539                io::ErrorKind::InvalidInput,
540                format!("`{}` has no parent destination", path.display()),
541            )
542        })?;
543    }
544
545    let mut identity = ancestor.canonicalize()?;
546    for component in suffix.iter().rev() {
547        identity.push(component);
548    }
549    identity.push(filename);
550    Ok(identity)
551}
552
553fn output_identity_error(path: &Path, error: io::Error) -> GenerateError {
554    GenerateError::diagnostic(
555        &codes::REQUEST_OUTPUT,
556        path.display().to_string(),
557        format!(
558            "cannot resolve output destination `{}`: {error}",
559            path.display()
560        ),
561    )
562}
563
564/// The outcome of a successful `--verify` publish: the rows written plus any
565/// capabilities the audit could not evaluate exactly (surfaced as a warning).
566struct VerifiedRun {
567    rows_written: u64,
568    diagnostics: DiagnosticBag,
569}
570
571struct VerifiedOptions {
572    explicit_seed: Option<u64>,
573    output: OutputTarget,
574    emit: Option<OutputTarget>,
575    render: RenderOptions,
576    strict: bool,
577}
578
579/// Render SQL to a protected temp beside the destination, verify it against the
580/// compiled plan, and publish atomically only if the full audit passes. A failed
581/// audit leaves every prior destination untouched and returns
582/// [`GenerateError::Diagnostic`] with `GEN-VERIFY-FAILED`. When a resolved model is also requested
583/// it is published *after* SQL verification succeeds; a failure publishing the
584/// second file is reported as a precise partial publication rather than as a
585/// pretended pairwise-atomic write.
586fn run_verified(
587    model: &SyntheticModel,
588    plan: GenerationPlan,
589    mut diagnostics: DiagnosticBag,
590    options: VerifiedOptions,
591) -> Result<VerifiedRun, GenerateError> {
592    let VerifiedOptions {
593        explicit_seed,
594        output,
595        emit,
596        render,
597        strict,
598    } = options;
599    let destination = match output {
600        OutputTarget::Path(path) => path,
601        OutputTarget::Discard => {
602            return Err(GenerateError::diagnostic(
603                &codes::VERIFY_NO_FILE,
604                "output",
605                "--verify requires a filesystem SQL destination, not stdout",
606            ))
607        }
608    };
609
610    // Stage the resolved model YAML up front so a serialization error fails
611    // before anything is rendered.
612    let emit_plan = match &emit {
613        Some(OutputTarget::Path(path)) => Some((
614            path.clone(),
615            resolved_model_yaml(model, &plan, explicit_seed)?,
616        )),
617        _ => None,
618    };
619
620    let verifier = verify::GenerationVerifier::new(&plan)
621        .dialect(render.dialect)
622        .output_mode(render.mode);
623
624    // Render SQL into a protected temp file beside the destination.
625    let mut sql_output = AtomicOutput::create(&destination).map_err(|error| {
626        GenerateError::diagnostic(
627            &codes::VERIFY_STAGE,
628            destination.display().to_string(),
629            format!(
630                "cannot stage output beside `{}`: {error}",
631                destination.display()
632            ),
633        )
634    })?;
635    let temp_path = sql_output.temp_path().to_path_buf();
636    let (rows_written, render_warnings) = {
637        let mut renderer = SqlRenderer::new(sql_output.writer(), render);
638        let engine_report = GenerationEngine::new(plan).run(&mut renderer)?;
639        let warnings = renderer.warnings().to_vec();
640        renderer.finish()?;
641        (engine_report.rows_written, warnings)
642    };
643
644    // Audit the freshly rendered temp file.
645    let report = verifier.verify_path(&temp_path)?;
646    if !report.passed() {
647        let failures: Vec<String> = report
648            .failures()
649            .map(|check| format!("{} ({})", check.name, check.detail))
650            .collect();
651        // Dropping `sql_output` removes the temp; the destination is untouched.
652        let mut diagnostic = Diagnostic::error(
653            &codes::VERIFY_FAILED,
654            destination.display().to_string(),
655            format!(
656                "generated output failed verification and was not published; {} check(s) failed",
657                failures.len()
658            ),
659        );
660        diagnostic.related = failures
661            .into_iter()
662            .map(|failure| SourceLocation {
663                path: destination.display().to_string(),
664                description: Some(failure),
665            })
666            .collect();
667        return Err(GenerateError::Diagnostic(Box::new(diagnostic)));
668    }
669    let not_checked: Vec<String> = report
670        .checks
671        .iter()
672        .filter(|check| check.status == verify::CheckStatus::NotChecked)
673        .map(|check| check.name.clone())
674        .collect();
675
676    merge_render_warnings(&mut diagnostics, &render_warnings);
677    merge_not_checked_warning(&mut diagnostics, &not_checked);
678    if strict && has_warnings(&diagnostics) {
679        // `sql_output` still names only a protected temp. Returning drops it,
680        // and the resolved model has not been published either.
681        return Err(GenerateError::Diagnostics(diagnostics));
682    }
683
684    // Verification passed: publish the SQL, then the model (if any).
685    let mut outputs = vec![sql_output];
686    if let Some((path, yaml)) = emit_plan {
687        let mut model_output = AtomicOutput::create(&path).map_err(|error| {
688            GenerateError::diagnostic(
689                &codes::VERIFY_STAGE,
690                path.display().to_string(),
691                format!("cannot stage model beside `{}`: {error}", path.display()),
692            )
693        })?;
694        use std::io::Write;
695        model_output
696            .writer()
697            .write_all(yaml.as_bytes())
698            .map_err(|error| {
699                GenerateError::diagnostic(
700                    &codes::EMIT_IO,
701                    path.display().to_string(),
702                    error.to_string(),
703                )
704            })?;
705        outputs.push(model_output);
706    }
707
708    publish_in_order(outputs).map_err(|partial| {
709        GenerateError::diagnostic(
710            &codes::VERIFY_PARTIAL_PUBLISH,
711            "output",
712            partial.to_string(),
713        )
714    })?;
715
716    Ok(VerifiedRun {
717        rows_written,
718        diagnostics,
719    })
720}
721
722/// A resolved base model plus the diagnostics and inference decisions gathered
723/// while assembling it.
724struct ResolvedModel {
725    model: SyntheticModel,
726    diagnostics: DiagnosticBag,
727    decisions: Vec<Decision>,
728}
729
730/// Resolve the model a request will compile: a pure `.config()` complete model,
731/// a profiled+inferred base from `.input()`, or that base with a `kind:
732/// overrides` `.config()` merged on top.
733fn assemble_model(
734    input: Option<&Path>,
735    config: Option<&Path>,
736    source: &SourceOptions,
737) -> Result<ResolvedModel, GenerateError> {
738    match (input, config) {
739        (None, None) => Err(GenerateError::diagnostic(
740            &codes::REQUEST_SOURCE,
741            "request",
742            "at least one of `.input()` or `.config()` is required",
743        )),
744        (None, Some(config_path)) => {
745            match ConfigLoader::load(config_path).map_err(GenerateError::Diagnostics)? {
746                SyntheticFile::Model(model) => Ok(ResolvedModel {
747                    model,
748                    diagnostics: DiagnosticBag::default(),
749                    decisions: Vec::new(),
750                }),
751                SyntheticFile::Overrides(_) => Err(GenerateError::diagnostic(
752                    &codes::OVERRIDES_NO_BASE,
753                    config_path.display().to_string(),
754                    format!(
755                        "`{}` is a `kind: overrides` document but no base model is available; \
756                         supply a source dump to profile (`.input()`) so the overrides have a \
757                         base to merge onto",
758                        config_path.display()
759                    ),
760                )),
761            }
762        }
763        (Some(input_path), config) => {
764            let profile = profile_source(input_path, source)?;
765            let inference = ModelInference::standard()
766                .infer(&profile.schema, &profile)
767                .map_err(|error| {
768                    GenerateError::diagnostic(
769                        &codes::INFER_FAILED,
770                        input_path.display().to_string(),
771                        error.to_string(),
772                    )
773                })?;
774
775            let mut diagnostics = DiagnosticBag::default();
776            diagnostics.diagnostics.extend(profile.warnings);
777            diagnostics.diagnostics.extend(
778                inference
779                    .warnings
780                    .into_iter()
781                    .filter(|diagnostic| diagnostic.code != codes::INFER_SOURCE_DERIVED.code),
782            );
783
784            let base = inference.model;
785            let decisions = inference.decisions;
786
787            match config {
788                None => Ok(ResolvedModel {
789                    model: base,
790                    diagnostics,
791                    decisions,
792                }),
793                Some(config_path) => {
794                    match ConfigLoader::load(config_path).map_err(GenerateError::Diagnostics)? {
795                        SyntheticFile::Overrides(patch) => {
796                            let (merged, bag) = ModelMerger::merge(base, patch)
797                                .map_err(GenerateError::Diagnostics)?;
798                            diagnostics.diagnostics.extend(bag.diagnostics);
799                            Ok(ResolvedModel {
800                                model: merged,
801                                diagnostics,
802                                decisions,
803                            })
804                        }
805                        SyntheticFile::Model(model) => {
806                            // An explicit complete model alongside a source: the
807                            // model is authoritative and stands alone, so use it
808                            // and note that the profiled base was set aside.
809                            diagnostics.warning(
810                                crate::diagnostic::codes::CONFIG_COMPLETE_MODEL.code,
811                                config_path.display().to_string(),
812                                "a complete `kind: model` config was supplied with a source dump; \
813                                 using the config model and ignoring the profiled base",
814                            );
815                            Ok(ResolvedModel {
816                                model,
817                                diagnostics,
818                                decisions: Vec::new(),
819                            })
820                        }
821                    }
822                }
823            }
824        }
825    }
826}
827
828/// Profile `path` into a [`DumpProfile`] carrying both its portable DDL schema
829/// and value evidence. The dump is read exactly once: the profiler builds the
830/// schema and sketches values in the same streaming pass, then exposes the
831/// schema on [`DumpProfile::schema`].
832fn profile_source(path: &Path, source: &SourceOptions) -> Result<DumpProfile, GenerateError> {
833    let mut builder = DumpProfiler::builder();
834    if let Some(dialect) = source.dialect {
835        builder = builder.dialect(dialect);
836    }
837    if let Some(depth) = source.depth {
838        builder = builder.depth(depth);
839    }
840    if let Some(sample) = source.sample {
841        builder = builder.budget(ProfileBudget {
842            sample_rows: sample,
843            ..ProfileBudget::default()
844        });
845    }
846    builder.build().profile_path(path).map_err(source_error)
847}
848
849/// Wrap an I/O / profiling failure as a `GEN-SOURCE-IO` invalid-input error.
850fn source_error(error: impl std::fmt::Display) -> GenerateError {
851    GenerateError::diagnostic(&codes::SOURCE_IO, "input", error.to_string())
852}
853
854/// Serialize the resolved model as a self-contained `--emit-config` document.
855///
856/// Freezes each table's resolved row count in place (keeping `kind: observed`),
857/// pins `defaults.inference: disabled`, and records the seed only when the run
858/// was explicitly seeded — an unseeded run emits no seed so reloading it is
859/// intentionally fresh. Inference already omits raw samples, so the emitted
860/// model carries only bounded, non-literal `profiles` metadata.
861/// Build the resolved, self-contained `--emit-config` YAML for `model`/`plan`.
862///
863/// Freezes each table's resolved row count, pins `inference: disabled`, and
864/// records the seed only for an explicitly-seeded run. Shared by normal and
865/// verified atomic publication paths.
866fn resolved_model_yaml(
867    model: &SyntheticModel,
868    plan: &GenerationPlan,
869    explicit_seed: Option<u64>,
870) -> Result<String, GenerateError> {
871    let mut emit = model.clone();
872
873    let resolved: BTreeMap<String, u64> = plan
874        .tables
875        .iter()
876        .map(|t| (t.name.clone(), t.rows))
877        .collect();
878    // The resolved model represents this compiled plan, not the pre-selection
879    // source model. Drop excluded tables and their optional profile metadata,
880    // and carry the compiler's normalized schema (including detached FKs).
881    emit.imports.clear();
882    emit.tables.retain(|name, _| resolved.contains_key(name));
883    emit.profiles.retain(|path, _| {
884        path.split_once('.')
885            .is_some_and(|(table, _)| resolved.contains_key(table))
886    });
887    for planned in &plan.tables {
888        let Some(table) = emit.tables.get_mut(&planned.name) else {
889            continue;
890        };
891        table.schema = planned.schema.clone();
892        table.relationships.retain(|relationship| {
893            planned.relationships.iter().any(|active| {
894                active.name == relationship.name
895                    && active.columns == relationship.columns
896                    && active.parent_table == relationship.references.table
897                    && active.parent_columns == relationship.references.columns
898            })
899        });
900    }
901    let family_children: HashSet<String> = plan
902        .tables
903        .iter()
904        .flat_map(|table| table.planners.iter())
905        .filter_map(|planner| planner.family_child_table().map(str::to_owned))
906        .collect();
907    emit.freeze_row_counts(&resolved, &family_children);
908    emit.defaults.inference = InferenceMode::Disabled;
909    emit.seed = explicit_seed;
910
911    serde_yaml_ng::to_string(&emit).map_err(|error| {
912        GenerateError::diagnostic(&codes::EMIT_SERIALIZE, "emit_config", error.to_string())
913    })
914}
915
916fn stage_model(
917    model: &SyntheticModel,
918    plan: &GenerationPlan,
919    explicit_seed: Option<u64>,
920    target: Option<&OutputTarget>,
921) -> Result<Option<AtomicOutput>, GenerateError> {
922    let Some(target) = target else {
923        return Ok(None);
924    };
925    let yaml = resolved_model_yaml(model, plan, explicit_seed)?;
926
927    match target {
928        OutputTarget::Path(path) => {
929            let mut output = AtomicOutput::create(path).map_err(|error| {
930                GenerateError::diagnostic(
931                    &codes::EMIT_IO,
932                    path.display().to_string(),
933                    format!("cannot stage model beside `{}`: {error}", path.display()),
934                )
935            })?;
936            output
937                .writer()
938                .write_all(yaml.as_bytes())
939                .map_err(|error| {
940                    GenerateError::diagnostic(
941                        &codes::EMIT_IO,
942                        path.display().to_string(),
943                        format!("failed to stage `{}`: {error}", path.display()),
944                    )
945                })?;
946            Ok(Some(output))
947        }
948        // The builder/CLI only ever routes emit to a real path (a stdout emit
949        // is spooled through a temp file), so this arm is unreachable in
950        // practice; discard rather than panic if a caller wires it directly.
951        OutputTarget::Discard => Ok(None),
952    }
953}
954
955fn publish_model(output: Option<AtomicOutput>) -> Result<(), GenerateError> {
956    let Some(output) = output else {
957        return Ok(());
958    };
959    let path = output.destination().to_path_buf();
960    output.commit().map_err(|error| {
961        GenerateError::diagnostic(
962            &codes::EMIT_IO,
963            path.display().to_string(),
964            format!("failed to publish `{}`: {error}", path.display()),
965        )
966    })
967}
968
969/// Reshape inference [`Decision`]s into the value-free `--explain` report.
970fn build_explain(decisions: &[Decision]) -> Vec<ExplainColumn> {
971    decisions
972        .iter()
973        .map(|decision| ExplainColumn {
974            column: decision.column.clone(),
975            reason: decision.reason.clone(),
976            confidence: confidence_label(decision.confidence).to_string(),
977            generator_kind: decision.generator_kind.clone(),
978            source_derived: decision.source_derived,
979            rejected: decision
980                .rejected
981                .iter()
982                .map(|rejected| ExplainRejected {
983                    generator_kind: rejected.generator_kind.clone(),
984                    reason: rejected.reason.clone(),
985                    precedence: precedence_label(rejected.precedence).to_string(),
986                    confidence: confidence_label(rejected.confidence).to_string(),
987                })
988                .collect(),
989        })
990        .collect()
991}
992
993/// Stable lowercase label for a [`Confidence`], for reporting.
994fn confidence_label(confidence: Confidence) -> &'static str {
995    match confidence {
996        Confidence::Low => "low",
997        Confidence::Medium => "medium",
998        Confidence::High => "high",
999        Confidence::Certain => "certain",
1000    }
1001}
1002
1003/// Stable lowercase label for a [`Precedence`] class, for reporting.
1004fn precedence_label(precedence: Precedence) -> &'static str {
1005    match precedence {
1006        Precedence::TypeFallback => "type_fallback",
1007        Precedence::ObservedDistribution => "observed_distribution",
1008        Precedence::StrongSemantic => "strong_semantic",
1009        Precedence::Relationship => "relationship",
1010        Precedence::CredentialGuard => "credential_guard",
1011        Precedence::SchemaConstraint => "schema_constraint",
1012        Precedence::ExplicitYaml => "explicit_yaml",
1013    }
1014}
1015
1016/// Run the engine under [`RunMode::Generate`], rendering to `output`. Returns
1017/// the engine report plus any warnings the renderer collected (e.g. lossy
1018/// cross-dialect type conversions), which the caller merges into the report
1019/// diagnostics so they are visible and `--strict`-promotable.
1020fn run_generate(
1021    engine: GenerationEngine,
1022    output: OutputTarget,
1023    model_output: Option<AtomicOutput>,
1024    render: RenderOptions,
1025    mut diagnostics: DiagnosticBag,
1026    strict: bool,
1027) -> Result<(EngineReport, DiagnosticBag), GenerateError> {
1028    match output {
1029        OutputTarget::Path(path) => {
1030            let mut sql_output = AtomicOutput::create(&path).map_err(|err| {
1031                GenerateError::diagnostic(
1032                    &codes::OUTPUT_IO,
1033                    path.display().to_string(),
1034                    format!("cannot stage output beside `{}`: {err}", path.display()),
1035                )
1036            })?;
1037            let (report, warnings) = {
1038                let mut renderer = SqlRenderer::new(sql_output.writer(), render);
1039                let report = engine.run(&mut renderer)?;
1040                // Drain the renderer's warnings before `finish` consumes it.
1041                let warnings = renderer.warnings().to_vec();
1042                renderer.finish()?;
1043                (report, warnings)
1044            };
1045
1046            merge_render_warnings(&mut diagnostics, &warnings);
1047            if strict && has_warnings(&diagnostics) {
1048                // Both outputs are staged only. Returning drops their temps and
1049                // preserves every previous destination byte.
1050                return Err(GenerateError::Diagnostics(diagnostics));
1051            }
1052
1053            if let Some(model_output) = model_output {
1054                // SQL is the primary artifact, so publish it first. The files
1055                // cannot form one cross-filesystem transaction; if publishing
1056                // the model then fails, report exactly what already landed.
1057                publish_in_order(vec![sql_output, model_output]).map_err(|partial| {
1058                    GenerateError::diagnostic(&codes::OUTPUT_IO, "output", partial.to_string())
1059                })?;
1060            } else {
1061                sql_output.commit().map_err(|error| {
1062                    GenerateError::diagnostic(
1063                        &codes::OUTPUT_IO,
1064                        path.display().to_string(),
1065                        format!("failed to publish `{}`: {error}", path.display()),
1066                    )
1067                })?;
1068            }
1069            Ok((report, diagnostics))
1070        }
1071        OutputTarget::Discard => {
1072            let mut sink = DiscardSink;
1073            let report = engine.run(&mut sink)?;
1074            publish_model(model_output)?;
1075            Ok((report, diagnostics))
1076        }
1077    }
1078}
1079
1080/// The batch size the CLI/`RenderOptions::default` land on when a run neither
1081/// passes `--batch-size` nor carries a model `output.batch_size`. Used as the
1082/// sentinel for "the caller left batch size at its neutral default", so a
1083/// model's `output.batch_size` can fill in under it.
1084const DEFAULT_RENDER_BATCH_SIZE: usize = 1_000;
1085
1086/// Fold the compiled model `output:` block into `render` under the caller's
1087/// explicit flags, resolving every field with a single precedence: an explicit
1088/// CLI/builder flag wins, then the model's `output:` block, then (dialect only)
1089/// the model's captured source/input dialect, then the built-in default.
1090///
1091/// * **dialect** — `--dialect`/[`GenerateBuilder::output_dialect`] > model
1092///   `output.dialect` > `plan.input_dialect` (preserve-source) > [`SqlDialect::
1093///   MySql`]. When the target dialect was chosen *deliberately* (CLI or model,
1094///   not preserve-source/fallback) the captured source dialect is threaded into
1095///   `source_dialect` so the renderer maps every type across dialects and
1096///   reports lossy conversions; a preserve-source or fallback run leaves
1097///   `source_dialect` unset (source == render dialect), so a model's optional
1098///   `source:` block stays removable metadata that cannot change output.
1099/// * **mode** — only the absence of `--schema-only`/`--data-only` yields
1100///   [`OutputMode::SchemaAndData`], so that value is the sentinel under which the
1101///   model's `output.mode` fills in; an explicit `--schema-only`/`--data-only`
1102///   always wins.
1103/// * **inserts** — the CLI has only a `--no-copy` opt-in, so a `false` `no_copy`
1104///   falls back to the model: `output.inserts: insert` forces multi-row INSERT,
1105///   while `auto`/`copy` keep the COPY default. An explicit `--no-copy` wins.
1106/// * **batch_size** — [`DEFAULT_RENDER_BATCH_SIZE`] is the neutral sentinel under
1107///   which a positive `output.batch_size` fills in; any other explicit value
1108///   wins.
1109fn resolve_render_options(
1110    render: &mut RenderOptions,
1111    output_dialect: Option<SqlDialect>,
1112    plan: &GenerationPlan,
1113) {
1114    let deliberate_dialect = match (output_dialect, plan.output.dialect) {
1115        (Some(cli), _) => {
1116            render.dialect = cli;
1117            true
1118        }
1119        (None, Some(model_dialect)) => {
1120            render.dialect = model_dialect;
1121            true
1122        }
1123        (None, None) => {
1124            render.dialect = plan.input_dialect.unwrap_or(SqlDialect::MySql);
1125            false
1126        }
1127    };
1128    if deliberate_dialect {
1129        render.source_dialect = render.source_dialect.or(plan.input_dialect);
1130    }
1131
1132    if render.mode == OutputMode::SchemaAndData {
1133        if let Some(mode) = plan.output.mode {
1134            render.mode = mode;
1135        }
1136    }
1137
1138    if !render.no_copy {
1139        render.no_copy = matches!(plan.output.inserts, Some(InsertMode::Insert));
1140    }
1141
1142    if render.batch_size == DEFAULT_RENDER_BATCH_SIZE {
1143        if let Some(batch) = plan.output.batch_size.filter(|&b| b > 0) {
1144            render.batch_size = batch as usize;
1145        }
1146    }
1147}
1148
1149/// Merge renderer [`ConvertWarning`]s into `diagnostics` as `Severity::Warning`
1150/// entries with stable `GEN-*` codes, so both the CLI's `write_diagnostics` and
1151/// its `--strict` `warnings_are_fatal` gate see a lossy cross-dialect conversion
1152/// (which would otherwise be silently dropped on the render pass).
1153fn merge_render_warnings(diagnostics: &mut DiagnosticBag, warnings: &[ConvertWarning]) {
1154    for warning in warnings {
1155        let code = match warning {
1156            ConvertWarning::LossyConversion { .. } => crate::diagnostic::codes::LOSSY_TYPE.code,
1157            _ => crate::diagnostic::codes::RENDER_WARNING.code,
1158        };
1159        diagnostics.warning(code, "output", warning.to_string());
1160    }
1161}
1162
1163/// Surface verification coverage gaps as warnings before the staged output is
1164/// published, so strict mode can reject them without changing destinations.
1165fn merge_not_checked_warning(diagnostics: &mut DiagnosticBag, not_checked: &[String]) {
1166    if not_checked.is_empty() {
1167        return;
1168    }
1169    diagnostics.warning(
1170        crate::diagnostic::codes::VERIFY_NOTCHECKED.code,
1171        String::new(),
1172        format!(
1173            "verification passed but {} capability/capabilities could not be checked exactly: {}",
1174            not_checked.len(),
1175            not_checked.join(", ")
1176        ),
1177    );
1178}
1179
1180fn has_warnings(diagnostics: &DiagnosticBag) -> bool {
1181    diagnostics
1182        .diagnostics
1183        .iter()
1184        .any(|diagnostic| diagnostic.severity == crate::diagnostic::Severity::Warning)
1185}
1186
1187/// A [`RowSink`] that counts rows (via [`GenerationEngine::run`]'s own
1188/// bookkeeping) but writes nothing; backs a `RunMode::Generate` request built
1189/// directly (bypassing [`GenerateBuilder`]) with `OutputTarget::Discard` —
1190/// e.g. a caller that wants a real row count without paying for a render.
1191/// [`GenerateBuilder`] itself never reaches this: it only produces `Discard`
1192/// under `Check`/`DryRun`, and those modes never call [`run_generate`].
1193struct DiscardSink;
1194
1195impl RowSink for DiscardSink {
1196    fn begin_table(&mut self, _table: &PlannedTable) -> Result<(), GenerateError> {
1197        Ok(())
1198    }
1199
1200    fn write_row(
1201        &mut self,
1202        _table: &PlannedTable,
1203        _row: &GeneratedRow,
1204    ) -> Result<(), GenerateError> {
1205        Ok(())
1206    }
1207
1208    fn end_table(&mut self, _table: &PlannedTable) -> Result<(), GenerateError> {
1209        Ok(())
1210    }
1211}
1212
1213/// Builds one [`GenerateRequest`] and runs it. The only validation performed
1214/// here is request *shape* (e.g. `RunMode::Generate` needs an output path);
1215/// anything about the model itself — a missing config, a compile error —
1216/// surfaces from [`Generate::run`] as a structured [`GenerateError`].
1217#[derive(Debug, Clone, Default)]
1218pub struct GenerateBuilder {
1219    input: Option<PathBuf>,
1220    config: Option<PathBuf>,
1221    output: Option<PathBuf>,
1222    emit: Option<PathBuf>,
1223    compile: CompileOptions,
1224    render: RenderOptions,
1225    output_dialect: Option<SqlDialect>,
1226    mode: RunMode,
1227    explain: bool,
1228    verify: bool,
1229    strict: bool,
1230    source: SourceOptions,
1231}
1232
1233impl GenerateBuilder {
1234    /// A source dump to profile into a base model. Profiling and inference run
1235    /// automatically; combine with a `kind: overrides` `.config()` to patch
1236    /// the profiled base.
1237    pub fn input(mut self, path: impl Into<PathBuf>) -> Self {
1238        self.input = Some(path.into());
1239        self
1240    }
1241
1242    /// The `kind: model` (or, once a base model is available, `kind:
1243    /// overrides`) YAML document to generate from.
1244    pub fn config(mut self, path: impl Into<PathBuf>) -> Self {
1245        self.config = Some(path.into());
1246        self
1247    }
1248
1249    /// The path rendered SQL is published to atomically after successful
1250    /// generation. Required under `RunMode::Generate`; optional under
1251    /// `Check`/`DryRun`, which never write SQL regardless.
1252    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
1253        self.output = Some(path.into());
1254        self
1255    }
1256
1257    /// The path the resolved, self-contained model is published to atomically
1258    /// (`--emit-config`). Emitting fires alongside whatever `mode` runs.
1259    pub fn emit(mut self, path: impl Into<PathBuf>) -> Self {
1260        self.emit = Some(path.into());
1261        self
1262    }
1263
1264    /// Whether to build the `--explain` inference report.
1265    pub fn explain(mut self, explain: bool) -> Self {
1266        self.explain = explain;
1267        self
1268    }
1269
1270    /// Force the dialect the source dump (`.input()`) is parsed as, instead of
1271    /// auto-detecting it.
1272    pub fn input_dialect(mut self, dialect: SqlDialect) -> Self {
1273        self.source.dialect = Some(dialect);
1274        self
1275    }
1276
1277    /// Per-column retained sample size used while profiling `.input()`.
1278    pub fn profile_sample(mut self, sample: usize) -> Self {
1279        self.source.sample = Some(sample);
1280        self
1281    }
1282
1283    /// The SQL dialect to render for, overriding the model's own `output.dialect`
1284    /// and captured source dialect. Choosing a dialect that differs from the
1285    /// model's source dialect renders every type across dialects (reporting lossy
1286    /// conversions); leaving it unset resolves the dialect from the model
1287    /// (`output.dialect`, else the source/input dialect, else MySQL).
1288    pub fn output_dialect(mut self, dialect: SqlDialect) -> Self {
1289        self.render.dialect = dialect;
1290        self.output_dialect = Some(dialect);
1291        self
1292    }
1293
1294    /// The run's root seed, overriding the model's own `seed:`.
1295    pub fn seed(mut self, seed: u64) -> Self {
1296        self.compile.seed = Some(seed);
1297        self
1298    }
1299
1300    /// Render MSSQL output in "production style" — see
1301    /// [`RenderOptions::mssql_production_style`]. No effect outside
1302    /// [`SqlDialect::Mssql`].
1303    pub fn mssql_production_style(mut self, production_style: bool) -> Self {
1304        self.render.mssql_production_style = production_style;
1305        self
1306    }
1307
1308    /// Emit a `GO` batch separator every `interval` `INSERT` batches instead
1309    /// of after every batch — see [`RenderOptions::mssql_go`]. No effect
1310    /// outside [`SqlDialect::Mssql`].
1311    pub fn mssql_go(mut self, interval: u64) -> Self {
1312        self.render.mssql_go = Some(interval);
1313        self
1314    }
1315
1316    /// A per-table row-count scale factor (`--table-scale`). Rejects a
1317    /// non-finite or negative factor.
1318    pub fn table_scale(
1319        mut self,
1320        table: impl Into<String>,
1321        factor: f64,
1322    ) -> Result<Self, GenerateError> {
1323        if !factor.is_finite() || factor < 0.0 {
1324            return Err(GenerateError::diagnostic(
1325                &codes::TABLE_SCALE_INVALID,
1326                format!("tables.{}", table.into()),
1327                format!("table scale must be a finite, non-negative number, found {factor}"),
1328            ));
1329        }
1330        self.compile
1331            .table_rows
1332            .push(TableCountOverride::scale(table, factor));
1333        Ok(self)
1334    }
1335
1336    /// Replace the full [`CompileOptions`] (row-count controls, table
1337    /// selection) in one call.
1338    pub fn compile(mut self, compile: CompileOptions) -> Self {
1339        self.compile = compile;
1340        self
1341    }
1342
1343    /// Whether to verify the generated SQL against the compiled plan and
1344    /// publish atomically only if the audit passes. Requires a filesystem SQL
1345    /// destination (`.output()`); a stdout destination is a usage error.
1346    pub fn verify(mut self, verify: bool) -> Self {
1347        self.verify = verify;
1348        self
1349    }
1350
1351    /// Treat every warning as fatal and publish no requested output when one
1352    /// is discovered.
1353    pub fn strict(mut self, strict: bool) -> Self {
1354        self.strict = strict;
1355        self
1356    }
1357
1358    /// The profiling depth for `.input()` (defaults to the profiler's full
1359    /// depth when unset).
1360    pub fn profile_depth(mut self, depth: ProfileDepth) -> Self {
1361        self.source.depth = Some(depth);
1362        self
1363    }
1364
1365    /// Run in `Check`, `DryRun`, or (the default) full `Generate` mode.
1366    pub fn mode(mut self, mode: RunMode) -> Self {
1367        self.mode = mode;
1368        self
1369    }
1370
1371    /// Assemble a [`GenerateRequest`], validating request shape only (e.g.
1372    /// `RunMode::Generate` needs `.output()`). Model-level problems surface
1373    /// later, from [`Generate::run`].
1374    fn build(self) -> Result<GenerateRequest, GenerateError> {
1375        if self.verify && self.mode != RunMode::Generate {
1376            return Err(GenerateError::diagnostic(
1377                &codes::VERIFY_MODE,
1378                "request.verify",
1379                "--verify generates and publishes; it cannot be combined with \
1380                 check/dry-run/emit-only modes",
1381            ));
1382        }
1383        let output = match (self.mode, self.output) {
1384            (RunMode::Generate, Some(path)) => OutputTarget::Path(path),
1385            (RunMode::Generate, None) => {
1386                return Err(GenerateError::diagnostic(
1387                    &codes::REQUEST_OUTPUT,
1388                    "request.output",
1389                    "`.output()` is required under `RunMode::Generate`",
1390                ))
1391            }
1392            (RunMode::Check | RunMode::DryRun | RunMode::EmitModel, Some(path)) => {
1393                OutputTarget::Path(path)
1394            }
1395            (RunMode::Check | RunMode::DryRun | RunMode::EmitModel, None) => OutputTarget::Discard,
1396        };
1397
1398        if self.verify && !matches!(output, OutputTarget::Path(_)) {
1399            return Err(GenerateError::diagnostic(
1400                &codes::VERIFY_NO_FILE,
1401                "request.output",
1402                "--verify requires a filesystem SQL destination",
1403            ));
1404        }
1405
1406        Ok(GenerateRequest {
1407            input: self.input,
1408            config: self.config,
1409            output,
1410            emit: self.emit.map(OutputTarget::Path),
1411            compile: self.compile,
1412            render: self.render,
1413            output_dialect: self.output_dialect,
1414            mode: self.mode,
1415            explain: self.explain,
1416            verify: self.verify,
1417            strict: self.strict,
1418            source: self.source,
1419        })
1420    }
1421
1422    /// Build the request and run it end to end.
1423    pub fn run(self) -> Result<GenerateReport, GenerateError> {
1424        Generate::run(self.build()?)
1425    }
1426}