Skip to main content

sql_splitter/generate/planners/
structural.rs

1//! Common same-table temporal planners plus the relationship/hierarchy
2//! planners that build on the same execution pattern.
3//!
4//! Temporal planners include `temporal.timestamps` (a created/updated pair, plus
5//! optional trailing timestamps), `temporal.soft_delete` (a coherent
6//! `deleted_at`/`is_deleted` pair), and `temporal.lifecycle` (a status column
7//! that only ever reaches legal states, each carrying a correctly-ordered
8//! timestamp).
9//!
10//! Relationship and hierarchy planners include `hierarchy.tree` (a self-referential
11//! parent_id tree with configurable-ratio roots and bounded depth/branching)
12//! and the cross-table FK-side planners `relation.junction_pair` (unique
13//! `(left, right)` edges via a deterministic pair-index permutation),
14//! `relation.polymorphic_pair` (an atomic `(type, id)` pair choosing a target
15//! table then a valid key in it), and `relation.tenant_family` (a same-tenant
16//! foreign key drawn from the child's own tenant partition of the parent). The
17//! cross-table planners cannot see the tables they reference, so the compiler
18//! injects the referenced parent counts and dense key recipes as facts under
19//! [`RELATION_FACTS_KEY`], driven off the descriptor's `cross_table` capability.
20//!
21//! # Shared machinery, separate planners
22//!
23//! Each planner is registered under its own `kind` with its own factory and
24//! compiled type — no option-heavy mega-planner. What they share is *how* a
25//! timestamp is chosen: [`InstantDraw`] picks a base instant (a bounded
26//! random draw or a monotonically increasing one), and [`OffsetDraw`] picks a
27//! non-negative whole-unit offset added to a base instant. Every timestamp is
28//! reduced to a single internal UTC instant measured in nanoseconds since the
29//! Unix epoch (an `i128`), so every "B happens no earlier than A" invariant is
30//! pure checked integer arithmetic, matching the `temporal.interval` approach.
31//!
32//! # Owned columns and streams
33//!
34//! Each planner owns exactly the columns named under its `columns:` mapping;
35//! the model compiler turns those into ownership claims, so a colliding
36//! generator raises `GEN-COLUMN-OWNER-CONFLICT`. Every row draws its
37//! constituent choices from independent, stably-keyed seed streams in a fixed
38//! order — regardless of which branch a row lands in — so a seeded run
39//! reproduces exactly.
40
41use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
42use rand::RngExt;
43use rand_chacha::ChaCha8Rng;
44use serde_yaml_ng::Value;
45
46use crate::diagnostic::DiagnosticBag;
47use crate::generate::registry::{
48    ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledPlanner, Determinism,
49    PlannerDescriptor, PlannerFactory, PlannerPredicate, PredicateGuard, Verification,
50};
51use crate::generate::seed::StreamId;
52use crate::generate::value::{GenerateError, GeneratedValue};
53use crate::synthetic::model::PlannerConfig;
54use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
55
56/// Nanoseconds per second, the base unit conversion for every offset.
57const NANOS_PER_SECOND: i128 = 1_000_000_000;
58
59// =============================================================================
60// Shared draws
61// =============================================================================
62
63/// How a row's base instant is chosen — shared by every planner's "starting
64/// point" column (`temporal.timestamps`'s `created`, `temporal.soft_delete`'s
65/// `deleted_range`, `temporal.lifecycle`'s `start`).
66#[derive(Clone, Copy)]
67enum InstantDraw {
68    /// A uniformly random instant in the inclusive `[min_ns, max_ns]` range.
69    Range { min_ns: i128, max_ns: i128 },
70    /// A strictly increasing instant: row `n` starts at `min_ns + n * step_ns`.
71    Monotonic { min_ns: i128, step_ns: i128 },
72}
73
74impl InstantDraw {
75    fn draw(&self, rng: &mut ChaCha8Rng, row_index: u64) -> i128 {
76        match *self {
77            InstantDraw::Range { min_ns, max_ns } => rng.random_range(min_ns..=max_ns),
78            InstantDraw::Monotonic { min_ns, step_ns } => {
79                min_ns.saturating_add(step_ns.saturating_mul(row_index as i128))
80            }
81        }
82    }
83}
84
85/// How a non-negative whole-unit offset added to a base instant is chosen —
86/// shared by every "delay after X" column.
87#[derive(Clone, Copy)]
88enum OffsetDraw {
89    Fixed(i128),
90    Uniform { min: i128, max: i128 },
91}
92
93impl OffsetDraw {
94    fn draw(&self, rng: &mut ChaCha8Rng) -> i128 {
95        match *self {
96            OffsetDraw::Fixed(value) => value,
97            OffsetDraw::Uniform { min, max } => {
98                if max <= min {
99                    min
100                } else {
101                    rng.random_range(min..=max)
102                }
103            }
104        }
105    }
106}
107
108/// Compile an `{ kind, min, max }` / `{ kind: monotonic, min, step_seconds }`
109/// block into an [`InstantDraw`]. Shared by `created`, `deleted_range`, and
110/// `start`.
111fn compile_instant_block(
112    block: Option<&Value>,
113    planner: &str,
114    code: &'static str,
115    path: &str,
116    bag: &mut DiagnosticBag,
117) -> Option<InstantDraw> {
118    let kind = block.and_then(|b| b.get("kind")).and_then(Value::as_str);
119    let min_ns = block
120        .and_then(|b| b.get("min"))
121        .and_then(as_instant_ns)
122        .or_else(|| {
123            bag.error(
124                code,
125                format!("{path}.min"),
126                format!("{planner} requires a parseable `min` timestamp"),
127            );
128            None
129        })?;
130
131    match kind {
132        Some("monotonic") => {
133            let step_seconds = block
134                .and_then(|b| b.get("step_seconds"))
135                .and_then(as_i128)
136                .unwrap_or(1)
137                .max(1);
138            Some(InstantDraw::Monotonic {
139                min_ns,
140                step_ns: step_seconds.saturating_mul(NANOS_PER_SECOND),
141            })
142        }
143        // `range`, or an omitted kind: a bounded random draw.
144        _ => {
145            let max_ns = block
146                .and_then(|b| b.get("max"))
147                .and_then(as_instant_ns)
148                .or_else(|| {
149                    bag.error(
150                        code,
151                        format!("{path}.max"),
152                        format!("{planner} range requires a parseable `max` timestamp"),
153                    );
154                    None
155                })?;
156            if max_ns < min_ns {
157                bag.error(
158                    code,
159                    path.to_string(),
160                    format!("{planner} `max` is before `min`"),
161                );
162                return None;
163            }
164            Some(InstantDraw::Range { min_ns, max_ns })
165        }
166    }
167}
168
169/// Compile a `{ kind, unit, value | min, max }` block into an [`OffsetDraw`]
170/// plus its unit size in nanoseconds. Shared by every delay/step block.
171fn compile_offset_block(
172    block: Option<&Value>,
173    planner: &str,
174    code: &'static str,
175    path: &str,
176    bag: &mut DiagnosticBag,
177) -> Option<(OffsetDraw, i128)> {
178    let unit = block
179        .and_then(|b| b.get("unit"))
180        .and_then(Value::as_str)
181        .unwrap_or("seconds");
182    let Some(unit_nanos) = unit_nanos(unit) else {
183        bag.error(
184            code,
185            format!("{path}.unit"),
186            format!("{planner} `unit` `{unit}` is not a recognized time unit"),
187        );
188        return None;
189    };
190
191    let kind = block.and_then(|b| b.get("kind")).and_then(Value::as_str);
192    let draw = match kind {
193        Some("fixed") => {
194            let value = block
195                .and_then(|b| b.get("value"))
196                .and_then(as_i128)
197                .unwrap_or(0);
198            check_nonneg_bounded(value, unit_nanos, planner, code, path, bag);
199            OffsetDraw::Fixed(value)
200        }
201        // `uniform`, or an omitted kind.
202        _ => {
203            let min = block
204                .and_then(|b| b.get("min"))
205                .and_then(as_i128)
206                .unwrap_or(0);
207            let max = block
208                .and_then(|b| b.get("max"))
209                .and_then(as_i128)
210                .unwrap_or(min);
211            check_nonneg_bounded(min, unit_nanos, planner, code, path, bag);
212            check_nonneg_bounded(max, unit_nanos, planner, code, path, bag);
213            if max < min {
214                bag.error(
215                    code,
216                    path.to_string(),
217                    format!("{planner} `max` is below `min`"),
218                );
219            }
220            OffsetDraw::Uniform { min, max }
221        }
222    };
223    Some((draw, unit_nanos))
224}
225
226/// Report a negative offset bound or one whose nanosecond span overflows.
227fn check_nonneg_bounded(
228    units: i128,
229    unit_nanos: i128,
230    planner: &str,
231    code: &'static str,
232    path: &str,
233    bag: &mut DiagnosticBag,
234) {
235    if units < 0 {
236        bag.error(
237            code,
238            path.to_string(),
239            format!("{planner} offset `{units}` is negative; offsets must be >= 0"),
240        );
241    } else if units.checked_mul(unit_nanos).is_none() {
242        bag.error(
243            code,
244            path.to_string(),
245            format!(
246                "{planner} offset `{units}` overflows the representable nanosecond range at this unit"
247            ),
248        );
249    }
250}
251
252/// Add a non-negative whole-unit offset to a base instant, in nanoseconds.
253fn add_offset(base_ns: i128, offset_units: i128, unit_nanos: i128) -> Result<i128, GenerateError> {
254    let span_ns = offset_units
255        .checked_mul(unit_nanos)
256        .ok_or_else(|| offset_overflow("offset multiplication"))?;
257    base_ns
258        .checked_add(span_ns)
259        .ok_or_else(|| offset_overflow("base + offset addition"))
260}
261
262fn offset_overflow(step: &str) -> GenerateError {
263    GenerateError::Overflow(format!(
264        "temporal planner: {step} overflows the representable instant range"
265    ))
266}
267
268// =============================================================================
269// Rendering
270// =============================================================================
271
272/// Render an epoch-nanosecond instant to UTC wall-clock text, in the
273/// representation `family` expects.
274fn render_instant(
275    instant_ns: i128,
276    family: &SqlTypeFamily,
277) -> Result<GeneratedValue, GenerateError> {
278    let text = format_instant(instant_ns)?;
279    Ok(match family {
280        SqlTypeFamily::DateTime => GeneratedValue::DateTime(text),
281        _ => GeneratedValue::Text(text),
282    })
283}
284
285/// Format an epoch-nanosecond instant as UTC wall-clock text. An instant
286/// outside chrono's representable timestamp range is an error rather than a
287/// silent fallback to the 1970 epoch (which would break ordering invariants).
288fn format_instant(instant_ns: i128) -> Result<String, GenerateError> {
289    let secs = instant_ns.div_euclid(NANOS_PER_SECOND);
290    let nanos = instant_ns.rem_euclid(NANOS_PER_SECOND) as u32;
291    let secs = i64::try_from(secs).map_err(|_| instant_overflow())?;
292    let utc = DateTime::<Utc>::from_timestamp(secs, nanos).ok_or_else(instant_overflow)?;
293    Ok(utc.format("%Y-%m-%d %H:%M:%S").to_string())
294}
295
296fn instant_overflow() -> GenerateError {
297    GenerateError::Overflow(
298        "temporal planner: instant is outside the representable timestamp range".to_string(),
299    )
300}
301
302/// Render a boolean flag in the representation `family` expects.
303fn render_flag(flag: bool, family: &SqlTypeFamily) -> GeneratedValue {
304    match family {
305        SqlTypeFamily::Boolean => GeneratedValue::Boolean(flag),
306        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(flag as i128),
307        _ => GeneratedValue::Text(flag.to_string()),
308    }
309}
310
311/// Render a status label in the representation `family` expects.
312fn render_status(status: &str, _family: &SqlTypeFamily) -> GeneratedValue {
313    GeneratedValue::Text(status.to_string())
314}
315
316// =============================================================================
317// Value parsing helpers
318// =============================================================================
319
320fn unit_nanos(unit: &str) -> Option<i128> {
321    let nanos = match unit {
322        "nanosecond" | "nanoseconds" | "ns" => 1,
323        "microsecond" | "microseconds" | "us" => 1_000,
324        "millisecond" | "milliseconds" | "ms" => 1_000_000,
325        "second" | "seconds" | "sec" | "s" => NANOS_PER_SECOND,
326        "minute" | "minutes" | "min" => 60 * NANOS_PER_SECOND,
327        "hour" | "hours" | "hr" | "h" => 3_600 * NANOS_PER_SECOND,
328        "day" | "days" | "d" => 86_400 * NANOS_PER_SECOND,
329        _ => return None,
330    };
331    Some(nanos)
332}
333
334fn as_i128(value: &Value) -> Option<i128> {
335    match value {
336        Value::Number(number) => number
337            .as_i64()
338            .map(i128::from)
339            .or_else(|| number.as_u64().map(i128::from))
340            .or_else(|| number.as_f64().map(|float| float as i128)),
341        Value::String(text) => text.trim().parse::<i128>().ok(),
342        _ => None,
343    }
344}
345
346fn as_f64(value: &Value) -> Option<f64> {
347    match value {
348        Value::Number(number) => number.as_f64(),
349        Value::String(text) => text.trim().parse::<f64>().ok(),
350        _ => None,
351    }
352}
353
354/// Parse a timestamp value into epoch nanoseconds. Accepts RFC 3339
355/// (`2024-01-01T00:00:00Z`), space- or `T`-separated naive timestamps, and bare
356/// dates (interpreted as UTC midnight).
357fn as_instant_ns(value: &Value) -> Option<i128> {
358    let text = value.as_str()?.trim();
359    if let Ok(dt) = DateTime::parse_from_rfc3339(text) {
360        return Some(
361            i128::from(dt.timestamp()) * NANOS_PER_SECOND + i128::from(dt.timestamp_subsec_nanos()),
362        );
363    }
364    for format in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"] {
365        if let Ok(naive) = NaiveDateTime::parse_from_str(text, format) {
366            return Some(i128::from(naive.and_utc().timestamp()) * NANOS_PER_SECOND);
367        }
368    }
369    NaiveDate::parse_from_str(text, "%Y-%m-%d")
370        .ok()
371        .and_then(|date| date.and_hms_opt(0, 0, 0))
372        .map(|naive| i128::from(naive.and_utc().timestamp()) * NANOS_PER_SECOND)
373}
374
375fn role_name<'a>(columns: Option<&'a Value>, role: &str) -> Option<&'a str> {
376    columns?.get(role).and_then(Value::as_str)
377}
378
379fn find_column<'a>(table: &'a PortableTable, name: &str) -> Option<&'a PortableColumn> {
380    table.columns.iter().find(|column| column.name == name)
381}
382
383fn column_nullable(table: &PortableTable, name: &str) -> bool {
384    find_column(table, name).is_some_and(|column| column.nullable)
385}
386
387/// Parse a YAML value into a list of strings (from a sequence of scalars).
388fn string_list(value: Option<&Value>) -> Vec<String> {
389    match value {
390        Some(Value::Sequence(items)) => items
391            .iter()
392            .filter_map(Value::as_str)
393            .map(str::to_string)
394            .collect(),
395        _ => Vec::new(),
396    }
397}
398
399/// Parse a YAML sequence of numbers into a list of `f64` weights.
400fn number_list(value: Option<&Value>) -> Option<Vec<f64>> {
401    match value {
402        Some(Value::Sequence(items)) => items.iter().map(as_f64).collect(),
403        _ => None,
404    }
405}
406
407// =============================================================================
408// temporal.timestamps
409// =============================================================================
410
411/// Static description of the `temporal.timestamps` planner.
412pub static TEMPORAL_TIMESTAMPS_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
413    kind: "temporal.timestamps",
414    aliases: &[],
415    summary: "Coordinates created_at/updated_at (plus optional trailing timestamps) so update never precedes creation.",
416    arguments: &[
417        ArgumentSpec {
418            name: "columns",
419            required: true,
420            summary: "Maps created_at, updated_at, and optional trailing timestamp roles to columns.",
421        },
422        ArgumentSpec {
423            name: "created",
424            required: true,
425            summary: "Configures the created timestamp range or monotonic sequence.",
426        },
427        ArgumentSpec {
428            name: "update_delay",
429            required: false,
430            summary: "Configures the non-negative delay from creation to update.",
431        },
432        ArgumentSpec {
433            name: "other_delay",
434            required: false,
435            summary: "Configures the delay from creation for additional timestamp roles.",
436        },
437    ],
438    writes: ColumnScope::Configured,
439    reads: ColumnScope::None,
440    determinism: Determinism::Deterministic,
441    buffering: Buffering::Streaming,
442    verification: Verification::Supported,
443    cross_table: false,
444};
445
446/// Factory for the `temporal.timestamps` planner.
447pub struct TemporalTimestampsFactory;
448
449impl PlannerFactory for TemporalTimestampsFactory {
450    fn descriptor(&self) -> &'static PlannerDescriptor {
451        &TEMPORAL_TIMESTAMPS_DESCRIPTOR
452    }
453
454    fn compile(
455        &self,
456        config: &PlannerConfig,
457        context: &CompileContext<'_>,
458    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
459        compile_timestamps(config, context)
460            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
461    }
462}
463
464/// A resolved trailing "other" timestamp column, drawn from its own stream as
465/// `created + offset`.
466struct OtherColumn {
467    family: SqlTypeFamily,
468    rng: ChaCha8Rng,
469}
470
471struct TemporalTimestampsPlanner {
472    writes: Vec<String>,
473    created_family: SqlTypeFamily,
474    updated_family: SqlTypeFamily,
475    created_draw: InstantDraw,
476    update_delay: OffsetDraw,
477    update_unit_nanos: i128,
478    other_delay: OffsetDraw,
479    other_unit_nanos: i128,
480    others: Vec<OtherColumn>,
481    created_rng: ChaCha8Rng,
482    update_rng: ChaCha8Rng,
483    predicates: Vec<PlannerPredicate>,
484}
485
486impl CompiledPlanner for TemporalTimestampsPlanner {
487    fn writes(&self) -> &[String] {
488        &self.writes
489    }
490
491    fn generate_row(
492        &mut self,
493        row_index: u64,
494        output: &mut [GeneratedValue],
495    ) -> Result<(), GenerateError> {
496        let created_ns = self.created_draw.draw(&mut self.created_rng, row_index);
497        let update_offset = self.update_delay.draw(&mut self.update_rng);
498        let updated_ns = add_offset(created_ns, update_offset, self.update_unit_nanos)?;
499
500        output[0] = render_instant(created_ns, &self.created_family)?;
501        output[1] = render_instant(updated_ns, &self.updated_family)?;
502
503        for (slot, other) in output[2..].iter_mut().zip(self.others.iter_mut()) {
504            let offset = self.other_delay.draw(&mut other.rng);
505            let other_ns = add_offset(created_ns, offset, self.other_unit_nanos)?;
506            *slot = render_instant(other_ns, &other.family)?;
507        }
508        Ok(())
509    }
510
511    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
512        self.predicates.clone()
513    }
514}
515
516fn compile_timestamps(
517    config: &PlannerConfig,
518    context: &CompileContext<'_>,
519) -> Result<TemporalTimestampsPlanner, DiagnosticBag> {
520    const CODE: &str = crate::diagnostic::codes::TIMESTAMPS_COLUMN_MISSING.code;
521    const RANGE_CODE: &str = crate::diagnostic::codes::TIMESTAMPS_RANGE.code;
522    const DELAY_CODE: &str = crate::diagnostic::codes::TIMESTAMPS_DELAY.code;
523    let mut bag = DiagnosticBag::default();
524    let table = context.table();
525    let path = context.path();
526    let columns = config.args.get("columns");
527
528    let created_col = resolve_required(columns, "created_at", table, path, CODE, &mut bag);
529    let updated_col = resolve_required(columns, "updated_at", table, path, CODE, &mut bag);
530    // Every `columns` entry beyond `created_at`/`updated_at` is a trailing
531    // "other" timestamp, keyed by an arbitrary role name — kept as a flat
532    // mapping (not a nested `others:` list) so the pre-compile column-ownership
533    // scan (which only reads one level of `columns` mapping values) sees every
534    // owned column. `other_cols` (and so `writes()`'s trailing columns) end up
535    // in `serde_yaml_ng::Mapping` iteration order, i.e. the order the `others`
536    // keys appear in the model's YAML text. That's deterministic for a given
537    // model file (seeded runs still reproduce exactly), but reordering those
538    // keys in the YAML reorders the produced columns too.
539    let mut other_cols: Vec<&PortableColumn> = Vec::new();
540    if let Some(Value::Mapping(map)) = columns {
541        for (key, value) in map {
542            let Some(role) = key.as_str() else { continue };
543            if role == "created_at" || role == "updated_at" {
544                continue;
545            }
546            let Some(name) = value.as_str() else { continue };
547            match find_column(table, name) {
548                Some(column) => other_cols.push(column),
549                None => {
550                    bag.error(
551                        CODE,
552                        format!("{path}.columns.{role}"),
553                        format!(
554                            "temporal.timestamps `{role}` column `{name}` does not exist on table `{}`",
555                            table.name
556                        ),
557                    );
558                }
559            }
560        }
561    }
562
563    let created_draw = compile_instant_block(
564        config.args.get("created"),
565        "temporal.timestamps `created`",
566        RANGE_CODE,
567        &format!("{path}.created"),
568        &mut bag,
569    );
570    let (update_delay, update_unit_nanos) = compile_offset_block(
571        config.args.get("update_delay"),
572        "temporal.timestamps `update_delay`",
573        DELAY_CODE,
574        &format!("{path}.update_delay"),
575        &mut bag,
576    )
577    .unzip();
578    let other_delay_block = config
579        .args
580        .get("other_delay")
581        .or(config.args.get("update_delay"));
582    let (other_delay, other_unit_nanos) = compile_offset_block(
583        other_delay_block,
584        "temporal.timestamps `other_delay`",
585        DELAY_CODE,
586        &format!("{path}.other_delay"),
587        &mut bag,
588    )
589    .unzip();
590
591    if bag.has_errors() {
592        return Err(bag);
593    }
594
595    let created = created_col.expect("created resolved without errors");
596    let updated = updated_col.expect("updated resolved without errors");
597    let created_draw = created_draw.expect("created draw resolved without errors");
598    let update_delay = update_delay.expect("update delay resolved without errors");
599    let update_unit_nanos = update_unit_nanos.expect("update unit resolved without errors");
600    let other_delay = other_delay.expect("other delay resolved without errors");
601    let other_unit_nanos = other_unit_nanos.expect("other unit resolved without errors");
602
603    let mut writes = vec![created.name.clone(), updated.name.clone()];
604    let mut others = Vec::with_capacity(other_cols.len());
605    let mut other_predicates = Vec::with_capacity(other_cols.len());
606    for column in other_cols {
607        writes.push(column.name.clone());
608        others.push(OtherColumn {
609            family: column.family.clone(),
610            rng: context.rng(StreamId::operator(
611                table.name.as_str(),
612                column.name.clone(),
613                "temporal.timestamps.other",
614            )),
615        });
616        other_predicates.push(PlannerPredicate::Ordering {
617            earlier: created.name.clone(),
618            later: column.name.clone(),
619            guard: None,
620        });
621    }
622
623    let created_rng = context.rng(StreamId::operator(
624        table.name.as_str(),
625        created.name.clone(),
626        "temporal.timestamps.created",
627    ));
628    let update_rng = context.rng(StreamId::operator(
629        table.name.as_str(),
630        updated.name.clone(),
631        "temporal.timestamps.update",
632    ));
633
634    let mut predicates = vec![PlannerPredicate::Ordering {
635        earlier: created.name.clone(),
636        later: updated.name.clone(),
637        guard: None,
638    }];
639    predicates.extend(other_predicates);
640    if let InstantDraw::Range { min_ns, max_ns } = created_draw {
641        predicates.push(PlannerPredicate::InRange {
642            column: created.name.clone(),
643            min_nanos: min_ns,
644            max_nanos: max_ns,
645        });
646    }
647
648    Ok(TemporalTimestampsPlanner {
649        writes,
650        created_family: created.family.clone(),
651        updated_family: updated.family.clone(),
652        created_draw,
653        update_delay,
654        update_unit_nanos,
655        other_delay,
656        other_unit_nanos,
657        others,
658        created_rng,
659        update_rng,
660        predicates,
661    })
662}
663
664/// Resolve a required column role to its schema column, reporting a missing
665/// role or a role naming an absent column.
666fn resolve_required<'a>(
667    columns: Option<&Value>,
668    role: &str,
669    table: &'a PortableTable,
670    path: &str,
671    code: &'static str,
672    bag: &mut DiagnosticBag,
673) -> Option<&'a PortableColumn> {
674    let Some(name) = role_name(columns, role) else {
675        bag.error(
676            code,
677            format!("{path}.columns.{role}"),
678            format!("requires a `{role}` column under `columns`"),
679        );
680        return None;
681    };
682    let column = find_column(table, name);
683    if column.is_none() {
684        bag.error(
685            code,
686            format!("{path}.columns.{role}"),
687            format!(
688                "`{role}` column `{name}` does not exist on table `{}`",
689                table.name
690            ),
691        );
692    }
693    column
694}
695
696// =============================================================================
697// temporal.soft_delete
698// =============================================================================
699
700/// Static description of the `temporal.soft_delete` planner.
701///
702/// Note: the null/non-null coherence between `deleted_at` and `is_deleted` is
703/// only surfaced as a verification predicate when an `is_deleted` flag column
704/// is configured — see [`build_soft_delete_predicates`]. A `deleted_at`-only
705/// model still gets `InRange` coverage on `deleted_at`, but not the
706/// null-iff-not-deleted / non-null-iff-deleted split, since there is no guard
707/// column to state it against.
708pub static TEMPORAL_SOFT_DELETE_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
709    kind: "temporal.soft_delete",
710    aliases: &[],
711    summary: "Coordinates a deleted_at timestamp and optional is_deleted flag so a deletion probability produces a coherent null/non-null pair.",
712    arguments: &[
713        ArgumentSpec {
714            name: "columns",
715            required: true,
716            summary: "Maps the required deleted_at role and optional is_deleted role to columns.",
717        },
718        ArgumentSpec {
719            name: "deletion_probability",
720            required: false,
721            summary: "Probability that a generated row is marked deleted.",
722        },
723        ArgumentSpec {
724            name: "deleted_range",
725            required: true,
726            summary: "Configures the range or monotonic sequence for deletion timestamps.",
727        },
728    ],
729    writes: ColumnScope::Configured,
730    reads: ColumnScope::None,
731    determinism: Determinism::Deterministic,
732    buffering: Buffering::Streaming,
733    verification: Verification::Supported,
734    cross_table: false,
735};
736
737/// Factory for the `temporal.soft_delete` planner.
738pub struct TemporalSoftDeleteFactory;
739
740impl PlannerFactory for TemporalSoftDeleteFactory {
741    fn descriptor(&self) -> &'static PlannerDescriptor {
742        &TEMPORAL_SOFT_DELETE_DESCRIPTOR
743    }
744
745    fn compile(
746        &self,
747        config: &PlannerConfig,
748        context: &CompileContext<'_>,
749    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
750        compile_soft_delete(config, context)
751            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
752    }
753}
754
755struct FlagColumn {
756    name: String,
757    family: SqlTypeFamily,
758}
759
760struct TemporalSoftDeletePlanner {
761    writes: Vec<String>,
762    deleted_at_family: SqlTypeFamily,
763    flag: Option<FlagColumn>,
764    deletion_probability: f64,
765    deleted_draw: InstantDraw,
766    decision_rng: ChaCha8Rng,
767    instant_rng: ChaCha8Rng,
768    predicates: Vec<PlannerPredicate>,
769}
770
771impl CompiledPlanner for TemporalSoftDeletePlanner {
772    fn writes(&self) -> &[String] {
773        &self.writes
774    }
775
776    fn generate_row(
777        &mut self,
778        row_index: u64,
779        output: &mut [GeneratedValue],
780    ) -> Result<(), GenerateError> {
781        // Draw both streams unconditionally, in a fixed order, so a seeded run
782        // reproduces regardless of which rows land deleted.
783        let decision = self.decision_rng.random::<f64>();
784        let deleted_ns = self.deleted_draw.draw(&mut self.instant_rng, row_index);
785        let is_deleted = self.deletion_probability > 0.0 && decision < self.deletion_probability;
786
787        output[0] = if is_deleted {
788            render_instant(deleted_ns, &self.deleted_at_family)?
789        } else {
790            GeneratedValue::Null
791        };
792        if self.flag.is_some() {
793            output[1] = render_flag(is_deleted, &output_flag_family(&self.flag));
794        }
795        Ok(())
796    }
797
798    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
799        self.predicates.clone()
800    }
801}
802
803fn output_flag_family(flag: &Option<FlagColumn>) -> SqlTypeFamily {
804    flag.as_ref()
805        .map(|f| f.family.clone())
806        .unwrap_or(SqlTypeFamily::Boolean)
807}
808
809fn compile_soft_delete(
810    config: &PlannerConfig,
811    context: &CompileContext<'_>,
812) -> Result<TemporalSoftDeletePlanner, DiagnosticBag> {
813    const CODE: &str = crate::diagnostic::codes::SOFT_DELETE_COLUMN_MISSING.code;
814    const RANGE_CODE: &str = crate::diagnostic::codes::SOFT_DELETE_RANGE.code;
815    const NULLABILITY_CODE: &str = crate::diagnostic::codes::SOFT_DELETE_NULLABILITY.code;
816    let mut bag = DiagnosticBag::default();
817    let table = context.table();
818    let path = context.path();
819    let columns = config.args.get("columns");
820
821    let deleted_col = resolve_required(columns, "deleted_at", table, path, CODE, &mut bag);
822    let flag_col = role_name(columns, "is_deleted").and_then(|name| {
823        find_column(table, name).or_else(|| {
824            bag.error(
825                CODE,
826                format!("{path}.columns.is_deleted"),
827                format!(
828                    "temporal.soft_delete `is_deleted` column `{name}` does not exist on table `{}`",
829                    table.name
830                ),
831            );
832            None
833        })
834    });
835
836    let deletion_probability = config
837        .args
838        .get("deletion_probability")
839        .and_then(as_f64)
840        .unwrap_or(0.0)
841        .clamp(0.0, 1.0);
842
843    // A non-nullable deleted_at cannot represent a row that isn't deleted,
844    // which happens whenever some probability mass falls on "not deleted".
845    if deletion_probability < 1.0 {
846        if let Some(deleted) = deleted_col {
847            if !deleted.nullable {
848                bag.error(
849                    NULLABILITY_CODE,
850                    format!("{path}.deletion_probability"),
851                    format!(
852                        "temporal.soft_delete has deletion_probability {deletion_probability} but its `deleted_at` column `{}` is not nullable; a non-deleted row needs a null deleted_at",
853                        deleted.name
854                    ),
855                );
856            }
857        }
858    }
859
860    let deleted_draw = compile_instant_block(
861        config.args.get("deleted_range"),
862        "temporal.soft_delete `deleted_range`",
863        RANGE_CODE,
864        &format!("{path}.deleted_range"),
865        &mut bag,
866    );
867
868    if bag.has_errors() {
869        return Err(bag);
870    }
871
872    let deleted = deleted_col.expect("deleted resolved without errors");
873    let deleted_draw = deleted_draw.expect("deleted draw resolved without errors");
874
875    let mut writes = vec![deleted.name.clone()];
876    let flag = flag_col.map(|column| {
877        writes.push(column.name.clone());
878        FlagColumn {
879            name: column.name.clone(),
880            family: column.family.clone(),
881        }
882    });
883
884    let decision_rng = context.rng(StreamId::operator(
885        table.name.as_str(),
886        deleted.name.clone(),
887        "temporal.soft_delete.decision",
888    ));
889    let instant_rng = context.rng(StreamId::operator(
890        table.name.as_str(),
891        deleted.name.clone(),
892        "temporal.soft_delete.instant",
893    ));
894
895    let predicates = build_soft_delete_predicates(
896        &deleted.name,
897        flag.as_ref(),
898        deletion_probability,
899        deleted_draw,
900    );
901
902    Ok(TemporalSoftDeletePlanner {
903        writes,
904        deleted_at_family: deleted.family.clone(),
905        flag,
906        deletion_probability,
907        deleted_draw,
908        decision_rng,
909        instant_rng,
910        predicates,
911    })
912}
913
914fn build_soft_delete_predicates(
915    deleted_at: &str,
916    flag: Option<&FlagColumn>,
917    _deletion_probability: f64,
918    deleted_draw: InstantDraw,
919) -> Vec<PlannerPredicate> {
920    let mut predicates = Vec::new();
921
922    // Every `PlannerPredicate::NullWhen`/`NotNullWhen` requires a guard, so the
923    // null/non-null coherence invariant is only statable when an explicit flag
924    // column names which rows are which (mirrors `temporal.interval`'s open
925    // flag handling: without a flag, "null when open" would be a tautology
926    // over the column itself).
927    if let Some(flag) = flag {
928        predicates.push(PlannerPredicate::NotNullWhen {
929            column: deleted_at.to_string(),
930            guard: PredicateGuard::Flag {
931                column: flag.name.clone(),
932                value: true,
933            },
934        });
935        predicates.push(PlannerPredicate::NullWhen {
936            column: deleted_at.to_string(),
937            guard: PredicateGuard::Flag {
938                column: flag.name.clone(),
939                value: false,
940            },
941        });
942    }
943
944    if let InstantDraw::Range { min_ns, max_ns } = deleted_draw {
945        predicates.push(PlannerPredicate::InRange {
946            column: deleted_at.to_string(),
947            min_nanos: min_ns,
948            max_nanos: max_ns,
949        });
950    }
951
952    predicates
953}
954
955// =============================================================================
956// temporal.lifecycle
957// =============================================================================
958
959/// Static description of the `temporal.lifecycle` planner.
960pub static TEMPORAL_LIFECYCLE_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
961    kind: "temporal.lifecycle",
962    aliases: &[],
963    summary: "Coordinates a status column that only reaches legal states, each carrying a correctly-ordered timestamp.",
964    arguments: &[
965        ArgumentSpec {
966            name: "columns",
967            required: true,
968            summary: "Maps the status role and each lifecycle state to its timestamp column.",
969        },
970        ArgumentSpec {
971            name: "states",
972            required: true,
973            summary: "Ordered lifecycle state vocabulary.",
974        },
975        ArgumentSpec {
976            name: "weights",
977            required: false,
978            summary: "Terminal-state weights in the same order as states.",
979        },
980        ArgumentSpec {
981            name: "start",
982            required: true,
983            summary: "Configures the first lifecycle timestamp range or sequence.",
984        },
985        ArgumentSpec {
986            name: "step",
987            required: false,
988            summary: "Configures the non-negative delay between lifecycle states.",
989        },
990    ],
991    writes: ColumnScope::Configured,
992    reads: ColumnScope::None,
993    determinism: Determinism::Deterministic,
994    buffering: Buffering::Streaming,
995    verification: Verification::Supported,
996    cross_table: false,
997};
998
999/// Factory for the `temporal.lifecycle` planner.
1000pub struct TemporalLifecycleFactory;
1001
1002impl PlannerFactory for TemporalLifecycleFactory {
1003    fn descriptor(&self) -> &'static PlannerDescriptor {
1004        &TEMPORAL_LIFECYCLE_DESCRIPTOR
1005    }
1006
1007    fn compile(
1008        &self,
1009        config: &PlannerConfig,
1010        context: &CompileContext<'_>,
1011    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
1012        compile_lifecycle(config, context)
1013            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
1014    }
1015}
1016
1017/// A state timestamp column mapped to its position in the legal chain.
1018struct StateSlot {
1019    /// Index into the planner's `states` chain.
1020    state_index: usize,
1021    name: String,
1022    family: SqlTypeFamily,
1023}
1024
1025struct TemporalLifecyclePlanner {
1026    writes: Vec<String>,
1027    status_family: SqlTypeFamily,
1028    states: Vec<String>,
1029    /// Normalized terminal-state weights, parallel to `states`.
1030    weights: Vec<f64>,
1031    /// Timestamp slots, in the write order after `status`.
1032    slots: Vec<StateSlot>,
1033    start_draw: InstantDraw,
1034    step_delay: OffsetDraw,
1035    step_unit_nanos: i128,
1036    terminal_rng: ChaCha8Rng,
1037    start_rng: ChaCha8Rng,
1038    step_rng: ChaCha8Rng,
1039    predicates: Vec<PlannerPredicate>,
1040}
1041
1042impl CompiledPlanner for TemporalLifecyclePlanner {
1043    fn writes(&self) -> &[String] {
1044        &self.writes
1045    }
1046
1047    fn generate_row(
1048        &mut self,
1049        row_index: u64,
1050        output: &mut [GeneratedValue],
1051    ) -> Result<(), GenerateError> {
1052        // Every stream is drawn unconditionally and in a fixed order — the
1053        // terminal pick, the base instant, then one step offset per possible
1054        // transition — so a seeded run reproduces regardless of which state a
1055        // row terminates at.
1056        let terminal_pick = self.terminal_rng.random::<f64>();
1057        let base_ns = self.start_draw.draw(&mut self.start_rng, row_index);
1058        let mut instants = Vec::with_capacity(self.states.len());
1059        instants.push(base_ns);
1060        for _ in 1..self.states.len() {
1061            let offset = self.step_delay.draw(&mut self.step_rng);
1062            let previous = *instants
1063                .last()
1064                .expect("instants seeded with the base instant");
1065            instants.push(add_offset(previous, offset, self.step_unit_nanos)?);
1066        }
1067
1068        let terminal_index = pick_weighted_index(&self.weights, terminal_pick);
1069
1070        output[0] = render_status(&self.states[terminal_index], &self.status_family);
1071        for (slot, cell) in self.slots.iter().zip(output[1..].iter_mut()) {
1072            *cell = if slot.state_index <= terminal_index {
1073                render_instant(instants[slot.state_index], &slot.family)?
1074            } else {
1075                GeneratedValue::Null
1076            };
1077        }
1078        Ok(())
1079    }
1080
1081    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
1082        self.predicates.clone()
1083    }
1084}
1085
1086/// Select an index from `weights` (assumed non-negative, summing to > 0)
1087/// using a uniform draw `r` in `[0, 1)`.
1088fn pick_weighted_index(weights: &[f64], r: f64) -> usize {
1089    let total: f64 = weights.iter().sum();
1090    if total <= 0.0 || weights.is_empty() {
1091        return 0;
1092    }
1093    let point = r * total;
1094    let mut cumulative = 0.0;
1095    for (index, weight) in weights.iter().enumerate() {
1096        cumulative += weight;
1097        if point < cumulative {
1098            return index;
1099        }
1100    }
1101    weights.len() - 1
1102}
1103
1104fn compile_lifecycle(
1105    config: &PlannerConfig,
1106    context: &CompileContext<'_>,
1107) -> Result<TemporalLifecyclePlanner, DiagnosticBag> {
1108    const COLUMN_CODE: &str = crate::diagnostic::codes::LIFECYCLE_COLUMN_MISSING.code;
1109    const STATES_CODE: &str = crate::diagnostic::codes::LIFECYCLE_STATES.code;
1110    const VOCAB_CODE: &str = crate::diagnostic::codes::LIFECYCLE_STATUS_VOCABULARY.code;
1111    const WEIGHTS_CODE: &str = crate::diagnostic::codes::LIFECYCLE_WEIGHTS.code;
1112    const RANGE_CODE: &str = crate::diagnostic::codes::LIFECYCLE_RANGE.code;
1113    const STEP_CODE: &str = crate::diagnostic::codes::LIFECYCLE_STEP.code;
1114    const NULLABILITY_CODE: &str = crate::diagnostic::codes::LIFECYCLE_NULLABILITY.code;
1115    let mut bag = DiagnosticBag::default();
1116    let table = context.table();
1117    let path = context.path();
1118    let columns = config.args.get("columns");
1119
1120    let status_col = resolve_required(columns, "status", table, path, COLUMN_CODE, &mut bag);
1121
1122    let states = string_list(config.args.get("states"));
1123    if states.is_empty() {
1124        bag.error(
1125            STATES_CODE,
1126            format!("{path}.states"),
1127            "temporal.lifecycle requires a non-empty `states` chain".to_string(),
1128        );
1129    }
1130    let mut unique_states: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1131    for state in &states {
1132        if !unique_states.insert(state.as_str()) {
1133            bag.error(
1134                STATES_CODE,
1135                format!("{path}.states"),
1136                format!("temporal.lifecycle `states` lists `{state}` more than once"),
1137            );
1138        }
1139    }
1140
1141    // Every `columns` entry beyond `status` maps a state name to its timestamp
1142    // column — kept as a flat mapping (not a nested `timestamps:` map) so the
1143    // pre-compile column-ownership scan (which only reads one level of
1144    // `columns` mapping values) sees every owned column.
1145    let mut timestamp_slots: Vec<StateSlot> = Vec::new();
1146    if let Some(Value::Mapping(map)) = columns {
1147        for (key, value) in map {
1148            let Some(state_name) = key.as_str() else {
1149                continue;
1150            };
1151            if state_name == "status" {
1152                continue;
1153            }
1154            let Some(column_name) = value.as_str() else {
1155                continue;
1156            };
1157            let Some(state_index) = states.iter().position(|s| s == state_name) else {
1158                bag.error(
1159                    VOCAB_CODE,
1160                    format!("{path}.columns.{state_name}"),
1161                    format!(
1162                        "temporal.lifecycle `columns` names state `{state_name}`, which is not in `states`"
1163                    ),
1164                );
1165                continue;
1166            };
1167            match find_column(table, column_name) {
1168                Some(column) => timestamp_slots.push(StateSlot {
1169                    state_index,
1170                    name: column.name.clone(),
1171                    family: column.family.clone(),
1172                }),
1173                None => {
1174                    bag.error(
1175                        COLUMN_CODE,
1176                        format!("{path}.columns.{state_name}"),
1177                        format!(
1178                            "temporal.lifecycle `{state_name}` column `{column_name}` does not exist on table `{}`",
1179                            table.name
1180                        ),
1181                    );
1182                }
1183            }
1184        }
1185    }
1186    timestamp_slots.sort_by_key(|slot| slot.state_index);
1187
1188    let weights = match number_list(config.args.get("weights")) {
1189        Some(weights) if weights.len() == states.len() => {
1190            if weights.iter().any(|w| !w.is_finite() || *w < 0.0) {
1191                bag.error(
1192                    WEIGHTS_CODE,
1193                    format!("{path}.weights"),
1194                    "temporal.lifecycle `weights` must be finite and non-negative".to_string(),
1195                );
1196                None
1197            } else if weights.iter().sum::<f64>() <= 0.0 {
1198                bag.error(
1199                    WEIGHTS_CODE,
1200                    format!("{path}.weights"),
1201                    "temporal.lifecycle `weights` sum to zero; at least one weight must be positive"
1202                        .to_string(),
1203                );
1204                None
1205            } else {
1206                Some(weights)
1207            }
1208        }
1209        Some(_) => {
1210            bag.error(
1211                WEIGHTS_CODE,
1212                format!("{path}.weights"),
1213                "temporal.lifecycle `weights` must have exactly one entry per `states` element"
1214                    .to_string(),
1215            );
1216            None
1217        }
1218        None if !states.is_empty() => Some(vec![1.0; states.len()]),
1219        None => None,
1220    };
1221
1222    // Impossible nullability: a state's timestamp column is non-nullable, but
1223    // some positive probability mass terminates before reaching that state,
1224    // leaving the column null.
1225    if let Some(weights) = &weights {
1226        let total: f64 = weights.iter().sum();
1227        let mut prefix = 0.0;
1228        for (index, state) in states.iter().enumerate() {
1229            if index > 0 && prefix > 0.0 && total > 0.0 {
1230                if let Some(slot) = timestamp_slots.iter().find(|s| s.state_index == index) {
1231                    if !column_nullable(table, &slot.name) {
1232                        bag.error(
1233                            NULLABILITY_CODE,
1234                            format!("{path}.columns.timestamps.{state}"),
1235                            format!(
1236                                "temporal.lifecycle `{state}` timestamp column `{}` is not nullable, but a row that terminates before `{state}` leaves it null",
1237                                slot.name
1238                            ),
1239                        );
1240                    }
1241                }
1242            }
1243            prefix += weights[index];
1244        }
1245    }
1246
1247    let start_draw = compile_instant_block(
1248        config.args.get("start"),
1249        "temporal.lifecycle `start`",
1250        RANGE_CODE,
1251        &format!("{path}.start"),
1252        &mut bag,
1253    );
1254    let (step_delay, step_unit_nanos) = compile_offset_block(
1255        config.args.get("step"),
1256        "temporal.lifecycle `step`",
1257        STEP_CODE,
1258        &format!("{path}.step"),
1259        &mut bag,
1260    )
1261    .unzip();
1262
1263    if bag.has_errors() {
1264        return Err(bag);
1265    }
1266
1267    let status = status_col.expect("status resolved without errors");
1268    let weights = weights.expect("weights resolved without errors");
1269    let start_draw = start_draw.expect("start draw resolved without errors");
1270    let step_delay = step_delay.expect("step delay resolved without errors");
1271    let step_unit_nanos = step_unit_nanos.expect("step unit resolved without errors");
1272
1273    let mut writes = vec![status.name.clone()];
1274    writes.extend(timestamp_slots.iter().map(|slot| slot.name.clone()));
1275
1276    let terminal_rng = context.rng(StreamId::operator(
1277        table.name.as_str(),
1278        status.name.clone(),
1279        "temporal.lifecycle.terminal",
1280    ));
1281    let start_rng = context.rng(StreamId::operator(
1282        table.name.as_str(),
1283        status.name.clone(),
1284        "temporal.lifecycle.start",
1285    ));
1286    let step_rng = context.rng(StreamId::operator(
1287        table.name.as_str(),
1288        status.name.clone(),
1289        "temporal.lifecycle.step",
1290    ));
1291
1292    let predicates =
1293        build_lifecycle_predicates(&status.name, &states, &timestamp_slots, start_draw);
1294
1295    Ok(TemporalLifecyclePlanner {
1296        writes,
1297        status_family: status.family.clone(),
1298        states,
1299        weights,
1300        slots: timestamp_slots,
1301        start_draw,
1302        step_delay,
1303        step_unit_nanos,
1304        terminal_rng,
1305        start_rng,
1306        step_rng,
1307        predicates,
1308    })
1309}
1310
1311fn build_lifecycle_predicates(
1312    status: &str,
1313    states: &[String],
1314    slots: &[StateSlot],
1315    start_draw: InstantDraw,
1316) -> Vec<PlannerPredicate> {
1317    let mut predicates = Vec::new();
1318
1319    for slot in slots {
1320        for (index, state) in states.iter().enumerate() {
1321            let guard = PredicateGuard::Equals {
1322                column: status.to_string(),
1323                value: state.clone(),
1324            };
1325            if index >= slot.state_index {
1326                predicates.push(PlannerPredicate::NotNullWhen {
1327                    column: slot.name.clone(),
1328                    guard,
1329                });
1330            } else {
1331                predicates.push(PlannerPredicate::NullWhen {
1332                    column: slot.name.clone(),
1333                    guard,
1334                });
1335            }
1336        }
1337    }
1338
1339    for pair in slots.windows(2) {
1340        predicates.push(PlannerPredicate::Ordering {
1341            earlier: pair[0].name.clone(),
1342            later: pair[1].name.clone(),
1343            guard: None,
1344        });
1345    }
1346
1347    if let (InstantDraw::Range { min_ns, max_ns }, Some(first)) =
1348        (start_draw, slots.iter().find(|slot| slot.state_index == 0))
1349    {
1350        predicates.push(PlannerPredicate::InRange {
1351            column: first.name.clone(),
1352            min_nanos: min_ns,
1353            max_nanos: max_ns,
1354        });
1355    }
1356
1357    predicates
1358}
1359
1360// =============================================================================
1361// hierarchy.tree
1362// =============================================================================
1363
1364/// Static description of the `hierarchy.tree` planner.
1365///
1366/// A same-table planner despite touching a self-referential foreign key: it
1367/// owns exactly the `parent` column and references only EARLIER rows of its own
1368/// table, so it is `cross_table: false` and needs no cross-table fact injection.
1369pub static HIERARCHY_TREE_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
1370    kind: "hierarchy.tree",
1371    aliases: &[],
1372    summary: "Builds a self-referential parent_id tree: configurable-ratio roots (null parent) and bounded-depth, bounded-branching descendants that reference an earlier row.",
1373    arguments: &[
1374        ArgumentSpec {
1375            name: "columns",
1376            required: true,
1377            summary: "Maps the required `parent` role to the nullable self-reference column, and an optional `depth` role to a column that receives each row's depth (roots = 0).",
1378        },
1379        ArgumentSpec {
1380            name: "relationship",
1381            required: false,
1382            summary: "Self-relationship used to derive the referenced dense key recipe.",
1383        },
1384        ArgumentSpec {
1385            name: "key",
1386            required: false,
1387            summary: "Explicit dense key start and step, overriding relationship-derived values.",
1388        },
1389        ArgumentSpec {
1390            name: "root_ratio",
1391            required: false,
1392            summary: "Fraction of rows generated as roots with a null parent.",
1393        },
1394        ArgumentSpec {
1395            name: "max_depth",
1396            required: false,
1397            summary: "The deepest node's depth; roots are depth 0, so depths span 0..=max_depth.",
1398        },
1399        ArgumentSpec {
1400            name: "max_branching",
1401            required: false,
1402            summary: "Maximum number of direct children per parent; omitted means unbounded.",
1403        },
1404    ],
1405    writes: ColumnScope::Configured,
1406    reads: ColumnScope::None,
1407    determinism: Determinism::Deterministic,
1408    buffering: Buffering::Streaming,
1409    verification: Verification::Supported,
1410    cross_table: false,
1411};
1412
1413/// Factory for the `hierarchy.tree` planner.
1414pub struct HierarchyTreeFactory;
1415
1416impl PlannerFactory for HierarchyTreeFactory {
1417    fn descriptor(&self) -> &'static PlannerDescriptor {
1418        &HIERARCHY_TREE_DESCRIPTOR
1419    }
1420
1421    fn compile(
1422        &self,
1423        config: &PlannerConfig,
1424        context: &CompileContext<'_>,
1425    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
1426        compile_tree(config, context).map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
1427    }
1428}
1429
1430/// The compiled `hierarchy.tree` planner. Rows are generated in index order, so
1431/// the planner accumulates the depth and remaining branching capacity of every
1432/// row it has already produced and only ever attaches a new non-root to an
1433/// earlier, still-eligible row.
1434struct HierarchyTreePlanner {
1435    writes: Vec<String>,
1436    parent_family: SqlTypeFamily,
1437    /// The family of the optional `depth` output column; `None` when no `depth`
1438    /// role is mapped. When set, each row's depth (roots = 0) is written to it.
1439    depth_family: Option<SqlTypeFamily>,
1440    root_ratio: f64,
1441    max_depth: u32,
1442    /// Maximum children per node; `None` is unbounded.
1443    max_branching: Option<u32>,
1444    /// The self primary key's dense recipe: row `n`'s key is `key_start + n *
1445    /// key_step`. A non-root at row `n` references an earlier row `j`'s key.
1446    key_start: i128,
1447    key_step: i128,
1448    decision_rng: ChaCha8Rng,
1449    select_rng: ChaCha8Rng,
1450    /// The frontier of rows that can still parent a new child (depth < max_depth
1451    /// and, when bounded, remaining branching > 0). A node's depth and remaining
1452    /// branching are only ever read while it is eligible, so this is the *only*
1453    /// per-node state kept — memory stays bounded by the live frontier, not the
1454    /// total row count (`Buffering::Streaming`).
1455    eligible: Vec<EligibleNode>,
1456    predicates: Vec<PlannerPredicate>,
1457}
1458
1459/// A row still on the tree frontier: its row index (for the child's parent key),
1460/// its depth, and how many more children it may still take.
1461struct EligibleNode {
1462    index: usize,
1463    depth: u32,
1464    remaining: u32,
1465}
1466
1467impl HierarchyTreePlanner {
1468    /// The dense key of the row at `row_index`.
1469    fn key_of(&self, row_index: usize) -> i128 {
1470        self.key_start + self.key_step * row_index as i128
1471    }
1472
1473    /// Render a parent key value in the representation the parent column expects.
1474    fn render_key(&self, key: i128) -> GeneratedValue {
1475        match self.parent_family {
1476            SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(key),
1477            _ => GeneratedValue::Text(key.to_string()),
1478        }
1479    }
1480}
1481
1482impl CompiledPlanner for HierarchyTreePlanner {
1483    fn writes(&self) -> &[String] {
1484        &self.writes
1485    }
1486
1487    fn generate_row(
1488        &mut self,
1489        row_index: u64,
1490        output: &mut [GeneratedValue],
1491    ) -> Result<(), GenerateError> {
1492        // Draw both streams unconditionally and in a fixed order, so a seeded run
1493        // reproduces regardless of whether a row lands a root.
1494        let decision = self.decision_rng.random::<f64>();
1495        let selection = self.select_rng.random::<f64>();
1496
1497        let n = row_index as usize;
1498        // The first row has no earlier row to attach to and is always a root;
1499        // otherwise a row is a root by the configured ratio, or forcibly when no
1500        // eligible parent remains within the depth/branching bounds.
1501        let is_root = n == 0 || decision < self.root_ratio || self.eligible.is_empty();
1502
1503        let (parent_value, depth) = if is_root {
1504            (GeneratedValue::Null, 0)
1505        } else {
1506            let slot = (selection * self.eligible.len() as f64) as usize;
1507            let slot = slot.min(self.eligible.len() - 1);
1508            let parent_index = self.eligible[slot].index;
1509            let depth = self.eligible[slot].depth + 1;
1510            if self.max_branching.is_some() {
1511                self.eligible[slot].remaining -= 1;
1512                if self.eligible[slot].remaining == 0 {
1513                    self.eligible.swap_remove(slot);
1514                }
1515            }
1516            (self.render_key(self.key_of(parent_index)), depth)
1517        };
1518
1519        // A node can parent future children only while it stays under the depth
1520        // bound (a child would sit at `depth + 1`).
1521        if depth < self.max_depth {
1522            self.eligible.push(EligibleNode {
1523                index: n,
1524                depth,
1525                remaining: self.max_branching.unwrap_or(u32::MAX).max(1),
1526            });
1527        }
1528
1529        output[0] = parent_value;
1530        // Optional depth output (roots = 0), in the representation the column
1531        // expects. `writes` places it at slot 1 when a `depth` role is mapped.
1532        if let Some(family) = &self.depth_family {
1533            output[1] = match family {
1534                SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => {
1535                    GeneratedValue::Integer(i128::from(depth))
1536                }
1537                _ => GeneratedValue::Text(depth.to_string()),
1538            };
1539        }
1540        Ok(())
1541    }
1542
1543    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
1544        self.predicates.clone()
1545    }
1546}
1547
1548fn compile_tree(
1549    config: &PlannerConfig,
1550    context: &CompileContext<'_>,
1551) -> Result<HierarchyTreePlanner, DiagnosticBag> {
1552    const COLUMN_CODE: &str = crate::diagnostic::codes::TREE_COLUMN_MISSING.code;
1553    const DEPTH_CODE: &str = crate::diagnostic::codes::TREE_DEPTH.code;
1554    const ROOT_CODE: &str = crate::diagnostic::codes::TREE_ROOT_RATIO.code;
1555    const BRANCH_CODE: &str = crate::diagnostic::codes::TREE_BRANCHING.code;
1556    const CYCLE_CODE: &str = crate::diagnostic::codes::TREE_REQUIRED_CYCLE.code;
1557    let mut bag = DiagnosticBag::default();
1558    let table = context.table();
1559    let path = context.path();
1560    let columns = config.args.get("columns");
1561
1562    let parent_col = resolve_required(columns, "parent", table, path, COLUMN_CODE, &mut bag);
1563
1564    // A non-nullable self-FK cannot hold the null a root needs, so every row
1565    // would have to reference another row: a required non-null self cycle with no
1566    // constructible seed. (A nullable parent lets roots be null, and every
1567    // non-root references an already-generated earlier row, so the FK is
1568    // satisfiable without deferral.)
1569    if let Some(parent) = parent_col {
1570        if !parent.nullable {
1571            bag.error(
1572                CYCLE_CODE,
1573                format!("{path}.columns.parent"),
1574                format!(
1575                    "hierarchy.tree parent column `{}` is not nullable, so tree roots (which need a null parent) cannot be represented; make it nullable to allow a constructible root seed",
1576                    parent.name
1577                ),
1578            );
1579        }
1580    }
1581
1582    let root_ratio = config
1583        .args
1584        .get("root_ratio")
1585        .and_then(as_f64)
1586        .unwrap_or(0.1);
1587    if !(0.0..=1.0).contains(&root_ratio) {
1588        bag.error(
1589            ROOT_CODE,
1590            format!("{path}.root_ratio"),
1591            format!("hierarchy.tree `root_ratio` {root_ratio} must be within [0.0, 1.0]"),
1592        );
1593    }
1594
1595    let max_depth = config.args.get("max_depth").and_then(as_i128).unwrap_or(6);
1596    if max_depth < 1 {
1597        bag.error(
1598            DEPTH_CODE,
1599            format!("{path}.max_depth"),
1600            format!("hierarchy.tree `max_depth` {max_depth} must be at least 1"),
1601        );
1602    }
1603
1604    let max_branching = match config.args.get("max_branching").and_then(as_i128) {
1605        None => None,
1606        Some(branching) if branching >= 1 => Some(branching as u32),
1607        Some(branching) => {
1608            bag.error(
1609                BRANCH_CODE,
1610                format!("{path}.max_branching"),
1611                format!(
1612                    "hierarchy.tree `max_branching` {branching} must be at least 1 (omit it for unbounded branching)"
1613                ),
1614            );
1615            None
1616        }
1617    };
1618
1619    // Derive the emitted parent_id key recipe from the ACTUAL primary key the
1620    // self-FK relationship references (a non-default `sequence` start/step must
1621    // be honored, or the produced parent_id values would not match any real
1622    // id). The compiler injects the referenced key's dense recipe under
1623    // `RELATION_FACTS_KEY`; an explicit `key:` block still wins over it, and a
1624    // plain default PK falls back to `1, 2, …`.
1625    let facts = config.args.get(RELATION_FACTS_KEY);
1626    let (derived_start, derived_step) = config
1627        .args
1628        .get("relationship")
1629        .and_then(Value::as_str)
1630        .and_then(|name| {
1631            facts
1632                .and_then(|f| f.get("relationships"))
1633                .and_then(|r| r.get(name))
1634        })
1635        .filter(|fact| fact.get("dense").and_then(Value::as_bool) == Some(true))
1636        .map(|fact| {
1637            (
1638                fact.get("start").and_then(as_i128).unwrap_or(1),
1639                fact.get("step").and_then(as_i128).unwrap_or(1),
1640            )
1641        })
1642        .unwrap_or((1, 1));
1643
1644    let key = config.args.get("key");
1645    let key_start = key
1646        .and_then(|k| k.get("start"))
1647        .and_then(as_i128)
1648        .unwrap_or(derived_start);
1649    let key_step = key
1650        .and_then(|k| k.get("step"))
1651        .and_then(as_i128)
1652        .unwrap_or(derived_step);
1653
1654    if bag.has_errors() {
1655        return Err(bag);
1656    }
1657
1658    // An optional `depth` role: the planner writes each row's depth (roots = 0)
1659    // into the mapped column, so a tree can carry a materialized depth level.
1660    let depth = match columns.and_then(|c| c.get("depth")).and_then(Value::as_str) {
1661        None => None,
1662        Some(depth_name) => match table.columns.iter().find(|col| col.name == depth_name) {
1663            Some(col) => Some(col.clone()),
1664            None => {
1665                bag.error(
1666                    COLUMN_CODE,
1667                    format!("{path}.columns.depth"),
1668                    format!(
1669                        "hierarchy.tree `depth` column `{depth_name}` does not exist on table `{}`",
1670                        table.name
1671                    ),
1672                );
1673                None
1674            }
1675        },
1676    };
1677
1678    if bag.has_errors() {
1679        return Err(bag);
1680    }
1681
1682    let parent = parent_col.expect("parent resolved without errors");
1683    let mut writes = vec![parent.name.clone()];
1684    if let Some(depth) = &depth {
1685        writes.push(depth.name.clone());
1686    }
1687    let depth_family = depth.map(|col| col.family);
1688    let mut predicates = Vec::new();
1689    // Every produced key is `key_start + step * index` with non-negative index;
1690    // with a non-negative start and step the parent column is never negative
1691    // (roots are null, which the verifier does not treat as negative).
1692    if key_start >= 0 && key_step >= 0 {
1693        predicates.push(PlannerPredicate::NonNegative {
1694            columns: vec![parent.name.clone()],
1695        });
1696    }
1697
1698    let decision_rng = context.rng(StreamId::operator(
1699        table.name.as_str(),
1700        parent.name.clone(),
1701        "hierarchy.tree.decision",
1702    ));
1703    let select_rng = context.rng(StreamId::operator(
1704        table.name.as_str(),
1705        parent.name.clone(),
1706        "hierarchy.tree.select",
1707    ));
1708
1709    Ok(HierarchyTreePlanner {
1710        writes,
1711        parent_family: parent.family.clone(),
1712        depth_family,
1713        root_ratio,
1714        max_depth: max_depth as u32,
1715        max_branching,
1716        key_start,
1717        key_step,
1718        decision_rng,
1719        select_rng,
1720        eligible: Vec::new(),
1721        predicates,
1722    })
1723}
1724
1725// =============================================================================
1726// Cross-table FK-side planners: shared machinery
1727// =============================================================================
1728
1729/// The private config key under which the compiler injects the resolved
1730/// parent-key facts an FK-side cross-table planner (`relation.junction_pair`,
1731/// `relation.tenant_family`, `relation.polymorphic_pair`) needs to produce valid
1732/// keys for tables it references but cannot see on its own. Documented as an
1733/// internal contract between [`super::super::compiler`] and these planners.
1734pub const RELATION_FACTS_KEY: &str = "__relation_facts";
1735
1736/// A referenced table's resolved key domain: a dense integer sequence
1737/// `start, start + step, …`, `count` rows long. Row `i` (0-based) renders the
1738/// key `start + i * step`.
1739#[derive(Clone, Copy)]
1740struct DenseKey {
1741    start: i128,
1742    step: i128,
1743    count: u64,
1744}
1745
1746impl DenseKey {
1747    /// The key of the referenced row at 0-based index `index`.
1748    fn key_at(&self, index: u64) -> i128 {
1749        self.start + self.step * index as i128
1750    }
1751}
1752
1753/// Render an integer key value in the representation the FK column expects.
1754fn render_key(key: i128, family: &SqlTypeFamily) -> GeneratedValue {
1755    match family {
1756        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(key),
1757        _ => GeneratedValue::Text(key.to_string()),
1758    }
1759}
1760
1761/// Resolve a relationship's injected fact into a [`DenseKey`], or report why it
1762/// cannot serve as a valid integer key domain (unknown relationship, or a
1763/// non-dense parent key such as a UUID).
1764fn dense_key_from_relationship(
1765    facts: Option<&Value>,
1766    rel_name: &str,
1767    planner: &str,
1768    role: &str,
1769    codes: [&'static str; 2],
1770    path: &str,
1771    bag: &mut DiagnosticBag,
1772) -> Option<DenseKey> {
1773    let [missing_code, key_code] = codes;
1774    let fact = facts
1775        .and_then(|f| f.get("relationships"))
1776        .and_then(|r| r.get(rel_name));
1777    let Some(fact) = fact else {
1778        bag.error(
1779            missing_code,
1780            format!("{path}.{role}"),
1781            format!(
1782                "{planner} `{role}` names relationship `{rel_name}`, which is not declared on this table"
1783            ),
1784        );
1785        return None;
1786    };
1787    dense_key_from_fact(fact, rel_name, planner, key_code, path, bag)
1788}
1789
1790/// Resolve an already-located fact mapping into a [`DenseKey`].
1791fn dense_key_from_fact(
1792    fact: &Value,
1793    label: &str,
1794    planner: &str,
1795    key_code: &'static str,
1796    path: &str,
1797    bag: &mut DiagnosticBag,
1798) -> Option<DenseKey> {
1799    let dense = fact.get("dense").and_then(Value::as_bool).unwrap_or(false);
1800    if !dense {
1801        bag.error(
1802            key_code,
1803            path.to_string(),
1804            format!(
1805                "{planner} target `{label}` does not have a dense integer key; only bare integer primary keys and `sequence` keys are supported"
1806            ),
1807        );
1808        return None;
1809    }
1810    let start = fact.get("start").and_then(as_i128).unwrap_or(1);
1811    let step = fact.get("step").and_then(as_i128).unwrap_or(1);
1812    let count = fact.get("count").and_then(Value::as_u64).unwrap_or(0);
1813    Some(DenseKey { start, step, count })
1814}
1815
1816/// The greatest common divisor of two non-negative integers.
1817fn gcd(mut a: i128, mut b: i128) -> i128 {
1818    while b != 0 {
1819        (a, b) = (b, a.rem_euclid(b));
1820    }
1821    a.abs()
1822}
1823
1824// =============================================================================
1825// relation.junction_pair
1826// =============================================================================
1827
1828/// Static description of the `relation.junction_pair` planner.
1829pub static RELATION_JUNCTION_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
1830    kind: "relation.junction_pair",
1831    aliases: &[],
1832    summary: "Fills a junction row's two foreign keys with a UNIQUE (left, right) pair, using a deterministic pair-index permutation so edges never repeat.",
1833    arguments: &[
1834        ArgumentSpec {
1835            name: "columns",
1836            required: true,
1837            summary: "Maps the left and right roles to the junction table's foreign-key columns.",
1838        },
1839        ArgumentSpec {
1840            name: "left_relationship",
1841            required: true,
1842            summary: "Relationship that supplies the left dense key domain.",
1843        },
1844        ArgumentSpec {
1845            name: "right_relationship",
1846            required: true,
1847            summary: "Relationship that supplies the right dense key domain.",
1848        },
1849    ],
1850    writes: ColumnScope::Configured,
1851    reads: ColumnScope::None,
1852    determinism: Determinism::Deterministic,
1853    buffering: Buffering::Streaming,
1854    verification: Verification::Supported,
1855    cross_table: true,
1856};
1857
1858/// Factory for the `relation.junction_pair` planner.
1859pub struct RelationJunctionPairFactory;
1860
1861impl PlannerFactory for RelationJunctionPairFactory {
1862    fn descriptor(&self) -> &'static PlannerDescriptor {
1863        &RELATION_JUNCTION_PAIR_DESCRIPTOR
1864    }
1865
1866    fn compile(
1867        &self,
1868        config: &PlannerConfig,
1869        context: &CompileContext<'_>,
1870    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
1871        compile_junction_pair(config, context)
1872            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
1873    }
1874}
1875
1876/// The compiled `relation.junction_pair` planner. It maps the junction row index
1877/// `n` to a distinct index in `[0, left.count * right.count)` via the bijection
1878/// `idx(n) = (offset + n * stride) mod total` (with `gcd(stride, total) == 1`),
1879/// then decodes that index into a `(left_row, right_row)` pair. Distinct `n`
1880/// therefore always yield distinct pairs — uniqueness is by construction, not by
1881/// rejection sampling.
1882struct RelationJunctionPairPlanner {
1883    writes: Vec<String>,
1884    left_family: SqlTypeFamily,
1885    right_family: SqlTypeFamily,
1886    left: DenseKey,
1887    right: DenseKey,
1888    total: i128,
1889    stride: i128,
1890    offset: i128,
1891    predicates: Vec<PlannerPredicate>,
1892}
1893
1894impl CompiledPlanner for RelationJunctionPairPlanner {
1895    fn writes(&self) -> &[String] {
1896        &self.writes
1897    }
1898
1899    fn generate_row(
1900        &mut self,
1901        row_index: u64,
1902        output: &mut [GeneratedValue],
1903    ) -> Result<(), GenerateError> {
1904        if self.total <= 0 {
1905            output[0] = GeneratedValue::Null;
1906            output[1] = GeneratedValue::Null;
1907            return Ok(());
1908        }
1909        let idx = (self.offset + (row_index as i128) * self.stride).rem_euclid(self.total);
1910        let right_count = self.right.count as i128;
1911        let left_row = (idx.div_euclid(right_count)) as u64;
1912        let right_row = (idx.rem_euclid(right_count)) as u64;
1913        output[0] = render_key(self.left.key_at(left_row), &self.left_family);
1914        output[1] = render_key(self.right.key_at(right_row), &self.right_family);
1915        Ok(())
1916    }
1917
1918    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
1919        self.predicates.clone()
1920    }
1921}
1922
1923fn compile_junction_pair(
1924    config: &PlannerConfig,
1925    context: &CompileContext<'_>,
1926) -> Result<RelationJunctionPairPlanner, DiagnosticBag> {
1927    const COLUMN_CODE: &str = crate::diagnostic::codes::JUNCTION_COLUMN_MISSING.code;
1928    const REL_CODE: &str = crate::diagnostic::codes::JUNCTION_RELATIONSHIP.code;
1929    const KEY_CODE: &str = crate::diagnostic::codes::JUNCTION_KEY_UNSUPPORTED.code;
1930    const EXHAUSTED_CODE: &str = crate::diagnostic::codes::JUNCTION_EXHAUSTED.code;
1931    let mut bag = DiagnosticBag::default();
1932    let table = context.table();
1933    let path = context.path();
1934    let columns = config.args.get("columns");
1935    let facts = config.args.get(RELATION_FACTS_KEY);
1936
1937    let left_col = resolve_required(columns, "left", table, path, COLUMN_CODE, &mut bag);
1938    let right_col = resolve_required(columns, "right", table, path, COLUMN_CODE, &mut bag);
1939
1940    let left_rel = config
1941        .args
1942        .get("left_relationship")
1943        .and_then(Value::as_str)
1944        .map(str::to_string);
1945    let right_rel = config
1946        .args
1947        .get("right_relationship")
1948        .and_then(Value::as_str)
1949        .map(str::to_string);
1950    if left_rel.is_none() {
1951        bag.error(
1952            REL_CODE,
1953            format!("{path}.left_relationship"),
1954            "relation.junction_pair requires a `left_relationship` naming the left foreign key"
1955                .to_string(),
1956        );
1957    }
1958    if right_rel.is_none() {
1959        bag.error(
1960            REL_CODE,
1961            format!("{path}.right_relationship"),
1962            "relation.junction_pair requires a `right_relationship` naming the right foreign key"
1963                .to_string(),
1964        );
1965    }
1966
1967    let left = left_rel.as_deref().and_then(|name| {
1968        dense_key_from_relationship(
1969            facts,
1970            name,
1971            "relation.junction_pair",
1972            "left_relationship",
1973            [REL_CODE, KEY_CODE],
1974            path,
1975            &mut bag,
1976        )
1977    });
1978    let right = right_rel.as_deref().and_then(|name| {
1979        dense_key_from_relationship(
1980            facts,
1981            name,
1982            "relation.junction_pair",
1983            "right_relationship",
1984            [REL_CODE, KEY_CODE],
1985            path,
1986            &mut bag,
1987        )
1988    });
1989
1990    // The junction can hold at most `left.count * right.count` distinct edges; a
1991    // larger row count could not fill unique pairs.
1992    let self_count = facts
1993        .and_then(|f| f.get("self_count"))
1994        .and_then(Value::as_u64);
1995    if let (Some(left), Some(right), Some(rows)) = (left, right, self_count) {
1996        let total = i128::from(left.count) * i128::from(right.count);
1997        if i128::from(rows) > total {
1998            bag.error(
1999                EXHAUSTED_CODE,
2000                path.to_string(),
2001                format!(
2002                    "relation.junction_pair needs {rows} unique (left, right) pairs but only {total} exist ({} left x {} right)",
2003                    left.count, right.count
2004                ),
2005            );
2006        }
2007    }
2008
2009    if bag.has_errors() {
2010        return Err(bag);
2011    }
2012
2013    let left_col = left_col.expect("left resolved without errors");
2014    let right_col = right_col.expect("right resolved without errors");
2015    let left = left.expect("left key resolved without errors");
2016    let right = right.expect("right key resolved without errors");
2017    let total = i128::from(left.count) * i128::from(right.count);
2018
2019    // A seeded stride coprime with `total` makes `n -> (offset + n*stride) mod
2020    // total` a bijection, so distinct rows land on distinct pairs. `stride == 1`
2021    // is always coprime, so the search below always terminates on a valid value.
2022    let mut rng = context.rng(StreamId::operator(
2023        table.name.as_str(),
2024        format!("{},{}", left_col.name, right_col.name),
2025        "relation.junction_pair",
2026    ));
2027    let (stride, offset) = if total > 1 {
2028        let offset = rng.random_range(0..total);
2029        let mut stride = 1 + rng.random_range(0..total - 1);
2030        let mut tries = 0;
2031        while gcd(stride, total) != 1 && tries < 64 {
2032            stride = stride % (total - 1) + 1;
2033            tries += 1;
2034        }
2035        if gcd(stride, total) != 1 {
2036            stride = 1;
2037        }
2038        (stride, offset)
2039    } else {
2040        (1, 0)
2041    };
2042
2043    let writes = vec![left_col.name.clone(), right_col.name.clone()];
2044    let mut predicates = Vec::new();
2045    if left.start >= 0 && left.step >= 0 && right.start >= 0 && right.step >= 0 {
2046        predicates.push(PlannerPredicate::NonNegative {
2047            columns: writes.clone(),
2048        });
2049    }
2050
2051    Ok(RelationJunctionPairPlanner {
2052        writes,
2053        left_family: left_col.family.clone(),
2054        right_family: right_col.family.clone(),
2055        left,
2056        right,
2057        total,
2058        stride,
2059        offset,
2060        predicates,
2061    })
2062}
2063
2064// =============================================================================
2065// relation.polymorphic_pair
2066// =============================================================================
2067
2068/// Static description of the `relation.polymorphic_pair` planner.
2069pub static RELATION_POLYMORPHIC_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2070    kind: "relation.polymorphic_pair",
2071    aliases: &[],
2072    summary: "Fills a (type, id) polymorphic pair atomically: a weighted choice picks a target table, then a valid key from that same target's key domain.",
2073    arguments: &[
2074        ArgumentSpec {
2075            name: "columns",
2076            required: true,
2077            summary: "Maps the polymorphic type and id roles to columns.",
2078        },
2079        ArgumentSpec {
2080            name: "targets",
2081            required: true,
2082            summary: "Weighted target tables with optional type labels and id-column overrides.",
2083        },
2084    ],
2085    writes: ColumnScope::Configured,
2086    reads: ColumnScope::None,
2087    determinism: Determinism::Deterministic,
2088    buffering: Buffering::Streaming,
2089    verification: Verification::Supported,
2090    cross_table: true,
2091};
2092
2093/// Factory for the `relation.polymorphic_pair` planner.
2094pub struct RelationPolymorphicPairFactory;
2095
2096impl PlannerFactory for RelationPolymorphicPairFactory {
2097    fn descriptor(&self) -> &'static PlannerDescriptor {
2098        &RELATION_POLYMORPHIC_PAIR_DESCRIPTOR
2099    }
2100
2101    fn compile(
2102        &self,
2103        config: &PlannerConfig,
2104        context: &CompileContext<'_>,
2105    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2106        compile_polymorphic_pair(config, context)
2107            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2108    }
2109}
2110
2111/// One resolved polymorphic target: the discriminator string written into the
2112/// type column and the key domain the id is drawn from.
2113struct PolyTarget {
2114    type_label: String,
2115    key: DenseKey,
2116}
2117
2118/// The compiled `relation.polymorphic_pair` planner. Each row draws a target
2119/// (weighted) and then a valid key from that same target's domain, in a fixed
2120/// stream order, so the type and id are always chosen together and never
2121/// independently.
2122struct RelationPolymorphicPairPlanner {
2123    writes: Vec<String>,
2124    id_family: SqlTypeFamily,
2125    targets: Vec<PolyTarget>,
2126    weights: Vec<f64>,
2127    rng: ChaCha8Rng,
2128    predicates: Vec<PlannerPredicate>,
2129}
2130
2131impl CompiledPlanner for RelationPolymorphicPairPlanner {
2132    fn writes(&self) -> &[String] {
2133        &self.writes
2134    }
2135
2136    fn generate_row(
2137        &mut self,
2138        _row_index: u64,
2139        output: &mut [GeneratedValue],
2140    ) -> Result<(), GenerateError> {
2141        // Draw the target pick, then the id pick, in a fixed order, so the pair
2142        // is atomic and a seeded run reproduces exactly.
2143        let target_pick = self.rng.random::<f64>();
2144        let id_pick = self.rng.random::<f64>();
2145        let index = pick_weighted_index(&self.weights, target_pick);
2146        let target = &self.targets[index];
2147        let row = if target.key.count == 0 {
2148            0
2149        } else {
2150            (id_pick * target.key.count as f64) as u64
2151        }
2152        .min(target.key.count.saturating_sub(1));
2153
2154        output[0] = GeneratedValue::Text(target.type_label.clone());
2155        output[1] = render_key(target.key.key_at(row), &self.id_family);
2156        Ok(())
2157    }
2158
2159    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2160        self.predicates.clone()
2161    }
2162}
2163
2164fn compile_polymorphic_pair(
2165    config: &PlannerConfig,
2166    context: &CompileContext<'_>,
2167) -> Result<RelationPolymorphicPairPlanner, DiagnosticBag> {
2168    const COLUMN_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_COLUMN_MISSING.code;
2169    const TARGETS_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_TARGETS.code;
2170    const TARGET_UNKNOWN_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_TARGET_UNKNOWN.code;
2171    const KEY_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_KEY_UNSUPPORTED.code;
2172    let mut bag = DiagnosticBag::default();
2173    let table = context.table();
2174    let path = context.path();
2175    let columns = config.args.get("columns");
2176    let facts = config.args.get(RELATION_FACTS_KEY);
2177
2178    let type_col = resolve_required(columns, "type", table, path, COLUMN_CODE, &mut bag);
2179    let id_col = resolve_required(columns, "id", table, path, COLUMN_CODE, &mut bag);
2180
2181    let target_items = match config.args.get("targets") {
2182        Some(Value::Sequence(items)) if !items.is_empty() => items.as_slice(),
2183        _ => {
2184            bag.error(
2185                TARGETS_CODE,
2186                format!("{path}.targets"),
2187                "relation.polymorphic_pair requires a non-empty `targets` list".to_string(),
2188            );
2189            &[]
2190        }
2191    };
2192
2193    let mut targets = Vec::new();
2194    let mut weights = Vec::new();
2195    for (index, item) in target_items.iter().enumerate() {
2196        let target_path = format!("{path}.targets[{index}]");
2197        let Some(table_name) = item.get("table").and_then(Value::as_str) else {
2198            bag.error(
2199                TARGETS_CODE,
2200                target_path,
2201                "relation.polymorphic_pair target requires a `table`".to_string(),
2202            );
2203            continue;
2204        };
2205        let table_fact = facts
2206            .and_then(|f| f.get("tables"))
2207            .and_then(|t| t.get(table_name));
2208        let Some(table_fact) = table_fact else {
2209            bag.error(
2210                TARGET_UNKNOWN_CODE,
2211                target_path,
2212                format!(
2213                    "relation.polymorphic_pair target `{table_name}` is not a table in the model"
2214                ),
2215            );
2216            continue;
2217        };
2218        // The id column: an explicit `id_column`, else the target's primary key.
2219        let id_column = item
2220            .get("id_column")
2221            .and_then(Value::as_str)
2222            .map(str::to_string)
2223            .or_else(|| {
2224                table_fact
2225                    .get("primary_key")
2226                    .and_then(Value::as_str)
2227                    .map(str::to_string)
2228            });
2229        let Some(id_column) = id_column else {
2230            bag.error(
2231                TARGET_UNKNOWN_CODE,
2232                target_path,
2233                format!(
2234                    "relation.polymorphic_pair target `{table_name}` has no primary key; specify an `id_column`"
2235                ),
2236            );
2237            continue;
2238        };
2239        let key_fact = table_fact.get("keys").and_then(|k| k.get(&id_column));
2240        let Some(key_fact) = key_fact else {
2241            bag.error(
2242                KEY_CODE,
2243                target_path,
2244                format!(
2245                    "relation.polymorphic_pair target `{table_name}.{id_column}` does not have a dense integer key; only bare integer primary keys and `sequence` keys are supported"
2246                ),
2247            );
2248            continue;
2249        };
2250        let Some(key) = dense_key_from_fact(
2251            key_fact,
2252            &format!("{table_name}.{id_column}"),
2253            "relation.polymorphic_pair",
2254            KEY_CODE,
2255            &target_path,
2256            &mut bag,
2257        ) else {
2258            continue;
2259        };
2260        if key.count == 0 {
2261            // A target with no rows can never supply a valid id; drop it rather
2262            // than emit an unsatisfiable (type, id) pair.
2263            continue;
2264        }
2265        let type_label = item
2266            .get("type")
2267            .and_then(Value::as_str)
2268            .unwrap_or(table_name)
2269            .to_string();
2270        let weight = item.get("weight").and_then(as_f64).unwrap_or(1.0).max(0.0);
2271        targets.push(PolyTarget { type_label, key });
2272        weights.push(weight);
2273    }
2274
2275    if targets.is_empty() && !bag.has_errors() {
2276        bag.error(
2277            TARGETS_CODE,
2278            format!("{path}.targets"),
2279            "relation.polymorphic_pair has no target with any rows to reference".to_string(),
2280        );
2281    }
2282    if weights.iter().sum::<f64>() <= 0.0 && !targets.is_empty() {
2283        // Degenerate weights: fall back to a uniform choice so every row still
2284        // resolves a valid (type, id) pair.
2285        weights = vec![1.0; targets.len()];
2286    }
2287
2288    if bag.has_errors() {
2289        return Err(bag);
2290    }
2291
2292    let type_col = type_col.expect("type resolved without errors");
2293    let id_col = id_col.expect("id resolved without errors");
2294    let writes = vec![type_col.name.clone(), id_col.name.clone()];
2295
2296    let mut predicates = Vec::new();
2297    if targets.iter().all(|t| t.key.start >= 0 && t.key.step >= 0) {
2298        predicates.push(PlannerPredicate::NonNegative {
2299            columns: vec![id_col.name.clone()],
2300        });
2301    }
2302
2303    let rng = context.rng(StreamId::operator(
2304        table.name.as_str(),
2305        format!("{},{}", type_col.name, id_col.name),
2306        "relation.polymorphic_pair",
2307    ));
2308
2309    Ok(RelationPolymorphicPairPlanner {
2310        writes,
2311        id_family: id_col.family.clone(),
2312        targets,
2313        weights,
2314        rng,
2315        predicates,
2316    })
2317}
2318
2319// =============================================================================
2320// relation.tenant_family
2321// =============================================================================
2322
2323/// Static description of the `relation.tenant_family` planner.
2324pub static RELATION_TENANT_FAMILY_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2325    kind: "relation.tenant_family",
2326    aliases: &[],
2327    summary: "Selects a same-tenant foreign key: the parent rows are partitioned into tenant blocks, and each child's FK is drawn from the block of the child's own tenant.",
2328    arguments: &[
2329        ArgumentSpec {
2330            name: "columns",
2331            required: true,
2332            summary: "Maps tenant and parent roles to the child table's columns.",
2333        },
2334        ArgumentSpec {
2335            name: "relationship",
2336            required: true,
2337            summary: "Relationship that supplies the parent dense key domain.",
2338        },
2339        ArgumentSpec {
2340            name: "num_tenants",
2341            required: false,
2342            summary: "Number of contiguous tenant partitions.",
2343        },
2344        ArgumentSpec {
2345            name: "tenant_start",
2346            required: false,
2347            summary: "First generated tenant identifier.",
2348        },
2349    ],
2350    writes: ColumnScope::Configured,
2351    reads: ColumnScope::None,
2352    determinism: Determinism::Deterministic,
2353    buffering: Buffering::Streaming,
2354    verification: Verification::Supported,
2355    cross_table: true,
2356};
2357
2358/// Factory for the `relation.tenant_family` planner.
2359pub struct RelationTenantFamilyFactory;
2360
2361impl PlannerFactory for RelationTenantFamilyFactory {
2362    fn descriptor(&self) -> &'static PlannerDescriptor {
2363        &RELATION_TENANT_FAMILY_DESCRIPTOR
2364    }
2365
2366    fn compile(
2367        &self,
2368        config: &PlannerConfig,
2369        context: &CompileContext<'_>,
2370    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2371        compile_tenant_family(config, context)
2372            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2373    }
2374}
2375
2376/// The compiled `relation.tenant_family` planner. The parent's `count` rows are
2377/// partitioned into `num_tenants` contiguous, balanced tenant blocks by row
2378/// index: tenant `t` owns parent rows `[t*count/T, (t+1)*count/T)`, so the
2379/// tenant of parent row `p` is `p*T/count`. Each child draws a tenant, sets its
2380/// own `tenant` column to that tenant, and draws its foreign key from that
2381/// tenant's parent block — so the child and the parent it references always
2382/// share a tenant, by construction.
2383struct RelationTenantFamilyPlanner {
2384    writes: Vec<String>,
2385    tenant_family: SqlTypeFamily,
2386    parent_family: SqlTypeFamily,
2387    parent: DenseKey,
2388    num_tenants: u64,
2389    tenant_start: i128,
2390    tenant_rng: ChaCha8Rng,
2391    select_rng: ChaCha8Rng,
2392    predicates: Vec<PlannerPredicate>,
2393}
2394
2395impl RelationTenantFamilyPlanner {
2396    /// The half-open parent-row range `[start, end)` owned by tenant `t`.
2397    fn tenant_block(&self, t: u64) -> (u64, u64) {
2398        let count = u128::from(self.parent.count);
2399        let tenants = u128::from(self.num_tenants);
2400        let start = (u128::from(t) * count / tenants) as u64;
2401        let end = (u128::from(t + 1) * count / tenants) as u64;
2402        (start, end.max(start + 1).min(self.parent.count))
2403    }
2404}
2405
2406impl CompiledPlanner for RelationTenantFamilyPlanner {
2407    fn writes(&self) -> &[String] {
2408        &self.writes
2409    }
2410
2411    fn generate_row(
2412        &mut self,
2413        _row_index: u64,
2414        output: &mut [GeneratedValue],
2415    ) -> Result<(), GenerateError> {
2416        // Draw the tenant, then the in-tenant parent, in a fixed order.
2417        let tenant_pick = self.tenant_rng.random::<f64>();
2418        let parent_pick = self.select_rng.random::<f64>();
2419
2420        let tenant = ((tenant_pick * self.num_tenants as f64) as u64).min(self.num_tenants - 1);
2421        let (start, end) = self.tenant_block(tenant);
2422        let size = end - start;
2423        let offset = if size == 0 {
2424            0
2425        } else {
2426            ((parent_pick * size as f64) as u64).min(size - 1)
2427        };
2428        let parent_row = start + offset;
2429
2430        output[0] = match self.tenant_family {
2431            SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => {
2432                GeneratedValue::Integer(self.tenant_start + tenant as i128)
2433            }
2434            _ => GeneratedValue::Text((self.tenant_start + tenant as i128).to_string()),
2435        };
2436        output[1] = render_key(self.parent.key_at(parent_row), &self.parent_family);
2437        Ok(())
2438    }
2439
2440    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2441        self.predicates.clone()
2442    }
2443}
2444
2445fn compile_tenant_family(
2446    config: &PlannerConfig,
2447    context: &CompileContext<'_>,
2448) -> Result<RelationTenantFamilyPlanner, DiagnosticBag> {
2449    const COLUMN_CODE: &str = crate::diagnostic::codes::TENANT_COLUMN_MISSING.code;
2450    const REL_CODE: &str = crate::diagnostic::codes::TENANT_RELATIONSHIP.code;
2451    const KEY_CODE: &str = crate::diagnostic::codes::TENANT_KEY_UNSUPPORTED.code;
2452    const PARTITION_CODE: &str = crate::diagnostic::codes::TENANT_PARTITION.code;
2453    let mut bag = DiagnosticBag::default();
2454    let table = context.table();
2455    let path = context.path();
2456    let columns = config.args.get("columns");
2457    let facts = config.args.get(RELATION_FACTS_KEY);
2458
2459    let tenant_col = resolve_required(columns, "tenant", table, path, COLUMN_CODE, &mut bag);
2460    let parent_col = resolve_required(columns, "parent", table, path, COLUMN_CODE, &mut bag);
2461
2462    let rel = config
2463        .args
2464        .get("relationship")
2465        .and_then(Value::as_str)
2466        .map(str::to_string);
2467    if rel.is_none() {
2468        bag.error(
2469            REL_CODE,
2470            format!("{path}.relationship"),
2471            "relation.tenant_family requires a `relationship` naming the parent foreign key"
2472                .to_string(),
2473        );
2474    }
2475    let parent = rel.as_deref().and_then(|name| {
2476        dense_key_from_relationship(
2477            facts,
2478            name,
2479            "relation.tenant_family",
2480            "relationship",
2481            [REL_CODE, KEY_CODE],
2482            path,
2483            &mut bag,
2484        )
2485    });
2486
2487    let num_tenants = config
2488        .args
2489        .get("num_tenants")
2490        .and_then(as_i128)
2491        .unwrap_or(4);
2492    let tenant_start = config
2493        .args
2494        .get("tenant_start")
2495        .and_then(as_i128)
2496        .unwrap_or(0);
2497
2498    if num_tenants < 1 {
2499        bag.error(
2500            PARTITION_CODE,
2501            format!("{path}.num_tenants"),
2502            format!("relation.tenant_family `num_tenants` {num_tenants} must be at least 1"),
2503        );
2504    }
2505    if let Some(parent) = parent {
2506        if num_tenants >= 1 && num_tenants as u64 > parent.count {
2507            bag.error(
2508                PARTITION_CODE,
2509                format!("{path}.num_tenants"),
2510                format!(
2511                    "relation.tenant_family `num_tenants` {num_tenants} exceeds the {} parent rows, so some tenants would have no parent to reference",
2512                    parent.count
2513                ),
2514            );
2515        }
2516    }
2517
2518    if bag.has_errors() {
2519        return Err(bag);
2520    }
2521
2522    let tenant_col = tenant_col.expect("tenant resolved without errors");
2523    let parent_col = parent_col.expect("parent resolved without errors");
2524    let parent = parent.expect("parent key resolved without errors");
2525    let writes = vec![tenant_col.name.clone(), parent_col.name.clone()];
2526
2527    let mut predicates = Vec::new();
2528    if parent.start >= 0 && parent.step >= 0 && tenant_start >= 0 {
2529        predicates.push(PlannerPredicate::NonNegative {
2530            columns: writes.clone(),
2531        });
2532    }
2533
2534    let tenant_rng = context.rng(StreamId::operator(
2535        table.name.as_str(),
2536        tenant_col.name.clone(),
2537        "relation.tenant_family.tenant",
2538    ));
2539    let select_rng = context.rng(StreamId::operator(
2540        table.name.as_str(),
2541        parent_col.name.clone(),
2542        "relation.tenant_family.parent",
2543    ));
2544
2545    Ok(RelationTenantFamilyPlanner {
2546        writes,
2547        tenant_family: tenant_col.family.clone(),
2548        parent_family: parent_col.family.clone(),
2549        parent,
2550        num_tenants: num_tenants as u64,
2551        tenant_start,
2552        tenant_rng,
2553        select_rng,
2554        predicates,
2555    })
2556}
2557
2558// =============================================================================
2559// geo.coordinate_pair
2560// =============================================================================
2561
2562/// Global inclusive latitude range, in whole degrees.
2563const LAT_MIN_DEGREES: f64 = -90.0;
2564const LAT_MAX_DEGREES: f64 = 90.0;
2565/// Global inclusive longitude range, in whole degrees.
2566const LON_MIN_DEGREES: f64 = -180.0;
2567const LON_MAX_DEGREES: f64 = 180.0;
2568
2569/// Static description of the `geo.coordinate_pair` planner.
2570///
2571/// Note: no [`PlannerPredicate`] variant expresses a decimal-valued bounded
2572/// range — [`PlannerPredicate::InRange`] is timestamp-only (it compares
2573/// epoch nanoseconds). Range and bounding-box correctness are
2574/// therefore guaranteed by construction (every draw is a `random_range` over
2575/// the compiled bound) and covered by this module's tests, not by a runtime
2576/// predicate.
2577pub static GEO_COORDINATE_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2578    kind: "geo.coordinate_pair",
2579    aliases: &[],
2580    summary: "Draws a coherent (latitude, longitude) pair within [-90, 90] x [-180, 180] (or a configured bounding box), at a configurable decimal precision.",
2581    arguments: &[
2582        ArgumentSpec {
2583            name: "columns",
2584            required: true,
2585            summary: "Maps latitude and longitude roles to decimal columns.",
2586        },
2587        ArgumentSpec {
2588            name: "precision",
2589            required: false,
2590            summary: "Number of decimal places, from 0 through 9.",
2591        },
2592        ArgumentSpec {
2593            name: "bounds",
2594            required: false,
2595            summary: "Optional minimum and maximum latitude and longitude bounding box.",
2596        },
2597    ],
2598    writes: ColumnScope::Configured,
2599    reads: ColumnScope::None,
2600    determinism: Determinism::Deterministic,
2601    buffering: Buffering::Streaming,
2602    verification: Verification::Unsupported,
2603    cross_table: false,
2604};
2605
2606/// Factory for the `geo.coordinate_pair` planner.
2607pub struct GeoCoordinatePairFactory;
2608
2609impl PlannerFactory for GeoCoordinatePairFactory {
2610    fn descriptor(&self) -> &'static PlannerDescriptor {
2611        &GEO_COORDINATE_PAIR_DESCRIPTOR
2612    }
2613
2614    fn compile(
2615        &self,
2616        config: &PlannerConfig,
2617        context: &CompileContext<'_>,
2618    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2619        compile_coordinate_pair(config, context)
2620            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2621    }
2622}
2623
2624struct GeoCoordinatePairPlanner {
2625    writes: Vec<String>,
2626    lat_family: SqlTypeFamily,
2627    lon_family: SqlTypeFamily,
2628    lat_min_minor: i128,
2629    lat_max_minor: i128,
2630    lon_min_minor: i128,
2631    lon_max_minor: i128,
2632    scale: u32,
2633    lat_rng: ChaCha8Rng,
2634    lon_rng: ChaCha8Rng,
2635}
2636
2637impl CompiledPlanner for GeoCoordinatePairPlanner {
2638    fn writes(&self) -> &[String] {
2639        &self.writes
2640    }
2641
2642    fn generate_row(
2643        &mut self,
2644        _row_index: u64,
2645        output: &mut [GeneratedValue],
2646    ) -> Result<(), GenerateError> {
2647        // Both columns are drawn from independent streams, in a fixed order,
2648        // every row — the pair is coherent (always present together) simply
2649        // because a single planner call produces both.
2650        let lat_minor = self
2651            .lat_rng
2652            .random_range(self.lat_min_minor..=self.lat_max_minor);
2653        let lon_minor = self
2654            .lon_rng
2655            .random_range(self.lon_min_minor..=self.lon_max_minor);
2656        output[0] = render_decimal(&self.lat_family, lat_minor, self.scale);
2657        output[1] = render_decimal(&self.lon_family, lon_minor, self.scale);
2658        Ok(())
2659    }
2660
2661    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2662        Vec::new()
2663    }
2664}
2665
2666/// Render a fixed-point value in whichever representation `family` expects
2667/// (mirrors `semantic.rs`'s private `decimal_value`; kept local since that
2668/// helper is module-private and duplicating it here is cheaper than exposing
2669/// it across modules for one shared use).
2670fn render_decimal(family: &SqlTypeFamily, minor: i128, scale: u32) -> GeneratedValue {
2671    match family {
2672        SqlTypeFamily::Decimal => GeneratedValue::Decimal { minor, scale },
2673        _ => GeneratedValue::Text(format_fixed_point(minor, scale)),
2674    }
2675}
2676
2677/// Render `minor` units at `scale` decimal places as a fixed-point string.
2678fn format_fixed_point(minor: i128, scale: u32) -> String {
2679    if scale == 0 {
2680        return minor.to_string();
2681    }
2682    let negative = minor < 0;
2683    let magnitude = minor.unsigned_abs();
2684    let factor = 10u128.pow(scale);
2685    let whole = magnitude / factor;
2686    let frac = magnitude % factor;
2687    let sign = if negative { "-" } else { "" };
2688    format!("{sign}{whole}.{frac:0width$}", width = scale as usize)
2689}
2690
2691fn compile_coordinate_pair(
2692    config: &PlannerConfig,
2693    context: &CompileContext<'_>,
2694) -> Result<GeoCoordinatePairPlanner, DiagnosticBag> {
2695    const COLUMN_CODE: &str = crate::diagnostic::codes::COORDINATE_COLUMN_MISSING.code;
2696    const BOUNDS_CODE: &str = crate::diagnostic::codes::COORDINATE_BOUNDS.code;
2697    const PRECISION_CODE: &str = crate::diagnostic::codes::COORDINATE_PRECISION.code;
2698    let mut bag = DiagnosticBag::default();
2699    let table = context.table();
2700    let path = context.path();
2701    let columns = config.args.get("columns");
2702
2703    let lat_col = resolve_required(columns, "latitude", table, path, COLUMN_CODE, &mut bag);
2704    let lon_col = resolve_required(columns, "longitude", table, path, COLUMN_CODE, &mut bag);
2705
2706    let precision = config.args.get("precision").and_then(as_i128).unwrap_or(6);
2707    if !(0..=9).contains(&precision) {
2708        bag.error(
2709            PRECISION_CODE,
2710            format!("{path}.precision"),
2711            format!("geo.coordinate_pair `precision` {precision} must be within [0, 9]"),
2712        );
2713    }
2714
2715    let bounds = config.args.get("bounds");
2716    let min_lat = bounds
2717        .and_then(|b| b.get("min_lat"))
2718        .and_then(as_f64)
2719        .unwrap_or(LAT_MIN_DEGREES);
2720    let max_lat = bounds
2721        .and_then(|b| b.get("max_lat"))
2722        .and_then(as_f64)
2723        .unwrap_or(LAT_MAX_DEGREES);
2724    let min_lon = bounds
2725        .and_then(|b| b.get("min_lon"))
2726        .and_then(as_f64)
2727        .unwrap_or(LON_MIN_DEGREES);
2728    let max_lon = bounds
2729        .and_then(|b| b.get("max_lon"))
2730        .and_then(as_f64)
2731        .unwrap_or(LON_MAX_DEGREES);
2732
2733    if !(LAT_MIN_DEGREES..=LAT_MAX_DEGREES).contains(&min_lat)
2734        || !(LAT_MIN_DEGREES..=LAT_MAX_DEGREES).contains(&max_lat)
2735        || min_lat > max_lat
2736    {
2737        bag.error(
2738            BOUNDS_CODE,
2739            format!("{path}.bounds"),
2740            format!(
2741                "geo.coordinate_pair latitude bounds [{min_lat}, {max_lat}] must lie within [-90, 90] with min <= max"
2742            ),
2743        );
2744    }
2745    if !(LON_MIN_DEGREES..=LON_MAX_DEGREES).contains(&min_lon)
2746        || !(LON_MIN_DEGREES..=LON_MAX_DEGREES).contains(&max_lon)
2747        || min_lon > max_lon
2748    {
2749        bag.error(
2750            BOUNDS_CODE,
2751            format!("{path}.bounds"),
2752            format!(
2753                "geo.coordinate_pair longitude bounds [{min_lon}, {max_lon}] must lie within [-180, 180] with min <= max"
2754            ),
2755        );
2756    }
2757
2758    if bag.has_errors() {
2759        return Err(bag);
2760    }
2761
2762    let lat = lat_col.expect("latitude resolved without errors");
2763    let lon = lon_col.expect("longitude resolved without errors");
2764    let scale = precision as u32;
2765    let factor = 10f64.powi(scale as i32);
2766    let lat_min_minor = (min_lat * factor).round() as i128;
2767    let lat_max_minor = (max_lat * factor).round() as i128;
2768    let lon_min_minor = (min_lon * factor).round() as i128;
2769    let lon_max_minor = (max_lon * factor).round() as i128;
2770
2771    let writes = vec![lat.name.clone(), lon.name.clone()];
2772    let lat_rng = context.rng(StreamId::operator(
2773        table.name.as_str(),
2774        lat.name.clone(),
2775        "geo.coordinate_pair.latitude",
2776    ));
2777    let lon_rng = context.rng(StreamId::operator(
2778        table.name.as_str(),
2779        lon.name.clone(),
2780        "geo.coordinate_pair.longitude",
2781    ));
2782
2783    Ok(GeoCoordinatePairPlanner {
2784        writes,
2785        lat_family: lat.family.clone(),
2786        lon_family: lon.family.clone(),
2787        lat_min_minor,
2788        lat_max_minor,
2789        lon_min_minor,
2790        lon_max_minor,
2791        scale,
2792        lat_rng,
2793        lon_rng,
2794    })
2795}
2796
2797// =============================================================================
2798// file.metadata
2799// =============================================================================
2800
2801/// One recognized `(extension, mime_type)` pairing `file.metadata` can draw.
2802/// Extensions are matched case-insensitively but stored (and rendered)
2803/// lowercase.
2804struct FileTypeEntry {
2805    extension: &'static str,
2806    mime_type: &'static str,
2807}
2808
2809/// The built-in extension/MIME catalog. Intentionally a plain, well-known
2810/// mapping (not tied to any locale or external crate) so `mime_type` is
2811/// always consistent with `extension` by construction.
2812const FILE_TYPE_CATALOG: &[FileTypeEntry] = &[
2813    FileTypeEntry {
2814        extension: "txt",
2815        mime_type: "text/plain",
2816    },
2817    FileTypeEntry {
2818        extension: "csv",
2819        mime_type: "text/csv",
2820    },
2821    FileTypeEntry {
2822        extension: "json",
2823        mime_type: "application/json",
2824    },
2825    FileTypeEntry {
2826        extension: "xml",
2827        mime_type: "application/xml",
2828    },
2829    FileTypeEntry {
2830        extension: "html",
2831        mime_type: "text/html",
2832    },
2833    FileTypeEntry {
2834        extension: "css",
2835        mime_type: "text/css",
2836    },
2837    FileTypeEntry {
2838        extension: "js",
2839        mime_type: "text/javascript",
2840    },
2841    FileTypeEntry {
2842        extension: "md",
2843        mime_type: "text/markdown",
2844    },
2845    FileTypeEntry {
2846        extension: "jpg",
2847        mime_type: "image/jpeg",
2848    },
2849    FileTypeEntry {
2850        extension: "jpeg",
2851        mime_type: "image/jpeg",
2852    },
2853    FileTypeEntry {
2854        extension: "png",
2855        mime_type: "image/png",
2856    },
2857    FileTypeEntry {
2858        extension: "gif",
2859        mime_type: "image/gif",
2860    },
2861    FileTypeEntry {
2862        extension: "webp",
2863        mime_type: "image/webp",
2864    },
2865    FileTypeEntry {
2866        extension: "svg",
2867        mime_type: "image/svg+xml",
2868    },
2869    FileTypeEntry {
2870        extension: "bmp",
2871        mime_type: "image/bmp",
2872    },
2873    FileTypeEntry {
2874        extension: "pdf",
2875        mime_type: "application/pdf",
2876    },
2877    FileTypeEntry {
2878        extension: "zip",
2879        mime_type: "application/zip",
2880    },
2881    FileTypeEntry {
2882        extension: "gz",
2883        mime_type: "application/gzip",
2884    },
2885    FileTypeEntry {
2886        extension: "tar",
2887        mime_type: "application/x-tar",
2888    },
2889    FileTypeEntry {
2890        extension: "mp3",
2891        mime_type: "audio/mpeg",
2892    },
2893    FileTypeEntry {
2894        extension: "wav",
2895        mime_type: "audio/wav",
2896    },
2897    FileTypeEntry {
2898        extension: "mp4",
2899        mime_type: "video/mp4",
2900    },
2901    FileTypeEntry {
2902        extension: "mov",
2903        mime_type: "video/quicktime",
2904    },
2905    FileTypeEntry {
2906        extension: "avi",
2907        mime_type: "video/x-msvideo",
2908    },
2909    FileTypeEntry {
2910        extension: "doc",
2911        mime_type: "application/msword",
2912    },
2913    FileTypeEntry {
2914        extension: "docx",
2915        mime_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2916    },
2917    FileTypeEntry {
2918        extension: "xls",
2919        mime_type: "application/vnd.ms-excel",
2920    },
2921    FileTypeEntry {
2922        extension: "xlsx",
2923        mime_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2924    },
2925    FileTypeEntry {
2926        extension: "ppt",
2927        mime_type: "application/vnd.ms-powerpoint",
2928    },
2929    FileTypeEntry {
2930        extension: "pptx",
2931        mime_type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2932    },
2933    FileTypeEntry {
2934        extension: "bin",
2935        mime_type: "application/octet-stream",
2936    },
2937];
2938
2939fn find_file_type(extension: &str) -> Option<&'static FileTypeEntry> {
2940    FILE_TYPE_CATALOG
2941        .iter()
2942        .find(|entry| entry.extension.eq_ignore_ascii_case(extension))
2943}
2944
2945/// Plain, unremarkable words a synthetic file name is built from — no
2946/// locale/crate dependency, just enough variety to look plausible.
2947const FILE_NAME_WORDS: &[&str] = &[
2948    "report",
2949    "invoice",
2950    "photo",
2951    "backup",
2952    "export",
2953    "summary",
2954    "dataset",
2955    "image",
2956    "archive",
2957    "document",
2958    "manifest",
2959    "snapshot",
2960    "profile",
2961    "transcript",
2962    "spreadsheet",
2963    "presentation",
2964    "recording",
2965    "scan",
2966    "thumbnail",
2967    "upload",
2968];
2969
2970const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
2971
2972/// A supported `hash_kind`: fixes the hex digest length `file.metadata`
2973/// draws. The digest is a uniformly random hex string of the correct
2974/// length/charset for the kind — digest-shaped, but never a hash of any real
2975/// content, so it is unmistakably synthetic (the same posture as
2976/// `identifier.hash`).
2977#[derive(Clone, Copy)]
2978enum HashKind {
2979    Md5,
2980    Sha1,
2981    Sha256,
2982    Sha512,
2983}
2984
2985impl HashKind {
2986    fn parse(name: &str) -> Option<Self> {
2987        match name {
2988            "md5" => Some(Self::Md5),
2989            "sha1" => Some(Self::Sha1),
2990            "sha256" => Some(Self::Sha256),
2991            "sha512" => Some(Self::Sha512),
2992            _ => None,
2993        }
2994    }
2995
2996    fn hex_len(self) -> usize {
2997        match self {
2998            Self::Md5 => 32,
2999            Self::Sha1 => 40,
3000            Self::Sha256 => 64,
3001            Self::Sha512 => 128,
3002        }
3003    }
3004}
3005
3006/// Static description of the `file.metadata` planner.
3007///
3008/// Note: only `size`'s nonnegativity has an equivalent in the existing
3009/// [`PlannerPredicate`] vocabulary ([`PlannerPredicate::NonNegative`]). There
3010/// is no "column ends with column" or cross-column text-equality predicate,
3011/// so the name/extension/mime_type textual coherence invariants are
3012/// guaranteed by construction (every row draws one target extension and
3013/// derives the name suffix and MIME type from it) and covered by this
3014/// module's tests rather than a runtime predicate.
3015pub static FILE_METADATA_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
3016    kind: "file.metadata",
3017    aliases: &[],
3018    summary: "Coordinates a coherent file name/extension/mime_type/size/hash: the extension matches the name's suffix, mime_type matches the extension, size is a plausible byte count, and hash is a clearly-synthetic digest-shaped string.",
3019    arguments: &[
3020        ArgumentSpec {
3021            name: "columns",
3022            required: true,
3023            summary: "Maps name and optional extension, MIME type, size, and hash roles to columns.",
3024        },
3025        ArgumentSpec {
3026            name: "extensions",
3027            required: false,
3028            summary: "Allow-list of recognized file extensions.",
3029        },
3030        ArgumentSpec {
3031            name: "size",
3032            required: false,
3033            summary: "Minimum and maximum generated byte size.",
3034        },
3035        ArgumentSpec {
3036            name: "hash_kind",
3037            required: false,
3038            summary: "Synthetic digest shape: md5, sha1, sha256, or sha512.",
3039        },
3040    ],
3041    writes: ColumnScope::Configured,
3042    reads: ColumnScope::None,
3043    determinism: Determinism::Deterministic,
3044    buffering: Buffering::Streaming,
3045    verification: Verification::Supported,
3046    cross_table: false,
3047};
3048
3049/// Factory for the `file.metadata` planner.
3050pub struct FileMetadataFactory;
3051
3052impl PlannerFactory for FileMetadataFactory {
3053    fn descriptor(&self) -> &'static PlannerDescriptor {
3054        &FILE_METADATA_DESCRIPTOR
3055    }
3056
3057    fn compile(
3058        &self,
3059        config: &PlannerConfig,
3060        context: &CompileContext<'_>,
3061    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
3062        compile_file_metadata(config, context)
3063            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
3064    }
3065}
3066
3067struct FileMetadataPlanner {
3068    writes: Vec<String>,
3069    entries: Vec<&'static FileTypeEntry>,
3070    has_extension: bool,
3071    has_mime_type: bool,
3072    size_family: Option<SqlTypeFamily>,
3073    size_min: i128,
3074    size_max: i128,
3075    hash_len: Option<usize>,
3076    ext_rng: ChaCha8Rng,
3077    name_rng: ChaCha8Rng,
3078    size_rng: ChaCha8Rng,
3079    hash_rng: ChaCha8Rng,
3080    predicates: Vec<PlannerPredicate>,
3081}
3082
3083impl CompiledPlanner for FileMetadataPlanner {
3084    fn writes(&self) -> &[String] {
3085        &self.writes
3086    }
3087
3088    fn generate_row(
3089        &mut self,
3090        row_index: u64,
3091        output: &mut [GeneratedValue],
3092    ) -> Result<(), GenerateError> {
3093        // Every stream is drawn unconditionally, in a fixed order, so a
3094        // seeded run reproduces exactly regardless of which optional columns
3095        // this instance was configured to own.
3096        let ext_pick = self.ext_rng.random::<f64>();
3097        let word1_pick = self.name_rng.random::<f64>();
3098        let word2_pick = self.name_rng.random::<f64>();
3099        let size_pick = self.size_rng.random::<f64>();
3100
3101        let entry = &self.entries[pick_index(ext_pick, self.entries.len())];
3102        let word1 = FILE_NAME_WORDS[pick_index(word1_pick, FILE_NAME_WORDS.len())];
3103        let word2 = FILE_NAME_WORDS[pick_index(word2_pick, FILE_NAME_WORDS.len())];
3104        let name = format!("{word1}_{word2}_{row_index}.{}", entry.extension);
3105
3106        let mut slot = 0usize;
3107        output[slot] = GeneratedValue::Text(name);
3108        slot += 1;
3109        if self.has_extension {
3110            output[slot] = GeneratedValue::Text(entry.extension.to_string());
3111            slot += 1;
3112        }
3113        if self.has_mime_type {
3114            output[slot] = GeneratedValue::Text(entry.mime_type.to_string());
3115            slot += 1;
3116        }
3117        if let Some(family) = &self.size_family {
3118            let span = self
3119                .size_max
3120                .saturating_sub(self.size_min)
3121                .saturating_add(1);
3122            let offset = ((size_pick * span as f64) as i128).clamp(0, span - 1);
3123            output[slot] = render_key(self.size_min.saturating_add(offset), family);
3124            slot += 1;
3125        }
3126        if let Some(hash_len) = self.hash_len {
3127            let digest: String = (0..hash_len)
3128                .map(|_| HEX_DIGITS[self.hash_rng.random_range(0..HEX_DIGITS.len())] as char)
3129                .collect();
3130            output[slot] = GeneratedValue::Text(digest);
3131            slot += 1;
3132        }
3133        debug_assert_eq!(slot, output.len());
3134        Ok(())
3135    }
3136
3137    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
3138        self.predicates.clone()
3139    }
3140}
3141
3142/// Map a uniform `[0, 1)` draw to an index in `[0, len)`.
3143fn pick_index(pick: f64, len: usize) -> usize {
3144    ((pick * len as f64) as usize).min(len.saturating_sub(1))
3145}
3146
3147fn compile_file_metadata(
3148    config: &PlannerConfig,
3149    context: &CompileContext<'_>,
3150) -> Result<FileMetadataPlanner, DiagnosticBag> {
3151    const COLUMN_CODE: &str = crate::diagnostic::codes::FILE_COLUMN_MISSING.code;
3152    const SIZE_CODE: &str = crate::diagnostic::codes::FILE_SIZE_RANGE.code;
3153    const HASH_CODE: &str = crate::diagnostic::codes::FILE_HASH_KIND.code;
3154    const EXTENSIONS_CODE: &str = crate::diagnostic::codes::FILE_EXTENSIONS.code;
3155    let mut bag = DiagnosticBag::default();
3156    let table = context.table();
3157    let path = context.path();
3158    let columns = config.args.get("columns");
3159
3160    let name_col = resolve_required(columns, "name", table, path, COLUMN_CODE, &mut bag);
3161    let extension_col = resolve_optional(columns, "extension", table, path, COLUMN_CODE, &mut bag);
3162    let mime_col = resolve_optional(columns, "mime_type", table, path, COLUMN_CODE, &mut bag);
3163    let size_col = resolve_optional(columns, "size", table, path, COLUMN_CODE, &mut bag);
3164    let hash_col = resolve_optional(columns, "hash", table, path, COLUMN_CODE, &mut bag);
3165
3166    let requested_extensions = string_list(config.args.get("extensions"));
3167    let mut entries: Vec<&'static FileTypeEntry> = Vec::new();
3168    if requested_extensions.is_empty() {
3169        entries.extend(FILE_TYPE_CATALOG.iter());
3170    } else {
3171        for extension in &requested_extensions {
3172            match find_file_type(extension) {
3173                Some(entry) => entries.push(entry),
3174                None => {
3175                    bag.error(
3176                        EXTENSIONS_CODE,
3177                        format!("{path}.extensions"),
3178                        format!(
3179                            "file.metadata `extensions` names `{extension}`, which is not a recognized file extension"
3180                        ),
3181                    );
3182                }
3183            }
3184        }
3185    }
3186    if entries.is_empty() && !bag.has_errors() {
3187        bag.error(
3188            EXTENSIONS_CODE,
3189            format!("{path}.extensions"),
3190            "file.metadata `extensions` must resolve to at least one recognized extension"
3191                .to_string(),
3192        );
3193    }
3194
3195    let size_block = config.args.get("size");
3196    let size_min = size_block
3197        .and_then(|s| s.get("min"))
3198        .and_then(as_i128)
3199        .unwrap_or(0);
3200    let size_max = size_block
3201        .and_then(|s| s.get("max"))
3202        .and_then(as_i128)
3203        .unwrap_or(10_000_000);
3204    // Validated unconditionally — a nonsensical `size:` block is a user error
3205    // worth reporting even when no `size` column is wired to consume it (the
3206    // disconnect itself is worth surfacing, not silently accepting).
3207    if size_min < 0 {
3208        bag.error(
3209            SIZE_CODE,
3210            format!("{path}.size.min"),
3211            format!("file.metadata `size.min` {size_min} must be >= 0"),
3212        );
3213    }
3214    if size_max < size_min {
3215        bag.error(
3216            SIZE_CODE,
3217            format!("{path}.size.max"),
3218            format!("file.metadata `size.max` {size_max} is below `size.min` {size_min}"),
3219        );
3220    }
3221
3222    let hash_kind_name = config
3223        .args
3224        .get("hash_kind")
3225        .and_then(Value::as_str)
3226        .unwrap_or("sha256");
3227    let hash_kind = HashKind::parse(hash_kind_name);
3228    if hash_col.is_some() && hash_kind.is_none() {
3229        bag.error(
3230            HASH_CODE,
3231            format!("{path}.hash_kind"),
3232            format!(
3233                "file.metadata `hash_kind` `{hash_kind_name}` is not a recognized hash kind (expected one of md5, sha1, sha256, sha512)"
3234            ),
3235        );
3236    }
3237
3238    if bag.has_errors() {
3239        return Err(bag);
3240    }
3241
3242    let name = name_col.expect("name resolved without errors");
3243    let mut writes = vec![name.name.clone()];
3244    let has_extension = extension_col.is_some();
3245    if let Some(column) = extension_col {
3246        writes.push(column.name.clone());
3247    }
3248    let has_mime_type = mime_col.is_some();
3249    if let Some(column) = mime_col {
3250        writes.push(column.name.clone());
3251    }
3252    let size_family = size_col.map(|column| {
3253        writes.push(column.name.clone());
3254        column.family.clone()
3255    });
3256    let hash_len = hash_col.map(|column| {
3257        writes.push(column.name.clone());
3258        hash_kind.unwrap_or(HashKind::Sha256).hex_len()
3259    });
3260
3261    let mut predicates = Vec::new();
3262    if let Some(size) = size_col {
3263        if size_min >= 0 {
3264            predicates.push(PlannerPredicate::NonNegative {
3265                columns: vec![size.name.clone()],
3266            });
3267        }
3268    }
3269
3270    let ext_rng = context.rng(StreamId::operator(
3271        table.name.as_str(),
3272        name.name.clone(),
3273        "file.metadata.extension",
3274    ));
3275    let name_rng = context.rng(StreamId::operator(
3276        table.name.as_str(),
3277        name.name.clone(),
3278        "file.metadata.name",
3279    ));
3280    let size_rng = context.rng(StreamId::operator(
3281        table.name.as_str(),
3282        name.name.clone(),
3283        "file.metadata.size",
3284    ));
3285    let hash_rng = context.rng(StreamId::operator(
3286        table.name.as_str(),
3287        name.name.clone(),
3288        "file.metadata.hash",
3289    ));
3290
3291    Ok(FileMetadataPlanner {
3292        writes,
3293        entries,
3294        has_extension,
3295        has_mime_type,
3296        size_family,
3297        size_min,
3298        size_max,
3299        hash_len,
3300        ext_rng,
3301        name_rng,
3302        size_rng,
3303        hash_rng,
3304        predicates,
3305    })
3306}
3307
3308/// Resolve an optional column role: `None` when the role is absent from
3309/// `columns`, `Some` when present and valid, or a compile error when present
3310/// but naming a column that does not exist on the table.
3311fn resolve_optional<'a>(
3312    columns: Option<&Value>,
3313    role: &str,
3314    table: &'a PortableTable,
3315    path: &str,
3316    code: &'static str,
3317    bag: &mut DiagnosticBag,
3318) -> Option<&'a PortableColumn> {
3319    let name = role_name(columns, role)?;
3320    let column = find_column(table, name);
3321    if column.is_none() {
3322        bag.error(
3323            code,
3324            format!("{path}.columns.{role}"),
3325            format!(
3326                "file.metadata `{role}` column `{name}` does not exist on table `{}`",
3327                table.name
3328            ),
3329        );
3330    }
3331    column
3332}