egglog 3.0.0

egglog is a language that combines the benefits of equality saturation and datalog. It can be used for analysis, optimization, and synthesis of programs. It is the successor to the popular rust library egg.
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
//! Tests for the typed primitive surface and the seminaive-safety
//! enforcement added in issue #772.
//!
//! Covers:
//! - Pure / write / read / full primitives accepted only in their
//!   respective valid contexts (typechecker rejects others).
//! - Higher-order primitive values carry runtime ids for every context where
//!   the wrapped primitive is valid; application in other contexts hits the
//!   mismatch path.
//! - `unstable-fn` over constructors and custom functions preserves the
//!   existing function/container runtime checks.
//! - Duplicate same-signature primitive registrations are ambiguous for direct
//!   calls and higher-order primitive dispatch.

use egglog::add_primitive;
use egglog::ast::Span;
use egglog::constraint::{SimpleTypeConstraint, TypeConstraint};
use egglog::scheduler::{Matches, Scheduler};
use egglog::sort::{I64Sort, S, StringSort};
use egglog::{
    EGraph, Error, FullPrim, FullState, Primitive, PurePrim, PureState, RawValues, Read, ReadPrim,
    ReadState, TypeError, Value, WritePrim, WriteState, prelude::*,
};

/// Assert that `result` failed with `TypeError::AmbiguousPrimitive`. Both direct
/// primitive calls and `unstable-fn` targets report duplicate registrations
/// through this one variant.
#[track_caller]
fn assert_ambiguous_primitive<T: std::fmt::Debug>(result: Result<T, Error>) {
    assert!(
        matches!(
            result,
            Err(Error::TypeError(TypeError::AmbiguousPrimitive { .. }))
        ),
        "expected TypeError::AmbiguousPrimitive, got: {result:?}"
    );
}

/// A scheduler that fires every match. Used by the scheduled-compilation
/// regression test; the rule there fails to compile before any match is
/// produced, so `filter_matches` is never actually reached.
#[derive(Clone)]
struct ChooseAllScheduler;
impl Scheduler for ChooseAllScheduler {
    fn filter_matches(&mut self, _rule: &str, _ruleset: &str, matches: &mut Matches) -> bool {
        matches.choose_all();
        false
    }
}

// --- shared test fixtures ---

/// A pure primitive that adds two i64s. Trivially safe in every context.
#[derive(Clone)]
struct PureAdd(&'static str);
impl Primitive for PureAdd {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![
                I64Sort.to_arcsort(),
                I64Sort.to_arcsort(),
                I64Sort.to_arcsort(),
            ],
            span.clone(),
        )
        .into_box()
    }
}
impl PurePrim for PureAdd {
    fn apply<'a, 'db>(&self, state: PureState<'a, 'db>, args: &[Value]) -> Option<Value> {
        let a = state.base_values().unwrap::<i64>(args[0]);
        let b = state.base_values().unwrap::<i64>(args[1]);
        Some(state.base_values().get(a + b))
    }
}

