semi-persistent-egraph 0.3.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Interpreter-level tests for the run-control and statistics surface: `:ruleset`, `(run …
//! :until …)`, and `print-stats`.
//!
//! The `.egg` fixtures in `tests/egg/` can only assert a program's outcome — ok, or a failed
//! check. The facts here are numbers the program itself cannot observe: how many iterations a
//! run took, and what the stats report. They come off the interpreter API and out of the JSON
//! file `(print-stats :file …)` writes.

use semi_persistent_egraph::interpret::Interpreter;
use semi_persistent_egraph::model::{BignumLit, BignumModel};
use semi_persistent_egraph::nodes::DefaultConfig;
use semi_persistent_egraph::saturate::SaturationStrategy;

type Interp = Interpreter<DefaultConfig, BignumLit, BignumModel, true, false>;

/// Run a program to completion and hand back the interpreter for inspection.
fn run(src: &str) -> Interp {
    run_with(src, SaturationStrategy::Naive)
}

fn run_with(src: &str, strategy: SaturationStrategy) -> Interp {
    let cmds = semi_persistent_egraph::parser::parse_program_v2(src).expect("parse");
    let mut interp = Interp::new(BignumModel);
    interp.set_strategy(strategy);
    let mut globals = semi_persistent_egraph::resolve::GlobalCtx::new();
    let checked = semi_persistent_egraph::sortcheck::sortcheck_program(
        cmds,
        &mut interp.eg,
        &interp.model,
        &mut globals,
    )
    .expect("sortcheck");
    interp.run_checked(&checked).expect("run");
    interp
}

fn sortcheck_error(src: &str) -> String {
    let cmds = semi_persistent_egraph::parser::parse_program_v2(src).expect("parse");
    let mut interp = Interp::new(BignumModel);
    let mut globals = semi_persistent_egraph::resolve::GlobalCtx::new();
    semi_persistent_egraph::sortcheck::sortcheck_program(
        cmds,
        &mut interp.eg,
        &interp.model,
        &mut globals,
    )
    .expect_err("program unexpectedly sort-checks")
    .to_string()
}

