lemma-engine 0.11.4

A pure, declarative language for business rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! Planned evaluation schedule: the program planning emits for evaluation to run.
//!
//! A rule's [`Segment`] lists its cells in evaluation order as emission points, each
//! in a [`Region`]. A region is live when its parent is and its [`Guard`] holds on
//! values already computed: a decision (an `unless` condition, a dispatch scrutinee,
//! an operand that vetoed) always precedes the region it guards. A point runs when its
//! region is live and its cell is not filled yet, after its operands.
//!
//! Cells are hash-consed, so one cell can be demanded in several regions (`x > 5` in a
//! condition and in a body that condition guards). Each demand is a point, in
//! first-demand order; a point is dropped only when an earlier point of the same cell
//! sits in its own region or an enclosing one, since that point always runs first.
//!
//! The order is the walker's first-demand depth-first order ([`crate::evaluation::tree`]):
//! an `unless` chain scans from the last arm, and its body follows its condition;
//! `and` / `or`, folds, and binary operators read left to right; a dispatch reads its
//! scrutinee before its region; a list command reads its list before its arguments.
//!
//! A per-row list command (`sum`, `where`, ...) is a loop: its first argument's points
//! run once per row of its list. A key scan is a loop of key reads that ends at the
//! first vetoed key. A row read (a member read, a row field, a key read) runs the slice
//! of the row's template for its end in the row's context, and first resolves the
//! deferred bindings of the slots it touches in the contexts that own them: that work
//! runs the owner's own segments ([`Entry`]) when the read happens, so it is not
//! expanded into the reading segment. A `uses … -> effective` slot selects its body at
//! its first read: a data pin awaiting its checks settles first, a rule pin runs with
//! the slot's step.
//!
//! A request runs its root program ([`request_program`]): the evaluated spec's pinned
//! slots select their bodies, then each requested rule's segment runs, in request order.
//! Rules no requested rule reads never run.
//!
//! A rule read on a row whose value misses data then settles in the row: rounds of the
//! live work its missing data reads that is not filled yet
//! ([`crate::planning::execution_plan::unsettled_live_work`]), each item run as its own
//! [`Entry::Cell`] or rule. Post-evaluation work (materializing rows for the response)
//! is not part of the program yet.

use crate::planning::execution_plan::{ExecutionPlan, RuleIndex, TargetForce};
use crate::planning::normalize::{
    DispatchRegion, LeafKind, NormalFormId, NormalFormKind, NormalFormListOp,
};
use crate::planning::semantics::{DataDefinition, ImportEffectivePin};
use std::collections::{HashMap, HashSet};

/// Index of a [`Region`] in its [`Segment`]. Region 0 is the rule's entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RegionId(u32);

impl RegionId {
    pub(crate) const ENTRY: RegionId = RegionId(0);

    pub(crate) fn index(self) -> usize {
        self.0 as usize
    }
}

/// When a region is live, given that its parent is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Guard {
    /// The rule is evaluated.
    Entry,
    /// `condition` holds (an `unless` arm is taken).
    Taken(NormalFormId),
    /// `condition` is false (the scan goes on to the next arm).
    NotTaken(NormalFormId),
    /// `operand` is not a definitive veto, or the run explains.
    NotDefinitiveVeto(NormalFormId),
    /// `operand` is a value.
    Value(NormalFormId),
    /// `operand` is a veto.
    Vetoed(NormalFormId),
    /// The n-ary `fold` is not settled by a definitive veto after its first `operands`
    /// operands, or the run explains.
    FoldOpen { fold: NormalFormId, operands: usize },
    /// The `logical` cell is not decided by an absorbing operand among its first
    /// `operands` operands.
    LogicalOpen {
        logical: NormalFormId,
        operands: usize,
    },
    /// The `dispatch` cell's scrutinee falls in region `index`.
    Dispatch {
        dispatch: NormalFormId,
        index: usize,
    },
    /// The list command `command`'s list and its first `operands` arguments are values.
    ArgumentsOpen {
        command: NormalFormId,
        operands: usize,
    },
    /// The run explains: work only an explanation narrates (a cell's pre-image).
    Explain,
    /// The data `leaf` holds a value: request data or a binding gave its slot one.
    Bound(NormalFormId),
    /// No key read of key-scan loop `in_loop` has vetoed before key field `field` of its
    /// current row: a vetoed key ends the scan.
    ScanOpen { in_loop: u32, field: u32 },
    /// The list of the keyed `find` `command` has no index on the find's key fields, so
    /// the find scans its rows.
    Unindexed(NormalFormId),
}

