sql_splitter/generate/registry.rs
1//! The typed extension registry: how generators, modifiers, and planners are
2//! declared, discovered, and turned into runnable operators.
3//!
4//! Everything a value operator does is split across two lifetimes:
5//!
6//! * **Factories** ([`GeneratorFactory`], [`ModifierFactory`],
7//! [`PlannerFactory`]) are the *static* half. Each carries a `&'static`
8//! [descriptor](GeneratorDescriptor) that advertises its `kind`, aliases,
9//! accepted [`SqlTypeFamily`] values, ownership/read declarations, and
10//! determinism/buffering/verification capabilities. A factory validates a
11//! config once and `compile`s it into a runtime operator.
12//! * **Compiled operators** ([`CompiledGenerator`], [`CompiledModifier`],
13//! [`CompiledPlanner`]) are the *hot* half. They run once per row (or per
14//! plan) and are deliberately allocation-lean: a generator overwrites a
15//! caller-owned [`GeneratedValue`] rather than returning a fresh one.
16//!
17//! [`ExtensionRegistry`] owns three [`Catalog`]s (one per operator role).
18//! Each catalog keeps a `BTreeMap` of primary kinds — so discovery order is
19//! deterministic regardless of registration order — plus a second map from
20//! alias to primary kind. Registration keeps the two namespaces disjoint:
21//! a primary kind may not be registered twice, and an alias may neither
22//! shadow a primary kind nor duplicate another alias.
23
24use std::collections::BTreeMap;
25
26use rand_chacha::ChaCha8Rng;
27
28use crate::diagnostic::DiagnosticBag;
29use crate::synthetic::model::{GeneratorConfig, ModifierConfig, PlannerConfig};
30use crate::synthetic::schema::{PortableColumn, PortableTable, SqlTypeFamily};
31
32use super::seed::{SeedRoot, StreamId};
33use super::value::{GenerateError, GeneratedValue};
34
35// --- Descriptor value types -------------------------------------------------
36
37/// A single named argument a factory reads out of its config.
38///
39/// Descriptors carry these so tooling (`--describe`, docs, validation) can
40/// list an operator's knobs without compiling it. Argument *type* checking
41/// stays with the factory's `compile`, which owns the config's semantics.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct ArgumentSpec {
44 /// The config key, e.g. `"value"` or `"min"`.
45 pub name: &'static str,
46 /// Whether omitting the argument is an error.
47 pub required: bool,
48 /// One-line description of what the argument controls.
49 pub summary: &'static str,
50}
51
52/// Which columns an operator reads from or writes to, declared statically so
53/// the compiler can reason about ownership before a single row is generated.
54///
55/// Concrete column *names* are resolved from config at compile time (a
56/// planner's `writes` set, a cross-column generator's `reads` set); this enum
57/// only classifies the shape of that access.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum ColumnScope {
60 /// No columns — e.g. a generator that never reads a sibling value.
61 None,
62 /// Exactly the column the operator is attached to (generators, modifiers).
63 OwnColumn,
64 /// A set of columns named in the operator's configuration (planners, and
65 /// cross-column generators).
66 Configured,
67}
68
69/// Whether an operator's output is reproducible from its seed alone.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Determinism {
72 /// Same seed and inputs always yield the same value.
73 Deterministic,
74 /// May draw from a nondeterministic source (wall clock, OS entropy); a
75 /// run using this operator is not reproducible.
76 NonDeterministic,
77}
78
79/// Whether an operator can stream row-by-row or must buffer rows first.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum Buffering {
82 /// Emits each row as it is produced; safe to stream to the writer.
83 Streaming,
84 /// Requires buffering rows before emitting (e.g. shuffles, global sorts).
85 /// The spooling stage keys off this value.
86 Buffered,
87}
88
89/// Whether an operator can verify its own output against the model's
90/// expectations (uniqueness, referential integrity, value distributions).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Verification {
93 /// The operator provides no verification hook.
94 Unsupported,
95 /// The operator can verify generated values against its constraints.
96 Supported,
97}
98
99/// Static description of a registered generator.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct GeneratorDescriptor {
102 /// Canonical registry name, e.g. `"constant"`.
103 pub kind: &'static str,
104 /// Alternate names that resolve to this generator, e.g. `["const"]`.
105 pub aliases: &'static [&'static str],
106 /// One-line human summary.
107 pub summary: &'static str,
108 /// The config arguments this generator understands.
109 pub arguments: &'static [ArgumentSpec],
110 /// Column type families this generator can populate.
111 pub accepts: &'static [SqlTypeFamily],
112 /// Which columns the generator produces.
113 pub writes: ColumnScope,
114 /// Which sibling columns the generator reads.
115 pub reads: ColumnScope,
116 /// Whether output is reproducible from the seed.
117 pub determinism: Determinism,
118 /// Whether the generator can stream or must buffer.
119 pub buffering: Buffering,
120 /// Whether the generator can verify its own output.
121 pub verification: Verification,
122}
123
124/// Static description of a registered modifier. Mirrors
125/// [`GeneratorDescriptor`], but `accepts` lists the families the modifier can
126/// *transform* rather than populate.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct ModifierDescriptor {
129 /// Canonical registry name, e.g. `"nullable"`.
130 pub kind: &'static str,
131 /// Alternate names that resolve to this modifier.
132 pub aliases: &'static [&'static str],
133 /// One-line human summary.
134 pub summary: &'static str,
135 /// The config arguments this modifier understands.
136 pub arguments: &'static [ArgumentSpec],
137 /// Column type families this modifier can transform.
138 pub accepts: &'static [SqlTypeFamily],
139 /// Which columns the modifier writes (typically its own).
140 pub writes: ColumnScope,
141 /// Which sibling columns the modifier reads.
142 pub reads: ColumnScope,
143 /// Whether output is reproducible from the seed.
144 pub determinism: Determinism,
145 /// Whether the modifier can stream or must buffer.
146 pub buffering: Buffering,
147 /// Whether the modifier can verify its own output.
148 pub verification: Verification,
149}
150
151/// Static description of a registered planner. Planners operate at table
152/// scope rather than on a single column's type, so there is no `accepts`
153/// family list; `writes`/`reads` describe the columns the planner coordinates.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct PlannerDescriptor {
156 /// Canonical registry name, e.g. `"relation.children"`.
157 pub kind: &'static str,
158 /// Alternate names that resolve to this planner.
159 pub aliases: &'static [&'static str],
160 /// One-line human summary.
161 pub summary: &'static str,
162 /// The config arguments this planner understands.
163 pub arguments: &'static [ArgumentSpec],
164 /// Which columns the planner produces (named in its config).
165 pub writes: ColumnScope,
166 /// Which columns the planner reads (named in its config).
167 pub reads: ColumnScope,
168 /// Whether the plan is reproducible from the seed.
169 pub determinism: Determinism,
170 /// Whether the planner can stream or must buffer.
171 pub buffering: Buffering,
172 /// Whether the planner can verify its own output.
173 pub verification: Verification,
174 /// Whether the planner coordinates columns across a table boundary (it
175 /// produces or references another table's rows). The compiler drives its
176 /// cross-table pre-pass (child-fact injection, external column ownership,
177 /// parent-key fact injection, and family phase building) off this capability
178 /// rather than off any specific planner `kind`. Same-table planners
179 /// (interval/progress/timestamps/soft_delete/lifecycle) set this `false`;
180 /// `commerce.order_family` and the relationship/tenant/polymorphic planners
181 /// set it `true`.
182 pub cross_table: bool,
183}
184
185// --- Compile- and row-time contexts ----------------------------------------
186
187/// Everything a factory needs to `compile` a config into a runtime operator:
188/// the table and (for column-scoped operators) the column being compiled, the
189/// run's [`SeedRoot`], and the config's YAML path for diagnostics.
190///
191/// It is `Copy` so factories can freely pass it down without ceremony.
192#[derive(Debug, Clone, Copy)]
193pub struct CompileContext<'a> {
194 table: &'a PortableTable,
195 column: Option<&'a PortableColumn>,
196 seed: SeedRoot,
197 path: &'a str,
198}
199
200impl<'a> CompileContext<'a> {
201 /// Context for a column-scoped operator (generator or modifier).
202 pub fn for_column(
203 table: &'a PortableTable,
204 column: &'a PortableColumn,
205 seed: SeedRoot,
206 path: &'a str,
207 ) -> Self {
208 Self {
209 table,
210 column: Some(column),
211 seed,
212 path,
213 }
214 }
215
216 /// Context for a table-scoped operator (planner), where no single column
217 /// owns the compilation.
218 pub fn for_table(table: &'a PortableTable, seed: SeedRoot, path: &'a str) -> Self {
219 Self {
220 table,
221 column: None,
222 seed,
223 path,
224 }
225 }
226
227 /// The table this operator belongs to.
228 pub fn table(&self) -> &'a PortableTable {
229 self.table
230 }
231
232 /// The column being compiled, if this is a column-scoped operator.
233 pub fn column(&self) -> Option<&'a PortableColumn> {
234 self.column
235 }
236
237 /// The run's root seed, for deriving deterministic RNG streams.
238 pub fn seed(&self) -> SeedRoot {
239 self.seed
240 }
241
242 /// The config's YAML path, for attaching diagnostics to the right place.
243 pub fn path(&self) -> &'a str {
244 self.path
245 }
246
247 /// Derive the deterministic RNG stream for the given identity. Convenience
248 /// over `self.seed().stream(id)`.
249 pub fn rng(&self, id: StreamId) -> ChaCha8Rng {
250 self.seed.stream(id)
251 }
252}
253
254/// Read access to the other columns of the row currently being generated.
255///
256/// The engine owns the row buffer; generators and modifiers only borrow it
257/// through this trait, so a compiled operator can read a sibling column's
258/// value (e.g. deriving `full_name` from `first_name` + `last_name`) without
259/// depending on the concrete buffer type.
260pub trait RowView {
261 /// The value already generated for `column` in this row, if any. Returns
262 /// `None` for columns not yet produced or not present.
263 fn get(&self, column: &str) -> Option<&GeneratedValue>;
264}
265
266/// Per-row context handed to a compiled generator or modifier.
267///
268/// A compiled operator owns its own per-operator RNG (seeded from
269/// [`CompileContext`] at compile time and advanced sequentially per row), so
270/// `RowContext` deliberately carries no RNG: it exposes the row index and
271/// read-only access to sibling column values, which is all the row-time
272/// dependencies a value operator needs. Spooling is coordinated at table scope.
273pub struct RowContext<'a> {
274 row_index: u64,
275 columns: &'a dyn RowView,
276}
277
278impl<'a> RowContext<'a> {
279 /// Build a context for the row at `row_index`, reading siblings from
280 /// `columns`.
281 pub fn new(row_index: u64, columns: &'a dyn RowView) -> Self {
282 Self { row_index, columns }
283 }
284
285 /// The zero-based index of the row being generated.
286 pub fn row_index(&self) -> u64 {
287 self.row_index
288 }
289
290 /// The value already generated for a sibling `column` in this row.
291 pub fn column(&self, column: &str) -> Option<&GeneratedValue> {
292 self.columns.get(column)
293 }
294}
295
296/// Context handed to a compiled planner. Planners run once per table before
297/// any row is generated, so they see the whole table and the run seed.
298///
299/// This type is the stable extension point for planner setup; row-count
300/// resolution, parent/child fan-out, and spooling are coordinated around it.
301#[derive(Debug, Clone, Copy)]
302pub struct PlanContext<'a> {
303 table: &'a PortableTable,
304 seed: SeedRoot,
305}
306
307impl<'a> PlanContext<'a> {
308 /// Build a planning context for `table` under the run's `seed`.
309 pub fn new(table: &'a PortableTable, seed: SeedRoot) -> Self {
310 Self { table, seed }
311 }
312
313 /// The table being planned.
314 pub fn table(&self) -> &'a PortableTable {
315 self.table
316 }
317
318 /// Derive the deterministic RNG stream for the given identity.
319 pub fn rng(&self, id: StreamId) -> ChaCha8Rng {
320 self.seed.stream(id)
321 }
322}
323
324// --- Factory and runtime traits --------------------------------------------
325
326/// Compiles a [`GeneratorConfig`] into a runnable generator.
327pub trait GeneratorFactory: Send + Sync {
328 /// This generator's static description.
329 fn descriptor(&self) -> &'static GeneratorDescriptor;
330
331 /// Validate `config` and build a runtime generator, or return a
332 /// [`DiagnosticBag`] describing every problem found.
333 fn compile(
334 &self,
335 config: &GeneratorConfig,
336 context: &CompileContext<'_>,
337 ) -> Result<Box<dyn CompiledGenerator>, DiagnosticBag>;
338}
339
340/// How a generator materializes as a random-access key domain when its column
341/// is a primary key referenced by a child foreign key. Context-free: the engine
342/// supplies the parent table/column/seed. A generator that is not a
343/// reproducible random-access key returns `None` from
344/// [`CompiledGenerator::key_recipe`].
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346pub enum KeyRecipe {
347 /// A dense integer sequence: parent row `n`'s key is `start + n * step`.
348 Dense {
349 /// The key of parent row 0.
350 start: i128,
351 /// The per-row increment.
352 step: i128,
353 },
354 /// A per-row-reseeded random UUID (RFC 4122 v4).
355 Uuid,
356}
357
358/// A compiled generator: produces one value per row into a caller-owned slot.
359pub trait CompiledGenerator: Send {
360 /// Overwrite `output` with the value for the current row. Overwriting
361 /// (rather than returning) lets the engine reuse the allocation across
362 /// rows.
363 fn generate(
364 &mut self,
365 context: &RowContext<'_>,
366 output: &mut GeneratedValue,
367 ) -> Result<(), GenerateError>;
368
369 /// How this generator materializes as a random-access key when its column
370 /// is a primary key referenced by a child foreign key. The default is
371 /// `None` (not a reproducible random-access key — the engine then reports
372 /// `GEN-KEY-DOMAIN-UNSUPPORTED`). A generator whose row `n` value is a
373 /// closed-form or per-row-reseeded function of `n` overrides this so the
374 /// engine can regenerate any parent row's key by index.
375 fn key_recipe(&self) -> Option<KeyRecipe> {
376 None
377 }
378
379 /// Whether this generator produces distinct values by construction (or
380 /// collides only negligibly), so a single-column key needs no auto-attached
381 /// `unique` modifier — and, crucially, is not capped by that modifier's
382 /// `max_tracked` budget on tables larger than it. The default is any
383 /// generator with a [`KeyRecipe`] (`sequence` is dense, `uuid` collides
384 /// negligibly). A high-entropy random generator (a long `nanoid`, `ulid`,
385 /// token, or hash) or a `monotonic` counter overrides this to `true`; a
386 /// short, low-entropy random string leaves it `false` so it is still tracked.
387 fn is_inherently_unique(&self) -> bool {
388 self.key_recipe().is_some()
389 }
390}
391
392/// The minimum output entropy (in bits) at which a random-string generator is
393/// treated as unique by construction. Below ~1e-9 birthday-collision
394/// probability for tables up to ten billion rows — far past any table a
395/// `unique` tracking budget could hold — so tracking such a column is pointless
396/// and only imposes the `max_tracked` ceiling.
397pub const INHERENT_UNIQUENESS_ENTROPY_BITS: f64 = 96.0;
398
399/// Compiles a [`ModifierConfig`] into a runnable modifier.
400pub trait ModifierFactory: Send + Sync {
401 /// This modifier's static description.
402 fn descriptor(&self) -> &'static ModifierDescriptor;
403
404 /// Validate `config` and build a runtime modifier, or return a
405 /// [`DiagnosticBag`] describing every problem found.
406 fn compile(
407 &self,
408 config: &ModifierConfig,
409 context: &CompileContext<'_>,
410 ) -> Result<Box<dyn CompiledModifier>, DiagnosticBag>;
411}
412
413/// A compiled modifier: transforms a value in place after generation.
414pub trait CompiledModifier: Send {
415 /// Transform `value` for the current row in place.
416 fn apply(
417 &mut self,
418 context: &RowContext<'_>,
419 value: &mut GeneratedValue,
420 ) -> Result<(), GenerateError>;
421}
422
423/// Compiles a [`PlannerConfig`] into a runnable planner.
424pub trait PlannerFactory: Send + Sync {
425 /// This planner's static description.
426 fn descriptor(&self) -> &'static PlannerDescriptor;
427
428 /// Validate `config` and build a runtime planner, or return a
429 /// [`DiagnosticBag`] describing every problem found.
430 fn compile(
431 &self,
432 config: &PlannerConfig,
433 context: &CompileContext<'_>,
434 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag>;
435}
436
437/// A compiled planner: coordinates several columns of a table together.
438///
439/// Planners split their work across two phases. [`plan`](Self::plan) runs once
440/// per table before any row and provides the table-scope extension point for
441/// spooling. [`generate_row`](Self::generate_row) runs once per row in the
442/// engine's row pipeline and *produces* the values of the columns the planner
443/// owns — a planner writes several correlated columns together (e.g. an
444/// interval's `start`/`end`/`duration`/`open`) rather than one column at a
445/// time. The engine maps [`writes`](Self::writes) to row-buffer slots once per
446/// table, then scatters each produced value into place; a planner-owned column
447/// therefore takes its value from the planner, not from a generator.
448pub trait CompiledPlanner: Send {
449 /// Contribute this planner's table-level decisions for `context`. Runs once
450 /// per table before any row is generated. Default: nothing to do.
451 fn plan(&mut self, _context: &PlanContext<'_>) -> Result<(), GenerateError> {
452 Ok(())
453 }
454
455 /// The columns this planner produces, in the positional order
456 /// [`generate_row`](Self::generate_row) writes them. The engine resolves
457 /// each name to a row-buffer slot once per table. Default: none (a planner
458 /// that contributes only structural decisions, not column values).
459 fn writes(&self) -> &[String] {
460 &[]
461 }
462
463 /// Produce this planner's owned column values for the row at `row_index`,
464 /// writing them into `output` positionally aligned with
465 /// [`writes`](Self::writes). Runs once per row, before column modifiers and
466 /// the sink. Default: no-op (nothing owned).
467 fn generate_row(
468 &mut self,
469 _row_index: u64,
470 _output: &mut [GeneratedValue],
471 ) -> Result<(), GenerateError> {
472 Ok(())
473 }
474
475 /// Machine-checkable invariants this planner guarantees over its owned
476 /// columns, surfaced so the verifier can assert them without knowing the
477 /// planner's internals. Default: none.
478 fn verification_predicates(&self) -> Vec<PlannerPredicate> {
479 Vec::new()
480 }
481
482 /// The name of the child table this planner coordinates as a cross-table
483 /// family, if any. A same-table planner returns `None`; a family planner
484 /// (e.g. `commerce.order_family`) names the child table whose rows it
485 /// produces alongside its parent columns. The engine spools those child
486 /// rows and renders them at the child table's dependency position.
487 fn family_child_table(&self) -> Option<&str> {
488 None
489 }
490
491 /// The child-table relationship (declared on the child) that carries the
492 /// foreign key back to this planner's parent, so the engine sets each
493 /// spooled child row's FK to the exact parent that produced it. Only
494 /// meaningful when [`family_child_table`](Self::family_child_table) is
495 /// `Some`.
496 fn family_relationship(&self) -> Option<&str> {
497 None
498 }
499
500 /// The child columns this planner produces, in the positional order of the
501 /// per-child value vectors returned by
502 /// [`take_family_children`](Self::take_family_children). Only meaningful for
503 /// a family planner. Default: none.
504 fn child_writes(&self) -> &[String] {
505 &[]
506 }
507
508 /// Take an incremental stream of child rows produced by the most recent
509 /// [`generate_row`](Self::generate_row) call. Each item is one child line,
510 /// aligned with [`child_writes`](Self::child_writes), so the engine can spool
511 /// it immediately without retaining a parent-sized child vector.
512 /// Default: an empty stream.
513 fn take_family_children(
514 &mut self,
515 ) -> Box<dyn Iterator<Item = Result<Vec<GeneratedValue>, GenerateError>> + '_> {
516 Box::new(std::iter::empty())
517 }
518
519 /// Cross-table sum invariants this family planner guarantees between a
520 /// parent aggregate column and the child rows that reference each parent
521 /// row. Same-table planners (whose invariants are stated as
522 /// [`verification_predicates`](Self::verification_predicates)) return none;
523 /// a family planner (e.g. `commerce.order_family`) surfaces the equalities
524 /// the verifier checks by grouping child rows on the
525 /// declared [`family_relationship`](Self::family_relationship) foreign key.
526 /// Default: none.
527 fn family_sum_checks(&self) -> Vec<FamilySumCheck> {
528 Vec::new()
529 }
530}
531
532/// A cross-table sum invariant: over the child rows of the
533/// [`CompiledPlanner::family_child_table`] that reference a given parent row,
534/// the integer value of `child_column` sums exactly to the integer value of the
535/// parent's `parent_column`. Money columns are compared in currency minor units,
536/// so a verifier normalizes decimal/text renderings to the same fixed scale
537/// before summing.
538#[derive(Debug, Clone, PartialEq, Eq)]
539pub struct FamilySumCheck {
540 /// The named relationship (declared on the child table) whose foreign key
541 /// groups child rows under their parent — the same name
542 /// [`CompiledPlanner::family_relationship`] returns.
543 pub relationship: String,
544 /// The parent aggregate column the child values must sum to.
545 pub parent_column: String,
546 /// The child column summed across every child of a parent row.
547 pub child_column: String,
548}
549
550/// A machine-checkable invariant a planner guarantees over the columns it owns.
551///
552/// Predicates are stated over column *names* and integer units so the verifier
553/// can evaluate them directly against generated rows without re-deriving the
554/// planner's logic. Timestamp columns are compared as
555/// nanoseconds since the Unix epoch; a duration column is an integer count of
556/// `duration_unit_nanos`-sized units.
557#[derive(Debug, Clone, PartialEq, Eq)]
558pub enum PlannerPredicate {
559 /// On every row the `guard` selects (or every row when `guard` is `None`),
560 /// the `end` timestamp is a checked-integer function of `start` and
561 /// `duration`. The exact relation depends on `end_inclusive`:
562 ///
563 /// * `end_inclusive == false` (half-open `[start, end)`):
564 /// `end_ns == start_ns + duration * duration_unit_nanos`.
565 /// * `end_inclusive == true` (closed `[start, end]`, `end` the last covered
566 /// instant): `end_ns == start_ns + duration * duration_unit_nanos - 1`
567 /// (one nanosecond, the smallest internal unit).
568 ///
569 /// The two modes are therefore *not* the same predicate: a verifier must
570 /// branch on `end_inclusive` and check the exact produced value.
571 Equation {
572 /// The start timestamp column.
573 start: String,
574 /// The end timestamp column.
575 end: String,
576 /// The duration column, an integer count of `duration_unit_nanos` units.
577 duration: String,
578 /// Nanoseconds per duration unit (e.g. `1_000_000_000` for seconds).
579 duration_unit_nanos: i128,
580 /// Whether `end` denotes the inclusive last instant of the interval.
581 end_inclusive: bool,
582 /// The rows the equation applies to; `None` means every row.
583 guard: Option<PredicateGuard>,
584 },
585 /// On every row the `guard` selects, `column` is SQL `NULL`.
586 NullWhen {
587 /// The column asserted to be `NULL`.
588 column: String,
589 /// The rows the assertion applies to.
590 guard: PredicateGuard,
591 },
592 /// `column`, compared as epoch nanoseconds, lies within the inclusive
593 /// bounds `[min_nanos, max_nanos]` on every non-null row.
594 InRange {
595 /// The timestamp column bounded.
596 column: String,
597 /// Inclusive lower bound, epoch nanoseconds.
598 min_nanos: i128,
599 /// Inclusive upper bound, epoch nanoseconds.
600 max_nanos: i128,
601 },
602 /// On every row the `guard` selects (or every row when `guard` is `None`),
603 /// the integer values of `addends` sum exactly to the integer value of
604 /// `sum`. Counter planners state their partition equations this way, e.g.
605 /// `succeeded + failed == processed` and `processed + pending == total`. A
606 /// single-element `addends` therefore asserts a plain equality between two
607 /// counter columns (e.g. `processed == total` on completed rows).
608 CounterSum {
609 /// The integer columns summed on the left-hand side.
610 addends: Vec<String>,
611 /// The integer column the addends must sum to.
612 sum: String,
613 /// The rows the equation applies to; `None` means every row.
614 guard: Option<PredicateGuard>,
615 },
616 /// Every listed integer `columns` value is `>= 0` on every row. Counter
617 /// planners assert their counters never go negative.
618 NonNegative {
619 /// The integer columns constrained to be non-negative.
620 columns: Vec<String>,
621 },
622 /// On every row the `guard` selects, `column` is non-`NULL` (the dual of
623 /// [`NullWhen`](Self::NullWhen)). Counter planners assert a completed row
624 /// carries a completion timestamp.
625 NotNullWhen {
626 /// The column asserted to be non-`NULL`.
627 column: String,
628 /// The rows the assertion applies to.
629 guard: PredicateGuard,
630 },
631 /// On every row the `guard` selects (or every row when `guard` is `None`)
632 /// where both endpoints are non-`NULL`, `earlier` (compared as epoch
633 /// nanoseconds) is at most `later`. A `NULL` endpoint never violates the
634 /// predicate — the `temporal.lifecycle` planner uses `NULL` to mean "state
635 /// not yet reached", so an unreached column's absence does not
636 /// participate in the ordering.
637 Ordering {
638 /// The timestamp column expected to occur first.
639 earlier: String,
640 /// The timestamp column expected to occur at or after `earlier`.
641 later: String,
642 /// The rows the ordering applies to; `None` means every row.
643 guard: Option<PredicateGuard>,
644 },
645}
646
647/// A row-level condition selecting which rows a [`PlannerPredicate`] applies to.
648#[derive(Debug, Clone, PartialEq, Eq)]
649pub enum PredicateGuard {
650 /// Rows where the boolean `column` equals `value`.
651 Flag {
652 /// The boolean flag column tested.
653 column: String,
654 /// The value the flag must equal.
655 value: bool,
656 },
657 /// Rows where `column` is `NULL` (`is_null`) or non-`NULL` (`!is_null`).
658 Null {
659 /// The column tested for nullness.
660 column: String,
661 /// Whether the guard selects null (`true`) or non-null (`false`) rows.
662 is_null: bool,
663 },
664 /// Rows where the text `column` equals `value`. Counter planners guard
665 /// state constraints on the workflow status column (e.g. rows whose
666 /// `status` is a particular completed status).
667 Equals {
668 /// The text column tested.
669 column: String,
670 /// The value the column must equal.
671 value: String,
672 },
673}
674
675// --- Catalog ----------------------------------------------------------------
676
677/// The `(kind, aliases)` a catalog needs to index any factory, regardless of
678/// role. Implemented for each factory trait object so [`Catalog`] can be
679/// generic over all three roles.
680trait FactoryMeta {
681 fn kind(&self) -> &'static str;
682 fn aliases(&self) -> &'static [&'static str];
683}
684
685impl FactoryMeta for dyn GeneratorFactory {
686 fn kind(&self) -> &'static str {
687 self.descriptor().kind
688 }
689 fn aliases(&self) -> &'static [&'static str] {
690 self.descriptor().aliases
691 }
692}
693
694impl FactoryMeta for dyn ModifierFactory {
695 fn kind(&self) -> &'static str {
696 self.descriptor().kind
697 }
698 fn aliases(&self) -> &'static [&'static str] {
699 self.descriptor().aliases
700 }
701}
702
703impl FactoryMeta for dyn PlannerFactory {
704 fn kind(&self) -> &'static str {
705 self.descriptor().kind
706 }
707 fn aliases(&self) -> &'static [&'static str] {
708 self.descriptor().aliases
709 }
710}
711
712/// One role's worth of registered factories: a deterministic primary-kind map
713/// plus an alias→kind map. Generic over the factory trait object so all three
714/// roles share the same registration and lookup rules.
715struct Catalog<F: ?Sized> {
716 /// Human label for diagnostics, e.g. `"generator"`.
717 label: &'static str,
718 /// Primary kind → factory. `BTreeMap` gives deterministic iteration.
719 primary: BTreeMap<String, Box<F>>,
720 /// Alias → primary kind. Kept disjoint from `primary`'s keys.
721 aliases: BTreeMap<String, String>,
722}
723
724impl<F: ?Sized + FactoryMeta> Catalog<F> {
725 fn new(label: &'static str) -> Self {
726 Self {
727 label,
728 primary: BTreeMap::new(),
729 aliases: BTreeMap::new(),
730 }
731 }
732
733 /// Register `factory`, validating that its kind and aliases collide with
734 /// nothing already installed. All problems are collected before returning
735 /// so a factory with several bad aliases reports them all at once, and
736 /// nothing is inserted unless validation passes.
737 fn register(&mut self, factory: Box<F>) -> Result<(), DiagnosticBag> {
738 let kind = factory.kind();
739 let aliases = factory.aliases();
740 let mut bag = DiagnosticBag::default();
741
742 if self.primary.contains_key(kind) {
743 bag.error(
744 crate::diagnostic::codes::REGISTRY_DUPLICATE.code,
745 format!("registry.{}s.{kind}", self.label),
746 format!("duplicate {} kind `{kind}`", self.label),
747 );
748 } else if self.aliases.contains_key(kind) {
749 bag.error(
750 crate::diagnostic::codes::REGISTRY_DUPLICATE.code,
751 format!("registry.{}s.{kind}", self.label),
752 format!(
753 "{} kind `{kind}` is already registered as an alias",
754 self.label
755 ),
756 );
757 }
758
759 let mut seen = BTreeMap::new();
760 for &alias in aliases {
761 let path = format!("registry.{}s.{kind}.aliases.{alias}", self.label);
762 if alias == kind {
763 bag.error(
764 crate::diagnostic::codes::REGISTRY_ALIAS_DUPLICATE.code,
765 path,
766 format!("alias `{alias}` duplicates its own kind"),
767 );
768 } else if self.primary.contains_key(alias) {
769 bag.error(
770 crate::diagnostic::codes::REGISTRY_ALIAS_SHADOWS_KIND.code,
771 path,
772 format!("alias `{alias}` shadows an existing {} kind", self.label),
773 );
774 } else if self.aliases.contains_key(alias) || seen.insert(alias, ()).is_some() {
775 bag.error(
776 crate::diagnostic::codes::REGISTRY_ALIAS_DUPLICATE.code,
777 path,
778 format!("duplicate alias `{alias}`"),
779 );
780 }
781 }
782
783 bag.into_result(())?;
784
785 for &alias in aliases {
786 self.aliases.insert(alias.to_string(), kind.to_string());
787 }
788 self.primary.insert(kind.to_string(), factory);
789 Ok(())
790 }
791
792 /// Resolve `name` as a primary kind first, then as an alias.
793 fn get(&self, name: &str) -> Option<&F> {
794 if let Some(factory) = self.primary.get(name) {
795 return Some(factory.as_ref());
796 }
797 let kind = self.aliases.get(name)?;
798 self.primary.get(kind).map(Box::as_ref)
799 }
800
801 /// Iterate factories in deterministic primary-kind order.
802 fn iter(&self) -> impl Iterator<Item = &F> + '_ {
803 self.primary.values().map(Box::as_ref)
804 }
805}
806
807// --- ExtensionRegistry ------------------------------------------------------
808
809/// The registry of all generator, modifier, and planner factories available
810/// to a compilation. Build an empty one with [`ExtensionRegistry::new`] or the
811/// phase's built-in set with [`ExtensionRegistry::standard`].
812pub struct ExtensionRegistry {
813 generators: Catalog<dyn GeneratorFactory>,
814 modifiers: Catalog<dyn ModifierFactory>,
815 planners: Catalog<dyn PlannerFactory>,
816}
817
818impl ExtensionRegistry {
819 /// An empty registry with no factories installed.
820 pub fn new() -> Self {
821 Self {
822 generators: Catalog::new("generator"),
823 modifiers: Catalog::new("modifier"),
824 planners: Catalog::new("planner"),
825 }
826 }
827
828 /// A registry preloaded with every built-in generator, modifier, and
829 /// planner factory.
830 pub fn standard() -> Self {
831 let mut registry = Self::new();
832 registry
833 .register_generator(Box::new(super::generators::ConstantFactory))
834 .expect("built-in generator kinds are collision-free");
835 super::generators::register_all(&mut registry);
836 super::generators::semantic::register_all(&mut registry);
837 super::generators::observed::register_all(&mut registry);
838 registry
839 .register_generator(Box::new(super::generators::relation::ForeignKeyFactory))
840 .expect("built-in generator kinds are collision-free");
841 registry
842 .register_generator(Box::new(super::generators::relation::CompositeKeyFactory))
843 .expect("built-in generator kinds are collision-free");
844 registry
845 .register_planner(Box::new(super::planners::TemporalIntervalFactory))
846 .expect("built-in planner kinds are collision-free");
847 registry
848 .register_planner(Box::new(super::planners::ProgressCountersFactory))
849 .expect("built-in planner kinds are collision-free");
850 registry
851 .register_planner(Box::new(super::planners::OrderFamilyFactory))
852 .expect("built-in planner kinds are collision-free");
853 registry
854 .register_planner(Box::new(super::planners::TemporalTimestampsFactory))
855 .expect("built-in planner kinds are collision-free");
856 registry
857 .register_planner(Box::new(super::planners::TemporalSoftDeleteFactory))
858 .expect("built-in planner kinds are collision-free");
859 registry
860 .register_planner(Box::new(super::planners::TemporalLifecycleFactory))
861 .expect("built-in planner kinds are collision-free");
862 registry
863 .register_planner(Box::new(super::planners::HierarchyTreeFactory))
864 .expect("built-in planner kinds are collision-free");
865 registry
866 .register_planner(Box::new(super::planners::RelationJunctionPairFactory))
867 .expect("built-in planner kinds are collision-free");
868 registry
869 .register_planner(Box::new(super::planners::RelationPolymorphicPairFactory))
870 .expect("built-in planner kinds are collision-free");
871 registry
872 .register_planner(Box::new(super::planners::RelationTenantFamilyFactory))
873 .expect("built-in planner kinds are collision-free");
874 registry
875 .register_planner(Box::new(super::planners::GeoCoordinatePairFactory))
876 .expect("built-in planner kinds are collision-free");
877 registry
878 .register_planner(Box::new(super::planners::FileMetadataFactory))
879 .expect("built-in planner kinds are collision-free");
880 registry
881 }
882
883 /// Register a generator factory.
884 pub fn register_generator(
885 &mut self,
886 factory: Box<dyn GeneratorFactory>,
887 ) -> Result<(), DiagnosticBag> {
888 self.generators.register(factory)
889 }
890
891 /// Register a modifier factory.
892 pub fn register_modifier(
893 &mut self,
894 factory: Box<dyn ModifierFactory>,
895 ) -> Result<(), DiagnosticBag> {
896 self.modifiers.register(factory)
897 }
898
899 /// Register a planner factory.
900 pub fn register_planner(
901 &mut self,
902 factory: Box<dyn PlannerFactory>,
903 ) -> Result<(), DiagnosticBag> {
904 self.planners.register(factory)
905 }
906
907 /// Resolve a generator by primary kind or alias.
908 pub fn generator(&self, name: &str) -> Option<&dyn GeneratorFactory> {
909 self.generators.get(name)
910 }
911
912 /// Resolve a modifier by primary kind or alias.
913 pub fn modifier(&self, name: &str) -> Option<&dyn ModifierFactory> {
914 self.modifiers.get(name)
915 }
916
917 /// Resolve a planner by primary kind or alias.
918 pub fn planner(&self, name: &str) -> Option<&dyn PlannerFactory> {
919 self.planners.get(name)
920 }
921
922 /// Iterate generator factories in deterministic primary-kind order.
923 pub fn generators(&self) -> impl Iterator<Item = &(dyn GeneratorFactory + 'static)> + '_ {
924 self.generators.iter()
925 }
926
927 /// Iterate modifier factories in deterministic primary-kind order.
928 pub fn modifiers(&self) -> impl Iterator<Item = &(dyn ModifierFactory + 'static)> + '_ {
929 self.modifiers.iter()
930 }
931
932 /// Iterate planner factories in deterministic primary-kind order.
933 pub fn planners(&self) -> impl Iterator<Item = &(dyn PlannerFactory + 'static)> + '_ {
934 self.planners.iter()
935 }
936}
937
938impl Default for ExtensionRegistry {
939 fn default() -> Self {
940 Self::new()
941 }
942}