#[test]
fn rhs_comprehensions_map_between_element_sorts() {
    run("
(sort A)
(sort B)
(sort E)
(constructor a () A)
(constructor b () A)
(constructor F (A) B)
(constructor AS (A) A :assoc)
(constructor ASet (A) A :assoc-comm-idem)
(constructor AMset (A) A :assoc-comm)
(constructor BS (B) B :assoc)
(constructor BSet (B) B :assoc-comm-idem)
(constructor BMset (B) B :assoc-comm)
(constructor WrapA (A) E)
(constructor WrapB (B) E)

(rewrite (WrapA (AS first ..rest))
         (WrapB (BS (F first) ..[(F element) for element in rest])))
(rewrite (WrapA (ASet chosen ..rest))
         (WrapB (BSet (F chosen) ..{(F element) for element in rest})))
(rewrite (WrapA (AMset chosen:1 ..rest))
         (WrapB
           (BMset (F chosen)
                  ..{(F element):count for element:count in rest})))

(let seq (WrapA (AS a b b)))
(let set (WrapA (ASet a b)))
(let mset (WrapA (AMset a b b)))
(run 2)

(check (= seq (WrapB (BS (F a) (F b) (F b)))))
(check (= set (WrapB (BSet (F a) (F b)))))
(check (= mset (WrapB (BMset (F a) (F b) (F b)))))
");
}

#[test]
fn rhs_splices_reject_a_different_element_sort() {
    for (source_decl, target_decl, lhs, rhs) in [
        (
            "(constructor AS (A) A :assoc)",
            "(constructor BS (B) B :assoc)",
            "(WrapA (AS first ..rest))",
            "(WrapB (BS ..rest))",
        ),
        (
            "(constructor AS (A) A :assoc-comm-idem)",
            "(constructor BS (B) B :assoc-comm-idem)",
            "(WrapA (AS first ..rest))",
            "(WrapB (BS ..rest))",
        ),
        (
            "(constructor AS (A) A :assoc-comm)",
            "(constructor BS (B) B :assoc-comm)",
            "(WrapA (AS first:1 ..rest))",
            "(WrapB (BS ..rest))",
        ),
    ] {
        let error = sortcheck_error(&format!(
            "
(sort A)
(sort B)
(sort E)
{source_decl}
{target_decl}
(constructor WrapA (A) E)
(constructor WrapB (B) E)
(rewrite {lhs} {rhs})
"
        ));
        assert!(
            error.contains("rest variable 'rest'")
                && error.contains("element sort")
                && error.contains("'A'")
                && error.contains("'B'"),
            "unexpected error: {error}"
        );
    }
}

// ── `:until` ───────────────────────────────────────────────────────────────

const UNBOUNDED: &str = "
(sort E)
(constructor a () E)
(constructor s (E) E)
(rewrite (s x) (s (s x)))
(let start (s (a)))
";

#[test]
fn until_stops_before_the_budget() {
    // The rule never saturates — it makes a longer term every round — so the budget is the
    // only other way out. The goal holds after one iteration, and the run has to stop there.
    for strategy in [SaturationStrategy::Naive, SaturationStrategy::SemiNaive] {
        let interp = run_with(
            &format!("{UNBOUNDED}(run 100 :until (= start (s (s (a)))))"),
            strategy,
        );
        let sat = interp.last_sat().expect("a run happened");
        assert!(sat.goal_met, "{strategy:?}: goal should be met");
        assert!(
            sat.iterations < 100,
            "{strategy:?}: stopped at the budget ({} iterations)",
            sat.iterations
        );
        assert!(!sat.saturated, "{strategy:?}: this rule cannot saturate");
    }
}

#[test]
fn until_shortens_the_run() {
    // The control for the test above: the same program without a goal runs longer, and
    // reports no goal. Stated as a contrast rather than an iteration count, which would pin
    // how fast this particular rule reaches its fixpoint.
    let with = run(&format!(
        "{UNBOUNDED}(run 100 :until (= start (s (s (a)))))"
    ));
    let without = run(&format!("{UNBOUNDED}(run 100)"));
    let (a, b) = (
        with.last_sat().expect("run").iterations,
        without.last_sat().expect("run").iterations,
    );
    assert!(a < b, "with :until {a} iterations, without {b}");
    assert!(!without.last_sat().expect("run").goal_met);
}

#[test]
fn until_already_satisfied_runs_no_iterations() {
    // The goal is checked *before* the first iteration, so a goal that already holds costs
    // nothing. `(!= …)` on two distinct classes is the cheapest such goal.
    let interp = run("
(sort E)
(constructor a () E)
(constructor b () E)
(let x (a))
(let y (b))
(run 50 :until (!= x y))
");
    let sat = interp.last_sat().expect("a run happened");
    assert_eq!(sat.iterations, 0);
    assert!(sat.goal_met);
}

#[test]
fn until_reports_a_goal_joined_by_rebuild() {
    let src = "
(sort E)
(constructor a () E)
(constructor b () E)
(constructor f (E) E)
(constructor seed () E)
(let fa (f (a)))
(let fb (f (b)))
(seed)
(rule ((seed)) ((union (a) (b))))
(run 1 :until (= fa fb))
";
    for strategy in [SaturationStrategy::Naive, SaturationStrategy::SemiNaive] {
        let interp = run_with(src, strategy);
        let sat = interp.last_sat().expect("a run happened");
        assert_eq!(
            sat.iterations, 1,
            "{strategy:?}: only the child-merging round should execute"
        );
        assert!(
            sat.goal_met,
            "{strategy:?}: rebuild made the parents congruent"
        );
        assert!(
            !sat.saturated,
            "{strategy:?}: the run stopped on its goal, not saturation"
        );
    }
}

#[test]
fn until_disequality_rebuilds_before_observing_a_dirty_graph() {
    let src = "
(sort E)
(constructor a () E)
(constructor b () E)
(constructor f (E) E)
(constructor seed () E)
(let fa (f (a)))
(let fb (f (b)))
(seed)
(rule ((seed)) ((union (a) (b))))
(run 1)
(run 1 :until (!= fa fb))
";
    for strategy in [SaturationStrategy::Naive, SaturationStrategy::SemiNaive] {
        let interp = run_with(src, strategy);
        let sat = interp.last_sat().expect("a run happened");
        assert_eq!(
            sat.iterations, 1,
            "{strategy:?}: the false disequality must not stop iteration zero"
        );
        assert!(
            !sat.goal_met,
            "{strategy:?}: rebuild makes the parent terms congruent"
        );
        assert!(
            sat.saturated,
            "{strategy:?}: the second run has no new equality to add"
        );
    }
}

// ── Rulesets ───────────────────────────────────────────────────────────────

#[test]
fn a_named_run_leaves_the_default_ruleset_alone() {
    // `tests/egg/ruleset_scoping.egg` pins the same scoping through `(check …)`; this asserts
    // it on the class ids, where "did not fire" is directly visible.
    let mut interp = run("
(sort E)
(constructor a () E)
(constructor b () E)
(constructor c () E)
(ruleset extra)
(rewrite (a) (b))
(rewrite (b) (c) :ruleset extra)
(let x (a))
(let y (b))
(run extra 10)
");
    let (x, _) = interp.global("x").expect("x");
    let (y, _) = interp.global("y").expect("y");
    assert_ne!(
        interp.eg.find(x),
        interp.eg.find(y),
        "the untagged rule fired under a named run"
    );
}

#[test]
fn pop_removes_rules_installed_after_push() {
    // Sortcheck resolves the ruleset name across the whole program. At execution time,
    // however, `push` records the installed-rule length and `pop` truncates back to it.
    let mut interp = run("
(sort E)
(constructor a () E)
(constructor b () E)
(ruleset temporary)
(let x (a))
(let y (b))
(push)
(rewrite (a) (b) :ruleset temporary)
(pop)
(run temporary 2)
");
    let (x, _) = interp.global("x").expect("x");
    let (y, _) = interp.global("y").expect("y");
    assert_ne!(
        interp.eg.find(x),
        interp.eg.find(y),
        "a rule installed after push survived pop"
    );
}

#[test]
fn pop_reuses_global_ids_for_later_rules() {
    // The checked GlobalCtx and runtime GlobalCtx must truncate at the same
    // point. Otherwise `live` resolves to gid 2 while runtime reuses gid 1,
    // and matching the rule indexes a nonexistent binding.
    run("
(sort E)
(constructor a () E)
(constructor b () E)
(constructor c () E)
(constructor f (E) E)
(constructor hit () E)
(let base (a))
(push)
(let scoped (b))
(pop)
(let live (c))
(f (c))
(rewrite (f live) (hit))
(run 2)
(check (= (f (c)) (hit)))
");
}

#[test]
fn pop_restores_a_shadowed_global_name() {
    // Truncation must restore the outer name->id mapping, not merely remove
    // the inner mapping. If `chosen` became a fresh pattern variable here,
    // both f-nodes would match and the final disequality would fail.
    run("
(sort E)
(constructor a () E)
(constructor b () E)
(constructor f (E) E)
(constructor hit () E)
(let chosen (a))
(push)
(let chosen (b))
(pop)
(f (a))
(f (b))
(rewrite (f chosen) (hit))
(run 2)
(check (= (f (a)) (hit)))
(check (!= (f (b)) (hit)))
");
}

#[test]
fn check_rebuilds_pending_congruence_after_budgeted_run() {
    // The one permitted round merges a and b in its apply phase, after the
    // round's rebuild. Both f-nodes already exist, so a node-growth-only check
    // would skip the rebuild that makes them congruent.
    run("
(sort E)
(constructor a () E)
(constructor b () E)
(constructor f (E) E)
(constructor seed () E)
(let fa (f (a)))
(let fb (f (b)))
(seed)
(rule ((seed)) ((union (a) (b))))
(run 1)
(check (= fa fb))
");
}

// ── Stats ──────────────────────────────────────────────────────────────────

const STATS_PROGRAM: &str = "
(sort E)
(constructor a () E)
(constructor f (E) E)
(constructor g (E) E)
(rewrite (f x) (g x))
(let x (f (a)))
(run 5)
";

/// Extract a JSON number or boolean by key from the flat object `print-stats` writes.
fn field<'a>(json: &'a str, key: &str) -> &'a str {
    let at = json
        .find(&format!("\"{key}\":"))
        .unwrap_or_else(|| panic!("key {key} missing from {json}"));
    let rest = &json[at + key.len() + 3..];
    let end = rest
        .find([',', '}'])
        .unwrap_or_else(|| panic!("unterminated value for {key} in {json}"));
    &rest[..end]
}

#[test]
fn print_stats_file_reports_the_last_run() {
    let path = std::env::temp_dir().join(format!(
        "semper-print-stats-{}-{:?}.json",
        std::process::id(),
        std::thread::current().id()
    ));
    let src = format!(
        "{STATS_PROGRAM}(print-stats :file \"{}\")",
        path.to_str().unwrap()
    );
    let interp = run(&src);
    let json = std::fs::read_to_string(&path).expect("stats file written");
    let _ = std::fs::remove_file(&path);

    let sat = interp.last_sat().expect("a run happened");
    assert_eq!(field(&json, "nodes"), interp.eg.len().to_string());
    assert_eq!(field(&json, "classes"), interp.eg.class_count().to_string());
    assert_eq!(field(&json, "iterations"), sat.iterations.to_string());
    assert_eq!(field(&json, "saturated"), "true");
    assert_eq!(field(&json, "goal_met"), "false");
    // The counter is armed by the presence of `(print-stats …)`, so a program that asks for
    // stats gets a real number rather than the default-off zero.
    assert!(
        field(&json, "match_steps").parse::<u64>().unwrap() > 0,
        "match steps not counted: {json}"
    );
    assert!(field(&json, "wall_time_ms").parse::<f64>().unwrap() >= 0.0);
}

#[test]
fn stats_classes_are_fewer_than_nodes_after_a_merging_run() {
    // `(f a)` and `(g a)` are two nodes in one class after the rewrite, so the two counts
    // have to differ — the check that `classes` is not just `nodes` under another name.
    let interp = run(STATS_PROGRAM);
    assert!(
        interp.eg.class_count() < interp.eg.len(),
        "classes {} nodes {}",
        interp.eg.class_count(),
        interp.eg.len()
    );
}