/// A span of the program guarded by a live bit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Region {
    pub(crate) parent: Option<RegionId>,
    pub(crate) guard: Guard,
}

/// What a [`Point`] runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Step {
    /// The cell, when it is not filled, after its operands.
    Cell(NormalFormId),
    /// The whole rule, when it has no value.
    Rule(RuleIndex),
    /// The start of loop [`Segment::loops`]`[loop]`: the points up to its
    /// [`Step::LoopEnd`] run once per row of the loop's list, in row order.
    LoopStart(u32),
    /// The end of a loop's body.
    LoopEnd(u32),
    /// A key scan's read of key field `field` on its loop's current row. The read, like
    /// every row read, resolves the deferred bindings of the slots it touches in the
    /// contexts that own them.
    ScanRead(u32),
}

/// One step of a segment, run when `region` is live. `in_loop` is the innermost loop
/// whose body holds it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Point {
    pub(crate) region: RegionId,
    pub(crate) step: Step,
    pub(crate) in_loop: Option<u32>,
}

/// What a loop runs per row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LoopKind {
    /// A per-row command's first argument.
    PerRow,
    /// A key scan's reads of the row's key fields, in order; a vetoed key ends it.
    KeyScan,
}

/// A list command's loop over the rows of its list.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Loop {
    /// The list command.
    pub(crate) command: NormalFormId,
    /// Its list: the loop runs once per row of this cell's value.
    pub(crate) list: NormalFormId,
    /// The row level its per-row cells read.
    pub(crate) level: u32,
    pub(crate) kind: LoopKind,
}

/// A rule's steps in evaluation order.
#[derive(Clone, Debug, Default)]
pub(crate) struct Segment {
    pub(crate) regions: Vec<Region>,
    pub(crate) points: Vec<Point>,
    pub(crate) loops: Vec<Loop>,
}

