cbcl-parser 0.3.0

CBCL pure parser and pipeline
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
//! Protocol progress counts established positions, not competing messages.
#![allow(clippy::cloned_ref_to_slice_refs)]
use cbcl_core::dialect::{Dialect, DialectRegistry};
use cbcl_core::r7::r7_violations;
use cbcl_core::state::{fold, render_json, render_schema, state_schema, Act};
use cbcl_core::store::ThreadId;
use cbcl_parser::state_exports::{admit, Admission};
use cbcl_parser::{parse, parse_dialect, parse_message};

fn source(body: &str) -> String {
    format!("(define demo (cbcl) @author (extend open (to) (tell to)) (extend tick (to) (tell to)) (extend other (to) (tell to)) (protocol (then begin {body})) (state (number (progress tick)) (messages (count tick))))")
}
fn install(body: &str) -> Dialect {
    let mut registry = DialectRegistry::new();
    registry
        .install(parse_dialect(&parse(&source(body)).unwrap()).unwrap())
        .unwrap();
    registry.iter().last().unwrap().clone()
}
fn act(verb: &str, pred: &str, who: &str) -> Act {
    Act::from_message(
        parse_message(
            &parse(&format!(
                "(lang demo ({verb} @all :caused-by {pred} :thread \"t\" :from {who}))"
            ))
            .unwrap(),
        )
        .unwrap(),
        who,
    )
    .unwrap()
}
fn state(d: &Dialect, history: &[Act]) -> serde_json::Value {
    serde_json::from_str(&render_json(&fold(
        d.state.as_ref().unwrap(),
        d.causal_protocol.as_ref(),
        history,
    )))
    .unwrap()
}
fn accept(d: &Dialect, history: &[Act], a: &Act) {
    assert_eq!(
        admit(d, &ThreadId("t".into()), history, a),
        Admission::Accepted
    );
}

#[test]
fn competing_branches_converge_on_progress_not_message_count() {
    let d = install("(repeat 100 tick)");
    assert_eq!(state(&d, &[]), serde_json::json!({"number":0,"messages":0}));
    let a = act("tick", "begin", "@a");
    let b = act("tick", &a.address, "@b");
    let c = act("tick", &a.address, "@c");
    let next = act("tick", &c.address, "@a");
    accept(&d, &[], &a);
    accept(&d, &[a.clone()], &b);
    accept(&d, &[a.clone(), b.clone()], &c);
    let history = vec![a, b, c];
    assert_eq!(
        state(&d, &history),
        serde_json::json!({"number":2,"messages":3})
    );
    let mut reversed = history.clone();
    reversed.reverse();
    let mut duplicated = reversed.clone();
    duplicated.extend(history.clone());
    assert_eq!(state(&d, &history), state(&d, &reversed));
    assert_eq!(state(&d, &history), state(&d, &duplicated));
    accept(&d, &history, &next);
    let mut advanced = history;
    advanced.push(next);
    assert_eq!(
        state(&d, &advanced),
        serde_json::json!({"number":3,"messages":4})
    );
}

#[test]
fn forks_at_99_reach_100_without_inflating_progress() {
    let d = install("(repeat 100 tick)");
    let mut history = Vec::new();
    for i in 0..99 {
        let parent = history
            .last()
            .map(|a: &Act| a.address.as_str())
            .unwrap_or("begin");
        let a = act("tick", parent, ["@a", "@b", "@c"][i % 3]);
        accept(&d, &history, &a);
        history.push(a);
    }
    assert_eq!(state(&d, &history)["number"], 99);
    let b = act("tick", &history[98].address, "@b");
    let c = act("tick", &history[98].address, "@c");
    accept(&d, &history, &b);
    accept(&d, &history, &c);
    history.push(b.clone());
    history.push(c.clone());
    assert_eq!(
        state(&d, &history),
        serde_json::json!({"number":100,"messages":101})
    );
    for tip in [b, c] {
        let extra = act("tick", &tip.address, "@a");
        assert!(matches!(
            admit(&d, &ThreadId("t".into()), &history, &extra),
            Admission::Rejected(_)
        ));
    }
}