/// A write primitive (touches the wrapper's `WriteState` surface). It
/// just returns its first arg; the body uses `&mut self`-shaped methods
/// so it only type-checks against `WriteState`.
#[derive(Clone)]
struct WriteEcho(&'static str);
impl Primitive for WriteEcho {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![I64Sort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl WritePrim for WriteEcho {
    fn apply<'a, 'db>(&self, state: WriteState<'a, 'db>, args: &[Value]) -> Option<Value> {
        let _ = state.base_values();
        Some(args[0])
    }
}

/// A read primitive — looks up a row in the table named by
/// `table_name` and returns the row's value column. Returns `None` if
/// the row is absent. Demonstrates the `Read::lookup` API.
#[derive(Clone)]
struct ReadLookup {
    name: &'static str,
    table_name: &'static str,
}
impl Primitive for ReadLookup {
    fn name(&self) -> &str {
        self.name
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![I64Sort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl ReadPrim for ReadLookup {
    fn apply<'a, 'db>(&self, state: ReadState<'a, 'db>, args: &[Value]) -> Option<Value> {
        state
            .lookup(self.table_name, RawValues(args.to_vec()))
            .ok()
            .flatten()
    }
}

/// A read primitive that uses the read-side table-size API.
#[derive(Clone)]
struct ReadTableSize(&'static str);
impl Primitive for ReadTableSize {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![StringSort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl ReadPrim for ReadTableSize {
    fn apply<'a, 'db>(&self, state: ReadState<'a, 'db>, args: &[Value]) -> Option<Value> {
        let table_name = state.base_values().unwrap::<S>(args[0]).0;
        let size = state.table_size(&table_name).unwrap_or(0);
        let size = i64::try_from(size).ok()?;
        Some(state.base_values().get::<i64>(size))
    }
}

/// A read primitive that uses the read-side all-table-size snapshot API.
#[derive(Clone)]
struct ReadAllTableSizes(&'static str);
impl Primitive for ReadAllTableSizes {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(self.name(), vec![I64Sort.to_arcsort()], span.clone()).into_box()
    }
}
impl ReadPrim for ReadAllTableSizes {
    fn apply<'a, 'db>(&self, state: ReadState<'a, 'db>, _args: &[Value]) -> Option<Value> {
        let size: usize = state.table_sizes().into_iter().map(|(_, size)| size).sum();
        let size = i64::try_from(size).ok()?;
        Some(state.base_values().get::<i64>(size))
    }
}

/// A full primitive — uses `FullState` (writes + reads).
#[derive(Clone)]
struct FullEcho(&'static str);
impl Primitive for FullEcho {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![I64Sort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl FullPrim for FullEcho {
    fn apply<'a, 'db>(&self, state: FullState<'a, 'db>, args: &[Value]) -> Option<Value> {
        let _ = state.base_values();
        Some(args[0])
    }
}

/// A pure primitive with the (i64) -> i64 shape used by the
/// unstable-app dispatch matrix below — uniform signature lets the
/// same `unstable-fn` / `unstable-app` programs cover all four
/// registration kinds.
#[derive(Clone)]
struct PureEcho(&'static str);
impl Primitive for PureEcho {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![I64Sort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl PurePrim for PureEcho {
    fn apply<'a, 'db>(&self, _state: PureState<'a, 'db>, args: &[Value]) -> Option<Value> {
        Some(args[0])
    }
}

/// A read primitive that doesn't actually consult a table — its body
/// just echoes `args[0]`. The trait still wraps it as a `ReadState`
/// at dispatch time, which is what the matrix test cares about.
#[derive(Clone)]
struct ReadEcho(&'static str);
impl Primitive for ReadEcho {
    fn name(&self) -> &str {
        self.0
    }
    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
        SimpleTypeConstraint::new(
            self.name(),
            vec![I64Sort.to_arcsort(), I64Sort.to_arcsort()],
            span.clone(),
        )
        .into_box()
    }
}
impl ReadPrim for ReadEcho {
    fn apply<'a, 'db>(&self, _state: ReadState<'a, 'db>, args: &[Value]) -> Option<Value> {
        Some(args[0])
    }
}

// --- per-context acceptance ---

/// A pure primitive runs in any of the four contexts.
#[test]
fn pure_primitive_accepted_everywhere() {
    let mut egraph = EGraph::default();
    egraph.add_pure_primitive(PureAdd("p-add"), None);

    // global query — `check`
    egraph
        .parse_and_run_program(None, "(check (= (p-add 2 3) 5))")
        .unwrap();
    // global action — top-level eval
    egraph
        .parse_and_run_program(None, "(let $x (p-add 7 8))")
        .unwrap();
    // rule query (LHS) and rule action (RHS)
    egraph
        .parse_and_run_program(
            None,
            "(function f (i64) i64 :no-merge)\n\
             (rule ((= y (p-add 1 2))) ((set (f y) (p-add 10 20))))\n\
             (run 1)",
        )
        .unwrap();
}

/// A `WritePrim` is rejected in any query context (rule LHS, global query).
#[test]
fn write_primitive_rejected_in_queries() {
    let mut egraph = EGraph::default();
    egraph.add_write_primitive(WriteEcho("w-echo"), None);

    // RHS of a rule (Context::Write) — fine.
    egraph
        .parse_and_run_program(
            None,
            "(function g (i64) i64 :no-merge)\n\
             (rule () ((set (g 0) (w-echo 42))))",
        )
        .unwrap();

    // LHS of a rule (Context::Pure) — must be rejected.
    let mut egraph2 = EGraph::default();
    egraph2.add_write_primitive(WriteEcho("w-echo"), None);
    let result = egraph2.parse_and_run_program(
        None,
        "(function g (i64) i64 :no-merge)\n\
         (rule ((= x (w-echo 1))) ((set (g 0) x)))",
    );
    assert!(result.is_err(), "WritePrim must be rejected on a rule LHS");

    // Top-level `check` (Context::Read) — must be rejected.
    let mut egraph3 = EGraph::default();
    egraph3.add_write_primitive(WriteEcho("w-echo"), None);
    let result = egraph3.parse_and_run_program(None, "(check (= (w-echo 1) 1))");
    assert!(
        result.is_err(),
        "WritePrim must be rejected in `check` (Context::Read)"
    );
}

/// A `ReadPrim` is rejected in rule contexts (both query and action) —
/// it's only valid in `Context::Read` and `Context::Full`. To use one
/// inside a rule, the rule must opt out of seminaive with `:naive`.
#[test]
fn read_primitive_rejected_in_rule_contexts() {
    let mut egraph = EGraph::default();
    egraph.add_read_primitive(
        ReadLookup {
            name: "lookup-f",
            table_name: "f",
        },
        None,
    );

    // Populate the `f` table at top level, then use `lookup-f` from a
    // Context::Read (`check`) and a Context::Full (`let`). Both should
    // see the value populated by `set`.
    egraph
        .parse_and_run_program(
            None,
            "(function f (i64) i64 :no-merge)\n\
             (set (f 7) 42)\n\
             (check (= (lookup-f 7) 42))\n\
             (let $r (lookup-f 7))\n\
             (check (= $r 42))",
        )
        .unwrap();

    // Rule LHS without `:naive` — rejected (Context::Pure isn't in
    // `ReadPrim`'s valid contexts).
    let mut egraph2 = EGraph::default();
    egraph2.add_read_primitive(
        ReadLookup {
            name: "lookup-f",
            table_name: "f",
        },
        None,
    );
    let result = egraph2.parse_and_run_program(
        None,
        "(function f (i64) i64 :no-merge)\n\
         (function g (i64) i64 :no-merge)\n\
         (rule ((= x (lookup-f 1))) ((set (g 0) x)))",
    );
    assert!(result.is_err(), "ReadPrim must be rejected on a rule LHS");

    // Rule RHS without `:naive` — also rejected (ReadPrim is Read+Full
    // only; Context::Write doesn't qualify).
    let mut egraph3 = EGraph::default();
    egraph3.add_read_primitive(
        ReadLookup {
            name: "lookup-f",
            table_name: "f",
        },
        None,
    );
    let result = egraph3.parse_and_run_program(
        None,
        "(function f (i64) i64 :no-merge)\n\
         (function g (i64) i64 :no-merge)\n\
         (rule () ((set (g 0) (lookup-f 1))))",
    );
    assert!(result.is_err(), "ReadPrim must be rejected on a rule RHS");

    // With `:naive` — both LHS and RHS accepted; the rule scans the
    // whole DB each iteration, so reads are sound.
    let mut egraph4 = EGraph::default();
    egraph4.add_read_primitive(
        ReadLookup {
            name: "lookup-f",
            table_name: "f",
        },
        None,
    );
    egraph4
        .parse_and_run_program(
            None,
            "(function f (i64) i64 :no-merge)\n\
             (function g (i64) i64 :no-merge)\n\
             (set (f 1) 99)\n\
             (rule ((= x (lookup-f 1))) ((set (g 0) x)) :naive)\n\
             (run 1)\n\
             (check (= (g 0) 99))",
        )
        .unwrap();
}

#[test]
fn read_primitive_can_observe_table_sizes() {
    let mut egraph = EGraph::default();
    egraph.add_read_primitive(ReadTableSize("table-size"), None);
    egraph.add_read_primitive(ReadAllTableSizes("all-table-sizes"), None);

    egraph
        .parse_and_run_program(
            None,
            "(function f (i64) i64 :no-merge)\n\
             (set (f 1) 10)\n\
             (set (f 2) 20)\n\
             (check (= (table-size \"f\") 2))\n\
             (check (= (all-table-sizes) 2))",
        )
        .unwrap();
}

/// A `FullPrim` is valid only in `Context::Full`.
#[test]
fn full_primitive_accepted_only_in_global_action() {
    let mut egraph = EGraph::default();
    egraph.add_full_primitive(FullEcho("f-echo"), None);

    // Context::Full (top-level action) — fine.
    egraph
        .parse_and_run_program(None, "(let $ff (f-echo 7))")
        .unwrap();

    // Context::Read (top-level `check`) — rejected.
    let mut egraph2 = EGraph::default();
    egraph2.add_full_primitive(FullEcho("f-echo"), None);
    let result = egraph2.parse_and_run_program(None, "(check (= (f-echo 1) 1))");
    assert!(
        result.is_err(),
        "FullPrim must be rejected in Context::Read (`check`)"
    );

    // Rule LHS without `:naive` — rejected.
    let mut egraph3 = EGraph::default();
    egraph3.add_full_primitive(FullEcho("f-echo"), None);
    let result = egraph3.parse_and_run_program(
        None,
        "(function f (i64) i64 :no-merge)\n\
         (rule ((= x (f-echo 1))) ((set (f 0) x)))",
    );
    assert!(result.is_err(), "FullPrim must be rejected on a rule LHS");

    // Rule RHS without `:naive` — rejected (action ctx is Write,
    // FullPrim is Full-only).
    let mut egraph4 = EGraph::default();
    egraph4.add_full_primitive(FullEcho("f-echo"), None);
    let result = egraph4.parse_and_run_program(
        None,
        "(function f (i64) i64 :no-merge)\n\
         (rule () ((set (f 0) (f-echo 1))))",
    );
    assert!(result.is_err(), "FullPrim must be rejected on a rule RHS");

    // With `:naive`, both LHS and RHS accept FullPrim (action ctx
    // widens to Full).
    let mut egraph5 = EGraph::default();
    egraph5.add_full_primitive(FullEcho("f-echo"), None);
    egraph5
        .parse_and_run_program(
            None,
            "(function f (i64) i64 :no-merge)\n\
             (function trigger () i64 :no-merge)\n\
             (set (trigger) 1)\n\
             (rule ((= _ (trigger))) ((set (f 0) (f-echo 5))) :naive)\n\
             (run 1)\n\
             (check (= (f 0) 5))",
        )
        .unwrap();
}

/// Merge expressions are action-side writes, not top-level full actions:
/// they may use pure/write primitives, but not primitives that read live DB
/// state.
#[test]
fn merge_primitives_use_write_context() {
    let mut egraph = EGraph::default();
    egraph.add_write_primitive(WriteEcho("w-echo"), None);
    egraph
        .parse_and_run_program(None, "(function g () i64 :merge (w-echo old))")
        .unwrap();

    let mut egraph2 = EGraph::default();
    egraph2.add_read_primitive(
        ReadLookup {
            name: "lookup-f",
            table_name: "f",
        },
        None,
    );
    let result = egraph2.parse_and_run_program(
        None,
        "(function f (i64) i64 :no-merge)\n\
         (function g () i64 :merge (lookup-f old))",
    );
    assert!(result.is_err(), "ReadPrim must be rejected in :merge");

    let mut egraph3 = EGraph::default();
    egraph3.add_full_primitive(FullEcho("f-echo"), None);
    let result = egraph3.parse_and_run_program(None, "(function g () i64 :merge (f-echo old))");
    assert!(result.is_err(), "FullPrim must be rejected in :merge");
}

// `unstable-app` dispatch tests live in
// `tests/typed_primitive_unstable_app.egg` — they only need built-in
// primitives, so the `.egg` form is more direct than building an
// EGraph from Rust.

// --- duplicate registration regression ---

/// Direct primitive resolution requires exactly one matching registration for
/// `(name, signature, context)`. Two independently registered pure primitives
/// both carry valid runtime ids for every context, so a same-signature direct
/// call is ambiguous. Resolution now reports a graceful `TypeError` instead of
/// panicking.
#[test]
fn two_same_signature_registrations_error_on_use() {
    let mut egraph = EGraph::default();
    egraph.add_pure_primitive(PureAdd("dup-add"), None);
    egraph.add_pure_primitive(PureAdd("dup-add"), None);

    assert_ambiguous_primitive(egraph.parse_and_run_program(None, "(check (= (dup-add 1 2) 3))"));
}

/// A duplicate same-signature primitive used on a rule's left-hand side (query)
/// is ambiguous in the query (`Pure`) context and reports a graceful error.
#[test]
fn duplicate_primitive_in_rule_query_errors() {
    let mut egraph = EGraph::default();
    egraph.add_pure_primitive(PureAdd("dup-add"), None);
    egraph.add_pure_primitive(PureAdd("dup-add"), None);

    assert_ambiguous_primitive(egraph.parse_and_run_program(
        None,
        "(relation R (i64))\n\
         (rule ((R x) (= y (dup-add x x))) ((R y)))",
    ));
}

/// A duplicate same-signature primitive used on a rule's right-hand side
/// (action) is ambiguous in the action (`Write`) context and reports a graceful
/// error.
#[test]
fn duplicate_primitive_in_rule_action_errors() {
    let mut egraph = EGraph::default();
    egraph.add_pure_primitive(PureAdd("dup-add"), None);
    egraph.add_pure_primitive(PureAdd("dup-add"), None);

    assert_ambiguous_primitive(egraph.parse_and_run_program(
        None,
        "(relation R (i64))\n\
         (function out (i64) i64 :no-merge)\n\
         (rule ((R x)) ((set (out x) (dup-add x x))))",
    ));
}

/// Scheduled rules are re-lowered lazily inside `step_rules_with_scheduler`, so
/// an ambiguity introduced after the rule is defined (here by a second
/// registration of `dup-echo`) only surfaces during scheduled compilation. That
/// compilation happens after the scheduler has taken `rulesets`/`schedulers` out
/// of the EGraph, so this also guards that those fields are restored on error:
/// a second step must reproduce the same graceful error rather than fail with a
/// spurious "no such ruleset".
#[test]
fn duplicate_primitive_in_scheduled_rule_errors_and_restores() {
    let mut egraph = EGraph::default();
    // One registration: the rule below lowers cleanly when it is defined.
    egraph.add_pure_primitive(PureEcho("dup-echo"), None);
    egraph
        .parse_and_run_program(
            None,
            "(sort Fn (UnstableFn (i64) i64))\n\
             (ruleset test)\n\
             (relation R (i64))\n\
             (relation S (i64))\n\
             (rule ((R x)) ((let f (unstable-fn \"dup-echo\")) (S (unstable-app f x))) \
                   :ruleset test :name \"uses-dup\")\n\
             (R 0)",
        )
        .unwrap();

    // A second registration makes `dup-echo` ambiguous.
    egraph.add_pure_primitive(PureEcho("dup-echo"), None);
    let scheduler_id = egraph.add_scheduler(Box::new(ChooseAllScheduler));

    assert_ambiguous_primitive(egraph.step_rules_with_scheduler(scheduler_id, "test"));

    // If `rulesets`/`schedulers` were not restored, this would fail with a
    // "no such ruleset" error instead of reproducing the ambiguity.
    assert_ambiguous_primitive(egraph.step_rules_with_scheduler(scheduler_id, "test"));
}

/// Registering a primitive whose argument type has no corresponding sort must
/// fail with a message naming the missing type.
#[test]
#[should_panic(expected = "Expected exactly one sort for type `u32`")]
fn missing_sort_panics_with_type_name() {
    let mut egraph = EGraph::default();
    add_primitive!(&mut egraph, "u32-id" = |a: u32| -> i64 { a as i64 });
}

/// `unstable-fn` over a primitive must preserve the same exact-one ambiguity
/// rule as direct primitive calls. The wrapped value records valid runtime ids
/// per application context, and duplicate same-signature registrations are
/// ambiguous for every context where more than one runtime id matches.
#[test]
fn unstable_fn_duplicate_primitive_registration_errors_on_build() {
    let mut egraph = EGraph::default();
    egraph.add_pure_primitive(PureEcho("dup-echo"), None);
    egraph.add_pure_primitive(PureEcho("dup-echo"), None);

    // Duplicate same-signature registrations are ambiguous; building the
    // `unstable-fn` reference now surfaces the same `TypeError::AmbiguousPrimitive`
    // as a direct call instead of panicking.
    assert_ambiguous_primitive(egraph.parse_and_run_program(
        None,
        "(sort Fn (UnstableFn (i64) i64))\n\
         (let $f (unstable-fn \"dup-echo\"))\n\
         (check (= (unstable-app $f 7) 7))",
    ));
}

// --- 4x4 unstable-app dispatch matrix ---
//
// `unstable-fn` over a primitive builds a per-context runtime id table, and
// `unstable-app` selects the id for the application context. For each
// registration kind we wrap a uniform (i64)->i64 echo primitive and apply it
// from all four application contexts. Dispatch succeeds iff the application
// context has a runtime id; otherwise the pre-registered mismatch panic
// surfaces as an error.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AppCtx {
    /// Rule LHS under default seminaive — body context is `Pure`.
    Pure,
    /// Top-level `check` — context is `Read`.
    Read,
    /// Rule RHS under default seminaive — action context is `Write`.
    Write,
    /// Top-level `let` — context is `Full`.
    Full,
}

const ALL_CTXS: [AppCtx; 4] = [AppCtx::Pure, AppCtx::Read, AppCtx::Write, AppCtx::Full];

fn matrix_program(ctx: AppCtx) -> String {
    let header = "(sort Fn (UnstableFn (i64) i64))\n\
                  (let $f (unstable-fn \"p\"))\n";
    match ctx {
        AppCtx::Pure => format!(
            "{header}(function out (i64) i64 :no-merge)\n\
             (rule ((= y (unstable-app $f 7))) ((set (out 0) y)))\n\
             (run 1)\n\
             (check (= (out 0) 7))"
        ),
        AppCtx::Read => format!("{header}(check (= (unstable-app $f 7) 7))"),
        AppCtx::Write => format!(
            "{header}(function out (i64) i64 :no-merge)\n\
             (rule () ((set (out 0) (unstable-app $f 7))))\n\
             (run 1)\n\
             (check (= (out 0) 7))"
        ),
        AppCtx::Full => format!("{header}(let $r (unstable-app $f 7))\n(check (= $r 7))"),
    }
}

fn run_matrix_cell(register: impl FnOnce(&mut EGraph), ctx: AppCtx) -> Result<(), String> {
    let mut egraph = EGraph::default();
    register(&mut egraph);
    egraph
        .parse_and_run_program(None, &matrix_program(ctx))
        .map(|_| ())
        .map_err(|e| e.to_string())
}

#[test]
fn unstable_app_dispatch_matrix() {
    // For each (registration kind, application ctx) cell, expected
    // success follows the trait's `valid_contexts`.
    let cells: &[(&str, fn(&mut EGraph), &[AppCtx])] = &[
        (
            "pure",
            |e: &mut EGraph| e.add_pure_primitive(PureEcho("p"), None),
            &[AppCtx::Pure, AppCtx::Read, AppCtx::Write, AppCtx::Full],
        ),
        (
            "read",
            |e: &mut EGraph| e.add_read_primitive(ReadEcho("p"), None),
            &[AppCtx::Read, AppCtx::Full],
        ),
        (
            "write",
            |e: &mut EGraph| e.add_write_primitive(WriteEcho("p"), None),
            &[AppCtx::Write, AppCtx::Full],
        ),
        (
            "full",
            |e: &mut EGraph| e.add_full_primitive(FullEcho("p"), None),
            &[AppCtx::Full],
        ),
    ];

    for (label, register, valid) in cells {
        for &ctx in &ALL_CTXS {
            let result = run_matrix_cell(*register, ctx);
            let should_succeed = valid.contains(&ctx);
            if should_succeed {
                assert!(
                    result.is_ok(),
                    "{label} prim applied via unstable-app in {ctx:?} ctx should succeed; \
                     got error: {:?}",
                    result.err()
                );
            } else {
                assert!(
                    result.is_err(),
                    "{label} prim applied via unstable-app in {ctx:?} ctx should fail \
                     (dispatch mismatch panic), but parse_and_run_program returned Ok"
                );
            }
        }
    }
}