1use 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
56const NANOS_PER_SECOND: i128 = 1_000_000_000;
58
59#[derive(Clone, Copy)]
67enum InstantDraw {
68 Range { min_ns: i128, max_ns: i128 },
70 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#[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
108fn 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 _ => {
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
169fn 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 _ => {
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
226fn 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
252fn 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
268fn 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
285fn 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
302fn 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
311fn render_status(status: &str, _family: &SqlTypeFamily) -> GeneratedValue {
313 GeneratedValue::Text(status.to_string())
314}
315
316fn 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
354fn 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
387fn 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
399fn 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
407pub 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
446pub 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
464struct 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 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
664fn 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
696pub 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
737pub 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 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 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 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
955pub 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
999pub 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
1017struct StateSlot {
1019 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 weights: Vec<f64>,
1031 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 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
1086fn 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 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 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, ×tamp_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
1360pub 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
1413pub 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
1430struct HierarchyTreePlanner {
1435 writes: Vec<String>,
1436 parent_family: SqlTypeFamily,
1437 depth_family: Option<SqlTypeFamily>,
1440 root_ratio: f64,
1441 max_depth: u32,
1442 max_branching: Option<u32>,
1444 key_start: i128,
1447 key_step: i128,
1448 decision_rng: ChaCha8Rng,
1449 select_rng: ChaCha8Rng,
1450 eligible: Vec<EligibleNode>,
1456 predicates: Vec<PlannerPredicate>,
1457}
1458
1459struct EligibleNode {
1462 index: usize,
1463 depth: u32,
1464 remaining: u32,
1465}
1466
1467impl HierarchyTreePlanner {
1468 fn key_of(&self, row_index: usize) -> i128 {
1470 self.key_start + self.key_step * row_index as i128
1471 }
1472
1473 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 let decision = self.decision_rng.random::<f64>();
1495 let selection = self.select_rng.random::<f64>();
1496
1497 let n = row_index as usize;
1498 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 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 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 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 } else if max_depth > u32::MAX as i128 {
1603 bag.error(
1606 DEPTH_CODE,
1607 format!("{path}.max_depth"),
1608 format!(
1609 "hierarchy.tree `max_depth` {max_depth} exceeds the maximum {}",
1610 u32::MAX
1611 ),
1612 );
1613 }
1614
1615 let max_branching = match config.args.get("max_branching").and_then(as_i128) {
1616 None => None,
1617 Some(branching) if branching < 1 => {
1618 bag.error(
1619 BRANCH_CODE,
1620 format!("{path}.max_branching"),
1621 format!(
1622 "hierarchy.tree `max_branching` {branching} must be at least 1 (omit it for unbounded branching)"
1623 ),
1624 );
1625 None
1626 }
1627 Some(branching) if branching > u32::MAX as i128 => {
1628 bag.error(
1629 BRANCH_CODE,
1630 format!("{path}.max_branching"),
1631 format!(
1632 "hierarchy.tree `max_branching` {branching} exceeds the maximum {}",
1633 u32::MAX
1634 ),
1635 );
1636 None
1637 }
1638 Some(branching) => Some(branching as u32),
1639 };
1640
1641 let facts = config.args.get(RELATION_FACTS_KEY);
1648 let (derived_start, derived_step) = config
1649 .args
1650 .get("relationship")
1651 .and_then(Value::as_str)
1652 .and_then(|name| {
1653 facts
1654 .and_then(|f| f.get("relationships"))
1655 .and_then(|r| r.get(name))
1656 })
1657 .filter(|fact| fact.get("dense").and_then(Value::as_bool) == Some(true))
1658 .map(|fact| {
1659 (
1660 fact.get("start").and_then(as_i128).unwrap_or(1),
1661 fact.get("step").and_then(as_i128).unwrap_or(1),
1662 )
1663 })
1664 .unwrap_or((1, 1));
1665
1666 let key = config.args.get("key");
1667 let key_start = key
1668 .and_then(|k| k.get("start"))
1669 .and_then(as_i128)
1670 .unwrap_or(derived_start);
1671 let key_step = key
1672 .and_then(|k| k.get("step"))
1673 .and_then(as_i128)
1674 .unwrap_or(derived_step);
1675
1676 if bag.has_errors() {
1677 return Err(bag);
1678 }
1679
1680 let depth = match columns.and_then(|c| c.get("depth")).and_then(Value::as_str) {
1683 None => None,
1684 Some(depth_name) => match table.columns.iter().find(|col| col.name == depth_name) {
1685 Some(col) => Some(col.clone()),
1686 None => {
1687 bag.error(
1688 COLUMN_CODE,
1689 format!("{path}.columns.depth"),
1690 format!(
1691 "hierarchy.tree `depth` column `{depth_name}` does not exist on table `{}`",
1692 table.name
1693 ),
1694 );
1695 None
1696 }
1697 },
1698 };
1699
1700 if bag.has_errors() {
1701 return Err(bag);
1702 }
1703
1704 let parent = parent_col.expect("parent resolved without errors");
1705 let mut writes = vec![parent.name.clone()];
1706 if let Some(depth) = &depth {
1707 writes.push(depth.name.clone());
1708 }
1709 let depth_family = depth.map(|col| col.family);
1710 let mut predicates = Vec::new();
1711 if key_start >= 0 && key_step >= 0 {
1715 predicates.push(PlannerPredicate::NonNegative {
1716 columns: vec![parent.name.clone()],
1717 });
1718 }
1719
1720 let decision_rng = context.rng(StreamId::operator(
1721 table.name.as_str(),
1722 parent.name.clone(),
1723 "hierarchy.tree.decision",
1724 ));
1725 let select_rng = context.rng(StreamId::operator(
1726 table.name.as_str(),
1727 parent.name.clone(),
1728 "hierarchy.tree.select",
1729 ));
1730
1731 Ok(HierarchyTreePlanner {
1732 writes,
1733 parent_family: parent.family.clone(),
1734 depth_family,
1735 root_ratio,
1736 max_depth: max_depth as u32,
1737 max_branching,
1738 key_start,
1739 key_step,
1740 decision_rng,
1741 select_rng,
1742 eligible: Vec::new(),
1743 predicates,
1744 })
1745}
1746
1747pub const RELATION_FACTS_KEY: &str = "__relation_facts";
1757
1758#[derive(Clone, Copy)]
1762struct DenseKey {
1763 start: i128,
1764 step: i128,
1765 count: u64,
1766}
1767
1768impl DenseKey {
1769 fn key_at(&self, index: u64) -> i128 {
1771 self.start + self.step * index as i128
1772 }
1773}
1774
1775fn render_key(key: i128, family: &SqlTypeFamily) -> GeneratedValue {
1777 match family {
1778 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(key),
1779 _ => GeneratedValue::Text(key.to_string()),
1780 }
1781}
1782
1783fn dense_key_from_relationship(
1787 facts: Option<&Value>,
1788 rel_name: &str,
1789 planner: &str,
1790 role: &str,
1791 codes: [&'static str; 2],
1792 path: &str,
1793 bag: &mut DiagnosticBag,
1794) -> Option<DenseKey> {
1795 let [missing_code, key_code] = codes;
1796 let fact = facts
1797 .and_then(|f| f.get("relationships"))
1798 .and_then(|r| r.get(rel_name));
1799 let Some(fact) = fact else {
1800 bag.error(
1801 missing_code,
1802 format!("{path}.{role}"),
1803 format!(
1804 "{planner} `{role}` names relationship `{rel_name}`, which is not declared on this table"
1805 ),
1806 );
1807 return None;
1808 };
1809 dense_key_from_fact(fact, rel_name, planner, key_code, path, bag)
1810}
1811
1812fn dense_key_from_fact(
1814 fact: &Value,
1815 label: &str,
1816 planner: &str,
1817 key_code: &'static str,
1818 path: &str,
1819 bag: &mut DiagnosticBag,
1820) -> Option<DenseKey> {
1821 let dense = fact.get("dense").and_then(Value::as_bool).unwrap_or(false);
1822 if !dense {
1823 bag.error(
1824 key_code,
1825 path.to_string(),
1826 format!(
1827 "{planner} target `{label}` does not have a dense integer key; only bare integer primary keys and `sequence` keys are supported"
1828 ),
1829 );
1830 return None;
1831 }
1832 let start = fact.get("start").and_then(as_i128).unwrap_or(1);
1833 let step = fact.get("step").and_then(as_i128).unwrap_or(1);
1834 let count = fact.get("count").and_then(Value::as_u64).unwrap_or(0);
1835 Some(DenseKey { start, step, count })
1836}
1837
1838fn gcd(mut a: i128, mut b: i128) -> i128 {
1840 while b != 0 {
1841 (a, b) = (b, a.rem_euclid(b));
1842 }
1843 a.abs()
1844}
1845
1846pub static RELATION_JUNCTION_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
1852 kind: "relation.junction_pair",
1853 aliases: &[],
1854 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.",
1855 arguments: &[
1856 ArgumentSpec {
1857 name: "columns",
1858 required: true,
1859 summary: "Maps the left and right roles to the junction table's foreign-key columns.",
1860 },
1861 ArgumentSpec {
1862 name: "left_relationship",
1863 required: true,
1864 summary: "Relationship that supplies the left dense key domain.",
1865 },
1866 ArgumentSpec {
1867 name: "right_relationship",
1868 required: true,
1869 summary: "Relationship that supplies the right dense key domain.",
1870 },
1871 ],
1872 writes: ColumnScope::Configured,
1873 reads: ColumnScope::None,
1874 determinism: Determinism::Deterministic,
1875 buffering: Buffering::Streaming,
1876 verification: Verification::Supported,
1877 cross_table: true,
1878};
1879
1880pub struct RelationJunctionPairFactory;
1882
1883impl PlannerFactory for RelationJunctionPairFactory {
1884 fn descriptor(&self) -> &'static PlannerDescriptor {
1885 &RELATION_JUNCTION_PAIR_DESCRIPTOR
1886 }
1887
1888 fn compile(
1889 &self,
1890 config: &PlannerConfig,
1891 context: &CompileContext<'_>,
1892 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
1893 compile_junction_pair(config, context)
1894 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
1895 }
1896}
1897
1898struct RelationJunctionPairPlanner {
1905 writes: Vec<String>,
1906 left_family: SqlTypeFamily,
1907 right_family: SqlTypeFamily,
1908 left: DenseKey,
1909 right: DenseKey,
1910 total: i128,
1911 stride: i128,
1912 offset: i128,
1913 predicates: Vec<PlannerPredicate>,
1914}
1915
1916impl CompiledPlanner for RelationJunctionPairPlanner {
1917 fn writes(&self) -> &[String] {
1918 &self.writes
1919 }
1920
1921 fn generate_row(
1922 &mut self,
1923 row_index: u64,
1924 output: &mut [GeneratedValue],
1925 ) -> Result<(), GenerateError> {
1926 if self.total <= 0 {
1927 output[0] = GeneratedValue::Null;
1928 output[1] = GeneratedValue::Null;
1929 return Ok(());
1930 }
1931 let idx = (self.offset + (row_index as i128) * self.stride).rem_euclid(self.total);
1932 let right_count = self.right.count as i128;
1933 let left_row = (idx.div_euclid(right_count)) as u64;
1934 let right_row = (idx.rem_euclid(right_count)) as u64;
1935 output[0] = render_key(self.left.key_at(left_row), &self.left_family);
1936 output[1] = render_key(self.right.key_at(right_row), &self.right_family);
1937 Ok(())
1938 }
1939
1940 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
1941 self.predicates.clone()
1942 }
1943}
1944
1945fn compile_junction_pair(
1946 config: &PlannerConfig,
1947 context: &CompileContext<'_>,
1948) -> Result<RelationJunctionPairPlanner, DiagnosticBag> {
1949 const COLUMN_CODE: &str = crate::diagnostic::codes::JUNCTION_COLUMN_MISSING.code;
1950 const REL_CODE: &str = crate::diagnostic::codes::JUNCTION_RELATIONSHIP.code;
1951 const KEY_CODE: &str = crate::diagnostic::codes::JUNCTION_KEY_UNSUPPORTED.code;
1952 const EXHAUSTED_CODE: &str = crate::diagnostic::codes::JUNCTION_EXHAUSTED.code;
1953 let mut bag = DiagnosticBag::default();
1954 let table = context.table();
1955 let path = context.path();
1956 let columns = config.args.get("columns");
1957 let facts = config.args.get(RELATION_FACTS_KEY);
1958
1959 let left_col = resolve_required(columns, "left", table, path, COLUMN_CODE, &mut bag);
1960 let right_col = resolve_required(columns, "right", table, path, COLUMN_CODE, &mut bag);
1961
1962 let left_rel = config
1963 .args
1964 .get("left_relationship")
1965 .and_then(Value::as_str)
1966 .map(str::to_string);
1967 let right_rel = config
1968 .args
1969 .get("right_relationship")
1970 .and_then(Value::as_str)
1971 .map(str::to_string);
1972 if left_rel.is_none() {
1973 bag.error(
1974 REL_CODE,
1975 format!("{path}.left_relationship"),
1976 "relation.junction_pair requires a `left_relationship` naming the left foreign key"
1977 .to_string(),
1978 );
1979 }
1980 if right_rel.is_none() {
1981 bag.error(
1982 REL_CODE,
1983 format!("{path}.right_relationship"),
1984 "relation.junction_pair requires a `right_relationship` naming the right foreign key"
1985 .to_string(),
1986 );
1987 }
1988
1989 let left = left_rel.as_deref().and_then(|name| {
1990 dense_key_from_relationship(
1991 facts,
1992 name,
1993 "relation.junction_pair",
1994 "left_relationship",
1995 [REL_CODE, KEY_CODE],
1996 path,
1997 &mut bag,
1998 )
1999 });
2000 let right = right_rel.as_deref().and_then(|name| {
2001 dense_key_from_relationship(
2002 facts,
2003 name,
2004 "relation.junction_pair",
2005 "right_relationship",
2006 [REL_CODE, KEY_CODE],
2007 path,
2008 &mut bag,
2009 )
2010 });
2011
2012 let self_count = facts
2015 .and_then(|f| f.get("self_count"))
2016 .and_then(Value::as_u64);
2017 if let (Some(left), Some(right), Some(rows)) = (left, right, self_count) {
2018 let total = i128::from(left.count) * i128::from(right.count);
2019 if i128::from(rows) > total {
2020 bag.error(
2021 EXHAUSTED_CODE,
2022 path.to_string(),
2023 format!(
2024 "relation.junction_pair needs {rows} unique (left, right) pairs but only {total} exist ({} left x {} right)",
2025 left.count, right.count
2026 ),
2027 );
2028 }
2029 }
2030
2031 if bag.has_errors() {
2032 return Err(bag);
2033 }
2034
2035 let left_col = left_col.expect("left resolved without errors");
2036 let right_col = right_col.expect("right resolved without errors");
2037 let left = left.expect("left key resolved without errors");
2038 let right = right.expect("right key resolved without errors");
2039 let total = i128::from(left.count) * i128::from(right.count);
2040
2041 let mut rng = context.rng(StreamId::operator(
2045 table.name.as_str(),
2046 format!("{},{}", left_col.name, right_col.name),
2047 "relation.junction_pair",
2048 ));
2049 let (stride, offset) = if total > 1 {
2050 let offset = rng.random_range(0..total);
2051 let mut stride = 1 + rng.random_range(0..total - 1);
2052 let mut tries = 0;
2053 while gcd(stride, total) != 1 && tries < 64 {
2054 stride = stride % (total - 1) + 1;
2055 tries += 1;
2056 }
2057 if gcd(stride, total) != 1 {
2058 stride = 1;
2059 }
2060 (stride, offset)
2061 } else {
2062 (1, 0)
2063 };
2064
2065 let writes = vec![left_col.name.clone(), right_col.name.clone()];
2066 let mut predicates = Vec::new();
2067 if left.start >= 0 && left.step >= 0 && right.start >= 0 && right.step >= 0 {
2068 predicates.push(PlannerPredicate::NonNegative {
2069 columns: writes.clone(),
2070 });
2071 }
2072
2073 Ok(RelationJunctionPairPlanner {
2074 writes,
2075 left_family: left_col.family.clone(),
2076 right_family: right_col.family.clone(),
2077 left,
2078 right,
2079 total,
2080 stride,
2081 offset,
2082 predicates,
2083 })
2084}
2085
2086pub static RELATION_POLYMORPHIC_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2092 kind: "relation.polymorphic_pair",
2093 aliases: &[],
2094 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.",
2095 arguments: &[
2096 ArgumentSpec {
2097 name: "columns",
2098 required: true,
2099 summary: "Maps the polymorphic type and id roles to columns.",
2100 },
2101 ArgumentSpec {
2102 name: "targets",
2103 required: true,
2104 summary: "Weighted target tables with optional type labels and id-column overrides.",
2105 },
2106 ],
2107 writes: ColumnScope::Configured,
2108 reads: ColumnScope::None,
2109 determinism: Determinism::Deterministic,
2110 buffering: Buffering::Streaming,
2111 verification: Verification::Supported,
2112 cross_table: true,
2113};
2114
2115pub struct RelationPolymorphicPairFactory;
2117
2118impl PlannerFactory for RelationPolymorphicPairFactory {
2119 fn descriptor(&self) -> &'static PlannerDescriptor {
2120 &RELATION_POLYMORPHIC_PAIR_DESCRIPTOR
2121 }
2122
2123 fn compile(
2124 &self,
2125 config: &PlannerConfig,
2126 context: &CompileContext<'_>,
2127 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2128 compile_polymorphic_pair(config, context)
2129 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2130 }
2131}
2132
2133struct PolyTarget {
2136 type_label: String,
2137 key: DenseKey,
2138}
2139
2140struct RelationPolymorphicPairPlanner {
2145 writes: Vec<String>,
2146 id_family: SqlTypeFamily,
2147 targets: Vec<PolyTarget>,
2148 weights: Vec<f64>,
2149 rng: ChaCha8Rng,
2150 predicates: Vec<PlannerPredicate>,
2151}
2152
2153impl CompiledPlanner for RelationPolymorphicPairPlanner {
2154 fn writes(&self) -> &[String] {
2155 &self.writes
2156 }
2157
2158 fn generate_row(
2159 &mut self,
2160 _row_index: u64,
2161 output: &mut [GeneratedValue],
2162 ) -> Result<(), GenerateError> {
2163 let target_pick = self.rng.random::<f64>();
2166 let id_pick = self.rng.random::<f64>();
2167 let index = pick_weighted_index(&self.weights, target_pick);
2168 let target = &self.targets[index];
2169 let row = if target.key.count == 0 {
2170 0
2171 } else {
2172 (id_pick * target.key.count as f64) as u64
2173 }
2174 .min(target.key.count.saturating_sub(1));
2175
2176 output[0] = GeneratedValue::Text(target.type_label.clone());
2177 output[1] = render_key(target.key.key_at(row), &self.id_family);
2178 Ok(())
2179 }
2180
2181 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2182 self.predicates.clone()
2183 }
2184}
2185
2186fn compile_polymorphic_pair(
2187 config: &PlannerConfig,
2188 context: &CompileContext<'_>,
2189) -> Result<RelationPolymorphicPairPlanner, DiagnosticBag> {
2190 const COLUMN_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_COLUMN_MISSING.code;
2191 const TARGETS_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_TARGETS.code;
2192 const TARGET_UNKNOWN_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_TARGET_UNKNOWN.code;
2193 const KEY_CODE: &str = crate::diagnostic::codes::POLYMORPHIC_KEY_UNSUPPORTED.code;
2194 let mut bag = DiagnosticBag::default();
2195 let table = context.table();
2196 let path = context.path();
2197 let columns = config.args.get("columns");
2198 let facts = config.args.get(RELATION_FACTS_KEY);
2199
2200 let type_col = resolve_required(columns, "type", table, path, COLUMN_CODE, &mut bag);
2201 let id_col = resolve_required(columns, "id", table, path, COLUMN_CODE, &mut bag);
2202
2203 let target_items = match config.args.get("targets") {
2204 Some(Value::Sequence(items)) if !items.is_empty() => items.as_slice(),
2205 _ => {
2206 bag.error(
2207 TARGETS_CODE,
2208 format!("{path}.targets"),
2209 "relation.polymorphic_pair requires a non-empty `targets` list".to_string(),
2210 );
2211 &[]
2212 }
2213 };
2214
2215 let mut targets = Vec::new();
2216 let mut weights = Vec::new();
2217 for (index, item) in target_items.iter().enumerate() {
2218 let target_path = format!("{path}.targets[{index}]");
2219 let Some(table_name) = item.get("table").and_then(Value::as_str) else {
2220 bag.error(
2221 TARGETS_CODE,
2222 target_path,
2223 "relation.polymorphic_pair target requires a `table`".to_string(),
2224 );
2225 continue;
2226 };
2227 let table_fact = facts
2228 .and_then(|f| f.get("tables"))
2229 .and_then(|t| t.get(table_name));
2230 let Some(table_fact) = table_fact else {
2231 bag.error(
2232 TARGET_UNKNOWN_CODE,
2233 target_path,
2234 format!(
2235 "relation.polymorphic_pair target `{table_name}` is not a table in the model"
2236 ),
2237 );
2238 continue;
2239 };
2240 let id_column = item
2242 .get("id_column")
2243 .and_then(Value::as_str)
2244 .map(str::to_string)
2245 .or_else(|| {
2246 table_fact
2247 .get("primary_key")
2248 .and_then(Value::as_str)
2249 .map(str::to_string)
2250 });
2251 let Some(id_column) = id_column else {
2252 bag.error(
2253 TARGET_UNKNOWN_CODE,
2254 target_path,
2255 format!(
2256 "relation.polymorphic_pair target `{table_name}` has no primary key; specify an `id_column`"
2257 ),
2258 );
2259 continue;
2260 };
2261 let key_fact = table_fact.get("keys").and_then(|k| k.get(&id_column));
2262 let Some(key_fact) = key_fact else {
2263 bag.error(
2264 KEY_CODE,
2265 target_path,
2266 format!(
2267 "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"
2268 ),
2269 );
2270 continue;
2271 };
2272 let Some(key) = dense_key_from_fact(
2273 key_fact,
2274 &format!("{table_name}.{id_column}"),
2275 "relation.polymorphic_pair",
2276 KEY_CODE,
2277 &target_path,
2278 &mut bag,
2279 ) else {
2280 continue;
2281 };
2282 if key.count == 0 {
2283 continue;
2286 }
2287 let type_label = item
2288 .get("type")
2289 .and_then(Value::as_str)
2290 .unwrap_or(table_name)
2291 .to_string();
2292 let weight = item.get("weight").and_then(as_f64).unwrap_or(1.0).max(0.0);
2293 targets.push(PolyTarget { type_label, key });
2294 weights.push(weight);
2295 }
2296
2297 if targets.is_empty() && !bag.has_errors() {
2298 bag.error(
2299 TARGETS_CODE,
2300 format!("{path}.targets"),
2301 "relation.polymorphic_pair has no target with any rows to reference".to_string(),
2302 );
2303 }
2304 if weights.iter().sum::<f64>() <= 0.0 && !targets.is_empty() {
2305 weights = vec![1.0; targets.len()];
2308 }
2309
2310 if bag.has_errors() {
2311 return Err(bag);
2312 }
2313
2314 let type_col = type_col.expect("type resolved without errors");
2315 let id_col = id_col.expect("id resolved without errors");
2316 let writes = vec![type_col.name.clone(), id_col.name.clone()];
2317
2318 let mut predicates = Vec::new();
2319 if targets.iter().all(|t| t.key.start >= 0 && t.key.step >= 0) {
2320 predicates.push(PlannerPredicate::NonNegative {
2321 columns: vec![id_col.name.clone()],
2322 });
2323 }
2324
2325 let rng = context.rng(StreamId::operator(
2326 table.name.as_str(),
2327 format!("{},{}", type_col.name, id_col.name),
2328 "relation.polymorphic_pair",
2329 ));
2330
2331 Ok(RelationPolymorphicPairPlanner {
2332 writes,
2333 id_family: id_col.family.clone(),
2334 targets,
2335 weights,
2336 rng,
2337 predicates,
2338 })
2339}
2340
2341pub static RELATION_TENANT_FAMILY_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2347 kind: "relation.tenant_family",
2348 aliases: &[],
2349 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.",
2350 arguments: &[
2351 ArgumentSpec {
2352 name: "columns",
2353 required: true,
2354 summary: "Maps tenant and parent roles to the child table's columns.",
2355 },
2356 ArgumentSpec {
2357 name: "relationship",
2358 required: true,
2359 summary: "Relationship that supplies the parent dense key domain.",
2360 },
2361 ArgumentSpec {
2362 name: "num_tenants",
2363 required: false,
2364 summary: "Number of contiguous tenant partitions.",
2365 },
2366 ArgumentSpec {
2367 name: "tenant_start",
2368 required: false,
2369 summary: "First generated tenant identifier.",
2370 },
2371 ],
2372 writes: ColumnScope::Configured,
2373 reads: ColumnScope::None,
2374 determinism: Determinism::Deterministic,
2375 buffering: Buffering::Streaming,
2376 verification: Verification::Supported,
2377 cross_table: true,
2378};
2379
2380pub struct RelationTenantFamilyFactory;
2382
2383impl PlannerFactory for RelationTenantFamilyFactory {
2384 fn descriptor(&self) -> &'static PlannerDescriptor {
2385 &RELATION_TENANT_FAMILY_DESCRIPTOR
2386 }
2387
2388 fn compile(
2389 &self,
2390 config: &PlannerConfig,
2391 context: &CompileContext<'_>,
2392 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2393 compile_tenant_family(config, context)
2394 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2395 }
2396}
2397
2398struct RelationTenantFamilyPlanner {
2406 writes: Vec<String>,
2407 tenant_family: SqlTypeFamily,
2408 parent_family: SqlTypeFamily,
2409 parent: DenseKey,
2410 num_tenants: u64,
2411 tenant_start: i128,
2412 tenant_rng: ChaCha8Rng,
2413 select_rng: ChaCha8Rng,
2414 predicates: Vec<PlannerPredicate>,
2415}
2416
2417impl RelationTenantFamilyPlanner {
2418 fn tenant_block(&self, t: u64) -> (u64, u64) {
2420 let count = u128::from(self.parent.count);
2421 let tenants = u128::from(self.num_tenants);
2422 let start = (u128::from(t) * count / tenants) as u64;
2423 let end = (u128::from(t + 1) * count / tenants) as u64;
2424 (start, end.max(start + 1).min(self.parent.count))
2425 }
2426}
2427
2428impl CompiledPlanner for RelationTenantFamilyPlanner {
2429 fn writes(&self) -> &[String] {
2430 &self.writes
2431 }
2432
2433 fn generate_row(
2434 &mut self,
2435 _row_index: u64,
2436 output: &mut [GeneratedValue],
2437 ) -> Result<(), GenerateError> {
2438 let tenant_pick = self.tenant_rng.random::<f64>();
2440 let parent_pick = self.select_rng.random::<f64>();
2441
2442 let tenant = ((tenant_pick * self.num_tenants as f64) as u64).min(self.num_tenants - 1);
2443 let (start, end) = self.tenant_block(tenant);
2444 let size = end - start;
2445 let offset = if size == 0 {
2446 0
2447 } else {
2448 ((parent_pick * size as f64) as u64).min(size - 1)
2449 };
2450 let parent_row = start + offset;
2451
2452 output[0] = match self.tenant_family {
2453 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => {
2454 GeneratedValue::Integer(self.tenant_start + tenant as i128)
2455 }
2456 _ => GeneratedValue::Text((self.tenant_start + tenant as i128).to_string()),
2457 };
2458 output[1] = render_key(self.parent.key_at(parent_row), &self.parent_family);
2459 Ok(())
2460 }
2461
2462 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2463 self.predicates.clone()
2464 }
2465}
2466
2467fn compile_tenant_family(
2468 config: &PlannerConfig,
2469 context: &CompileContext<'_>,
2470) -> Result<RelationTenantFamilyPlanner, DiagnosticBag> {
2471 const COLUMN_CODE: &str = crate::diagnostic::codes::TENANT_COLUMN_MISSING.code;
2472 const REL_CODE: &str = crate::diagnostic::codes::TENANT_RELATIONSHIP.code;
2473 const KEY_CODE: &str = crate::diagnostic::codes::TENANT_KEY_UNSUPPORTED.code;
2474 const PARTITION_CODE: &str = crate::diagnostic::codes::TENANT_PARTITION.code;
2475 let mut bag = DiagnosticBag::default();
2476 let table = context.table();
2477 let path = context.path();
2478 let columns = config.args.get("columns");
2479 let facts = config.args.get(RELATION_FACTS_KEY);
2480
2481 let tenant_col = resolve_required(columns, "tenant", table, path, COLUMN_CODE, &mut bag);
2482 let parent_col = resolve_required(columns, "parent", table, path, COLUMN_CODE, &mut bag);
2483
2484 let rel = config
2485 .args
2486 .get("relationship")
2487 .and_then(Value::as_str)
2488 .map(str::to_string);
2489 if rel.is_none() {
2490 bag.error(
2491 REL_CODE,
2492 format!("{path}.relationship"),
2493 "relation.tenant_family requires a `relationship` naming the parent foreign key"
2494 .to_string(),
2495 );
2496 }
2497 let parent = rel.as_deref().and_then(|name| {
2498 dense_key_from_relationship(
2499 facts,
2500 name,
2501 "relation.tenant_family",
2502 "relationship",
2503 [REL_CODE, KEY_CODE],
2504 path,
2505 &mut bag,
2506 )
2507 });
2508
2509 let num_tenants = config
2510 .args
2511 .get("num_tenants")
2512 .and_then(as_i128)
2513 .unwrap_or(4);
2514 let tenant_start = config
2515 .args
2516 .get("tenant_start")
2517 .and_then(as_i128)
2518 .unwrap_or(0);
2519
2520 if num_tenants < 1 {
2521 bag.error(
2522 PARTITION_CODE,
2523 format!("{path}.num_tenants"),
2524 format!("relation.tenant_family `num_tenants` {num_tenants} must be at least 1"),
2525 );
2526 }
2527 if let Some(parent) = parent {
2528 if num_tenants >= 1 && num_tenants as u64 > parent.count {
2529 bag.error(
2530 PARTITION_CODE,
2531 format!("{path}.num_tenants"),
2532 format!(
2533 "relation.tenant_family `num_tenants` {num_tenants} exceeds the {} parent rows, so some tenants would have no parent to reference",
2534 parent.count
2535 ),
2536 );
2537 }
2538 }
2539
2540 if bag.has_errors() {
2541 return Err(bag);
2542 }
2543
2544 let tenant_col = tenant_col.expect("tenant resolved without errors");
2545 let parent_col = parent_col.expect("parent resolved without errors");
2546 let parent = parent.expect("parent key resolved without errors");
2547 let writes = vec![tenant_col.name.clone(), parent_col.name.clone()];
2548
2549 let mut predicates = Vec::new();
2550 if parent.start >= 0 && parent.step >= 0 && tenant_start >= 0 {
2551 predicates.push(PlannerPredicate::NonNegative {
2552 columns: writes.clone(),
2553 });
2554 }
2555
2556 let tenant_rng = context.rng(StreamId::operator(
2557 table.name.as_str(),
2558 tenant_col.name.clone(),
2559 "relation.tenant_family.tenant",
2560 ));
2561 let select_rng = context.rng(StreamId::operator(
2562 table.name.as_str(),
2563 parent_col.name.clone(),
2564 "relation.tenant_family.parent",
2565 ));
2566
2567 Ok(RelationTenantFamilyPlanner {
2568 writes,
2569 tenant_family: tenant_col.family.clone(),
2570 parent_family: parent_col.family.clone(),
2571 parent,
2572 num_tenants: num_tenants as u64,
2573 tenant_start,
2574 tenant_rng,
2575 select_rng,
2576 predicates,
2577 })
2578}
2579
2580const LAT_MIN_DEGREES: f64 = -90.0;
2586const LAT_MAX_DEGREES: f64 = 90.0;
2587const LON_MIN_DEGREES: f64 = -180.0;
2589const LON_MAX_DEGREES: f64 = 180.0;
2590
2591pub static GEO_COORDINATE_PAIR_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
2600 kind: "geo.coordinate_pair",
2601 aliases: &[],
2602 summary: "Draws a coherent (latitude, longitude) pair within [-90, 90] x [-180, 180] (or a configured bounding box), at a configurable decimal precision.",
2603 arguments: &[
2604 ArgumentSpec {
2605 name: "columns",
2606 required: true,
2607 summary: "Maps latitude and longitude roles to decimal columns.",
2608 },
2609 ArgumentSpec {
2610 name: "precision",
2611 required: false,
2612 summary: "Number of decimal places, from 0 through 9.",
2613 },
2614 ArgumentSpec {
2615 name: "bounds",
2616 required: false,
2617 summary: "Optional minimum and maximum latitude and longitude bounding box.",
2618 },
2619 ],
2620 writes: ColumnScope::Configured,
2621 reads: ColumnScope::None,
2622 determinism: Determinism::Deterministic,
2623 buffering: Buffering::Streaming,
2624 verification: Verification::Unsupported,
2625 cross_table: false,
2626};
2627
2628pub struct GeoCoordinatePairFactory;
2630
2631impl PlannerFactory for GeoCoordinatePairFactory {
2632 fn descriptor(&self) -> &'static PlannerDescriptor {
2633 &GEO_COORDINATE_PAIR_DESCRIPTOR
2634 }
2635
2636 fn compile(
2637 &self,
2638 config: &PlannerConfig,
2639 context: &CompileContext<'_>,
2640 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
2641 compile_coordinate_pair(config, context)
2642 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
2643 }
2644}
2645
2646struct GeoCoordinatePairPlanner {
2647 writes: Vec<String>,
2648 lat_family: SqlTypeFamily,
2649 lon_family: SqlTypeFamily,
2650 lat_min_minor: i128,
2651 lat_max_minor: i128,
2652 lon_min_minor: i128,
2653 lon_max_minor: i128,
2654 scale: u32,
2655 lat_rng: ChaCha8Rng,
2656 lon_rng: ChaCha8Rng,
2657}
2658
2659impl CompiledPlanner for GeoCoordinatePairPlanner {
2660 fn writes(&self) -> &[String] {
2661 &self.writes
2662 }
2663
2664 fn generate_row(
2665 &mut self,
2666 _row_index: u64,
2667 output: &mut [GeneratedValue],
2668 ) -> Result<(), GenerateError> {
2669 let lat_minor = self
2673 .lat_rng
2674 .random_range(self.lat_min_minor..=self.lat_max_minor);
2675 let lon_minor = self
2676 .lon_rng
2677 .random_range(self.lon_min_minor..=self.lon_max_minor);
2678 output[0] = render_decimal(&self.lat_family, lat_minor, self.scale);
2679 output[1] = render_decimal(&self.lon_family, lon_minor, self.scale);
2680 Ok(())
2681 }
2682
2683 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
2684 Vec::new()
2685 }
2686}
2687
2688fn render_decimal(family: &SqlTypeFamily, minor: i128, scale: u32) -> GeneratedValue {
2693 match family {
2694 SqlTypeFamily::Decimal => GeneratedValue::Decimal { minor, scale },
2695 _ => GeneratedValue::Text(format_fixed_point(minor, scale)),
2696 }
2697}
2698
2699fn format_fixed_point(minor: i128, scale: u32) -> String {
2701 if scale == 0 {
2702 return minor.to_string();
2703 }
2704 let negative = minor < 0;
2705 let magnitude = minor.unsigned_abs();
2706 let factor = 10u128.pow(scale);
2707 let whole = magnitude / factor;
2708 let frac = magnitude % factor;
2709 let sign = if negative { "-" } else { "" };
2710 format!("{sign}{whole}.{frac:0width$}", width = scale as usize)
2711}
2712
2713fn compile_coordinate_pair(
2714 config: &PlannerConfig,
2715 context: &CompileContext<'_>,
2716) -> Result<GeoCoordinatePairPlanner, DiagnosticBag> {
2717 const COLUMN_CODE: &str = crate::diagnostic::codes::COORDINATE_COLUMN_MISSING.code;
2718 const BOUNDS_CODE: &str = crate::diagnostic::codes::COORDINATE_BOUNDS.code;
2719 const PRECISION_CODE: &str = crate::diagnostic::codes::COORDINATE_PRECISION.code;
2720 let mut bag = DiagnosticBag::default();
2721 let table = context.table();
2722 let path = context.path();
2723 let columns = config.args.get("columns");
2724
2725 let lat_col = resolve_required(columns, "latitude", table, path, COLUMN_CODE, &mut bag);
2726 let lon_col = resolve_required(columns, "longitude", table, path, COLUMN_CODE, &mut bag);
2727
2728 let precision = config.args.get("precision").and_then(as_i128).unwrap_or(6);
2729 if !(0..=9).contains(&precision) {
2730 bag.error(
2731 PRECISION_CODE,
2732 format!("{path}.precision"),
2733 format!("geo.coordinate_pair `precision` {precision} must be within [0, 9]"),
2734 );
2735 }
2736
2737 let bounds = config.args.get("bounds");
2738 let min_lat = bounds
2739 .and_then(|b| b.get("min_lat"))
2740 .and_then(as_f64)
2741 .unwrap_or(LAT_MIN_DEGREES);
2742 let max_lat = bounds
2743 .and_then(|b| b.get("max_lat"))
2744 .and_then(as_f64)
2745 .unwrap_or(LAT_MAX_DEGREES);
2746 let min_lon = bounds
2747 .and_then(|b| b.get("min_lon"))
2748 .and_then(as_f64)
2749 .unwrap_or(LON_MIN_DEGREES);
2750 let max_lon = bounds
2751 .and_then(|b| b.get("max_lon"))
2752 .and_then(as_f64)
2753 .unwrap_or(LON_MAX_DEGREES);
2754
2755 if !(LAT_MIN_DEGREES..=LAT_MAX_DEGREES).contains(&min_lat)
2756 || !(LAT_MIN_DEGREES..=LAT_MAX_DEGREES).contains(&max_lat)
2757 || min_lat > max_lat
2758 {
2759 bag.error(
2760 BOUNDS_CODE,
2761 format!("{path}.bounds"),
2762 format!(
2763 "geo.coordinate_pair latitude bounds [{min_lat}, {max_lat}] must lie within [-90, 90] with min <= max"
2764 ),
2765 );
2766 }
2767 if !(LON_MIN_DEGREES..=LON_MAX_DEGREES).contains(&min_lon)
2768 || !(LON_MIN_DEGREES..=LON_MAX_DEGREES).contains(&max_lon)
2769 || min_lon > max_lon
2770 {
2771 bag.error(
2772 BOUNDS_CODE,
2773 format!("{path}.bounds"),
2774 format!(
2775 "geo.coordinate_pair longitude bounds [{min_lon}, {max_lon}] must lie within [-180, 180] with min <= max"
2776 ),
2777 );
2778 }
2779
2780 if bag.has_errors() {
2781 return Err(bag);
2782 }
2783
2784 let lat = lat_col.expect("latitude resolved without errors");
2785 let lon = lon_col.expect("longitude resolved without errors");
2786 let scale = precision as u32;
2787 let factor = 10f64.powi(scale as i32);
2788 let lat_min_minor = (min_lat * factor).round() as i128;
2789 let lat_max_minor = (max_lat * factor).round() as i128;
2790 let lon_min_minor = (min_lon * factor).round() as i128;
2791 let lon_max_minor = (max_lon * factor).round() as i128;
2792
2793 let writes = vec![lat.name.clone(), lon.name.clone()];
2794 let lat_rng = context.rng(StreamId::operator(
2795 table.name.as_str(),
2796 lat.name.clone(),
2797 "geo.coordinate_pair.latitude",
2798 ));
2799 let lon_rng = context.rng(StreamId::operator(
2800 table.name.as_str(),
2801 lon.name.clone(),
2802 "geo.coordinate_pair.longitude",
2803 ));
2804
2805 Ok(GeoCoordinatePairPlanner {
2806 writes,
2807 lat_family: lat.family.clone(),
2808 lon_family: lon.family.clone(),
2809 lat_min_minor,
2810 lat_max_minor,
2811 lon_min_minor,
2812 lon_max_minor,
2813 scale,
2814 lat_rng,
2815 lon_rng,
2816 })
2817}
2818
2819struct FileTypeEntry {
2827 extension: &'static str,
2828 mime_type: &'static str,
2829}
2830
2831const FILE_TYPE_CATALOG: &[FileTypeEntry] = &[
2835 FileTypeEntry {
2836 extension: "txt",
2837 mime_type: "text/plain",
2838 },
2839 FileTypeEntry {
2840 extension: "csv",
2841 mime_type: "text/csv",
2842 },
2843 FileTypeEntry {
2844 extension: "json",
2845 mime_type: "application/json",
2846 },
2847 FileTypeEntry {
2848 extension: "xml",
2849 mime_type: "application/xml",
2850 },
2851 FileTypeEntry {
2852 extension: "html",
2853 mime_type: "text/html",
2854 },
2855 FileTypeEntry {
2856 extension: "css",
2857 mime_type: "text/css",
2858 },
2859 FileTypeEntry {
2860 extension: "js",
2861 mime_type: "text/javascript",
2862 },
2863 FileTypeEntry {
2864 extension: "md",
2865 mime_type: "text/markdown",
2866 },
2867 FileTypeEntry {
2868 extension: "jpg",
2869 mime_type: "image/jpeg",
2870 },
2871 FileTypeEntry {
2872 extension: "jpeg",
2873 mime_type: "image/jpeg",
2874 },
2875 FileTypeEntry {
2876 extension: "png",
2877 mime_type: "image/png",
2878 },
2879 FileTypeEntry {
2880 extension: "gif",
2881 mime_type: "image/gif",
2882 },
2883 FileTypeEntry {
2884 extension: "webp",
2885 mime_type: "image/webp",
2886 },
2887 FileTypeEntry {
2888 extension: "svg",
2889 mime_type: "image/svg+xml",
2890 },
2891 FileTypeEntry {
2892 extension: "bmp",
2893 mime_type: "image/bmp",
2894 },
2895 FileTypeEntry {
2896 extension: "pdf",
2897 mime_type: "application/pdf",
2898 },
2899 FileTypeEntry {
2900 extension: "zip",
2901 mime_type: "application/zip",
2902 },
2903 FileTypeEntry {
2904 extension: "gz",
2905 mime_type: "application/gzip",
2906 },
2907 FileTypeEntry {
2908 extension: "tar",
2909 mime_type: "application/x-tar",
2910 },
2911 FileTypeEntry {
2912 extension: "mp3",
2913 mime_type: "audio/mpeg",
2914 },
2915 FileTypeEntry {
2916 extension: "wav",
2917 mime_type: "audio/wav",
2918 },
2919 FileTypeEntry {
2920 extension: "mp4",
2921 mime_type: "video/mp4",
2922 },
2923 FileTypeEntry {
2924 extension: "mov",
2925 mime_type: "video/quicktime",
2926 },
2927 FileTypeEntry {
2928 extension: "avi",
2929 mime_type: "video/x-msvideo",
2930 },
2931 FileTypeEntry {
2932 extension: "doc",
2933 mime_type: "application/msword",
2934 },
2935 FileTypeEntry {
2936 extension: "docx",
2937 mime_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2938 },
2939 FileTypeEntry {
2940 extension: "xls",
2941 mime_type: "application/vnd.ms-excel",
2942 },
2943 FileTypeEntry {
2944 extension: "xlsx",
2945 mime_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2946 },
2947 FileTypeEntry {
2948 extension: "ppt",
2949 mime_type: "application/vnd.ms-powerpoint",
2950 },
2951 FileTypeEntry {
2952 extension: "pptx",
2953 mime_type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2954 },
2955 FileTypeEntry {
2956 extension: "bin",
2957 mime_type: "application/octet-stream",
2958 },
2959];
2960
2961fn find_file_type(extension: &str) -> Option<&'static FileTypeEntry> {
2962 FILE_TYPE_CATALOG
2963 .iter()
2964 .find(|entry| entry.extension.eq_ignore_ascii_case(extension))
2965}
2966
2967const FILE_NAME_WORDS: &[&str] = &[
2970 "report",
2971 "invoice",
2972 "photo",
2973 "backup",
2974 "export",
2975 "summary",
2976 "dataset",
2977 "image",
2978 "archive",
2979 "document",
2980 "manifest",
2981 "snapshot",
2982 "profile",
2983 "transcript",
2984 "spreadsheet",
2985 "presentation",
2986 "recording",
2987 "scan",
2988 "thumbnail",
2989 "upload",
2990];
2991
2992const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
2993
2994#[derive(Clone, Copy)]
3000enum HashKind {
3001 Md5,
3002 Sha1,
3003 Sha256,
3004 Sha512,
3005}
3006
3007impl HashKind {
3008 fn parse(name: &str) -> Option<Self> {
3009 match name {
3010 "md5" => Some(Self::Md5),
3011 "sha1" => Some(Self::Sha1),
3012 "sha256" => Some(Self::Sha256),
3013 "sha512" => Some(Self::Sha512),
3014 _ => None,
3015 }
3016 }
3017
3018 fn hex_len(self) -> usize {
3019 match self {
3020 Self::Md5 => 32,
3021 Self::Sha1 => 40,
3022 Self::Sha256 => 64,
3023 Self::Sha512 => 128,
3024 }
3025 }
3026}
3027
3028pub static FILE_METADATA_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
3038 kind: "file.metadata",
3039 aliases: &[],
3040 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.",
3041 arguments: &[
3042 ArgumentSpec {
3043 name: "columns",
3044 required: true,
3045 summary: "Maps name and optional extension, MIME type, size, and hash roles to columns.",
3046 },
3047 ArgumentSpec {
3048 name: "extensions",
3049 required: false,
3050 summary: "Allow-list of recognized file extensions.",
3051 },
3052 ArgumentSpec {
3053 name: "size",
3054 required: false,
3055 summary: "Minimum and maximum generated byte size.",
3056 },
3057 ArgumentSpec {
3058 name: "hash_kind",
3059 required: false,
3060 summary: "Synthetic digest shape: md5, sha1, sha256, or sha512.",
3061 },
3062 ],
3063 writes: ColumnScope::Configured,
3064 reads: ColumnScope::None,
3065 determinism: Determinism::Deterministic,
3066 buffering: Buffering::Streaming,
3067 verification: Verification::Supported,
3068 cross_table: false,
3069};
3070
3071pub struct FileMetadataFactory;
3073
3074impl PlannerFactory for FileMetadataFactory {
3075 fn descriptor(&self) -> &'static PlannerDescriptor {
3076 &FILE_METADATA_DESCRIPTOR
3077 }
3078
3079 fn compile(
3080 &self,
3081 config: &PlannerConfig,
3082 context: &CompileContext<'_>,
3083 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
3084 compile_file_metadata(config, context)
3085 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
3086 }
3087}
3088
3089struct FileMetadataPlanner {
3090 writes: Vec<String>,
3091 entries: Vec<&'static FileTypeEntry>,
3092 has_extension: bool,
3093 has_mime_type: bool,
3094 size_family: Option<SqlTypeFamily>,
3095 size_min: i128,
3096 size_max: i128,
3097 hash_len: Option<usize>,
3098 ext_rng: ChaCha8Rng,
3099 name_rng: ChaCha8Rng,
3100 size_rng: ChaCha8Rng,
3101 hash_rng: ChaCha8Rng,
3102 predicates: Vec<PlannerPredicate>,
3103}
3104
3105impl CompiledPlanner for FileMetadataPlanner {
3106 fn writes(&self) -> &[String] {
3107 &self.writes
3108 }
3109
3110 fn generate_row(
3111 &mut self,
3112 row_index: u64,
3113 output: &mut [GeneratedValue],
3114 ) -> Result<(), GenerateError> {
3115 let ext_pick = self.ext_rng.random::<f64>();
3119 let word1_pick = self.name_rng.random::<f64>();
3120 let word2_pick = self.name_rng.random::<f64>();
3121 let size_pick = self.size_rng.random::<f64>();
3122
3123 let entry = &self.entries[pick_index(ext_pick, self.entries.len())];
3124 let word1 = FILE_NAME_WORDS[pick_index(word1_pick, FILE_NAME_WORDS.len())];
3125 let word2 = FILE_NAME_WORDS[pick_index(word2_pick, FILE_NAME_WORDS.len())];
3126 let name = format!("{word1}_{word2}_{row_index}.{}", entry.extension);
3127
3128 let mut slot = 0usize;
3129 output[slot] = GeneratedValue::Text(name);
3130 slot += 1;
3131 if self.has_extension {
3132 output[slot] = GeneratedValue::Text(entry.extension.to_string());
3133 slot += 1;
3134 }
3135 if self.has_mime_type {
3136 output[slot] = GeneratedValue::Text(entry.mime_type.to_string());
3137 slot += 1;
3138 }
3139 if let Some(family) = &self.size_family {
3140 let span = self
3141 .size_max
3142 .saturating_sub(self.size_min)
3143 .saturating_add(1);
3144 let offset = ((size_pick * span as f64) as i128).clamp(0, span - 1);
3145 output[slot] = render_key(self.size_min.saturating_add(offset), family);
3146 slot += 1;
3147 }
3148 if let Some(hash_len) = self.hash_len {
3149 let digest: String = (0..hash_len)
3150 .map(|_| HEX_DIGITS[self.hash_rng.random_range(0..HEX_DIGITS.len())] as char)
3151 .collect();
3152 output[slot] = GeneratedValue::Text(digest);
3153 slot += 1;
3154 }
3155 debug_assert_eq!(slot, output.len());
3156 Ok(())
3157 }
3158
3159 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
3160 self.predicates.clone()
3161 }
3162}
3163
3164fn pick_index(pick: f64, len: usize) -> usize {
3166 ((pick * len as f64) as usize).min(len.saturating_sub(1))
3167}
3168
3169fn compile_file_metadata(
3170 config: &PlannerConfig,
3171 context: &CompileContext<'_>,
3172) -> Result<FileMetadataPlanner, DiagnosticBag> {
3173 const COLUMN_CODE: &str = crate::diagnostic::codes::FILE_COLUMN_MISSING.code;
3174 const SIZE_CODE: &str = crate::diagnostic::codes::FILE_SIZE_RANGE.code;
3175 const HASH_CODE: &str = crate::diagnostic::codes::FILE_HASH_KIND.code;
3176 const EXTENSIONS_CODE: &str = crate::diagnostic::codes::FILE_EXTENSIONS.code;
3177 let mut bag = DiagnosticBag::default();
3178 let table = context.table();
3179 let path = context.path();
3180 let columns = config.args.get("columns");
3181
3182 let name_col = resolve_required(columns, "name", table, path, COLUMN_CODE, &mut bag);
3183 let extension_col = resolve_optional(columns, "extension", table, path, COLUMN_CODE, &mut bag);
3184 let mime_col = resolve_optional(columns, "mime_type", table, path, COLUMN_CODE, &mut bag);
3185 let size_col = resolve_optional(columns, "size", table, path, COLUMN_CODE, &mut bag);
3186 let hash_col = resolve_optional(columns, "hash", table, path, COLUMN_CODE, &mut bag);
3187
3188 let requested_extensions = string_list(config.args.get("extensions"));
3189 let mut entries: Vec<&'static FileTypeEntry> = Vec::new();
3190 if requested_extensions.is_empty() {
3191 entries.extend(FILE_TYPE_CATALOG.iter());
3192 } else {
3193 for extension in &requested_extensions {
3194 match find_file_type(extension) {
3195 Some(entry) => entries.push(entry),
3196 None => {
3197 bag.error(
3198 EXTENSIONS_CODE,
3199 format!("{path}.extensions"),
3200 format!(
3201 "file.metadata `extensions` names `{extension}`, which is not a recognized file extension"
3202 ),
3203 );
3204 }
3205 }
3206 }
3207 }
3208 if entries.is_empty() && !bag.has_errors() {
3209 bag.error(
3210 EXTENSIONS_CODE,
3211 format!("{path}.extensions"),
3212 "file.metadata `extensions` must resolve to at least one recognized extension"
3213 .to_string(),
3214 );
3215 }
3216
3217 let size_block = config.args.get("size");
3218 let size_min = size_block
3219 .and_then(|s| s.get("min"))
3220 .and_then(as_i128)
3221 .unwrap_or(0);
3222 let size_max = size_block
3223 .and_then(|s| s.get("max"))
3224 .and_then(as_i128)
3225 .unwrap_or(10_000_000);
3226 if size_min < 0 {
3230 bag.error(
3231 SIZE_CODE,
3232 format!("{path}.size.min"),
3233 format!("file.metadata `size.min` {size_min} must be >= 0"),
3234 );
3235 }
3236 if size_max < size_min {
3237 bag.error(
3238 SIZE_CODE,
3239 format!("{path}.size.max"),
3240 format!("file.metadata `size.max` {size_max} is below `size.min` {size_min}"),
3241 );
3242 }
3243
3244 let hash_kind_name = config
3245 .args
3246 .get("hash_kind")
3247 .and_then(Value::as_str)
3248 .unwrap_or("sha256");
3249 let hash_kind = HashKind::parse(hash_kind_name);
3250 if hash_col.is_some() && hash_kind.is_none() {
3251 bag.error(
3252 HASH_CODE,
3253 format!("{path}.hash_kind"),
3254 format!(
3255 "file.metadata `hash_kind` `{hash_kind_name}` is not a recognized hash kind (expected one of md5, sha1, sha256, sha512)"
3256 ),
3257 );
3258 }
3259
3260 if bag.has_errors() {
3261 return Err(bag);
3262 }
3263
3264 let name = name_col.expect("name resolved without errors");
3265 let mut writes = vec![name.name.clone()];
3266 let has_extension = extension_col.is_some();
3267 if let Some(column) = extension_col {
3268 writes.push(column.name.clone());
3269 }
3270 let has_mime_type = mime_col.is_some();
3271 if let Some(column) = mime_col {
3272 writes.push(column.name.clone());
3273 }
3274 let size_family = size_col.map(|column| {
3275 writes.push(column.name.clone());
3276 column.family.clone()
3277 });
3278 let hash_len = hash_col.map(|column| {
3279 writes.push(column.name.clone());
3280 hash_kind.unwrap_or(HashKind::Sha256).hex_len()
3281 });
3282
3283 let mut predicates = Vec::new();
3284 if let Some(size) = size_col {
3285 if size_min >= 0 {
3286 predicates.push(PlannerPredicate::NonNegative {
3287 columns: vec![size.name.clone()],
3288 });
3289 }
3290 }
3291
3292 let ext_rng = context.rng(StreamId::operator(
3293 table.name.as_str(),
3294 name.name.clone(),
3295 "file.metadata.extension",
3296 ));
3297 let name_rng = context.rng(StreamId::operator(
3298 table.name.as_str(),
3299 name.name.clone(),
3300 "file.metadata.name",
3301 ));
3302 let size_rng = context.rng(StreamId::operator(
3303 table.name.as_str(),
3304 name.name.clone(),
3305 "file.metadata.size",
3306 ));
3307 let hash_rng = context.rng(StreamId::operator(
3308 table.name.as_str(),
3309 name.name.clone(),
3310 "file.metadata.hash",
3311 ));
3312
3313 Ok(FileMetadataPlanner {
3314 writes,
3315 entries,
3316 has_extension,
3317 has_mime_type,
3318 size_family,
3319 size_min,
3320 size_max,
3321 hash_len,
3322 ext_rng,
3323 name_rng,
3324 size_rng,
3325 hash_rng,
3326 predicates,
3327 })
3328}
3329
3330fn resolve_optional<'a>(
3334 columns: Option<&Value>,
3335 role: &str,
3336 table: &'a PortableTable,
3337 path: &str,
3338 code: &'static str,
3339 bag: &mut DiagnosticBag,
3340) -> Option<&'a PortableColumn> {
3341 let name = role_name(columns, role)?;
3342 let column = find_column(table, name);
3343 if column.is_none() {
3344 bag.error(
3345 code,
3346 format!("{path}.columns.{role}"),
3347 format!(
3348 "file.metadata `{role}` column `{name}` does not exist on table `{}`",
3349 table.name
3350 ),
3351 );
3352 }
3353 column
3354}