/// The operands `cell` reads, each in the region it is read in, in reading order.
/// Rule reference cells read no operand of this segment: the rule is its own segment.
fn operands(
    plan: &ExecutionPlan,
    cell: NormalFormId,
    region: RegionId,
    regions: &mut RegionTable,
) -> Vec<(NormalFormId, RegionId)> {
    if plan.rule_ref_indexes[cell.index()].is_some() {
        return Vec::new();
    }
    match &plan.normal_form(cell).kind {
        // A `uses … -> effective` slot selects its body when it is first read: a data pin
        // whose value still awaits its checks (options, unit scales) settles first.
        NormalFormKind::Leaf(LeafKind::DataPath(path)) => match plan.data.get(path) {
            Some(DataDefinition::Import {
                pin: Some(ImportEffectivePin::Data(pin)),
                ..
            }) => {
                let leaf = *plan
                    .data_leaf
                    .get(pin)
                    .expect("BUG: an effective pin's data has a leaf");
                if plan.walk_settled_leaves.contains(&leaf) {
                    vec![(leaf, regions.child(region, Guard::Bound(leaf)))]
                } else {
                    Vec::new()
                }
            }
            _ => Vec::new(),
        },
        NormalFormKind::Leaf(_)
        | NormalFormKind::Now
        | NormalFormKind::Veto(_)
        | NormalFormKind::RowField { .. } => Vec::new(),
        NormalFormKind::Negate(inner)
        | NormalFormKind::Reciprocal(inner)
        | NormalFormKind::Not(inner)
        | NormalFormKind::MathOp(_, inner)
        | NormalFormKind::StepRounding(_, inner, None)
        | NormalFormKind::UnitConversion(inner, _)
        | NormalFormKind::DateRelative(_, inner)
        | NormalFormKind::DateCalendar(_, _, inner)
        | NormalFormKind::RangeBound(_, inner)
        | NormalFormKind::PastFutureRange(_, inner)
        | NormalFormKind::ResultIsVeto(inner)
        | NormalFormKind::SpecMember { base: inner, .. } => vec![(*inner, region)],
        NormalFormKind::Subtract(left, right)
        | NormalFormKind::Divide(left, right)
        | NormalFormKind::Power(left, right)
        | NormalFormKind::Modulo(left, right)
        | NormalFormKind::Comparison(left, _, right)
        | NormalFormKind::StepRounding(_, left, Some(right))
        | NormalFormKind::RangeLiteral(left, right)
        | NormalFormKind::RangeContainment(left, right) => vec![
            (*left, region),
            (
                *right,
                regions.child(region, Guard::NotDefinitiveVeto(*left)),
            ),
        ],
        NormalFormKind::Sum(terms) | NormalFormKind::Product(terms) => terms
            .iter()
            .enumerate()
            .map(|(index, term)| {
                let read_in = match index {
                    0 => region,
                    operands => regions.child(
                        region,
                        Guard::FoldOpen {
                            fold: cell,
                            operands,
                        },
                    ),
                };
                (term.operand, read_in)
            })
            .collect(),
        NormalFormKind::Logical(_, children) => children
            .iter()
            .enumerate()
            .map(|(index, child)| {
                let read_in = match index {
                    0 => region,
                    operands => regions.child(
                        region,
                        Guard::LogicalOpen {
                            logical: cell,
                            operands,
                        },
                    ),
                };
                (*child, read_in)
            })
            .collect(),
        NormalFormKind::Piecewise(arms) => {
            assert!(!arms.is_empty(), "BUG: empty piecewise");
            let mut reads = Vec::new();
            let mut scan = region;
            for &(condition, body) in arms[1..].iter().rev() {
                reads.push((condition, scan));
                reads.push((body, regions.child(scan, Guard::Taken(condition))));
                scan = regions.child(scan, Guard::NotTaken(condition));
            }
            reads.push((arms[0].1, scan));
            reads
        }
        NormalFormKind::OrderedDispatch {
            scrutinee,
            regions: arms,
            ..
        } => {
            let mut reads = vec![(*scrutinee, region)];
            for (index, arm) in arms.iter().enumerate() {
                reads.push((
                    arm.cell(),
                    regions.child(
                        region,
                        Guard::Dispatch {
                            dispatch: cell,
                            index,
                        },
                    ),
                ));
            }
            if arms.iter().any(DispatchRegion::is_conjunctive) {
                reads.push((
                    plan.normal_form(cell).dispatched_rule(),
                    regions.child(region, Guard::Vetoed(*scrutinee)),
                ));
            }
            reads
        }
        NormalFormKind::ListCommand {
            list,
            op,
            args,
            row_level,
        } => {
            let mut reads = vec![(*list, region)];
            match row_level {
                // Arguments that read no row are read once the list is a value; the
                // per-row arguments are the rows' work.
                Some(_) => {
                    let read_in = regions.child(region, Guard::Value(*list));
                    reads.extend(
                        args.iter()
                            .filter(|arg| plan.row_mask[arg.index()] == 0)
                            .map(|arg| (*arg, read_in)),
                    );
                }
                // A value-list command reads its arguments in order once the list is a
                // value, and stops at the first that is not.
                None => {
                    let count = match op {
                        NormalFormListOp::With => args.len(),
                        NormalFormListOp::Find | NormalFormListOp::Top => 1,
                        _ => 0,
                    };
                    for (operands, arg) in args.iter().take(count).enumerate() {
                        reads.push((
                            *arg,
                            regions.child(
                                region,
                                Guard::ArgumentsOpen {
                                    command: cell,
                                    operands,
                                },
                            ),
                        ));
                    }
                }
            }
            reads
        }
    }
}