#[test]
fn nested_repeats_and_intervening_other_verbs_have_static_occurrence_ranks() {
    let d = install("open (repeat 2 (repeat 2 tick) other)");
    let mut history = vec![act("open", "begin", "@a")];
    let mut count = 0;
    for verb in ["tick", "tick", "other", "tick", "tick", "other"] {
        let a = act(verb, &history.last().unwrap().address, "@a");
        accept(&d, &history, &a);
        history.push(a);
        if verb == "tick" {
            count += 1;
        }
        assert_eq!(state(&d, &history)["number"], count);
    }
}

#[test]
fn rejects_missing_or_incomparable_positions_and_bad_rule_arity() {
    let mut d = install("(repeat 2 tick)");
    d.causal_protocol
        .as_mut()
        .unwrap()
        .steps
        .retain(|name, _| !name.starts_with("tick"));
    assert!(r7_violations(&d)
        .iter()
        .any(|e| e.to_string().contains("progress")));
    // A typed programmatic DAG with incomparable occurrences must not acquire
    // an arbitrary order merely because BTreeMap keys sort deterministically.
    use cbcl_core::protocol::NodeRef;
    let mut d = install("open (repeat 2 tick)");
    let p = d.causal_protocol.as_mut().unwrap();
    p.steps.get_mut("tick#2").unwrap().predecessors = vec![NodeRef::Single("open".into())];
    p.steps.get_mut("open").unwrap().successors = vec![NodeRef::All(
        ["tick#1".into(), "tick#2".into()].into_iter().collect(),
    )];
    p.steps.get_mut("tick#1").unwrap().successors.clear();
    assert!(r7_violations(&d)
        .iter()
        .any(|e| e.to_string().contains("incomparable")));
    assert!(parse_dialect(
        &parse(&source("(repeat 2 tick)").replace("(progress tick)", "(progress tick other)"))
            .unwrap()
    )
    .is_err());
}

#[test]
fn missing_evidence_and_unrelated_threads_cannot_invent_progress() {
    let d = install("(repeat 3 tick)");
    let a = act("tick", "begin", "@a");
    let b = act("tick", &a.address, "@b");
    assert_eq!(state(&d, &[b.clone()])["number"], 0);
    let other = Act::from_message(
        parse_message(
            &parse(&cbcl_core::intend::canonical_text(&a.message).replace("\"t\"", "\"other\""))
                .unwrap(),
        )
        .unwrap(),
        "@a",
    )
    .unwrap();
    assert_eq!(state(&d, &[other, b])["number"], 1);
}

#[test]
fn progress_is_integer_typed_described_and_content_addressed() {
    let d = install("(repeat 3 tick)");
    let schema = render_schema(&state_schema(d.state.as_ref().unwrap(), &d.shapes));
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(&schema).unwrap()["number"]["type"],
        "int"
    );
    let description: serde_json::Value = serde_json::from_str(
        &cbcl_parser::describe::describe_dialect_str(&source("(repeat 3 tick)")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        description["state"]["number"],
        serde_json::json!(["progress", "tick"])
    );
    let changed = parse_dialect(
        &parse(&source("(repeat 3 tick)").replace("(progress tick)", "(count tick)")).unwrap(),
    )
    .unwrap();
    assert_ne!(
        cbcl_core::canonical::dialect_hash(&d),
        cbcl_core::canonical::dialect_hash(&changed)
    );
}

