thal 0.0.1

Reactive semantic runtime — molecules, reactions, and effect actors for building LLM-backed applications as dataflow programs.
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
use crate::runtime::store::{FieldSchema, MoleculeSchema, TypeRegistry};
use crate::syntax::ast::*;
use crate::value::{MoleculeKindId, PrimitiveType, Type};
use crate::Error;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

#[derive(Clone)]
pub struct VerifiedProgram {
    pub program: Arc<Program>,
    pub type_registry: Arc<TypeRegistry>,
    /// kind_id -> [(reaction_idx, pin_position_in_when)].
    /// Plan 08's delta-pinning eligibility: when a delta of this kind arrives,
    /// the reactor pins it to `pin_position` and scans the other when-positions.
    pub when_eligibility: BTreeMap<MoleculeKindId, Vec<(usize, usize)>>,
    /// kind_id -> [reaction_idx]. Plan 14: deltas of a rollup kind trigger a
    /// full re-evaluation of the reaction with all when-positions scanned.
    pub rollup_eligibility: BTreeMap<MoleculeKindId, Vec<usize>>,
}

impl VerifiedProgram {
    pub fn type_registry(&self) -> &Arc<TypeRegistry> {
        &self.type_registry
    }

    pub fn reactions(&self) -> &[ReactionDecl] {
        &self.program.reactions
    }

    pub fn reactions_for(&self, kind: MoleculeKindId) -> &[(usize, usize)] {
        self.when_eligibility
            .get(&kind)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    pub fn rollup_reactions_for(&self, kind: MoleculeKindId) -> &[usize] {
        self.rollup_eligibility
            .get(&kind)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }
}

pub fn run_passes(program: Program) -> Result<VerifiedProgram, Error> {
    let registry = Arc::new(TypeRegistry::new());

    register_builtins(&registry);
    register_user_molecules(&registry, &program)?;

    pass_typecheck(&program, &registry)?;
    pass_coverage(&program, &registry)?;
    pass_no_self_join(&program, &registry)?;
    pass_no_cycle(&program, &registry)?;

    let (when_eligibility, rollup_eligibility) = build_eligibility(&program, &registry)?;

    Ok(VerifiedProgram {
        program: Arc::new(program),
        type_registry: registry,
        when_eligibility,
        rollup_eligibility,
    })
}

fn register_builtins(registry: &TypeRegistry) {
    // Timer config (Source). Emitted at startup; consumed by TimerActor.
    registry.register(MoleculeSchema {
        name: "Timer".into(),
        fields: vec![FieldSchema {
            name: "interval".into(),
            ty: Type::Primitive(PrimitiveType::Duration),
            default: None,
        }],
        primary_key: vec![],
        merge: None,
        is_singleton: true,
    });

    // Boot — emitted exactly once by the reactor at startup. Replaces the
    // `startup { ... }` block; user programs put their initial-state reaction
    // in `reaction Init { when: Boot(b) emit: ... }`.
    registry.register(MoleculeSchema {
        name: "Boot".into(),
        fields: vec![FieldSchema {
            name: "ts".into(),
            ty: Type::Primitive(PrimitiveType::Timestamp),
            default: Some(Expr::Call("now".into(), vec![])),
        }],
        primary_key: vec![],
        merge: None,
        is_singleton: true,
    });

    // Tick event emitted by TimerActor
    registry.register(MoleculeSchema {
        name: "Tick".into(),
        fields: vec![
            FieldSchema {
                name: "sequence".into(),
                ty: Type::Primitive(PrimitiveType::Int),
                default: None,
            },
            FieldSchema {
                name: "ts".into(),
                ty: Type::Primitive(PrimitiveType::Timestamp),
                default: None,
            },
        ],
        primary_key: vec!["sequence".into()],
        merge: None,
        is_singleton: false,
    });

    // LlmCall Effect — see plan 10. Provider dispatch is by name.
    registry.register(MoleculeSchema {
        name: "LlmCall".into(),
        fields: vec![
            FieldSchema {
                name: "id".into(),
                ty: Type::Primitive(PrimitiveType::Uuid),
                default: Some(Expr::Call("uuid".into(), vec![])),
            },
            FieldSchema {
                name: "provider".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("mock".into())),
            },
            FieldSchema {
                name: "model".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("default".into())),
            },
            FieldSchema {
                name: "prompt".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: None,
            },
            FieldSchema {
                name: "temperature".into(),
                ty: Type::Primitive(PrimitiveType::Float),
                default: Some(Expr::LitFloat(0.2)),
            },
            FieldSchema {
                name: "max_tokens".into(),
                ty: Type::Primitive(PrimitiveType::Int),
                default: Some(Expr::LitInt(1024)),
            },
            FieldSchema {
                name: "status".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("Pending".into())),
            },
            FieldSchema {
                name: "text".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
            FieldSchema {
                name: "finish_reason".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
        ],
        primary_key: vec!["id".into()],
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: false,
    });