/// Regions interned by (parent, guard), so a decision read twice guards one region,
/// with the ancestry that answers [`RegionTable::encloses`] in logarithmic time: an
/// `unless` chain nests one region per arm.
struct RegionTable {
    regions: Vec<Region>,
    by_key: HashMap<(RegionId, Guard), RegionId>,
    /// Depth below the entry, per region.
    depth: Vec<u32>,
    /// `jumps[region][k]` is the ancestor `2^k` levels up (the entry past the top).
    jumps: Vec<Vec<RegionId>>,
}

impl RegionTable {
    fn new() -> Self {
        RegionTable {
            regions: vec![Region {
                parent: None,
                guard: Guard::Entry,
            }],
            by_key: HashMap::new(),
            depth: vec![0],
            jumps: vec![Vec::new()],
        }
    }

    /// The table of `segment`'s regions, as its builder made them.
    fn of(segment: &Segment) -> Self {
        let mut table = RegionTable::new();
        for region in &segment.regions[1..] {
            let parent = region
                .parent
                .expect("BUG: a region past the entry has a parent");
            table.child(parent, region.guard);
        }
        assert_eq!(
            table.regions, segment.regions,
            "BUG: a segment's regions are not the ones its builder interns"
        );
        table
    }

    fn child(&mut self, parent: RegionId, guard: Guard) -> RegionId {
        if let Some(&region) = self.by_key.get(&(parent, guard)) {
            return region;
        }
        let region =
            RegionId(u32::try_from(self.regions.len()).expect("BUG: region count fits u32"));
        self.regions.push(Region {
            parent: Some(parent),
            guard,
        });
        self.by_key.insert((parent, guard), region);
        self.depth.push(self.depth[parent.index()] + 1);
        let mut jumps = vec![parent];
        while let Some(&next) = self.jumps[jumps[jumps.len() - 1].index()].get(jumps.len() - 1) {
            jumps.push(next);
        }
        self.jumps.push(jumps);
        region
    }

    /// Whether `inner` is `outer` or lies inside it.
    fn encloses(&self, outer: RegionId, inner: RegionId) -> bool {
        let (outer_depth, mut depth) = (self.depth[outer.index()], self.depth[inner.index()]);
        if outer_depth > depth {
            return false;
        }
        let mut current = inner;
        while depth > outer_depth {
            let climb = (depth - outer_depth).ilog2() as usize;
            current = self.jumps[current.index()][climb];
            depth -= 1 << climb;
        }
        current == outer
    }
}

/// Work of the segment builder's explicit stack. `Option<u32>` is the innermost loop
/// whose body the work lands in.
enum Work {
    /// Demand `cell` in `region`: its operands, its pre-image when explaining, then it.
    Demand(NormalFormId, RegionId, Option<u32>),
    /// Emit the point of `cell` in `region`.
    Emit(NormalFormId, RegionId, Option<u32>),
    /// Emit a point that runs rule `rule` in `region`.
    Rule(RuleIndex, RegionId, Option<u32>),
    /// Emit a loop marker in `region`.
    Marker(Step, RegionId, Option<u32>),
}

/// Whether the row-level list command `op` runs its first argument once per row.
fn per_row(op: &NormalFormListOp) -> bool {
    matches!(
        op,
        NormalFormListOp::Sum
            | NormalFormListOp::Product
            | NormalFormListOp::Avg
            | NormalFormListOp::Min
            | NormalFormListOp::Max
            | NormalFormListOp::Sort { .. }
            | NormalFormListOp::Predicate { .. }
    )
}

