Skip to main content

sql_splitter/generate/planners/
interval.rs

1//! The `temporal.interval` planner: coordinates a start/end/duration/open
2//! column group so closed rows satisfy `end = start + duration` exactly and
3//! open rows carry a coherent null/flag state.
4//!
5//! # One instant, integer arithmetic
6//!
7//! Every timestamp is reduced to a single internal UTC instant measured in
8//! nanoseconds since the Unix epoch (an `i128`), and every duration to an
9//! integer count of unit-sized nanoseconds. The interval equation
10//! `end_ns = start_ns + duration_units * unit_nanos` is therefore pure checked
11//! integer arithmetic — floats are used only to *choose* a duration from a
12//! distribution, never to compute the equation. Timezone is carried as
13//! rendering metadata: the instant is the same regardless of the zone it is
14//! rendered in, so the equation holds across DST boundaries by construction.
15//!
16//! # Owned columns and streams
17//!
18//! The planner owns the columns named under its `columns:` mapping
19//! (`start`/`end`/`duration`, plus an optional `open` flag). Each row draws the
20//! start instant, the open-state, and the duration from three *separate* stable
21//! seed streams, then derives the dependent columns rather than redrawing — so
22//! the open decision never perturbs the duration stream and a seeded run
23//! repeats exactly.
24
25use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
26use chrono_tz::Tz;
27use rand::RngExt;
28use rand_chacha::ChaCha8Rng;
29use serde_yaml_ng::Value;
30
31use crate::diagnostic::DiagnosticBag;
32use crate::generate::registry::{
33    ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledPlanner, Determinism,
34    PlannerDescriptor, PlannerFactory, PlannerPredicate, PredicateGuard, Verification,
35};
36use crate::generate::seed::StreamId;
37use crate::generate::value::{GenerateError, GeneratedValue};
38use crate::synthetic::model::PlannerConfig;
39use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
40
41/// Nanoseconds per second, the base unit conversion for the interval equation.
42const NANOS_PER_SECOND: i128 = 1_000_000_000;
43
44/// Static description of the `temporal.interval` planner.
45pub static TEMPORAL_INTERVAL_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
46    kind: "temporal.interval",
47    aliases: &[],
48    summary: "Coordinates a start/end/duration/open interval group so closed rows satisfy end = start + duration.",
49    arguments: &[
50        ArgumentSpec {
51            name: "columns",
52            required: true,
53            summary: "Maps the required start, end, and duration roles plus an optional open role to columns.",
54        },
55        ArgumentSpec {
56            name: "start",
57            required: true,
58            summary: "Configures the range, observed range, or monotonic start timestamp draw.",
59        },
60        ArgumentSpec {
61            name: "duration",
62            required: false,
63            summary: "Configures the fixed, uniform, normal, histogram, or observed duration draw.",
64        },
65        ArgumentSpec {
66            name: "open_probability",
67            required: false,
68            summary: "Probability that a row is open and therefore has no end timestamp.",
69        },
70        ArgumentSpec {
71            name: "open_value",
72            required: false,
73            summary: "Boolean value written to the optional open column for an open row.",
74        },
75        ArgumentSpec {
76            name: "end_inclusive",
77            required: false,
78            summary: "Whether the end timestamp is inclusive of the final duration unit.",
79        },
80        ArgumentSpec {
81            name: "timezone",
82            required: false,
83            summary: "Timestamp rendering zone: preserve, utc, or an IANA timezone name.",
84        },
85    ],
86    writes: ColumnScope::Configured,
87    reads: ColumnScope::None,
88    determinism: Determinism::Deterministic,
89    buffering: Buffering::Streaming,
90    verification: Verification::Supported,
91    cross_table: false,
92};
93
94/// Factory for the `temporal.interval` planner.
95pub struct TemporalIntervalFactory;
96
97impl PlannerFactory for TemporalIntervalFactory {
98    fn descriptor(&self) -> &'static PlannerDescriptor {
99        &TEMPORAL_INTERVAL_DESCRIPTOR
100    }
101
102    fn compile(
103        &self,
104        config: &PlannerConfig,
105        context: &CompileContext<'_>,
106    ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
107        compile_interval(config, context)
108            .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
109    }
110}
111
112// --- Resolved column roles --------------------------------------------------
113
114/// A resolved timestamp column: its schema name and family (so the rendered
115/// value takes the `DateTime` or `Text` shape the column expects).
116struct TimestampColumn {
117    name: String,
118    family: SqlTypeFamily,
119}
120
121/// A resolved duration column: name, family, whether it is nullable (open rows
122/// null it out when possible), and how many nanoseconds one unit represents.
123struct DurationColumn {
124    name: String,
125    family: SqlTypeFamily,
126    nullable: bool,
127    unit_nanos: i128,
128}
129
130/// A resolved open-flag column: name, family, and the flag value an *open* row
131/// carries (a closed row carries its negation).
132struct OpenColumn {
133    name: String,
134    family: SqlTypeFamily,
135    open_value: bool,
136}
137
138/// How each row's start instant is chosen.
139enum StartKind {
140    /// A uniformly random instant in the inclusive `[min_ns, max_ns]` range.
141    /// Covers both `range` and `observed_range` (the latter's bounds come from
142    /// an observed profile; the mechanism is identical).
143    Range { min_ns: i128, max_ns: i128 },
144    /// A strictly increasing instant: row `n` starts at `min_ns + n * step_ns`.
145    Monotonic { min_ns: i128, step_ns: i128 },
146}
147
148/// How each row's duration (in whole units) is chosen. All variants yield a
149/// non-negative integer count of units bounded by the configured range.
150enum DurationDraw {
151    Fixed(i128),
152    Uniform {
153        min: i128,
154        max: i128,
155    },
156    Normal {
157        mean: f64,
158        stddev: f64,
159        min: i128,
160        max: i128,
161    },
162    /// A bounded draw skewed toward the minimum (short durations are common).
163    /// Covers both `histogram` and `observed`.
164    Skewed {
165        min: i128,
166        max: i128,
167    },
168}
169
170/// How instants are rendered to wall-clock text.
171enum RenderZone {
172    /// Render UTC wall clock with no offset (`preserve` keeps the observed
173    /// zone; with no observed original zone it renders as UTC).
174    Utc,
175    /// Render the wall clock of a named IANA zone, DST-aware, with an explicit
176    /// offset so the absolute instant round-trips.
177    Named(Tz),
178}
179
180// --- The compiled planner ---------------------------------------------------
181
182/// The compiled `temporal.interval` planner.
183struct TemporalIntervalPlanner {
184    /// Owned columns in `generate_row` write order: `[start, end, duration]`
185    /// plus `open` when configured.
186    writes: Vec<String>,
187    start: TimestampColumn,
188    end: TimestampColumn,
189    duration: DurationColumn,
190    open: Option<OpenColumn>,
191    start_kind: StartKind,
192    duration_draw: DurationDraw,
193    open_probability: f64,
194    end_inclusive: bool,
195    zone: RenderZone,
196    start_rng: ChaCha8Rng,
197    open_rng: ChaCha8Rng,
198    duration_rng: ChaCha8Rng,
199    predicates: Vec<PlannerPredicate>,
200}
201
202impl CompiledPlanner for TemporalIntervalPlanner {
203    fn writes(&self) -> &[String] {
204        &self.writes
205    }
206
207    fn generate_row(
208        &mut self,
209        row_index: u64,
210        output: &mut [GeneratedValue],
211    ) -> Result<(), GenerateError> {
212        // Draw all three streams unconditionally and in a fixed order so the
213        // open decision never perturbs the duration stream: a seeded run
214        // repeats regardless of which rows land open.
215        // Rendering and verification operate at whole-second precision, so align
216        // the drawn start to a second boundary. Otherwise a sub-second start
217        // absorbs the inclusive `end = start + span - 1ns` adjustment and the
218        // rendered end lands a second later than the verifier — which recomputes
219        // from the second-precision start it parses back — expects.
220        let start_ns = self.draw_start(row_index).div_euclid(NANOS_PER_SECOND) * NANOS_PER_SECOND;
221        let is_open =
222            self.open_probability > 0.0 && self.open_rng.random::<f64>() < self.open_probability;
223        let duration_units = self.draw_duration();
224
225        output[0] = render_instant(start_ns, &self.zone, &self.start.family)?;
226
227        if is_open {
228            output[1] = GeneratedValue::Null;
229            output[2] = self.open_duration();
230        } else {
231            let span_ns = duration_units
232                .checked_mul(self.duration.unit_nanos)
233                .ok_or_else(interval_overflow)?;
234            // Inclusive `[start, end]` renders `end` as the last covered instant
235            // — one nanosecond (the smallest internal unit) before the half-open
236            // boundary. Exclusive `[start, end)` renders the boundary itself.
237            // A positive duration is guaranteed at compile time for the
238            // inclusive case, so the subtraction never goes below `start`.
239            let delta_ns = if self.end_inclusive {
240                span_ns - 1
241            } else {
242                span_ns
243            };
244            let end_ns = start_ns
245                .checked_add(delta_ns)
246                .ok_or_else(interval_overflow)?;
247            output[1] = render_instant(end_ns, &self.zone, &self.end.family)?;
248            output[2] = render_duration(duration_units, &self.duration.family);
249        }
250
251        if let Some(open) = &self.open {
252            let flag = is_open == open.open_value;
253            output[3] = render_flag(flag, &open.family);
254        }
255        Ok(())
256    }
257
258    fn verification_predicates(&self) -> Vec<PlannerPredicate> {
259        self.predicates.clone()
260    }
261}
262
263impl TemporalIntervalPlanner {
264    /// The start instant for `row_index`, in epoch nanoseconds.
265    fn draw_start(&mut self, row_index: u64) -> i128 {
266        match self.start_kind {
267            StartKind::Range { min_ns, max_ns } => self.start_rng.random_range(min_ns..=max_ns),
268            StartKind::Monotonic { min_ns, step_ns } => {
269                // Saturating keeps a very long run inside the representable
270                // range instead of wrapping; the equation still holds on the
271                // clamped instant.
272                min_ns.saturating_add(step_ns.saturating_mul(row_index as i128))
273            }
274        }
275    }
276
277    /// The duration for a row, in whole units (always non-negative).
278    fn draw_duration(&mut self) -> i128 {
279        match self.duration_draw {
280            DurationDraw::Fixed(value) => value,
281            DurationDraw::Uniform { min, max } => self.draw_uniform(min, max),
282            DurationDraw::Skewed { min, max } => {
283                if max <= min {
284                    return min;
285                }
286                let t = self.duration_rng.random::<f64>();
287                // Square biases the draw toward `min` (short intervals common)
288                // while staying within `[min, max]`.
289                let span = (max - min) as f64;
290                min + (span * t * t) as i128
291            }
292            DurationDraw::Normal {
293                mean,
294                stddev,
295                min,
296                max,
297            } => {
298                let z = self.standard_normal();
299                let value = (mean + z * stddev).round() as i128;
300                // Tolerate an inverted range (min > max) like the uniform/skewed
301                // arms: collapse to `min` rather than panicking in std `clamp`.
302                value.clamp(min, min.max(max))
303            }
304        }
305    }
306
307    /// A uniform integer draw in `[min, max]`, tolerant of an inverted range.
308    fn draw_uniform(&mut self, min: i128, max: i128) -> i128 {
309        if max <= min {
310            min
311        } else {
312            self.duration_rng.random_range(min..=max)
313        }
314    }
315
316    /// A standard-normal draw via Box–Muller from the duration stream.
317    fn standard_normal(&mut self) -> f64 {
318        // Guard the log against exactly zero.
319        let u1 = (self.duration_rng.random::<f64>()).max(f64::MIN_POSITIVE);
320        let u2 = self.duration_rng.random::<f64>();
321        (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
322    }
323
324    /// The duration value an open row carries: `NULL` when the column is
325    /// nullable, otherwise a coherent zero (no completed duration yet).
326    fn open_duration(&self) -> GeneratedValue {
327        if self.duration.nullable {
328            GeneratedValue::Null
329        } else {
330            render_duration(0, &self.duration.family)
331        }
332    }
333}
334
335// --- Rendering --------------------------------------------------------------
336
337/// Render an epoch-nanosecond instant to a wall-clock literal in `zone`, in the
338/// representation `family` expects.
339fn render_instant(
340    instant_ns: i128,
341    zone: &RenderZone,
342    family: &SqlTypeFamily,
343) -> Result<GeneratedValue, GenerateError> {
344    let text = format_instant(instant_ns, zone)?;
345    Ok(match family {
346        SqlTypeFamily::DateTime => GeneratedValue::DateTime(text),
347        _ => GeneratedValue::Text(text),
348    })
349}
350
351/// Format an epoch-nanosecond instant as wall-clock text in `zone`. An instant
352/// outside chrono's representable timestamp range is an error rather than a
353/// silent fallback to the 1970 epoch (which would break the interval equation).
354fn format_instant(instant_ns: i128, zone: &RenderZone) -> Result<String, GenerateError> {
355    let secs = instant_ns.div_euclid(NANOS_PER_SECOND);
356    let nanos = instant_ns.rem_euclid(NANOS_PER_SECOND) as u32;
357    let secs = i64::try_from(secs).map_err(|_| instant_overflow())?;
358    let utc = DateTime::<Utc>::from_timestamp(secs, nanos).ok_or_else(instant_overflow)?;
359    Ok(match zone {
360        RenderZone::Utc => utc.format("%Y-%m-%d %H:%M:%S").to_string(),
361        // Include the offset for a named zone so the absolute instant round-
362        // trips even across a DST transition (the offset disambiguates the
363        // repeated wall-clock hour).
364        RenderZone::Named(tz) => utc
365            .with_timezone(tz)
366            .format("%Y-%m-%d %H:%M:%S%:z")
367            .to_string(),
368    })
369}
370
371/// The error for an interval arithmetic step that overflows the representable
372/// instant range.
373fn interval_overflow() -> GenerateError {
374    GenerateError::Overflow(
375        "temporal.interval: start + duration overflows the representable instant range".to_string(),
376    )
377}
378
379/// The error for an instant that falls outside chrono's representable range.
380fn instant_overflow() -> GenerateError {
381    GenerateError::Overflow(
382        "temporal.interval: instant is outside the representable timestamp range".to_string(),
383    )
384}
385
386/// Render a duration (in whole units) in the representation `family` expects.
387fn render_duration(units: i128, family: &SqlTypeFamily) -> GeneratedValue {
388    match family {
389        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(units),
390        _ => GeneratedValue::Text(units.to_string()),
391    }
392}
393
394/// Render an open-flag boolean in the representation `family` expects.
395fn render_flag(flag: bool, family: &SqlTypeFamily) -> GeneratedValue {
396    match family {
397        SqlTypeFamily::Boolean => GeneratedValue::Boolean(flag),
398        SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(flag as i128),
399        _ => GeneratedValue::Text(flag.to_string()),
400    }
401}
402
403// --- Compilation ------------------------------------------------------------
404
405/// Validate `config` against the table schema and build the compiled planner,
406/// gathering every independent error before returning.
407fn compile_interval(
408    config: &PlannerConfig,
409    context: &CompileContext<'_>,
410) -> Result<TemporalIntervalPlanner, DiagnosticBag> {
411    let mut bag = DiagnosticBag::default();
412    let table = context.table();
413    let path = context.path();
414
415    let columns = config.args.get("columns");
416    let start_col = resolve_role(columns, "start", table, path, &mut bag);
417    let end_col = resolve_role(columns, "end", table, path, &mut bag);
418    let duration_col = resolve_role(columns, "duration", table, path, &mut bag);
419    // `open` is optional; only resolve it (and validate existence) if named.
420    let open_col = role_name(columns, "open").and_then(|name| {
421        find_column(table, name).or_else(|| {
422            bag.error(
423                crate::diagnostic::codes::INTERVAL_COLUMN_MISSING.code,
424                format!("{path}.columns.open"),
425                format!(
426                    "temporal.interval `open` column `{name}` does not exist on table `{}`",
427                    table.name
428                ),
429            );
430            None
431        })
432    });
433
434    let open_probability = config
435        .args
436        .get("open_probability")
437        .and_then(as_f64)
438        .unwrap_or(0.0)
439        .clamp(0.0, 1.0);
440
441    // A non-nullable end cannot represent an open (end-less) row.
442    if open_probability > 0.0 {
443        if let Some(end) = end_col {
444            if !end.nullable {
445                bag.error(
446                    crate::diagnostic::codes::INTERVAL_OPEN_END.code,
447                    format!("{path}.open_probability"),
448                    format!(
449                        "temporal.interval has open_probability {open_probability} but its `end` column `{}` is not nullable; an open row needs a null end",
450                        end.name
451                    ),
452                );
453            }
454        }
455    }
456
457    let end_inclusive = config
458        .args
459        .get("end_inclusive")
460        .and_then(Value::as_bool)
461        .unwrap_or(false);
462
463    let start_kind = compile_start(config.args.get("start"), path, &mut bag);
464    let (duration_draw, unit_nanos) = compile_duration(config.args.get("duration"), path, &mut bag);
465    let zone = compile_zone(config.args.get("timezone"), path, &mut bag);
466
467    // An inclusive interval renders `end = start + duration - 1ns`, so a
468    // zero-length interval (minimum duration of 0) is impossible: `end` would
469    // fall before `start`. Require a strictly positive minimum duration.
470    if end_inclusive {
471        if let Some(draw) = &duration_draw {
472            if min_duration_units(draw) < 1 {
473                bag.error(
474                    crate::diagnostic::codes::INTERVAL_DURATION.code,
475                    format!("{path}.duration"),
476                    "temporal.interval `end_inclusive: true` requires a minimum duration of at least 1 unit; a zero-length closed interval is impossible".to_string(),
477                );
478            }
479        }
480    }
481
482    // Bail before touching the (possibly unresolved) column roles.
483    if bag.has_errors() {
484        return Err(bag);
485    }
486
487    let start = start_col.expect("start resolved without errors");
488    let end = end_col.expect("end resolved without errors");
489    let duration = duration_col.expect("duration resolved without errors");
490    let start_kind = start_kind.expect("start kind resolved without errors");
491    let duration_draw = duration_draw.expect("duration resolved without errors");
492    let unit_nanos = unit_nanos.expect("duration unit resolved without errors");
493    let zone = zone.expect("zone resolved without errors");
494
495    let start = TimestampColumn {
496        name: start.name.clone(),
497        family: start.family.clone(),
498    };
499    let end = TimestampColumn {
500        name: end.name.clone(),
501        family: end.family.clone(),
502    };
503    let duration = DurationColumn {
504        name: duration.name.clone(),
505        family: duration.family.clone(),
506        nullable: duration.nullable,
507        unit_nanos,
508    };
509    let open = open_col.map(|column| OpenColumn {
510        name: column.name.clone(),
511        family: column.family.clone(),
512        open_value: config
513            .args
514            .get("open_value")
515            .and_then(Value::as_bool)
516            .unwrap_or(true),
517    });
518
519    let mut writes = vec![start.name.clone(), end.name.clone(), duration.name.clone()];
520    if let Some(open) = &open {
521        writes.push(open.name.clone());
522    }
523
524    let (start_rng, open_rng, duration_rng) = build_streams(context, &start, &open, &duration);
525    let predicates = build_predicates(
526        &start,
527        &end,
528        &duration,
529        open.as_ref(),
530        &start_kind,
531        open_probability,
532        end_inclusive,
533    );
534
535    Ok(TemporalIntervalPlanner {
536        writes,
537        start,
538        end,
539        duration,
540        open,
541        start_kind,
542        duration_draw,
543        open_probability,
544        end_inclusive,
545        zone,
546        start_rng,
547        open_rng,
548        duration_rng,
549        predicates,
550    })
551}
552
553/// Resolve a required column role to its schema column, reporting a missing
554/// role or a role naming an absent column.
555fn resolve_role<'a>(
556    columns: Option<&Value>,
557    role: &str,
558    table: &'a PortableTable,
559    path: &str,
560    bag: &mut DiagnosticBag,
561) -> Option<&'a PortableColumn> {
562    let Some(name) = role_name(columns, role) else {
563        bag.error(
564            crate::diagnostic::codes::INTERVAL_COLUMN_MISSING.code,
565            format!("{path}.columns.{role}"),
566            format!("temporal.interval requires a `{role}` column under `columns`"),
567        );
568        return None;
569    };
570    let column = find_column(table, name);
571    if column.is_none() {
572        bag.error(
573            crate::diagnostic::codes::INTERVAL_COLUMN_MISSING.code,
574            format!("{path}.columns.{role}"),
575            format!(
576                "temporal.interval `{role}` column `{name}` does not exist on table `{}`",
577                table.name
578            ),
579        );
580    }
581    column
582}
583
584/// The column name a `columns:` mapping assigns to `role`, if any.
585fn role_name<'a>(columns: Option<&'a Value>, role: &str) -> Option<&'a str> {
586    columns?.get(role).and_then(Value::as_str)
587}
588
589fn find_column<'a>(table: &'a PortableTable, name: &str) -> Option<&'a PortableColumn> {
590    table.columns.iter().find(|column| column.name == name)
591}
592
593/// Compile the `start:` block into a [`StartKind`]. Returns `None` (after
594/// recording an error) when the config is malformed.
595fn compile_start(start: Option<&Value>, path: &str, bag: &mut DiagnosticBag) -> Option<StartKind> {
596    let kind = start.and_then(|s| s.get("kind")).and_then(Value::as_str);
597    let min_ns = start
598        .and_then(|s| s.get("min"))
599        .and_then(as_instant_ns)
600        .or_else(|| {
601            bag.error(
602                crate::diagnostic::codes::INTERVAL_START.code,
603                format!("{path}.start.min"),
604                "temporal.interval `start` requires a parseable `min` timestamp".to_string(),
605            );
606            None
607        })?;
608
609    match kind {
610        Some("monotonic") => {
611            let step_seconds = start
612                .and_then(|s| s.get("step_seconds"))
613                .and_then(as_i128)
614                .unwrap_or(1)
615                .max(1);
616            Some(StartKind::Monotonic {
617                min_ns,
618                step_ns: step_seconds.saturating_mul(NANOS_PER_SECOND),
619            })
620        }
621        // `range`, `observed_range`, or an omitted kind: a bounded random draw.
622        _ => {
623            let max_ns = start
624                .and_then(|s| s.get("max"))
625                .and_then(as_instant_ns)
626                .or_else(|| {
627                    bag.error(
628                        crate::diagnostic::codes::INTERVAL_START.code,
629                        format!("{path}.start.max"),
630                        "temporal.interval `start` range requires a parseable `max` timestamp"
631                            .to_string(),
632                    );
633                    None
634                })?;
635            if max_ns < min_ns {
636                bag.error(
637                    crate::diagnostic::codes::INTERVAL_START.code,
638                    format!("{path}.start"),
639                    "temporal.interval `start.max` is before `start.min`".to_string(),
640                );
641                return None;
642            }
643            Some(StartKind::Range { min_ns, max_ns })
644        }
645    }
646}
647
648/// Compile the `duration:` block into a [`DurationDraw`] plus its unit size in
649/// nanoseconds. Reports negative and overflowing durations and unknown units.
650fn compile_duration(
651    duration: Option<&Value>,
652    path: &str,
653    bag: &mut DiagnosticBag,
654) -> (Option<DurationDraw>, Option<i128>) {
655    let unit = duration
656        .and_then(|d| d.get("unit"))
657        .and_then(Value::as_str)
658        .unwrap_or("seconds");
659    let Some(unit_nanos) = unit_nanos(unit) else {
660        bag.error(
661            crate::diagnostic::codes::INTERVAL_DURATION.code,
662            format!("{path}.duration.unit"),
663            format!("temporal.interval `duration.unit` `{unit}` is not a recognized time unit"),
664        );
665        return (None, None);
666    };
667
668    let field_i128 = |key: &str| duration.and_then(|d| d.get(key)).and_then(as_i128);
669    let field_f64 = |key: &str| duration.and_then(|d| d.get(key)).and_then(as_f64);
670    let kind = duration.and_then(|d| d.get("kind")).and_then(Value::as_str);
671
672    let draw = match kind {
673        Some("fixed") => {
674            let value = field_i128("value").unwrap_or(0);
675            check_nonneg_bounded(value, unit_nanos, path, bag);
676            DurationDraw::Fixed(value)
677        }
678        Some("normal") => {
679            let mean = field_f64("mean").unwrap_or(0.0);
680            let stddev = field_f64("stddev").unwrap_or(0.0).abs();
681            let min = field_i128("min").unwrap_or(0);
682            let max = field_i128("max").unwrap_or(min);
683            check_nonneg_bounded(min, unit_nanos, path, bag);
684            check_nonneg_bounded(max, unit_nanos, path, bag);
685            DurationDraw::Normal {
686                mean,
687                stddev,
688                min,
689                max,
690            }
691        }
692        Some("histogram") | Some("observed") => {
693            let min = field_i128("min").unwrap_or(0);
694            let max = field_i128("max").unwrap_or(min);
695            check_nonneg_bounded(min, unit_nanos, path, bag);
696            check_nonneg_bounded(max, unit_nanos, path, bag);
697            DurationDraw::Skewed { min, max }
698        }
699        // `uniform`, or an omitted kind.
700        _ => {
701            let min = field_i128("min").unwrap_or(0);
702            let max = field_i128("max").unwrap_or(min);
703            check_nonneg_bounded(min, unit_nanos, path, bag);
704            check_nonneg_bounded(max, unit_nanos, path, bag);
705            DurationDraw::Uniform { min, max }
706        }
707    };
708
709    (Some(draw), Some(unit_nanos))
710}
711
712/// The smallest duration (in whole units) a draw can ever yield. Used to reject
713/// a zero-length inclusive interval at compile time.
714fn min_duration_units(draw: &DurationDraw) -> i128 {
715    match draw {
716        DurationDraw::Fixed(value) => *value,
717        DurationDraw::Uniform { min, .. }
718        | DurationDraw::Skewed { min, .. }
719        | DurationDraw::Normal { min, .. } => *min,
720    }
721}
722
723/// Report a negative duration bound or one whose nanosecond span overflows.
724fn check_nonneg_bounded(units: i128, unit_nanos: i128, path: &str, bag: &mut DiagnosticBag) {
725    if units < 0 {
726        bag.error(
727            crate::diagnostic::codes::INTERVAL_DURATION.code,
728            format!("{path}.duration"),
729            format!("temporal.interval duration `{units}` is negative; durations must be >= 0"),
730        );
731    } else if units.checked_mul(unit_nanos).is_none() {
732        bag.error(
733            crate::diagnostic::codes::INTERVAL_DURATION.code,
734            format!("{path}.duration"),
735            format!(
736                "temporal.interval duration `{units}` overflows the representable nanosecond range at this unit"
737            ),
738        );
739    }
740}
741
742/// Compile the `timezone:` value into a [`RenderZone`]. An unknown IANA name is
743/// a `GEN-INTERVAL-TIMEZONE` error.
744fn compile_zone(zone: Option<&Value>, path: &str, bag: &mut DiagnosticBag) -> Option<RenderZone> {
745    match zone.and_then(Value::as_str).unwrap_or("preserve") {
746        "preserve" | "utc" | "UTC" => Some(RenderZone::Utc),
747        name => match name.parse::<Tz>() {
748            Ok(tz) => Some(RenderZone::Named(tz)),
749            Err(_) => {
750                bag.error(
751                    crate::diagnostic::codes::INTERVAL_TIMEZONE.code,
752                    format!("{path}.timezone"),
753                    format!("temporal.interval `timezone` `{name}` is not a valid IANA zone name"),
754                );
755                None
756            }
757        },
758    }
759}
760
761/// Build the three independent per-row streams (start, open, duration) keyed on
762/// each role's column so they stay stable and mutually independent.
763fn build_streams(
764    context: &CompileContext<'_>,
765    start: &TimestampColumn,
766    open: &Option<OpenColumn>,
767    duration: &DurationColumn,
768) -> (ChaCha8Rng, ChaCha8Rng, ChaCha8Rng) {
769    let table = context.table().name.as_str();
770    let open_key = open.as_ref().map_or("open", |column| column.name.as_str());
771    (
772        context.rng(StreamId::operator(
773            table,
774            start.name.clone(),
775            "temporal.interval.start",
776        )),
777        context.rng(StreamId::operator(
778            table,
779            open_key.to_string(),
780            "temporal.interval.open",
781        )),
782        context.rng(StreamId::operator(
783            table,
784            duration.name.clone(),
785            "temporal.interval.duration",
786        )),
787    )
788}
789
790/// Build the verification predicates the planner guarantees over its columns.
791fn build_predicates(
792    start: &TimestampColumn,
793    end: &TimestampColumn,
794    duration: &DurationColumn,
795    open: Option<&OpenColumn>,
796    start_kind: &StartKind,
797    open_probability: f64,
798    end_inclusive: bool,
799) -> Vec<PlannerPredicate> {
800    let mut predicates = Vec::new();
801
802    // Which rows are closed (and so satisfy the equation): all rows when no row
803    // is ever open, else those the open flag / null end marks closed.
804    let closed_guard = if open_probability > 0.0 {
805        match open {
806            Some(open) => Some(PredicateGuard::Flag {
807                column: open.name.clone(),
808                value: !open.open_value,
809            }),
810            None => Some(PredicateGuard::Null {
811                column: end.name.clone(),
812                is_null: false,
813            }),
814        }
815    } else {
816        None
817    };
818
819    predicates.push(PlannerPredicate::Equation {
820        start: start.name.clone(),
821        end: end.name.clone(),
822        duration: duration.name.clone(),
823        duration_unit_nanos: duration.unit_nanos,
824        end_inclusive,
825        guard: closed_guard,
826    });
827
828    // Open rows have a null end — checkable only when an explicit flag marks
829    // them (otherwise "end is null when open" is a tautology on the end column).
830    if open_probability > 0.0 {
831        if let Some(open) = open {
832            predicates.push(PlannerPredicate::NullWhen {
833                column: end.name.clone(),
834                guard: PredicateGuard::Flag {
835                    column: open.name.clone(),
836                    value: open.open_value,
837                },
838            });
839        }
840    }
841
842    if let StartKind::Range { min_ns, max_ns } = start_kind {
843        predicates.push(PlannerPredicate::InRange {
844            column: start.name.clone(),
845            min_nanos: *min_ns,
846            max_nanos: *max_ns,
847        });
848    }
849
850    predicates
851}
852
853// --- Value parsing helpers --------------------------------------------------
854
855fn unit_nanos(unit: &str) -> Option<i128> {
856    let nanos = match unit {
857        "nanosecond" | "nanoseconds" | "ns" => 1,
858        "microsecond" | "microseconds" | "us" => 1_000,
859        "millisecond" | "milliseconds" | "ms" => 1_000_000,
860        "second" | "seconds" | "sec" | "s" => NANOS_PER_SECOND,
861        "minute" | "minutes" | "min" => 60 * NANOS_PER_SECOND,
862        "hour" | "hours" | "hr" | "h" => 3_600 * NANOS_PER_SECOND,
863        "day" | "days" | "d" => 86_400 * NANOS_PER_SECOND,
864        _ => return None,
865    };
866    Some(nanos)
867}
868
869fn as_i128(value: &Value) -> Option<i128> {
870    match value {
871        Value::Number(number) => number
872            .as_i64()
873            .map(i128::from)
874            .or_else(|| number.as_u64().map(i128::from))
875            .or_else(|| number.as_f64().map(|float| float as i128)),
876        Value::String(text) => text.trim().parse::<i128>().ok(),
877        _ => None,
878    }
879}
880
881fn as_f64(value: &Value) -> Option<f64> {
882    match value {
883        Value::Number(number) => number.as_f64(),
884        Value::String(text) => text.trim().parse::<f64>().ok(),
885        _ => None,
886    }
887}
888
889/// Parse a timestamp value into epoch nanoseconds. Accepts RFC 3339
890/// (`2024-01-01T00:00:00Z`), space- or `T`-separated naive timestamps, and bare
891/// dates (interpreted as UTC midnight).
892fn as_instant_ns(value: &Value) -> Option<i128> {
893    let text = value.as_str()?.trim();
894    if let Ok(dt) = DateTime::parse_from_rfc3339(text) {
895        return Some(
896            i128::from(dt.timestamp()) * NANOS_PER_SECOND + i128::from(dt.timestamp_subsec_nanos()),
897        );
898    }
899    for format in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"] {
900        if let Ok(naive) = NaiveDateTime::parse_from_str(text, format) {
901            return Some(i128::from(naive.and_utc().timestamp()) * NANOS_PER_SECOND);
902        }
903    }
904    NaiveDate::parse_from_str(text, "%Y-%m-%d")
905        .ok()
906        .and_then(|date| date.and_hms_opt(0, 0, 0))
907        .map(|naive| i128::from(naive.and_utc().timestamp()) * NANOS_PER_SECOND)
908}