    // Process Effect — see plan 09.
    registry.register(MoleculeSchema {
        name: "Process".into(),
        fields: vec![
            FieldSchema {
                name: "id".into(),
                ty: Type::Primitive(PrimitiveType::Uuid),
                default: Some(Expr::Call("uuid".into(), vec![])),
            },
            FieldSchema {
                name: "cmd".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: None,
            },
            FieldSchema {
                name: "args".into(),
                ty: Type::List(Box::new(Type::Primitive(PrimitiveType::String))),
                default: Some(Expr::ListLit(vec![])),
            },
            FieldSchema {
                name: "status".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("Pending".into())),
            },
            FieldSchema {
                name: "stdout".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
            FieldSchema {
                name: "stderr".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
            FieldSchema {
                name: "exit_code".into(),
                ty: Type::Primitive(PrimitiveType::Int),
                default: Some(Expr::LitInt(0)),
            },
        ],
        primary_key: vec!["id".into()],
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: false,
    });

    // LlmProvider config molecule — see plan 20. Declared in `startup { ... }`
    // and intercepted by the reactor: registers a provider with the
    // LlmProviderRegistry instead of being applied to the molecule store.
    registry.register(MoleculeSchema {
        name: "LlmProvider".into(),
        fields: vec![
            FieldSchema {
                name: "name".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: None,
            },
            FieldSchema {
                name: "kind".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("openai_compat".into())),
            },
            FieldSchema {
                name: "base_url".into(),
                ty: Type::Optional(Box::new(Type::Primitive(PrimitiveType::String))),
                default: Some(Expr::LitNull),
            },
            FieldSchema {
                name: "token_file".into(),
                ty: Type::Optional(Box::new(Type::Primitive(PrimitiveType::String))),
                default: Some(Expr::LitNull),
            },
            FieldSchema {
                name: "token_jq".into(),
                ty: Type::Optional(Box::new(Type::Primitive(PrimitiveType::String))),
                default: Some(Expr::LitNull),
            },
        ],
        primary_key: vec!["name".into()],
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: false,
    });

    // TerminalPrompt Effect — see plan 12.
    registry.register(MoleculeSchema {
        name: "TerminalPrompt".into(),
        fields: vec![
            FieldSchema {
                name: "id".into(),
                ty: Type::Primitive(PrimitiveType::Uuid),
                default: Some(Expr::Call("uuid".into(), vec![])),
            },
            FieldSchema {
                name: "question".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: None,
            },
            FieldSchema {
                name: "status".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("Pending".into())),
            },
            FieldSchema {
                name: "answer".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
        ],
        primary_key: vec!["id".into()],
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: false,
    });