/// The rule a `uses … -> effective <rule>` slot read at data leaf `cell` runs to select
/// its body, the first time the slot is read in a context.
pub(crate) fn pin_rule(plan: &ExecutionPlan, cell: NormalFormId) -> Option<RuleIndex> {
    let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &plan.normal_form(cell).kind else {
        return None;
    };
    match plan.data.get(path) {
        Some(DataDefinition::Import {
            pin: Some(ImportEffectivePin::Rule(rule)),
            ..
        }) => Some(plan.rule_index(rule)),
        _ => None,
    }
}

/// Key fields of the keyed list type `list_type`; none for a numbered list.
fn key_fields(
    list_type: &crate::planning::semantics::LemmaType,
) -> Vec<crate::planning::semantics::DataPath> {
    match &list_type.specifications {
        crate::planning::semantics::TypeSpecification::List {
            key: crate::planning::semantics::ListKey::Fields(fields),
            ..
        } => fields.iter().map(|field| field.path.clone()).collect(),
        crate::planning::semantics::TypeSpecification::List { .. } => Vec::new(),
        other => panic!("BUG: a list command's list is a list, got {other:?}"),
    }
}

/// Where a segment starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Entry {
    /// A rule: the targets of its scale dependencies, then its body.
    Rule(RuleIndex),
    /// A row's data leaf read: the targets of its data's scale dependencies, then it.
    Leaf(NormalFormId),
    /// One cell evaluated on its own: a member read a deferred binding of another row ends
    /// at, or live work a settle pass evaluates for a rule's missing data.
    Cell(NormalFormId),
    /// A row materialized for the response: the targets of every slot's scale, in slot
    /// order. Its bindings resolve in the contexts that own them, as any read's do.
    Materialize,
}

/// A step of a request's root program ([`request_program`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RequestStep {
    /// The segment at this entry, when its work is not done yet: a rule without a value,
    /// a data leaf awaiting its checks.
    Run(Entry),
    /// The `uses … -> effective` slot at this index of [`ExecutionPlan::data`] selects
    /// its body from its pin, which the steps before it computed.
    SelectBody(usize),
}

/// The root program of a request for `requested` on `plan`: each pinned slot of the
/// evaluated spec selects its body (its pin first: a rule pin runs, a data pin awaiting
/// checks settles), in slot order; then each requested rule, in request order. Only the
/// requested rules' segments run, and only the work they read.
pub(crate) fn request_program<'p>(
    plan: &'p ExecutionPlan,
    requested: impl IntoIterator<Item = RuleIndex> + 'p,
) -> impl Iterator<Item = RequestStep> + 'p {
    let pins =
        plan.data
            .values()
            .enumerate()
            .flat_map(move |(slot, definition)| {
                let DataDefinition::Import { pin: Some(pin), .. } = definition else {
                    return [None, None];
                };
                let pin = match pin {
                    ImportEffectivePin::Rule(rule) => {
                        Some(RequestStep::Run(Entry::Rule(plan.rule_index(rule))))
                    }
                    ImportEffectivePin::Data(path) => {
                        let leaf = *plan.data_leaf.get(path).unwrap_or_else(|| {
                            panic!("BUG: effective pin data '{path}' has no leaf")
                        });
                        plan.walk_settled_leaves
                            .contains(&leaf)
                            .then_some(RequestStep::Run(Entry::Leaf(leaf)))
                    }
                };
                [pin, Some(RequestStep::SelectBody(slot))]
            })
            .flatten();
    pins.chain(
        requested
            .into_iter()
            .map(|rule| RequestStep::Run(Entry::Rule(rule))),
    )
}

/// The work that forces `targets` in this context, in order.
fn target_forces(
    plan: &ExecutionPlan,
    targets: &[crate::planning::semantics::ScaleTarget],
) -> Vec<Work> {
    targets
        .iter()
        .filter_map(|scale| plan.target_force(&scale.target))
        .map(|force| match force {
            TargetForce::Member(cell) => Work::Demand(cell, RegionId::ENTRY, None),
            TargetForce::Rule(rule) => Work::Rule(rule, RegionId::ENTRY, None),
        })
        .collect()
}