#[test]
#[ignore = "requires lake build LeanCbcl.StateProgress; explicitly run by Lean CI"]
fn native_progress_matches_kernel_reduced_lean() {
    use cbcl_core::message::CausedBy;
    use std::collections::BTreeMap;
    use std::fmt::Write;
    struct Comparisons {
        source: String,
        cases: usize,
    }
    impl Comparisons {
        fn snapshot(&mut self, bound: usize, acts: &[Act]) {
            let d = install(&format!("(repeat {bound} tick)"));
            let actual = state(&d, acts)["number"].as_u64().unwrap();
            let id = self.cases;
            let mut addresses = BTreeMap::new();
            for a in acts {
                let next = addresses.len();
                addresses.entry(a.address.clone()).or_insert(next);
            }
            // Reserve absent-reference IDs after all present addresses. No
            // string/hash equality is guessed by the model transcription.
            for a in acts {
                for h in &a.predecessors {
                    let next = addresses.len();
                    addresses.entry(h.clone()).or_insert(next);
                }
            }
            writeln!(
                self.source,
                "def store{id} : Store := fun h => match h with"
            )
            .unwrap();
            let mut seen = std::collections::BTreeSet::new();
            for a in acts {
                if !seen.insert(&a.address) {
                    continue;
                }
                let h = addresses[&a.address];
                let cause = match a.simple().caused_by() {
                    Some(CausedBy::Begin) => ".begin".to_owned(),
                    Some(CausedBy::Single(p)) => format!(".previous {}", addresses[p]),
                    _ => ".absent".to_owned(),
                };
                assert_eq!(a.verb, "tick", "single-verb comparison boundary");
                assert_eq!(a.simple().thread(), Some("t"));
                writeln!(self.source, "  | {h} => some ⟨0, \"tick\", {cause}⟩").unwrap();
            }
            writeln!(self.source, "  | _ => none").unwrap();
            let hashes = acts
                .iter()
                .map(|a| addresses[&a.address].to_string())
                .collect::<Vec<_>>()
                .join(",");
            writeln!(self.source, "theorem comparison{id} : progress store{id} 0 \"tick\" {bound} [{hashes}] = {actual} := by decide\n#print axioms comparison{id}").unwrap();
            self.cases += 1;
        }
    }
    let mut checks = Comparisons { source: "import LeanCbcl.StateProgress\nopen CBCL.Repeat CBCL.StateProgress\nset_option maxRecDepth 4096\nset_option maxHeartbeats 0\n".into(), cases:0 };
    for bound in [1, 2, 3, 10, 100] {
        let mut history = Vec::new();
        checks.snapshot(bound, &history);
        for i in 0..bound {
            let pred = history
                .last()
                .map(|a: &Act| a.address.as_str())
                .unwrap_or("begin");
            history.push(act("tick", pred, ["@a", "@b", "@c"][i % 3]));
        }
        checks.snapshot(bound, &history[..1]);
        checks.snapshot(bound, &history);
        let pred = if bound == 1 {
            "begin"
        } else {
            history[bound - 2].address.as_str()
        };
        let peer = act("tick", pred, "@peer");
        history.push(peer);
        checks.snapshot(bound, &history);
        checks.snapshot(bound, &history[bound..]);
        history.reverse();
        let mut duplicated = history.clone();
        duplicated.extend(history);
        checks.snapshot(bound, &duplicated);
    }
    let path =
        std::env::temp_dir().join(format!("cbcl-state-progress-{}.lean", std::process::id()));
    std::fs::write(&path, &checks.source).unwrap();
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lean-cbcl");
    let output = std::process::Command::new("lake")
        .args(["env", "lean"])
        .arg(&path)
        .current_dir(root)
        .output()
        .unwrap();
    let _ = std::fs::remove_file(path);
    let report = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(output.status.success(), "{report}");
    assert!(
        !report.contains("sorry") && !report.contains("sorryAx"),
        "{report}"
    );
    let audited: Vec<&str> = report
        .lines()
        .filter(|line| line.starts_with("'comparison"))
        .collect();
    assert_eq!(audited.len(), checks.cases, "{report}");
    for line in audited {
        if line.contains("does not depend on any axioms") {
            continue;
        }
        let axioms = line
            .split_once('[')
            .and_then(|(_, tail)| tail.strip_suffix(']'))
            .expect("malformed axiom audit");
        assert!(
            axioms
                .split(',')
                .all(|a| matches!(a.trim(), "propext" | "Classical.choice" | "Quot.sound")),
            "nonstandard comparison axiom: {line}"
        );
    }
}

#[test]
fn domain_filtering_does_not_hide_causal_progress() {
    let text="(define demo (cbcl) @author (extend open (to options) (tell to :options options)) (extend tick (to choice) (tell to :choice choice)) (shape open (require :options list)) (shape tick (require :choice string)) (protocol (then begin open (repeat 3 tick))) (state (options (initial open :options)) (domain tick :choice options) (number (progress tick)) (messages (count tick))))";
    let mut registry = DialectRegistry::new();
    registry
        .install(parse_dialect(&parse(text).unwrap()).unwrap())
        .unwrap();
    let d = registry.iter().last().unwrap();
    let wire = |text: &str| {
        Act::from_message(parse_message(&parse(text).unwrap()).unwrap(), "@a").unwrap()
    };
    let open =
        wire("(lang demo (open @all :options (\"yes\") :caused-by begin :thread \"t\" :from @a))");
    let tick = wire(&format!(
        "(lang demo (tick @all :choice \"no\" :caused-by {} :thread \"t\" :from @a))",
        open.address
    ));
    accept(d, &[], &open);
    accept(d, &[open.clone()], &tick);
    let state = state(d, &[open, tick]);
    assert_eq!(state["number"], 1);
    assert_eq!(state["messages"], 0);
}