    // Spinner Effect — see plan 26. Singleton; latest emit replaces.
    registry.register(MoleculeSchema {
        name: "Spinner".into(),
        fields: vec![
            FieldSchema {
                name: "label".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString(String::new())),
            },
            FieldSchema {
                name: "running".into(),
                ty: Type::Primitive(PrimitiveType::Bool),
                default: Some(Expr::LitBool(false)),
            },
            FieldSchema {
                name: "status".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("Pending".into())),
            },
        ],
        primary_key: vec![],
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: true,
    });

    // TerminalWrite Effect — see plan 07.
    // Defaults are constructed as AST so the runtime evaluator applies them
    // identically to user-declared molecules.
    registry.register(MoleculeSchema {
        name: "TerminalWrite".into(),
        fields: vec![
            FieldSchema {
                name: "id".into(),
                ty: Type::Primitive(PrimitiveType::Uuid),
                default: Some(Expr::Call("uuid".into(), vec![])),
            },
            FieldSchema {
                name: "stream".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("stdout".into())),
            },
            FieldSchema {
                name: "content".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: None,
            },
            FieldSchema {
                name: "newline".into(),
                ty: Type::Primitive(PrimitiveType::Bool),
                default: Some(Expr::LitBool(true)),
            },
            FieldSchema {
                name: "markdown".into(),
                ty: Type::Primitive(PrimitiveType::Bool),
                default: Some(Expr::LitBool(false)),
            },
            FieldSchema {
                name: "status".into(),
                ty: Type::Primitive(PrimitiveType::String),
                default: Some(Expr::LitString("Pending".into())),
            },
        ],
        primary_key: vec!["id".into()],
        // Last-write-wins: lets the actor's `Done` update replace the
        // initial `Pending` insert without a PK conflict.
        merge: Some(MergeFn {
            old_binding: "old".into(),
            new_binding: "new".into(),
            body: Expr::Ident("new".into()),
        }),
        is_singleton: false,
    });
}

fn register_user_molecules(
    registry: &TypeRegistry,
    program: &Program,
) -> Result<(), Error> {
    let mixins_by_name: std::collections::HashMap<&str, &MixinDecl> = program
        .mixins
        .iter()
        .map(|m| (m.name.as_str(), m))
        .collect();

    for decl in &program.molecules {
        // Apply mixins in declaration order: each mixin's fields are appended
        // (rejecting cross-mixin name collisions); molecule-declared fields
        // override mixin fields by name.
        let mut fields: Vec<FieldDecl> = Vec::new();
        let mut inherited_pk: Option<Vec<String>> = None;
        let mut inherited_merge: Option<MergeFn> = None;

        for mixin_name in &decl.mixins {
            let mixin = mixins_by_name.get(mixin_name.as_str()).ok_or_else(|| {
                Error::Verify(format!(
                    "molecule `{}` references unknown mixin `{}`",
                    decl.name, mixin_name
                ))
            })?;

            for f in &mixin.fields {
                if fields.iter().any(|x| x.name == f.name) {
                    return Err(Error::Verify(format!(
                        "molecule `{}`: field `{}` from mixin `{}` collides with an earlier mixin",
                        decl.name, f.name, mixin_name
                    )));
                }
                fields.push(f.clone());
            }

            if let Some(pk) = &mixin.primary_key {
                if let Some(existing) = &inherited_pk {
                    if existing != pk {
                        return Err(Error::Verify(format!(
                            "molecule `{}`: conflicting primary_key from multiple mixins",
                            decl.name
                        )));
                    }
                } else {
                    inherited_pk = Some(pk.clone());
                }
            }

            if let Some(m) = &mixin.merge {
                if inherited_merge.is_some() {
                    return Err(Error::Verify(format!(
                        "molecule `{}`: multiple mixins provide a merge clause",
                        decl.name
                    )));
                }
                inherited_merge = Some(m.clone());
            }
        }

        // Molecule-own fields override mixin fields by name.
        for f in &decl.fields {
            fields.retain(|x| x.name != f.name);
            fields.push(f.clone());
        }

        let primary_key = match decl.primary_key.clone().or(inherited_pk) {
            Some(pk) => pk,
            None => {
                return Err(Error::Verify(format!(
                    "molecule `{}` missing primary_key (not declared and no mixin provides one)",
                    decl.name
                )))
            }
        };

        let merge = decl.merge.clone().or(inherited_merge);

        let schema_fields: Vec<FieldSchema> = fields
            .iter()
            .map(|f| FieldSchema {
                name: f.name.clone(),
                ty: type_expr_to_type(&f.ty),
                default: f.default.clone(),
            })
            .collect();

        let is_singleton = primary_key.is_empty();
        registry.register(MoleculeSchema {
            name: decl.name.clone(),
            fields: schema_fields,
            primary_key,
            merge,
            is_singleton,
        });
    }
    Ok(())
}

fn type_expr_to_type(ty: &TypeExpr) -> Type {
    match ty {
        TypeExpr::Primitive(p) => Type::Primitive(*p),
        TypeExpr::Named(n) => Type::Enum(n.clone()),
        TypeExpr::List(inner) => Type::List(Box::new(type_expr_to_type(inner))),
        TypeExpr::Optional(inner) => Type::Optional(Box::new(type_expr_to_type(inner))),
    }
}