/// The segment that starts at `entry`.
///
/// Termination: a demand opens its cell until the cell is emitted, and a cell is never
/// demanded while open (a `BUG:` panic: that would be a cycle planning rejects), so open
/// demands nest at most as deep as the plan has cells. Each region is a (parent, guard)
/// pair and every guard names a cell, row or loop of the plan, so there are finitely
/// many regions at that depth. Each (cell, region, loop) demand is processed at most
/// once. The worklist therefore visits a finite set, each element once, and ends.
pub(crate) fn segment(plan: &ExecutionPlan, entry: Entry) -> Segment {
    let mut table = RegionTable::new();
    let mut points: Vec<Point> = Vec::new();
    let mut loops: Vec<Loop> = Vec::new();
    // Cells whose demand is open: a demand of one of them again is a cycle.
    let mut open: HashSet<NormalFormId> = HashSet::new();
    // Demands processed, each once.
    let mut demanded: HashSet<(NormalFormId, RegionId, Option<u32>)> = HashSet::new();
    // Regions each cell, and each rule, has a point in already.
    let mut emitted: HashMap<NormalFormId, Vec<RegionId>> = HashMap::new();
    let mut emitted_rules: HashMap<RuleIndex, Vec<RegionId>> = HashMap::new();
    let mut stack: Vec<Work> = match entry {
        Entry::Rule(rule) => {
            let rule = plan.rule_at(rule);
            let mut work = target_forces(plan, &rule.scale_dependencies);
            work.push(Work::Demand(rule.normal_form, RegionId::ENTRY, None));
            work
        }
        Entry::Leaf(cell) => {
            let NormalFormKind::Leaf(LeafKind::DataPath(path)) = &plan.normal_form(cell).kind
            else {
                panic!("BUG: a leaf entry is a data leaf");
            };
            let mut work = target_forces(plan, plan.data_scale_targets(path));
            work.push(Work::Demand(cell, RegionId::ENTRY, None));
            work
        }
        Entry::Cell(cell) => vec![Work::Demand(cell, RegionId::ENTRY, None)],
        Entry::Materialize => {
            let targets: Vec<_> = plan.slot_scale_targets.iter().flatten().cloned().collect();
            target_forces(plan, &targets)
        }
    };
    stack.reverse();
    while let Some(work) = stack.pop() {
        match work {
            Work::Demand(cell, region, in_loop) => {
                if !demanded.insert((cell, region, in_loop)) {
                    continue;
                }
                let covered = emitted.get(&cell).is_some_and(|regions| {
                    regions
                        .iter()
                        .any(|&earlier| table.encloses(earlier, region))
                });
                if covered {
                    continue;
                }
                assert!(
                    open.insert(cell),
                    "BUG: cell {} of '{}' is demanded while its own demand is open",
                    cell.index(),
                    plan.spec_name
                );
                stack.push(Work::Emit(cell, region, in_loop));
                if let Some(origin) = plan.normal_form(cell).origin {
                    stack.push(Work::Demand(
                        origin,
                        table.child(region, Guard::Explain),
                        in_loop,
                    ));
                }
                // Work this cell does between reading its operands and its own value,
                // pushed in reverse.
                let mut between: Vec<Work> = Vec::new();
                match &plan.normal_form(cell).kind {
                    NormalFormKind::ListCommand {
                        list,
                        op,
                        args,
                        row_level: Some(level),
                    } if per_row(op) && plan.rule_ref_indexes[cell.index()].is_none() => {
                        let argument = *args
                            .first()
                            .expect("BUG: a per-row command has an argument");
                        let lp = u32::try_from(loops.len()).expect("BUG: loop count fits u32");
                        loops.push(Loop {
                            command: cell,
                            list: *list,
                            level: *level,
                            kind: LoopKind::PerRow,
                        });
                        let body = table.child(region, Guard::Value(*list));
                        between.push(Work::Marker(Step::LoopStart(lp), body, in_loop));
                        between.push(Work::Demand(argument, body, Some(lp)));
                        between.push(Work::Marker(Step::LoopEnd(lp), body, in_loop));
                    }
                    NormalFormKind::ListCommand {
                        list,
                        op: op @ (NormalFormListOp::Key { .. } | NormalFormListOp::Find),
                        args,
                        row_level: Some(level),
                    } if plan.rule_ref_indexes[cell.index()].is_none() => {
                        // A find straight over a stored list or `-> key` probes their
                        // index and scans nothing.
                        let fields = match op {
                            NormalFormListOp::Key { .. } => {
                                key_fields(plan.result_type(cell).as_ref())
                            }
                            _ if crate::planning::graph::normal_index_dropped(plan, *list) => {
                                key_fields(plan.result_type(*list).as_ref())
                            }
                            _ => Vec::new(),
                        };
                        if !fields.is_empty() {
                            let scan_in = match op {
                                NormalFormListOp::Key { .. } => {
                                    table.child(region, Guard::Value(*list))
                                }
                                _ => {
                                    let read = table.child(
                                        region,
                                        Guard::ArgumentsOpen {
                                            command: cell,
                                            operands: args.len(),
                                        },
                                    );
                                    table.child(read, Guard::Unindexed(cell))
                                }
                            };
                            let lp = u32::try_from(loops.len()).expect("BUG: loop count fits u32");
                            loops.push(Loop {
                                command: cell,
                                list: *list,
                                level: *level,
                                kind: LoopKind::KeyScan,
                            });
                            between.push(Work::Marker(Step::LoopStart(lp), scan_in, in_loop));
                            for field in 0..fields.len() {
                                let field =
                                    u32::try_from(field).expect("BUG: key field count fits u32");
                                let read_in =
                                    table.child(scan_in, Guard::ScanOpen { in_loop: lp, field });
                                between.push(Work::Marker(
                                    Step::ScanRead(field),
                                    read_in,
                                    Some(lp),
                                ));
                            }
                            between.push(Work::Marker(Step::LoopEnd(lp), scan_in, in_loop));
                        }
                    }
                    _ => {}
                }
                stack.extend(between.into_iter().rev());
                for (operand, read_in) in operands(plan, cell, region, &mut table).into_iter().rev()
                {
                    stack.push(Work::Demand(operand, read_in, in_loop));
                }
            }
            Work::Emit(cell, region, in_loop) => {
                assert!(open.remove(&cell), "BUG: an emitted cell's demand is open");
                let regions = emitted.entry(cell).or_default();
                if regions
                    .iter()
                    .any(|&earlier| table.encloses(earlier, region))
                {
                    continue;
                }
                regions.push(region);
                points.push(Point {
                    region,
                    step: Step::Cell(cell),
                    in_loop,
                });
            }
            Work::Rule(rule, region, in_loop) => {
                let regions = emitted_rules.entry(rule).or_default();
                if regions
                    .iter()
                    .any(|&earlier| table.encloses(earlier, region))
                {
                    continue;
                }
                regions.push(region);
                points.push(Point {
                    region,
                    step: Step::Rule(rule),
                    in_loop,
                });
            }
            Work::Marker(step, region, in_loop) => points.push(Point {
                region,
                step,
                in_loop,
            }),
        }
    }
    assert!(open.is_empty(), "BUG: a demand of the segment never closed");
    assert!(
        demanded.len() <= plan.normal_forms.len() * table.regions.len() * (loops.len() + 1),
        "BUG: the segment builder processed more demands than cells, regions and loops allow"
    );
    Segment {
        regions: table.regions,
        points,
        loops,
    }
}