#[test]
fn progress_uses_pinned_role_root_and_accepts_competing_members() {
    let source="(define demo (cbcl) @author (:roles ((* member))) (extend tick (to) :from member :to (member) (tell to)) (protocol (then begin (repeat 100 tick))) (state (number (progress tick)) (messages (count tick))))";
    let mut registry = DialectRegistry::new();
    registry
        .install(parse_dialect(&parse(source).unwrap()).unwrap())
        .unwrap();
    let d = registry.iter().last().unwrap();
    let parse_act = |s: &str, who: &str| {
        Act::from_message(parse_message(&parse(s).unwrap()).unwrap(), who).unwrap()
    };
    let sealed =
        "(with-roles ((member @a @b @c)) (signed @a (hello :thread \"t\" :caused-by begin)))";
    for root_text in [sealed.to_string(), format!("(signed @a {sealed})")] {
        let root = parse_act(&root_text, "@a");
        let signed = |pred: &str, who: &str| {
            parse_act(&format!("(signed {who} (lang demo (tick (@a @b @c) :caused-by {pred} :thread \"t\" :from {who})))"),who)
        };
        let a = signed(&root.address, "@a");
        let b = signed(&a.address, "@b");
        let c = signed(&a.address, "@c");
        accept(d, &[], &root);
        accept(d, &[root.clone()], &a);
        accept(d, &[root.clone(), a.clone()], &b);
        accept(d, &[root.clone(), a.clone()], &c);
        let mut accepted = vec![root, a, b, c];
        assert_eq!(
            state(d, &accepted),
            serde_json::json!({"number":2,"messages":3})
        );
        accepted.reverse();
        assert_eq!(state(d, &accepted)["number"], 2);
    }
}

#[test]
fn json_authoring_compiles_progress_through_the_same_native_rule() {
    let contract = serde_json::json!({"version":3,"kind":"contract","name":"progress-demo","verbs":{"open":{"after":["begin"],"fields":{}},"tick":{"after":["open"],"fields":{}}},"state":{"number":["progress","tick"]}});
    let compiled: serde_json::Value =
        serde_json::from_str(&cbcl_parser::compile_contract_str(&contract.to_string()).unwrap())
            .unwrap();
    assert!(compiled["dialect"]
        .as_str()
        .unwrap()
        .contains("(number (progress tick))"));
}

#[test]
fn progress_does_not_feed_back_into_acceptance() {
    let progress = install("(repeat 2 tick)");
    let mut registry = DialectRegistry::new();
    registry
        .install(
            parse_dialect(
                &parse(&source("(repeat 2 tick)").replace("(progress tick)", "(count tick)"))
                    .unwrap(),
            )
            .unwrap(),
        )
        .unwrap();
    let counted = registry.iter().last().unwrap();
    let a = act("tick", "begin", "@a");
    let b = act("tick", &a.address, "@b");
    let c = act("tick", &a.address, "@c");
    let history = vec![a, b, c];
    assert_ne!(
        state(&progress, &history)["number"],
        state(counted, &history)["number"]
    );
    for candidate in [
        act("tick", &history[0].address, "@d"),
        act("tick", &history[1].address, "@d"),
    ] {
        assert_eq!(
            admit(&progress, &ThreadId("t".into()), &history, &candidate),
            admit(counted, &ThreadId("t".into()), &history, &candidate)
        );
    }
}

#[test]
fn shipped_counting_dialect_installs_with_progress() {
    let source = include_str!("../../../dialects/count-to-one-hundred.cbcl");
    let mut registry = DialectRegistry::new();
    registry
        .install(parse_dialect(&parse(source).unwrap()).unwrap())
        .unwrap();
    let d = registry.iter().last().unwrap();
    assert_eq!(state(d, &[])["number"], 0);
}