/// Pass 2: type check. v0 only checks that field-assign target fields exist
/// on the target schema; full type inference lands in plan 06+.
fn pass_typecheck(program: &Program, registry: &TypeRegistry) -> Result<(), Error> {
    for reaction in &program.reactions {
        for emit in &reaction.emit {
            let schema = registry
                .schema_by_name(&emit.molecule_name)
                .ok_or_else(|| {
                    Error::Verify(format!(
                        "reaction {} emits unknown molecule {}",
                        reaction.name, emit.molecule_name
                    ))
                })?;
            let known: BTreeSet<&str> =
                schema.fields.iter().map(|f| f.name.as_str()).collect();
            for fa in &emit.fields {
                if !known.contains(fa.name.as_str()) {
                    return Err(Error::Verify(format!(
                        "reaction {} emits {}.{} but molecule has no such field",
                        reaction.name, emit.molecule_name, fa.name
                    )));
                }
            }
        }
    }
    Ok(())
}

/// Pass 5: coverage. Every molecule referenced in `when`, `emit`, and `startup`
/// must resolve to a registered molecule.
fn pass_coverage(program: &Program, registry: &TypeRegistry) -> Result<(), Error> {
    for reaction in &program.reactions {
        for pat in &reaction.when {
            if registry.id_by_name(&pat.molecule_name).is_none() {
                return Err(Error::Verify(format!(
                    "reaction {} when-pattern references unknown molecule {}",
                    reaction.name, pat.molecule_name
                )));
            }
        }
        for emit in &reaction.emit {
            if registry.id_by_name(&emit.molecule_name).is_none() {
                return Err(Error::Verify(format!(
                    "reaction {} emit references unknown molecule {}",
                    reaction.name, emit.molecule_name
                )));
            }
        }
    }
    Ok(())
}

/// Plan 18: outgoing edges from builtin Effect kinds are excluded from the
/// cycle graph because their `Pending → Done` transition is paced by an
/// external actor (user input, network I/O, stdout). A reaction triggered by
/// such a status update only fires after wall-clock work, so the chain isn't
/// a deterministic re-eval loop. Cycles that pass through *only* non-Effect
/// kinds are still rejected.
const EFFECT_KINDS: &[&str] = &[
    "TerminalWrite",
    "TerminalPrompt",
    "Process",
    "LlmCall",
];