/// Planning checks of `segment`, the segment of the rule at `rule_position` in
/// `plan.rules`: every operand a point reads has an earlier point in the region it is
/// read in or an enclosing one; a point reads a list row only inside a loop at that
/// row's level; loops nest; every row a guard names is in the row table; and every rule
/// a point references or runs comes earlier in topological order.
pub(crate) fn check_rule_segment(plan: &ExecutionPlan, rule_position: usize, segment: &Segment) {
    let mut table = RegionTable::of(segment);
    let mut seen: HashMap<NormalFormId, Vec<RegionId>> = HashMap::new();
    let mut loop_stack: Vec<u32> = Vec::new();
    for point in &segment.points {
        let cell = match point.step {
            Step::LoopStart(lp) => {
                assert_eq!(
                    point.in_loop,
                    loop_stack.last().copied(),
                    "BUG: a loop starts outside its parent"
                );
                loop_stack.push(lp);
                continue;
            }
            Step::LoopEnd(lp) => {
                assert_eq!(loop_stack.pop(), Some(lp), "BUG: a loop ends out of order");
                continue;
            }
            Step::ScanRead(_) => {
                let lp = *loop_stack.last().expect("BUG: a key read outside its scan");
                assert_eq!(
                    segment.loops[lp as usize].kind,
                    LoopKind::KeyScan,
                    "BUG: a key read in a loop that is not a key scan"
                );
                continue;
            }
            Step::Rule(rule) => {
                assert!(
                    rule.index() < rule_position,
                    "BUG: rule '{}' forces a rule later in topological order",
                    plan.rule_at(rule).path
                );
                continue;
            }
            Step::Cell(cell) => cell,
        };
        assert_eq!(
            point.in_loop,
            loop_stack.last().copied(),
            "BUG: segment point {} is not in the loop it was built in",
            cell.index()
        );
        let mask = plan.row_mask[cell.index()];
        if mask != 0 {
            let levels: u32 = loop_stack
                .iter()
                .map(|&lp| 1u32 << segment.loops[lp as usize].level)
                .fold(0, |levels, level| levels | level);
            assert_eq!(
                mask & !levels,
                0,
                "BUG: segment point {} reads a list row outside its loop",
                cell.index()
            );
        }
        if let Some(rule) = plan.rule_ref_indexes[cell.index()] {
            assert!(
                rule.index() < rule_position,
                "BUG: rule '{}' references a rule later in topological order",
                plan.rule_at(rule).path
            );
        }
        if let Some(pin) = pin_rule(plan, cell) {
            assert!(
                pin.index() < rule_position,
                "BUG: rule '{}' pins a `uses` slot it reads to a rule later in topological order",
                plan.rule_at(pin).path
            );
        }
        for (operand, read_in) in operands(plan, cell, point.region, &mut table) {
            let produced = seen.get(&operand).is_some_and(|regions| {
                regions
                    .iter()
                    .any(|&earlier| table.encloses(earlier, read_in))
            });
            assert!(
                produced,
                "BUG: segment point {} reads cell {} before a point produces it",
                cell.index(),
                operand.index()
            );
        }
        seen.entry(cell).or_default().push(point.region);
    }
    assert!(
        loop_stack.is_empty(),
        "BUG: a loop of the segment never ends"
    );
    assert_eq!(
        table.regions.len(),
        segment.regions.len(),
        "BUG: a segment's checks found a region its builder did not make"
    );
}

/// Build every segment a read of `plan` can start (each rule, each data leaf, each
/// member target) and run the planning checks on it.
pub(crate) fn check_program(plan: &ExecutionPlan) {
    for (position, rule) in plan.rules.values().enumerate() {
        assert_eq!(
            plan.rule_index(&rule.path).index(),
            position,
            "BUG: a rule's index is its position in topological order"
        );
        let segment = segment(plan, Entry::Rule(plan.rule_index(&rule.path)));
        check_rule_segment(plan, position, &segment);
    }
    // A read of data or of a member target may force any rule.
    let every_rule = plan.rules.len();
    for &leaf in plan.data_leaf.values() {
        check_rule_segment(plan, every_rule, &segment(plan, Entry::Leaf(leaf)));
    }
    for &member in plan.member_targets.values() {
        check_rule_segment(plan, every_rule, &segment(plan, Entry::Cell(member)));
    }
    check_rule_segment(plan, every_rule, &segment(plan, Entry::Materialize));
}