/// Plan 17 / pass 3: reject programs whose reaction graph contains a directed
/// cycle. Edges go from `when.kind` (and `rollup.kind`) into each `emit.kind`,
/// minus the relaxation in `EFFECT_KINDS`.
fn pass_no_cycle(program: &Program, registry: &TypeRegistry) -> Result<(), Error> {
    use std::collections::{BTreeMap, BTreeSet};

    let mut edges: BTreeMap<MoleculeKindId, BTreeSet<MoleculeKindId>> = BTreeMap::new();
    let mut name_of: BTreeMap<MoleculeKindId, String> = BTreeMap::new();

    for reaction in &program.reactions {
        let mut sources: Vec<(MoleculeKindId, String)> = Vec::new();
        for pat in &reaction.when {
            let id = registry.id_by_name(&pat.molecule_name).ok_or_else(|| {
                Error::Verify(format!("unknown molecule {}", pat.molecule_name))
            })?;
            sources.push((id, pat.molecule_name.clone()));
            name_of.entry(id).or_insert_with(|| pat.molecule_name.clone());
        }
        if let Some(rollup) = &reaction.rollup {
            let id = registry.id_by_name(&rollup.molecule_name).ok_or_else(|| {
                Error::Verify(format!(
                    "unknown rollup molecule {}",
                    rollup.molecule_name
                ))
            })?;
            sources.push((id, rollup.molecule_name.clone()));
            name_of
                .entry(id)
                .or_insert_with(|| rollup.molecule_name.clone());
        }
        for emit in &reaction.emit {
            let target = registry.id_by_name(&emit.molecule_name).ok_or_else(|| {
                Error::Verify(format!("unknown emit molecule {}", emit.molecule_name))
            })?;
            name_of
                .entry(target)
                .or_insert_with(|| emit.molecule_name.clone());
            for (s_id, s_name) in &sources {
                // Effect-kinded sources don't introduce a determinstic edge;
                // their `Done` updates are paced by an external actor.
                if EFFECT_KINDS.contains(&s_name.as_str()) {
                    continue;
                }
                edges.entry(*s_id).or_default().insert(target);
            }
        }
    }

    #[derive(Clone, Copy, PartialEq)]
    enum Color {
        White,
        Gray,
        Black,
    }
    let mut color: BTreeMap<MoleculeKindId, Color> = BTreeMap::new();
    for &k in edges.keys() {
        color.insert(k, Color::White);
    }

    fn dfs(
        node: MoleculeKindId,
        edges: &BTreeMap<MoleculeKindId, BTreeSet<MoleculeKindId>>,
        color: &mut BTreeMap<MoleculeKindId, Color>,
        name_of: &BTreeMap<MoleculeKindId, String>,
        path: &mut Vec<MoleculeKindId>,
    ) -> Result<(), Error> {
        color.insert(node, Color::Gray);
        path.push(node);
        if let Some(succs) = edges.get(&node) {
            for &next in succs {
                match color.get(&next).copied().unwrap_or(Color::White) {
                    Color::White => dfs(next, edges, color, name_of, path)?,
                    Color::Gray => {
                        let mut chain: Vec<&str> = path
                            .iter()
                            .skip_while(|n| **n != next)
                            .filter_map(|n| name_of.get(n).map(String::as_str))
                            .collect();
                        if let Some(s) = name_of.get(&next).map(String::as_str) {
                            chain.push(s);
                        }
                        return Err(Error::Verify(format!(
                            "reaction graph has a cycle: {}",
                            chain.join(" -> ")
                        )));
                    }
                    Color::Black => {}
                }
            }
        }
        path.pop();
        color.insert(node, Color::Black);
        Ok(())
    }

    for &k in edges.keys().copied().collect::<Vec<_>>().iter() {
        if matches!(color.get(&k).copied().unwrap_or(Color::White), Color::White) {
            dfs(k, &edges, &mut color, &name_of, &mut Vec::new())?;
        }
    }
    Ok(())
}

/// Plan 08: forbid duplicate molecule kinds in `when` (no self-joins yet).
/// Delta-pinning evaluation needs a unique pin position per (reaction, delta-kind).
fn pass_no_self_join(program: &Program, registry: &TypeRegistry) -> Result<(), Error> {
    use std::collections::HashSet;
    for reaction in &program.reactions {
        let mut seen: HashSet<MoleculeKindId> = HashSet::new();
        for pat in &reaction.when {
            let id = registry.id_by_name(&pat.molecule_name).ok_or_else(|| {
                Error::Verify(format!("unknown molecule {}", pat.molecule_name))
            })?;
            if !seen.insert(id) {
                return Err(Error::Verify(format!(
                    "reaction `{}` mentions {} more than once in `when` (self-joins are deferred to a later plan)",
                    reaction.name, pat.molecule_name
                )));
            }
        }
    }
    Ok(())
}

type Eligibility = (
    BTreeMap<MoleculeKindId, Vec<(usize, usize)>>,
    BTreeMap<MoleculeKindId, Vec<usize>>,
);

fn build_eligibility(program: &Program, registry: &TypeRegistry) -> Result<Eligibility, Error> {
    let mut when_map: BTreeMap<MoleculeKindId, Vec<(usize, usize)>> = BTreeMap::new();
    let mut rollup_map: BTreeMap<MoleculeKindId, Vec<usize>> = BTreeMap::new();
    for (ridx, reaction) in program.reactions.iter().enumerate() {
        for (pos, pat) in reaction.when.iter().enumerate() {
            let id = registry
                .id_by_name(&pat.molecule_name)
                .ok_or_else(|| Error::Verify(format!("unknown {}", pat.molecule_name)))?;
            when_map.entry(id).or_default().push((ridx, pos));
        }
        if let Some(rollup) = &reaction.rollup {
            let id = registry.id_by_name(&rollup.molecule_name).ok_or_else(|| {
                Error::Verify(format!(
                    "unknown rollup molecule {}",
                    rollup.molecule_name
                ))
            })?;
            rollup_map.entry(id).or_default().push(ridx);
        }
    }
    Ok((when_map, rollup_map))
}