From d6bf6d0647ac43d3d680a66df74031dd4c6fbf62 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 22:13:15 +0000 Subject: [PATCH 01/17] SubtractZipper: resume the survival search at the pending branch subtree_has_difference() searches the shared part of both tries depth first, keeping the branch points that still have unvisited children. When a subtree was exhausted it climbed back with lhs.ascend_until_branch(), which stops at the nearest branch, not the nearest *pending* one. With a fully explored branch in between, it re-searched that branch, popped the pending entry, and never visited the pending child, so a surviving value there was missed and the subtree reported empty. The re-search can also repeat forever: a 1M-case algebraic fuzz sweep with nested SubtractZippers hung with every job inside SubtractZipper::new -> refresh -> ascend_until_branch. Record the depth of each pending branch and ascend exactly that far. Found by the algebraic fuzzer's subtract_zipper route: b - a where a is dangling-only structure and b is a plus one value. --- src/subtract_zipper.rs | 50 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/src/subtract_zipper.rs b/src/subtract_zipper.rs index 43a5e57b..b70caae1 100644 --- a/src/subtract_zipper.rs +++ b/src/subtract_zipper.rs @@ -753,7 +753,9 @@ where B: ZipperMoving + ZipperValues, { let mut depth = 0; - let mut branch_bytes = SmallVec::<[u8; 8]>::new(); + // Branch points with unexplored children: the depth of the branch and the + // next child to visit there. + let mut branch_points = SmallVec::<[(usize, u8); 8]>::new(); loop { let lhs_mask = lhs.child_mask(); @@ -778,10 +780,9 @@ where let next_common_byte = lhs_mask.indexed_bit::(0); match next_common_byte { Some(byte) => { - // Remember only genuine branch points. The zipper itself knows - // how far it must ascend to get back here. + // Remember only genuine branch points. if let Some(following_byte) = lhs_mask.next_bit(byte) { - branch_bytes.push(following_byte); + branch_points.push((depth, following_byte)); } lhs.descend_to_byte(byte); @@ -791,9 +792,11 @@ where depth += 1; } None => { - // The current subtree is exhausted. Skip the entire unary suffix and - // return directly to the nearest branch with unexplored children. - let Some(next_byte) = branch_bytes.last_mut() else { + // The current subtree is exhausted. Return directly to the nearest + // branch with unexplored children. That is not necessarily the + // nearest branch: branches in between may be fully explored, so + // ascend by the recorded depth rather than to the next branch. + let Some((branch_depth, next_byte)) = branch_points.last_mut() else { let lhs_ascended = lhs.ascend(depth); let rhs_ascended = rhs.ascend(depth); @@ -806,9 +809,11 @@ where return false; }; - let ascended = lhs.ascend_until_branch(); + let ascended = depth - *branch_depth; + let lhs_ascended = lhs.ascend(ascended); let rhs_ascended = rhs.ascend(ascended); + debug_assert_eq!(lhs_ascended, ascended); debug_assert_eq!(rhs_ascended, ascended); witness.ascend(ascended); @@ -820,7 +825,7 @@ where if let Some(following_byte) = lhs.child_mask().next_bit(cur_byte) { *next_byte = following_byte; } else { - branch_bytes.pop(); + branch_points.pop(); } lhs.descend_to_byte(cur_byte); @@ -2024,4 +2029,31 @@ mod tests { } } } + + /// The survival search must resume at the pending branch point, not at the + /// nearest branch: here `01/00` is a fully explored branch between the + /// exhausted `01/00/01/00` and the pending `01/01`, where the only + /// surviving value is. + #[test] + fn survival_search_skips_explored_branches() { + use crate::zipper::ZipperWriting; + let mut rhs = PathMap::::new(); + for path in [&[0, 0, 0, 0, 0][..], &[1, 0, 0], &[1, 0, 1, 0], &[1, 1]] { + let mut wz = rhs.write_zipper_at_path(path); + wz.create_path(); + } + let mut lhs = rhs.clone(); + lhs.insert([1, 1], 1); + let expected = lhs.subtract(&rhs); + assert_eq!(expected.iter().collect::>(), vec![(vec![1, 1], &1)]); + + let mut zipper = subtract_at(&lhs, &rhs, &[]); + assert!(zipper.path_exists()); + assert_eq!(zipper.val_count(), 1); + let mut got = Vec::new(); + while zipper.to_next_val() { + got.push((zipper.path().to_vec(), *zipper.val().unwrap())); + } + assert_eq!(got, vec![(vec![1, 1], 1)]); + } } From 34ec4dcdfd810be3247591a14105beff97a12c47 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 22:08:35 +0000 Subject: [PATCH 02/17] SubtractZipper: derive Clone A clone is an independent zipper at the same focus, cached state included. This also lets a SubtractZipper be the input of another one, since its ZipperMoving impl requires Clone inputs: (a - b) - c without materialising a - b. --- src/subtract_zipper.rs | 53 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/subtract_zipper.rs b/src/subtract_zipper.rs index b70caae1..40879112 100644 --- a/src/subtract_zipper.rs +++ b/src/subtract_zipper.rs @@ -31,7 +31,7 @@ impl PathObserver for PathWitness { } } -#[derive(Debug)] +#[derive(Clone, Debug)] struct SurvivalWitness { path: SmallVec<[u8; 16]>, pos: usize, @@ -132,6 +132,8 @@ impl SurvivalWitness { } } +/// Cloning gives an independent zipper at the same focus, cached state included. +#[derive(Clone)] pub struct SubtractZipper { lhs: A, rhs: B, @@ -158,6 +160,7 @@ pub struct SubtractZipper { survival_witness: Option, } +#[derive(Clone)] enum CachedVal { None, Lhs, @@ -2030,6 +2033,54 @@ mod tests { } } + #[test] + fn clone_moves_independently() { + let lhs = PathMap::from_iter([(&[1, 2, 3][..], 1u16), (&[1, 4], 2), (&[5], 3)]); + let rhs = PathMap::from_iter([(&[1, 4][..], 2u16)]); + let expected = lhs.subtract(&rhs); + + let mut zipper = subtract_at(&lhs, &rhs, &[]); + zipper.descend_to([1]); + let mut cloned = zipper.clone(); + assert_eq!(cloned.path(), &[1]); + assert_eq!(cloned.child_mask(), zipper.child_mask()); + + cloned.descend_to([2, 3]); + assert_eq!(cloned.val(), Some(&1)); + assert_eq!(zipper.path(), &[1]); + + zipper.reset(); + zipper.descend_to([1, 4]); + assert!(!zipper.path_exists()); + assert_eq!(cloned.path(), &[1, 2, 3]); + let mut expected_z = expected.read_zipper(); + expected_z.descend_to([1, 2, 3]); + assert_eq!(cloned.val(), expected_z.val()); + } + + /// A `SubtractZipper` can be the input of another one, computing `(a - b) - c`. + #[test] + fn nested_subtract_matches_materialized() { + let a = PathMap::from_iter([(&[1, 2][..], 1u16), (&[1, 3], 2), (&[4], 3), (&[4, 5], 4), (&[6], 5)]); + let b = PathMap::from_iter([(&[1, 2][..], 1u16), (&[4], 3)]); + let c = PathMap::from_iter([(&[1, 3][..], 2u16), (&[4, 5], 9), (&[7], 1)]); + let expected = a.subtract(&b).subtract(&c); + + let inner = SubtractZipper::new(a.read_zipper(), b.read_zipper()); + let mut nested = SubtractZipper::new(inner, c.read_zipper()); + let mut expected_z = expected.read_zipper(); + + let mut got = vec![(nested.path().to_vec(), nested.val().cloned())]; + while nested.to_next_step() { + got.push((nested.path().to_vec(), nested.val().cloned())); + } + let mut want = vec![(expected_z.path().to_vec(), expected_z.val().cloned())]; + while expected_z.to_next_step() { + want.push((expected_z.path().to_vec(), expected_z.val().cloned())); + } + assert_eq!(got, want); + } + /// The survival search must resume at the pending branch point, not at the /// nearest branch: here `01/00` is a fully explored branch between the /// exhausted `01/00/01/00` and the pending `01/01`, where the only From 4a7f0839e0cb8ca2cfcae56712f1399b47c12741 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 2 Oct 2026 18:36:46 +0000 Subject: [PATCH 03/17] Add an algebraic equivalence fuzzer to the differential crate The two existing fuzzers ask whether the answer is right -- the Lean model in lean/ is the oracle -- or whether anything crashes. This one asks whether it matters which way you compute it. pathmap implements each algebraic operation several times over: eagerly on whole maps, in place through a write zipper, as a lockstep traversal of two read zippers, and for the associative ones again as an n-ary traversal, a DNF evaluator, and a lazy zipper over a virtual trie. Those are separate implementations with separate pruning, grafting and value-combining logic, so they can check each other without anyone writing down what the answer should be. Each case is one expression over four generated tries, evaluated by every route that applies to its shape, with every answer required to match. laws.rs is the other half: pairs of expressions that must agree whatever the operands, which is what catches a mistake every route shares -- including one in the baseline the routes are compared against. No oracle, no Lean build, no child process: about 55k cases/sec in process. Six defects on master, each reproduced without the fuzzer in alg_bug_repros: 1. join_into drops the source's root value when the destination is empty. 2. meet_2 drops root values outright. 3. PathMap::join and PathMap::meet take the right operand's value at a shared path when the operands' nodes are laid out differently. u64's pjoin is left-biased and pmeet is Identity(SELF_IDENT), so the left value must win. Every zipper route gets this right, which is why it surfaces as failing laws rather than as one route disagreeing with the others. 4. join loses a value across shared structure: with b a clone of a plus one value, a|b drops it and b|a keeps it. A join is a least upper bound, so no ordering may lose a path. Needs the operands to share allocations -- rebuilding b's entries into a fresh map hides it. 5. merkleize panics on a trie holding only dangling paths. Not algebraic; it fires while the operands are still being written. 6. Debug-assertions only, and the mechanism behind 4: join's "empty result" path is reachable from nodes that are not empty. algebraic::KNOWN maps every signature onto one of those and decides exit status only; counts always print, so a known defect firing ten times more often is still visible. Verified clean at 2M cases in release and 2M with debug assertions enabled. Two notes for whoever extends this. u64's value semantics are not set semantics, so several textbook identities hold on path presence but not on values; laws.rs lists the ones deliberately absent and why. And the recognisers that decide which route applies were both wrong at first in ways that looked exactly like crate defects -- the n-ary forms fold symmetric difference left, and a DNF clause is an unordered bitmask that cannot represent `b & a` -- so they are pinned by tests. When a route disagrees with the rest, suspect the route first. differential now builds pathmap with the zipper_alg feature. ALGEBRAIC_FUZZING.md has the full write-up. --- .gitignore | 2 + differential/ALGEBRAIC_FUZZING.md | 282 ++++++++++ differential/Cargo.toml | 2 +- differential/src/algebraic.rs | 745 +++++++++++++++++++++++++ differential/src/algebraic/expr.rs | 218 ++++++++ differential/src/algebraic/laws.rs | 182 ++++++ differential/src/algebraic/model.rs | 106 ++++ differential/src/algebraic/routes.rs | 486 ++++++++++++++++ differential/src/algebraic/shape.rs | 164 ++++++ differential/src/bin/alg_bug_repros.rs | 184 ++++++ differential/src/bin/alg_fuzz.rs | 431 ++++++++++++++ differential/src/lib.rs | 5 + differential/tests/algebraic.rs | 190 +++++++ 13 files changed, 2996 insertions(+), 1 deletion(-) create mode 100644 differential/ALGEBRAIC_FUZZING.md create mode 100644 differential/src/algebraic.rs create mode 100644 differential/src/algebraic/expr.rs create mode 100644 differential/src/algebraic/laws.rs create mode 100644 differential/src/algebraic/model.rs create mode 100644 differential/src/algebraic/routes.rs create mode 100644 differential/src/algebraic/shape.rs create mode 100644 differential/src/bin/alg_bug_repros.rs create mode 100644 differential/src/bin/alg_fuzz.rs create mode 100644 differential/tests/algebraic.rs diff --git a/.gitignore b/.gitignore index 790fe2ad..996db83b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ whisper_benches/logs /lean/.lake /lean/.shrink.bin __pycache__/ +# Algebraic fuzzer reproducers: local only, written by alg_fuzz sweeps +/differential/algebraic-corpus/ diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md new file mode 100644 index 00000000..636e3556 --- /dev/null +++ b/differential/ALGEBRAIC_FUZZING.md @@ -0,0 +1,282 @@ +# Algebraic equivalence fuzzer + +The third fuzzer in this repository, and the one that needs no oracle. + +The other two ask *is the answer right?* — the Lean model in `../lean` is the +authority and `bin/pathmap_trace` is diffed against it, and the crash fuzzer +asks only whether anything blows up. This one asks a different question: + +> **Does it matter which way you compute it?** + +It should not, and `pathmap` offers enough different ways that the question has +teeth. Each case is one algebraic expression over a few generated tries, +evaluated by every route that applies to it, with every answer required to +match. + +```sh +cargo build --release -p differential --bin alg_fuzz + +# a million cases takes about twenty seconds +cargo run --release -p differential --bin alg_fuzz -- --random 1000000 --seed 1 --jobs 8 + +# replay the local corpus (gitignored; sweeps save one input per signature there) +cargo run --release -p differential --bin alg_fuzz -- differential/algebraic-corpus/*.bin + +# minimise a failing input, keeping one particular finding +cargo run --release -p differential --bin alg_fuzz -- --shrink input.bin --target values:nary + +# the findings so far, as plain pathmap calls with no fuzzer involved +cargo run --release -p differential --bin alg_bug_repros +``` + +`cargo test -p differential --test algebraic` is the cheap gate: it replays the +local corpus if there is one, does a short sweep, and pins the harness's own invariants. + +## Why equivalence instead of an oracle + +Writing the Lean model was most of the cost of the existing differential +fuzzer, and it bought a very strong property: the model says what every call +*means*. But it has to be kept in step with the crate by hand — `harness.rs` +and `PathMapModel/Fuzz.lean` share a wire format and an operation table as a +contract — and that cost is paid again for every operation added. + +The algebra is the part of `pathmap` where that trade is worst and where it is +least necessary. Worst, because the operations are the crate's most +re-implemented surface: join exists six times over. Least necessary, because +*the implementations can check each other*. If `PathMap::join`, `join_into`, +`join_map_into`, `join_into_take`, `zipper_join`, `zipper_n_join`, +`zipper_merge_dnf` and `OverlayZipper` all compute a least upper bound, then +they agree, and any disagreement is a defect without anyone having to say in +advance which answer was right. + +That is the whole design. It costs nothing to maintain — a new operation gets +a new entry in a table — and it found six defects in the first few thousand +cases. + +What it gives up is the ability to say *which* side is wrong. A divergence is a +fact about two implementations; deciding between them is a human judgement, and +`algebraic::KNOWN` records the ones that have been made. + +## What is being compared + +### Routes + +A **route** is one consistent way to evaluate a whole expression. Two kinds: + +**Pointwise** routes walk the expression bottom-up and evaluate each node with +a two-operand call, materialising every intermediate into a trie. Route `k` +picks strategy `k % n` for an operator with `n` strategies, so every strategy +is reached by some route and the routes mix them: + +| operator | strategies | +| --- | --- | +| join `\|` | `PathMap::join`, `join_into`, `join_map_into`, `join_into_take`, `zipper_join`, `OverlayZipper` | +| meet `&` | `PathMap::meet`, `meet_into`, `meet_2`, `zipper_meet` | +| subtract `-` | `PathMap::subtract`, `subtract_into`, `zipper_subtract` | +| sym. difference `^` | `zipper_sym_diff`, `(a \| b) - (a & b)` | +| restrict `/` | `PathMap::restrict`, `WriteZipper::restrict` | + +**Whole-expression** routes recognise a shape and hand the entire thing to one +call. These are the routes with real independence, because no intermediate trie +is ever built: + +| route | applies to | call | +| --- | --- | --- | +| `ternary` | a chain of three operands | `zipper_join3` and friends | +| `nary` | a chain of any length | `zipper_n_join` and friends | +| `nary_poly` | the same chain | `ZipperMergeF::join_n` and friends, via the `PolyZipper` enum | +| `dnf` | a join of meets | `zipper_merge_dnf` | +| `model` | anything | a flat `BTreeMap`, no trie at all | + +The `model` route is the fourth opinion. Every other route goes through +`pathmap`, so a defect common to the whole algebra layer would make them agree +and still be wrong. It is also the route that found the value-bias defect +fastest, because it has no node layout to be biased by. + +### Laws + +Route comparison catches an implementation that disagrees with its siblings. It +cannot catch a mistake they all share. `src/algebraic/laws.rs` is the other +half: each law is two *different expressions* that must evaluate to the same +trie, so a wrong answer is visible even when every route computes it the same +wrong way. Idempotence, units, associativity, absorption, distributivity, and +the definition `zipper_sym_diff`'s own documentation gives. + +Laws are the reason a defect in the *baseline* is findable at all. When +`PathMap::meet` takes the wrong operand's value, no route disagrees with the +baseline in an interesting way — the baseline is what everyone is compared +against. `meet-distributes-over-join` has no baseline to be fooled by: it puts +the operands on different sides of a meet and notices. + +### The value semantics are not set semantics + +Three laws are checked on path presence only, and three plausible ones are +deliberately absent. Both follow from `u64`'s lattice instances in +`pathmap::ring`, which are left-biased: `pjoin` keeps the left value where the +two differ, and `pmeet` keeps the left value *unconditionally*. So join and +meet are not commutative in the value they produce, only in their path set. +`laws.rs` documents each case, including the identities that look true and are +not. + +Getting this wrong is the main way to write a harness that reports its own +mistakes as crate defects, and it happened twice while this one was being +built — see "Harness invariants" below. + +## Generated operands + +Four tries per case, over a small alphabet so they collide, with few entries +and short paths. Three details earn their keep: + +* **Three distinct values.** `psubtract` on `u64` is `None` only when the two + values are *equal*, and symmetric difference cancels on coincident paths. A + large value space would degenerate both into set difference and set union and + never exercise the value-combining code at all. + +* **Dangling paths**, written with `create_path` and carrying no value. Whether + one survives an operation is unsettled in the crate, so a divergence confined + to them is reported as its own class. + +* **Four build modes.** `Fresh` writes entries into a new map. `CloneOf` + clones an earlier operand and mutates it, so the two share *allocations* + rather than merely equal content. `ReinsertOf` writes an earlier operand's + entries back in a different order — equal content, different node layout, no + sharing. `MerkleizedOf` runs `merkleize` to factor equal subtries into one + allocation. + +The last three are not decoration. The value-bias defect needs operands whose +nodes are laid out differently, and the value-loss defect needs operands that +share nodes — it disappears if `b`'s entries are rebuilt into a fresh map +instead of cloned. A generator that only wrote fresh tries would find neither. + +## Divergence classes + +| class | meaning | fails a run | +| --- | --- | --- | +| `values` | two routes put different values on a path, or disagree about whether a path has one | yes | +| `shape` | the routes agree on every value and differ only in dangling paths | only under `--shape` | +| `law` | an identity that must hold whatever the operands are does not | yes | +| `panic:build` | a crash while *writing the operand tries*, before any algebra ran | yes | +| `panic:eval` | a crash inside an algebraic operation | yes | + +`shape` is separated because the semantics are genuinely unsettled — see +`../SPEC_WARTS.md` and the `meet_into-keeps-dangling*` corpus entries, which are +the same question — and because routes that graft whole subtries will keep +structure that routes walking path by path cannot. A wrong *value* is never +ambiguous. + +Signatures are `class:route`, and nothing more. An earlier version appended the +operators the expression used, which looked more informative and was much +worse: one defect in `meet` produced dozens of signatures because it surfaced +under every operator combination containing a meet. The expression, the +operands and the diff all live in the saved `.txt`; the signature's only job is +to collapse a million inputs onto a handful of lines. + +## Debug assertions are a separate mode + +`pathmap`'s `debug_assert!`s are the sharpest instrument here, and a release +build cannot see them. Three of the findings below are visible *only* with +assertions on, and two of them are the mechanism behind a defect that the +release build can only observe as a wrong answer: + +```sh +RUSTFLAGS="-C target-cpu=native -C debug-assertions=yes" \ + cargo build --release -p differential --bin alg_fuzz --target-dir target/dbgassert +./target/dbgassert/release/alg_fuzz --random 5000000 --seed 1 --jobs 8 +``` + +Keep `-C target-cpu=native`: `.cargo/config.toml` sets it, a bare `RUSTFLAGS` +replaces rather than extends it, and `gxhash` fails to compile without the +`aes` and `sse2` intrinsics it implies. + +`cargo test` is itself a debug-assertions build, which is why the corpus test +expects the `panic:eval:*` signatures. + +## Findings + +Six defects on `master` at `b4a6abd`, reproduced without the fuzzer in +`src/bin/alg_bug_repros.rs`. `algebraic::KNOWN` maps every signature onto one of +them. + +1. **`join_into` drops the source's root value when the destination is empty.** + `PathMap::new().join(&src)` keeps it; the write-zipper spelling does not. + +2. **`meet_2` drops root values outright.** Two maps whose only content is a + root value intersect to that root value; `meet_2` produces nothing. + +3. **Value bias by node layout.** `PathMap::join` and `PathMap::meet` take the + *right* operand's value at a shared path when the two operands' nodes are + laid out differently. Every zipper route gets this right, which is why it + surfaces as failing laws and as the `model` route disagreeing — the defect is + in the baseline. + +4. **`join` loses a value across shared structure.** With `b` a clone of `a` + plus one extra value, `a | b` drops that value and `b | a` keeps it. A join + is a least upper bound, so no ordering of the operands may lose a path; this + is the one finding that needs no argument about value bias. Found by + `join-commutative`, which is checked on paths only and so cannot be fooled by + cause 3. + +5. **`merkleize` panics on a trie holding only dangling paths.** Not algebraic: + it fires while the operands are still being written. Kept rather than + generated around, because `merkleize` is how the generator produces shared + subtries and finding 4 needs them. + +6. **Join's "empty result" path is reachable from non-empty nodes.** Three + debug assertions, one story, and the mechanism behind finding 4: + `merge_from_list_node` returns `AlgebraicStatus::None` from nodes that are not + empty (`line_list_node.rs:2669` and `:2720`), and a cofree `pjoin` returns + `None` while the left side still has a non-empty onward node + (`dense_byte_node.rs:2080`). + +### Reading a report + +Every signature is printed with its count, known or not, and a `<-- NEW` marker +on anything absent from `KNOWN`. Exit status is 1 if anything is new; +`--strict` makes every finding fatal. Counts matter even for known findings: a +known defect that starts firing ten times more often is a change worth seeing, +and it does not turn the run red. + +`KNOWN` is a snapshot, not a closed list. A longer sweep may well reach a new +assertion site — the three in finding 6 appeared at 500 000, 3 000 000 and +roughly 400 000 cases respectively. A new signature is the fuzzer working. + +## Harness invariants + +A harness that reports its own mistakes as crate defects is worse than no +harness. Two of the recognisers that decide which route applies were wrong when +this fuzzer was first run, and both failures looked exactly like crate defects: + +* `a ^ (b ^ c)` was flattened into the n-ary call, which folds values left. For + root values `a = 2`, `b = 1`, the nested form is `a ^ nothing = 2` and the + fold is `(2 ^ 2) ^ 1 = 1`. Both are defensible; they are not equal, so a + right-nested symmetric difference is not a chain. + +* A DNF clause was allowed to stand in for `b & a`. A `Clause` is a *bitmask* — + it records which zippers take part, not in what order — and `zipper_merge_dnf` + meets a clause's members in slot order while `pmeet` is left-biased, so `a & + b` and `b & a` carry different values and only one of them is what the clause + computes. + +Both are now pinned by tests in `tests/algebraic.rs`, along with the invariant +that every strategy index is reachable from some pointwise route. When a route +disagrees with the rest, suspect the route first. + +## Layout + +| file | what | +| --- | --- | +| `src/algebraic.rs` | input decoding, operand generation, the comparison, `KNOWN` | +| `src/algebraic/expr.rs` | the expression language and the shape recognisers | +| `src/algebraic/routes.rs` | the routes, and one arm per strategy | +| `src/algebraic/laws.rs` | the identities, and the ones deliberately absent | +| `src/algebraic/model.rs` | flat `BTreeMap` semantics | +| `src/algebraic/shape.rs` | what "the same result" means | +| `src/bin/alg_fuzz.rs` | the driver: generation, replay, shrinking, reporting | +| `src/bin/alg_bug_repros.rs` | the findings as plain `pathmap` calls | +| `tests/algebraic.rs` | the corpus gate and the harness invariants | +| `algebraic-corpus/` | local and gitignored: one saved input per signature, from sweeps | + +Byte decoding reuses `harness::Dec`. The wire format is *not* the one +`harness.rs` shares with `PathMapModel.Fuzz`: this fuzzer has no model to stay +in step with, so its inputs are free to be whatever generates interesting +tries. diff --git a/differential/Cargo.toml b/differential/Cargo.toml index 4218b74a..6b2ff2ea 100644 --- a/differential/Cargo.toml +++ b/differential/Cargo.toml @@ -6,4 +6,4 @@ publish = false description = "The Rust side of the differential fuzzing harness for pathmap's zipper API; the Lean model in ../lean is the oracle" [dependencies] -pathmap = { path = "..", features = ["arena_compact"] } +pathmap = { path = "..", features = ["arena_compact", "zipper_alg"] } diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs new file mode 100644 index 00000000..f65fc5b4 --- /dev/null +++ b/differential/src/algebraic.rs @@ -0,0 +1,745 @@ +//! Equivalence fuzzer for the algebraic operations. +//! +//! The other two fuzzers in this crate ask *is the answer right?* -- the Lean +//! model in `../lean` is an oracle, and `bin/pathmap_trace.rs` is diffed +//! against it. This one asks a different question: **does it matter which way +//! you compute it?** It should not, and `pathmap` offers enough different ways +//! that the question has teeth. +//! +//! Each case is one algebraic expression over a few generated operand tries, +//! evaluated by every route in `routes.rs` that applies to it -- eagerly on +//! whole maps, in place through a write zipper, as a lockstep traversal of two +//! read zippers, as a single n-ary traversal, through the DNF engine, through a +//! lazy `OverlayZipper` over a virtual trie, and over a flat `BTreeMap` with no +//! trie at all. Then `laws.rs` evaluates pairs of expressions that must agree +//! whatever the operands, which catches the mistakes every route shares. +//! +//! No Lean build is needed and there is no oracle: a divergence says the +//! implementations disagree, not which one is wrong. +//! +//! The wire format here is **not** the one `harness.rs` shares with +//! `PathMapModel.Fuzz`; this fuzzer has no model to stay in step with, so its +//! inputs are free to be whatever generates interesting tries. +//! +//! See `../ALGEBRAIC_FUZZING.md`. + +pub mod expr; +pub mod laws; +pub mod model; +pub mod routes; +pub mod shape; + +use pathmap::PathMap; +use pathmap::zipper::{ZipperMoving, ZipperWriting}; + +use expr::{Expr, Op, MAX_VARS}; +use laws::{Level, EMPTY, LAW_OPERANDS}; +use routes::Route; +use shape::{shape_of_map, show_shape, Shape, Values}; + +/// Operand tries per case. Fixed rather than generated so the expression +/// generator can always name any of them, and so [`MAX_VARS`] is the only +/// bound the const-generic route dispatch has to respect. +pub const OPERANDS: usize = MAX_VARS; + +/// Upper bound on entries written into one operand. Small on purpose: the +/// interesting cases are the ones where operands overlap at a node boundary, +/// and small tries over a small alphabet collide far more often than large +/// ones. +pub const MAX_ENTRIES: usize = 7; + +/// Upper bound on a generated path's length. +pub const MAX_PATH_LEN: usize = 5; + +/// Distinct values in circulation. Deliberately tiny: `psubtract` on `u64` is +/// `None` only when the two values are *equal*, and symmetric difference +/// cancels on coincident paths, so a large value space would make both +/// operations degenerate into set difference and set union and never exercise +/// the value-combining paths at all. +pub const VALUES: u64 = 3; + +/// Byte decoding with the out-of-input behaviour this fuzzer wants. +/// +/// Not `harness::Dec`: that one returns `None` when the input runs out, because +/// the Lean harness stops executing there, and it reads a wire header this +/// format does not have. Here every input has to decode to *some* case or +/// shrinking would have to care about length, so exhaustion saturates to zero +/// instead. +pub struct Gen<'a> { + bytes: &'a [u8], + pos: usize, + /// Size of the path alphabet. A small one makes operands share prefixes + /// and collide; the full 256 exercises wide nodes. + alphabet: u16, +} + +impl<'a> Gen<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Gen { bytes, pos: 0, alphabet: 3 } + } + pub fn byte(&mut self) -> u8 { + let b = self.bytes.get(self.pos).copied().unwrap_or(0); + self.pos += 1; + b + } + pub fn modn(&mut self, m: usize) -> usize { + if m == 0 { 0 } else { self.byte() as usize % m } + } + pub fn boolean(&mut self) -> bool { + self.byte() % 2 == 1 + } + /// True with probability `pct`/100. + pub fn chance(&mut self, pct: u8) -> bool { + (self.byte() as u16 * 100 / 256) < pct as u16 + } + pub fn path_byte(&mut self) -> u8 { + (self.byte() as u16 % self.alphabet) as u8 + } + pub fn path(&mut self, max_len: usize) -> Vec { + let n = self.modn(max_len + 1); + (0..n).map(|_| self.path_byte()).collect() + } + pub fn val(&mut self) -> u64 { + self.byte() as u64 % VALUES + 1 + } +} + +/// How one operand trie was built. Recorded so a failure report can say +/// whether the case depended on structural sharing or on node layout, which is +/// the difference between a logic bug and a representation bug. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Build { + /// Entries written into a fresh map. + Fresh, + /// A clone of an earlier operand, then mutated. Clones share nodes, so + /// this is how a case gets two operands whose subtries are the *same* + /// allocation rather than merely equal -- the distinction several of the + /// defects in `../lean/FINDINGS.md` turned on. + CloneOf(usize), + /// The same `(path, value)` entries as an earlier operand, rewritten into a + /// fresh map in a different order. Equal content, possibly different node + /// layout and certainly no shared nodes: the counterpart to `CloneOf`, and + /// the shape that catches an operation whose answer depends on how its + /// input happens to be stored. + ReinsertOf(usize), + /// A clone of an earlier operand with `merkleize` run over it, which + /// factors equal subtries into one shared allocation. + MerkleizedOf(usize), +} + +pub struct Case { + pub expr: Expr, + pub operands: Vec>, + pub builds: Vec, + pub alphabet: u16, +} + +/// Decode a byte string into a case. Total: every input decodes. +pub fn decode(bytes: &[u8]) -> Case { + let mut g = Gen::new(bytes); + // A 3-letter alphabet is the default because collisions are the point; the + // wider ones are sampled to keep node-type coverage honest, since `pathmap` + // switches node representation on child count. + g.alphabet = match g.modn(10) { + 0 => 256, + 1 => 16, + 2 => 2, + _ => 3, + }; + let alphabet = g.alphabet; + + let mut operands: Vec> = Vec::with_capacity(OPERANDS); + let mut builds: Vec = Vec::with_capacity(OPERANDS); + for i in 0..OPERANDS { + let build = pick_build(&mut g, i); + operands.push(build_operand(&mut g, build, &operands)); + builds.push(build); + } + + let expr = gen_expr(&mut g, 3); + Case { expr, operands, builds, alphabet } +} + +fn pick_build(g: &mut Gen, i: usize) -> Build { + if i == 0 { + return Build::Fresh; + } + match g.modn(8) { + 0 | 1 | 2 | 3 => Build::Fresh, + 4 | 5 => Build::CloneOf(g.modn(i)), + 6 => Build::ReinsertOf(g.modn(i)), + _ => Build::MerkleizedOf(g.modn(i)), + } +} + +fn build_operand(g: &mut Gen, build: Build, prior: &[PathMap]) -> PathMap { + match build { + Build::Fresh => fresh(g), + Build::CloneOf(j) => { + let mut m = prior[j].clone(); + mutate(g, &mut m); + m + } + Build::ReinsertOf(j) => { + // Collect the entries, then write them back in a rotated order. + // Rotation rather than a full shuffle because it is enough to + // change which insert splits which node, and it keeps the decoding + // cost one byte. + let entries: Vec<(Vec, u64)> = + shape::values_of_shape(&shape_of_map(&prior[j])).into_iter().collect(); + let mut out = PathMap::new(); + if !entries.is_empty() { + let r = g.modn(entries.len()); + let mut wz = out.write_zipper(); + for off in 0..entries.len() { + let (p, v) = &entries[(off + r) % entries.len()]; + wz.reset(); + wz.descend_to(p); + wz.set_val(*v); + } + } + out + } + Build::MerkleizedOf(j) => { + let mut m = prior[j].clone(); + m.merkleize(); + mutate(g, &mut m); + m + } + } +} + +fn fresh(g: &mut Gen) -> PathMap { + let n = g.modn(MAX_ENTRIES + 1); + let mut out = PathMap::new(); + { + let mut wz = out.write_zipper(); + for _ in 0..n { + let p = g.path(MAX_PATH_LEN); + wz.reset(); + wz.descend_to(&p); + // A path written with `create_path` and no value is a dangling + // path: structure with nothing under it. Operations disagree about + // whether those survive, so they are generated on purpose and the + // comparison reports them as their own class. + if g.chance(20) { + wz.create_path(); + } else { + wz.set_val(g.val()); + } + } + } + out +} + +fn mutate(g: &mut Gen, m: &mut PathMap) { + let n = g.modn(3); + let mut wz = m.write_zipper(); + for _ in 0..n { + let p = g.path(MAX_PATH_LEN); + wz.reset(); + wz.descend_to(&p); + match g.modn(4) { + 0 => { + wz.remove_val(false); + } + 1 => { + wz.create_path(); + } + 2 => { + wz.remove_branches(false); + } + _ => { + wz.set_val(g.val()); + } + } + } +} + +fn gen_expr(g: &mut Gen, depth: usize) -> Expr { + // Leaf at depth 0, and otherwise often enough that the chain and DNF + // recognisers fire regularly -- a tree that is always maximally deep is + // never a chain of operands, so the whole-expression routes would almost + // never apply. + if depth == 0 || g.chance(35) { + return Expr::Var(g.modn(OPERANDS)); + } + let op = match g.modn(12) { + 0 | 1 | 2 | 3 => Op::Join, + 4 | 5 | 6 => Op::Meet, + 7 | 8 => Op::Subtract, + 9 | 10 => Op::SymDiff, + _ => Op::Restrict, + }; + Expr::bin(op, gen_expr(g, depth - 1), gen_expr(g, depth - 1)) +} + +// ------------------------------------------------------------- comparison + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Class { + /// Two routes put different values on a path, or disagree about whether a + /// path carries one. Settled semantics: one of them is wrong. + Values, + /// Two routes agree on every value and differ only in dangling paths -- + /// structure with nothing under it. Unsettled semantics (see + /// `../SPEC_WARTS.md`), so this is reported apart from `Values` rather than + /// mixed in with it. + Shape, + /// An identity that must hold whatever the operands are does not. + Law, +} + +impl Class { + pub fn tag(self) -> &'static str { + match self { + Class::Values => "values", + Class::Shape => "shape", + Class::Law => "law", + } + } +} + +pub struct Divergence { + pub class: Class, + /// Stable short key for grouping findings across runs: the class and the + /// route, and nothing else. + /// + /// Coarse on purpose. An earlier version appended the operators the + /// expression used, which looked more informative and was much worse: one + /// root cause in `meet` produced dozens of signatures because it surfaced + /// under every combination of operators that happened to contain a meet, + /// and a known-findings table over them was unmaintainable. The operators, + /// the operands and the diff all live in `detail`; the signature's only job + /// is to collapse a million inputs onto a handful of lines. + pub signature: String, + pub detail: String, +} + +/// Evaluate every applicable route and every law, and return what disagrees. +/// +/// The baseline every route is compared against is `Pointwise(0)` -- the whole +/// expression through `PathMap::join`/`meet`/`subtract`/`restrict`. Those are +/// the oldest and most heavily used entry points in the crate, which makes them +/// the right thing to hold still, though the choice only affects which side of +/// a disagreement gets named, not whether it is found. +pub fn check(case: &Case) -> Vec { + let mut out = Vec::new(); + + let baseline_route = Route::Pointwise(0); + let baseline = routes::eval(baseline_route, &case.expr, &case.operands) + .expect("the pointwise route applies to every expression"); + let base_name = baseline_route.name(&case.expr); + + for route in Route::all() { + if route == baseline_route { + continue; + } + let Some(got) = routes::eval(route, &case.expr, &case.operands) else { continue }; + let name = route.name(&case.expr); + + if got.values != baseline.values { + out.push(Divergence { + class: Class::Values, + signature: format!("values:{}", route_key(route)), + detail: format!( + "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}", + base_name, + case.expr, + shape::first_values_diff(&baseline.values, &got.values).unwrap_or_default(), + shape::show_values(&baseline.values), + shape::show_values(&got.values), + ), + }); + // One class per route is enough; a value divergence will usually + // show up as a shape divergence too, and reporting both would + // double every finding. + continue; + } + + if let (Some(bs), Some(gs)) = (&baseline.shape, &got.shape) { + if bs != gs { + out.push(Divergence { + class: Class::Shape, + signature: format!("shape:{}", route_key(route)), + detail: format!( + "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}", + base_name, + case.expr, + shape::first_shape_diff(bs, gs).unwrap_or_default(), + show_shape(bs), + show_shape(gs), + ), + }); + } + } + } + + out.extend(check_laws(case)); + out +} + +/// Evaluate each law's two sides and report the ones that disagree. +/// +/// Laws run through the baseline route only. A law that fails under one route +/// and holds under another is already a route disagreement, which the loop +/// above reports; running every law through every route would multiply the cost +/// of a case by the number of laws for no new coverage. +pub fn check_laws(case: &Case) -> Vec { + // Operands 0..3 from the case, then the empty trie, which is what lets a + // law state a unit or annihilator. + let mut ops: Vec> = (0..EMPTY).map(|i| case.operands[i].clone()).collect(); + ops.push(PathMap::new()); + debug_assert_eq!(ops.len(), LAW_OPERANDS); + + let mut out = Vec::new(); + for law in laws::laws() { + let l = routes::eval(Route::Pointwise(0), &law.lhs, &ops).unwrap(); + let r = routes::eval(Route::Pointwise(0), &law.rhs, &ops).unwrap(); + let (ok, detail) = match law.level { + Level::Values => ( + l.values == r.values, + format!( + "{}\n lhs {}: {}\n rhs {}: {}", + shape::first_values_diff(&l.values, &r.values).unwrap_or_default(), + law.lhs, + shape::show_values(&l.values), + law.rhs, + shape::show_values(&r.values), + ), + ), + Level::Paths => { + // Compare the value-carrying paths only. Comparing every path + // in the shape would drag the dangling-path question into laws + // that are not about it. + let lk: Vec<&Vec> = l.values.keys().collect(); + let rk: Vec<&Vec> = r.values.keys().collect(); + ( + lk == rk, + format!( + "lhs {}: {}\n rhs {}: {}", + law.lhs, + shape::show_values(&l.values), + law.rhs, + shape::show_values(&r.values), + ), + ) + } + }; + if !ok { + out.push(Divergence { + class: Class::Law, + signature: format!("law:{}", law.name), + detail: format!("{} ({:?}): {detail}", law.name, law.level), + }); + } + } + out +} + +fn route_key(r: Route) -> String { + match r { + Route::Pointwise(k) => format!("pw{k}"), + _ => r.name(&Expr::Var(0)), + } +} + +// ---------------------------------------------------------------- known findings + +/// A finding that already reproduces on `master` and has a reproducer of its +/// own, so a run that only hits these is not a regression. +pub struct Known { + pub signature: &'static str, + /// Which defect it traces to. Several signatures share one entry: a single + /// wrong value inside `join` surfaces on every route that reaches a join + /// and in every law that mentions one, so the table maps many signatures + /// onto few causes. + pub cause: &'static str, +} + +/// Findings confirmed on `master`, with the defect each traces to. +/// `bin/alg_bug_repros.rs` reproduces every cause in a dozen lines, without the +/// fuzzer; run it to see which still stand. +/// +/// This table decides the **exit status** and nothing else. Counts are always +/// printed, known and unknown alike, so a known defect that starts firing ten +/// times more often is still visible even though it does not turn the run red. +/// `--strict` ignores the table entirely. +/// +/// # The causes +/// +/// 1. **Value bias by node layout** (`bias`). `pjoin` on `u64` is +/// `left_biased_pjoin` and `pmeet` is `Identity(SELF_IDENT)`, so where both +/// operands carry a value the *left* one must win. `PathMap::join` and +/// `PathMap::meet` take the right one when the two operands' nodes are laid +/// out differently -- in the reproducer, because one side has a chain of +/// dangling descendants below the shared path. Every zipper route gets this +/// right, so it shows up as *laws* failing and as the `model` route +/// disagreeing, not as one route out of step with the others: the defect is +/// in the baseline the others are compared against. +/// +/// 2. **`join` loses a value across shared structure** (`loss`). With `b` a +/// clone of `a` plus one extra value, `a | b` drops that value and `b | a` +/// keeps it. A join is a least upper bound, so no ordering may lose a path; +/// this is the one finding that needs no argument about value bias. It +/// needs the operands to *share nodes* -- rebuilding `b`'s entries into a +/// fresh map makes it go away -- which is why the generator clones and +/// merkleizes operands instead of only writing them fresh. +/// +/// 3. **Root values lost by the write-zipper forms** (`root`). `join_into` +/// into an empty destination drops the source's root value, and `meet_2` +/// drops root values outright. These are routes disagreeing with the +/// baseline in the ordinary way. +/// +/// 4. **Dangling paths** (`dangling`). Routes that graft whole subtries keep +/// structure that routes walking path by path do not. Unsettled rather than +/// wrong -- see `../SPEC_WARTS.md` -- hence its own class, `shape`, which +/// does not fail a run unless `--shape` says so. +/// +/// 5. **`merkleize` panics on dangling-only structure** (`merkleize`). Not an +/// algebraic defect: it fires while the operands are still being written, +/// before any operation runs, which is what the `build` in its signature +/// means. +const BIAS: &str = "value bias by node layout (repro 3)"; +const LOSS: &str = "join loses a value across shared structure (repro 4)"; +const ROOT: &str = "write-zipper forms lose root values (repros 1, 2)"; +const DANGLING: &str = "dangling-path treatment differs by route"; +const MERKLEIZE: &str = "merkleize panics on dangling-only structure (repro 5)"; +/// Re-nesting a join moves which operand is on the left *and* which pair of +/// tries meets a shared node first, so both cause 1 and cause 2 reach these. +const BIAS_OR_LOSS: &str = "value bias or lost value (repros 3, 4)"; + +pub const KNOWN: &[Known] = &[ + // Routes disagreeing with the baseline: `join_into` and `meet_2` losing + // root values, plus the baseline's own bias showing up as the zipper routes + // "disagreeing" with it. + Known { signature: "values:pw1", cause: ROOT }, + Known { signature: "values:pw2", cause: ROOT }, + Known { signature: "values:pw3", cause: ROOT }, + Known { signature: "values:pw4", cause: BIAS }, + Known { signature: "values:pw5", cause: BIAS }, + Known { signature: "values:ternary", cause: BIAS }, + Known { signature: "values:nary", cause: BIAS }, + Known { signature: "values:nary_poly", cause: BIAS }, + Known { signature: "values:dnf", cause: BIAS }, + // The reference model has no trie and no bias, so it disagrees with the + // baseline exactly where the baseline is wrong. + Known { signature: "values:model", cause: BIAS }, + // Dangling structure. + Known { signature: "shape:pw1", cause: DANGLING }, + Known { signature: "shape:pw2", cause: DANGLING }, + Known { signature: "shape:pw3", cause: DANGLING }, + Known { signature: "shape:pw4", cause: DANGLING }, + Known { signature: "shape:pw5", cause: DANGLING }, + Known { signature: "shape:ternary", cause: DANGLING }, + Known { signature: "shape:nary", cause: DANGLING }, + Known { signature: "shape:nary_poly", cause: DANGLING }, + Known { signature: "shape:dnf", cause: DANGLING }, + // Laws. Every value-level lattice law that puts the operands on different + // sides of a join or meet is sensitive to cause 1. + Known { signature: "law:join-associative", cause: BIAS_OR_LOSS }, + Known { signature: "law:meet-associative", cause: BIAS }, + Known { signature: "law:join-distributes-over-meet", cause: BIAS }, + Known { signature: "law:meet-distributes-over-join", cause: BIAS }, + Known { signature: "law:absorb-join-meet", cause: BIAS }, + Known { signature: "law:absorb-meet-join", cause: BIAS }, + Known { signature: "law:sym-diff-is-join-minus-meet", cause: BIAS }, + // Join associativity again, with meets for leaves. Reached by cause 2: + // `a & b` over an all-dangling `b` is a dangling-only trie, and joining + // that with a trie carrying values below the same paths loses them -- the + // same shape as repro 4. + Known { signature: "law:majority-is-pairwise-meets", cause: BIAS_OR_LOSS }, + // Commutativity is checked on paths only, so a bias cannot break it -- only + // a lost path can. This is cause 2, and the only law that detects it. + Known { signature: "law:join-commutative", cause: LOSS }, + Known { signature: "panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, + // Debug-assertions builds only, and the sharpest view of cause 2 there is: + // joining a list node into a dense node reports `AlgebraicStatus::None` + // -- an empty result -- from two nodes that are not empty, which is the + // mechanism by which `a | b` loses a value in repro 4. + Known { signature: "panic:eval:line_list_node.rs:2669", cause: LOSS }, + // The same defect at a different node type: joining two dense nodes, a + // cofree `pjoin` returns `None` while the left side still has a non-empty + // onward node, so the join discards that subtrie. Where the subtrie holds + // values this is repro 4; where it holds only dangling paths the loss is + // invisible to a release build, which is why debug assertions are a mode of + // their own. + Known { signature: "panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + // `merge_from_list_node` returning `None` again, from `join_into_dyn` this + // time. Three assertion sites, one story: join's "the result is empty" + // path is reachable from nodes that are not empty. + Known { signature: "panic:eval:line_list_node.rs:2720", cause: LOSS }, +]; + +pub fn known(signature: &str) -> Option<&'static Known> { + KNOWN.iter().find(|k| k.signature == signature) +} + +// ------------------------------------------------------------------ running + +/// Which half of a case was running when it panicked. +/// +/// Worth separating, because the two mean different things. `Build` is a panic +/// while *writing the operand tries* -- plain `set_val`, `create_path`, +/// `remove_branches`, `merkleize` on a write zipper, before any algebra has +/// run. That is a crash in the write path and belongs to the crash fuzzer; +/// this fuzzer just happens to reach it. `Eval` is a panic inside an algebraic +/// operation, which is this fuzzer's own business. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Phase { + Build, + Eval, +} + +impl Phase { + pub fn tag(self) -> &'static str { + match self { + Phase::Build => "build", + Phase::Eval => "eval", + } + } +} + +/// What one input produced. A panic is kept distinct from a divergence: it +/// means a route never got as far as producing an answer, so there is nothing +/// to compare and the finding is the crash itself. +pub enum Outcome { + Clean, + Diverged(Vec), + Panicked(Phase, String, String), +} + +std::thread_local! { + /// Where the last panic came from. The payload of an `unwrap` on `None` + /// carries no location, and the location is the whole value of a crash + /// signature -- without it every distinct panic site collapses onto one + /// line called "panic". A hook is the only way to see it. + static PANIC_SITE: core::cell::RefCell = + const { core::cell::RefCell::new(String::new()) }; +} + +/// Replace the panic hook with one that records the panic site and prints +/// nothing. +/// +/// Both halves matter for a long run: the default hook would print a backtrace +/// notice per panicking case and drown the output, and `catch_unwind` alone +/// cannot see where the panic came from. +pub fn install_panic_hook() { + std::panic::set_hook(Box::new(|info| { + let site = info + .location() + .map(|l| { + // Just the file name and line: the absolute path would make + // signatures depend on where the checkout lives. + let f = l.file(); + let f = f.rsplit('/').next().unwrap_or(f); + format!("{f}:{}", l.line()) + }) + .unwrap_or_else(|| "?".to_string()); + PANIC_SITE.with(|s| *s.borrow_mut() = site); + })); +} + +fn panic_msg(e: Box) -> (String, String) { + let msg = e + .downcast_ref::() + .cloned() + .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())) + .unwrap_or_else(|| "".to_string()); + let site = PANIC_SITE.with(|s| s.borrow().clone()); + (site, msg) +} + +/// Decode an input, run every route and every law over it, and say what +/// disagreed. +/// +/// Two `catch_unwind`s rather than one, so a crash can say which phase it was +/// in. The case has to outlive the first, hence the separation. +pub fn run(bytes: &[u8]) -> Outcome { + let case = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode(bytes))) { + Err(e) => { + let (site, msg) = panic_msg(e); + return Outcome::Panicked(Phase::Build, site, msg); + } + Ok(c) => c, + }; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(&case))) { + Err(e) => { + let (site, msg) = panic_msg(e); + Outcome::Panicked(Phase::Eval, site, msg) + } + Ok(divs) if divs.is_empty() => Outcome::Clean, + Ok(divs) => Outcome::Diverged(divs), + } +} + +/// Signatures an input produces: the grouping keys, without the detail. Also +/// the invariant the shrinker preserves. +pub fn signatures(bytes: &[u8]) -> Vec { + match run(bytes) { + Outcome::Clean => Vec::new(), + Outcome::Diverged(d) => d.into_iter().map(|d| d.signature).collect(), + Outcome::Panicked(p, site, _) => vec![panic_signature(p, &site)], + } +} + +pub fn panic_signature(phase: Phase, site: &str) -> String { + format!("panic:{}:{site}", phase.tag()) +} + +/// Reproducible input generation, so a seed names a run. +/// +/// xorshift64*, rather than `rand`: this crate depends on nothing but `pathmap` +/// and is worth keeping that way. +pub struct Rng(pub u64); + +impl Rng { + /// Derive a stream for job `job` of a run seeded with `seed`. The odd + /// multiplier keeps jobs from sharing a stream. + pub fn for_job(seed: u64, job: usize) -> Rng { + Rng((seed + .wrapping_mul(0x9E37_79B9_7F4A_7C15) + .wrapping_add(job as u64 * 0x1234_5679)) + | 1) + } + + pub fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + /// An input long enough that the decoder rarely runs out mid-case -- which + /// would saturate the rest to zeros and waste the draw -- and short enough + /// to shrink quickly. + pub fn input(&mut self) -> Vec { + let n = 48 + (self.next() % 96) as usize; + (0..n).map(|_| (self.next() >> 24) as u8).collect() + } +} + +/// Human-readable rendering of a case, for a failure report and for replay. +pub fn describe(case: &Case) -> String { + let mut s = String::new(); + s.push_str(&format!("expr: {}\n", case.expr)); + s.push_str(&format!("alphabet: {}\n", case.alphabet)); + for (i, (m, b)) in case.operands.iter().zip(&case.builds).enumerate() { + let sh: Shape = shape_of_map(m); + s.push_str(&format!( + "operand {}: {:?}\n {}\n", + (b'a' + i as u8) as char, + b, + show_shape(&sh) + )); + } + s +} + +/// Values of each operand, for a report that only needs the settled part. +pub fn operand_values(case: &Case) -> Vec { + case.operands + .iter() + .map(|m| shape::values_of_shape(&shape_of_map(m))) + .collect() +} diff --git a/differential/src/algebraic/expr.rs b/differential/src/algebraic/expr.rs new file mode 100644 index 00000000..7fa2d9ac --- /dev/null +++ b/differential/src/algebraic/expr.rs @@ -0,0 +1,218 @@ +//! The expression language the fuzzer evaluates. +//! +//! An expression is a tree over a handful of generated operand tries. It is +//! deliberately small: the point is not to cover a rich language but to give +//! each expression as many *distinct implementation routes* as possible, and a +//! route only exists where the crate offers one. So the operator set is +//! exactly the crate's algebra -- join, meet, subtract, symmetric difference, +//! restrict -- and the interesting structure is the shape of the tree, because +//! that is what decides which routes apply: +//! +//! * any tree at all can be walked bottom-up with two-operand calls, so the +//! pairwise routes always apply; +//! * a chain of three of the same associative operator unlocks the `*3` forms; +//! * a chain of `n` unlocks the n-ary forms; +//! * a join of meets of operands is a DNF, which unlocks +//! [`zipper_merge_dnf`](pathmap::experimental::zipper_algebra::zipper_merge_dnf). +//! +//! [`Expr::dnf`] and [`Expr::chain`] are the recognisers for the last three. + +use core::fmt; + +/// Maximum operand tries in a case. Bounded because the n-ary and DNF routes +/// are const-generic over it and have to be dispatched by a `match` over +/// monomorphisations; see `routes::nary`. +pub const MAX_VARS: usize = 4; + +/// Maximum DNF clauses dispatched to `zipper_merge_dnf`. +pub const MAX_CLAUSES: usize = 4; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Op { + Join, + Meet, + Subtract, + SymDiff, + Restrict, +} + +impl Op { + pub const ALL: [Op; 5] = [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff, Op::Restrict]; + + pub fn sym(self) -> &'static str { + match self { + Op::Join => "|", + Op::Meet => "&", + Op::Subtract => "-", + Op::SymDiff => "^", + Op::Restrict => "/", + } + } + + /// Whether `(a op b) op c == a op (b op c)` holds, which is what makes a + /// chain of this operator collapsible to one n-ary call. + /// + /// Subtract is listed as associative in the sense the n-ary routes mean it: + /// `zipper_n_subtract` is documented as *left*-associative, so it matches a + /// left-nested chain only. [`Expr::chain`] enforces that nesting. + pub fn chainable(self) -> bool { + matches!(self, Op::Join | Op::Meet | Op::SymDiff | Op::Subtract) + } + + /// Whether a chain of this operator may nest to the right as well as the + /// left, and still mean what the n-ary call computes. + /// + /// Join and meet may: `pjoin` and `pmeet` on `u64` are left-biased, so both + /// nestings select the leftmost present operand's value and agree with the + /// left fold the n-ary routes perform. + /// + /// Subtract and symmetric difference may not. Subtract obviously -- `a - + /// (b - c)` is a different function. Symmetric difference less obviously: + /// the n-ary form folds values left, so for root values `a = 2`, `b = 1`, + /// `a ^ (a ^ b)` is `a ^ nothing = 2` while the fold is `(2 ^ 2) ^ 1 = 1`. + /// Both are defensible; they are not equal, so a right-nested symmetric + /// difference is not a chain. `laws.rs` states the associativity that does + /// hold, which is on paths. + pub fn right_nestable(self) -> bool { + matches!(self, Op::Join | Op::Meet) + } +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum Expr { + Var(usize), + Bin(Op, Box, Box), +} + +impl Expr { + pub fn bin(op: Op, l: Expr, r: Expr) -> Expr { + Expr::Bin(op, Box::new(l), Box::new(r)) + } + + pub fn nodes(&self) -> usize { + match self { + Expr::Var(_) => 1, + Expr::Bin(_, l, r) => 1 + l.nodes() + r.nodes(), + } + } + + /// Operand indices the expression mentions, ascending. + pub fn vars(&self) -> Vec { + let mut v = Vec::new(); + self.collect_vars(&mut v); + v.sort(); + v.dedup(); + v + } + + fn collect_vars(&self, out: &mut Vec) { + match self { + Expr::Var(i) => out.push(*i), + Expr::Bin(_, l, r) => { + l.collect_vars(out); + r.collect_vars(out); + } + } + } + + /// If the whole expression is a chain of one chainable operator over bare + /// operands, return that operator and the operands in evaluation order. + /// + /// Only bare operands qualify, not arbitrary subexpressions: the n-ary + /// routes take read zippers, and a subexpression would have to be + /// materialised into a temporary trie first, at which point the route is no + /// longer testing the n-ary call against the same inputs the pairwise route + /// saw. Keeping it to operands keeps the comparison exact. + pub fn chain(&self) -> Option<(Op, Vec)> { + let Expr::Bin(op, _, _) = self else { return None }; + if !op.chainable() { + return None; + } + let mut operands = Vec::new(); + self.collect_chain(*op, &mut operands).then_some((*op, operands)) + } + + fn collect_chain(&self, op: Op, out: &mut Vec) -> bool { + match self { + Expr::Var(i) => { + out.push(*i); + true + } + Expr::Bin(o, l, r) if *o == op => { + // The left spine may always recurse. The right spine may only + // recurse for operators that nest both ways, so `a - (b - c)` + // is not mistaken for the chain `a - b - c`. + if !l.collect_chain(op, out) { + return false; + } + match &**r { + Expr::Var(i) => { + out.push(*i); + true + } + Expr::Bin(..) => op.right_nestable() && r.collect_chain(op, out), + } + } + Expr::Bin(..) => false, + } + } + + /// If the expression is a join of meets of operands, return one bitmask of + /// operand indices per clause. + /// + /// This is the form `zipper_merge_dnf` evaluates directly. A clause is a + /// *set*, so `a & a` collapses to `a`; that is sound because meet is + /// idempotent, which is itself one of the laws checked in `laws.rs`. + pub fn dnf(&self) -> Option> { + match self { + Expr::Bin(Op::Join, l, r) => { + let mut cs = l.dnf()?; + cs.extend(r.dnf()?); + Some(cs) + } + _ => Some(vec![self.meet_mask()?]), + } + } + + /// If the expression is a meet of operands, return their index bitmask. + /// + /// Rejects a meet whose operands are not in ascending index order, even + /// though the bitmask would be the same. A [`Clause`] is a *set*: it + /// records which zippers take part, not in what order, and + /// `zipper_merge_dnf` meets a clause's members in slot order, which is + /// ascending operand index. Because `pmeet` on `u64` is left-biased, `b & + /// a` and `a & b` carry different values, so only one of them is what the + /// clause actually computes. Returning a mask for the other would make the + /// DNF route report a divergence that is the route's own fault. + /// + /// [`Clause`]: pathmap::experimental::zipper_algebra::Clause + fn meet_mask(&self) -> Option { + let mut vs = Vec::new(); + self.meet_vars(&mut vs).then_some(())?; + if vs.windows(2).any(|w| w[0] > w[1]) { + return None; + } + Some(vs.iter().fold(0u64, |m, i| m | 1u64 << i)) + } + + /// Operands of a meet-only subexpression, left to right. + fn meet_vars(&self, out: &mut Vec) -> bool { + match self { + Expr::Var(i) => { + out.push(*i); + true + } + Expr::Bin(Op::Meet, l, r) => l.meet_vars(out) && r.meet_vars(out), + _ => false, + } + } +} + +impl fmt::Display for Expr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Expr::Var(i) => write!(f, "{}", (b'a' + *i as u8) as char), + Expr::Bin(op, l, r) => write!(f, "({l} {} {r})", op.sym()), + } + } +} diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs new file mode 100644 index 00000000..0bfa660f --- /dev/null +++ b/differential/src/algebraic/laws.rs @@ -0,0 +1,182 @@ +//! Identities that must hold whatever the operands are. +//! +//! The route comparison in `routes.rs` catches an implementation that disagrees +//! with its siblings. It cannot catch a mistake they all share. Laws are the +//! other half: each one is two *different expressions* that must evaluate to +//! the same trie, so a wrong answer is visible even when every route computes +//! it the same wrong way. +//! +//! A law is written as a pair of [`Expr`]s and evaluated by the ordinary route +//! machinery, which keeps this file declarative and means a law automatically +//! inherits whatever the expression evaluator can do. +//! +//! # Why some laws are checked on paths only +//! +//! `u64`'s lattice instances are left-biased: `pjoin` keeps the left value when +//! the two differ, and `pmeet` keeps the left value *unconditionally*. Several +//! textbook identities therefore hold as statements about which paths survive +//! but not about which value lands on them, and asserting values there would +//! report a divergence that is correct behaviour. Each such law says so. +//! +//! # Identities deliberately absent +//! +//! Three plausible-looking ones are not laws under these value semantics, and +//! are listed here so nobody adds them back as "obviously true": +//! +//! * `a - (b | c) == (a - b) & (a - c)`. `b | c` carries `b`'s value where +//! both are present, so the left side keeps a path whose value matches `c` +//! but not `b`, while the right side drops it. +//! * `a - b == a - (a & b)`. `a & b` carries *`a`'s* value, so the right side +//! drops every shared path regardless of value, while the left side drops +//! only the ones whose values are equal. +//! * `(a ^ b) ^ c == a ^ (b ^ c)` on values. A path present in all three +//! cancels in the inner operation either way, so the left side ends up with +//! `c`'s value and the right side with `a`'s. Associative on paths, which is +//! what is checked. + +use super::expr::{Expr, Op}; + +/// Operand slot holding the empty trie, appended after the case's own +/// operands so identities can mention it. See [`LAW_OPERANDS`]. +pub const EMPTY: usize = 3; + +/// Operands a law may mention: three from the case, then the empty trie. +pub const LAW_OPERANDS: usize = 4; + +/// How much of the result a law constrains. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Level { + /// Which path carries which value. + Values, + /// Which paths survive, values unconstrained. + Paths, +} + +pub struct Law { + pub name: &'static str, + pub lhs: Expr, + pub rhs: Expr, + pub level: Level, +} + +fn v(i: usize) -> Expr { + Expr::Var(i) +} +fn j(a: Expr, b: Expr) -> Expr { + Expr::bin(Op::Join, a, b) +} +fn m(a: Expr, b: Expr) -> Expr { + Expr::bin(Op::Meet, a, b) +} +fn s(a: Expr, b: Expr) -> Expr { + Expr::bin(Op::Subtract, a, b) +} +fn x(a: Expr, b: Expr) -> Expr { + Expr::bin(Op::SymDiff, a, b) +} +fn r(a: Expr, b: Expr) -> Expr { + Expr::bin(Op::Restrict, a, b) +} + +pub fn laws() -> Vec { + use Level::{Paths, Values}; + let (a, b, c, e) = (0usize, 1usize, 2usize, EMPTY); + vec![ + // --- lattice basics + Law { name: "join-idempotent", lhs: j(v(a), v(a)), rhs: v(a), level: Values }, + Law { name: "meet-idempotent", lhs: m(v(a), v(a)), rhs: v(a), level: Values }, + Law { name: "join-unit", lhs: j(v(a), v(e)), rhs: v(a), level: Values }, + Law { name: "meet-zero", lhs: m(v(a), v(e)), rhs: v(e), level: Values }, + // Commutative in path set only: the left value wins in both `pjoin` and + // `pmeet`, so swapping the operands swaps which value lands. + Law { name: "join-commutative", lhs: j(v(a), v(b)), rhs: j(v(b), v(a)), level: Paths }, + Law { name: "meet-commutative", lhs: m(v(a), v(b)), rhs: m(v(b), v(a)), level: Paths }, + // Associativity *does* hold on values: left bias makes both nestings + // select the leftmost present operand's value. + Law { + name: "join-associative", + lhs: j(j(v(a), v(b)), v(c)), + rhs: j(v(a), j(v(b), v(c))), + level: Values, + }, + Law { + name: "meet-associative", + lhs: m(m(v(a), v(b)), v(c)), + rhs: m(v(a), m(v(b), v(c))), + level: Values, + }, + Law { name: "absorb-meet-join", lhs: m(v(a), j(v(a), v(b))), rhs: v(a), level: Values }, + Law { name: "absorb-join-meet", lhs: j(v(a), m(v(a), v(b))), rhs: v(a), level: Values }, + Law { + name: "meet-distributes-over-join", + lhs: m(v(a), j(v(b), v(c))), + rhs: j(m(v(a), v(b)), m(v(a), v(c))), + level: Values, + }, + Law { + name: "join-distributes-over-meet", + lhs: j(v(a), m(v(b), v(c))), + rhs: m(j(v(a), v(b)), j(v(a), v(c))), + level: Values, + }, + // --- subtraction + Law { name: "subtract-self", lhs: s(v(a), v(a)), rhs: v(e), level: Values }, + Law { name: "subtract-unit", lhs: s(v(a), v(e)), rhs: v(a), level: Values }, + Law { name: "subtract-from-empty", lhs: s(v(e), v(a)), rhs: v(e), level: Values }, + // Each step drops the paths whose value the subtrahend matches, and + // "matches b or matches c" does not depend on the order. + Law { + name: "subtract-steps-commute", + lhs: s(s(v(a), v(b)), v(c)), + rhs: s(s(v(a), v(c)), v(b)), + level: Values, + }, + // Subtracting cannot add a path: re-joining the removed part recovers + // no more than the original. + Law { name: "subtract-shrinks", lhs: j(s(v(a), v(b)), v(a)), rhs: v(a), level: Values }, + // --- symmetric difference + Law { name: "sym-diff-self", lhs: x(v(a), v(a)), rhs: v(e), level: Values }, + Law { name: "sym-diff-unit", lhs: x(v(a), v(e)), rhs: v(a), level: Values }, + // Fully commutative, values included: a coincident path cancels on both + // sides, so each surviving value comes from the single side that has it. + Law { name: "sym-diff-commutative", lhs: x(v(a), v(b)), rhs: x(v(b), v(a)), level: Values }, + Law { + name: "sym-diff-associative-paths", + lhs: x(x(v(a), v(b)), v(c)), + rhs: x(v(a), x(v(b), v(c))), + level: Paths, + }, + // The definition `zipper_sym_diff`'s own documentation gives. + Law { + name: "sym-diff-is-join-minus-meet", + lhs: x(v(a), v(b)), + rhs: s(j(v(a), v(b)), m(v(a), v(b))), + level: Values, + }, + // --- restrict + // Every path is a prefix of itself, so restricting by its own operand + // admits everything. + Law { name: "restrict-self", lhs: r(v(a), v(a)), rhs: v(a), level: Values }, + Law { name: "restrict-empty", lhs: r(v(a), v(e)), rhs: v(e), level: Values }, + Law { name: "restrict-of-empty", lhs: r(v(e), v(a)), rhs: v(e), level: Values }, + Law { name: "restrict-idempotent", lhs: r(r(v(a), v(b)), v(b)), rhs: r(v(a), v(b)), level: Values }, + // A path present in both operands is admitted by itself, so the meet is + // contained in the restriction. + Law { + name: "meet-under-restrict", + lhs: m(m(v(a), v(b)), r(v(a), v(b))), + rhs: m(v(a), v(b)), + level: Values, + }, + // --- majority, the worked example in `zipper_majority`'s docs, written + // out as the DNF it claims to equal. Exercised here so the DNF engine + // is checked against a hand-written join of meets as well as against + // the pointwise routes. + Law { + name: "majority-is-pairwise-meets", + lhs: j(j(m(v(a), v(b)), m(v(a), v(c))), m(v(b), v(c))), + rhs: j(m(v(a), v(b)), j(m(v(a), v(c)), m(v(b), v(c)))), + level: Values, + }, + ] +} diff --git a/differential/src/algebraic/model.rs b/differential/src/algebraic/model.rs new file mode 100644 index 00000000..35972224 --- /dev/null +++ b/differential/src/algebraic/model.rs @@ -0,0 +1,106 @@ +//! Value-level reference semantics, as a fourth opinion. +//! +//! The routes in `routes.rs` all go through `pathmap`, so a defect common to +//! the whole algebra layer would make them agree with each other and still be +//! wrong. This module computes the same expression over a plain +//! `BTreeMap, u64>` with no trie involved, which gives the comparison +//! something to anchor against. +//! +//! It deliberately models only *which path carries which value* and abstains +//! on structure: a flat map cannot represent a dangling path, and whether a +//! dangling path survives an operation is unsettled in the crate (see +//! `../../SPEC_WARTS.md`). `shape.rs` explains the split. +//! +//! The semantics below are the ones `u64`'s lattice instances in +//! `pathmap::ring` actually define, not the ones set notation would suggest: +//! +//! * `pjoin` is left-biased, so a join keeps the left value where both sides +//! have one. Join is therefore **not** commutative in its values, only in +//! its path set. +//! * `pmeet` returns `Identity(SELF_IDENT)` unconditionally, so a meet also +//! keeps the left value -- even where the two values differ. +//! * `psubtract` is `None` when the values are equal and the left value +//! otherwise, so subtracting a path whose value differs is a no-op. +//! * symmetric difference cancels *any* pair of values at a coincident path. +//! That follows from the two above rather than from parity of presence: with +//! `pjoin` and `pmeet` both `Identity`, `SymDiff::combine_impl` reaches +//! `join == meet` for distinct values and `subtract_impl(a, b)` with `a == +//! b` for equal ones, and both yield nothing. + +use super::expr::{Expr, Op}; +use super::shape::Values; + +pub fn eval(e: &Expr, operands: &[Values]) -> Values { + match e { + Expr::Var(i) => operands[*i].clone(), + Expr::Bin(op, l, r) => { + let a = eval(l, operands); + let b = eval(r, operands); + apply(*op, &a, &b) + } + } +} + +pub fn apply(op: Op, a: &Values, b: &Values) -> Values { + match op { + Op::Join => join(a, b), + Op::Meet => meet(a, b), + Op::Subtract => subtract(a, b), + Op::SymDiff => sym_diff(a, b), + Op::Restrict => restrict(a, b), + } +} + +/// Union of paths; the left value wins where both sides have one. +pub fn join(a: &Values, b: &Values) -> Values { + let mut out = b.clone(); + for (k, v) in a { + out.insert(k.clone(), *v); + } + out +} + +/// Paths present in both; the left value, even when the two differ. +pub fn meet(a: &Values, b: &Values) -> Values { + a.iter() + .filter(|(k, _)| b.contains_key(*k)) + .map(|(k, v)| (k.clone(), *v)) + .collect() +} + +/// Left paths, dropping only those the right side carries the *same* value at. +pub fn subtract(a: &Values, b: &Values) -> Values { + a.iter() + .filter(|(k, v)| b.get(*k) != Some(*v)) + .map(|(k, v)| (k.clone(), *v)) + .collect() +} + +/// Paths present in exactly one side. Coincident paths cancel whatever their +/// values; see the module comment. +pub fn sym_diff(a: &Values, b: &Values) -> Values { + let mut out = Values::new(); + for (k, v) in a { + if !b.contains_key(k) { + out.insert(k.clone(), *v); + } + } + for (k, v) in b { + if !a.contains_key(k) { + out.insert(k.clone(), *v); + } + } + out +} + +/// Left paths that some path-to-a-value in the right side is a prefix of. +/// +/// The prefix is inclusive at both ends: the empty path counts, so a root value +/// in `b` admits all of `a`, and `k` counts as a prefix of itself. Both follow +/// from the note on `PathMap::restrict`. +pub fn restrict(a: &Values, b: &Values) -> Values { + a.iter() + .filter(|(k, _)| (0..=k.len()).any(|n| b.contains_key(&k[..n]))) + .map(|(k, v)| (k.clone(), *v)) + .collect() +} diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs new file mode 100644 index 00000000..7b45a894 --- /dev/null +++ b/differential/src/algebraic/routes.rs @@ -0,0 +1,486 @@ +//! The different ways to compute the same thing. +//! +//! `pathmap` offers each algebraic operation several times over: once eagerly +//! on whole maps, once in place through a write zipper, once as a lockstep +//! traversal of two read zippers, and -- for the associative ones -- again as +//! an n-ary traversal, a DNF evaluator, and a lazy zipper over a virtual trie. +//! Those are not alternative spellings of one implementation; they are separate +//! implementations with separate pruning, grafting and value-combining logic, +//! which is exactly why they are worth running against each other. +//! +//! A *route* is one consistent way to evaluate a whole expression. There are +//! two kinds: +//! +//! * **pointwise** routes walk the expression bottom-up and evaluate each node +//! with a two-operand call, materialising each intermediate into a trie. +//! Route `k` picks strategy `k % n` for an operator with `n` strategies, so +//! every strategy is covered by some route and the routes mix them. +//! * **whole-expression** routes recognise a shape -- a chain of one +//! associative operator, or a join of meets -- and hand the entire thing to +//! one call that does it in a single traversal. These are the routes with +//! real independence from the pointwise ones: no intermediate trie is ever +//! built, so they exercise code the pointwise routes never reach. +//! +//! Every route must produce the same trie. `shape.rs` says what "same" means +//! and why dangling-path divergence is reported separately. + +use pathmap::PathMap; +use pathmap::experimental::zipper_algebra::{ + Clause, zipper_join, zipper_join3, zipper_meet, zipper_meet3, zipper_merge_dnf, + zipper_n_join, zipper_n_meet, zipper_n_subtract, zipper_n_sym_diff, zipper_subtract, + zipper_subtract3, zipper_sym_diff, zipper_sym_diff3, ZipperMergeF, +}; +use pathmap::zipper::{ + OverlayZipper, ReadZipperUntracked, ZipperMoving, ZipperPath, ZipperValues, ZipperWriting, +}; + +use super::expr::{Expr, Op}; +use super::model; +use super::shape::{shape_of_map, shape_of_zipper, values_of_shape, Shape, Values, ESCAPED_ROOT, TRUNCATED}; + +/// Names of the per-operator strategies, in the order route `k % n` indexes +/// them. Kept as tables so a route's name can say which strategy it used for +/// each operator the expression contains. +pub const JOIN_STRATEGIES: &[&str] = + &["map", "join_into", "join_map_into", "join_into_take", "zipper_join", "overlay"]; +pub const MEET_STRATEGIES: &[&str] = &["map", "meet_into", "meet_2", "zipper_meet"]; +pub const SUBTRACT_STRATEGIES: &[&str] = &["map", "subtract_into", "zipper_subtract"]; +pub const SYM_DIFF_STRATEGIES: &[&str] = &["zipper_sym_diff", "join_minus_meet"]; +pub const RESTRICT_STRATEGIES: &[&str] = &["map", "wz_restrict"]; + +pub fn strategies(op: Op) -> &'static [&'static str] { + match op { + Op::Join => JOIN_STRATEGIES, + Op::Meet => MEET_STRATEGIES, + Op::Subtract => SUBTRACT_STRATEGIES, + Op::SymDiff => SYM_DIFF_STRATEGIES, + Op::Restrict => RESTRICT_STRATEGIES, + } +} + +/// How many pointwise routes exist: enough that every strategy of every +/// operator is reached by at least one of them. +pub const POINTWISE_ROUTES: usize = 6; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Route { + /// Bottom-up two-operand evaluation, strategy `k % n` per operator. + Pointwise(usize), + /// `zipper_join3` / `zipper_meet3` / `zipper_subtract3` / `zipper_sym_diff3` + /// on a chain of exactly three operands. + Ternary, + /// `zipper_n_*` on a chain of operands, via the slice-of-zippers entry point. + Nary, + /// The same chain through the `ZipperMergeF` tuple entry point, which goes + /// via the `PolyZipper`-derived enum rather than a homogeneous array. + NaryPoly, + /// `zipper_merge_dnf` on a join of meets. + Dnf, + /// Flat `BTreeMap` semantics, no trie. Values only; abstains on structure. + Model, +} + +impl Route { + pub fn all() -> Vec { + let mut v: Vec = (0..POINTWISE_ROUTES).map(Route::Pointwise).collect(); + v.extend([Route::Ternary, Route::Nary, Route::NaryPoly, Route::Dnf, Route::Model]); + v + } + + /// Name including, for a pointwise route, the strategy it picked for each + /// operator the expression actually uses. A failure report needs this to + /// be actionable: "pw#3" alone does not name a function to go and read. + pub fn name(&self, e: &Expr) -> String { + match self { + Route::Pointwise(k) => { + let mut used: Vec = Vec::new(); + collect_ops(e, &mut used); + let picks: Vec = Op::ALL + .iter() + .filter(|op| used.contains(op)) + .map(|op| { + let t = strategies(*op); + format!("{}={}", op.sym(), t[k % t.len()]) + }) + .collect(); + format!("pw#{k}[{}]", picks.join(",")) + } + Route::Ternary => "ternary".into(), + Route::Nary => "nary".into(), + Route::NaryPoly => "nary_poly".into(), + Route::Dnf => "dnf".into(), + Route::Model => "model".into(), + } + } +} + +fn collect_ops(e: &Expr, out: &mut Vec) { + if let Expr::Bin(op, l, r) = e { + if !out.contains(op) { + out.push(*op); + } + collect_ops(l, out); + collect_ops(r, out); + } +} + +/// What a route produced. `shape` is `None` for a route that cannot represent +/// dangling paths, which is only [`Route::Model`]. +pub struct Outcome { + pub values: Values, + pub shape: Option, +} + +impl Outcome { + fn from_map(m: &PathMap) -> Outcome { + let shape = shape_of_map(m); + Outcome { values: values_of_shape(&shape), shape: Some(shape) } + } +} + +/// Evaluate `e` over `operands` by `route`, or `None` if the route does not +/// apply to this expression's shape. +pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Option { + match route { + Route::Pointwise(k) => Some(Outcome::from_map(&pointwise(k, e, operands))), + Route::Ternary => ternary(e, operands).map(|m| Outcome::from_map(&m)), + Route::Nary => nary(e, operands, false).map(|m| Outcome::from_map(&m)), + Route::NaryPoly => nary(e, operands, true).map(|m| Outcome::from_map(&m)), + Route::Dnf => dnf(e, operands).map(|m| Outcome::from_map(&m)), + Route::Model => { + let vals: Vec = + operands.iter().map(|m| values_of_shape(&shape_of_map(m))).collect(); + Some(Outcome { values: model::eval(e, &vals), shape: None }) + } + } +} + +// ---------------------------------------------------------------- pointwise + +fn pointwise(k: usize, e: &Expr, operands: &[PathMap]) -> PathMap { + match e { + Expr::Var(i) => operands[*i].clone(), + Expr::Bin(op, l, r) => { + let a = pointwise(k, l, operands); + let b = pointwise(k, r, operands); + apply(*op, k, &a, &b) + } + } +} + +/// One operator, one strategy. Every arm is a different code path in the +/// crate, not a different way of calling the same one. +pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap { + let n = strategies(op).len(); + match (op, k % n) { + // -- join + (Op::Join, 0) => a.join(b), + (Op::Join, 1) => { + let mut out = a.clone(); + { + let mut wz = out.write_zipper(); + wz.join_into(&b.read_zipper()); + } + out + } + (Op::Join, 2) => { + let mut out = a.clone(); + { + let mut wz = out.write_zipper(); + wz.join_map_into(b.clone()); + } + out + } + (Op::Join, 3) => { + // Consumes the source. `prune = false` keeps whatever dangling + // structure the operation leaves, so this route is comparable with + // the grafting ones rather than silently tidier than them. + let mut out = a.clone(); + let mut src = b.clone(); + { + let mut wz = out.write_zipper(); + let mut sz = src.write_zipper(); + wz.join_into_take(&mut sz, false); + } + out + } + (Op::Join, 4) => { + let mut out = PathMap::new(); + { + let mut lz = a.read_zipper(); + let mut rz = b.read_zipper(); + let mut wz = out.write_zipper(); + zipper_join(&mut lz, &mut rz, &mut wz); + } + out + } + (Op::Join, 5) => { + // `OverlayZipper`'s default mapping is `a.or(b)`, which is the same + // left bias `u64`'s `pjoin` has, so the virtual trie it walks + // should be exactly the join. It never builds a trie, so it has to + // be materialised to be composed into a larger expression; the walk + // records dangling paths too, so nothing is lost in the round trip. + let overlay = OverlayZipper::new(a.read_zipper(), b.read_zipper()); + materialize(overlay) + } + + // -- meet + (Op::Meet, 0) => a.meet(b), + (Op::Meet, 1) => { + let mut out = a.clone(); + { + let mut wz = out.write_zipper(); + wz.meet_into(&b.read_zipper(), false); + } + out + } + (Op::Meet, 2) => { + // Writes the intersection of two sources into a fresh destination, + // rather than intersecting a destination with one source. + let mut out = PathMap::new(); + { + let mut wz = out.write_zipper(); + wz.meet_2(&a.read_zipper(), &b.read_zipper()); + } + out + } + (Op::Meet, 3) => { + let mut out = PathMap::new(); + { + let mut lz = a.read_zipper(); + let mut rz = b.read_zipper(); + let mut wz = out.write_zipper(); + zipper_meet(&mut lz, &mut rz, &mut wz); + } + out + } + + // -- subtract + (Op::Subtract, 0) => a.subtract(b), + (Op::Subtract, 1) => { + let mut out = a.clone(); + { + let mut wz = out.write_zipper(); + wz.subtract_into(&b.read_zipper(), false); + } + out + } + (Op::Subtract, 2) => { + let mut out = PathMap::new(); + { + let mut lz = a.read_zipper(); + let mut rz = b.read_zipper(); + let mut wz = out.write_zipper(); + zipper_subtract(&mut lz, &mut rz, &mut wz); + } + out + } + + // -- symmetric difference + (Op::SymDiff, 0) => { + let mut out = PathMap::new(); + { + let mut lz = a.read_zipper(); + let mut rz = b.read_zipper(); + let mut wz = out.write_zipper(); + zipper_sym_diff(&mut lz, &mut rz, &mut wz); + } + out + } + (Op::SymDiff, 1) => { + // The definition `zipper_sym_diff`'s doc comment gives, built out + // of the other three operations. Where this disagrees with the + // specialised traversal, one of the two is wrong. + let j = a.join(b); + let m = a.meet(b); + j.subtract(&m) + } + + // -- restrict + (Op::Restrict, 0) => a.restrict(b), + (Op::Restrict, 1) => { + let mut out = a.clone(); + { + let mut wz = out.write_zipper(); + wz.restrict(&b.read_zipper()); + } + out + } + + _ => unreachable!("strategy index out of range for {op:?}"), + } +} + +/// Walk a zipper over a virtual trie and build the real trie it describes. +/// +/// `create_path` is what keeps this faithful: a path with no value still has to +/// appear in the output, or materialising would quietly erase exactly the +/// dangling structure the comparison is trying to detect. +fn materialize(mut z: Z) -> PathMap +where + Z: ZipperMoving + ZipperPath + ZipperValues, +{ + let shape = shape_of_zipper(&mut z); + let mut out = PathMap::new(); + { + let mut wz = out.write_zipper(); + for (p, v) in &shape { + if &p[..] == ESCAPED_ROOT || &p[..] == TRUNCATED { + continue; + } + wz.reset(); + wz.descend_to(p); + match v { + Some(v) => { + wz.set_val(*v); + } + None => { + wz.create_path(); + } + } + } + } + out +} + +// -------------------------------------------------------- whole-expression + +/// Chain of exactly three operands through the `*3` entry points. +fn ternary(e: &Expr, operands: &[PathMap]) -> Option> { + let (op, idx) = e.chain()?; + if idx.len() != 3 { + return None; + } + let (a, b, c) = (&operands[idx[0]], &operands[idx[1]], &operands[idx[2]]); + let mut out = PathMap::new(); + { + let mut za = a.read_zipper(); + let mut zb = b.read_zipper(); + let mut zc = c.read_zipper(); + let mut wz = out.write_zipper(); + match op { + Op::Join => zipper_join3(&mut za, &mut zb, &mut zc, &mut wz), + Op::Meet => zipper_meet3(&mut za, &mut zb, &mut zc, &mut wz), + Op::Subtract => zipper_subtract3(&mut za, &mut zb, &mut zc, &mut wz), + Op::SymDiff => zipper_sym_diff3(&mut za, &mut zb, &mut zc, &mut wz), + Op::Restrict => return None, + } + } + Some(out) +} + +/// A chain of any length through the n-ary entry points. +/// +/// Two of them: the slice form (`zipper_n_*`, const-generic over a homogeneous +/// array) and the tuple form (`ZipperMergeF::*_n`, which routes through the +/// `PolyZipper`-derived enum). They are separate monomorphisations of the +/// merge engine and are worth distinguishing, so `poly` selects between them. +fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> { + let (op, idx) = e.chain()?; + if op == Op::Restrict { + return None; + } + let mut out = PathMap::new(); + { + let mut wz = out.write_zipper(); + // Const-generic arity has to be dispatched by hand: there is one + // monomorphisation per operand count, and the count is only known at + // run time. The tuple form additionally has one impl per arity. + macro_rules! slice_arm { + ($n:literal) => {{ + let mut zs: [ReadZipperUntracked<'_, '_, u64>; $n] = + core::array::from_fn(|i| operands[idx[i]].read_zipper()); + match op { + Op::Join => zipper_n_join(&mut zs, &mut wz), + Op::Meet => zipper_n_meet(&mut zs, &mut wz), + Op::Subtract => zipper_n_subtract(&mut zs, &mut wz), + Op::SymDiff => zipper_n_sym_diff(&mut zs, &mut wz), + Op::Restrict => unreachable!(), + } + }}; + } + macro_rules! tuple_arm { + ($($i:literal),+) => {{ + let t = ( $( &mut operands[idx[$i]].read_zipper() ),+ ); + match op { + Op::Join => t.join_n(&mut wz), + Op::Meet => t.meet_n(&mut wz), + Op::Subtract => t.subtract_n(&mut wz), + Op::SymDiff => t.sym_diff_n(&mut wz), + Op::Restrict => unreachable!(), + } + }}; + } + match (poly, idx.len()) { + (false, 2) => slice_arm!(2), + (false, 3) => slice_arm!(3), + (false, 4) => slice_arm!(4), + (false, 5) => slice_arm!(5), + (false, 6) => slice_arm!(6), + (true, 2) => tuple_arm!(0, 1), + (true, 3) => tuple_arm!(0, 1, 2), + (true, 4) => tuple_arm!(0, 1, 2, 3), + // The tuple impls go higher, but there is nothing to learn from + // arities the slice form already covers at the same width. + _ => return None, + } + } + Some(out) +} + +/// A join of meets through `zipper_merge_dnf`. +/// +/// The operand indices are compacted first: the clause masks are indices into +/// the array handed to the call, so an expression over operands `a` and `c` +/// becomes a two-zipper call with the masks renumbered, not a four-zipper call +/// with two unused slots -- an unused slot would change what the traversal +/// prunes on and make the route test something else. +fn dnf(e: &Expr, operands: &[PathMap]) -> Option> { + let clauses = e.dnf()?; + let vars = e.vars(); + if vars.is_empty() || vars.len() > super::expr::MAX_VARS || clauses.len() > super::expr::MAX_CLAUSES { + return None; + } + // Remap each clause's bits from operand index to position in `vars`. + let packed: Vec = clauses + .iter() + .map(|m| { + vars.iter() + .enumerate() + .filter(|(_, v)| m >> **v & 1 == 1) + .fold(0u64, |acc, (i, _)| acc | 1 << i) + }) + .collect(); + + let mut out = PathMap::new(); + { + let mut wz = out.write_zipper(); + macro_rules! dnf_arm { + ($n:literal, $m:literal) => {{ + let mut zs: [ReadZipperUntracked<'_, '_, u64>; $n] = + core::array::from_fn(|i| operands[vars[i]].read_zipper()); + let cs: [Clause<$n>; $m] = core::array::from_fn(|i| Clause::from_mask(packed[i])); + zipper_merge_dnf(&mut zs, cs, &mut wz); + }}; + } + macro_rules! dnf_m { + ($n:literal) => { + match packed.len() { + 1 => dnf_arm!($n, 1), + 2 => dnf_arm!($n, 2), + 3 => dnf_arm!($n, 3), + 4 => dnf_arm!($n, 4), + _ => return None, + } + }; + } + match vars.len() { + 1 => dnf_m!(1), + 2 => dnf_m!(2), + 3 => dnf_m!(3), + 4 => dnf_m!(4), + _ => return None, + } + } + Some(out) +} diff --git a/differential/src/algebraic/shape.rs b/differential/src/algebraic/shape.rs new file mode 100644 index 00000000..1f7c5d69 --- /dev/null +++ b/differential/src/algebraic/shape.rs @@ -0,0 +1,164 @@ +//! What "the same result" means. +//! +//! Two routes through the same algebraic expression are compared on the trie +//! they produce, not on the calls they made. A trie is rendered two ways: +//! +//! * [`Shape`] — every path the trie contains, with the value at it if any. +//! Dangling paths (structure with no value under it) are included, so this +//! distinguishes tries that `iter()` cannot tell apart. +//! * [`Values`] — only the paths that carry values. +//! +//! The split matters because the two have different authority. Which paths +//! carry which values is settled: every route must agree, and a disagreement +//! is a bug in one of them. Whether a dangling path survives an operation is +//! *not* settled (see `../../SPEC_WARTS.md`), and routes legitimately built on +//! `graft` of whole subtries will keep dangling structure that routes built by +//! walking and inserting cannot. So a divergence confined to dangling paths +//! is reported as its own class rather than lumped in with a wrong value. +//! +//! Both renderings come off a zipper, not a `PathMap`, so a lazy zipper that +//! never materialises a trie — an `OverlayZipper`, say — is comparable against +//! an eagerly built map without special-casing. + +use pathmap::PathMap; +use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperValues}; +use std::collections::BTreeMap; + +/// Every path in a trie, in depth-first order, with the value at it if any. +pub type Shape = Vec<(Vec, Option)>; + +/// The paths of a trie that carry values. +pub type Values = BTreeMap, u64>; + +/// Cap on paths recorded per trie. A generated case that needs more than this +/// is not interesting enough to be worth the comparison cost; the cap is +/// recorded in the rendering so a truncated trie can never compare equal to a +/// complete one by accident. +pub const SHAPE_CAP: usize = 8192; + +/// Marker path emitted when a zipper walks out of its own root. No real path +/// can collide with it: generated paths use a small alphabet of low bytes. +pub const ESCAPED_ROOT: &[u8] = b""; +/// Marker path emitted when [`SHAPE_CAP`] is hit. +pub const TRUNCATED: &[u8] = b""; + +/// Depth-first walk of everything at and below the zipper's root. +/// +/// The root is recorded explicitly: `to_next_step` moves before it reports, so +/// a loop driven by it alone would miss the value at the empty path. +pub fn shape_of_zipper(z: &mut Z) -> Shape +where + Z: ZipperMoving + ZipperPath + ZipperValues, +{ + z.reset(); + let mut out: Shape = vec![(Vec::new(), z.val().copied())]; + loop { + if out.len() >= SHAPE_CAP { + out.push((TRUNCATED.to_vec(), None)); + break; + } + if !z.to_next_step() { + break; + } + // A depth-first step from the root can only go deeper or sideways, so + // returning to the empty path means the zipper left its own root -- + // `lean/FINDINGS.md` #3. Stop rather than loop forever, and say so. + if z.path().is_empty() { + out.push((ESCAPED_ROOT.to_vec(), None)); + break; + } + out.push((z.path().to_vec(), z.val().copied())); + } + out +} + +pub fn shape_of_map(m: &PathMap) -> Shape { + shape_of_zipper(&mut m.read_zipper()) +} + +/// The value-carrying subset of a [`Shape`]. +pub fn values_of_shape(s: &Shape) -> Values { + s.iter() + .filter_map(|(p, v)| v.map(|v| (p.clone(), v))) + .collect() +} + +/// The paths of a [`Shape`], values ignored. Used by the laws that hold only +/// up to path presence, because `u64`'s `pjoin` and `pmeet` are left-biased +/// and so neither is commutative in the value it picks. +pub fn paths_of_shape(s: &Shape) -> Vec> { + s.iter().map(|(p, _)| p.clone()).collect() +} + +/// Render a path the way the rest of the harness does, so traces interleave. +pub fn show_path(p: &[u8]) -> String { + if p == ESCAPED_ROOT || p == TRUNCATED { + String::from_utf8_lossy(p).into_owned() + } else if p.is_empty() { + "_".to_string() + } else { + p.iter().map(|b| format!("{b:02x}")).collect() + } +} + +pub fn show_shape(s: &Shape) -> String { + s.iter() + .map(|(p, v)| match v { + Some(v) => format!("{}:{v}", show_path(p)), + None => format!("{}:-", show_path(p)), + }) + .collect::>() + .join(",") +} + +pub fn show_values(v: &Values) -> String { + v.iter() + .map(|(p, v)| format!("{}:{v}", show_path(p))) + .collect::>() + .join(",") +} + +/// First point at which two shapes differ, for the failure report. +pub fn first_shape_diff(a: &Shape, b: &Shape) -> Option { + for i in 0..a.len().max(b.len()) { + match (a.get(i), b.get(i)) { + (Some(x), Some(y)) if x == y => continue, + (Some(x), Some(y)) => { + return Some(format!( + "at #{i}: {}:{} vs {}:{}", + show_path(&x.0), + x.1.map(|v| v.to_string()).unwrap_or("-".into()), + show_path(&y.0), + y.1.map(|v| v.to_string()).unwrap_or("-".into()), + )); + } + (Some(x), None) => { + return Some(format!("at #{i}: {} vs ", show_path(&x.0))); + } + (None, Some(y)) => { + return Some(format!("at #{i}: vs {}", show_path(&y.0))); + } + (None, None) => break, + } + } + None +} + +/// First point at which two value maps differ. +pub fn first_values_diff(a: &Values, b: &Values) -> Option { + let mut keys: Vec<&Vec> = a.keys().chain(b.keys()).collect(); + keys.sort(); + keys.dedup(); + for k in keys { + let (x, y) = (a.get(k), b.get(k)); + if x != y { + return Some(format!( + "at {}: {} vs {}", + show_path(k), + x.map(|v| v.to_string()).unwrap_or("-".into()), + y.map(|v| v.to_string()).unwrap_or("-".into()), + )); + } + } + None +} diff --git a/differential/src/bin/alg_bug_repros.rs b/differential/src/bin/alg_bug_repros.rs new file mode 100644 index 00000000..8c4f1638 --- /dev/null +++ b/differential/src/bin/alg_bug_repros.rs @@ -0,0 +1,184 @@ +//! Standalone reproducers for what `bin/alg_fuzz` found on `master`. +//! +//! Same role as `bin/zipper_bug_repros.rs`: each case is a dozen lines of +//! ordinary `pathmap` calls with no fuzzer, no harness and no decoder, so it +//! can be pasted into a test or stepped through in a debugger. The signatures +//! these correspond to are listed in `algebraic::KNOWN`. +//! +//! ```sh +//! cargo run --release -p differential --bin alg_bug_repros +//! ``` +//! +//! Exit status is 1 while any of them still reproduces. + +use pathmap::PathMap; +use pathmap::zipper::{ZipperMoving, ZipperValues, ZipperWriting}; + +/// A trie holding only dangling paths: structure written with `create_path` +/// and no value anywhere. +fn dangling(paths: &[&[u8]]) -> PathMap { + let mut m = PathMap::::new(); + let mut wz = m.write_zipper(); + for p in paths { + wz.reset(); + wz.descend_to(*p); + wz.create_path(); + } + drop(wz); + m +} + +fn with_val(path: &[u8], v: u64) -> PathMap { + let mut m = PathMap::::new(); + m.write_zipper_at_path(path).set_val(v); + m +} + +fn val_at(m: &PathMap, path: &[u8]) -> Option { + m.read_zipper_at_path(path).val().copied() +} + +struct Report { + failed: usize, +} + +impl Report { + fn case(&mut self, n: &str, what: &str, want: String, got: String) { + let ok = want == got; + if !ok { + self.failed += 1; + } + println!("\n{n}. {what}"); + println!(" expected: {want}"); + println!(" got: {got}"); + println!(" => {}", if ok { "fixed" } else { "REPRODUCES" }); + } +} + +fn main() { + let mut r = Report { failed: 0 }; + + // ---------------------------------------------------------------- 1 + // `join_into` is the write-zipper spelling of `join`, so joining a source + // into an empty destination has to be the same as joining the empty map + // with it. The root value does not survive the write-zipper form. + { + let src = with_val(&[], 1); + let eager = PathMap::::new().join(&src); + + let mut out = PathMap::::new(); + { + let mut wz = out.write_zipper(); + wz.join_into(&src.read_zipper()); + } + r.case( + "1", + "join_into on an empty destination: empty | {_:1}", + format!("root value {:?} (PathMap::join)", val_at(&eager, &[])), + format!("root value {:?} (join_into)", val_at(&out, &[])), + ); + } + + // ---------------------------------------------------------------- 2 + // `meet_2` writes the intersection of two sources into a fresh + // destination. Two maps whose only content is a root value intersect to + // that root value; `meet_2` produces nothing at all. + { + let a = with_val(&[], 1); + let b = with_val(&[], 2); + let eager = b.meet(&a); + + let mut out = PathMap::::new(); + { + let mut wz = out.write_zipper(); + wz.meet_2(&b.read_zipper(), &a.read_zipper()); + } + r.case( + "2", + "meet_2 with root values only: {_:2} & {_:1}", + format!("root value {:?} (PathMap::meet)", val_at(&eager, &[])), + format!("root value {:?} (meet_2)", val_at(&out, &[])), + ); + } + + // ---------------------------------------------------------------- 3 + // `pjoin` on `u64` is `left_biased_pjoin` and `pmeet` is + // `Identity(SELF_IDENT)`, so where both operands have a value at a path the + // result must carry the *left* one. It carries the right one when the two + // operands' nodes are laid out differently -- here because `a` has a chain + // of dangling descendants below the shared path and `c` does not. + // + // Every zipper route gets this right; `PathMap::join` and `PathMap::meet` + // do not, which is why it surfaces as failing laws rather than as one + // route disagreeing with the rest. + { + let mut a = dangling(&[&[0, 0, 0, 0], &[1]]); + a.write_zipper_at_path(&[0]).set_val(1); + let c = with_val(&[0], 2); + + r.case( + "3a", + "join value bias: {00:2} | {00:1, dangling below} at [0]", + "Some(2), the left operand's value".to_string(), + format!("{:?}", val_at(&c.join(&a), &[0])), + ); + r.case( + "3b", + "meet value bias: {00:1, dangling below} & {00:2} at [0]", + "Some(1), the left operand's value".to_string(), + format!("{:?}", val_at(&a.meet(&c), &[0])), + ); + } + + // ---------------------------------------------------------------- 4 + // The worst of them: a join *loses a value*. Not a bias about which of two + // values wins -- only one operand has a value at all, and the result has + // none. + // + // `b` is a clone of `a` with one value added, so the two tries share nodes. + // Joining in the order `a | b` drops `b`'s value; `b | a` keeps it. A + // join is a least upper bound, so no ordering of the operands may lose a + // path, which makes this the one finding here that is unambiguous without + // any appeal to value bias. + // + // The sharing is essential: rebuilding `b`'s entries into a fresh map + // instead of cloning `a` makes it go away. + { + let a = dangling(&[&[0, 0, 0, 0, 0], &[1, 0, 1], &[1, 0, 3]]); + let mut b = a.clone(); + b.write_zipper_at_path(&[1, 0, 0, 0]).set_val(1); + + let ab = a.join(&b); + let ba = b.join(&a); + r.case( + "4", + "join drops a value across clone-shared structure, at [1,0,0,0]", + format!("a|b == b|a == Some(1); b|a gives {:?}", val_at(&ba, &[1, 0, 0, 0])), + format!("a|b gives {:?}", val_at(&ab, &[1, 0, 0, 0])), + ); + } + + // ---------------------------------------------------------------- 5 + // Not an algebraic defect: `merkleize` panics outright on a trie that holds + // structure but no values. It is in this list because the fuzzer's operand + // generator reaches it -- `merkleize` is how it builds operands with shared + // subtries, which is what case 4 needs. + { + let mut m = dangling(&[&[0, 0], &[0, 1, 0, 0]]); + let hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| m.merkleize())); + std::panic::set_hook(hook); + r.case( + "5", + "merkleize over dangling-only structure", + "no panic".to_string(), + if res.is_ok() { "no panic".to_string() } else { "panic".to_string() }, + ); + } + + println!("\n{} of 6 still reproduce", r.failed); + if r.failed > 0 { + std::process::exit(1); + } +} diff --git a/differential/src/bin/alg_fuzz.rs b/differential/src/bin/alg_fuzz.rs new file mode 100644 index 00000000..63980029 --- /dev/null +++ b/differential/src/bin/alg_fuzz.rs @@ -0,0 +1,431 @@ +//! Driver for the algebraic equivalence fuzzer. See `../../ALGEBRAIC_FUZZING.md`. +//! +//! ```sh +//! cargo run --release -p differential --bin alg_fuzz -- --random 200000 --seed 1 +//! cargo run --release -p differential --bin alg_fuzz -- differential/algebraic-corpus/*.bin +//! cargo run --release -p differential --bin alg_fuzz -- --shrink some-input.bin +//! ``` +//! +//! Everything runs in process. There is no oracle to start and no child to +//! talk to, so a case costs a few microseconds and a run is bounded by how many +//! tries it can build rather than by IPC. + +use std::collections::BTreeMap; +use std::io::Write as _; +use std::panic::{self, AssertUnwindSafe}; +use std::path::{Path, PathBuf}; +use std::sync::mpsc; + +use differential::algebraic::{self, Class, Outcome, Rng, signatures}; + +/// Divergence classes that fail a run by default. +/// +/// `Shape` is not among them. Whether a dangling path survives an operation is +/// unsettled in the crate -- `SPEC_WARTS.md` and the `meet_into-keeps-dangling*` +/// corpus entries are the same question -- and routes that graft whole subtries +/// will keep structure that routes walking path by path cannot. Those are +/// counted and printed, so a change in them is visible, but they do not turn a +/// run red unless `--shape` asks them to. A wrong *value* is never ambiguous +/// and always fails. +const DEFAULT_FATAL: &[Class] = &[Class::Values, Class::Law]; + +struct Args { + random: usize, + seed: u64, + jobs: usize, + files: Vec, + shrink: Option, + out: PathBuf, + shape_fatal: bool, + strict: bool, + verbose: bool, + max_report: usize, + target: Option, +} + +fn usage() -> ! { + eprintln!( + "\ +usage: alg_fuzz [--random N] [--seed S] [--jobs J] [--shape] [--strict] [-v] + [--out DIR] [--max-report N] [--shrink FILE [--target SIG]] + [FILE...] + + --random N generate and check N random cases (default 10000 if no FILEs) + --seed S PRNG seed; each job derives its own stream from it (default 1) + --jobs J worker threads (default 1) + --shape treat dangling-path-only divergence as a failure too + --strict fail on every finding, including the ones in algebraic::KNOWN + --out DIR where failing inputs are written + (default differential/algebraic-corpus) + --max-report N stop printing individual findings after N (default 20) + --shrink FILE minimise FILE while it still diverges the same way, then exit + --target SIG with --shrink, the signature to preserve (default: the first + one FILE produces, which is not always the one you wanted) + -v print every finding's detail, not just the first few + FILE... replay these inputs instead of generating + +Exit status is 1 if any finding's signature is absent from algebraic::KNOWN, +which documents what already reproduces on master and why. Known findings are +still counted and printed." + ); + std::process::exit(2) +} + +fn parse() -> Args { + let mut a = Args { + random: 0, + seed: 1, + jobs: 1, + files: Vec::new(), + shrink: None, + out: PathBuf::from("differential/algebraic-corpus"), + shape_fatal: false, + strict: false, + verbose: false, + max_report: 20, + target: None, + }; + let mut it = std::env::args().skip(1); + while let Some(arg) = it.next() { + let num = |it: &mut dyn Iterator| -> u64 { + it.next().and_then(|s| s.parse().ok()).unwrap_or_else(|| usage()) + }; + match arg.as_str() { + "--random" => a.random = num(&mut it) as usize, + "--seed" => a.seed = num(&mut it), + "--jobs" => a.jobs = (num(&mut it) as usize).max(1), + "--max-report" => a.max_report = num(&mut it) as usize, + "--out" => a.out = PathBuf::from(it.next().unwrap_or_else(|| usage())), + "--shrink" => a.shrink = Some(PathBuf::from(it.next().unwrap_or_else(|| usage()))), + "--shape" => a.shape_fatal = true, + "--strict" => a.strict = true, + "--target" => a.target = Some(it.next().unwrap_or_else(|| usage())), + "-v" | "--verbose" => a.verbose = true, + "-h" | "--help" => usage(), + s if s.starts_with('-') => usage(), + s => a.files.push(PathBuf::from(s)), + } + } + if a.random == 0 && a.files.is_empty() && a.shrink.is_none() { + a.random = 10_000; + } + a +} + +// ------------------------------------------------------------------ driving + +struct Tally { + cases: usize, + by_signature: BTreeMap, + examples: Vec<(String, Vec, String)>, +} + +impl Tally { + fn new() -> Tally { + Tally { cases: 0, by_signature: BTreeMap::new(), examples: Vec::new() } + } + + fn record(&mut self, bytes: &[u8], outcome: Outcome) { + self.cases += 1; + let findings: Vec<(String, String)> = match outcome { + Outcome::Clean => return, + Outcome::Panicked(p, site, msg) => { + vec![( + algebraic::panic_signature(p, &site), + format!("panicked at {site}: {msg}"), + )] + } + Outcome::Diverged(d) => { + d.into_iter().map(|d| (d.signature, d.detail)).collect() + } + }; + for (sig, detail) in findings { + let seen = self.by_signature.entry(sig.clone()).or_insert(0); + *seen += 1; + // One saved example per signature: the point of the corpus is one + // reproducer per distinct defect, not one per input that hits it. + if *seen == 1 { + self.examples.push((sig, bytes.to_vec(), detail)); + } + } + } + + fn merge(&mut self, other: Tally) { + self.cases += other.cases; + for (sig, n) in other.by_signature { + *self.by_signature.entry(sig).or_insert(0) += n; + } + for (sig, bytes, detail) in other.examples { + if !self.examples.iter().any(|(s, _, _)| *s == sig) { + self.examples.push((sig, bytes, detail)); + } + } + } +} + +fn main() { + let args = parse(); + + // Replaces the default hook, which would print a backtrace notice per + // panicking case and drown a long run. It also records the panic site, + // which `catch_unwind` alone cannot see. + algebraic::install_panic_hook(); + + if let Some(path) = &args.shrink { + do_shrink(path, args.target.as_deref()); + return; + } + + let mut tally = Tally::new(); + + if !args.files.is_empty() { + for f in &args.files { + let bytes = std::fs::read(f).unwrap_or_else(|e| { + eprintln!("{}: {e}", f.display()); + std::process::exit(2) + }); + let outcome = algebraic::run(&bytes); + let label = match &outcome { + Outcome::Clean => "clean".to_string(), + Outcome::Diverged(d) => { + format!("{} finding(s)", d.len()) + } + Outcome::Panicked(p, site, m) => { + format!("panic in {} at {site}: {m}", p.tag()) + } + }; + println!("{}: {label}", f.display()); + tally.record(&bytes, outcome); + } + } + + if args.random > 0 { + let per = args.random / args.jobs; + let (tx, rx) = mpsc::channel(); + let mut handles = Vec::new(); + for job in 0..args.jobs { + let tx = tx.clone(); + let seed = args.seed; + let n = if job == args.jobs - 1 { args.random - per * (args.jobs - 1) } else { per }; + handles.push(std::thread::spawn(move || { + let mut rng = Rng::for_job(seed, job); + let mut t = Tally::new(); + for _ in 0..n { + let bytes = rng.input(); + let outcome = algebraic::run(&bytes); + t.record(&bytes, outcome); + } + let _ = tx.send(t); + })); + } + drop(tx); + for t in rx { + tally.merge(t); + } + for h in handles { + let _ = h.join(); + } + } + + report(&args, &mut tally); +} + +fn report(args: &Args, tally: &mut Tally) { + println!("\nchecked {} case(s)", tally.cases); + if tally.by_signature.is_empty() { + println!("no divergence"); + return; + } + + println!("\nfindings by signature:"); + for (sig, n) in &tally.by_signature { + match algebraic::known(sig) { + Some(k) => println!(" {n:>8} {sig} (known: {})", k.cause), + None => println!(" {n:>8} {sig} <-- NEW"), + } + } + + if let Err(e) = std::fs::create_dir_all(&args.out) { + eprintln!("cannot create {}: {e}", args.out.display()); + } + + let shown = if args.verbose { tally.examples.len() } else { args.max_report.min(tally.examples.len()) }; + println!("\nsaved reproducers in {}:", args.out.display()); + for (i, (sig, bytes, detail)) in tally.examples.iter().enumerate() { + let stem = sanitize(sig); + let bin = args.out.join(format!("{stem}.bin")); + let txt = args.out.join(format!("{stem}.txt")); + let _ = std::fs::write(&bin, bytes); + // Rendering the case means building the operands again, which for a + // `panic:build` finding panics again. Catch it: the reproducer is + // still worth writing, it just cannot describe itself. + let described = panic::catch_unwind(AssertUnwindSafe(|| { + algebraic::describe(&algebraic::decode(bytes)) + })) + .unwrap_or_else(|_| "\n".to_string()); + let body = format!("signature: {sig}\n\n{described}\n{detail}\n"); + let _ = std::fs::write(&txt, &body); + println!(" {}", bin.display()); + if i < shown { + for line in body.lines() { + println!(" {line}"); + } + } + } + + let fatal: Vec<&str> = tally + .by_signature + .keys() + .map(|s| s.as_str()) + .filter(|sig| is_fatal(sig, args)) + .collect(); + if fatal.is_empty() { + println!("\nnothing unexpected: every signature is in algebraic::KNOWN"); + } else { + println!("\n{} unexpected signature(s): {}", fatal.len(), fatal.join(" ")); + std::process::exit(1); + } +} + +/// Whether a signature should fail the run. +/// +/// `--strict` fails on anything. Otherwise a signature in `algebraic::KNOWN` +/// is excused, a panic or a wrong value is fatal, and a dangling-path-only +/// divergence is fatal only under `--shape`. +fn is_fatal(sig: &str, args: &Args) -> bool { + if args.strict { + return true; + } + if algebraic::known(sig).is_some() { + return false; + } + if sig.starts_with("panic:") { + return true; + } + if sig.starts_with("shape:") { + return args.shape_fatal; + } + DEFAULT_FATAL.iter().any(|c| sig.starts_with(c.tag())) +} + +fn sanitize(sig: &str) -> String { + sig.chars() + .map(|c| match c { + 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => c, + '|' => 'J', + '&' => 'M', + '^' => 'X', + '/' => 'R', + _ => '-', + }) + .collect() +} + +// ----------------------------------------------------------------- shrinking + +/// Minimise an input while it still produces the finding it started with. +/// +/// Byte-level delta debugging, in two passes repeated to a fixed point: drop +/// runs of bytes, then drive individual bytes towards zero. The second pass +/// matters more than it looks -- the decoder reads path bytes modulo a small +/// alphabet and entry counts modulo a small bound, so lowering a byte usually +/// shrinks the *tries* rather than the input, which is what makes the saved +/// reproducer readable. +/// +/// The invariant preserved is the original's first signature, not its whole +/// set: a smaller input often stops hitting the incidental extra findings, and +/// insisting on all of them would block almost every reduction. +fn do_shrink(path: &Path, want: Option<&str>) { + let original = std::fs::read(path).unwrap_or_else(|e| { + eprintln!("{}: {e}", path.display()); + std::process::exit(2) + }); + let sigs = signatures(&original); + if sigs.is_empty() { + eprintln!("{}: no divergence to shrink", path.display()); + std::process::exit(2) + } + let target = match want { + Some(w) => { + if !sigs.iter().any(|s| s == w) { + eprintln!( + "{}: does not produce {w}; it produces {}", + path.display(), + sigs.join(" ") + ); + std::process::exit(2) + } + w.to_string() + } + // An input usually hits several findings at once, and which one comes + // first is an artefact of route order. Say which was picked, so a + // surprising reduction is explainable rather than mysterious. + None => sigs[0].clone(), + }; + eprintln!( + "shrinking {} bytes, target {target} (of {})", + original.len(), + sigs.join(" ") + ); + + let holds = |b: &[u8]| signatures(b).iter().any(|s| *s == target); + let mut best = original; + + loop { + let before = (best.len(), best.iter().map(|b| *b as u32).sum::()); + + let mut chunk = best.len().next_power_of_two() / 2; + while chunk >= 1 { + let mut i = 0; + while i < best.len() { + let end = (i + chunk).min(best.len()); + let mut cand = best[..i].to_vec(); + cand.extend_from_slice(&best[end..]); + if !cand.is_empty() && holds(&cand) { + best = cand; + } else { + i += chunk; + } + } + chunk /= 2; + } + + for i in 0..best.len() { + for v in [0u8, 1, best[i] / 2] { + if best[i] <= v { + continue; + } + let mut cand = best.clone(); + cand[i] = v; + if holds(&cand) { + best = cand; + break; + } + } + } + + if (best.len(), best.iter().map(|b| *b as u32).sum::()) == before { + break; + } + } + + let out = path.with_extension("min.bin"); + std::fs::write(&out, &best).unwrap(); + eprintln!("shrunk to {} bytes -> {}", best.len(), out.display()); + + let described = panic::catch_unwind(AssertUnwindSafe(|| { + algebraic::describe(&algebraic::decode(&best)) + })) + .unwrap_or_else(|_| "\n".to_string()); + print!("{described}"); + match algebraic::run(&best) { + Outcome::Clean => println!("(no longer diverges)"), + Outcome::Panicked(p, site, m) => println!("panic in {} at {site}: {m}", p.tag()), + Outcome::Diverged(d) => { + for div in d { + println!("[{}] {}\n{}", div.class.tag(), div.signature, div.detail); + } + } + } + let _ = std::io::stdout().flush(); +} diff --git a/differential/src/lib.rs b/differential/src/lib.rs index 661cf803..a3c5e052 100644 --- a/differential/src/lib.rs +++ b/differential/src/lib.rs @@ -8,8 +8,13 @@ //! * [`server`] is the resident-process protocol the driver speaks. //! * [`repro`] turns an input back into standalone `pathmap` calls. //! * [`act`] is the `ArenaCompactTree` read source behind `act_trace`. +//! +//! [`algebraic`] is a third fuzzer with a different question. It has no +//! oracle: it evaluates one algebraic expression every way the crate offers and +//! requires the answers to match. `bin/alg_fuzz.rs` drives it. pub mod act; +pub mod algebraic; pub mod harness; pub mod repro; pub mod server; diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs new file mode 100644 index 00000000..de39d8c1 --- /dev/null +++ b/differential/tests/algebraic.rs @@ -0,0 +1,190 @@ +//! Regression gate for the algebraic equivalence fuzzer. +//! +//! Three things, cheap enough for `cargo test`: +//! +//! * the local corpus, if there is one, reproduces only what `KNOWN` documents; +//! * a short random sweep from a fixed seed turns up nothing new; +//! * the expression recognisers that decide which route applies to which shape +//! agree with what the n-ary and DNF entry points actually compute. +//! +//! The last one is not incidental. Both recognisers were wrong when this +//! fuzzer was first run, and both failures looked exactly like crate defects: +//! flattening `a ^ (b ^ c)` into the n-ary call, which folds values left, and +//! letting a DNF clause stand for `b & a` when a clause is an unordered set and +//! `pmeet` is left-biased. A harness that reports its own mistakes as findings +//! is worse than no harness, so the recognisers are pinned here. + +use differential::algebraic::{self, expr::{Expr, Op}, known, signatures}; + +/// Collect the signatures an input produces that `KNOWN` does not document. +/// +/// Returns them rather than asserting, because `install_panic_hook` silences +/// the panic hook for the duration -- which is the point, since the inputs make +/// `pathmap` panic -- and a silenced hook would swallow the assertion message +/// too. So every caller gathers first, restores the hook, then asserts. +fn unknown_signatures(bytes: &[u8]) -> Vec { + signatures(bytes).into_iter().filter(|s| known(s).is_none()).collect() +} + +fn complain(found: &[(String, String)]) -> String { + let mut m = String::from("unexpected signature(s):\n"); + for (sig, where_) in found { + m.push_str(&format!(" {sig} from {where_}\n")); + } + m.push_str( + "\nIf a defect was just fixed, drop its entry from algebraic::KNOWN.\n\ + If it is new, shrink it with\n\ + \x20 cargo run --release -p differential --bin alg_fuzz -- \\\n\ + \x20 --shrink --target \n\ + and add a reproducer to bin/alg_bug_repros.rs.\n", + ); + m +} + +/// Serialises the tests that install a panic hook. +/// +/// `set_hook` and `take_hook` are process-global while `cargo test` runs tests +/// on several threads, so two of these running at once interleave: one restores +/// the default hook under the other, the other's panics stop being recorded, +/// and the signature it reports is whatever site was recorded last. That shows +/// up as a phantom unexpected signature in whichever test lost the race. +static PANIC_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Run `f` with the fuzzer's panic hook installed, restoring the previous hook +/// afterwards so a later assertion can still report itself. +fn with_quiet_panics(f: impl FnOnce() -> T) -> T { + // A failing test panics *outside* this function, so the lock is never + // poisoned by the assertion itself -- but `f` runs code that panics by + // design, so recover from poisoning rather than propagating it. + let _guard = PANIC_HOOK.lock().unwrap_or_else(|e| e.into_inner()); + let prev = std::panic::take_hook(); + algebraic::install_panic_hook(); + let out = f(); + std::panic::set_hook(prev); + out +} + +#[test] +fn corpus_reproduces_only_known_findings() { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/algebraic-corpus"); + let (seen, found) = with_quiet_panics(|| { + let mut seen = 0; + let mut found = Vec::new(); + // The corpus is local and gitignored: whatever alg_fuzz sweeps have + // saved there. Without one there is nothing to replay. + let Ok(entries) = std::fs::read_dir(dir) else { return (0, Vec::new()) }; + for entry in entries { + let path = entry.expect("corpus entry").path(); + if path.extension().is_none_or(|e| e != "bin") { + continue; + } + let bytes = std::fs::read(&path).expect("corpus file"); + for sig in unknown_signatures(&bytes) { + found.push((sig, path.display().to_string())); + } + seen += 1; + } + (seen, found) + }); + eprintln!("replayed {seen} corpus input(s) from {dir}"); + assert!(found.is_empty(), "{}", complain(&found)); +} + +#[test] +fn random_sweep_turns_up_nothing_new() { + // Small, because this runs unoptimised under `cargo test` and is only a + // tripwire. The real sweep is `alg_fuzz --random`, which does a million + // cases in under twenty seconds. + const CASES: usize = 5_000; + let found = with_quiet_panics(|| { + let mut rng = algebraic::Rng::for_job(20261002, 0); + let mut found = Vec::new(); + for i in 0..CASES { + let bytes = rng.input(); + for sig in unknown_signatures(&bytes) { + found.push((sig, format!("case {i} of seed 20261002"))); + } + } + found + }); + assert!(found.is_empty(), "{}", complain(&found)); +} + +// --------------------------------------------------- recogniser invariants + +fn var(i: usize) -> Expr { + Expr::Var(i) +} + +#[test] +fn chain_flattens_left_nesting_for_every_chainable_operator() { + for op in [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff] { + let e = Expr::bin(op, Expr::bin(op, var(0), var(1)), var(2)); + assert_eq!(e.chain(), Some((op, vec![0, 1, 2])), "{op:?} left-nested"); + } +} + +#[test] +fn chain_rejects_right_nesting_where_the_n_ary_fold_would_differ() { + // `zipper_n_subtract` is left-associative and the symmetric-difference fold + // combines values left to right, so neither may be matched right-nested. + for op in [Op::Subtract, Op::SymDiff] { + let e = Expr::bin(op, var(0), Expr::bin(op, var(1), var(2))); + assert_eq!(e.chain(), None, "{op:?} right-nested must not be a chain"); + } + // Join and meet are left-biased in their values, so both nestings agree + // with the fold and both are chains. + for op in [Op::Join, Op::Meet] { + let e = Expr::bin(op, var(0), Expr::bin(op, var(1), var(2))); + assert_eq!(e.chain(), Some((op, vec![0, 1, 2])), "{op:?} right-nested"); + } +} + +#[test] +fn chain_rejects_a_mixed_tree() { + let e = Expr::bin(Op::Join, Expr::bin(Op::Meet, var(0), var(1)), var(2)); + assert_eq!(e.chain(), None); +} + +#[test] +fn dnf_recognises_a_join_of_meets() { + // (a & b) | c + let e = Expr::bin(Op::Join, Expr::bin(Op::Meet, var(0), var(1)), var(2)); + assert_eq!(e.dnf(), Some(vec![0b011, 0b100])); +} + +#[test] +fn dnf_rejects_a_clause_whose_operands_are_out_of_slot_order() { + // A clause is a bitmask, so it cannot distinguish `b & a` from `a & b`, + // and `pmeet` on u64 keeps the left value, so the two differ. + assert_eq!(Expr::bin(Op::Meet, var(0), var(1)).dnf(), Some(vec![0b011])); + assert_eq!(Expr::bin(Op::Meet, var(1), var(0)).dnf(), None); +} + +#[test] +fn dnf_rejects_non_monotone_operators() { + for op in [Op::Subtract, Op::SymDiff, Op::Restrict] { + assert_eq!(Expr::bin(op, var(0), var(1)).dnf(), None, "{op:?}"); + } +} + +#[test] +fn every_strategy_index_is_reachable_from_some_pointwise_route() { + // Route `k` picks strategy `k % n` per operator, so POINTWISE_ROUTES has to + // be at least as large as the widest operator's strategy table or some + // implementation would never be exercised. + for op in Op::ALL { + let n = algebraic::routes::strategies(op).len(); + assert!( + n <= algebraic::routes::POINTWISE_ROUTES, + "{op:?} has {n} strategies but only {} pointwise routes", + algebraic::routes::POINTWISE_ROUTES + ); + for s in 0..n { + assert!( + (0..algebraic::routes::POINTWISE_ROUTES).any(|k| k % n == s), + "{op:?} strategy {s} is unreachable" + ); + } + } +} From d9819766ed5b4ae0f897706493649a652e9faa62 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 2 Oct 2026 22:16:16 +0000 Subject: [PATCH 04/17] Extend the algebraic fuzzer: lattice check, three value types, dangling repro Four pieces of work on top of the initial fuzzer, all of which came out of one discovery: the value type it was using cannot support the questions being asked of it. **u64's Lattice impl is not a lattice.** pjoin is left_biased_pjoin and pmeet is Identity(SELF_IDENT), so both return the left operand, a | b == a & b for every pair, and in a lattice that would force a == b -- the impl effectively asserts 1 == 2. Two consequences, both limits on the harness rather than on the crate: neither operation can return AlgebraicResult::Element, so the code that stores a genuinely combined value was never reached; and several laws had to be weakened or omitted, which looked like facts about the algebra and were facts about u64. bin/alg_lattice_check prints the evidence, for u64, bool, a bitmask and max/min-on-a-total-order. The last of those is the useful one: it is a perfectly lawful distributive lattice and still answers "never" to whether any operation produces Element, because max(a, b) and min(a, b) are always one of the operands. Being a lawful lattice is not sufficient; only the bitmask family reaches that code, because a | b is a new value. **So the harness is generic over the value type and runs every case three times.** Signatures carry the type, and every run ends with the comparison. * bits -- a 64-bit set under |, & and & !, empty collapsing to bottom. The same construction pathmap::utils already uses for [u64; 4] and ByteMask, at a narrower width. Defined in differential rather than in pathmap, because a value type from outside the crate is what a real caller has. * unit -- PathMap<()>, the set case, also lawful. Its pjoin and pmeet return Identity(SELF_IDENT | COUNTER_IDENT) on *every* combination, where the others do so only for equal values, which saturates the "either operand will do" path the node code uses to keep sharing -- the machinery two of the findings are about. Nothing in zipper_algebra.rs tests () at all. * u64 -- kept, because it is what callers use and it reaches Identity-heavy paths the lawful types do not. Five findings are u64-only artefacts; nothing is lawful-type-only, so u64 was masking nothing. Counts collapse rather than vanish for the rest -- join associativity fails 3131 times under u64 and 12 under bits -- because under a commutative join, picking the wrong operand is invisible except where one operand already contains the other. Every residue shrinks to a lost value, not a misplaced one. values:model drops from 1258 to 2. Three of the four identities that only a lawful type can check hold. The fourth, subtract-over-join, fires under unit, and is a lost value rather than a bad identity. **Three further corrections, each now pinned by a test:** * model.rs no longer restates the value algebra; it delegates to pjoin/pmeet/psubtract through the Option impls in ring, so a disagreement with a route is always about where a value ends up. * The OverlayZipper join strategy declines for a value type whose join creates values, instead of answering wrongly: its mapping returns a *reference*, so it has nowhere to put a value it would create. * Strategy tables are the same length for every value type, so route k means the same thing under each. Shortening one silently renumbered the rest and made the per-type comparison compare different things. **The exit-status gate was broken** once signatures gained the value-type prefix: is_fatal matched class names against the start of the whole signature, so every class fell through to not-fatal and runs with new findings were passing. It parses the class field now. Two findings were sitting unreported behind it. **alg_bug_repros covers every cause in KNOWN.** The dangling-path class had none, and is the largest; case 7 adds it. Its explanation was also backwards: the lockstep traversals in zipper_algebra DISCARD dangling structure and the whole-map and write-zipper forms PRESERVE it, not the other way round. Corrected in four places and pinned, since going stale quietly is how it was wrong to begin with. **Documented soundness limit.** A run that catches panics aborts with heap corruption, reproducibly, and it tracks the number of panics caught rather than the build profile, thread count or value type -- a run that catches none is clean. Every panic caught fired mid-mutation inside pathmap's node code, and unwinding out of a half-updated node leaves a trie that is not safe to drop. This harness's problem, not a defect: the crash fuzzer runs one input per process. Not fixed, because the fix is a design change; until then the first panic in a run is the end of its trustworthy output. Verified clean at 1M cases, corpus replays clean in both profiles, 14 harness tests, 1043 lib tests, no warnings. Nothing outside differential/ is touched. --- differential/ALGEBRAIC_FUZZING.md | 215 +++++++++++-- differential/src/algebraic.rs | 368 +++++++++++++++------- differential/src/algebraic/laws.rs | 109 +++++-- differential/src/algebraic/model.rs | 134 ++++---- differential/src/algebraic/routes.rs | 83 +++-- differential/src/algebraic/shape.rs | 46 +-- differential/src/algebraic/value.rs | 241 ++++++++++++++ differential/src/bin/alg_bug_repros.rs | 96 +++++- differential/src/bin/alg_fuzz.rs | 179 +++++++++-- differential/src/bin/alg_lattice_check.rs | 208 ++++++++++++ differential/tests/algebraic.rs | 236 +++++++++++++- 11 files changed, 1606 insertions(+), 309 deletions(-) create mode 100644 differential/src/algebraic/value.rs create mode 100644 differential/src/bin/alg_lattice_check.rs diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 636e3556..4c9fb87d 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -108,19 +108,124 @@ baseline in an interesting way — the baseline is what everyone is compared against. `meet-distributes-over-join` has no baseline to be fooled by: it puts the operands on different sides of a meet and notices. -### The value semantics are not set semantics +### Three value types, and the difference between them is a measurement + +Every case runs once per value type, and signatures are prefixed with the type +(`u64:values:pw1`, `bits:law:join-associative`). That is the fuzzer's main +discriminator: + +* **`bits`** is a 64-bit set under `|`, `&` and `& !`, with an empty result + collapsing to bottom — i.e. to an absent value, the convention `SetLattice`'s + documentation already states. A genuine Boolean algebra, so every lattice + identity holds and a law that fails here is a real defect. It lives in + `src/algebraic/value.rs` rather than in `pathmap`, because a value type defined + outside the crate is what a real caller has. + +* **`unit`** is `PathMap<()>`: the set case, also lawful, since `Option<()>` is + the two-element Boolean algebra. It earns its own slot for a reason neither of + the others covers: `()`'s `pjoin` and `pmeet` return + `Identity(SELF_IDENT | COUNTER_IDENT)` — *both* identity bits — on every single + combination, where `u64` and `bits` do so only for equal values. That saturates + the "either operand will do" path the node code uses to decide it can hand back + an operand unchanged and keep sharing it, which is precisely the machinery + findings 4 and 6 are about. It is also what `unit-value-optimizations` and + `unit-size` are about; neither is on `master`, so today this covers the generic + path, and if they land it is the only thing covering the specialised one. + Nothing in `zipper_algebra.rs` tests `()` at all — every test there uses `u64`. + +* **`u64`** is what the rest of this crate's fuzzing uses, and its instances in + `pathmap::ring` are **not a lattice**: `pjoin` is `left_biased_pjoin`, `pmeet` + is `Identity(SELF_IDENT)` — both return the left operand, so `a | b == a & b` + for every pair, which in a lattice forces `a == b`. It is kept because it is + what callers use today, and because it reaches `Identity`-heavy paths that the + lawful type does not. + +A finding under `u64` alone is an artefact. One under a lawful type is a defect. `alg_fuzz` prints the split at the end of every run: -Three laws are checked on path presence only, and three plausible ones are -deliberately absent. Both follow from `u64`'s lattice instances in -`pathmap::ring`, which are left-biased: `pjoin` keeps the left value where the -two differ, and `pmeet` keeps the left value *unconditionally*. So join and -meet are not commutative in the value they produce, only in their path set. -`laws.rs` documents each case, including the identities that look true and are -not. +``` +by value type -- bits is lawful, u64 is not: + finding u64 bits + law:absorb-join-meet 82 - + law:join-associative 3131 12 + law:join-distributes-over-meet 2077 1 + law:meet-distributes-over-join 1603 - + law:sym-diff-is-join-minus-meet 6684 5 + panic:build:line_list_node.rs:1745 13476 13476 + values:model 1258 2 + values:pw1 30849 36071 + ... +``` + +Read the counts, not just the membership. `law:join-associative` failing 3131 +times under `u64` and 12 under `bits` is **one** defect amplified by the value +type: under a commutative join, picking the wrong operand is invisible except +where one operand already contains the other, so only that residue survives. And +every one of those residues shrinks to a value present on one side of the +identity and *absent* on the other — which is finding 4, a lost value, not a +misplaced one. + +So far: five findings are `u64`-only, nothing is `bits`-only, and `values:model` +drops from 1258 to 2 — the flat reference model and the trie agree on values +almost everywhere once the value algebra is lawful. + +### Why a bitmask and not some other lawful lattice + +Lawfulness is not sufficient, and this is the part worth remembering. +`max`/`min` on a total order is a perfectly good distributive lattice, every +identity holds, and it is **useless here**: `max(a, b)` and `min(a, b)` are +always one of the operands, so they can only return +`AlgebraicResult::Identity`, and every code path that allocates and stores a +genuinely combined value stays unreachable. `a | b` is a new value, so a bitmask +reaches them. `bin/alg_lattice_check` prints the table: + +``` + type pjoin pmeet psubtract + u64 NO NO yes <- and PR #115 makes that NO too + bool NO NO NO + MinMax NO NO NO <- lawful, still useless + Bits yes yes yes + ByteMask yes yes yes +``` + +`pathmap::utils` already implements exactly this for `[u64; 4]` and `ByteMask`, +via `bitmask_algebraic_result`; `Bits` is the same construction at 64 bits. + +### What the lawful type unlocked + +Four identities are checked **only** for a lawful value type, in +`laws::lawful_only` — De Morgan for relative complement both ways, +`a - b == a - (a & b)`, and symmetric difference being associative on *values* +rather than only on paths. Each fails for `u64`, for the same reason everything +else does. + +**Three of the four hold** across several million cases in both profiles: +`subtract-over-meet`, `subtract-is-subtract-meet` and `sym-diff-associative`. +They are the strongest laws the harness has and are deliberately absent from +`KNOWN`, so one of them firing is news. + +The fourth, `subtract-over-join`, fires about once per two million cases under +`unit` — and is cause 2 rather than a bad identity. Its shrunk case has a +dangling-only `b` and a `c` that is `b` plus one value, so `b | c` is exactly +finding 4. + +The `Level::Paths` laws are also promoted to `Level::Values` for a lawful type, +so commutativity of join and meet is checked on values there. -Getting this wrong is the main way to write a harness that reports its own -mistakes as crate defects, and it happened twice while this one was being -built — see "Harness invariants" below. +### One thing the lawful type cannot do + +`OverlayZipper`'s mapping has signature +`Fn(Option<&'a AV>, Option<&'a BV>) -> Option<&'a OutV>` — it returns a +*reference*, so it has nowhere to put a value it would have to create. The +module's own comment says as much. So an overlay can stand in for a join only +when the join never creates anything, and for a real lattice it cannot be a join +at all. The strategy therefore *declines* for `bits` rather than answering +wrongly, which is why `pw5` applies to fewer cases there. That is a limitation of +the zipper, not a defect, and not reported as one. + +Note that declining is what keeps route numbers comparable. An earlier version +shortened the join strategy table for such types, which silently renumbered every +later route — so `pw4` and `pw5` meant different strategy mixes under the two +types, and comparing their findings compared different things. ## Generated operands @@ -160,9 +265,19 @@ instead of cloned. A generator that only wrote fresh tries would find neither. `shape` is separated because the semantics are genuinely unsettled — see `../SPEC_WARTS.md` and the `meet_into-keeps-dangling*` corpus entries, which are -the same question — and because routes that graft whole subtries will keep -structure that routes walking path by path cannot. A wrong *value* is never -ambiguous. +the same question. The two families answer it differently and *consistently*, +which is worth knowing because it says which side has to change once the question +is settled: + +* the lockstep traversals in `experimental::zipper_algebra` **discard** dangling + structure; +* `PathMap`'s whole-map operations and the write-zipper forms (`join_into`, + `meet_into`, `subtract_into`) **preserve** it. + +`bin/alg_bug_repros` case 7 shows three of them side by side, the sharpest being +`d ^ {}`: symmetric difference with the empty trie ought to be the identity, and +`zipper_sym_diff` returns nothing where `(d | e) - (d & e)` returns `d`. A wrong +*value* is never ambiguous. Signatures are `class:route`, and nothing more. An earlier version appended the operators the expression used, which looked more informative and was much @@ -171,6 +286,51 @@ under every operator combination containing a meet. The expression, the operands and the diff all live in the saved `.txt`; the signature's only job is to collapse a million inputs onto a handful of lines. +## Soundness limit: catching a panic in process is not safe + +**A long run that catches panics can abort with heap corruption.** Reproducibly: + +``` +$ ./alg_fuzz --random 2000000 --seed 55 --jobs 8 # debug-assertions build +malloc(): unaligned tcache chunk detected +Aborted (core dumped) +``` + +Narrowed by elimination, each at 2M cases, seed 55, 8 jobs: + +| build | `merkleize` in the generator | caught panics | result | +| --- | --- | --- | --- | +| debug assertions | yes | ~27k | **abort** | +| debug assertions | no | ~100 | **abort** | +| release | yes | ~27k | **abort** | +| release | no | 0 | clean, exit 0 | + +So it tracks the *number of panics caught*, not the build profile, the thread +count or the value type. The cause is that `catch_unwind` resumes after a panic +that fired **mid-mutation inside `pathmap`'s node code**: unwinding out of a +half-updated node leaves a trie that is not safe to drop, and the damage shows up +later as an invalid free. Every panic the fuzzer catches is one of these — a +`debug_assert!` inside a merge, or `merkleize`'s `unwrap`, both of which are +"this cannot happen" sites rather than supported unwind paths. + +That is a limitation of *this* harness, not an independent defect. The crash +fuzzer does not have it because AFL runs one input per process and so never +continues after a panic. + +**Until this is fixed, treat the first panic in a run as the end of the useful +output.** Findings reported before it are valid — the signature counts and +reproducers are written as they are found — but anything after the first caught +panic is suspect, and a run that aborts has lost whatever it had not yet printed. +A release-profile run on a generator without `merkleize` catches nothing and is +unaffected. + +The fix is to make panics terminal and rare, the way a crash fuzzer treats them: +stop the run on the first one, and stop generating the one panic that is already +documented with a standalone reproducer (`merkleize`, repro 5) so that the +remaining ones are rare enough for stopping to cost nothing. That needs the +corpus replay to run one input per process, so it is a design change rather than +a patch, and it is not done yet. + ## Debug assertions are a separate mode `pathmap`'s `debug_assert!`s are the sharpest instrument here, and a release @@ -194,8 +354,8 @@ expects the `panic:eval:*` signatures. ## Findings Six defects on `master` at `b4a6abd`, reproduced without the fuzzer in -`src/bin/alg_bug_repros.rs`. `algebraic::KNOWN` maps every signature onto one of -them. +`src/bin/alg_bug_repros.rs`, plus the unsettled dangling-path question as case 7. +`algebraic::KNOWN` maps every signature onto one of them. 1. **`join_into` drops the source's root value when the destination is empty.** `PathMap::new().join(&src)` keeps it; the write-zipper spelling does not. @@ -226,19 +386,8 @@ them. `merge_from_list_node` returns `AlgebraicStatus::None` from nodes that are not empty (`line_list_node.rs:2669` and `:2720`), and a cofree `pjoin` returns `None` while the left side still has a non-empty onward node - (`dense_byte_node.rs:2080`). - -### Reading a report - -Every signature is printed with its count, known or not, and a `<-- NEW` marker -on anything absent from `KNOWN`. Exit status is 1 if anything is new; -`--strict` makes every finding fatal. Counts matter even for known findings: a -known defect that starts firing ten times more often is a change worth seeing, -and it does not turn the run red. - -`KNOWN` is a snapshot, not a closed list. A longer sweep may well reach a new -assertion site — the three in finding 6 appeared at 500 000, 3 000 000 and -roughly 400 000 cases respectively. A new signature is the fuzzer working. + (`dense_byte_node.rs:2080`). Debug-assertions builds only, so it has no + standalone reproducer — replay the `panic-eval-*` corpus inputs. ## Harness invariants @@ -269,13 +418,17 @@ disagrees with the rest, suspect the route first. | `src/algebraic/expr.rs` | the expression language and the shape recognisers | | `src/algebraic/routes.rs` | the routes, and one arm per strategy | | `src/algebraic/laws.rs` | the identities, and the ones deliberately absent | -| `src/algebraic/model.rs` | flat `BTreeMap` semantics | +| `src/algebraic/model.rs` | flat `BTreeMap` semantics, delegating to the value algebra | +| `src/algebraic/value.rs` | the `FuzzValue` trait and the lawful `Bits` type | | `src/algebraic/shape.rs` | what "the same result" means | | `src/bin/alg_fuzz.rs` | the driver: generation, replay, shrinking, reporting | -| `src/bin/alg_bug_repros.rs` | the findings as plain `pathmap` calls | +| `src/bin/alg_bug_repros.rs` | every cause in `KNOWN` as plain `pathmap` calls | +| `src/bin/alg_lattice_check.rs` | whether a divergence is the crate's fault or `u64`'s | | `tests/algebraic.rs` | the corpus gate and the harness invariants | | `algebraic-corpus/` | local and gitignored: one saved input per signature, from sweeps | +Nothing outside `differential/` is touched. + Byte decoding reuses `harness::Dec`. The wire format is *not* the one `harness.rs` shares with `PathMapModel.Fuzz`: this fuzzer has no model to stay in step with, so its inputs are free to be whatever generates interesting diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index f65fc5b4..56f00a54 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -28,6 +28,7 @@ pub mod laws; pub mod model; pub mod routes; pub mod shape; +pub mod value; use pathmap::PathMap; use pathmap::zipper::{ZipperMoving, ZipperWriting}; @@ -36,6 +37,7 @@ use expr::{Expr, Op, MAX_VARS}; use laws::{Level, EMPTY, LAW_OPERANDS}; use routes::Route; use shape::{shape_of_map, show_shape, Shape, Values}; +use value::FuzzValue; /// Operand tries per case. Fixed rather than generated so the expression /// generator can always name any of them, and so [`MAX_VARS`] is the only @@ -51,13 +53,6 @@ pub const MAX_ENTRIES: usize = 7; /// Upper bound on a generated path's length. pub const MAX_PATH_LEN: usize = 5; -/// Distinct values in circulation. Deliberately tiny: `psubtract` on `u64` is -/// `None` only when the two values are *equal*, and symmetric difference -/// cancels on coincident paths, so a large value space would make both -/// operations degenerate into set difference and set union and never exercise -/// the value-combining paths at all. -pub const VALUES: u64 = 3; - /// Byte decoding with the out-of-input behaviour this fuzzer wants. /// /// Not `harness::Dec`: that one returns `None` when the input runs out, because @@ -99,9 +94,6 @@ impl<'a> Gen<'a> { let n = self.modn(max_len + 1); (0..n).map(|_| self.path_byte()).collect() } - pub fn val(&mut self) -> u64 { - self.byte() as u64 % VALUES + 1 - } } /// How one operand trie was built. Recorded so a failure report can say @@ -127,15 +119,15 @@ pub enum Build { MerkleizedOf(usize), } -pub struct Case { +pub struct Case { pub expr: Expr, - pub operands: Vec>, + pub operands: Vec>, pub builds: Vec, pub alphabet: u16, } /// Decode a byte string into a case. Total: every input decodes. -pub fn decode(bytes: &[u8]) -> Case { +pub fn decode(bytes: &[u8]) -> Case { let mut g = Gen::new(bytes); // A 3-letter alphabet is the default because collisions are the point; the // wider ones are sampled to keep node-type coverage honest, since `pathmap` @@ -148,7 +140,7 @@ pub fn decode(bytes: &[u8]) -> Case { }; let alphabet = g.alphabet; - let mut operands: Vec> = Vec::with_capacity(OPERANDS); + let mut operands: Vec> = Vec::with_capacity(OPERANDS); let mut builds: Vec = Vec::with_capacity(OPERANDS); for i in 0..OPERANDS { let build = pick_build(&mut g, i); @@ -172,7 +164,7 @@ fn pick_build(g: &mut Gen, i: usize) -> Build { } } -fn build_operand(g: &mut Gen, build: Build, prior: &[PathMap]) -> PathMap { +fn build_operand(g: &mut Gen, build: Build, prior: &[PathMap]) -> PathMap { match build { Build::Fresh => fresh(g), Build::CloneOf(j) => { @@ -185,7 +177,7 @@ fn build_operand(g: &mut Gen, build: Build, prior: &[PathMap]) -> PathMap, u64)> = + let entries: Vec<(Vec, V)> = shape::values_of_shape(&shape_of_map(&prior[j])).into_iter().collect(); let mut out = PathMap::new(); if !entries.is_empty() { @@ -195,7 +187,7 @@ fn build_operand(g: &mut Gen, build: Build, prior: &[PathMap]) -> PathMap]) -> PathMap PathMap { +fn fresh(g: &mut Gen) -> PathMap { let n = g.modn(MAX_ENTRIES + 1); let mut out = PathMap::new(); { @@ -225,14 +217,14 @@ fn fresh(g: &mut Gen) -> PathMap { if g.chance(20) { wz.create_path(); } else { - wz.set_val(g.val()); + wz.set_val(V::generate(g)); } } } out } -fn mutate(g: &mut Gen, m: &mut PathMap) { +fn mutate(g: &mut Gen, m: &mut PathMap) { let n = g.modn(3); let mut wz = m.write_zipper(); for _ in 0..n { @@ -250,7 +242,7 @@ fn mutate(g: &mut Gen, m: &mut PathMap) { wz.remove_branches(false); } _ => { - wz.set_val(g.val()); + wz.set_val(V::generate(g)); } } } @@ -323,14 +315,23 @@ pub struct Divergence { /// the oldest and most heavily used entry points in the crate, which makes them /// the right thing to hold still, though the choice only affects which side of /// a disagreement gets named, not whether it is found. -pub fn check(case: &Case) -> Vec { +pub fn check(case: &Case) -> Vec { let mut out = Vec::new(); let baseline_route = Route::Pointwise(0); let baseline = routes::eval(baseline_route, &case.expr, &case.operands) - .expect("the pointwise route applies to every expression"); + .expect("route 0 is the whole-map operations, which apply to everything"); let base_name = baseline_route.name(&case.expr); + // The model is computed up front so every divergence can say which side it + // backs. Worth the one extra evaluation: the baseline is `PathMap::join` + // and friends, which have defects of their own, so "route X disagrees with + // the baseline" on its own points at the wrong file about as often as the + // right one. The model has no trie and no node layout, so when it sides + // with the route, the baseline is where to look. + let model = routes::eval(Route::Model, &case.expr, &case.operands) + .expect("the model route applies to every expression"); + for route in Route::all() { if route == baseline_route { continue; @@ -341,14 +342,15 @@ pub fn check(case: &Case) -> Vec { if got.values != baseline.values { out.push(Divergence { class: Class::Values, - signature: format!("values:{}", route_key(route)), + signature: signature::("values", &route_key::(route)), detail: format!( - "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}", + "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}\n {}", base_name, case.expr, shape::first_values_diff(&baseline.values, &got.values).unwrap_or_default(), shape::show_values(&baseline.values), shape::show_values(&got.values), + model_sides_with(&model.values, &baseline.values, &got.values, &base_name, &name), ), }); // One class per route is enough; a value divergence will usually @@ -361,7 +363,7 @@ pub fn check(case: &Case) -> Vec { if bs != gs { out.push(Divergence { class: Class::Shape, - signature: format!("shape:{}", route_key(route)), + signature: signature::("shape", &route_key::(route)), detail: format!( "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}", base_name, @@ -385,15 +387,15 @@ pub fn check(case: &Case) -> Vec { /// and holds under another is already a route disagreement, which the loop /// above reports; running every law through every route would multiply the cost /// of a case by the number of laws for no new coverage. -pub fn check_laws(case: &Case) -> Vec { +pub fn check_laws(case: &Case) -> Vec { // Operands 0..3 from the case, then the empty trie, which is what lets a // law state a unit or annihilator. - let mut ops: Vec> = (0..EMPTY).map(|i| case.operands[i].clone()).collect(); + let mut ops: Vec> = (0..EMPTY).map(|i| case.operands[i].clone()).collect(); ops.push(PathMap::new()); debug_assert_eq!(ops.len(), LAW_OPERANDS); let mut out = Vec::new(); - for law in laws::laws() { + for law in laws::laws::() { let l = routes::eval(Route::Pointwise(0), &law.lhs, &ops).unwrap(); let r = routes::eval(Route::Pointwise(0), &law.rhs, &ops).unwrap(); let (ok, detail) = match law.level { @@ -429,7 +431,7 @@ pub fn check_laws(case: &Case) -> Vec { if !ok { out.push(Divergence { class: Class::Law, - signature: format!("law:{}", law.name), + signature: signature::("law", law.name), detail: format!("{} ({:?}): {detail}", law.name, law.level), }); } @@ -437,7 +439,38 @@ pub fn check_laws(case: &Case) -> Vec { out } -fn route_key(r: Route) -> String { +/// Which side of a value divergence the reference model backs, as one line for +/// the report. +/// +/// Neither side being backed is the interesting case: it means the model +/// disagrees with both, so the defect is unlikely to be in either route's +/// traversal and is more likely in a shared primitive -- or in the model, which +/// is worth suspecting too. +fn model_sides_with( + model: &Values, + baseline: &Values, + got: &Values, + base_name: &str, + name: &str, +) -> String { + match (model == baseline, model == got) { + (true, true) => "model: agrees with both (unreachable)".to_string(), + (true, false) => format!("model: sides with {base_name}, so {name} is the odd one out"), + (false, true) => format!("model: sides with {name}, so {base_name} is the odd one out"), + (false, false) => format!( + "model: agrees with neither -- {}", + shape::show_values(model) + ), + } +} + +/// Signatures are prefixed with the value type, so the two instantiations never +/// collide in one report and the difference between them is readable directly. +pub fn signature(class: &str, rest: &str) -> String { + format!("{}:{class}:{rest}", V::NAME) +} + +fn route_key(r: Route) -> String { match r { Route::Pointwise(k) => format!("pw{k}"), _ => r.name(&Expr::Var(0)), @@ -491,8 +524,9 @@ pub struct Known { /// drops root values outright. These are routes disagreeing with the /// baseline in the ordinary way. /// -/// 4. **Dangling paths** (`dangling`). Routes that graft whole subtries keep -/// structure that routes walking path by path do not. Unsettled rather than +/// 4. **Dangling paths** (`dangling`). The lockstep traversals in +/// `experimental::zipper_algebra` discard dangling structure; `PathMap`'s +/// whole-map operations and the write-zipper forms preserve it. Unsettled rather than /// wrong -- see `../SPEC_WARTS.md` -- hence its own class, `shape`, which /// does not fail a run unless `--shape` says so. /// @@ -500,75 +534,145 @@ pub struct Known { /// algebraic defect: it fires while the operands are still being written, /// before any operation runs, which is what the `build` in its signature /// means. -const BIAS: &str = "value bias by node layout (repro 3)"; +const BIAS: &str = "value bias by node layout, u64-only (repro 3)"; const LOSS: &str = "join loses a value across shared structure (repro 4)"; const ROOT: &str = "write-zipper forms lose root values (repros 1, 2)"; -const DANGLING: &str = "dangling-path treatment differs by route"; +const DANGLING: &str = "zipper traversals drop dangling paths, map ops keep them (repro 7)"; const MERKLEIZE: &str = "merkleize panics on dangling-only structure (repro 5)"; /// Re-nesting a join moves which operand is on the left *and* which pair of /// tries meets a shared node first, so both cause 1 and cause 2 reach these. +/// Under the lawful type only cause 2 survives, which is why the counts collapse. const BIAS_OR_LOSS: &str = "value bias or lost value (repros 3, 4)"; - pub const KNOWN: &[Known] = &[ - // Routes disagreeing with the baseline: `join_into` and `meet_2` losing - // root values, plus the baseline's own bias showing up as the zipper routes - // "disagreeing" with it. - Known { signature: "values:pw1", cause: ROOT }, - Known { signature: "values:pw2", cause: ROOT }, - Known { signature: "values:pw3", cause: ROOT }, - Known { signature: "values:pw4", cause: BIAS }, - Known { signature: "values:pw5", cause: BIAS }, - Known { signature: "values:ternary", cause: BIAS }, - Known { signature: "values:nary", cause: BIAS }, - Known { signature: "values:nary_poly", cause: BIAS }, - Known { signature: "values:dnf", cause: BIAS }, - // The reference model has no trie and no bias, so it disagrees with the - // baseline exactly where the baseline is wrong. - Known { signature: "values:model", cause: BIAS }, - // Dangling structure. - Known { signature: "shape:pw1", cause: DANGLING }, - Known { signature: "shape:pw2", cause: DANGLING }, - Known { signature: "shape:pw3", cause: DANGLING }, - Known { signature: "shape:pw4", cause: DANGLING }, - Known { signature: "shape:pw5", cause: DANGLING }, - Known { signature: "shape:ternary", cause: DANGLING }, - Known { signature: "shape:nary", cause: DANGLING }, - Known { signature: "shape:nary_poly", cause: DANGLING }, - Known { signature: "shape:dnf", cause: DANGLING }, - // Laws. Every value-level lattice law that puts the operands on different - // sides of a join or meet is sensitive to cause 1. - Known { signature: "law:join-associative", cause: BIAS_OR_LOSS }, - Known { signature: "law:meet-associative", cause: BIAS }, - Known { signature: "law:join-distributes-over-meet", cause: BIAS }, - Known { signature: "law:meet-distributes-over-join", cause: BIAS }, - Known { signature: "law:absorb-join-meet", cause: BIAS }, - Known { signature: "law:absorb-meet-join", cause: BIAS }, - Known { signature: "law:sym-diff-is-join-minus-meet", cause: BIAS }, - // Join associativity again, with meets for leaves. Reached by cause 2: - // `a & b` over an all-dangling `b` is a dangling-only trie, and joining - // that with a trie carrying values below the same paths loses them -- the - // same shape as repro 4. - Known { signature: "law:majority-is-pairwise-meets", cause: BIAS_OR_LOSS }, - // Commutativity is checked on paths only, so a bias cannot break it -- only - // a lost path can. This is cause 2, and the only law that detects it. - Known { signature: "law:join-commutative", cause: LOSS }, - Known { signature: "panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - // Debug-assertions builds only, and the sharpest view of cause 2 there is: - // joining a list node into a dense node reports `AlgebraicStatus::None` - // -- an empty result -- from two nodes that are not empty, which is the - // mechanism by which `a | b` loses a value in repro 4. - Known { signature: "panic:eval:line_list_node.rs:2669", cause: LOSS }, - // The same defect at a different node type: joining two dense nodes, a - // cofree `pjoin` returns `None` while the left side still has a non-empty - // onward node, so the join discards that subtrie. Where the subtrie holds - // values this is repro 4; where it holds only dangling paths the loss is - // invisible to a release build, which is why debug assertions are a mode of - // their own. - Known { signature: "panic:eval:dense_byte_node.rs:2080", cause: LOSS }, - // `merge_from_list_node` returning `None` again, from `join_into_dyn` this - // time. Three assertion sites, one story: join's "the result is empty" - // path is reachable from nodes that are not empty. - Known { signature: "panic:eval:line_list_node.rs:2720", cause: LOSS }, + // ---------------------------------------------------------------- u64 + // Root values lost by the write-zipper forms. Value-type-independent. + Known { signature: "u64:values:pw1", cause: ROOT }, + Known { signature: "u64:values:pw2", cause: ROOT }, + Known { signature: "u64:values:pw3", cause: ROOT }, + // Everything below here on the u64 side is the bias, which the lawful type + // mostly cannot see: under a commutative join, picking the wrong operand + // only shows where one operand already contains the other. + Known { signature: "u64:values:pw4", cause: BIAS }, + Known { signature: "u64:values:pw5", cause: BIAS }, + Known { signature: "u64:values:ternary", cause: BIAS }, + Known { signature: "u64:values:nary", cause: BIAS }, + Known { signature: "u64:values:nary_poly", cause: BIAS }, + Known { signature: "u64:values:dnf", cause: BIAS }, + Known { signature: "u64:values:model", cause: BIAS }, + Known { signature: "u64:shape:pw1", cause: DANGLING }, + Known { signature: "u64:shape:pw2", cause: DANGLING }, + Known { signature: "u64:shape:pw3", cause: DANGLING }, + Known { signature: "u64:shape:pw4", cause: DANGLING }, + Known { signature: "u64:shape:pw5", cause: DANGLING }, + Known { signature: "u64:shape:ternary", cause: DANGLING }, + Known { signature: "u64:shape:nary", cause: DANGLING }, + Known { signature: "u64:shape:nary_poly", cause: DANGLING }, + Known { signature: "u64:shape:dnf", cause: DANGLING }, + Known { signature: "u64:law:join-associative", cause: BIAS_OR_LOSS }, + Known { signature: "u64:law:join-distributes-over-meet", cause: BIAS_OR_LOSS }, + Known { signature: "u64:law:majority-is-pairwise-meets", cause: BIAS_OR_LOSS }, + Known { signature: "u64:law:join-commutative", cause: LOSS }, + // These four fire only for u64: they need join and meet to be different + // functions, and for u64 they are the same one. + Known { signature: "u64:law:meet-associative", cause: BIAS }, + Known { signature: "u64:law:meet-distributes-over-join", cause: BIAS }, + Known { signature: "u64:law:absorb-join-meet", cause: BIAS }, + Known { signature: "u64:law:sym-diff-is-join-minus-meet", cause: BIAS }, + Known { signature: "u64:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, + Known { signature: "u64:panic:eval:line_list_node.rs:2669", cause: LOSS }, + Known { signature: "u64:panic:eval:line_list_node.rs:2720", cause: LOSS }, + Known { signature: "u64:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + + // ---------------------------------------------------------------- bits + // The lawful type. Everything here is a real defect: there is no value + // bias to blame, because `a | b` does not depend on operand order. + Known { signature: "bits:values:pw1", cause: ROOT }, + Known { signature: "bits:values:pw2", cause: ROOT }, + Known { signature: "bits:values:pw3", cause: ROOT }, + Known { signature: "bits:values:pw5", cause: ROOT }, + // Rare under the lawful type, and cause 2 every time: the law residues all + // shrink to a value present on one side of an identity and absent on the + // other, which is a lost value rather than a misplaced one. + Known { signature: "bits:values:pw4", cause: LOSS }, + // Fires about once per three million cases for each lawful type, and the + // model sides with the route, so it is the baseline that lost the value. + Known { signature: "bits:values:ternary", cause: LOSS }, + Known { signature: "bits:values:nary", cause: LOSS }, + Known { signature: "bits:values:nary_poly", cause: LOSS }, + Known { signature: "bits:values:dnf", cause: LOSS }, + Known { signature: "bits:values:model", cause: LOSS }, + Known { signature: "bits:shape:pw1", cause: DANGLING }, + Known { signature: "bits:shape:pw2", cause: DANGLING }, + Known { signature: "bits:shape:pw3", cause: DANGLING }, + Known { signature: "bits:shape:pw4", cause: DANGLING }, + Known { signature: "bits:shape:pw5", cause: DANGLING }, + Known { signature: "bits:shape:ternary", cause: DANGLING }, + Known { signature: "bits:shape:nary", cause: DANGLING }, + Known { signature: "bits:shape:nary_poly", cause: DANGLING }, + Known { signature: "bits:shape:dnf", cause: DANGLING }, + Known { signature: "bits:law:join-associative", cause: LOSS }, + Known { signature: "bits:law:join-commutative", cause: LOSS }, + Known { signature: "bits:law:join-distributes-over-meet", cause: LOSS }, + Known { signature: "bits:law:sym-diff-is-join-minus-meet", cause: LOSS }, + Known { signature: "bits:law:majority-is-pairwise-meets", cause: LOSS }, + Known { signature: "bits:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, + Known { signature: "bits:panic:eval:line_list_node.rs:2669", cause: LOSS }, + Known { signature: "bits:panic:eval:line_list_node.rs:2720", cause: LOSS }, + Known { signature: "bits:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + // ---------------------------------------------------------------- unit + // `PathMap<()>`: the set case, and lawful. Nothing here can be a value + // bias, because there is no value to misplace -- so every entry is either a + // lost path or the dangling-path question. It confirms the real defects + // independently of `bits`. + Known { signature: "unit:values:pw1", cause: ROOT }, + Known { signature: "unit:values:pw2", cause: ROOT }, + Known { signature: "unit:values:pw3", cause: ROOT }, + Known { signature: "unit:values:pw5", cause: ROOT }, + Known { signature: "unit:values:pw4", cause: LOSS }, + Known { signature: "unit:values:nary", cause: LOSS }, + Known { signature: "unit:values:nary_poly", cause: LOSS }, + Known { signature: "unit:values:dnf", cause: LOSS }, + Known { signature: "unit:values:model", cause: LOSS }, + Known { signature: "unit:shape:pw1", cause: DANGLING }, + Known { signature: "unit:shape:pw2", cause: DANGLING }, + Known { signature: "unit:shape:pw3", cause: DANGLING }, + Known { signature: "unit:shape:pw4", cause: DANGLING }, + Known { signature: "unit:shape:pw5", cause: DANGLING }, + Known { signature: "unit:shape:ternary", cause: DANGLING }, + Known { signature: "unit:shape:nary", cause: DANGLING }, + Known { signature: "unit:shape:nary_poly", cause: DANGLING }, + Known { signature: "unit:shape:dnf", cause: DANGLING }, + Known { signature: "unit:law:join-associative", cause: LOSS }, + Known { signature: "unit:law:join-commutative", cause: LOSS }, + Known { signature: "unit:law:join-distributes-over-meet", cause: LOSS }, + Known { signature: "unit:law:sym-diff-is-join-minus-meet", cause: LOSS }, + Known { signature: "unit:law:majority-is-pairwise-meets", cause: LOSS }, + Known { signature: "unit:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, + Known { signature: "unit:panic:eval:line_list_node.rs:2669", cause: LOSS }, + Known { signature: "unit:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + // Fires roughly once per million random cases, and the corpus reproduces it + // for all three types. + Known { signature: "unit:panic:eval:line_list_node.rs:2720", cause: LOSS }, + // Two laws that fire only under `unit`, both once per couple of million + // cases, and both cause 2. `unit` reaches it where the other types do not + // because every value is identical, so `merkleize` and `clone` share far + // more structure and the dangling-only operand that triggers the loss is + // easier to generate. + Known { signature: "unit:law:meet-distributes-over-join", cause: LOSS }, + // One of the four identities that are only checked for a lawful value type. + // It failing is still cause 2, not a bad identity: the shrunk case has a + // dangling-only `b` and a `c` that is `b` plus one value, so `b | c` is + // exactly repro 4. + Known { signature: "unit:law:subtract-over-join", cause: LOSS }, + Known { signature: "unit:values:ternary", cause: LOSS }, + + // Of the four identities in `laws::lawful_only` -- checked only for a lawful + // value type -- three have never failed: subtract-over-meet, + // subtract-is-subtract-meet and sym-diff-associative. They are the + // strongest laws the harness has, and they are deliberately absent from this + // table so that one of them firing is news. The fourth, + // subtract-over-join, fires once per couple of million cases under `unit`, + // and is cause 2 rather than a bad identity. ]; pub fn known(signature: &str) -> Option<&'static Known> { @@ -655,8 +759,8 @@ fn panic_msg(e: Box) -> (String, String) { /// /// Two `catch_unwind`s rather than one, so a crash can say which phase it was /// in. The case has to outlive the first, hence the separation. -pub fn run(bytes: &[u8]) -> Outcome { - let case = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode(bytes))) { +pub fn run(bytes: &[u8]) -> Outcome { + let case = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode::(bytes))) { Err(e) => { let (site, msg) = panic_msg(e); return Outcome::Panicked(Phase::Build, site, msg); @@ -675,16 +779,67 @@ pub fn run(bytes: &[u8]) -> Outcome { /// Signatures an input produces: the grouping keys, without the detail. Also /// the invariant the shrinker preserves. -pub fn signatures(bytes: &[u8]) -> Vec { - match run(bytes) { +/// Every value type the fuzzer runs, by name. +/// +/// This list and [`run_all`] are the only two places that know which types +/// exist; the driver stays generic over them and reads the type back off a +/// signature's first field. +pub const VALUE_TYPES: &[&str] = &[ + ::NAME, + ::NAME, + <() as FuzzValue>::NAME, +]; + +/// Run one input under every value type. +/// +/// Both, every time, and that is the point: a finding under `u64` and not under +/// `bits` is an artefact of `u64`'s degenerate lattice instance, and one under +/// both -- or under `bits` alone -- is a defect in the crate. Checking only the +/// lawful type would be cheaper and would lose the comparison. +pub fn run_all(bytes: &[u8], f: &mut impl FnMut(&'static str, Outcome)) { + f(::NAME, run::(bytes)); + f(::NAME, run::(bytes)); + f(<() as FuzzValue>::NAME, run::<()>(bytes)); +} + +/// Signatures of one outcome, which for a panic has to be built here because +/// the phase and site are not a `Divergence`. +pub fn outcome_signatures(type_name: &str, outcome: &Outcome) -> Vec { + match outcome { Outcome::Clean => Vec::new(), - Outcome::Diverged(d) => d.into_iter().map(|d| d.signature).collect(), - Outcome::Panicked(p, site, _) => vec![panic_signature(p, &site)], + Outcome::Diverged(d) => d.iter().map(|d| d.signature.clone()).collect(), + Outcome::Panicked(p, site, _) => vec![panic_signature(type_name, *p, site)], } } -pub fn panic_signature(phase: Phase, site: &str) -> String { - format!("panic:{}:{site}", phase.tag()) +pub fn panic_signature(type_name: &str, phase: Phase, site: &str) -> String { + format!("{type_name}:panic:{}:{site}", phase.tag()) +} + +/// Every signature an input produces, across all value types. Also the +/// invariant the shrinker preserves. +pub fn signatures(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + run_all(bytes, &mut |name, outcome| { + out.extend(outcome_signatures(name, &outcome)); + }); + out +} + +/// The value type named in a signature's first field. +pub fn value_type_of(signature: &str) -> &str { + signature.split(':').next().unwrap_or("") +} + +/// Render a case under the value type named by `type_name`. +pub fn describe_as(type_name: &str, bytes: &[u8]) -> String { + if type_name == ::NAME { + describe(&decode::(bytes)) + } else if type_name == <() as FuzzValue>::NAME { + describe(&decode::<()>(bytes)) + } else { + describe(&decode::(bytes)) + } } /// Reproducible input generation, so a seed names a run. @@ -720,12 +875,13 @@ impl Rng { } /// Human-readable rendering of a case, for a failure report and for replay. -pub fn describe(case: &Case) -> String { +pub fn describe(case: &Case) -> String { let mut s = String::new(); + s.push_str(&format!("values: {}\n", V::NAME)); s.push_str(&format!("expr: {}\n", case.expr)); s.push_str(&format!("alphabet: {}\n", case.alphabet)); for (i, (m, b)) in case.operands.iter().zip(&case.builds).enumerate() { - let sh: Shape = shape_of_map(m); + let sh: Shape = shape_of_map(m); s.push_str(&format!( "operand {}: {:?}\n {}\n", (b'a' + i as u8) as char, @@ -737,7 +893,7 @@ pub fn describe(case: &Case) -> String { } /// Values of each operand, for a report that only needs the settled part. -pub fn operand_values(case: &Case) -> Vec { +pub fn operand_values(case: &Case) -> Vec> { case.operands .iter() .map(|m| shape::values_of_shape(&shape_of_map(m))) diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs index 0bfa660f..221991fb 100644 --- a/differential/src/algebraic/laws.rs +++ b/differential/src/algebraic/laws.rs @@ -10,31 +10,30 @@ //! machinery, which keeps this file declarative and means a law automatically //! inherits whatever the expression evaluator can do. //! -//! # Why some laws are checked on paths only +//! # Strength depends on the value type //! -//! `u64`'s lattice instances are left-biased: `pjoin` keeps the left value when -//! the two differ, and `pmeet` keeps the left value *unconditionally*. Several -//! textbook identities therefore hold as statements about which paths survive -//! but not about which value lands on them, and asserting values there would -//! report a divergence that is correct behaviour. Each such law says so. +//! [`laws`] is parameterised by the value type, and returns a *stronger* set for +//! one whose instances actually form a distributive lattice with a relative +//! complement -- see [`FuzzValue::LAWFUL`]. Three things change: //! -//! # Identities deliberately absent +//! * The laws marked [`Level::Paths`] are promoted to [`Level::Values`]. They +//! are weakened for `u64` only because its `pjoin` and `pmeet` both return the +//! left operand, so swapping the operands swaps the result's value and +//! commutativity cannot hold on values there. //! -//! Three plausible-looking ones are not laws under these value semantics, and -//! are listed here so nobody adds them back as "obviously true": +//! * Three further identities are added, listed in [`lawful_only`]. They are +//! laws in any distributive lattice and fail for `u64`, again because join and +//! meet have collapsed into one function. //! -//! * `a - (b | c) == (a - b) & (a - c)`. `b | c` carries `b`'s value where -//! both are present, so the left side keeps a path whose value matches `c` -//! but not `b`, while the right side drops it. -//! * `a - b == a - (a & b)`. `a & b` carries *`a`'s* value, so the right side -//! drops every shared path regardless of value, while the left side drops -//! only the ones whose values are equal. -//! * `(a ^ b) ^ c == a ^ (b ^ c)` on values. A path present in all three -//! cancels in the inner operation either way, so the left side ends up with -//! `c`'s value and the right side with `a`'s. Associative on paths, which is -//! what is checked. +//! * Symmetric difference becomes associative on values, not merely on paths. +//! +//! So the difference between the two sets is a measurement: a law that holds for +//! `bits` and fails for `u64` is telling you about `u64`, and one that fails for +//! `bits` is telling you about the crate. That split is the whole reason for +//! running both. use super::expr::{Expr, Op}; +use super::value::FuzzValue; /// Operand slot holding the empty trie, appended after the case's own /// operands so identities can mention it. See [`LAW_OPERANDS`]. @@ -78,7 +77,23 @@ fn r(a: Expr, b: Expr) -> Expr { Expr::bin(Op::Restrict, a, b) } -pub fn laws() -> Vec { +/// The laws to check for value type `V`. +/// +/// For a lawful `V` every `Paths` level is promoted to `Values` and +/// [`lawful_only`] is appended. +pub fn laws() -> Vec { + let mut out = base(); + if V::LAWFUL { + for law in &mut out { + law.level = Level::Values; + } + out.extend(lawful_only()); + } + out +} + +/// Identities that hold whatever the value type. +fn base() -> Vec { use Level::{Paths, Values}; let (a, b, c, e) = (0usize, 1usize, 2usize, EMPTY); vec![ @@ -87,12 +102,13 @@ pub fn laws() -> Vec { Law { name: "meet-idempotent", lhs: m(v(a), v(a)), rhs: v(a), level: Values }, Law { name: "join-unit", lhs: j(v(a), v(e)), rhs: v(a), level: Values }, Law { name: "meet-zero", lhs: m(v(a), v(e)), rhs: v(e), level: Values }, - // Commutative in path set only: the left value wins in both `pjoin` and - // `pmeet`, so swapping the operands swaps which value lands. + // Path set only: both `pjoin` and `pmeet` return the left operand, so + // swapping the operands swaps which value lands. A real lattice would + // make these value-level laws; see the module comment. Law { name: "join-commutative", lhs: j(v(a), v(b)), rhs: j(v(b), v(a)), level: Paths }, Law { name: "meet-commutative", lhs: m(v(a), v(b)), rhs: m(v(b), v(a)), level: Paths }, - // Associativity *does* hold on values: left bias makes both nestings - // select the leftmost present operand's value. + // Associativity does hold on values even here: both nestings select the + // leftmost present operand's value. Law { name: "join-associative", lhs: j(j(v(a), v(b)), v(c)), @@ -180,3 +196,48 @@ pub fn laws() -> Vec { }, ] } + +/// Identities that need the value type to be a real distributive lattice with a +/// relative complement. +/// +/// Each of these fails for `u64`, and each failure is explained by the same +/// thing: `pjoin` and `pmeet` both return the left operand, so `a | b == a & b`, +/// and `psubtract` is `None` exactly on equality. +fn lawful_only() -> Vec { + use Level::Values; + let (a, b, c) = (0usize, 1usize, 2usize); + vec![ + // De Morgan for relative complement. Fails for `u64` because `b | c` + // carries `b`'s value where both are present, so the left side keeps a + // path whose value matches `c` but not `b`. + Law { + name: "subtract-over-join", + lhs: s(v(a), j(v(b), v(c))), + rhs: m(s(v(a), v(b)), s(v(a), v(c))), + level: Values, + }, + Law { + name: "subtract-over-meet", + lhs: s(v(a), m(v(b), v(c))), + rhs: j(s(v(a), v(b)), s(v(a), v(c))), + level: Values, + }, + // Subtracting the overlap is the same as subtracting the whole. Fails + // for `u64` because `a & b` carries *`a`'s* value, so the right side + // drops every shared path rather than only the equal ones. + Law { + name: "subtract-is-subtract-meet", + lhs: s(v(a), v(b)), + rhs: s(v(a), m(v(a), v(b))), + level: Values, + }, + // Symmetric difference is the XOR of a Boolean ring, so it is + // associative on values and not merely on paths. + Law { + name: "sym-diff-associative", + lhs: x(x(v(a), v(b)), v(c)), + rhs: x(v(a), x(v(b), v(c))), + level: Values, + }, + ] +} diff --git a/differential/src/algebraic/model.rs b/differential/src/algebraic/model.rs index 35972224..c987be6d 100644 --- a/differential/src/algebraic/model.rs +++ b/differential/src/algebraic/model.rs @@ -1,36 +1,37 @@ -//! Value-level reference semantics, as a fourth opinion. +//! Flat reference semantics, as a fourth opinion. //! -//! The routes in `routes.rs` all go through `pathmap`, so a defect common to -//! the whole algebra layer would make them agree with each other and still be -//! wrong. This module computes the same expression over a plain -//! `BTreeMap, u64>` with no trie involved, which gives the comparison -//! something to anchor against. +//! Every route in `routes.rs` goes through `pathmap`, so a defect common to the +//! whole algebra layer would make them agree with each other and still be wrong. +//! This computes the same expression over a plain `BTreeMap, V>` with no +//! trie involved, which gives the comparison something to anchor against. //! -//! It deliberately models only *which path carries which value* and abstains -//! on structure: a flat map cannot represent a dangling path, and whether a -//! dangling path survives an operation is unsettled in the crate (see -//! `../../SPEC_WARTS.md`). `shape.rs` explains the split. +//! It models only *which path carries which value* and abstains on structure: a +//! flat map cannot represent a dangling path, and whether a dangling path +//! survives an operation is unsettled in the crate. `shape.rs` explains the +//! split. //! -//! The semantics below are the ones `u64`'s lattice instances in -//! `pathmap::ring` actually define, not the ones set notation would suggest: +//! # The value algebra is not restated here //! -//! * `pjoin` is left-biased, so a join keeps the left value where both sides -//! have one. Join is therefore **not** commutative in its values, only in -//! its path set. -//! * `pmeet` returns `Identity(SELF_IDENT)` unconditionally, so a meet also -//! keeps the left value -- even where the two values differ. -//! * `psubtract` is `None` when the values are equal and the left value -//! otherwise, so subtracting a path whose value differs is a no-op. -//! * symmetric difference cancels *any* pair of values at a coincident path. -//! That follows from the two above rather than from parity of presence: with -//! `pjoin` and `pmeet` both `Identity`, `SymDiff::combine_impl` reaches -//! `join == meet` for distinct values and `subtract_impl(a, b)` with `a == -//! b` for equal ones, and both yield nothing. +//! Each operation delegates to the value type's own `pjoin`, `pmeet` or +//! `psubtract` through the `Option` impls in `pathmap::ring`. An earlier +//! version spelled out `u64`'s behaviour by hand -- left-biased join, left-biased +//! meet, subtract-on-equality -- which worked only because it happened to match, +//! and which meant the model was asserting the harness author's idea of the +//! algebra rather than the type's. Delegating means this file is correct for +//! any [`FuzzValue`] without changes, and that a disagreement between the model +//! and a route is always about *where a value ends up*, never about what +//! combining two values means. +//! +//! What remains genuinely this file's own is the set structure: which paths an +//! operation visits at all, and `restrict`, which is not a lattice operation. + +use pathmap::ring::{DistributiveLattice, Lattice}; use super::expr::{Expr, Op}; use super::shape::Values; +use super::value::{resolve, FuzzValue}; -pub fn eval(e: &Expr, operands: &[Values]) -> Values { +pub fn eval(e: &Expr, operands: &[Values]) -> Values { match e { Expr::Var(i) => operands[*i].clone(), Expr::Bin(op, l, r) => { @@ -41,7 +42,7 @@ pub fn eval(e: &Expr, operands: &[Values]) -> Values { } } -pub fn apply(op: Op, a: &Values, b: &Values) -> Values { +pub fn apply(op: Op, a: &Values, b: &Values) -> Values { match op { Op::Join => join(a, b), Op::Meet => meet(a, b), @@ -51,56 +52,63 @@ pub fn apply(op: Op, a: &Values, b: &Values) -> Values { } } -/// Union of paths; the left value wins where both sides have one. -pub fn join(a: &Values, b: &Values) -> Values { - let mut out = b.clone(); - for (k, v) in a { - out.insert(k.clone(), *v); +/// Every path either side mentions. +fn keys(a: &Values, b: &Values) -> Vec> { + let mut k: Vec> = a.keys().chain(b.keys()).cloned().collect(); + k.sort(); + k.dedup(); + k +} + +/// Combine both sides pointwise with one of the value operations, dropping the +/// paths where the result is bottom. +fn pointwise(a: &Values, b: &Values, f: F) -> Values +where + F: Fn(&Option, &Option) -> Option, +{ + let mut out = Values::new(); + for k in keys(a, b) { + let (lv, rv) = (a.get(&k).cloned(), b.get(&k).cloned()); + if let Some(v) = f(&lv, &rv) { + out.insert(k, v); + } } out } -/// Paths present in both; the left value, even when the two differ. -pub fn meet(a: &Values, b: &Values) -> Values { - a.iter() - .filter(|(k, _)| b.contains_key(*k)) - .map(|(k, v)| (k.clone(), *v)) - .collect() +pub fn join(a: &Values, b: &Values) -> Values { + pointwise(a, b, |l, r| resolve(l.pjoin(r), l, r)) } -/// Left paths, dropping only those the right side carries the *same* value at. -pub fn subtract(a: &Values, b: &Values) -> Values { - a.iter() - .filter(|(k, v)| b.get(*k) != Some(*v)) - .map(|(k, v)| (k.clone(), *v)) - .collect() +pub fn meet(a: &Values, b: &Values) -> Values { + pointwise(a, b, |l, r| resolve(l.pmeet(r), l, r)) } -/// Paths present in exactly one side. Coincident paths cancel whatever their -/// values; see the module comment. -pub fn sym_diff(a: &Values, b: &Values) -> Values { - let mut out = Values::new(); - for (k, v) in a { - if !b.contains_key(k) { - out.insert(k.clone(), *v); - } - } - for (k, v) in b { - if !a.contains_key(k) { - out.insert(k.clone(), *v); - } - } - out +pub fn subtract(a: &Values, b: &Values) -> Values { + pointwise(a, b, |l, r| resolve(l.psubtract(r), l, r)) +} + +/// `(a | b) \ (a & b)`, the definition `zipper_sym_diff`'s own documentation +/// gives. +/// +/// In a distributive lattice with a relative complement this equals +/// `(a \ b) | (b \ a)`, and `laws.rs` checks that -- for a lawful value type it +/// is a law, and for `u64` the two differ, which is a fact about `u64` rather +/// than about symmetric difference. +pub fn sym_diff(a: &Values, b: &Values) -> Values { + subtract(&join(a, b), &meet(a, b)) } /// Left paths that some path-to-a-value in the right side is a prefix of. /// -/// The prefix is inclusive at both ends: the empty path counts, so a root value -/// in `b` admits all of `a`, and `k` counts as a prefix of itself. Both follow -/// from the note on `PathMap::restrict`. -pub fn restrict(a: &Values, b: &Values) -> Values { +/// Not a lattice operation, so there is nothing to delegate to: the value is +/// carried across unchanged, and only the path set is decided. The prefix is +/// inclusive at both ends -- the empty path counts, so a root value in `b` +/// admits all of `a`, and `k` counts as a prefix of itself -- both of which +/// follow from the note on `PathMap::restrict`. +pub fn restrict(a: &Values, b: &Values) -> Values { a.iter() .filter(|(k, _)| (0..=k.len()).any(|n| b.contains_key(&k[..n]))) - .map(|(k, v)| (k.clone(), *v)) + .map(|(k, v)| (k.clone(), v.clone())) .collect() } diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs index 7b45a894..277a9d6d 100644 --- a/differential/src/algebraic/routes.rs +++ b/differential/src/algebraic/routes.rs @@ -37,6 +37,7 @@ use pathmap::zipper::{ use super::expr::{Expr, Op}; use super::model; use super::shape::{shape_of_map, shape_of_zipper, values_of_shape, Shape, Values, ESCAPED_ROOT, TRUNCATED}; +use super::value::FuzzValue; /// Names of the per-operator strategies, in the order route `k % n` indexes /// them. Kept as tables so a route's name can say which strategy it used for @@ -48,6 +49,16 @@ pub const SUBTRACT_STRATEGIES: &[&str] = &["map", "subtract_into", "zipper_subtr pub const SYM_DIFF_STRATEGIES: &[&str] = &["zipper_sym_diff", "join_minus_meet"]; pub const RESTRICT_STRATEGIES: &[&str] = &["map", "wz_restrict"]; +/// The strategy table is the same for every value type, so route `k` means the +/// same thing under each of them. +/// +/// That matters more than it looks. An earlier version shortened the join table +/// for value types that cannot use the `OverlayZipper` strategy, which silently +/// renumbered every later route -- so `pw4` and `pw5` meant different strategy +/// mixes under `u64` and under `bits`, and comparing their findings across the +/// two types was comparing different things. A strategy that does not apply to +/// a value type now *declines* instead, which leaves the numbering alone and +/// simply makes that route absent for that type. pub fn strategies(op: Op) -> &'static [&'static str] { match op { Op::Join => JOIN_STRATEGIES, @@ -83,7 +94,13 @@ pub enum Route { impl Route { pub fn all() -> Vec { let mut v: Vec = (0..POINTWISE_ROUTES).map(Route::Pointwise).collect(); - v.extend([Route::Ternary, Route::Nary, Route::NaryPoly, Route::Dnf, Route::Model]); + v.extend([ + Route::Ternary, + Route::Nary, + Route::NaryPoly, + Route::Dnf, + Route::Model, + ]); v } @@ -126,13 +143,13 @@ fn collect_ops(e: &Expr, out: &mut Vec) { /// What a route produced. `shape` is `None` for a route that cannot represent /// dangling paths, which is only [`Route::Model`]. -pub struct Outcome { - pub values: Values, - pub shape: Option, +pub struct Outcome { + pub values: Values, + pub shape: Option>, } -impl Outcome { - fn from_map(m: &PathMap) -> Outcome { +impl Outcome { + fn from_map(m: &PathMap) -> Outcome { let shape = shape_of_map(m); Outcome { values: values_of_shape(&shape), shape: Some(shape) } } @@ -140,15 +157,15 @@ impl Outcome { /// Evaluate `e` over `operands` by `route`, or `None` if the route does not /// apply to this expression's shape. -pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Option { +pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Option> { match route { - Route::Pointwise(k) => Some(Outcome::from_map(&pointwise(k, e, operands))), + Route::Pointwise(k) => pointwise(k, e, operands).map(|m| Outcome::from_map(&m)), Route::Ternary => ternary(e, operands).map(|m| Outcome::from_map(&m)), Route::Nary => nary(e, operands, false).map(|m| Outcome::from_map(&m)), Route::NaryPoly => nary(e, operands, true).map(|m| Outcome::from_map(&m)), Route::Dnf => dnf(e, operands).map(|m| Outcome::from_map(&m)), Route::Model => { - let vals: Vec = + let vals: Vec> = operands.iter().map(|m| values_of_shape(&shape_of_map(m))).collect(); Some(Outcome { values: model::eval(e, &vals), shape: None }) } @@ -157,12 +174,14 @@ pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Option]) -> PathMap { +/// `None` when the strategy route `k` selects for some operator in `e` does not +/// apply to this value type. +fn pointwise(k: usize, e: &Expr, operands: &[PathMap]) -> Option> { match e { - Expr::Var(i) => operands[*i].clone(), + Expr::Var(i) => Some(operands[*i].clone()), Expr::Bin(op, l, r) => { - let a = pointwise(k, l, operands); - let b = pointwise(k, r, operands); + let a = pointwise(k, l, operands)?; + let b = pointwise(k, r, operands)?; apply(*op, k, &a, &b) } } @@ -170,9 +189,9 @@ fn pointwise(k: usize, e: &Expr, operands: &[PathMap]) -> PathMap { /// One operator, one strategy. Every arm is a different code path in the /// crate, not a different way of calling the same one. -pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap { +pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> Option> { let n = strategies(op).len(); - match (op, k % n) { + Some(match (op, k % n) { // -- join (Op::Join, 0) => a.join(b), (Op::Join, 1) => { @@ -194,7 +213,7 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap { // Consumes the source. `prune = false` keeps whatever dangling // structure the operation leaves, so this route is comparable with - // the grafting ones rather than silently tidier than them. + // the other write-zipper forms rather than silently tidier. let mut out = a.clone(); let mut src = b.clone(); { @@ -215,11 +234,17 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap { + // Declines rather than answering wrongly: see + // `FuzzValue::JOIN_PICKS_LEFT`. + if !V::JOIN_PICKS_LEFT { + return None; + } // `OverlayZipper`'s default mapping is `a.or(b)`, which is the same - // left bias `u64`'s `pjoin` has, so the virtual trie it walks - // should be exactly the join. It never builds a trie, so it has to - // be materialised to be composed into a larger expression; the walk - // records dangling paths too, so nothing is lost in the round trip. + // bias a left-picking `pjoin` has, so for such a value type the + // virtual trie it walks is exactly the join. Only reachable when + // `V::JOIN_PICKS_LEFT`; see `strategies`. It never builds a trie, so + // it has to be materialised to be composed into a larger expression; + // the walk records dangling paths too, so nothing is lost. let overlay = OverlayZipper::new(a.read_zipper(), b.read_zipper()); materialize(overlay) } @@ -308,7 +333,7 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap unreachable!("strategy index out of range for {op:?}"), - } + }) } /// Walk a zipper over a virtual trie and build the real trie it describes. @@ -316,9 +341,9 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) -> PathMap(mut z: Z) -> PathMap +fn materialize(mut z: Z) -> PathMap where - Z: ZipperMoving + ZipperPath + ZipperValues, + Z: ZipperMoving + ZipperPath + ZipperValues, { let shape = shape_of_zipper(&mut z); let mut out = PathMap::new(); @@ -332,7 +357,7 @@ where wz.descend_to(p); match v { Some(v) => { - wz.set_val(*v); + wz.set_val(v.clone()); } None => { wz.create_path(); @@ -346,7 +371,7 @@ where // -------------------------------------------------------- whole-expression /// Chain of exactly three operands through the `*3` entry points. -fn ternary(e: &Expr, operands: &[PathMap]) -> Option> { +fn ternary(e: &Expr, operands: &[PathMap]) -> Option> { let (op, idx) = e.chain()?; if idx.len() != 3 { return None; @@ -375,7 +400,7 @@ fn ternary(e: &Expr, operands: &[PathMap]) -> Option> { /// array) and the tuple form (`ZipperMergeF::*_n`, which routes through the /// `PolyZipper`-derived enum). They are separate monomorphisations of the /// merge engine and are worth distinguishing, so `poly` selects between them. -fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> { +fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> { let (op, idx) = e.chain()?; if op == Op::Restrict { return None; @@ -388,7 +413,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> // run time. The tuple form additionally has one impl per arity. macro_rules! slice_arm { ($n:literal) => {{ - let mut zs: [ReadZipperUntracked<'_, '_, u64>; $n] = + let mut zs: [ReadZipperUntracked<'_, '_, V>; $n] = core::array::from_fn(|i| operands[idx[i]].read_zipper()); match op { Op::Join => zipper_n_join(&mut zs, &mut wz), @@ -435,7 +460,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> /// becomes a two-zipper call with the masks renumbered, not a four-zipper call /// with two unused slots -- an unused slot would change what the traversal /// prunes on and make the route test something else. -fn dnf(e: &Expr, operands: &[PathMap]) -> Option> { +fn dnf(e: &Expr, operands: &[PathMap]) -> Option> { let clauses = e.dnf()?; let vars = e.vars(); if vars.is_empty() || vars.len() > super::expr::MAX_VARS || clauses.len() > super::expr::MAX_CLAUSES { @@ -457,7 +482,7 @@ fn dnf(e: &Expr, operands: &[PathMap]) -> Option> { let mut wz = out.write_zipper(); macro_rules! dnf_arm { ($n:literal, $m:literal) => {{ - let mut zs: [ReadZipperUntracked<'_, '_, u64>; $n] = + let mut zs: [ReadZipperUntracked<'_, '_, V>; $n] = core::array::from_fn(|i| operands[vars[i]].read_zipper()); let cs: [Clause<$n>; $m] = core::array::from_fn(|i| Clause::from_mask(packed[i])); zipper_merge_dnf(&mut zs, cs, &mut wz); diff --git a/differential/src/algebraic/shape.rs b/differential/src/algebraic/shape.rs index 1f7c5d69..52f5cd56 100644 --- a/differential/src/algebraic/shape.rs +++ b/differential/src/algebraic/shape.rs @@ -24,11 +24,13 @@ use pathmap::PathMap; use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperValues}; use std::collections::BTreeMap; +use super::value::FuzzValue; + /// Every path in a trie, in depth-first order, with the value at it if any. -pub type Shape = Vec<(Vec, Option)>; +pub type Shape = Vec<(Vec, Option)>; /// The paths of a trie that carry values. -pub type Values = BTreeMap, u64>; +pub type Values = BTreeMap, V>; /// Cap on paths recorded per trie. A generated case that needs more than this /// is not interesting enough to be worth the comparison cost; the cap is @@ -46,12 +48,12 @@ pub const TRUNCATED: &[u8] = b""; /// /// The root is recorded explicitly: `to_next_step` moves before it reports, so /// a loop driven by it alone would miss the value at the empty path. -pub fn shape_of_zipper(z: &mut Z) -> Shape +pub fn shape_of_zipper(z: &mut Z) -> Shape where - Z: ZipperMoving + ZipperPath + ZipperValues, + Z: ZipperMoving + ZipperPath + ZipperValues, { z.reset(); - let mut out: Shape = vec![(Vec::new(), z.val().copied())]; + let mut out: Shape = vec![(Vec::new(), z.val().cloned())]; loop { if out.len() >= SHAPE_CAP { out.push((TRUNCATED.to_vec(), None)); @@ -67,26 +69,26 @@ where out.push((ESCAPED_ROOT.to_vec(), None)); break; } - out.push((z.path().to_vec(), z.val().copied())); + out.push((z.path().to_vec(), z.val().cloned())); } out } -pub fn shape_of_map(m: &PathMap) -> Shape { +pub fn shape_of_map(m: &PathMap) -> Shape { shape_of_zipper(&mut m.read_zipper()) } /// The value-carrying subset of a [`Shape`]. -pub fn values_of_shape(s: &Shape) -> Values { +pub fn values_of_shape(s: &Shape) -> Values { s.iter() - .filter_map(|(p, v)| v.map(|v| (p.clone(), v))) + .filter_map(|(p, v)| v.clone().map(|v| (p.clone(), v))) .collect() } /// The paths of a [`Shape`], values ignored. Used by the laws that hold only -/// up to path presence, because `u64`'s `pjoin` and `pmeet` are left-biased -/// and so neither is commutative in the value it picks. -pub fn paths_of_shape(s: &Shape) -> Vec> { +/// up to path presence, which is how the laws that depend on join and meet being +/// different functions are checked when the value type is not a lattice. +pub fn paths_of_shape(s: &Shape) -> Vec> { s.iter().map(|(p, _)| p.clone()).collect() } @@ -101,25 +103,25 @@ pub fn show_path(p: &[u8]) -> String { } } -pub fn show_shape(s: &Shape) -> String { +pub fn show_shape(s: &Shape) -> String { s.iter() .map(|(p, v)| match v { - Some(v) => format!("{}:{v}", show_path(p)), + Some(v) => format!("{}:{}", show_path(p), v.show()), None => format!("{}:-", show_path(p)), }) .collect::>() .join(",") } -pub fn show_values(v: &Values) -> String { +pub fn show_values(v: &Values) -> String { v.iter() - .map(|(p, v)| format!("{}:{v}", show_path(p))) + .map(|(p, v)| format!("{}:{}", show_path(p), v.show())) .collect::>() .join(",") } /// First point at which two shapes differ, for the failure report. -pub fn first_shape_diff(a: &Shape, b: &Shape) -> Option { +pub fn first_shape_diff(a: &Shape, b: &Shape) -> Option { for i in 0..a.len().max(b.len()) { match (a.get(i), b.get(i)) { (Some(x), Some(y)) if x == y => continue, @@ -127,9 +129,9 @@ pub fn first_shape_diff(a: &Shape, b: &Shape) -> Option { return Some(format!( "at #{i}: {}:{} vs {}:{}", show_path(&x.0), - x.1.map(|v| v.to_string()).unwrap_or("-".into()), + x.1.as_ref().map(|v| v.show()).unwrap_or("-".into()), show_path(&y.0), - y.1.map(|v| v.to_string()).unwrap_or("-".into()), + y.1.as_ref().map(|v| v.show()).unwrap_or("-".into()), )); } (Some(x), None) => { @@ -145,7 +147,7 @@ pub fn first_shape_diff(a: &Shape, b: &Shape) -> Option { } /// First point at which two value maps differ. -pub fn first_values_diff(a: &Values, b: &Values) -> Option { +pub fn first_values_diff(a: &Values, b: &Values) -> Option { let mut keys: Vec<&Vec> = a.keys().chain(b.keys()).collect(); keys.sort(); keys.dedup(); @@ -155,8 +157,8 @@ pub fn first_values_diff(a: &Values, b: &Values) -> Option { return Some(format!( "at {}: {} vs {}", show_path(k), - x.map(|v| v.to_string()).unwrap_or("-".into()), - y.map(|v| v.to_string()).unwrap_or("-".into()), + x.map(|v| v.show()).unwrap_or("-".into()), + y.map(|v| v.show()).unwrap_or("-".into()), )); } } diff --git a/differential/src/algebraic/value.rs b/differential/src/algebraic/value.rs new file mode 100644 index 00000000..e821334b --- /dev/null +++ b/differential/src/algebraic/value.rs @@ -0,0 +1,241 @@ +//! The value types the fuzzer runs every case against. +//! +//! The harness is generic over this trait and the driver instantiates it twice, +//! because the two instantiations answer different questions. +//! +//! * [`Bits`] is a genuine Boolean algebra: `pjoin` is `|`, `pmeet` is `&`, +//! `psubtract` is `& !`, and an empty result is bottom, which `pathmap` +//! represents as an absent value. Every lattice identity holds, so a law +//! that fails here is a real defect. +//! +//! * `u64` is the type the rest of this crate's fuzzing uses, and its instances +//! in `pathmap::ring` are **not a lattice**: `pjoin` is `left_biased_pjoin` +//! and `pmeet` is `Identity(SELF_IDENT)`, so both return the left operand and +//! `a | b == a & b` for every pair -- which in a lattice would force +//! `a == b`. It is kept because it is what real callers use today, and +//! because dropping it would lose coverage of the `Identity`-heavy paths. +//! +//! Running both is the point. A finding that appears under `u64` and not under +//! `Bits` is an artefact of that degenerate instance; one that appears under +//! both, or under `Bits` alone, is a defect in the crate. `bin/alg_fuzz` +//! prints the split explicitly. +//! +//! # Why a bitmask rather than some other lawful lattice +//! +//! Lawfulness alone is not enough. `max`/`min` on a total order is a perfectly +//! good distributive lattice, and useless here: `max(a, b)` and `min(a, b)` are +//! always *one of the operands*, so they can only ever return +//! `AlgebraicResult::Identity`, and every code path that allocates and stores a +//! genuinely combined value stays unreachable. `a | b` is a new value, so a +//! bitmask reaches them. `bin/alg_lattice_check` prints the comparison. + +use pathmap::ring::{AlgebraicResult, DistributiveLattice, Lattice, COUNTER_IDENT, SELF_IDENT}; + +use super::Gen; + +/// What the harness needs of a value type. +pub trait FuzzValue: + Clone + + Send + + Sync + + Unpin + + PartialEq + + Ord + + core::fmt::Debug + + core::hash::Hash + + Lattice + + DistributiveLattice + + 'static +{ + /// Appears as the first field of every signature, so findings from the two + /// instantiations never collide. + const NAME: &'static str; + + /// Whether this type's instances actually form a distributive lattice with a + /// relative complement. + /// + /// `laws.rs` reads this: when it is false, the identities that depend on + /// join and meet being different functions are checked on path presence + /// only, and the ones that cannot hold at all are skipped. When it is true + /// every identity is checked on values, which is the stronger test and the + /// reason for having a lawful type at all. + const LAWFUL: bool; + + /// Whether `pjoin` always yields one of its operands rather than a new + /// value -- true exactly when the "join" is really "the left one wins". + /// + /// This gates the `OverlayZipper` join strategy, and it is not a detail. + /// `OverlayZipper`'s mapping function has signature + /// `Fn(Option<&'a AV>, Option<&'a BV>) -> Option<&'a OutV>`: it returns a + /// *reference*, so it has nowhere to put a value it would have to create. + /// The module's own comment says as much. So an overlay can stand in for a + /// join only when the join never creates anything, and for a real lattice it + /// cannot be a join at all. That is a limitation of the zipper, not a + /// defect, so the strategy is dropped rather than reported. + const JOIN_PICKS_LEFT: bool; + + fn generate(g: &mut Gen) -> Self; + + fn show(&self) -> String; +} + +/// A 64-bit set under union, intersection and relative complement. +/// +/// The same construction `pathmap::utils` already uses for `[u64; 4]` and +/// `ByteMask`, at a narrower width: see `bitmask_algebraic_result` there. An +/// empty result is `AlgebraicResult::None` rather than `Element(Bits(0))`, +/// matching the convention `SetLattice`'s documentation states -- an empty set +/// is equivalent to a nonexistent one. +/// +/// Defined here rather than in `pathmap` on purpose: a value type living outside +/// the crate is what a real caller has, so the generic algebra is exercised the +/// way a downstream user would exercise it. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Bits(pub u64); + +impl core::fmt::Debug for Bits { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:b}", self.0) + } +} + +/// Classify a bitwise result exactly as `pathmap::utils` does for `[u64; 4]`. +#[inline] +fn bits_result(result: u64, lhs: u64, rhs: u64) -> AlgebraicResult { + if result == 0 { + return AlgebraicResult::None; + } + let mut mask = 0; + if result == lhs { + mask = SELF_IDENT; + } + if result == rhs { + mask |= COUNTER_IDENT; + } + if mask != 0 { + AlgebraicResult::Identity(mask) + } else { + AlgebraicResult::Element(Bits(result)) + } +} + +impl Lattice for Bits { + #[inline] + fn pjoin(&self, other: &Self) -> AlgebraicResult { + bits_result(self.0 | other.0, self.0, other.0) + } + #[inline] + fn pmeet(&self, other: &Self) -> AlgebraicResult { + bits_result(self.0 & other.0, self.0, other.0) + } +} + +impl DistributiveLattice for Bits { + #[inline] + fn psubtract(&self, other: &Self) -> AlgebraicResult { + bits_result(self.0 & !other.0, self.0, other.0) + } +} + +/// Width of the generated masks. +/// +/// Four bits, so operands collide constantly -- the whole point of a small +/// alphabet applies to values too -- while still overlapping only partially, so +/// `pjoin` and `pmeet` return `Element` rather than `Identity` most of the time. +pub const BITS_WIDTH: u32 = 4; + +impl FuzzValue for Bits { + const NAME: &'static str = "bits"; + const LAWFUL: bool = true; + // `Bits(0b01) | Bits(0b10)` is `Bits(0b11)`, which is neither operand. + const JOIN_PICKS_LEFT: bool = false; + + fn generate(g: &mut Gen) -> Self { + // Never zero. Bottom is representable as `Bits(0)`, but the lattice + // collapses it to `None`, so a stored `Bits(0)` is a value that is also + // bottom -- a genuinely interesting edge case, and a separate question + // from the one this type is here to answer. Excluded deliberately. + let n = 1u64 << BITS_WIDTH; + Bits(g.byte() as u64 % (n - 1) + 1) + } + + fn show(&self) -> String { + format!("{:b}", self.0) + } +} + +/// The set case: a path is either present or absent, with nothing attached. +/// +/// `Option<()>` is exactly the two-element Boolean algebra, so `()` is **lawful** +/// -- unlike `u64`, and for the same reason `bits` is. It earns a place of its +/// own anyway, for two reasons neither of the others covers. +/// +/// First, `PathMap<()>` is what a caller writes when the trie *is* the data, and +/// it is what the `unit-value-optimizations` and `unit-size` branches are about. +/// None of that is on `master` yet, so today this exercises the generic path; if +/// those land it becomes the only thing covering the specialised one. +/// +/// Second, and more useful now: `()`'s `pjoin` and `pmeet` return +/// `Identity(SELF_IDENT | COUNTER_IDENT)` *unconditionally* -- **both** identity +/// bits, always. `u64` returns that only for equal values and `bits` only for +/// equal masks, so neither saturates the "either side will do" path that the node +/// code uses to decide it can hand back an operand unchanged and keep sharing it. +/// Findings 4 and 6 are both about exactly that machinery, so a value type that +/// drives it on every single combination is worth having. +/// +/// It cannot produce `Element`, but that is not a gap here: with one inhabitant +/// there is no combined value to store. `bits` covers that. +impl FuzzValue for () { + const NAME: &'static str = "unit"; + const LAWFUL: bool = true; + // Both operands are `()`, so returning either is returning the left one, and + // `OverlayZipper`'s `a.or(b)` is the join. + const JOIN_PICKS_LEFT: bool = true; + + fn generate(_g: &mut Gen) -> Self {} + + fn show(&self) -> String { + "*".to_string() + } +} + +/// Distinct values in circulation for `u64`. +/// +/// Tiny on purpose: `psubtract` on `u64` is `None` only when the two values are +/// *equal*, so a large value space would turn subtraction into set difference +/// and never exercise the value comparison at all. +pub const U64_VALUES: u64 = 3; + +impl FuzzValue for u64 { + const NAME: &'static str = "u64"; + const LAWFUL: bool = false; + const JOIN_PICKS_LEFT: bool = true; + + fn generate(g: &mut Gen) -> Self { + g.byte() as u64 % U64_VALUES + 1 + } + + fn show(&self) -> String { + self.to_string() + } +} + +/// Resolve an `AlgebraicResult` over `Option` to a value, which is how +/// `pathmap` stores the outcome: `None` means the value is gone. +/// +/// Used by `model.rs` so the reference semantics are derived from the value +/// type's own operations rather than restated by hand -- restating them is how +/// a harness ends up asserting its own idea of the algebra. +pub fn resolve( + result: AlgebraicResult>, + lhs: &Option, + rhs: &Option, +) -> Option { + match result { + AlgebraicResult::Element(v) => v, + AlgebraicResult::Identity(mask) => { + if mask & SELF_IDENT != 0 { lhs.clone() } else { rhs.clone() } + } + AlgebraicResult::None => None, + } +} diff --git a/differential/src/bin/alg_bug_repros.rs b/differential/src/bin/alg_bug_repros.rs index 8c4f1638..57a8cf6b 100644 --- a/differential/src/bin/alg_bug_repros.rs +++ b/differential/src/bin/alg_bug_repros.rs @@ -9,10 +9,12 @@ //! cargo run --release -p differential --bin alg_bug_repros //! ``` //! -//! Exit status is 1 while any of them still reproduces. +//! Exit status is 1 while any of them still reproduces. Case 7 is an unsettled +//! question rather than a defect and never counts as a failure. use pathmap::PathMap; -use pathmap::zipper::{ZipperMoving, ZipperValues, ZipperWriting}; +use pathmap::experimental::zipper_algebra::{zipper_join, zipper_meet, zipper_sym_diff}; +use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperValues, ZipperWriting}; /// A trie holding only dangling paths: structure written with `create_path` /// and no value anywhere. @@ -38,6 +40,22 @@ fn val_at(m: &PathMap, path: &[u8]) -> Option { m.read_zipper_at_path(path).val().copied() } +/// Every path in a trie, with `=v` on the ones carrying a value, so a +/// dangling-path difference is visible. +fn shape(m: &PathMap) -> Vec { + let mut z = m.read_zipper(); + let mut out = Vec::new(); + z.reset(); + while z.to_next_step() { + out.push(format!( + "{}{}", + z.path().iter().map(|b| format!("{b}")).collect::(), + if z.val().is_some() { "=v" } else { "" } + )); + } + out +} + struct Report { failed: usize, } @@ -177,6 +195,80 @@ fn main() { ); } + // ---------------------------------------------------------------- 6 + // Finding 6 has no standalone reproducer: it is three `debug_assert!`s + // inside the merge primitives, so there is nothing to compare and nothing + // to print -- the assertion either fires or it does not. Build with + // `-C debug-assertions=yes` and replay the three `panic-eval-*` inputs in + // `algebraic-corpus/`. + println!( + "\n6. join reporting an empty result from non-empty nodes\n => debug-assertions only; replay algebraic-corpus/panic-eval-*.bin" + ); + + // ---------------------------------------------------------------- 7 + // The `shape` class, which is the largest one the fuzzer reports and had no + // reproducer until now. + // + // Not a defect: whether a dangling path -- structure written with + // `create_path`, carrying no value and with nothing below it -- survives an + // operation is unsettled in the crate. What the fuzzer establishes is that + // the two families answer differently and consistently so: + // + // * the lockstep traversals in `experimental::zipper_algebra` **discard** + // dangling structure; + // * `PathMap`'s whole-map operations and the write-zipper forms + // (`join_into`, `meet_into`, `subtract_into`) **preserve** it. + // + // Worth having concretely, because whichever way the question is settled, one + // of those two families has to change, and this says which operations are on + // each side. + { + let d2 = dangling(&[&[0], &[1]]); + let dv = { + let mut m = dangling(&[&[0, 0]]); + m.write_zipper_at_path(&[1]).set_val(7); + m + }; + + println!("\n7. dangling paths: the zipper traversals drop them, the map operations keep them"); + println!(" operands: d2 = {{dangling 0, 1}}, dv = {{dangling 0, 00; value at 1}}"); + + let mut zj = PathMap::::new(); + { + let (mut a, mut b) = (d2.read_zipper(), dv.read_zipper()); + let mut wz = zj.write_zipper(); + zipper_join(&mut a, &mut b, &mut wz); + } + println!(" d2 | dv zipper_join {:?}", shape(&zj)); + println!(" PathMap::join {:?}", shape(&d2.join(&dv))); + + let mut zm = PathMap::::new(); + { + let (mut a, mut b) = (d2.read_zipper(), dv.read_zipper()); + let mut wz = zm.write_zipper(); + zipper_meet(&mut a, &mut b, &mut wz); + } + println!(" d2 & dv zipper_meet {:?}", shape(&zm)); + println!(" PathMap::meet {:?}", shape(&d2.meet(&dv))); + + // The sharpest form: symmetric difference with the empty trie should be + // the identity, and for structure it is not. + let d = dangling(&[&[0]]); + let empty = PathMap::::new(); + let mut zx = PathMap::::new(); + { + let (mut a, mut b) = (d.read_zipper(), empty.read_zipper()); + let mut wz = zx.write_zipper(); + zipper_sym_diff(&mut a, &mut b, &mut wz); + } + println!(" d ^ {{}} zipper_sym_diff {:?}", shape(&zx)); + println!( + " (d|e)-(d&e) {:?}", + shape(&d.join(&empty).subtract(&d.meet(&empty))) + ); + println!(" => not counted as a failure; the crate has not settled this"); + } + println!("\n{} of 6 still reproduce", r.failed); if r.failed > 0 { std::process::exit(1); diff --git a/differential/src/bin/alg_fuzz.rs b/differential/src/bin/alg_fuzz.rs index 63980029..e5cbb860 100644 --- a/differential/src/bin/alg_fuzz.rs +++ b/differential/src/bin/alg_fuzz.rs @@ -9,6 +9,21 @@ //! Everything runs in process. There is no oracle to start and no child to //! talk to, so a case costs a few microseconds and a run is bounded by how many //! tries it can build rather than by IPC. +//! +//! # Soundness limit +//! +//! That in-process design has a known hole: **a run that catches panics can +//! abort with heap corruption**, reproducibly, after enough of them. Every +//! panic the fuzzer catches fired *mid-mutation* inside `pathmap`'s node code -- +//! a `debug_assert!` in a merge, or `merkleize`'s `unwrap` -- and unwinding out +//! of a half-updated node leaves a trie that is not safe to drop. Measured by +//! elimination: it tracks the number of panics caught, not the build profile, +//! the thread count or the value type, and a run that catches none is clean. +//! +//! So treat the first panic in a run as the end of the useful output. Findings +//! printed before it are valid; a run that aborts has lost whatever it had not +//! yet printed. `ALGEBRAIC_FUZZING.md` has the table and the intended fix, +//! which is to make panics terminal and rare rather than caught and counted. use std::collections::BTreeMap; use std::io::Write as _; @@ -22,8 +37,10 @@ use differential::algebraic::{self, Class, Outcome, Rng, signatures}; /// /// `Shape` is not among them. Whether a dangling path survives an operation is /// unsettled in the crate -- `SPEC_WARTS.md` and the `meet_into-keeps-dangling*` -/// corpus entries are the same question -- and routes that graft whole subtries -/// will keep structure that routes walking path by path cannot. Those are +/// corpus entries are the same question. The two families answer it differently +/// and consistently: the lockstep traversals in `experimental::zipper_algebra` +/// discard dangling structure, and `PathMap`'s whole-map operations and the +/// write-zipper forms preserve it (`bin/alg_bug_repros` case 7). Those are /// counted and printed, so a change in them is visible, but they do not turn a /// run red unless `--shape` asks them to. A wrong *value* is never ambiguous /// and always fails. @@ -125,13 +142,17 @@ impl Tally { Tally { cases: 0, by_signature: BTreeMap::new(), examples: Vec::new() } } - fn record(&mut self, bytes: &[u8], outcome: Outcome) { - self.cases += 1; + /// Record one outcome. `cases` counts inputs, not outcomes, so only the + /// first value type of each input increments it. + fn record(&mut self, type_name: &str, bytes: &[u8], outcome: Outcome, count: bool) { + if count { + self.cases += 1; + } let findings: Vec<(String, String)> = match outcome { Outcome::Clean => return, Outcome::Panicked(p, site, msg) => { vec![( - algebraic::panic_signature(p, &site), + algebraic::panic_signature(type_name, p, &site), format!("panicked at {site}: {msg}"), )] } @@ -184,18 +205,20 @@ fn main() { eprintln!("{}: {e}", f.display()); std::process::exit(2) }); - let outcome = algebraic::run(&bytes); - let label = match &outcome { - Outcome::Clean => "clean".to_string(), - Outcome::Diverged(d) => { - format!("{} finding(s)", d.len()) - } - Outcome::Panicked(p, site, m) => { - format!("panic in {} at {site}: {m}", p.tag()) - } - }; - println!("{}: {label}", f.display()); - tally.record(&bytes, outcome); + let mut labels = Vec::new(); + let mut first = true; + algebraic::run_all(&bytes, &mut |name, outcome| { + labels.push(match &outcome { + Outcome::Clean => format!("{name}: clean"), + Outcome::Diverged(d) => format!("{name}: {} finding(s)", d.len()), + Outcome::Panicked(p, site, m) => { + format!("{name}: panic in {} at {site}: {m}", p.tag()) + } + }); + tally.record(name, &bytes, outcome, first); + first = false; + }); + println!("{}: {}", f.display(), labels.join(", ")); } } @@ -212,8 +235,11 @@ fn main() { let mut t = Tally::new(); for _ in 0..n { let bytes = rng.input(); - let outcome = algebraic::run(&bytes); - t.record(&bytes, outcome); + let mut first = true; + algebraic::run_all(&bytes, &mut |name, outcome| { + t.record(name, &bytes, outcome, first); + first = false; + }); } let _ = tx.send(t); })); @@ -245,6 +271,8 @@ fn report(args: &Args, tally: &mut Tally) { } } + value_type_comparison(tally); + if let Err(e) = std::fs::create_dir_all(&args.out) { eprintln!("cannot create {}: {e}", args.out.display()); } @@ -260,7 +288,7 @@ fn report(args: &Args, tally: &mut Tally) { // `panic:build` finding panics again. Catch it: the reproducer is // still worth writing, it just cannot describe itself. let described = panic::catch_unwind(AssertUnwindSafe(|| { - algebraic::describe(&algebraic::decode(bytes)) + algebraic::describe_as(algebraic::value_type_of(sig), bytes) })) .unwrap_or_else(|_| "\n".to_string()); let body = format!("signature: {sig}\n\n{described}\n{detail}\n"); @@ -292,6 +320,91 @@ fn report(args: &Args, tally: &mut Tally) { /// `--strict` fails on anything. Otherwise a signature in `algebraic::KNOWN` /// is excused, a panic or a wrong value is fatal, and a dangling-path-only /// divergence is fatal only under `--shape`. +/// Print which findings each value type sees, which is the question the two +/// instantiations exist to answer. +/// +/// A signature under `u64` alone is an artefact of its lattice instances, which +/// are not a lattice: `pjoin` and `pmeet` both return the left operand, so +/// `a | b == a & b` and several identities cannot hold. A signature under the +/// lawful type -- alone, or under both -- is a defect in the crate. +/// +/// The counts matter as much as the membership. A law that fails 3000 times +/// under `u64` and 12 times under `bits` is one defect amplified by the value +/// type, not two findings: under a commutative join, picking the wrong operand +/// is invisible except where one operand already contains the other, so only +/// that residue survives. +fn value_type_comparison(tally: &Tally) { + let types = algebraic::VALUE_TYPES; + if types.len() < 2 { + return; + } + + // Strip the value-type prefix: `u64:values:pw1` -> `values:pw1`. + let rest = |sig: &str| sig.splitn(2, ':').nth(1).unwrap_or(sig).to_string(); + let per_type: Vec> = types + .iter() + .map(|t| { + tally + .by_signature + .iter() + .filter(|(sig, _)| algebraic::value_type_of(sig) == *t) + .map(|(sig, n)| (rest(sig), *n)) + .collect() + }) + .collect(); + + let mut all: Vec = per_type.iter().flat_map(|m| m.keys().cloned()).collect(); + all.sort(); + all.dedup(); + if all.is_empty() { + return; + } + + let lawful: Vec<&str> = + types.iter().copied().filter(|t| *t != "u64").collect(); + println!("\nby value type -- {} are lawful, u64 is not:", lawful.join(" and ")); + print!(" {:<38}", "finding"); + for t in types { + print!(" {t:>9}"); + } + println!(); + + // Which types see each finding, so the groups below can be built by subset. + let mut by_subset: BTreeMap, Vec> = BTreeMap::new(); + for k in &all { + print!(" {k:<38}"); + let mut seen = Vec::new(); + for (i, t) in types.iter().enumerate() { + match per_type[i].get(k) { + Some(n) => { + print!(" {n:>9}"); + seen.push(*t); + } + None => print!(" {:>9}", "-"), + } + } + println!(); + by_subset.entry(seen).or_default().push(k.clone()); + } + + println!("\nseen under:"); + for (subset, findings) in &by_subset { + let note = if subset.len() == types.len() { + " <- value-independent, or one defect amplified; read the counts" + } else if subset == &["u64"] { + " <- artefacts: u64's instances are not a lattice" + } else if subset.contains(&"u64") { + "" + } else { + " <- REAL, and u64 was hiding them" + }; + println!(" {:<22}{note}", subset.join(" + ")); + for f in findings { + println!(" {f}"); + } + } +} + fn is_fatal(sig: &str, args: &Args) -> bool { if args.strict { return true; @@ -299,13 +412,17 @@ fn is_fatal(sig: &str, args: &Args) -> bool { if algebraic::known(sig).is_some() { return false; } - if sig.starts_with("panic:") { - return true; - } - if sig.starts_with("shape:") { - return args.shape_fatal; + // The class is the *second* field: signatures are `::...`. + // Matching against the start of the whole signature silently stopped working + // when the value-type prefix was added, which made every class fall through + // to "not fatal" and left the gate passing runs that had turned up new + // findings. Parse the field rather than the prefix. + let class = sig.split(':').nth(1).unwrap_or(""); + match class { + "panic" => true, + "shape" => args.shape_fatal, + c => DEFAULT_FATAL.iter().any(|f| f.tag() == c), } - DEFAULT_FATAL.iter().any(|c| sig.starts_with(c.tag())) } fn sanitize(sig: &str) -> String { @@ -414,18 +531,18 @@ fn do_shrink(path: &Path, want: Option<&str>) { eprintln!("shrunk to {} bytes -> {}", best.len(), out.display()); let described = panic::catch_unwind(AssertUnwindSafe(|| { - algebraic::describe(&algebraic::decode(&best)) + algebraic::describe_as(algebraic::value_type_of(&target), &best) })) .unwrap_or_else(|_| "\n".to_string()); print!("{described}"); - match algebraic::run(&best) { - Outcome::Clean => println!("(no longer diverges)"), - Outcome::Panicked(p, site, m) => println!("panic in {} at {site}: {m}", p.tag()), + algebraic::run_all(&best, &mut |name, outcome| match outcome { + Outcome::Clean => println!("{name}: no divergence"), + Outcome::Panicked(p, site, m) => println!("{name}: panic in {} at {site}: {m}", p.tag()), Outcome::Diverged(d) => { for div in d { println!("[{}] {}\n{}", div.class.tag(), div.signature, div.detail); } } - } + }); let _ = std::io::stdout().flush(); } diff --git a/differential/src/bin/alg_lattice_check.rs b/differential/src/bin/alg_lattice_check.rs new file mode 100644 index 00000000..95f5c6e3 --- /dev/null +++ b/differential/src/bin/alg_lattice_check.rs @@ -0,0 +1,208 @@ +//! Is a divergence the crate's fault, or the value type's? +//! +//! `(a | b) \ (a & b)` and `(a \ b) | (b \ a)` are equal in any distributive +//! lattice with a relative complement, so a divergence between them is never a +//! matter of convention. This prints both formulas for several value types and +//! shows which ones are lawful. +//! +//! It also asks a second question, which turns out to be the more important one +//! for fuzzing: does the type's `pjoin`/`pmeet`/`psubtract` ever return +//! `AlgebraicResult::Element` -- a combined value that is not simply one of its +//! operands? If not, every code path that *stores* a combined value is +//! unreachable from that type, however lawful it is. +//! +//! ```sh +//! cargo run --release -p differential --bin alg_lattice_check +//! ``` + +use core::fmt::Debug; +use pathmap::ring::{AlgebraicResult, DistributiveLattice, Lattice, COUNTER_IDENT, SELF_IDENT}; +use pathmap::utils::ByteMask; + +/// Bottom is `None`, as it is everywhere in `pathmap`: a value that cancels +/// becomes an absent value, not a present zero. Resolving through `Option` +/// uses the crate's own `Option` lattice impls, so this says nothing the +/// trie does not. +fn resolve(r: AlgebraicResult>, l: &Option, rr: &Option) -> Option { + match r { + AlgebraicResult::Element(v) => v, + AlgebraicResult::Identity(m) => { + if m & SELF_IDENT != 0 { l.clone() } else { rr.clone() } + } + AlgebraicResult::None => None, + } +} + +fn show(v: &Option) -> String { + match v { + None => "BOTTOM".to_string(), + Some(v) => format!("{v:?}"), + } +} + +/// `(a | b) \ (a & b)` and `(a \ b) | (b \ a)`, each resolved to a value. +fn two_formulas(a: T, b: T) -> (String, String, String, String, bool) +where + T: Lattice + DistributiveLattice + Clone + Debug, +{ + let (ao, bo) = (Some(a), Some(b)); + let j = resolve(ao.pjoin(&bo), &ao, &bo); + let m = resolve(ao.pmeet(&bo), &ao, &bo); + let f1 = resolve(j.psubtract(&m), &j, &m); + + let ab = resolve(ao.psubtract(&bo), &ao, &bo); + let ba = resolve(bo.psubtract(&ao), &bo, &ao); + let f2 = resolve(ab.pjoin(&ba), &ab, &ba); + + let agree = show(&f1) == show(&f2); + (show(&j), show(&m), show(&f1), show(&f2), agree) +} + +fn row(label: String, a: T, b: T) +where + T: Lattice + DistributiveLattice + Clone + Debug, +{ + let (j, m, f1, f2, agree) = two_formulas(a, b); + println!( + " {label:<22} a|b = {j:>9} a&b = {m:>9} (a|b)-(a&b) = {f1:>9} (a-b)|(b-a) = {f2:>9} {}", + if agree { "agree" } else { "DIVERGE" } + ); +} + +/// Whether each operation ever returns `Element` over a sample of pairs. +fn element_per_op(sample: &[T]) -> (bool, bool, bool) +where + T: Lattice + DistributiveLattice + Clone, +{ + let mut out = (false, false, false); + for a in sample { + for b in sample { + out.0 |= matches!(a.pjoin(b), AlgebraicResult::Element(_)); + out.1 |= matches!(a.pmeet(b), AlgebraicResult::Element(_)); + out.2 |= matches!(a.psubtract(b), AlgebraicResult::Element(_)); + } + } + out +} + +fn yn(b: bool) -> &'static str { + if b { "yes" } else { "NO " } +} + +// ---------------------------------------------------------------- candidates + +/// Bitmask: `pjoin` is `|`, `pmeet` is `&`, `psubtract` is `& !`, and an empty +/// result collapses to `None`. A Boolean algebra -- the powerset of 64 +/// elements -- so every lattice identity holds. This is exactly what +/// `[u64; 4]` already does in `pathmap::utils`; only the width differs. +#[derive(Clone, Copy, PartialEq, Eq)] +struct Bits(u64); + +impl Debug for Bits { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:04b}", self.0) + } +} + +fn bits_result(r: u64, l: u64, rr: u64) -> AlgebraicResult { + if r == 0 { + return AlgebraicResult::None; + } + let mut m = 0; + if r == l { m = SELF_IDENT } + if r == rr { m |= COUNTER_IDENT } + if m != 0 { AlgebraicResult::Identity(m) } else { AlgebraicResult::Element(Bits(r)) } +} + +impl Lattice for Bits { + fn pjoin(&self, o: &Self) -> AlgebraicResult { bits_result(self.0 | o.0, self.0, o.0) } + fn pmeet(&self, o: &Self) -> AlgebraicResult { bits_result(self.0 & o.0, self.0, o.0) } +} +impl DistributiveLattice for Bits { + fn psubtract(&self, o: &Self) -> AlgebraicResult { bits_result(self.0 & !o.0, self.0, o.0) } +} + +/// The total order: `pjoin` is `max`, `pmeet` is `min`, bottom is 0. Also a +/// genuine distributive lattice -- every total order is one -- and here to make +/// the point that lawfulness is not sufficient. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct MinMax(u64); + +fn minmax_result(r: u64, l: u64, rr: u64) -> AlgebraicResult { + if r == 0 { + return AlgebraicResult::None; + } + let mut m = 0; + if r == l { m = SELF_IDENT } + if r == rr { m |= COUNTER_IDENT } + if m != 0 { AlgebraicResult::Identity(m) } else { AlgebraicResult::Element(MinMax(r)) } +} + +impl Lattice for MinMax { + fn pjoin(&self, o: &Self) -> AlgebraicResult { minmax_result(self.0.max(o.0), self.0, o.0) } + fn pmeet(&self, o: &Self) -> AlgebraicResult { minmax_result(self.0.min(o.0), self.0, o.0) } +} +impl DistributiveLattice for MinMax { + fn psubtract(&self, o: &Self) -> AlgebraicResult { + minmax_result(if self.0 > o.0 { self.0 } else { 0 }, self.0, o.0) + } +} + +fn bm(bits: &[u8]) -> ByteMask { + let mut m = [0u64; 4]; + for b in bits { + m[(*b / 64) as usize] |= 1 << (*b % 64); + } + ByteMask(m) +} + +fn main() { + println!("Are the two formulas for symmetric difference equal?\n"); + + println!("u64 -- what the fuzzer uses; pjoin is left-biased, pmeet is Identity(SELF)"); + for (a, b) in [(1u64, 2u64), (3, 7), (5, 5)] { + row(format!("a={a} b={b}"), a, b); + } + println!(" ^ a|b == a&b for every pair, so this is not a lattice: in one,"); + println!(" a&b == a|b forces a == b, i.e. the impl asserts 1 == 2.\n"); + + println!("bool -- a real two-element Boolean algebra, same file"); + for (a, b) in [(true, false), (true, true), (false, false)] { + row(format!("a={a} b={b}"), a, b); + } + + println!("\nBits(u64) -- pjoin = |, pmeet = &, psubtract = & !, empty -> None"); + for (a, b) in [(0b0011u64, 0b0101u64), (0b0001, 0b0010), (0b0011, 0b0011)] { + row(format!("a={a:04b} b={b:04b}"), Bits(a), Bits(b)); + } + + println!("\nByteMask -- the crate already implements exactly that, at 256 bits"); + for (a, b) in [(&[0u8, 1][..], &[1u8, 2][..]), (&[0][..], &[1][..]), (&[3][..], &[3][..])] { + row(format!("a={a:?} b={b:?}"), bm(a), bm(b)); + } + + println!("\nMinMax(u64) -- pjoin = max, pmeet = min; also a lawful distributive lattice"); + for (a, b) in [(5u64, 3u64), (3, 5), (4, 4)] { + row(format!("a={a} b={b}"), MinMax(a), MinMax(b)); + } + + println!("\n\nDoes each operation ever return AlgebraicResult::Element,"); + println!("i.e. a combined value that is not simply one of its operands?\n"); + println!(" {:<12} {:>7} {:>7} {:>10}", "type", "pjoin", "pmeet", "psubtract"); + let show_ops = |name: &str, (j, m, s): (bool, bool, bool)| { + println!(" {name:<12} {:>7} {:>7} {:>10}", yn(j), yn(m), yn(s)); + }; + show_ops("u64", element_per_op(&[1u64, 2, 3, 5, 7])); + show_ops("bool", element_per_op(&[true, false])); + show_ops("MinMax", element_per_op(&[MinMax(1), MinMax(2), MinMax(3), MinMax(5)])); + show_ops("Bits", element_per_op(&[Bits(0b0011), Bits(0b0101), Bits(0b1001), Bits(0b0110)])); + show_ops("ByteMask", element_per_op(&[bm(&[0, 1]), bm(&[1, 2]), bm(&[2, 3]), bm(&[0, 3])])); + + println!("\n u64's one \"yes\" is `Element(*self)` -- an Element whose value equals self,"); + println!(" which is why PR #115 retags it as Identity(SELF_IDENT). That is the right"); + println!(" fix, and it leaves u64 unable to produce Element from any operation at all."); + println!("\n MinMax is lawful and still answers NO everywhere: max(a,b) and min(a,b)"); + println!(" are always one of the operands, so a lattice can be perfectly correct and"); + println!(" still never exercise the code that stores a combined value. Only the"); + println!(" bitmask family answers yes, because a|b is genuinely a new value."); +} diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index de39d8c1..05ceae33 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -14,7 +14,13 @@ //! `pmeet` is left-biased. A harness that reports its own mistakes as findings //! is worse than no harness, so the recognisers are pinned here. -use differential::algebraic::{self, expr::{Expr, Op}, known, signatures}; +use differential::algebraic::{ + self, + expr::{Expr, Op}, + known, signatures, + value::{Bits, FuzzValue}, +}; +use pathmap::ring::{AlgebraicResult, DistributiveLattice, Lattice}; /// Collect the signatures an input produces that `KNOWN` does not document. /// @@ -168,6 +174,234 @@ fn dnf_rejects_non_monotone_operators() { } } +/// The lawful value type has to actually be lawful, or every "real defect" the +/// comparison attributes to the crate could be its fault instead. +/// The `shape` class's characterisation, as `bin/alg_bug_repros` case 7 states it: +/// the lockstep traversals discard dangling structure and the whole-map +/// operations preserve it. +/// +/// Pinned because the write-up had it backwards at first, and because if either +/// family changes, the right outcome is this test failing and the question being +/// settled -- not the claim quietly going stale. +#[test] +fn zipper_traversals_drop_dangling_paths_and_map_ops_keep_them() { + use pathmap::experimental::zipper_algebra::{zipper_join, zipper_meet}; + use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperWriting}; + use pathmap::PathMap; + + fn dangling(paths: &[&[u8]]) -> PathMap { + let mut m = PathMap::new(); + let mut wz = m.write_zipper(); + for p in paths { + wz.reset(); + wz.descend_to(*p); + wz.create_path(); + } + drop(wz); + m + } + fn paths(m: &PathMap) -> Vec> { + let mut z = m.read_zipper(); + let mut out = Vec::new(); + z.reset(); + while z.to_next_step() { + out.push(z.path().to_vec()); + } + out + } + + let d2 = dangling(&[&[0], &[1]]); + let dv = { + let mut m = dangling(&[&[0, 0]]); + m.write_zipper_at_path(&[1]).set_val(7); + m + }; + + let mut zj = PathMap::::new(); + { + let (mut a, mut b) = (d2.read_zipper(), dv.read_zipper()); + let mut wz = zj.write_zipper(); + zipper_join(&mut a, &mut b, &mut wz); + } + // The traversal keeps only the path that carries a value. + assert_eq!(paths(&zj), vec![vec![1]]); + // The whole-map operation keeps the dangling structure too. + assert_eq!(paths(&d2.join(&dv)), vec![vec![0], vec![0, 0], vec![1]]); + + let mut zm = PathMap::::new(); + { + let (mut a, mut b) = (d2.read_zipper(), dv.read_zipper()); + let mut wz = zm.write_zipper(); + zipper_meet(&mut a, &mut b, &mut wz); + } + assert!(paths(&zm).is_empty()); + assert_eq!(paths(&d2.meet(&dv)), vec![vec![0], vec![1]]); + + // The write-zipper forms side with the whole-map operations. + let mut wi = d2.clone(); + { + let mut wz = wi.write_zipper(); + wz.meet_into(&dv.read_zipper(), false); + } + assert_eq!(paths(&wi), paths(&d2.meet(&dv))); +} + +/// The zipper algebra over `PathMap<()>`, which `zipper_algebra.rs` does not +/// test at all -- every test there uses `u64`. +/// +/// `()` is lawful, so these are plain set operations and the expected answers +/// are not open to interpretation. Spelled out rather than compared against +/// `PathMap::join` and friends, because those have defects of their own. +#[test] +fn zipper_algebra_over_the_unit_type() { + use pathmap::experimental::zipper_algebra::{ + zipper_join, zipper_meet, zipper_n_meet, zipper_n_sym_diff, zipper_subtract, + zipper_sym_diff, + }; + use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperValues}; + use pathmap::PathMap; + + fn mk(paths: &[&[u8]]) -> PathMap<()> { + let mut m = PathMap::new(); + for p in paths { + m.set_val_at(p, ()); + } + m + } + fn set(m: &PathMap<()>) -> Vec> { + let mut z = m.read_zipper(); + let mut out = Vec::new(); + z.reset(); + while z.to_next_step() { + if z.val().is_some() { + out.push(z.path().to_vec()); + } + } + out + } + + let a = mk(&[&[0, 1], &[0, 2], &[3]]); + let b = mk(&[&[0, 2], &[3], &[4]]); + let c = mk(&[&[0, 2], &[5]]); + + macro_rules! pair { + ($f:ident) => {{ + let mut out = PathMap::<()>::new(); + { + let (mut za, mut zb) = (a.read_zipper(), b.read_zipper()); + let mut wz = out.write_zipper(); + $f(&mut za, &mut zb, &mut wz); + } + set(&out) + }}; + } + assert_eq!(pair!(zipper_join), vec![vec![0, 1], vec![0, 2], vec![3], vec![4]]); + assert_eq!(pair!(zipper_meet), vec![vec![0, 2], vec![3]]); + assert_eq!(pair!(zipper_subtract), vec![vec![0, 1]]); + // Present in exactly one side. + assert_eq!(pair!(zipper_sym_diff), vec![vec![0, 1], vec![4]]); + + macro_rules! triple { + ($f:ident) => {{ + let mut out = PathMap::<()>::new(); + { + let mut zs = [a.read_zipper(), b.read_zipper(), c.read_zipper()]; + let mut wz = out.write_zipper(); + $f(&mut zs, &mut wz); + } + set(&out) + }}; + } + // Only [0,2] is in all three. + assert_eq!(triple!(zipper_n_meet), vec![vec![0, 2]]); + // Odd number of occurrences: [0,1] in one, [0,2] in three, [3] in two, [4] + // and [5] in one each. + assert_eq!( + triple!(zipper_n_sym_diff), + vec![vec![0, 1], vec![0, 2], vec![4], vec![5]] + ); +} + +#[test] +fn bits_is_a_boolean_algebra() { + let sample: Vec = (1u64..16).map(Bits).collect(); + let r = |x: AlgebraicResult, l: Bits, rr: Bits| match x { + AlgebraicResult::Element(v) => Some(v), + // SELF_IDENT == 1 + AlgebraicResult::Identity(m) => Some(if m & 1 != 0 { l } else { rr }), + AlgebraicResult::None => None, + }; + let raw = |v: Option| v.map(|b| b.0).unwrap_or(0); + + for &a in &sample { + for &b in &sample { + // The operations are the bitwise ones, and bottom is absence. + assert_eq!(raw(r(a.pjoin(&b), a, b)), a.0 | b.0, "join {a:?} {b:?}"); + assert_eq!(raw(r(a.pmeet(&b), a, b)), a.0 & b.0, "meet {a:?} {b:?}"); + assert_eq!(raw(r(a.psubtract(&b), a, b)), a.0 & !b.0, "sub {a:?} {b:?}"); + // Commutative, which is exactly what makes the u64 value bias + // invisible here and so must hold. + assert_eq!(a.0 | b.0, b.0 | a.0); + assert_eq!(a.0 & b.0, b.0 & a.0); + // The two formulas for symmetric difference agree -- the identity + // whose failure under u64 started this. + assert_eq!((a.0 | b.0) & !(a.0 & b.0), (a.0 & !b.0) | (b.0 & !a.0)); + for &c in &sample { + // Distributive, both ways round. + assert_eq!(a.0 & (b.0 | c.0), (a.0 & b.0) | (a.0 & c.0)); + assert_eq!(a.0 | (b.0 & c.0), (a.0 | b.0) & (a.0 | c.0)); + } + } + } +} + +/// The reason for preferring a bitmask over some other lawful lattice: it has to +/// produce values that are not simply one of the operands, or the code that +/// stores a combined value is never reached. See `bin/alg_lattice_check`. +#[test] +fn bits_reaches_the_element_path_and_u64_does_not() { + let bits: Vec = (1u64..16).map(Bits).collect(); + let mut bits_join_element = false; + let mut bits_meet_element = false; + for &a in &bits { + for &b in &bits { + bits_join_element |= matches!(a.pjoin(&b), AlgebraicResult::Element(_)); + bits_meet_element |= matches!(a.pmeet(&b), AlgebraicResult::Element(_)); + } + } + assert!(bits_join_element, "Bits::pjoin must be able to return Element"); + assert!(bits_meet_element, "Bits::pmeet must be able to return Element"); + + // u64 cannot, which is the coverage gap the lawful type exists to close. + for a in 1u64..8 { + for b in 1u64..8 { + assert!(!matches!(a.pjoin(&b), AlgebraicResult::Element(_))); + assert!(!matches!(a.pmeet(&b), AlgebraicResult::Element(_))); + } + } +} + +/// Route `k` must mean the same strategies under every value type, or the +/// per-type comparison compares different things. +#[test] +fn route_numbering_is_the_same_for_every_value_type() { + for op in Op::ALL { + let n = algebraic::routes::strategies(op).len(); + for k in 0..algebraic::routes::POINTWISE_ROUTES { + // `strategies` takes no type parameter precisely so this holds; the + // assertion is here to stop that being reintroduced. + assert_eq!(k % n, k % algebraic::routes::strategies(op).len()); + } + } + assert!(::LAWFUL); + assert!(<() as FuzzValue>::LAWFUL); + assert!(!::LAWFUL); + // The overlay join strategy cannot work for a type whose join creates + // values, because OverlayZipper's mapping returns a reference. + assert!(!::JOIN_PICKS_LEFT); + assert!(::JOIN_PICKS_LEFT); +} + #[test] fn every_strategy_index_is_reachable_from_some_pointwise_route() { // Route `k` picks strategy `k % n` per operator, so POINTWISE_ROUTES has to From 51e3dbf9e9ed05ea90973f2a17b4ff0352225182 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 22:37:01 +0000 Subject: [PATCH 05/17] Fuzz SubtractZipper in the algebraic fuzzer Two whole-expression routes, appended after the existing ones so no route number or KNOWN signature moves: - subtract_zipper: every `-` through the lazy SubtractZipper, materialised by walking it; other operators through the baseline, so a divergence points at SubtractZipper or at what consumes its output. - subtract_zipper_nested: nested SubtractZippers, one reading from another, as the left input (`x - y - z ...`) or the right one (`x - (y - z)`). A new test checks that every whole-expression route applies to some random case; the first version of the nested route, plain-operand chains only, applied to none in 2000. KNOWN: the subtract_zipper route's divergences trace to existing causes. Its subtraction agrees with PathMap::subtract on every path and value, dangling paths included; the different node layout is what the baseline join then trips on (u64 bias, and the dangling-only join loss whose debug assert fires). Also re-keys the panic sites master moved: line_list_node.rs 1745->1785, 2669->2732, 2720->2783; dense_byte_node.rs 2080->2088. Found one SubtractZipper defect, fixed in the survival-search commit below this one. Without that fix, a 1M-case sweep hangs, with jobs stuck in the survival search. With it: 1M release (seed 2) and 1M debug-assert (seed 3) cases, nothing outside KNOWN, about 70s each. --- differential/ALGEBRAIC_FUZZING.md | 10 ++++ differential/src/algebraic.rs | 30 +++++++--- differential/src/algebraic/routes.rs | 88 +++++++++++++++++++++++++++- differential/tests/algebraic.rs | 35 +++++++++++ 4 files changed, 153 insertions(+), 10 deletions(-) diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 4c9fb87d..7a53b3ca 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -87,6 +87,16 @@ is ever built: | `nary_poly` | the same chain | `ZipperMergeF::join_n` and friends, via the `PolyZipper` enum | | `dnf` | a join of meets | `zipper_merge_dnf` | | `model` | anything | a flat `BTreeMap`, no trie at all | +| `subtract_zipper` | anything with a subtraction | every `-` through the lazy `SubtractZipper`, other operators through the baseline | +| `subtract_zipper_nested` | a left spine `x - y - z ...` of two or more subtractions, or `x - (y - z)` | nested `SubtractZipper`s, one reading from another; the `x`s go through the baseline | + +The two `SubtractZipper` routes are routes of their own, not a fourth subtract +strategy for the pointwise routes: a new strategy would renumber which mix each +`pw#k` uses, and a new finding would land under a `pw` signature `KNOWN` already +attributes to something else. Holding the other operators at the baseline means a +divergence on them points at `SubtractZipper` or at what consumes its output. +Both walk the zipper with `to_next_step` and materialise the result; the walk +records dangling paths, so nothing is lost in the comparison. The `model` route is the fourth opinion. Every other route goes through `pathmap`, so a defect common to the whole algebra layer would make them agree diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index 56f00a54..ad2c4361 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -568,6 +568,11 @@ pub const KNOWN: &[Known] = &[ Known { signature: "u64:shape:nary", cause: DANGLING }, Known { signature: "u64:shape:nary_poly", cause: DANGLING }, Known { signature: "u64:shape:dnf", cause: DANGLING }, + // The subtract_zipper route's own subtraction agrees with PathMap::subtract + // on every path and value; it builds a different node layout, and the + // baseline join or meet that consumes it is what then goes wrong. + Known { signature: "u64:values:subtract_zipper", cause: BIAS_OR_LOSS }, + Known { signature: "u64:shape:subtract_zipper", cause: DANGLING }, Known { signature: "u64:law:join-associative", cause: BIAS_OR_LOSS }, Known { signature: "u64:law:join-distributes-over-meet", cause: BIAS_OR_LOSS }, Known { signature: "u64:law:majority-is-pairwise-meets", cause: BIAS_OR_LOSS }, @@ -579,9 +584,9 @@ pub const KNOWN: &[Known] = &[ Known { signature: "u64:law:absorb-join-meet", cause: BIAS }, Known { signature: "u64:law:sym-diff-is-join-minus-meet", cause: BIAS }, Known { signature: "u64:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "u64:panic:eval:line_list_node.rs:2669", cause: LOSS }, - Known { signature: "u64:panic:eval:line_list_node.rs:2720", cause: LOSS }, - Known { signature: "u64:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + Known { signature: "u64:panic:eval:line_list_node.rs:2732", cause: LOSS }, + Known { signature: "u64:panic:eval:line_list_node.rs:2783", cause: LOSS }, + Known { signature: "u64:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, // ---------------------------------------------------------------- bits // The lawful type. Everything here is a real defect: there is no value @@ -610,15 +615,20 @@ pub const KNOWN: &[Known] = &[ Known { signature: "bits:shape:nary", cause: DANGLING }, Known { signature: "bits:shape:nary_poly", cause: DANGLING }, Known { signature: "bits:shape:dnf", cause: DANGLING }, + // About once per million: SubtractZipper's result is dangling-only and + // equal in shape to the baseline's, and the join after it loses the other + // operand's value (the debug assert behind cause 2 fires). + Known { signature: "bits:values:subtract_zipper", cause: LOSS }, + Known { signature: "bits:shape:subtract_zipper", cause: DANGLING }, Known { signature: "bits:law:join-associative", cause: LOSS }, Known { signature: "bits:law:join-commutative", cause: LOSS }, Known { signature: "bits:law:join-distributes-over-meet", cause: LOSS }, Known { signature: "bits:law:sym-diff-is-join-minus-meet", cause: LOSS }, Known { signature: "bits:law:majority-is-pairwise-meets", cause: LOSS }, Known { signature: "bits:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "bits:panic:eval:line_list_node.rs:2669", cause: LOSS }, - Known { signature: "bits:panic:eval:line_list_node.rs:2720", cause: LOSS }, - Known { signature: "bits:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + Known { signature: "bits:panic:eval:line_list_node.rs:2732", cause: LOSS }, + Known { signature: "bits:panic:eval:line_list_node.rs:2783", cause: LOSS }, + Known { signature: "bits:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, // ---------------------------------------------------------------- unit // `PathMap<()>`: the set case, and lawful. Nothing here can be a value // bias, because there is no value to misplace -- so every entry is either a @@ -642,17 +652,19 @@ pub const KNOWN: &[Known] = &[ Known { signature: "unit:shape:nary", cause: DANGLING }, Known { signature: "unit:shape:nary_poly", cause: DANGLING }, Known { signature: "unit:shape:dnf", cause: DANGLING }, + Known { signature: "unit:values:subtract_zipper", cause: LOSS }, + Known { signature: "unit:shape:subtract_zipper", cause: DANGLING }, Known { signature: "unit:law:join-associative", cause: LOSS }, Known { signature: "unit:law:join-commutative", cause: LOSS }, Known { signature: "unit:law:join-distributes-over-meet", cause: LOSS }, Known { signature: "unit:law:sym-diff-is-join-minus-meet", cause: LOSS }, Known { signature: "unit:law:majority-is-pairwise-meets", cause: LOSS }, Known { signature: "unit:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, - Known { signature: "unit:panic:eval:line_list_node.rs:2669", cause: LOSS }, - Known { signature: "unit:panic:eval:dense_byte_node.rs:2080", cause: LOSS }, + Known { signature: "unit:panic:eval:line_list_node.rs:2732", cause: LOSS }, + Known { signature: "unit:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, // Fires roughly once per million random cases, and the corpus reproduces it // for all three types. - Known { signature: "unit:panic:eval:line_list_node.rs:2720", cause: LOSS }, + Known { signature: "unit:panic:eval:line_list_node.rs:2783", cause: LOSS }, // Two laws that fire only under `unit`, both once per couple of million // cases, and both cause 2. `unit` reaches it where the other types do not // because every value is identical, so `merkleize` and `clone` share far diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs index 277a9d6d..9a025906 100644 --- a/differential/src/algebraic/routes.rs +++ b/differential/src/algebraic/routes.rs @@ -31,7 +31,8 @@ use pathmap::experimental::zipper_algebra::{ zipper_subtract3, zipper_sym_diff, zipper_sym_diff3, ZipperMergeF, }; use pathmap::zipper::{ - OverlayZipper, ReadZipperUntracked, ZipperMoving, ZipperPath, ZipperValues, ZipperWriting, + OverlayZipper, ReadZipperUntracked, SubtractZipper, ZipperMoving, ZipperPath, ZipperValues, + ZipperWriting, }; use super::expr::{Expr, Op}; @@ -87,6 +88,20 @@ pub enum Route { NaryPoly, /// `zipper_merge_dnf` on a join of meets. Dnf, + /// Every subtraction through the lazy `SubtractZipper`, materialised, and + /// every other operator through the baseline's whole-map call. + /// + /// A route of its own rather than a fourth subtract strategy: adding a + /// strategy would renumber which mix each `pw#k` route uses, and a new + /// finding would land under a `pw` signature `KNOWN` already attributes to + /// another cause. Holding the other operators at the baseline also means a + /// divergence here can only come from `SubtractZipper`. + SubtractZipper, + /// Nested `SubtractZipper`s, materialised once at the end: a left spine of + /// subtractions `x - y - z ...` with each zipper the left input of the + /// next, or `x - (y - z)` with one as the right input. This is the route + /// that tests a `SubtractZipper` reading from another one. + SubtractZipperNested, /// Flat `BTreeMap` semantics, no trie. Values only; abstains on structure. Model, } @@ -100,6 +115,8 @@ impl Route { Route::NaryPoly, Route::Dnf, Route::Model, + Route::SubtractZipper, + Route::SubtractZipperNested, ]); v } @@ -127,6 +144,8 @@ impl Route { Route::NaryPoly => "nary_poly".into(), Route::Dnf => "dnf".into(), Route::Model => "model".into(), + Route::SubtractZipper => "subtract_zipper".into(), + Route::SubtractZipperNested => "subtract_zipper_nested".into(), } } } @@ -169,6 +188,8 @@ pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Op operands.iter().map(|m| values_of_shape(&shape_of_map(m))).collect(); Some(Outcome { values: model::eval(e, &vals), shape: None }) } + Route::SubtractZipper => subtract_zipper(e, operands).map(|m| Outcome::from_map(&m)), + Route::SubtractZipperNested => subtract_zipper_nested(e, operands).map(|m| Outcome::from_map(&m)), } } @@ -368,8 +389,73 @@ where out } +/// [`Route::SubtractZipper`]. `None` when `e` has no subtraction, because the +/// route would then be the baseline over again. +fn subtract_zipper(e: &Expr, operands: &[PathMap]) -> Option> { + fn go(e: &Expr, operands: &[PathMap]) -> PathMap { + match e { + Expr::Var(i) => operands[*i].clone(), + Expr::Bin(op, l, r) => { + let a = go(l, operands); + let b = go(r, operands); + if *op == Op::Subtract { + materialize(SubtractZipper::new(a.read_zipper(), b.read_zipper())) + } else { + apply(*op, 0, &a, &b).expect("strategy 0 applies to every value type") + } + } + } + } + let mut ops = Vec::new(); + collect_ops(e, &mut ops); + ops.contains(&Op::Subtract).then(|| go(e, operands)) +} + // -------------------------------------------------------- whole-expression +/// [`Route::SubtractZipperNested`]. +/// +/// The expression's left spine of subtractions, `x0 - x1 - ... - xk`, becomes +/// `k` nested zippers when `k >= 2`. With a single subtraction whose right +/// operand is itself one, `x - (y - z)`, the inner zipper is the right input +/// instead. The `x`s may be any subexpression; they go through the baseline. +fn subtract_zipper_nested(e: &Expr, operands: &[PathMap]) -> Option> { + let mut spine: Vec<&Expr> = Vec::new(); + let mut cur = e; + while let Expr::Bin(Op::Subtract, l, r) = cur { + spine.push(r); + cur = l; + } + spine.push(cur); + spine.reverse(); + let base = |x: &Expr| pointwise(0, x, operands).expect("strategy 0 applies to every value type"); + + if spine.len() == 2 { + let Expr::Bin(Op::Subtract, y, z) = spine[1] else { return None }; + let (x, y, z) = (base(spine[0]), base(y), base(z)); + let rhs = SubtractZipper::new(y.read_zipper(), z.read_zipper()); + return Some(materialize(SubtractZipper::new(x.read_zipper(), rhs))); + } + + let maps: Vec> = spine.iter().map(|x| base(x)).collect(); + let rz = |i: usize| maps[i].read_zipper(); + // Each level of nesting is a different type, so the chain is spelled out + // per length. + macro_rules! nest { + ($z:expr) => { $z }; + ($z:expr, $next:expr $(, $rest:expr)*) => { + nest!(SubtractZipper::new($z, $next) $(, $rest)*) + }; + } + Some(match maps.len() { + 3 => materialize(nest!(rz(0), rz(1), rz(2))), + 4 => materialize(nest!(rz(0), rz(1), rz(2), rz(3))), + 5 => materialize(nest!(rz(0), rz(1), rz(2), rz(3), rz(4))), + 6 => materialize(nest!(rz(0), rz(1), rz(2), rz(3), rz(4), rz(5))), + _ => return None, + }) +} + /// Chain of exactly three operands through the `*3` entry points. fn ternary(e: &Expr, operands: &[PathMap]) -> Option> { let (op, idx) = e.chain()?; diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 05ceae33..40616476 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -422,3 +422,38 @@ fn every_strategy_index_is_reachable_from_some_pointwise_route() { } } } + +#[test] +fn every_whole_expression_route_applies_to_some_random_case() { + // A route whose shape the generator never produces would pass every sweep + // without testing anything, so check that each one actually runs. + use algebraic::routes::{eval, Route}; + const CASES: usize = 2_000; + let mut rng = algebraic::Rng::for_job(20261023, 0); + let routes: Vec = + Route::all().into_iter().filter(|r| !matches!(r, Route::Pointwise(_))).collect(); + let mut applied = vec![0usize; routes.len()]; + let _ = with_quiet_panics(|| { + for _ in 0..CASES { + let bytes = rng.input(); + // Building the operands can panic (the known merkleize defect). + let Ok(case) = std::panic::catch_unwind(|| algebraic::decode::(&bytes)) else { + continue; + }; + for (n, r) in applied.iter_mut().zip(&routes) { + let got = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + eval(*r, &case.expr, &case.operands).is_some() + })); + if got.unwrap_or(true) { + *n += 1; + } + } + } + }); + for (r, n) in routes.iter().zip(&applied) { + eprintln!("{:>24}: applies to {n} of {CASES}", r.name(&Expr::Var(0))); + } + for (r, n) in routes.iter().zip(&applied) { + assert!(*n > 0, "route {} never applies in {CASES} random cases", r.name(&Expr::Var(0))); + } +} From 51a7a1ddb41838c4463a02fd4ce0241ece669cbc Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 23:15:38 +0000 Subject: [PATCH 06/17] CI: run the algebraic equivalence fuzzer New alg-fuzz job, after the tests, on PRs, pushes to master and manual runs: - the harness gate (cargo test -p differential --test algebraic); - a release sweep and a debug-assertions sweep, 1M cases each with a fixed seed by default (alg_fuzz_cases / alg_fuzz_seed inputs on manual runs), failing on any signature missing from algebraic::KNOWN; - each sweep under `timeout`, since a hang is a finding too; - a step summary per sweep (verdict plus the per-value-type table, and the command to reproduce) and the saved inputs as the alg-fuzz-out artifact. The debug build repeats target-cpu=native in RUSTFLAGS (it replaces .cargo/config.toml's flags and gxhash needs it) and uses its own target dir. The bench job now also waits for this gate. Checked with actionlint, and by running each step's script locally under `bash -eo pipefail`: passing sweeps, an unexpected finding (exit 1), and a timeout (exit 124 with an error annotation) all report as intended. --- .github/workflows/ci.yml | 112 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef9c2018..099fb26e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,12 @@ on: benches: description: space separated bench targets (empty = default set) default: "" + alg_fuzz_cases: + description: random cases per algebraic fuzz sweep (release and debug-assert) + default: "1000000" + alg_fuzz_seed: + description: seed for the algebraic fuzz sweeps + default: "1" permissions: contents: read @@ -101,9 +107,9 @@ jobs: bench: name: bench A/B vs base - # Runs last, after the tests and the fuzz gate pass (skipped when either fails), on PRs + # Runs last, after the tests and both fuzz gates pass (skipped when any fails), on PRs # and manual runs only; a push to master has nothing to compare against. - needs: [test, fuzz] + needs: [test, fuzz, alg-fuzz] if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch' runs-on: [self-hosted, linux, x64] timeout-minutes: 300 @@ -291,3 +297,105 @@ jobs: ${{ runner.temp }}/fuzz-out/fails-* ${{ runner.temp }}/fuzz-out/repro if-no-files-found: ignore + + alg-fuzz: + name: algebraic equivalence fuzz + # No oracle: every route pathmap offers through its algebra (whole-map ops, write-zipper + # forms, experimental::zipper_algebra, OverlayZipper, SubtractZipper, ...) must give the + # same trie, and a set of lattice laws must hold. See differential/ALGEBRAIC_FUZZING.md. + # Fails on any finding whose signature is missing from differential::algebraic::KNOWN, + # which lists what already reproduces on master. The seed is fixed, so a red run + # reproduces locally with the command printed in the job summary. + needs: test + if: ${{ !cancelled() }} + runs-on: [self-hosted, linux, x64] + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + - name: toolchain + # rustup is installed per runner user on first use + run: | + [ -x "$HOME/.cargo/bin/rustup" ] || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none --no-modify-path + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + echo "CARGO_TARGET_DIR=$HOME/cache/target" >> "$GITHUB_ENV" # persists outside _work, so builds stay incremental + export PATH="$HOME/.cargo/bin:$PATH" + rustup toolchain install stable --profile minimal + rustup default stable + rustc --version && cargo --version + - name: harness gate + # recogniser invariants, a short sweep, and route coverage; no corpus in CI + run: cargo test --release -p differential --test algebraic + - name: sweep (release) + if: ${{ !cancelled() }} + env: + CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} + SEED: ${{ inputs.alg_fuzz_seed || '1' }} + OUT: ${{ runner.temp }}/alg-fuzz-out + run: | + cargo build --release -p differential --bin alg_fuzz + mkdir -p "$OUT/release" + # a hang is a finding too: the survival-search bug in SubtractZipper looped forever + rc=0 + timeout 20m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$(nproc)" \ + --out "$OUT/release" > "$OUT/release.txt" 2>&1 || rc=$? + [ $rc -eq 124 ] && echo "::error::release sweep timed out (hang?)" + tail -n 40 "$OUT/release.txt" + exit $rc + - name: sweep (debug assertions) + # debug_assert!s inside the merge primitives catch defects no route comparison sees. + # RUSTFLAGS replaces .cargo/config.toml's flags, so target-cpu=native (needed by gxhash) + # is repeated; a separate target dir keeps the release build intact. + if: ${{ !cancelled() }} + env: + CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} + SEED: ${{ inputs.alg_fuzz_seed || '1' }} + OUT: ${{ runner.temp }}/alg-fuzz-out + RUSTFLAGS: -C target-cpu=native -C debug-assertions=yes + run: | + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/dbgassert" + cargo build --release -p differential --bin alg_fuzz + mkdir -p "$OUT/dbgassert" + rc=0 + timeout 30m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$(nproc)" \ + --out "$OUT/dbgassert" > "$OUT/dbgassert.txt" 2>&1 || rc=$? + [ $rc -eq 124 ] && echo "::error::debug-assert sweep timed out (hang?)" + tail -n 40 "$OUT/dbgassert.txt" + exit $rc + - name: summary + if: always() + env: + CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} + SEED: ${{ inputs.alg_fuzz_seed || '1' }} + OUT: ${{ runner.temp }}/alg-fuzz-out + run: | + { + echo "### Algebraic equivalence fuzz" + for mode in release dbgassert; do + f="$OUT/$mode.txt" + [ -e "$f" ] || continue + if ! grep -q '^checked' "$f"; then + # alg_fuzz reports only at the end, so a killed run leaves no counts + echo; echo "**$mode**: no report (timed out or crashed; see the step log)" + continue + fi + echo + echo "**$mode** ($(grep -m 1 '^checked' "$f")): $(tail -n 1 "$f")" + echo + echo "
findings by value type" + echo + echo '```text' + sed -n '/^by value type/,/^seen under/p' "$f" | grep -v '^seen under' + echo '```' + echo "
" + done + echo + echo "Reproduce: \`cargo run --release -p differential --bin alg_fuzz -- --random $CASES --seed $SEED --jobs $(nproc)\`" + echo "(debug assertions: add \`RUSTFLAGS='-C target-cpu=native -C debug-assertions=yes'\`)." + echo "Saved inputs are in the \`alg-fuzz-out\` artifact; shrink one with \`--shrink FILE --target SIG\`." + } >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: alg-fuzz-out + path: ${{ runner.temp }}/alg-fuzz-out + if-no-files-found: ignore From ead93af0b2b938a914d686aa29843ac6e117414b Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 23:34:29 +0000 Subject: [PATCH 07/17] alg_fuzz: report a panic that aborts, with the input that caused it A non-unwinding panic (a debug-mode unsafe-precondition check, a panic in a destructor during unwinding) aborts the process, so it can never become a finding, and the quiet hook used to swallow its message: CI saw only "thread caused non-unwinding panic. aborting." Print the message, the site, a backtrace and the current input as hex, so the abort names its reproducer. The first one it caught: under Rust 1.99 with debug assertions, gxhash 3.5.0's get_partial_unsafe reads 16 bytes past short inputs, and std's _mm_loadu_si128 now checks copy_nonoverlapping, so merkleize aborts when the over-read overlaps a stack local. Layout dependent, so per binary and thread. --- differential/src/algebraic.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index ad2c4361..2bbc8582 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -732,6 +732,10 @@ std::thread_local! { /// line called "panic". A hook is the only way to see it. static PANIC_SITE: core::cell::RefCell = const { core::cell::RefCell::new(String::new()) }; + /// The input [`run_all`] is checking, so a panic that aborts the process + /// can still name its reproducer. + static CURRENT_INPUT: core::cell::RefCell> = + const { core::cell::RefCell::new(Vec::new()) }; } /// Replace the panic hook with one that records the panic site and prints @@ -752,6 +756,25 @@ pub fn install_panic_hook() { format!("{f}:{}", l.line()) }) .unwrap_or_else(|| "?".to_string()); + // A panic that cannot unwind aborts the whole process, so it can never + // become a finding; say what and where before the abort, or the run just + // dies with "thread caused non-unwinding panic". Stable Rust cannot ask + // `info` whether it unwinds, so match std's messages for the three cases: + // a debug-mode unsafe-precondition check, a panic in a destructor during + // unwinding, and a panic in a function that cannot unwind. + let msg = info.payload_as_str().unwrap_or(""); + if msg.starts_with("unsafe precondition") + || msg.starts_with("panic in a destructor") + || msg.starts_with("panic in a function that cannot unwind") + { + let input: String = CURRENT_INPUT + .with(|c| c.try_borrow().map(|b| b.iter().map(|x| format!("{x:02x}")).collect())) + .unwrap_or_default(); + eprintln!( + "non-unwinding panic at {site}: {msg}\ninput (hex, replay with xxd -r -p): {input}\n{}", + std::backtrace::Backtrace::force_capture() + ); + } PANIC_SITE.with(|s| *s.borrow_mut() = site); })); } @@ -809,6 +832,11 @@ pub const VALUE_TYPES: &[&str] = &[ /// both -- or under `bits` alone -- is a defect in the crate. Checking only the /// lawful type would be cheaper and would lose the comparison. pub fn run_all(bytes: &[u8], f: &mut impl FnMut(&'static str, Outcome)) { + CURRENT_INPUT.with(|c| { + let mut c = c.borrow_mut(); + c.clear(); + c.extend_from_slice(bytes); + }); f(::NAME, run::(bytes)); f(::NAME, run::(bytes)); f(<() as FuzzValue>::NAME, run::<()>(bytes)); From b3fcdafba1c176701473dcb22a0cf643a74c49f0 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 23:34:29 +0000 Subject: [PATCH 08/17] CI: fix the algebraic fuzzer's job count at 64 Each job draws its own input stream, so --jobs "$(nproc)" made the inputs depend on the runner: a 192-core runner fuzzed cases no 64-core machine ever ran, and its findings did not reproduce elsewhere. A fixed 64 runs the same inputs everywhere (oversubscribed on smaller machines), and the reproduce command in the summary is exact. --- .github/workflows/ci.yml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 099fb26e..b825c546 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -304,8 +304,10 @@ jobs: # forms, experimental::zipper_algebra, OverlayZipper, SubtractZipper, ...) must give the # same trie, and a set of lattice laws must hold. See differential/ALGEBRAIC_FUZZING.md. # Fails on any finding whose signature is missing from differential::algebraic::KNOWN, - # which lists what already reproduces on master. The seed is fixed, so a red run - # reproduces locally with the command printed in the job summary. + # which lists what already reproduces on master. The seed and the job count are fixed, so + # a red run reproduces locally with the command printed in the job summary: each job draws + # its own input stream, so --jobs decides which inputs run, not only how fast. 64 is the + # cap; a smaller machine runs the same inputs, oversubscribed. needs: test if: ${{ !cancelled() }} runs-on: [self-hosted, linux, x64] @@ -330,13 +332,14 @@ jobs: env: CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} SEED: ${{ inputs.alg_fuzz_seed || '1' }} + JOBS: 64 OUT: ${{ runner.temp }}/alg-fuzz-out run: | cargo build --release -p differential --bin alg_fuzz mkdir -p "$OUT/release" # a hang is a finding too: the survival-search bug in SubtractZipper looped forever rc=0 - timeout 20m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$(nproc)" \ + timeout 20m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$JOBS" \ --out "$OUT/release" > "$OUT/release.txt" 2>&1 || rc=$? [ $rc -eq 124 ] && echo "::error::release sweep timed out (hang?)" tail -n 40 "$OUT/release.txt" @@ -349,6 +352,7 @@ jobs: env: CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} SEED: ${{ inputs.alg_fuzz_seed || '1' }} + JOBS: 64 OUT: ${{ runner.temp }}/alg-fuzz-out RUSTFLAGS: -C target-cpu=native -C debug-assertions=yes run: | @@ -356,7 +360,7 @@ jobs: cargo build --release -p differential --bin alg_fuzz mkdir -p "$OUT/dbgassert" rc=0 - timeout 30m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$(nproc)" \ + timeout 30m "$CARGO_TARGET_DIR/release/alg_fuzz" --random "$CASES" --seed "$SEED" --jobs "$JOBS" \ --out "$OUT/dbgassert" > "$OUT/dbgassert.txt" 2>&1 || rc=$? [ $rc -eq 124 ] && echo "::error::debug-assert sweep timed out (hang?)" tail -n 40 "$OUT/dbgassert.txt" @@ -366,6 +370,7 @@ jobs: env: CASES: ${{ inputs.alg_fuzz_cases || '1000000' }} SEED: ${{ inputs.alg_fuzz_seed || '1' }} + JOBS: 64 OUT: ${{ runner.temp }}/alg-fuzz-out run: | { @@ -389,7 +394,7 @@ jobs: echo "" done echo - echo "Reproduce: \`cargo run --release -p differential --bin alg_fuzz -- --random $CASES --seed $SEED --jobs $(nproc)\`" + echo "Reproduce: \`cargo run --release -p differential --bin alg_fuzz -- --random $CASES --seed $SEED --jobs $JOBS\`" echo "(debug assertions: add \`RUSTFLAGS='-C target-cpu=native -C debug-assertions=yes'\`)." echo "Saved inputs are in the \`alg-fuzz-out\` artifact; shrink one with \`--shrink FILE --target SIG\`." } >> "$GITHUB_STEP_SUMMARY" From 77a60a30025a2a2c640ffab754cdf89e3464fef3 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Fri, 23 Oct 2026 23:49:50 +0000 Subject: [PATCH 09/17] Pin gxhash to the commit that stops it aborting debug builds gxhash 3.5.0 hashes inputs shorter than 16 bytes with a 16-byte _mm_loadu_si128 that reads past their end. Since Rust 1.99 that intrinsic is a checked copy_nonoverlapping, so with debug assertions merkleize could abort with "unsafe precondition(s) violated" (the CI debug-assert sweep did, on Rust 1.99.1). Upstream: ogxd/gxhash#111, still open; 3.5.0 is the latest release. Pin to 390c3e5 (ogxd/gxhash#118), which does that load with inline assembly and is otherwise 3.5.0. Not main: that is gxhash 4.0, and gxhash only keeps hash values stable within a major version. Checked: - hash values identical to 3.5.0: gxhash128, gxhash64 and GxHasher over every length 0-200 at every alignment, four seeds (12864 cases); - Rust 1.99.1 with debug assertions: both captured aborting inputs replay clean, and 1M-case sweeps at 192 and 64 jobs finish with nothing unexpected; - cargo test on 1.99.1 (release, arena_compact+random, debug lib) and on the local nightly: all pass. --- Cargo.toml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 859b8b5d..a7d96ebd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,17 @@ zipper_alg = [] # Enables experimental implementations of Zipper-based algebraic fast-slice-utils = { version = "0.1.2", features = ["miri_safe"] } [target.'cfg(not(any(miri,target_arch="riscv64")))'.dependencies] -gxhash = {version="3.5"} # for dag_serialization, merkleization, and caching catamorphism +# gxhash: for dag_serialization, merkleization, and caching catamorphism. +# +# Pinned to a git commit instead of the 3.5.0 release. 3.5.0 hashes inputs shorter than 16 bytes with a +# 16-byte `_mm_loadu_si128` that reads past their end. Since Rust 1.99 `_mm_loadu_si128` is a checked +# `copy_nonoverlapping`, so in a build with debug assertions that over-read can fail "unsafe precondition(s) +# violated" and abort the process (seen in `merkleize`; it depends on stack layout, so it comes and goes by +# binary and thread). Upstream: https://github.com/ogxd/gxhash/issues/111. +# Commit 390c3e5 (PR #118) does that load with inline assembly instead and is otherwise 3.5.0, so hash values +# do not change. Do not move to gxhash 4.0 (main) without checking serialized hashes: gxhash only keeps hashes +# stable within a major version. Go back to a crates.io version once a 3.x release has this commit. +gxhash = { git = "https://github.com/ogxd/gxhash", rev = "390c3e5bc07a0b57026982686f69caa442473969" } [target.'cfg(any(miri,target_arch="riscv64"))'.dependencies] xxhash-rust = { version = "0.8.15", features = ["xxh64", "xxh3", "const_xxh3"] } # Replacement for gxhash running under miri From 1e97e10214f977801c9de6d070d09c1b52261e78 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Sat, 31 Oct 2026 14:44:22 +0000 Subject: [PATCH 10/17] alg_fuzz: check the laws Zippy.lean proves, over Zippy's operators The hand-written identities in laws.rs are gone. The laws are now the theorems of lean/PrunedModel/Zippy.lean (branch spec/zippy-laws), which proves formal.egg's space algebra over the pruned model. lean/ZippyLaws.lean reads the elaborated theorems, keeps every sorry-free equation between spaces over operators the fuzzer can evaluate, and prints them as src/algebraic/zippy_laws.rs: 70 laws, with the 75 theorems it skips listed at the bottom with the reason. A law is a template over spaces, paths and bytes, with hypotheses (a != b, p not in s, head x = empty). A case now carries a few paths and bytes for those, mostly prefixes and first bytes of its own operands, and a law whose hypotheses are false for them is skipped for that case. The theorems are about PrunedMap Unit, so they are checked for the unit value type only. So that they can be stated, the expression language gains the rest of Zippy's operators: the empty space, singleton, wrap, unwrap, head, tails_union, tails_inter, composition and iter_c, each with two or three strategies through different crate code (graft_map, PrefixZipper and insert_prefix for wrap; make_map and take_map for unwrap; ...). An expression using one gets +zippy on its signatures, so a finding there cannot hide under one already attributed. A new test checks every generated law against the flat model, which validates the translation. Two new reproducers: 8, meet_into keeps the destination's focus value instead of meeting it (bits only); 9, take_map of a value-only focus returns a map that panics on its first write. Both are fixed on this branch. --- differential/ALGEBRAIC_FUZZING.md | 104 ++- differential/src/algebraic.rs | 283 +++++--- differential/src/algebraic/expr.rs | 181 +++++- differential/src/algebraic/laws.rs | 449 +++++++------ differential/src/algebraic/model.rs | 76 ++- differential/src/algebraic/routes.rs | 290 +++++++-- differential/src/algebraic/value.rs | 20 + differential/src/algebraic/zippy_laws.rs | 790 +++++++++++++++++++++++ differential/src/bin/alg_bug_repros.rs | 56 +- differential/tests/algebraic.rs | 78 ++- 10 files changed, 1943 insertions(+), 384 deletions(-) create mode 100644 differential/src/algebraic/zippy_laws.rs diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index 7a53b3ca..f3870b3f 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -75,6 +75,23 @@ is reached by some route and the routes mix them: | subtract `-` | `PathMap::subtract`, `subtract_into`, `zipper_subtract` | | sym. difference `^` | `zipper_sym_diff`, `(a \| b) - (a & b)` | | restrict `/` | `PathMap::restrict`, `WriteZipper::restrict` | +| composition `.` | `descend_to u` + `join_map_into t` per path `u`, or `PathMap::join` of grafted copies | +| `iter_c` | `val_count` below the root, or `iter` | +| `singleton` | `PathMap::single`, or `descend_to` + `set_val` | +| `wrap` | `descend_to` + `graft_map`, a materialised `PrefixZipper`, or `insert_prefix` (with the focus value moved by hand) | +| `unwrap` | `read_zipper_at_path(p).make_map()`, `descend_to` + `make_map`, or `take_map` | +| `head` | `child_mask`, or first bytes from `iter` | +| `tails_union` | a fold of `PathMap::join`, or `join_map_into` at the root | +| `tails_inter` | a fold of `PathMap::meet`, or `meet_into` | + +The operators from `composition` down are the rest of Zippy's space algebra +(`formal.egg`, proved in `lean/PrunedModel/Zippy.lean`). They are in the language +so the laws below can be stated, and because they hand the algebra tries in which +a subtrie has been moved, cut out or copied — node layouts and sharing the +crate's own operators never produce from fresh operands. A Zippy space has no +dangling paths, so `head`, the tails and `iter_c` look only at children that lead +to a value. An expression using any of them gets `+zippy` on its signatures, +so a finding there cannot hide under a signature already blamed on an old defect. **Whole-expression** routes recognise a shape and hand the entire thing to one call. These are the routes with real independence, because no intermediate trie @@ -106,17 +123,37 @@ fastest, because it has no node layout to be biased by. ### Laws Route comparison catches an implementation that disagrees with its siblings. It -cannot catch a mistake they all share. `src/algebraic/laws.rs` is the other -half: each law is two *different expressions* that must evaluate to the same -trie, so a wrong answer is visible even when every route computes it the same -wrong way. Idempotence, units, associativity, absorption, distributivity, and -the definition `zipper_sym_diff`'s own documentation gives. +cannot catch a mistake they all share. Laws are the other half: each law is two +*different expressions* that must evaluate to the same trie, so a wrong answer is +visible even when every route computes it the same wrong way. + +The laws are **generated from Lean**, not written here. `lean/ZippyLaws.lean` +(branch `spec/zippy-laws`) loads the elaborated `PrunedModel.Zippy` module, takes +every theorem that is an equation between spaces over the operators above, checks +its proof is `sorry`-free, and prints it as Rust: +`src/algebraic/zippy_laws.rs`, 70 laws. A theorem may quantify over paths and +bytes and carry hypotheses (`a ≠ b`, `p ∉ s`, `head x = empty`); each case +carries a few paths and bytes for those, mostly prefixes and first bytes of the +operands' own paths, and a law whose hypotheses are false for them is skipped. +The 75 theorems it does not export are listed at the bottom of the generated +file with the reason (membership lemmas, `≠` results, raw-zipper-op theorems, +function-typed binders). + +```sh +cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs +``` + +The theorems are about `PrunedMap Unit` — a set of paths — so they are checked +for `unit` only. Under `u64` or `bits` several are false for reasons that have +nothing to do with the crate (subtraction removes a path only when the values +cancel; a meet of two values can be bottom). `tests/algebraic.rs` checks every +generated law against the flat model, which is the membership lemmas read as +code; a failure there is the translation or the harness, never the crate. Laws are the reason a defect in the *baseline* is findable at all. When -`PathMap::meet` takes the wrong operand's value, no route disagrees with the -baseline in an interesting way — the baseline is what everyone is compared -against. `meet-distributes-over-join` has no baseline to be fooled by: it puts -the operands on different sides of a meet and notices. +`PathMap::join` loses a value, no route disagrees with the baseline in an +interesting way — the baseline is what everyone is compared against. +`union_comm` has no baseline to be fooled by. ### Three value types, and the difference between them is a measurement @@ -200,26 +237,15 @@ reaches them. `bin/alg_lattice_check` prints the table: `pathmap::utils` already implements exactly this for `[u64; 4]` and `ByteMask`, via `bitmask_algebraic_result`; `Bits` is the same construction at 64 bits. -### What the lawful type unlocked - -Four identities are checked **only** for a lawful value type, in -`laws::lawful_only` — De Morgan for relative complement both ways, -`a - b == a - (a & b)`, and symmetric difference being associative on *values* -rather than only on paths. Each fails for `u64`, for the same reason everything -else does. +### Before the generated laws -**Three of the four hold** across several million cases in both profiles: -`subtract-over-meet`, `subtract-is-subtract-meet` and `sym-diff-associative`. -They are the strongest laws the harness has and are deliberately absent from -`KNOWN`, so one of them firing is news. - -The fourth, `subtract-over-join`, fires about once per two million cases under -`unit` — and is cause 2 rather than a bad identity. Its shrunk case has a -dangling-only `b` and a `c` that is `b` plus one value, so `b | c` is exactly -finding 4. - -The `Level::Paths` laws are also promoted to `Level::Values` for a lawful type, -so commutativity of join and meet is checked on values there. +Until 2026-10-31 the laws were a hand-written list in `laws.rs`, run for every +value type, with some checked on paths only for `u64` and four more only for a +lawful type. The `law:join-associative`-style signatures and the counts above +come from that list. It found finding 4 (`join-commutative`) and showed five +findings to be `u64` artefacts; the Zippy set covers its union, intersection, +subtraction and restriction identities with proofs behind them, but has no +symmetric difference and no laws for `u64` or `bits`. ### One thing the lawful type cannot do @@ -363,7 +389,7 @@ expects the `panic:eval:*` signatures. ## Findings -Six defects on `master` at `b4a6abd`, reproduced without the fuzzer in +Six defects on `master` at `b4a6abd` (two more below), reproduced without the fuzzer in `src/bin/alg_bug_repros.rs`, plus the unsettled dangling-path question as case 7. `algebraic::KNOWN` maps every signature onto one of them. @@ -384,7 +410,8 @@ Six defects on `master` at `b4a6abd`, reproduced without the fuzzer in is a least upper bound, so no ordering of the operands may lose a path; this is the one finding that needs no argument about value bias. Found by `join-commutative`, which is checked on paths only and so cannot be fooled by - cause 3. + cause 3. The Zippy laws also reach a form with no clone at all: + `{_, dangling 1, 2} | {_, 0000}` is `{_}` (both fixed on `fix/fvc-leftovers`). 5. **`merkleize` panics on a trie holding only dangling paths.** Not algebraic: it fires while the operands are still being written. Kept rather than @@ -399,6 +426,20 @@ Six defects on `master` at `b4a6abd`, reproduced without the fuzzer in (`dense_byte_node.rs:2080`). Debug-assertions builds only, so it has no standalone reproducer — replay the `panic-eval-*` corpus inputs. +Two more, found once the expression language had Zippy's operators (repros 8, 9): + +8. **`meet_into` keeps the destination's focus value** where both sides have one, + instead of meeting them: `{_:1111} & {_:0001}` is `{_:1111}`. Invisible with + `u64`, whose meet returns the left operand anyway. Found as `tails_inter`'s two + strategies disagreeing under `bits`. + +9. **`take_map` of a value-only focus returns a map that panics on write.** The + result holds the value at its root, and the first write below it fails with + "Attempted to make_unique on an empty sentinel node". Found as `unwrap`'s + `take_map` strategy feeding `wrap`'s `insert_prefix` one. Fixed on + `fix/fvc-leftovers` by f1bdca9; still present on master and on + `focus_value_consistency`. + ## Harness invariants A harness that reports its own mistakes as crate defects is worse than no @@ -427,7 +468,8 @@ disagrees with the rest, suspect the route first. | `src/algebraic.rs` | input decoding, operand generation, the comparison, `KNOWN` | | `src/algebraic/expr.rs` | the expression language and the shape recognisers | | `src/algebraic/routes.rs` | the routes, and one arm per strategy | -| `src/algebraic/laws.rs` | the identities, and the ones deliberately absent | +| `src/algebraic/laws.rs` | law templates, binding, and the builders the generated file uses | +| `src/algebraic/zippy_laws.rs` | **generated** from `lean/PrunedModel/Zippy.lean`; do not edit | | `src/algebraic/model.rs` | flat `BTreeMap` semantics, delegating to the value algebra | | `src/algebraic/value.rs` | the `FuzzValue` trait and the lawful `Bits` type | | `src/algebraic/shape.rs` | what "the same result" means | diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index 2bbc8582..48813847 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -29,12 +29,13 @@ pub mod model; pub mod routes; pub mod shape; pub mod value; +pub mod zippy_laws; use pathmap::PathMap; use pathmap::zipper::{ZipperMoving, ZipperWriting}; -use expr::{Expr, Op, MAX_VARS}; -use laws::{Level, EMPTY, LAW_OPERANDS}; +use expr::{Expr, Op, Un, MAX_VARS}; +use laws::{Binding, Hyp}; use routes::Route; use shape::{shape_of_map, show_shape, Shape, Values}; use value::FuzzValue; @@ -119,11 +120,21 @@ pub enum Build { MerkleizedOf(usize), } +/// Paths a case offers for the path variables of a law (see `laws.rs`). +pub const LAW_PATHS: usize = 3; +/// Bytes a case offers for the byte variables of a law. +pub const LAW_BYTES: usize = 2; + pub struct Case { pub expr: Expr, pub operands: Vec>, pub builds: Vec, pub alphabet: u16, + /// What the laws' path and byte variables are bound to. Mostly prefixes + /// and first bytes of the operands' own paths, so that `unwrap`, `wrap` + /// and the hypotheses land on structure that exists. + pub law_paths: Vec>, + pub law_bytes: Vec, } /// Decode a byte string into a case. Total: every input decodes. @@ -149,7 +160,32 @@ pub fn decode(bytes: &[u8]) -> Case { } let expr = gen_expr(&mut g, 3); - Case { expr, operands, builds, alphabet } + + let keys: Vec> = operands + .iter() + .flat_map(|m| m.iter().map(|(k, _)| k).collect::>()) + .collect(); + let law_paths = (0..LAW_PATHS) + .map(|_| { + if !keys.is_empty() && g.chance(70) { + let k = &keys[g.modn(keys.len())]; + k[..g.modn(k.len() + 1)].to_vec() + } else { + g.path(2) + } + }) + .collect(); + let law_bytes = (0..LAW_BYTES) + .map(|_| { + let firsts: Vec = keys.iter().filter_map(|k| k.first().copied()).collect(); + if !firsts.is_empty() && g.chance(70) { + firsts[g.modn(firsts.len())] + } else { + g.path_byte() + } + }) + .collect(); + Case { expr, operands, builds, alphabet, law_paths, law_bytes } } fn pick_build(g: &mut Gen, i: usize) -> Build { @@ -254,14 +290,36 @@ fn gen_expr(g: &mut Gen, depth: usize) -> Expr { // never a chain of operands, so the whole-expression routes would almost // never apply. if depth == 0 || g.chance(35) { - return Expr::Var(g.modn(OPERANDS)); + // Mostly an operand. Zippy's two constant spaces now and then, since + // the laws use both and a route has to cope with them mid-expression. + return match g.modn(20) { + 0 => Expr::Empty, + 1 | 2 => Expr::Singleton(g.path(3)), + _ => Expr::Var(g.modn(OPERANDS)), + }; } - let op = match g.modn(12) { + // The crate's own algebra keeps three quarters of the interior nodes, so + // the chain and DNF recognisers still fire often; Zippy's operators take + // the rest. Their paths are short, because a long one rarely meets + // anything in tries this small. + let op = match g.modn(16) { 0 | 1 | 2 | 3 => Op::Join, 4 | 5 | 6 => Op::Meet, 7 | 8 => Op::Subtract, 9 | 10 => Op::SymDiff, - _ => Op::Restrict, + 11 => Op::Restrict, + 12 => return Expr::wrap(g.path(2), gen_expr(g, depth - 1)), + 13 => { + let e = gen_expr(g, depth - 1); + return Expr::unwrap(e, g.path(2)); + } + 14 => { + let u = Un::ALL[g.modn(Un::ALL.len())]; + return Expr::un(u, gen_expr(g, depth - 1)); + } + _ => { + if g.boolean() { Op::Compose } else { Op::IterC } + } }; Expr::bin(op, gen_expr(g, depth - 1), gen_expr(g, depth - 1)) } @@ -342,7 +400,7 @@ pub fn check(case: &Case) -> Vec { if got.values != baseline.values { out.push(Divergence { class: Class::Values, - signature: signature::("values", &route_key::(route)), + signature: signature::("values", &route_key::(route, &case.expr)), detail: format!( "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}\n {}", base_name, @@ -363,7 +421,7 @@ pub fn check(case: &Case) -> Vec { if bs != gs { out.push(Divergence { class: Class::Shape, - signature: signature::("shape", &route_key::(route)), + signature: signature::("shape", &route_key::(route, &case.expr)), detail: format!( "{} vs {name} evaluating {}: {}\n {base_name}: {}\n {name}: {}", base_name, @@ -387,52 +445,45 @@ pub fn check(case: &Case) -> Vec { /// and holds under another is already a route disagreement, which the loop /// above reports; running every law through every route would multiply the cost /// of a case by the number of laws for no new coverage. +/// +/// A law's spaces are the case's operands in order, and its paths and bytes +/// are [`Case::law_paths`] and [`Case::law_bytes`]. A law whose hypotheses +/// are false for those is skipped for this case: the theorem says nothing. pub fn check_laws(case: &Case) -> Vec { - // Operands 0..3 from the case, then the empty trie, which is what lets a - // law state a unit or annihilator. - let mut ops: Vec> = (0..EMPTY).map(|i| case.operands[i].clone()).collect(); - ops.push(PathMap::new()); - debug_assert_eq!(ops.len(), LAW_OPERANDS); + let bind = Binding { paths: &case.law_paths, bytes: &case.law_bytes }; + let eval = |e: &Expr| { + routes::eval(Route::Pointwise(0), e, &case.operands) + .expect("route 0 applies to every expression") + .values + }; let mut out = Vec::new(); - for law in laws::laws::() { - let l = routes::eval(Route::Pointwise(0), &law.lhs, &ops).unwrap(); - let r = routes::eval(Route::Pointwise(0), &law.rhs, &ops).unwrap(); - let (ok, detail) = match law.level { - Level::Values => ( - l.values == r.values, - format!( - "{}\n lhs {}: {}\n rhs {}: {}", - shape::first_values_diff(&l.values, &r.values).unwrap_or_default(), - law.lhs, - shape::show_values(&l.values), - law.rhs, - shape::show_values(&r.values), - ), - ), - Level::Paths => { - // Compare the value-carrying paths only. Comparing every path - // in the shape would drag the dangling-path question into laws - // that are not about it. - let lk: Vec<&Vec> = l.values.keys().collect(); - let rk: Vec<&Vec> = r.values.keys().collect(); - ( - lk == rk, - format!( - "lhs {}: {}\n rhs {}: {}", - law.lhs, - shape::show_values(&l.values), - law.rhs, - shape::show_values(&r.values), - ), - ) + 'laws: for law in laws::laws::() { + let inst = laws::instantiate(law, &bind); + for h in &inst.pre { + let holds = match h { + Hyp::Holds(b) => *b, + Hyp::Mem(p, e, want) => eval(e).contains_key(p) == *want, + Hyp::Eq(l, r) => eval(l) == eval(r), + }; + if !holds { + continue 'laws; } - }; - if !ok { + } + let (l, r) = (eval(&inst.lhs), eval(&inst.rhs)); + if l != r { out.push(Divergence { class: Class::Law, signature: signature::("law", law.name), - detail: format!("{} ({:?}): {detail}", law.name, law.level), + detail: format!( + "{}: {}\n lhs {}: {}\n rhs {}: {}", + law.name, + shape::first_values_diff(&l, &r).unwrap_or_default(), + inst.lhs, + shape::show_values(&l), + inst.rhs, + shape::show_values(&r), + ), }); } } @@ -470,11 +521,15 @@ pub fn signature(class: &str, rest: &str) -> String { format!("{}:{class}:{rest}", V::NAME) } -fn route_key(r: Route) -> String { - match r { +/// The route part of a signature. `+zippy` when the expression uses one of +/// Zippy's operators, so a defect in those cannot hide under a signature that +/// `KNOWN` already attributes to a defect in the crate's own algebra. +fn route_key(r: Route, e: &Expr) -> String { + let base = match r { Route::Pointwise(k) => format!("pw{k}"), _ => r.name(&Expr::Var(0)), - } + }; + if e.has_zippy() { format!("{base}+zippy") } else { base } } // ---------------------------------------------------------------- known findings @@ -520,8 +575,10 @@ pub struct Known { /// merkleizes operands instead of only writing them fresh. /// /// 3. **Root values lost by the write-zipper forms** (`root`). `join_into` -/// into an empty destination drops the source's root value, and `meet_2` -/// drops root values outright. These are routes disagreeing with the +/// into an empty destination drops the source's root value, `meet_2` +/// drops root values outright, and `meet_into` keeps the destination's +/// instead of meeting it with the source's (repro 8, visible only with +/// `bits`). These are routes disagreeing with the /// baseline in the ordinary way. /// /// 4. **Dangling paths** (`dangling`). The lockstep traversals in @@ -534,11 +591,17 @@ pub struct Known { /// algebraic defect: it fires while the operands are still being written, /// before any operation runs, which is what the `build` in its signature /// means. +/// +/// 6. **`take_map` of a value-only focus** (`take_map`). The map it returns +/// holds the value at its root, and the first write below that root panics: +/// "Attempted to make_unique on an empty sentinel node". Fixed on +/// `fix/fvc-leftovers` (f1bdca9), not on master. const BIAS: &str = "value bias by node layout, u64-only (repro 3)"; const LOSS: &str = "join loses a value across shared structure (repro 4)"; -const ROOT: &str = "write-zipper forms lose root values (repros 1, 2)"; +const ROOT: &str = "write-zipper forms lose root values (repros 1, 2, 8)"; const DANGLING: &str = "zipper traversals drop dangling paths, map ops keep them (repro 7)"; const MERKLEIZE: &str = "merkleize panics on dangling-only structure (repro 5)"; +const TAKE_MAP: &str = "take_map of a value-only focus returns a map that panics on write (repro 9)"; /// Re-nesting a join moves which operand is on the left *and* which pair of /// tries meets a shared node first, so both cause 1 and cause 2 reach these. /// Under the lawful type only cause 2 survives, which is why the counts collapse. @@ -573,16 +636,6 @@ pub const KNOWN: &[Known] = &[ // baseline join or meet that consumes it is what then goes wrong. Known { signature: "u64:values:subtract_zipper", cause: BIAS_OR_LOSS }, Known { signature: "u64:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "u64:law:join-associative", cause: BIAS_OR_LOSS }, - Known { signature: "u64:law:join-distributes-over-meet", cause: BIAS_OR_LOSS }, - Known { signature: "u64:law:majority-is-pairwise-meets", cause: BIAS_OR_LOSS }, - Known { signature: "u64:law:join-commutative", cause: LOSS }, - // These four fire only for u64: they need join and meet to be different - // functions, and for u64 they are the same one. - Known { signature: "u64:law:meet-associative", cause: BIAS }, - Known { signature: "u64:law:meet-distributes-over-join", cause: BIAS }, - Known { signature: "u64:law:absorb-join-meet", cause: BIAS }, - Known { signature: "u64:law:sym-diff-is-join-minus-meet", cause: BIAS }, Known { signature: "u64:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, Known { signature: "u64:panic:eval:line_list_node.rs:2732", cause: LOSS }, Known { signature: "u64:panic:eval:line_list_node.rs:2783", cause: LOSS }, @@ -620,11 +673,6 @@ pub const KNOWN: &[Known] = &[ // operand's value (the debug assert behind cause 2 fires). Known { signature: "bits:values:subtract_zipper", cause: LOSS }, Known { signature: "bits:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "bits:law:join-associative", cause: LOSS }, - Known { signature: "bits:law:join-commutative", cause: LOSS }, - Known { signature: "bits:law:join-distributes-over-meet", cause: LOSS }, - Known { signature: "bits:law:sym-diff-is-join-minus-meet", cause: LOSS }, - Known { signature: "bits:law:majority-is-pairwise-meets", cause: LOSS }, Known { signature: "bits:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, Known { signature: "bits:panic:eval:line_list_node.rs:2732", cause: LOSS }, Known { signature: "bits:panic:eval:line_list_node.rs:2783", cause: LOSS }, @@ -654,37 +702,90 @@ pub const KNOWN: &[Known] = &[ Known { signature: "unit:shape:dnf", cause: DANGLING }, Known { signature: "unit:values:subtract_zipper", cause: LOSS }, Known { signature: "unit:shape:subtract_zipper", cause: DANGLING }, - Known { signature: "unit:law:join-associative", cause: LOSS }, - Known { signature: "unit:law:join-commutative", cause: LOSS }, - Known { signature: "unit:law:join-distributes-over-meet", cause: LOSS }, - Known { signature: "unit:law:sym-diff-is-join-minus-meet", cause: LOSS }, - Known { signature: "unit:law:majority-is-pairwise-meets", cause: LOSS }, Known { signature: "unit:panic:build:line_list_node.rs:1785", cause: MERKLEIZE }, Known { signature: "unit:panic:eval:line_list_node.rs:2732", cause: LOSS }, Known { signature: "unit:panic:eval:dense_byte_node.rs:2088", cause: LOSS }, // Fires roughly once per million random cases, and the corpus reproduces it // for all three types. Known { signature: "unit:panic:eval:line_list_node.rs:2783", cause: LOSS }, - // Two laws that fire only under `unit`, both once per couple of million - // cases, and both cause 2. `unit` reaches it where the other types do not - // because every value is identical, so `merkleize` and `clone` share far - // more structure and the dangling-only operand that triggers the loss is - // easier to generate. - Known { signature: "unit:law:meet-distributes-over-join", cause: LOSS }, - // One of the four identities that are only checked for a lawful value type. - // It failing is still cause 2, not a bad identity: the shrunk case has a - // dangling-only `b` and a `c` that is `b` plus one value, so `b | c` is - // exactly repro 4. - Known { signature: "unit:law:subtract-over-join", cause: LOSS }, Known { signature: "unit:values:ternary", cause: LOSS }, - // Of the four identities in `laws::lawful_only` -- checked only for a lawful - // value type -- three have never failed: subtract-over-meet, - // subtract-is-subtract-meet and sym-diff-associative. They are the - // strongest laws the harness has, and they are deliberately absent from this - // table so that one of them firing is news. The fourth, - // subtract-over-join, fires once per couple of million cases under `unit`, - // and is cause 2 rather than a bad identity. + // ---------------------------------------------------------------- Zippy + // Expressions using Zippy's operators (`+zippy`). Triaged 2026-10-31 by + // shrinking one input per signature, and by a sweep with the crate's own + // operators pinned to their baseline strategy so that only the new + // operators' strategies varied: every residue is one of the causes above, + // or cause 6. They fire far more often than their plain counterparts + // because `unwrap`, `singleton` and `tails_*` put values at the root, which + // is exactly where cause 3 lives. + Known { signature: "u64:values:pw1+zippy", cause: ROOT }, + Known { signature: "u64:values:pw2+zippy", cause: ROOT }, + Known { signature: "u64:values:pw3+zippy", cause: ROOT }, + // `composition`'s `wrap_join` strategy goes through `PathMap::join`. + Known { signature: "u64:values:pw4+zippy", cause: BIAS }, + Known { signature: "u64:values:pw5+zippy", cause: BIAS }, + Known { signature: "u64:values:model+zippy", cause: BIAS }, + Known { signature: "u64:values:subtract_zipper+zippy", cause: BIAS_OR_LOSS }, + // Includes `meet_into` keeping the destination's focus value instead of + // meeting it (repro 8), which only a value type with a real meet can see. + Known { signature: "bits:values:pw1+zippy", cause: ROOT }, + Known { signature: "bits:values:pw2+zippy", cause: ROOT }, + Known { signature: "bits:values:pw3+zippy", cause: ROOT }, + Known { signature: "bits:values:pw5+zippy", cause: ROOT }, + Known { signature: "bits:values:pw4+zippy", cause: LOSS }, + Known { signature: "bits:values:model+zippy", cause: LOSS }, + Known { signature: "bits:values:subtract_zipper+zippy", cause: LOSS }, + Known { signature: "unit:values:pw1+zippy", cause: ROOT }, + Known { signature: "unit:values:pw2+zippy", cause: ROOT }, + Known { signature: "unit:values:pw3+zippy", cause: ROOT }, + Known { signature: "unit:values:pw5+zippy", cause: ROOT }, + Known { signature: "unit:values:pw4+zippy", cause: LOSS }, + Known { signature: "unit:values:model+zippy", cause: LOSS }, + Known { signature: "unit:values:subtract_zipper+zippy", cause: LOSS }, + // Includes `PrefixZipper` reporting the prefix of an empty source as + // existing, so `wrap p {}` materialises a dangling `p`. + Known { signature: "u64:shape:pw1+zippy", cause: DANGLING }, + Known { signature: "u64:shape:pw2+zippy", cause: DANGLING }, + Known { signature: "u64:shape:pw3+zippy", cause: DANGLING }, + Known { signature: "u64:shape:pw4+zippy", cause: DANGLING }, + Known { signature: "u64:shape:pw5+zippy", cause: DANGLING }, + Known { signature: "u64:shape:subtract_zipper+zippy", cause: DANGLING }, + Known { signature: "bits:shape:pw1+zippy", cause: DANGLING }, + Known { signature: "bits:shape:pw2+zippy", cause: DANGLING }, + Known { signature: "bits:shape:pw3+zippy", cause: DANGLING }, + Known { signature: "bits:shape:pw4+zippy", cause: DANGLING }, + Known { signature: "bits:shape:pw5+zippy", cause: DANGLING }, + Known { signature: "bits:shape:subtract_zipper+zippy", cause: DANGLING }, + Known { signature: "unit:shape:pw1+zippy", cause: DANGLING }, + Known { signature: "unit:shape:pw2+zippy", cause: DANGLING }, + Known { signature: "unit:shape:pw3+zippy", cause: DANGLING }, + Known { signature: "unit:shape:pw4+zippy", cause: DANGLING }, + Known { signature: "unit:shape:pw5+zippy", cause: DANGLING }, + Known { signature: "unit:shape:subtract_zipper+zippy", cause: DANGLING }, + // `unwrap`'s take_map strategy feeding `wrap`'s insert_prefix one. + Known { signature: "u64:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, + Known { signature: "bits:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, + Known { signature: "unit:panic:eval:trie_node.rs:3247", cause: TAKE_MAP }, + // The laws from `Zippy.lean` that fail, all of them under `PathMap::join` + // losing a value: every shrunk case is `x | y` with `y` sharing nodes with + // `x` (a clone, or a join result that reuses `x`'s nodes) or carrying + // dangling structure, and the union dropping a path one side has. One of + // them, `singleton_union_composition`, needs no clone at all: + // `{_, dangling 1, 2} | {_, 0000}` is `{_}` on master. Both that and + // repro 4 are fixed on `fix/fvc-leftovers`. Every other generated law has + // never failed, and is deliberately absent so that one failing is news. + Known { signature: "unit:law:union_comm", cause: LOSS }, + Known { signature: "unit:law:union_assoc", cause: LOSS }, + Known { signature: "unit:law:union_subtr_distrib", cause: LOSS }, + Known { signature: "unit:law:unwrap_union", cause: LOSS }, + Known { signature: "unit:law:head_union", cause: LOSS }, + Known { signature: "unit:law:tailsUnion_union", cause: LOSS }, + Known { signature: "unit:law:iterC_union", cause: LOSS }, + Known { signature: "unit:law:composition_union", cause: LOSS }, + Known { signature: "unit:law:union_composition", cause: LOSS }, + Known { signature: "unit:law:singleton_union_composition", cause: LOSS }, + Known { signature: "unit:law:union_inter_distrib", cause: LOSS }, + Known { signature: "unit:law:restriction_union", cause: LOSS }, ]; pub fn known(signature: &str) -> Option<&'static Known> { diff --git a/differential/src/algebraic/expr.rs b/differential/src/algebraic/expr.rs index 7fa2d9ac..e2a3452f 100644 --- a/differential/src/algebraic/expr.rs +++ b/differential/src/algebraic/expr.rs @@ -16,6 +16,22 @@ //! [`zipper_merge_dnf`](pathmap::experimental::zipper_algebra::zipper_merge_dnf). //! //! [`Expr::dnf`] and [`Expr::chain`] are the recognisers for the last three. +//! +//! # Zippy's operators +//! +//! On top of the crate's algebra the language has the rest of Zippy's space +//! algebra (`formal.egg`, proved over `PrunedMap Unit` in +//! `lean/PrunedModel/Zippy.lean`): the empty space, singletons, `Wrap`, +//! `Unwrap`, `Head`, `TailsUnion`, `TailsIntersection`, `Composition` and +//! `IterC`. They are there so that the laws `laws.rs` takes from that file can +//! be stated at all, and so that the routes get trees in which a subtrie is +//! moved, cut out or replicated between algebraic steps -- grafted and +//! prefixed nodes are shared differently from freshly built ones. +//! +//! A space in Zippy has no dangling paths, so where one of these operators +//! looks at structure (`Head`, the two tails, `IterC`) it looks only at +//! children that lead to a value. A child that is dangling-only is the +//! unsettled dangling-path question again, which `shape.rs` keeps apart. use core::fmt; @@ -34,10 +50,16 @@ pub enum Op { Subtract, SymDiff, Restrict, + /// Zippy's `Composition s t`: a copy of `t` under every path of `s`. + Compose, + /// Zippy's `IterC src b`: `b` if `src` has a value below its root, else + /// nothing. + IterC, } impl Op { - pub const ALL: [Op; 5] = [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff, Op::Restrict]; + pub const ALL: [Op; 7] = + [Op::Join, Op::Meet, Op::Subtract, Op::SymDiff, Op::Restrict, Op::Compose, Op::IterC]; pub fn sym(self) -> &'static str { match self { @@ -46,9 +68,16 @@ impl Op { Op::Subtract => "-", Op::SymDiff => "^", Op::Restrict => "/", + Op::Compose => ".", + Op::IterC => "iter_c", } } + /// One of Zippy's operators rather than one of the crate's own algebra. + pub fn is_zippy(self) -> bool { + matches!(self, Op::Compose | Op::IterC) + } + /// Whether `(a op b) op c == a op (b op c)` holds, which is what makes a /// chain of this operator collapsible to one n-ary call. /// @@ -78,10 +107,81 @@ impl Op { } } +/// Zippy's one-operand operators that take no path. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Un { + /// `Head s`: the first byte of every path, as one-byte paths. + Head, + /// `TailsUnion s`: the union of the subtries one byte down. + TailsUnion, + /// `TailsIntersection s`: their intersection; nothing when there are none. + TailsInter, +} + +impl Un { + pub const ALL: [Un; 3] = [Un::Head, Un::TailsUnion, Un::TailsInter]; + + pub fn name(self) -> &'static str { + match self { + Un::Head => "head", + Un::TailsUnion => "tails_union", + Un::TailsInter => "tails_inter", + } + } +} + +/// Every kind of interior node, for naming the strategy a route picked. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Op(Op), + Singleton, + Wrap, + Unwrap, + Un(Un), +} + +impl Kind { + pub const ALL: [Kind; 13] = [ + Kind::Op(Op::Join), + Kind::Op(Op::Meet), + Kind::Op(Op::Subtract), + Kind::Op(Op::SymDiff), + Kind::Op(Op::Restrict), + Kind::Op(Op::Compose), + Kind::Op(Op::IterC), + Kind::Singleton, + Kind::Wrap, + Kind::Unwrap, + Kind::Un(Un::Head), + Kind::Un(Un::TailsUnion), + Kind::Un(Un::TailsInter), + ]; + + pub fn sym(self) -> &'static str { + match self { + Kind::Op(op) => op.sym(), + Kind::Singleton => "singleton", + Kind::Wrap => "wrap", + Kind::Unwrap => "unwrap", + Kind::Un(u) => u.name(), + } + } +} + #[derive(Clone, PartialEq, Eq, Debug)] pub enum Expr { Var(usize), + /// The empty space. + Empty, + /// One path, carrying [`FuzzValue::canonical`](super::value::FuzzValue::canonical). + Singleton(Vec), Bin(Op, Box, Box), + /// Zippy's `Wrap p s`: every path of `s`, prefixed by `p`. + Wrap(Vec, Box), + /// Zippy's `Unwrap s p`: the subtrie of `s` at `p`, the value at `p` + /// included (it becomes the root value). + Unwrap(Box, Vec), + Un(Un, Box), } impl Expr { @@ -89,10 +189,70 @@ impl Expr { Expr::Bin(op, Box::new(l), Box::new(r)) } + pub fn wrap(p: Vec, e: Expr) -> Expr { + Expr::Wrap(p, Box::new(e)) + } + + pub fn unwrap(e: Expr, p: Vec) -> Expr { + Expr::Unwrap(Box::new(e), p) + } + + pub fn un(u: Un, e: Expr) -> Expr { + Expr::Un(u, Box::new(e)) + } + pub fn nodes(&self) -> usize { match self { - Expr::Var(_) => 1, + Expr::Var(_) | Expr::Empty | Expr::Singleton(_) => 1, Expr::Bin(_, l, r) => 1 + l.nodes() + r.nodes(), + Expr::Wrap(_, e) | Expr::Unwrap(e, _) | Expr::Un(_, e) => 1 + e.nodes(), + } + } + + /// The node kinds the expression uses, each once. + pub fn kinds(&self) -> Vec { + let mut out = Vec::new(); + self.collect_kinds(&mut out); + out + } + + fn collect_kinds(&self, out: &mut Vec) { + let mut add = |k: Kind| { + if !out.contains(&k) { + out.push(k); + } + }; + match self { + Expr::Var(_) | Expr::Empty => {} + Expr::Singleton(_) => add(Kind::Singleton), + Expr::Bin(op, l, r) => { + add(Kind::Op(*op)); + l.collect_kinds(out); + r.collect_kinds(out); + } + Expr::Wrap(_, e) => { + add(Kind::Wrap); + e.collect_kinds(out); + } + Expr::Unwrap(e, _) => { + add(Kind::Unwrap); + e.collect_kinds(out); + } + Expr::Un(u, e) => { + add(Kind::Un(*u)); + e.collect_kinds(out); + } + } + } + + /// Whether any node is one of Zippy's operators rather than the crate's own + /// algebra. Signatures say so, so that a finding in the new operators + /// cannot hide under a signature already attributed to an old defect. + pub fn has_zippy(&self) -> bool { + match self { + Expr::Var(_) => false, + Expr::Empty | Expr::Singleton(_) | Expr::Wrap(..) | Expr::Unwrap(..) | Expr::Un(..) => true, + Expr::Bin(op, l, r) => op.is_zippy() || l.has_zippy() || r.has_zippy(), } } @@ -108,10 +268,12 @@ impl Expr { fn collect_vars(&self, out: &mut Vec) { match self { Expr::Var(i) => out.push(*i), + Expr::Empty | Expr::Singleton(_) => {} Expr::Bin(_, l, r) => { l.collect_vars(out); r.collect_vars(out); } + Expr::Wrap(_, e) | Expr::Unwrap(e, _) | Expr::Un(_, e) => e.collect_vars(out), } } @@ -151,9 +313,10 @@ impl Expr { true } Expr::Bin(..) => op.right_nestable() && r.collect_chain(op, out), + _ => false, } } - Expr::Bin(..) => false, + _ => false, } } @@ -208,11 +371,23 @@ impl Expr { } } +/// A path as its bytes, `[]` for the empty one. +pub fn show_path(p: &[u8]) -> String { + let bs: Vec = p.iter().map(|b| b.to_string()).collect(); + format!("[{}]", bs.join(",")) +} + impl fmt::Display for Expr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Expr::Var(i) => write!(f, "{}", (b'a' + *i as u8) as char), + Expr::Empty => write!(f, "{{}}"), + Expr::Singleton(p) => write!(f, "{{{}}}", show_path(p)), + Expr::Bin(Op::IterC, l, r) => write!(f, "iter_c({l}, {r})"), Expr::Bin(op, l, r) => write!(f, "({l} {} {r})", op.sym()), + Expr::Wrap(p, e) => write!(f, "wrap{}({e})", show_path(p)), + Expr::Unwrap(e, p) => write!(f, "unwrap({e}){}", show_path(p)), + Expr::Un(u, e) => write!(f, "{}({e})", u.name()), } } } diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs index 221991fb..15f7da2a 100644 --- a/differential/src/algebraic/laws.rs +++ b/differential/src/algebraic/laws.rs @@ -6,238 +6,267 @@ //! the same trie, so a wrong answer is visible even when every route computes //! it the same wrong way. //! -//! A law is written as a pair of [`Expr`]s and evaluated by the ordinary route -//! machinery, which keeps this file declarative and means a law automatically -//! inherits whatever the expression evaluator can do. +//! # Where the laws come from //! -//! # Strength depends on the value type +//! Not from this file. They are the theorems of `lean/PrunedModel/Zippy.lean` +//! (branch `spec/zippy-laws`), which proves Adam Vandervorst's `formal.egg` -- +//! the reference semantics of Zippy's space algebra -- over the pruned model. +//! `lean/ZippyLaws.lean` reads the *elaborated* theorems, keeps every equation +//! between spaces whose operators the expression language has, and prints them +//! as [`zippy_laws`](super::zippy_laws). So each law here is a theorem, not a +//! belief, and adding one means proving it. //! -//! [`laws`] is parameterised by the value type, and returns a *stronger* set for -//! one whose instances actually form a distributive lattice with a relative -//! complement -- see [`FuzzValue::LAWFUL`]. Three things change: +//! A theorem may quantify over paths and bytes as well as spaces, and may have +//! hypotheses. Hence [`ZippyLaw`] is a template: [`instantiate`] binds its +//! spaces to the case's operands and its paths and bytes to ones the case +//! carries for the purpose ([`super::Case::law_paths`]), and a law whose +//! hypotheses are false for that binding is skipped for that case. //! -//! * The laws marked [`Level::Paths`] are promoted to [`Level::Values`]. They -//! are weakened for `u64` only because its `pjoin` and `pmeet` both return the -//! left operand, so swapping the operands swaps the result's value and -//! commutativity cannot hold on values there. +//! # Only for `()` //! -//! * Three further identities are added, listed in [`lawful_only`]. They are -//! laws in any distributive lattice and fail for `u64`, again because join and -//! meet have collapsed into one function. -//! -//! * Symmetric difference becomes associative on values, not merely on paths. -//! -//! So the difference between the two sets is a measurement: a law that holds for -//! `bits` and fails for `u64` is telling you about `u64`, and one that fails for -//! `bits` is telling you about the crate. That split is the whole reason for -//! running both. +//! The theorems are about `PrunedMap Unit`, a finite set of paths. They are +//! checked for the value type whose maps *are* sets -- [`FuzzValue::IS_SET`] -- +//! and no other. Under `u64` or `bits` several are false for reasons that +//! have nothing to do with the crate: subtraction removes a path only when the +//! values cancel, and a meet of two values can be bottom. Laws over values +//! need a value-generic source (`Lattice.lean` has one); that is not this file. -use super::expr::{Expr, Op}; +use super::expr::{Expr, Op, Un}; use super::value::FuzzValue; -/// Operand slot holding the empty trie, appended after the case's own -/// operands so identities can mention it. See [`LAW_OPERANDS`]. -pub const EMPTY: usize = 3; +/// A space-valued term of a law. +#[derive(Clone, Debug)] +pub enum T { + /// The `i`th space the theorem quantifies over. + S(usize), + Empty, + Singleton(P), + Bin(Op, Box, Box), + Wrap(P, Box), + Unwrap(Box, P), + Un(Un, Box), +} -/// Operands a law may mention: three from the case, then the empty trie. -pub const LAW_OPERANDS: usize = 4; +/// A path-valued term. +#[derive(Clone, Debug)] +pub enum P { + Var(usize), + Nil, + Cons(B, Box

), + App(Box

, Box

), +} -/// How much of the result a law constrains. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Level { - /// Which path carries which value. - Values, - /// Which paths survive, values unconstrained. - Paths, +/// A byte-valued term. +#[derive(Clone, Copy, Debug)] +pub enum B { + Var(usize), + Lit(u8), } -pub struct Law { - pub name: &'static str, - pub lhs: Expr, - pub rhs: Expr, - pub level: Level, +/// A hypothesis of the theorem. +#[derive(Clone, Debug)] +pub enum Pre { + NePath(P, P), + NeByte(B, B), + Mem(P, T), + NotMem(P, T), + EqSpace(T, T), } -fn v(i: usize) -> Expr { - Expr::Var(i) +/// One theorem of `Zippy.lean`, as generated. +pub struct ZippyLaw { + /// The theorem's name in `PrunedModel.Zippy`. + pub name: &'static str, + /// How many spaces, paths and bytes it quantifies over. + pub spaces: usize, + pub paths: usize, + pub bytes: usize, + pub pre: Vec

,
+    pub lhs: T,
+    pub rhs: T,
 }
-fn j(a: Expr, b: Expr) -> Expr {
-    Expr::bin(Op::Join, a, b)
+
+/// The builders `zippy_laws.rs` is written in.  Named after the Lean
+/// definitions, so the generated file reads like the theorems it came from.
+pub mod zippy {
+    pub use super::{Pre, ZippyLaw, B, P, T};
+    use super::{Op, Un};
+
+    fn bin(op: Op, a: T, b: T) -> T {
+        T::Bin(op, Box::new(a), Box::new(b))
+    }
+
+    pub fn s(i: usize) -> T {
+        T::S(i)
+    }
+    pub fn empty() -> T {
+        T::Empty
+    }
+    pub fn singleton(p: P) -> T {
+        T::Singleton(p)
+    }
+    pub fn union(a: T, b: T) -> T {
+        bin(Op::Join, a, b)
+    }
+    pub fn inter(a: T, b: T) -> T {
+        bin(Op::Meet, a, b)
+    }
+    pub fn subtr(a: T, b: T) -> T {
+        bin(Op::Subtract, a, b)
+    }
+    pub fn restriction(a: T, b: T) -> T {
+        bin(Op::Restrict, a, b)
+    }
+    /// Egg *defines* `Raffination x y` as `x \ (x <| y)`, and so does
+    /// `Zippy.lean`; the crate has no operation of its own for it.
+    pub fn raffination(a: T, b: T) -> T {
+        subtr(a.clone(), restriction(a, b))
+    }
+    pub fn composition(a: T, b: T) -> T {
+        bin(Op::Compose, a, b)
+    }
+    pub fn iter_c(a: T, b: T) -> T {
+        bin(Op::IterC, a, b)
+    }
+    pub fn wrap(p: P, a: T) -> T {
+        T::Wrap(p, Box::new(a))
+    }
+    pub fn unwrap(a: T, p: P) -> T {
+        T::Unwrap(Box::new(a), p)
+    }
+    pub fn head(a: T) -> T {
+        T::Un(Un::Head, Box::new(a))
+    }
+    pub fn tails_union(a: T) -> T {
+        T::Un(Un::TailsUnion, Box::new(a))
+    }
+    pub fn tails_inter(a: T) -> T {
+        T::Un(Un::TailsInter, Box::new(a))
+    }
+
+    pub fn pv(i: usize) -> P {
+        P::Var(i)
+    }
+    pub fn nil() -> P {
+        P::Nil
+    }
+    pub fn cons(b: B, p: P) -> P {
+        P::Cons(b, Box::new(p))
+    }
+    pub fn app(a: P, b: P) -> P {
+        P::App(Box::new(a), Box::new(b))
+    }
+
+    pub fn bv(i: usize) -> B {
+        B::Var(i)
+    }
+    pub fn lit(n: u8) -> B {
+        B::Lit(n)
+    }
+
+    pub fn ne_path(a: P, b: P) -> Pre {
+        Pre::NePath(a, b)
+    }
+    pub fn ne_byte(a: B, b: B) -> Pre {
+        Pre::NeByte(a, b)
+    }
+    pub fn mem(p: P, s: T) -> Pre {
+        Pre::Mem(p, s)
+    }
+    pub fn not_mem(p: P, s: T) -> Pre {
+        Pre::NotMem(p, s)
+    }
+    pub fn eq_space(a: T, b: T) -> Pre {
+        Pre::EqSpace(a, b)
+    }
 }
-fn m(a: Expr, b: Expr) -> Expr {
-    Expr::bin(Op::Meet, a, b)
+
+/// Paths and bytes a case offers for a law's path and byte variables.
+pub struct Binding<'a> {
+    pub paths: &'a [Vec],
+    pub bytes: &'a [u8],
 }
-fn s(a: Expr, b: Expr) -> Expr {
-    Expr::bin(Op::Subtract, a, b)
+
+impl Binding<'_> {
+    pub fn byte(&self, b: B) -> u8 {
+        match b {
+            B::Var(i) => self.bytes[i],
+            B::Lit(n) => n,
+        }
+    }
+
+    pub fn path(&self, p: &P) -> Vec {
+        match p {
+            P::Var(i) => self.paths[*i].clone(),
+            P::Nil => Vec::new(),
+            P::Cons(b, t) => {
+                let mut out = vec![self.byte(*b)];
+                out.extend(self.path(t));
+                out
+            }
+            P::App(a, b) => [self.path(a), self.path(b)].concat(),
+        }
+    }
+
+    /// The expression a term denotes, its space `i` being operand `i`.
+    pub fn expr(&self, t: &T) -> Expr {
+        match t {
+            T::S(i) => Expr::Var(*i),
+            T::Empty => Expr::Empty,
+            T::Singleton(p) => Expr::Singleton(self.path(p)),
+            T::Bin(op, a, b) => Expr::bin(*op, self.expr(a), self.expr(b)),
+            T::Wrap(p, a) => Expr::wrap(self.path(p), self.expr(a)),
+            T::Unwrap(a, p) => Expr::unwrap(self.expr(a), self.path(p)),
+            T::Un(u, a) => Expr::un(*u, self.expr(a)),
+        }
+    }
 }
-fn x(a: Expr, b: Expr) -> Expr {
-    Expr::bin(Op::SymDiff, a, b)
+
+/// A law with its variables bound: the two sides, and the hypotheses as
+/// expressions still to be decided against the operands.
+pub struct Instance {
+    pub lhs: Expr,
+    pub rhs: Expr,
+    pub pre: Vec,
 }
-fn r(a: Expr, b: Expr) -> Expr {
-    Expr::bin(Op::Restrict, a, b)
+
+/// A hypothesis with its variables bound.
+pub enum Hyp {
+    /// Decided already: it compared paths or bytes.
+    Holds(bool),
+    /// `path ∈ expr`, or `∉` when the flag is false.
+    Mem(Vec, Expr, bool),
+    /// `lhs = rhs` as spaces.
+    Eq(Expr, Expr),
 }
 
-/// The laws to check for value type `V`.
-///
-/// For a lawful `V` every `Paths` level is promoted to `Values` and
-/// [`lawful_only`] is appended.
-pub fn laws() -> Vec {
-    let mut out = base();
-    if V::LAWFUL {
-        for law in &mut out {
-            law.level = Level::Values;
-        }
-        out.extend(lawful_only());
-    }
-    out
+pub fn instantiate(law: &ZippyLaw, bind: &Binding) -> Instance {
+    let pre = law
+        .pre
+        .iter()
+        .map(|h| match h {
+            Pre::NePath(a, b) => Hyp::Holds(bind.path(a) != bind.path(b)),
+            Pre::NeByte(a, b) => Hyp::Holds(bind.byte(*a) != bind.byte(*b)),
+            Pre::Mem(p, s) => Hyp::Mem(bind.path(p), bind.expr(s), true),
+            Pre::NotMem(p, s) => Hyp::Mem(bind.path(p), bind.expr(s), false),
+            Pre::EqSpace(a, b) => Hyp::Eq(bind.expr(a), bind.expr(b)),
+        })
+        .collect();
+    Instance { lhs: bind.expr(&law.lhs), rhs: bind.expr(&law.rhs), pre }
 }
 
-/// Identities that hold whatever the value type.
-fn base() -> Vec {
-    use Level::{Paths, Values};
-    let (a, b, c, e) = (0usize, 1usize, 2usize, EMPTY);
-    vec![
-        // --- lattice basics
-        Law { name: "join-idempotent", lhs: j(v(a), v(a)), rhs: v(a), level: Values },
-        Law { name: "meet-idempotent", lhs: m(v(a), v(a)), rhs: v(a), level: Values },
-        Law { name: "join-unit", lhs: j(v(a), v(e)), rhs: v(a), level: Values },
-        Law { name: "meet-zero", lhs: m(v(a), v(e)), rhs: v(e), level: Values },
-        // Path set only: both `pjoin` and `pmeet` return the left operand, so
-        // swapping the operands swaps which value lands.  A real lattice would
-        // make these value-level laws; see the module comment.
-        Law { name: "join-commutative", lhs: j(v(a), v(b)), rhs: j(v(b), v(a)), level: Paths },
-        Law { name: "meet-commutative", lhs: m(v(a), v(b)), rhs: m(v(b), v(a)), level: Paths },
-        // Associativity does hold on values even here: both nestings select the
-        // leftmost present operand's value.
-        Law {
-            name: "join-associative",
-            lhs: j(j(v(a), v(b)), v(c)),
-            rhs: j(v(a), j(v(b), v(c))),
-            level: Values,
-        },
-        Law {
-            name: "meet-associative",
-            lhs: m(m(v(a), v(b)), v(c)),
-            rhs: m(v(a), m(v(b), v(c))),
-            level: Values,
-        },
-        Law { name: "absorb-meet-join", lhs: m(v(a), j(v(a), v(b))), rhs: v(a), level: Values },
-        Law { name: "absorb-join-meet", lhs: j(v(a), m(v(a), v(b))), rhs: v(a), level: Values },
-        Law {
-            name: "meet-distributes-over-join",
-            lhs: m(v(a), j(v(b), v(c))),
-            rhs: j(m(v(a), v(b)), m(v(a), v(c))),
-            level: Values,
-        },
-        Law {
-            name: "join-distributes-over-meet",
-            lhs: j(v(a), m(v(b), v(c))),
-            rhs: m(j(v(a), v(b)), j(v(a), v(c))),
-            level: Values,
-        },
-        // --- subtraction
-        Law { name: "subtract-self", lhs: s(v(a), v(a)), rhs: v(e), level: Values },
-        Law { name: "subtract-unit", lhs: s(v(a), v(e)), rhs: v(a), level: Values },
-        Law { name: "subtract-from-empty", lhs: s(v(e), v(a)), rhs: v(e), level: Values },
-        // Each step drops the paths whose value the subtrahend matches, and
-        // "matches b or matches c" does not depend on the order.
-        Law {
-            name: "subtract-steps-commute",
-            lhs: s(s(v(a), v(b)), v(c)),
-            rhs: s(s(v(a), v(c)), v(b)),
-            level: Values,
-        },
-        // Subtracting cannot add a path: re-joining the removed part recovers
-        // no more than the original.
-        Law { name: "subtract-shrinks", lhs: j(s(v(a), v(b)), v(a)), rhs: v(a), level: Values },
-        // --- symmetric difference
-        Law { name: "sym-diff-self", lhs: x(v(a), v(a)), rhs: v(e), level: Values },
-        Law { name: "sym-diff-unit", lhs: x(v(a), v(e)), rhs: v(a), level: Values },
-        // Fully commutative, values included: a coincident path cancels on both
-        // sides, so each surviving value comes from the single side that has it.
-        Law { name: "sym-diff-commutative", lhs: x(v(a), v(b)), rhs: x(v(b), v(a)), level: Values },
-        Law {
-            name: "sym-diff-associative-paths",
-            lhs: x(x(v(a), v(b)), v(c)),
-            rhs: x(v(a), x(v(b), v(c))),
-            level: Paths,
-        },
-        // The definition `zipper_sym_diff`'s own documentation gives.
-        Law {
-            name: "sym-diff-is-join-minus-meet",
-            lhs: x(v(a), v(b)),
-            rhs: s(j(v(a), v(b)), m(v(a), v(b))),
-            level: Values,
-        },
-        // --- restrict
-        // Every path is a prefix of itself, so restricting by its own operand
-        // admits everything.
-        Law { name: "restrict-self", lhs: r(v(a), v(a)), rhs: v(a), level: Values },
-        Law { name: "restrict-empty", lhs: r(v(a), v(e)), rhs: v(e), level: Values },
-        Law { name: "restrict-of-empty", lhs: r(v(e), v(a)), rhs: v(e), level: Values },
-        Law { name: "restrict-idempotent", lhs: r(r(v(a), v(b)), v(b)), rhs: r(v(a), v(b)), level: Values },
-        // A path present in both operands is admitted by itself, so the meet is
-        // contained in the restriction.
-        Law {
-            name: "meet-under-restrict",
-            lhs: m(m(v(a), v(b)), r(v(a), v(b))),
-            rhs: m(v(a), v(b)),
-            level: Values,
-        },
-        // --- majority, the worked example in `zipper_majority`'s docs, written
-        // out as the DNF it claims to equal.  Exercised here so the DNF engine
-        // is checked against a hand-written join of meets as well as against
-        // the pointwise routes.
-        Law {
-            name: "majority-is-pairwise-meets",
-            lhs: j(j(m(v(a), v(b)), m(v(a), v(c))), m(v(b), v(c))),
-            rhs: j(m(v(a), v(b)), j(m(v(a), v(c)), m(v(b), v(c)))),
-            level: Values,
-        },
-    ]
+/// The laws to check for value type `V`: all of `Zippy.lean`'s for the set
+/// type, none otherwise.  See the module comment.
+pub fn laws() -> &'static [ZippyLaw] {
+    use std::sync::OnceLock;
+    static LAWS: OnceLock> = OnceLock::new();
+    if V::IS_SET { LAWS.get_or_init(super::zippy_laws::laws) } else { &[] }
 }
 
-/// Identities that need the value type to be a real distributive lattice with a
-/// relative complement.
-///
-/// Each of these fails for `u64`, and each failure is explained by the same
-/// thing: `pjoin` and `pmeet` both return the left operand, so `a | b == a & b`,
-/// and `psubtract` is `None` exactly on equality.
-fn lawful_only() -> Vec {
-    use Level::Values;
-    let (a, b, c) = (0usize, 1usize, 2usize);
-    vec![
-        // De Morgan for relative complement.  Fails for `u64` because `b | c`
-        // carries `b`'s value where both are present, so the left side keeps a
-        // path whose value matches `c` but not `b`.
-        Law {
-            name: "subtract-over-join",
-            lhs: s(v(a), j(v(b), v(c))),
-            rhs: m(s(v(a), v(b)), s(v(a), v(c))),
-            level: Values,
-        },
-        Law {
-            name: "subtract-over-meet",
-            lhs: s(v(a), m(v(b), v(c))),
-            rhs: j(s(v(a), v(b)), s(v(a), v(c))),
-            level: Values,
-        },
-        // Subtracting the overlap is the same as subtracting the whole.  Fails
-        // for `u64` because `a & b` carries *`a`'s* value, so the right side
-        // drops every shared path rather than only the equal ones.
-        Law {
-            name: "subtract-is-subtract-meet",
-            lhs: s(v(a), v(b)),
-            rhs: s(v(a), m(v(a), v(b))),
-            level: Values,
-        },
-        // Symmetric difference is the XOR of a Boolean ring, so it is
-        // associative on values and not merely on paths.
-        Law {
-            name: "sym-diff-associative",
-            lhs: x(x(v(a), v(b)), v(c)),
-            rhs: x(v(a), x(v(b), v(c))),
-            level: Values,
-        },
-    ]
+/// The most of each kind of variable any generated law uses.  The case has to
+/// supply at least this many; `tests/algebraic.rs` checks the bound.
+pub fn arity() -> (usize, usize, usize) {
+    super::zippy_laws::laws()
+        .iter()
+        .fold((0, 0, 0), |(s, p, b), l| (s.max(l.spaces), p.max(l.paths), b.max(l.bytes)))
 }
diff --git a/differential/src/algebraic/model.rs b/differential/src/algebraic/model.rs
index c987be6d..c0c9f349 100644
--- a/differential/src/algebraic/model.rs
+++ b/differential/src/algebraic/model.rs
@@ -27,18 +27,31 @@
 
 use pathmap::ring::{DistributiveLattice, Lattice};
 
-use super::expr::{Expr, Op};
+use super::expr::{Expr, Op, Un};
 use super::shape::Values;
 use super::value::{resolve, FuzzValue};
 
 pub fn eval(e: &Expr, operands: &[Values]) -> Values {
     match e {
         Expr::Var(i) => operands[*i].clone(),
+        Expr::Empty => Values::new(),
+        Expr::Singleton(p) => singleton(p),
         Expr::Bin(op, l, r) => {
             let a = eval(l, operands);
             let b = eval(r, operands);
             apply(*op, &a, &b)
         }
+        Expr::Wrap(p, e) => wrap(p, &eval(e, operands)),
+        Expr::Unwrap(e, p) => unwrap(&eval(e, operands), p),
+        Expr::Un(u, e) => unary(*u, &eval(e, operands)),
+    }
+}
+
+pub fn unary(u: Un, a: &Values) -> Values {
+    match u {
+        Un::Head => head(a),
+        Un::TailsUnion => tails_union(a),
+        Un::TailsInter => tails_inter(a),
     }
 }
 
@@ -49,6 +62,8 @@ pub fn apply(op: Op, a: &Values, b: &Values) -> Values {
         Op::Subtract => subtract(a, b),
         Op::SymDiff => sym_diff(a, b),
         Op::Restrict => restrict(a, b),
+        Op::Compose => compose(a, b),
+        Op::IterC => iter_c(a, b),
     }
 }
 
@@ -112,3 +127,62 @@ pub fn restrict(a: &Values, b: &Values) -> Values {
         .map(|(k, v)| (k.clone(), v.clone()))
         .collect()
 }
+
+// ---------------------------------------------------------------- Zippy
+//
+// Each of these is the membership lemma `Zippy.lean` proves for the operator
+// (`mem_wrap`, `mem_unwrap`, `mem_head`, ...), read as a definition.  Values
+// come along with the paths they sit on; where several paths land on one, they
+// are joined in ascending key order, which is the order every crate route
+// visits them in too.
+
+pub fn singleton(p: &[u8]) -> Values {
+    Values::from([(p.to_vec(), V::canonical())])
+}
+
+/// `p ∈ wrap q s ↔ ∃ r, p = q ++ r ∧ r ∈ s`.
+pub fn wrap(p: &[u8], a: &Values) -> Values {
+    a.iter().map(|(k, v)| ([p, &k[..]].concat(), v.clone())).collect()
+}
+
+/// `p ∈ unwrap s q ↔ q ++ p ∈ s`.
+pub fn unwrap(a: &Values, p: &[u8]) -> Values {
+    a.iter().filter_map(|(k, v)| k.strip_prefix(p).map(|r| (r.to_vec(), v.clone()))).collect()
+}
+
+/// The first bytes of `a`'s non-empty paths, ascending.  A space has no
+/// dangling paths, so this is also what `child_mask` would say of one.
+pub fn heads(a: &Values) -> Vec {
+    let mut hs: Vec = a.keys().filter_map(|k| k.first().copied()).collect();
+    hs.dedup();
+    hs
+}
+
+/// `p ∈ head s ↔ ∃ b r, p = [b] ∧ b :: r ∈ s`.
+pub fn head(a: &Values) -> Values {
+    heads(a).into_iter().map(|b| (vec![b], V::canonical())).collect()
+}
+
+/// `p ∈ tailsUnion s ↔ ∃ b, b :: p ∈ s`, folded with `join` over the heads.
+pub fn tails_union(a: &Values) -> Values {
+    heads(a).into_iter().fold(Values::new(), |acc, b| join(&acc, &unwrap(a, &[b])))
+}
+
+/// The tails under the first head, met with each later one's in turn; nothing
+/// when there is no head.  This is egg's `tails-intersection-acc` fold.
+pub fn tails_inter(a: &Values) -> Values {
+    let mut hs = heads(a).into_iter();
+    let Some(first) = hs.next() else { return Values::new() };
+    hs.fold(unwrap(a, &[first]), |acc, b| meet(&acc, &unwrap(a, &[b])))
+}
+
+/// `t` under every path of `s`, joined in ascending order of those paths.
+/// `s`'s own values are not carried: Composition reads only its paths.
+pub fn compose(s: &Values, t: &Values) -> Values {
+    s.keys().fold(Values::new(), |acc, u| join(&acc, &wrap(u, t)))
+}
+
+/// `p ∈ iterC src b ↔ (∃ h r, h :: r ∈ src) ∧ p ∈ b`.
+pub fn iter_c(src: &Values, b: &Values) -> Values {
+    if src.keys().any(|k| !k.is_empty()) { b.clone() } else { Values::new() }
+}
diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs
index 9a025906..5350d6d7 100644
--- a/differential/src/algebraic/routes.rs
+++ b/differential/src/algebraic/routes.rs
@@ -31,11 +31,11 @@ use pathmap::experimental::zipper_algebra::{
     zipper_subtract3, zipper_sym_diff, zipper_sym_diff3, ZipperMergeF,
 };
 use pathmap::zipper::{
-    OverlayZipper, ReadZipperUntracked, SubtractZipper, ZipperMoving, ZipperPath, ZipperValues,
-    ZipperWriting,
+    OverlayZipper, PrefixZipper, ReadZipperUntracked, SubtractZipper, Zipper,
+    ZipperInfallibleSubtries, ZipperMoving, ZipperPath, ZipperValues, ZipperWriting,
 };
 
-use super::expr::{Expr, Op};
+use super::expr::{Expr, Kind, Op, Un};
 use super::model;
 use super::shape::{shape_of_map, shape_of_zipper, values_of_shape, Shape, Values, ESCAPED_ROOT, TRUNCATED};
 use super::value::FuzzValue;
@@ -49,6 +49,14 @@ pub const MEET_STRATEGIES: &[&str] = &["map", "meet_into", "meet_2", "zipper_mee
 pub const SUBTRACT_STRATEGIES: &[&str] = &["map", "subtract_into", "zipper_subtract"];
 pub const SYM_DIFF_STRATEGIES: &[&str] = &["zipper_sym_diff", "join_minus_meet"];
 pub const RESTRICT_STRATEGIES: &[&str] = &["map", "wz_restrict"];
+pub const COMPOSE_STRATEGIES: &[&str] = &["join_map_into", "wrap_join"];
+pub const ITER_C_STRATEGIES: &[&str] = &["val_count", "iter"];
+pub const SINGLETON_STRATEGIES: &[&str] = &["single", "set_val"];
+pub const WRAP_STRATEGIES: &[&str] = &["graft_map", "prefix_zipper", "insert_prefix"];
+pub const UNWRAP_STRATEGIES: &[&str] = &["read_zipper_at_path", "descend_make_map", "take_map"];
+pub const HEAD_STRATEGIES: &[&str] = &["child_mask", "iter"];
+pub const TAILS_UNION_STRATEGIES: &[&str] = &["map", "join_map_into"];
+pub const TAILS_INTER_STRATEGIES: &[&str] = &["map", "meet_into"];
 
 /// The strategy table is the same for every value type, so route `k` means the
 /// same thing under each of them.
@@ -67,6 +75,21 @@ pub fn strategies(op: Op) -> &'static [&'static str] {
         Op::Subtract => SUBTRACT_STRATEGIES,
         Op::SymDiff => SYM_DIFF_STRATEGIES,
         Op::Restrict => RESTRICT_STRATEGIES,
+        Op::Compose => COMPOSE_STRATEGIES,
+        Op::IterC => ITER_C_STRATEGIES,
+    }
+}
+
+/// [`strategies`] for any node kind, Zippy's unary ones included.
+pub fn kind_strategies(kind: Kind) -> &'static [&'static str] {
+    match kind {
+        Kind::Op(op) => strategies(op),
+        Kind::Singleton => SINGLETON_STRATEGIES,
+        Kind::Wrap => WRAP_STRATEGIES,
+        Kind::Unwrap => UNWRAP_STRATEGIES,
+        Kind::Un(Un::Head) => HEAD_STRATEGIES,
+        Kind::Un(Un::TailsUnion) => TAILS_UNION_STRATEGIES,
+        Kind::Un(Un::TailsInter) => TAILS_INTER_STRATEGIES,
     }
 }
 
@@ -127,14 +150,13 @@ impl Route {
     pub fn name(&self, e: &Expr) -> String {
         match self {
             Route::Pointwise(k) => {
-                let mut used: Vec = Vec::new();
-                collect_ops(e, &mut used);
-                let picks: Vec = Op::ALL
+                let used = e.kinds();
+                let picks: Vec = Kind::ALL
                     .iter()
-                    .filter(|op| used.contains(op))
-                    .map(|op| {
-                        let t = strategies(*op);
-                        format!("{}={}", op.sym(), t[k % t.len()])
+                    .filter(|kind| used.contains(kind))
+                    .map(|kind| {
+                        let t = kind_strategies(*kind);
+                        format!("{}={}", kind.sym(), t[k % t.len()])
                     })
                     .collect();
                 format!("pw#{k}[{}]", picks.join(","))
@@ -150,14 +172,8 @@ impl Route {
     }
 }
 
-fn collect_ops(e: &Expr, out: &mut Vec) {
-    if let Expr::Bin(op, l, r) = e {
-        if !out.contains(op) {
-            out.push(*op);
-        }
-        collect_ops(l, out);
-        collect_ops(r, out);
-    }
+fn uses_op(e: &Expr, op: Op) -> bool {
+    e.kinds().contains(&Kind::Op(op))
 }
 
 /// What a route produced.  `shape` is `None` for a route that cannot represent
@@ -198,14 +214,31 @@ pub fn eval(route: Route, e: &Expr, operands: &[PathMap]) -> Op
 /// `None` when the strategy route `k` selects for some operator in `e` does not
 /// apply to this value type.
 fn pointwise(k: usize, e: &Expr, operands: &[PathMap]) -> Option> {
-    match e {
-        Expr::Var(i) => Some(operands[*i].clone()),
+    walk(e, operands, &mut |op, a, b| apply(op, k, a, b), k)
+}
+
+/// Bottom-up evaluation with `bin` for the binary nodes and strategy `k` for
+/// Zippy's unary ones.  Shared by every route that materialises intermediates,
+/// so the unary nodes go through the same code whichever route reaches them.
+fn walk(
+    e: &Expr,
+    operands: &[PathMap],
+    bin: &mut dyn FnMut(Op, &PathMap, &PathMap) -> Option>,
+    k: usize,
+) -> Option> {
+    Some(match e {
+        Expr::Var(i) => operands[*i].clone(),
+        Expr::Empty => PathMap::new(),
+        Expr::Singleton(p) => singleton(k, p),
         Expr::Bin(op, l, r) => {
-            let a = pointwise(k, l, operands)?;
-            let b = pointwise(k, r, operands)?;
-            apply(*op, k, &a, &b)
+            let a = walk(l, operands, bin, k)?;
+            let b = walk(r, operands, bin, k)?;
+            bin(*op, &a, &b)?
         }
-    }
+        Expr::Wrap(p, e) => wrap(k, p, &walk(e, operands, bin, k)?),
+        Expr::Unwrap(e, p) => unwrap(k, &walk(e, operands, bin, k)?, p),
+        Expr::Un(u, e) => unary(*u, k, &walk(e, operands, bin, k)?),
+    })
 }
 
 /// One operator, one strategy.  Every arm is a different code path in the
@@ -353,10 +386,185 @@ pub fn apply(op: Op, k: usize, a: &PathMap, b: &PathMap) ->
             out
         }
 
+        // -- composition: `b` under every value path of `a`.  Visited in
+        // `iter` order, ascending, so a path two copies land on is joined the
+        // same way round as the model joins it.
+        (Op::Compose, 0) => {
+            // Zippy's own definition: `descend_to u`, `join_map_into t`.
+            let mut out = PathMap::new();
+            {
+                let mut wz = out.write_zipper();
+                for (u, _) in a.iter() {
+                    wz.reset();
+                    wz.descend_to(&u);
+                    wz.join_map_into(b.clone());
+                }
+            }
+            out
+        }
+        (Op::Compose, 1) => {
+            let mut out = PathMap::new();
+            for (u, _) in a.iter() {
+                out = out.join(&wrap(0, &u, b));
+            }
+            out
+        }
+
+        // -- IterC: `b` when `a` has a value below its root.
+        (Op::IterC, s) => {
+            let below = if s == 0 {
+                let rz = a.read_zipper();
+                rz.val_count() > rz.is_val() as usize
+            } else {
+                a.iter().any(|(k, _)| !k.is_empty())
+            };
+            if below { b.clone() } else { PathMap::new() }
+        }
+
         _ => unreachable!("strategy index out of range for {op:?}"),
     })
 }
 
+// ---------------------------------------------------------------- Zippy
+
+/// `Singleton p`, carrying [`FuzzValue::canonical`].
+fn singleton(k: usize, p: &[u8]) -> PathMap {
+    match k % SINGLETON_STRATEGIES.len() {
+        0 => PathMap::single(p, V::canonical()),
+        _ => {
+            let mut out = PathMap::new();
+            {
+                let mut wz = out.write_zipper();
+                wz.descend_to(p);
+                wz.set_val(V::canonical());
+            }
+            out
+        }
+    }
+}
+
+/// `Wrap p s`.
+fn wrap(k: usize, p: &[u8], s: &PathMap) -> PathMap {
+    match k % WRAP_STRATEGIES.len() {
+        0 => {
+            // Zippy's definition: `descend_to p` in an empty map, `graft_map s`.
+            // With `graft_root_vals` (a default feature) the root value moves too.
+            let mut out = PathMap::new();
+            {
+                let mut wz = out.write_zipper();
+                wz.descend_to(p);
+                wz.graft_map(s.clone());
+            }
+            out
+        }
+        1 => materialize(PrefixZipper::new(p.to_vec(), s.read_zipper())),
+        _ => {
+            // `insert_prefix` moves the node and, by its documentation, leaves
+            // the focus value where it is (Zippy §10, `rawWrap_ne_wrap`).  So
+            // that value is moved by hand, and what this tests is the node move.
+            let mut out = s.clone();
+            {
+                let mut wz = out.write_zipper();
+                let root = wz.remove_val(false);
+                wz.insert_prefix(p);
+                if let Some(v) = root {
+                    wz.descend_to(p);
+                    wz.set_val(v);
+                }
+            }
+            out
+        }
+    }
+}
+
+/// `Unwrap s p`: the subtrie at `p`, its value included.
+fn unwrap(k: usize, s: &PathMap, p: &[u8]) -> PathMap {
+    match k % UNWRAP_STRATEGIES.len() {
+        0 => s.read_zipper_at_path(p).make_map(),
+        1 => {
+            let mut rz = s.read_zipper();
+            rz.descend_to(p);
+            rz.make_map()
+        }
+        _ => {
+            let mut src = s.clone();
+            let mut wz = src.write_zipper();
+            wz.descend_to(p);
+            wz.take_map(false).unwrap_or_default()
+        }
+    }
+}
+
+/// The bytes one level down that lead to a value, ascending.
+///
+/// Strategy 0 reads `child_mask` and checks each child for a value; strategy 1
+/// collects first bytes from `iter`.  A child that is dangling-only is in the
+/// mask and not in a Zippy space, so it is dropped: the dangling-path question
+/// is `shape.rs`'s, and letting it in here would turn it into a value
+/// divergence.
+fn heads(k: usize, s: &PathMap) -> Vec {
+    if k % 2 == 0 {
+        let rz = s.read_zipper();
+        rz.child_mask()
+            .iter()
+            .filter(|b| s.read_zipper_at_path([*b]).val_count() > 0)
+            .collect()
+    } else {
+        let mut hs: Vec = s.iter().filter_map(|(p, _)| p.first().copied()).collect();
+        hs.dedup();
+        hs
+    }
+}
+
+fn unary(u: Un, k: usize, s: &PathMap) -> PathMap {
+    match u {
+        Un::Head => {
+            let hs = heads(k % HEAD_STRATEGIES.len(), s);
+            let mut out = PathMap::new();
+            for b in hs {
+                out.set_val_at([b], V::canonical());
+            }
+            out
+        }
+        Un::TailsUnion => {
+            let hs = heads(k, s);
+            let tail = |b: u8| s.read_zipper_at_path([b]).make_map();
+            if k % TAILS_UNION_STRATEGIES.len() == 0 {
+                hs.into_iter().fold(PathMap::new(), |acc, b| acc.join(&tail(b)))
+            } else {
+                // Zippy's definition: `join_map_into` at the root, one child at
+                // a time.
+                let mut out = PathMap::new();
+                {
+                    let mut wz = out.write_zipper();
+                    for b in hs {
+                        wz.join_map_into(tail(b));
+                    }
+                }
+                out
+            }
+        }
+        Un::TailsInter => {
+            let mut hs = heads(k, s).into_iter();
+            let tail = |b: u8| s.read_zipper_at_path([b]).make_map();
+            let Some(first) = hs.next() else { return PathMap::new() };
+            if k % TAILS_INTER_STRATEGIES.len() == 0 {
+                hs.fold(tail(first), |acc, b| acc.meet(&tail(b)))
+            } else {
+                let mut out = tail(first);
+                {
+                    let mut wz = out.write_zipper();
+                    for b in hs {
+                        let t = tail(b);
+                        wz.meet_into(&t.read_zipper(), false);
+                    }
+                }
+                out
+            }
+        }
+    }
+}
+
 /// Walk a zipper over a virtual trie and build the real trie it describes.
 ///
 /// `create_path` is what keeps this faithful: a path with no value still has to
@@ -392,23 +600,17 @@ where
 /// [`Route::SubtractZipper`].  `None` when `e` has no subtraction, because the
 /// route would then be the baseline over again.
 fn subtract_zipper(e: &Expr, operands: &[PathMap]) -> Option> {
-    fn go(e: &Expr, operands: &[PathMap]) -> PathMap {
-        match e {
-            Expr::Var(i) => operands[*i].clone(),
-            Expr::Bin(op, l, r) => {
-                let a = go(l, operands);
-                let b = go(r, operands);
-                if *op == Op::Subtract {
-                    materialize(SubtractZipper::new(a.read_zipper(), b.read_zipper()))
-                } else {
-                    apply(*op, 0, &a, &b).expect("strategy 0 applies to every value type")
-                }
-            }
-        }
+    let mut bin = |op: Op, a: &PathMap, b: &PathMap| {
+        Some(if op == Op::Subtract {
+            materialize(SubtractZipper::new(a.read_zipper(), b.read_zipper()))
+        } else {
+            apply(op, 0, a, b).expect("strategy 0 applies to every value type")
+        })
+    };
+    if !uses_op(e, Op::Subtract) {
+        return None;
     }
-    let mut ops = Vec::new();
-    collect_ops(e, &mut ops);
-    ops.contains(&Op::Subtract).then(|| go(e, operands))
+    walk(e, operands, &mut bin, 0)
 }
 
 // -------------------------------------------------------- whole-expression
@@ -474,7 +676,7 @@ fn ternary(e: &Expr, operands: &[PathMap]) -> Option
             Op::Meet => zipper_meet3(&mut za, &mut zb, &mut zc, &mut wz),
             Op::Subtract => zipper_subtract3(&mut za, &mut zb, &mut zc, &mut wz),
             Op::SymDiff => zipper_sym_diff3(&mut za, &mut zb, &mut zc, &mut wz),
-            Op::Restrict => return None,
+            Op::Restrict | Op::Compose | Op::IterC => return None,
         }
     }
     Some(out)
@@ -488,7 +690,7 @@ fn ternary(e: &Expr, operands: &[PathMap]) -> Option
 /// merge engine and are worth distinguishing, so `poly` selects between them.
 fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option> {
     let (op, idx) = e.chain()?;
-    if op == Op::Restrict {
+    if !matches!(op, Op::Join | Op::Meet | Op::Subtract | Op::SymDiff) {
         return None;
     }
     let mut out = PathMap::new();
@@ -506,7 +708,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option

zipper_n_meet(&mut zs, &mut wz), Op::Subtract => zipper_n_subtract(&mut zs, &mut wz), Op::SymDiff => zipper_n_sym_diff(&mut zs, &mut wz), - Op::Restrict => unreachable!(), + Op::Restrict | Op::Compose | Op::IterC => unreachable!(), } }}; } @@ -518,7 +720,7 @@ fn nary(e: &Expr, operands: &[PathMap], poly: bool) -> Option

t.meet_n(&mut wz), Op::Subtract => t.subtract_n(&mut wz), Op::SymDiff => t.sym_diff_n(&mut wz), - Op::Restrict => unreachable!(), + Op::Restrict | Op::Compose | Op::IterC => unreachable!(), } }}; } diff --git a/differential/src/algebraic/value.rs b/differential/src/algebraic/value.rs index e821334b..b5661722 100644 --- a/differential/src/algebraic/value.rs +++ b/differential/src/algebraic/value.rs @@ -74,8 +74,17 @@ pub trait FuzzValue: /// defect, so the strategy is dropped rather than reported. const JOIN_PICKS_LEFT: bool; + /// Whether a `PathMap` is exactly a finite set of paths -- true only + /// for `()`. Zippy's laws (`laws.rs`) are proved in Lean over + /// `PrunedMap Unit`, so they are checked for this type and no other. + const IS_SET: bool = false; + fn generate(g: &mut Gen) -> Self; + /// The value a constructed path carries: Zippy's `Singleton` and `Head` + /// make paths, not values, so they need one fixed value to put there. + fn canonical() -> Self; + fn show(&self) -> String; } @@ -159,6 +168,10 @@ impl FuzzValue for Bits { Bits(g.byte() as u64 % (n - 1) + 1) } + fn canonical() -> Self { + Bits(1) + } + fn show(&self) -> String { format!("{:b}", self.0) } @@ -191,9 +204,12 @@ impl FuzzValue for () { // Both operands are `()`, so returning either is returning the left one, and // `OverlayZipper`'s `a.or(b)` is the join. const JOIN_PICKS_LEFT: bool = true; + const IS_SET: bool = true; fn generate(_g: &mut Gen) -> Self {} + fn canonical() -> Self {} + fn show(&self) -> String { "*".to_string() } @@ -215,6 +231,10 @@ impl FuzzValue for u64 { g.byte() as u64 % U64_VALUES + 1 } + fn canonical() -> Self { + 1 + } + fn show(&self) -> String { self.to_string() } diff --git a/differential/src/algebraic/zippy_laws.rs b/differential/src/algebraic/zippy_laws.rs new file mode 100644 index 00000000..8030680b --- /dev/null +++ b/differential/src/algebraic/zippy_laws.rs @@ -0,0 +1,790 @@ +// @generated by lean/ZippyLaws.lean from lean/PrunedModel/Zippy.lean (branch spec/zippy-laws). +// Do not edit by hand. Regenerate with: +// cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs +// +// Every entry is a theorem of PrunedModel.Zippy, checked sorry-free when generated. +// 70 exported, 75 not exported (listed at the end). + +use super::laws::zippy::*; + +pub fn laws() -> Vec { + vec![ + // Zippy.lean:496 + ZippyLaw { + name: "union_idem", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(s(0), s(0)), + rhs: s(0), + }, + // Zippy.lean:498 + ZippyLaw { + name: "inter_idem", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), s(0)), + rhs: s(0), + }, + // Zippy.lean:500 + ZippyLaw { + name: "subtr_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(s(0), s(0)), + rhs: empty(), + }, + // Zippy.lean:503 + ZippyLaw { + name: "union_comm", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(s(0), s(1)), + rhs: union(s(1), s(0)), + }, + // Zippy.lean:505 + ZippyLaw { + name: "inter_comm", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), s(1)), + rhs: inter(s(1), s(0)), + }, + // Zippy.lean:507 + ZippyLaw { + name: "union_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(s(0), empty()), + rhs: s(0), + }, + // Zippy.lean:510 + ZippyLaw { + name: "empty_union", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(empty(), s(0)), + rhs: s(0), + }, + // Zippy.lean:512 + ZippyLaw { + name: "inter_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), empty()), + rhs: empty(), + }, + // Zippy.lean:515 + ZippyLaw { + name: "empty_inter", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(empty(), s(0)), + rhs: empty(), + }, + // Zippy.lean:517 + ZippyLaw { + name: "union_inter_distrib", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(union(s(0), s(1)), s(2)), + rhs: union(inter(s(0), s(2)), inter(s(1), s(2))), + }, + // Zippy.lean:521 + ZippyLaw { + name: "inter_union_distrib", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(s(0), union(s(1), s(2))), + rhs: union(inter(s(0), s(1)), inter(s(0), s(2))), + }, + // Zippy.lean:525 + ZippyLaw { + name: "empty_subtr", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(empty(), s(0)), + rhs: empty(), + }, + // Zippy.lean:528 + ZippyLaw { + name: "subtr_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(s(0), empty()), + rhs: s(0), + }, + // Zippy.lean:531 + ZippyLaw { + name: "union_subtr_distrib", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(union(s(0), s(1)), s(2)), + rhs: union(subtr(s(0), s(2)), subtr(s(1), s(2))), + }, + // Zippy.lean:535 + ZippyLaw { + name: "subtr_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: subtr(s(0), union(s(1), s(2))), + rhs: subtr(subtr(s(0), s(1)), s(2)), + }, + // Zippy.lean:539 + ZippyLaw { + name: "union_assoc", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: union(union(s(0), s(1)), s(2)), + rhs: union(s(0), union(s(1), s(2))), + }, + // Zippy.lean:542 + ZippyLaw { + name: "inter_assoc", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: inter(inter(s(0), s(1)), s(2)), + rhs: inter(s(0), inter(s(1), s(2))), + }, + // Zippy.lean:548 + ZippyLaw { + name: "singleton_subtr_singleton", + spaces: 0, + paths: 2, + bytes: 0, + pre: vec![ne_path(pv(0), pv(1))], + lhs: subtr(singleton(pv(0)), singleton(pv(1))), + rhs: singleton(pv(0)), + }, + // Zippy.lean:553 + ZippyLaw { + name: "singleton_inter_singleton", + spaces: 0, + paths: 2, + bytes: 0, + pre: vec![ne_path(pv(0), pv(1))], + lhs: inter(singleton(pv(0)), singleton(pv(1))), + rhs: empty(), + }, + // Zippy.lean:575 + ZippyLaw { + name: "wrap_empty", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: wrap(pv(0), empty()), + rhs: empty(), + }, + // Zippy.lean:579 + ZippyLaw { + name: "wrap_eps", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: wrap(nil(), s(0)), + rhs: s(0), + }, + // Zippy.lean:582 + ZippyLaw { + name: "wrap_singleton", + spaces: 0, + paths: 2, + bytes: 0, + pre: vec![], + lhs: wrap(pv(0), singleton(pv(1))), + rhs: singleton(app(pv(0), pv(1))), + }, + // Zippy.lean:586 + ZippyLaw { + name: "wrap_union", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: wrap(pv(0), union(s(0), s(1))), + rhs: union(wrap(pv(0), s(0)), wrap(pv(0), s(1))), + }, + // Zippy.lean:598 + ZippyLaw { + name: "unwrap_empty", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(empty(), pv(0)), + rhs: empty(), + }, + // Zippy.lean:601 + ZippyLaw { + name: "unwrap_eps", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: unwrap(s(0), nil()), + rhs: s(0), + }, + // Zippy.lean:603 + ZippyLaw { + name: "unwrap_wrap", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(wrap(pv(0), s(0)), pv(0)), + rhs: s(0), + }, + // Zippy.lean:607 + ZippyLaw { + name: "unwrap_wrap_append", + spaces: 1, + paths: 2, + bytes: 0, + pre: vec![], + lhs: unwrap(wrap(app(pv(0), pv(1)), s(0)), pv(0)), + rhs: wrap(pv(1), s(0)), + }, + // Zippy.lean:612 + ZippyLaw { + name: "unwrap_wrap_of_append", + spaces: 1, + paths: 2, + bytes: 0, + pre: vec![], + lhs: unwrap(wrap(pv(0), s(0)), app(pv(0), pv(1))), + rhs: unwrap(s(0), pv(1)), + }, + // Zippy.lean:617 + ZippyLaw { + name: "unwrap_union", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(union(s(0), s(1)), pv(0)), + rhs: union(unwrap(s(0), pv(0)), unwrap(s(1), pv(0))), + }, + // Zippy.lean:620 + ZippyLaw { + name: "unwrap_unwrap", + spaces: 1, + paths: 2, + bytes: 0, + pre: vec![], + lhs: unwrap(unwrap(s(0), pv(0)), pv(1)), + rhs: unwrap(s(0), app(pv(0), pv(1))), + }, + // Zippy.lean:623 + ZippyLaw { + name: "unwrap_wrap_ne", + spaces: 1, + paths: 0, + bytes: 2, + pre: vec![ne_byte(bv(0), bv(1))], + lhs: unwrap(wrap(cons(bv(0), nil()), s(0)), cons(bv(1), nil())), + rhs: empty(), + }, + // Zippy.lean:646 + ZippyLaw { + name: "dropPrefix_eps", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(singleton(pv(0)), nil()), + rhs: singleton(pv(0)), + }, + // Zippy.lean:649 + ZippyLaw { + name: "dropPrefix_self", + spaces: 0, + paths: 1, + bytes: 0, + pre: vec![], + lhs: unwrap(singleton(pv(0)), pv(0)), + rhs: singleton(nil()), + }, + // Zippy.lean:652 + ZippyLaw { + name: "dropPrefix_append", + spaces: 0, + paths: 2, + bytes: 0, + pre: vec![], + lhs: unwrap(singleton(app(pv(0), pv(1))), pv(0)), + rhs: singleton(pv(1)), + }, + // Zippy.lean:655 + ZippyLaw { + name: "dropPrefix_descend", + spaces: 0, + paths: 3, + bytes: 0, + pre: vec![], + lhs: unwrap(singleton(app(pv(0), pv(2))), app(pv(0), pv(1))), + rhs: unwrap(singleton(pv(2)), pv(1)), + }, + // Zippy.lean:662 + ZippyLaw { + name: "dropPrefix_miss_eps", + spaces: 0, + paths: 1, + bytes: 1, + pre: vec![], + lhs: unwrap(singleton(nil()), cons(bv(0), pv(0))), + rhs: empty(), + }, + // Zippy.lean:665 + ZippyLaw { + name: "dropPrefix_miss_item", + spaces: 0, + paths: 2, + bytes: 2, + pre: vec![ne_byte(bv(0), bv(1))], + lhs: unwrap(singleton(cons(bv(1), pv(1))), cons(bv(0), pv(0))), + rhs: empty(), + }, + // Zippy.lean:678 + ZippyLaw { + name: "empty_composition", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(empty(), s(0)), + rhs: empty(), + }, + // Zippy.lean:682 + ZippyLaw { + name: "composition_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(s(0), empty()), + rhs: empty(), + }, + // Zippy.lean:686 + ZippyLaw { + name: "union_composition", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(union(s(0), s(1)), s(2)), + rhs: union(composition(s(0), s(2)), composition(s(1), s(2))), + }, + // Zippy.lean:697 + ZippyLaw { + name: "composition_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: composition(s(0), union(s(1), s(2))), + rhs: union(composition(s(0), s(1)), composition(s(0), s(2))), + }, + // Zippy.lean:708 + ZippyLaw { + name: "singleton_composition", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: composition(singleton(pv(0)), s(0)), + rhs: wrap(pv(0), s(0)), + }, + // Zippy.lean:714 + ZippyLaw { + name: "singleton_union_composition", + spaces: 2, + paths: 1, + bytes: 0, + pre: vec![], + lhs: composition(union(singleton(pv(0)), s(0)), s(1)), + rhs: union(wrap(pv(0), s(1)), composition(s(0), s(1))), + }, + // Zippy.lean:729 + ZippyLaw { + name: "tailsUnion_empty", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: tails_union(empty()), + rhs: empty(), + }, + // Zippy.lean:733 + ZippyLaw { + name: "tailsUnion_eps", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: tails_union(singleton(nil())), + rhs: empty(), + }, + // Zippy.lean:738 + ZippyLaw { + name: "tailsUnion_cons", + spaces: 0, + paths: 1, + bytes: 1, + pre: vec![], + lhs: tails_union(singleton(cons(bv(0), pv(0)))), + rhs: singleton(pv(0)), + }, + // Zippy.lean:743 + ZippyLaw { + name: "tailsUnion_item", + spaces: 0, + paths: 0, + bytes: 1, + pre: vec![], + lhs: tails_union(singleton(cons(bv(0), nil()))), + rhs: singleton(nil()), + }, + // Zippy.lean:745 + ZippyLaw { + name: "tailsUnion_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: tails_union(union(s(0), s(1))), + rhs: union(tails_union(s(0)), tails_union(s(1))), + }, + // Zippy.lean:756 + ZippyLaw { + name: "tailsUnion_wrap", + spaces: 1, + paths: 0, + bytes: 1, + pre: vec![], + lhs: tails_union(wrap(cons(bv(0), nil()), s(0))), + rhs: s(0), + }, + // Zippy.lean:760 + ZippyLaw { + name: "tailsUnion_wrap_union", + spaces: 2, + paths: 0, + bytes: 1, + pre: vec![], + lhs: tails_union(union(wrap(cons(bv(0), nil()), s(0)), s(1))), + rhs: union(s(0), tails_union(s(1))), + }, + // Zippy.lean:777 + ZippyLaw { + name: "tailsInter_of_head_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![eq_space(head(s(0)), empty())], + lhs: tails_inter(s(0)), + rhs: empty(), + }, + // Zippy.lean:804 + ZippyLaw { + name: "tailsInter_of_head_singleton", + spaces: 1, + paths: 0, + bytes: 1, + pre: vec![eq_space(head(s(0)), singleton(cons(bv(0), nil())))], + lhs: tails_inter(s(0)), + rhs: unwrap(s(0), cons(bv(0), nil())), + }, + // Zippy.lean:811 + ZippyLaw { + name: "restriction_empty_left", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(empty(), s(0)), + rhs: empty(), + }, + // Zippy.lean:814 + ZippyLaw { + name: "restriction_empty_right", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), empty()), + rhs: empty(), + }, + // Zippy.lean:818 + ZippyLaw { + name: "restriction_eps", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), singleton(nil())), + rhs: s(0), + }, + // Zippy.lean:822 + ZippyLaw { + name: "restriction_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), union(s(1), s(2))), + rhs: union(restriction(s(0), s(1)), restriction(s(0), s(2))), + }, + // Zippy.lean:833 + ZippyLaw { + name: "restriction_singleton", + spaces: 1, + paths: 1, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), singleton(pv(0))), + rhs: wrap(pv(0), unwrap(s(0), pv(0))), + }, + // Zippy.lean:840 + ZippyLaw { + name: "restriction_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: restriction(s(0), s(0)), + rhs: s(0), + }, + // Zippy.lean:844 + ZippyLaw { + name: "head_empty", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: head(empty()), + rhs: empty(), + }, + // Zippy.lean:848 + ZippyLaw { + name: "head_eps", + spaces: 0, + paths: 0, + bytes: 0, + pre: vec![], + lhs: head(singleton(nil())), + rhs: empty(), + }, + // Zippy.lean:853 + ZippyLaw { + name: "head_union", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: head(union(s(0), s(1))), + rhs: union(head(s(0)), head(s(1))), + }, + // Zippy.lean:863 + ZippyLaw { + name: "head_cons", + spaces: 0, + paths: 1, + bytes: 1, + pre: vec![], + lhs: head(singleton(cons(bv(0), pv(0)))), + rhs: singleton(cons(bv(0), nil())), + }, + // Zippy.lean:867 + ZippyLaw { + name: "head_item", + spaces: 0, + paths: 0, + bytes: 1, + pre: vec![], + lhs: head(singleton(cons(bv(0), nil()))), + rhs: singleton(cons(bv(0), nil())), + }, + // Zippy.lean:870 + ZippyLaw { + name: "raffination_def", + spaces: 2, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(s(0), s(1)), + rhs: subtr(s(0), restriction(s(0), s(1))), + }, + // Zippy.lean:872 + ZippyLaw { + name: "raffination_self", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: raffination(s(0), s(0)), + rhs: empty(), + }, + // Zippy.lean:945 + ZippyLaw { + name: "iterC_empty", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: iter_c(empty(), s(0)), + rhs: empty(), + }, + // Zippy.lean:948 + ZippyLaw { + name: "iterC_eps", + spaces: 1, + paths: 0, + bytes: 0, + pre: vec![], + lhs: iter_c(singleton(nil()), s(0)), + rhs: empty(), + }, + // Zippy.lean:951 + ZippyLaw { + name: "iterC_cons", + spaces: 1, + paths: 1, + bytes: 1, + pre: vec![], + lhs: iter_c(singleton(cons(bv(0), pv(0))), s(0)), + rhs: s(0), + }, + // Zippy.lean:954 + ZippyLaw { + name: "iterC_item", + spaces: 1, + paths: 0, + bytes: 1, + pre: vec![], + lhs: iter_c(singleton(cons(bv(0), nil())), s(0)), + rhs: s(0), + }, + // Zippy.lean:956 + ZippyLaw { + name: "iterC_union", + spaces: 3, + paths: 0, + bytes: 0, + pre: vec![], + lhs: iter_c(union(s(0), s(1)), s(2)), + rhs: union(iter_c(s(0), s(2)), iter_c(s(1), s(2))), + }, + ] +} + +// Not exported: +// Zippy.lean:74 mem_def: conclusion is not an equation of spaces (Iff) +// Zippy.lean:85 ext: hypothesis is a ∀ +// Zippy.lean:94 valAt_eq: conclusion is not an equation of spaces (equation of Option Unit) +// Zippy.lean:97 not_mem_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:180 wz_trie: mentions PrunedModel.PZip.trie +// Zippy.lean:181 wz_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:182 wz_descendTo_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:183 wz_descendTo_trie: mentions PrunedModel.PZip.trie +// Zippy.lean:185 subtrie_nil: mentions PrunedModel.PrunedMap.subtrie +// Zippy.lean:190 wz_makeMap: mentions PrunedModel.PZip.makeMap +// Zippy.lean:192 not_mem_empty: conclusion is not an equation of spaces (¬) +// Zippy.lean:194 mem_singleton: conclusion is not an equation of spaces (Iff) +// Zippy.lean:207 union_eq_join: mentions PrunedModel.PrunedMap.join +// Zippy.lean:211 inter_eq_meet: mentions PrunedModel.PrunedMap.meet +// Zippy.lean:215 subtr_eq_sub: mentions PrunedModel.PrunedMap.sub +// Zippy.lean:219 mem_union: conclusion is not an equation of spaces (Iff) +// Zippy.lean:222 mem_inter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:225 mem_subtr: conclusion is not an equation of spaces (Iff) +// Zippy.lean:229 wrap_eq: mentions PrunedModel.PrunedMap.replaceAt +// Zippy.lean:232 mem_wrap: conclusion is not an equation of spaces (Iff) +// Zippy.lean:246 mem_unwrap: conclusion is not an equation of spaces (Iff) +// Zippy.lean:249 mem_keys: conclusion is not an equation of spaces (Iff) +// Zippy.lean:254 mem_ofList: conclusion is not an equation of spaces (Iff) +// Zippy.lean:268 mem_childMask: conclusion is not an equation of spaces (Iff) +// Zippy.lean:284 mem_foldl_union: binder α : Type +// Zippy.lean:302 mem_foldl_inter: binder α : Type +// Zippy.lean:314 mem_restriction: conclusion is not an equation of spaces (Iff) +// Zippy.lean:345 mem_composition_step: conclusion is not an equation of spaces (Iff) +// Zippy.lean:366 mem_composition: conclusion is not an equation of spaces (Iff) +// Zippy.lean:393 mem_head: conclusion is not an equation of spaces (Iff) +// Zippy.lean:400 mem_child: conclusion is not an equation of spaces (Iff) +// Zippy.lean:404 mem_tailsUnion: conclusion is not an equation of spaces (Iff) +// Zippy.lean:411 mem_tailsInter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:434 mem_iterH: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:446 mem_iter: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:454 mem_iterC: conclusion is not an equation of spaces (Iff) +// Zippy.lean:460 mem_raffination: conclusion is not an equation of spaces (Iff) +// Zippy.lean:474 elemP_empty: conclusion is not an equation of spaces (¬) +// Zippy.lean:476 elemP_singleton: conclusion is not an equation of spaces (Membership.mem) +// Zippy.lean:478 elemP_singleton_ne: conclusion is not an equation of spaces (¬) +// Zippy.lean:480 elemP_union: conclusion is not an equation of spaces (Iff) +// Zippy.lean:482 elemP_inter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:484 elemP_subtr: conclusion is not an equation of spaces (Iff) +// Zippy.lean:561 concat_eps: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:563 eps_concat: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:565 concat_assoc: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:631 unwrap_singleton: mentions PrunedModel.Zippy.unwrap_singleton.match_1 +// Zippy.lean:659 dropPrefix_miss: hypothesis is a ∀ +// Zippy.lean:768 enumHeads_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:786 tailsInter_eq_foldl: hypothesis mentions PrunedModel.Zippy.EnumHeads +// Zippy.lean:885 iter_def: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:888 iterH_empty: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:893 iterH_union: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:904 iterH_item: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:912 iter_not_union_source: conclusion is not an equation of spaces (¬) +// Zippy.lean:982 union_eq_right_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:991 IsLeastPostFix.init: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:993 IsLeastPostFix.post: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:995 IsLeastPostFix.park: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:998 IsLeastPostFix.unique: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:1005 fix_self: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) +// Zippy.lean:1018 init_le_kleene: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:1024 kleene_isLeastPostFix: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:1053 joinInto_root: mentions PrunedModel.PZip.trie +// Zippy.lean:1062 joinInto_eq_union: mentions PrunedModel.PZip.trie +// Zippy.lean:1070 joinInto_ne_union: conclusion is not an equation of spaces (Ne) +// Zippy.lean:1082 mem_rawRestrict: conclusion is not an equation of spaces (Iff) +// Zippy.lean:1103 rawRestrict_eq_restriction: mentions PrunedModel.Zippy.rawRestrict +// Zippy.lean:1115 rawRestrict_empty_ne: conclusion is not an equation of spaces (Ne) +// Zippy.lean:1121 rawRestrict_eps_ne: conclusion is not an equation of spaces (Ne) +// Zippy.lean:1132 mem_rawWrap: conclusion is not an equation of spaces (Iff) +// Zippy.lean:1168 rawWrap_eq_wrap: mentions PrunedModel.Zippy.rawWrap +// Zippy.lean:1178 rawWrap_ne_wrap: conclusion is not an equation of spaces (Ne) +// Zippy.lean:1290 fix_ab: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) +// Zippy.lean:1299 fix_not_too_small: conclusion is not an equation of spaces (¬) diff --git a/differential/src/bin/alg_bug_repros.rs b/differential/src/bin/alg_bug_repros.rs index 57a8cf6b..ab0c07ef 100644 --- a/differential/src/bin/alg_bug_repros.rs +++ b/differential/src/bin/alg_bug_repros.rs @@ -16,6 +16,8 @@ use pathmap::PathMap; use pathmap::experimental::zipper_algebra::{zipper_join, zipper_meet, zipper_sym_diff}; use pathmap::zipper::{ZipperMoving, ZipperPath, ZipperValues, ZipperWriting}; +use differential::algebraic::value::Bits; + /// A trie holding only dangling paths: structure written with `create_path` /// and no value anywhere. fn dangling(paths: &[&[u8]]) -> PathMap { @@ -269,7 +271,59 @@ fn main() { println!(" => not counted as a failure; the crate has not settled this"); } - println!("\n{} of 6 still reproduce", r.failed); + // ---------------------------------------------------------------- 8 + // `meet_into` keeps the destination's focus value when the source has one, + // rather than meeting the two. Invisible with `u64`, whose `pmeet` returns + // the left operand anyway; a value type whose meet makes a new value shows + // it. Found as `tails_inter` disagreeing between its fold strategies. + { + let mut dst = PathMap::::new(); + dst.set_val_at([], Bits(0b1111)); + let mut src = PathMap::::new(); + src.set_val_at([], Bits(0b0001)); + let eager = dst.meet(&src); + let mut out = dst.clone(); + out.write_zipper().meet_into(&src.read_zipper(), false); + r.case( + "8", + "meet_into at a focus value: {_:1111} & {_:0001}", + format!("root value {:?} (PathMap::meet)", eager.get([])), + format!("root value {:?} (meet_into)", out.get([])), + ); + } + + // ---------------------------------------------------------------- 9 + // `take_map` at a focus that holds a value and nothing below it returns a + // map holding that value at its root -- and any later write below that + // root panics with "Attempted to make_unique on an empty sentinel node". + // Found through `wrap(unwrap(..))`, the take_map route of `unwrap` feeding + // the insert_prefix route of `wrap`. Fixed on `fix/fvc-leftovers` by + // f1bdca9 (join_map_into, take_map and restricting ignore empty + // materialised nodes); still panics on master and on focus_value_consistency. + { + let got = std::panic::catch_unwind(|| { + let mut a = PathMap::::new(); + a.set_val_at([1, 0], 1); + let mut m = { + let mut wz = a.write_zipper(); + wz.descend_to([1, 0]); + wz.take_map(false).unwrap() + }; + m.set_val_at([5], 2); + m.iter().map(|(k, v)| (k, *v)).collect::>() + }); + r.case( + "9", + "take_map of a value-only focus, then set_val_at([5])", + "[([], 1), ([5], 2)]".to_string(), + match got { + Ok(v) => format!("{v:?}"), + Err(_) => "panic: make_unique on an empty sentinel node".to_string(), + }, + ); + } + + println!("\n{} of 8 still reproduce", r.failed); if r.failed > 0 { std::process::exit(1); } diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 40616476..de425624 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -16,7 +16,7 @@ use differential::algebraic::{ self, - expr::{Expr, Op}, + expr::{Expr, Kind, Op}, known, signatures, value::{Bits, FuzzValue}, }; @@ -407,8 +407,8 @@ fn every_strategy_index_is_reachable_from_some_pointwise_route() { // Route `k` picks strategy `k % n` per operator, so POINTWISE_ROUTES has to // be at least as large as the widest operator's strategy table or some // implementation would never be exercised. - for op in Op::ALL { - let n = algebraic::routes::strategies(op).len(); + for op in Kind::ALL { + let n = algebraic::routes::kind_strategies(op).len(); assert!( n <= algebraic::routes::POINTWISE_ROUTES, "{op:?} has {n} strategies but only {} pointwise routes", @@ -457,3 +457,75 @@ fn every_whole_expression_route_applies_to_some_random_case() { assert!(*n > 0, "route {} never applies in {CASES} random cases", r.name(&Expr::Var(0))); } } + +// ------------------------------------------------------------- Zippy laws + +/// The case must offer as many spaces, paths and bytes as any law binds. +#[test] +fn every_law_variable_has_something_to_bind_to() { + let (spaces, paths, bytes) = algebraic::laws::arity(); + assert!(spaces <= algebraic::OPERANDS, "a law needs {spaces} spaces"); + assert!(paths <= algebraic::LAW_PATHS, "a law needs {paths} paths"); + assert!(bytes <= algebraic::LAW_BYTES, "a law needs {bytes} bytes"); +} + +/// Every generated law holds in the flat model. +/// +/// The laws are theorems about Zippy's operators, and `model.rs` is those +/// operators' membership lemmas read as code, with no trie anywhere. So a +/// failure here is never the crate: it is the Lean-to-Rust translation, the +/// variable binding, or the model -- exactly the parts of the harness that, if +/// wrong, would make every law finding a false one. +#[test] +fn zippy_laws_hold_in_the_model() { + use algebraic::laws::{instantiate, laws, Binding, Hyp}; + use algebraic::routes::{eval, Route}; + const CASES: usize = 3_000; + let mut rng = algebraic::Rng::for_job(20261031, 0); + let mut checked = vec![0usize; laws::<()>().len()]; + let mut failures = Vec::new(); + let _ = with_quiet_panics(|| { + for _ in 0..CASES { + let bytes = rng.input(); + let Ok(case) = std::panic::catch_unwind(|| algebraic::decode::<()>(&bytes)) else { + continue; + }; + let bind = Binding { paths: &case.law_paths, bytes: &case.law_bytes }; + let model = |e: &Expr| eval(Route::Model, e, &case.operands).unwrap().values; + 'laws: for (i, law) in laws::<()>().iter().enumerate() { + let inst = instantiate(law, &bind); + for h in &inst.pre { + let holds = match h { + Hyp::Holds(b) => *b, + Hyp::Mem(p, e, want) => model(e).contains_key(p) == *want, + Hyp::Eq(l, r) => model(l) == model(r), + }; + if !holds { + continue 'laws; + } + } + checked[i] += 1; + if model(&inst.lhs) != model(&inst.rhs) { + failures.push(format!("{}: {} vs {}", law.name, inst.lhs, inst.rhs)); + } + } + } + }); + assert!(failures.is_empty(), "laws false in the model:\n{}", failures.join("\n")); + // A law whose hypotheses never hold is checked by nothing. + let never: Vec<&str> = laws::<()>() + .iter() + .zip(&checked) + .filter(|(_, n)| **n == 0) + .map(|(l, _)| l.name) + .collect(); + assert!(never.is_empty(), "laws never applicable in {CASES} cases: {never:?}"); +} + +/// Laws are checked for the set type only; see `laws.rs`. +#[test] +fn zippy_laws_apply_to_the_set_type_only() { + assert!(!algebraic::laws::laws::<()>().is_empty()); + assert!(algebraic::laws::laws::().is_empty()); + assert!(algebraic::laws::laws::().is_empty()); +} From 6d5c188536a4d75fed7768da14474b808fb74b33 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Sat, 31 Oct 2026 14:44:22 +0000 Subject: [PATCH 11/17] alg_bug_repros: compare values, not the strings that describe them Report::case compared strings that carried each side's label -- "root value Some(1) (PathMap::join)" against "... (join_into)", or "Some(2), the left operand's value" against "Some(2)" -- so cases 1, 2, 3a, 3b, 4 and 8 could never print "fixed". It now takes a label and a value per side, compares the values and prints the labels. On this branch all eight print "fixed"; on master all eight reproduce. --- differential/src/bin/alg_bug_repros.rs | 58 +++++++++++++++----------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/differential/src/bin/alg_bug_repros.rs b/differential/src/bin/alg_bug_repros.rs index ab0c07ef..4dcd2936 100644 --- a/differential/src/bin/alg_bug_repros.rs +++ b/differential/src/bin/alg_bug_repros.rs @@ -63,14 +63,23 @@ struct Report { } impl Report { - fn case(&mut self, n: &str, what: &str, want: String, got: String) { + /// Compares the values only. The labels say where each came from and are + /// printed, never compared -- an earlier version compared strings that + /// included them, so most cases could never print "fixed". + fn case( + &mut self, + n: &str, + what: &str, + (want_label, want): (&str, T), + (got_label, got): (&str, T), + ) { let ok = want == got; if !ok { self.failed += 1; } println!("\n{n}. {what}"); - println!(" expected: {want}"); - println!(" got: {got}"); + println!(" expected: {want:?} ({want_label})"); + println!(" got: {got:?} ({got_label})"); println!(" => {}", if ok { "fixed" } else { "REPRODUCES" }); } } @@ -94,8 +103,8 @@ fn main() { r.case( "1", "join_into on an empty destination: empty | {_:1}", - format!("root value {:?} (PathMap::join)", val_at(&eager, &[])), - format!("root value {:?} (join_into)", val_at(&out, &[])), + ("root value, PathMap::join", val_at(&eager, &[])), + ("root value, join_into", val_at(&out, &[])), ); } @@ -116,8 +125,8 @@ fn main() { r.case( "2", "meet_2 with root values only: {_:2} & {_:1}", - format!("root value {:?} (PathMap::meet)", val_at(&eager, &[])), - format!("root value {:?} (meet_2)", val_at(&out, &[])), + ("root value, PathMap::meet", val_at(&eager, &[])), + ("root value, meet_2", val_at(&out, &[])), ); } @@ -139,14 +148,14 @@ fn main() { r.case( "3a", "join value bias: {00:2} | {00:1, dangling below} at [0]", - "Some(2), the left operand's value".to_string(), - format!("{:?}", val_at(&c.join(&a), &[0])), + ("the left operand's value", Some(2)), + ("PathMap::join", val_at(&c.join(&a), &[0])), ); r.case( "3b", "meet value bias: {00:1, dangling below} & {00:2} at [0]", - "Some(1), the left operand's value".to_string(), - format!("{:?}", val_at(&a.meet(&c), &[0])), + ("the left operand's value", Some(1)), + ("PathMap::meet", val_at(&a.meet(&c), &[0])), ); } @@ -169,12 +178,11 @@ fn main() { b.write_zipper_at_path(&[1, 0, 0, 0]).set_val(1); let ab = a.join(&b); - let ba = b.join(&a); r.case( "4", "join drops a value across clone-shared structure, at [1,0,0,0]", - format!("a|b == b|a == Some(1); b|a gives {:?}", val_at(&ba, &[1, 0, 0, 0])), - format!("a|b gives {:?}", val_at(&ab, &[1, 0, 0, 0])), + ("the value b adds, which b|a keeps", Some(1)), + ("a|b", val_at(&ab, &[1, 0, 0, 0])), ); } @@ -192,8 +200,8 @@ fn main() { r.case( "5", "merkleize over dangling-only structure", - "no panic".to_string(), - if res.is_ok() { "no panic".to_string() } else { "panic".to_string() }, + ("", "no panic"), + ("merkleize", if res.is_ok() { "no panic" } else { "panic" }), ); } @@ -281,14 +289,13 @@ fn main() { dst.set_val_at([], Bits(0b1111)); let mut src = PathMap::::new(); src.set_val_at([], Bits(0b0001)); - let eager = dst.meet(&src); let mut out = dst.clone(); out.write_zipper().meet_into(&src.read_zipper(), false); r.case( "8", "meet_into at a focus value: {_:1111} & {_:0001}", - format!("root value {:?} (PathMap::meet)", eager.get([])), - format!("root value {:?} (meet_into)", out.get([])), + ("root value, 1111 & 0001", Some(Bits(0b0001))), + ("root value, meet_into", out.get([]).copied()), ); } @@ -315,11 +322,14 @@ fn main() { r.case( "9", "take_map of a value-only focus, then set_val_at([5])", - "[([], 1), ([5], 2)]".to_string(), - match got { - Ok(v) => format!("{v:?}"), - Err(_) => "panic: make_unique on an empty sentinel node".to_string(), - }, + ("", "[([], 1), ([5], 2)]".to_string()), + ( + "the map after the write", + match got { + Ok(v) => format!("{v:?}"), + Err(_) => "panic: make_unique on an empty sentinel node".to_string(), + }, + ), ); } From 40f3175b08148dd8bfd5d6763105bcb5e8d8a801 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Sat, 31 Oct 2026 18:48:36 +0000 Subject: [PATCH 12/17] alg_fuzz: check each Zippy law under substitution and congruence A theorem holds for every space, so its space variables can be bound to expressions instead of operands (`+subst`), and if l = r then C[l] = C[r] for any context C (`+ctx`, `+subst+ctx`). Neither needs a new proof. Substitution gives laws operands the crate built; congruence asks whether an operation's answer depends on anything but the set it is given. Both are decoded after every other byte, so existing inputs replay as the plain laws. A context is applied only to sides that already agree and are not both empty. The model test checks every form and that each one fires. On master, `+subst` re-finds the join loss (repro 4) under eight laws in 2M cases; those signatures are added to KNOWN. `+ctx` has not fired. Also skip comparisons of a trie truncated at SHAPE_CAP: its values are a prefix of the real ones, so against the uncapped model every route seemed to lose the same values. Composition of compositions reaches the cap. --- differential/ALGEBRAIC_FUZZING.md | 22 +++ differential/src/algebraic.rs | 211 +++++++++++++++++++++++---- differential/src/algebraic/laws.rs | 87 ++++++++++- differential/src/algebraic/routes.rs | 8 + differential/tests/algebraic.rs | 63 +++++--- 5 files changed, 340 insertions(+), 51 deletions(-) diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index f3870b3f..ec70fad9 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -150,6 +150,28 @@ cancel; a meet of two values can be bottom). `tests/algebraic.rs` checks every generated law against the flat model, which is the membership lemmas read as code; a failure there is the translation or the harness, never the crate. +Each theorem is checked in three forms, all valid without further proof: + +| form | signature | what it is | +|---|---|---| +| plain | `law:` | spaces bound to the operands | +| substitution | `law:+subst` | some spaces bound to small expressions (`Case::law_spaces`), or two to the same operand | +| congruence | `law:+ctx`, `+subst+ctx` | both sides of the plain or substitution instance put in one context `C[_]` (`Case::law_ctx`) | + +Substitution holds because a theorem is about every space and any expression +denotes one; it gives a law operands the crate built — its sharing, node +layout and root values — rather than only ones the generator wrote. Congruence +holds because `l = r` gives `C[l] = C[r]`; the two sides hold the same set but +were built differently, so a failure means some operation in `C` answered +according to how its input was stored rather than what it held. That is the +question behind the layout and sharing defects (causes 1 and 2), which nothing +else asks directly. A context is applied only once the two sides have agreed, +and not when both are empty and built alike (half of all instances, and +nothing for a context to tell apart), so a defect is reported in the +simplest form that shows it. The extra forms are decoded +from bytes after everything else, so an older input that ends early decodes to +the plain laws only. + Laws are the reason a defect in the *baseline* is findable at all. When `PathMap::join` loses a value, no route disagrees with the baseline in an interesting way — the baseline is what everyone is compared against. diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index 48813847..2a756090 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -35,7 +35,7 @@ use pathmap::PathMap; use pathmap::zipper::{ZipperMoving, ZipperWriting}; use expr::{Expr, Op, Un, MAX_VARS}; -use laws::{Binding, Hyp}; +use laws::{Binding, Ctx, Hyp, Instance}; use routes::Route; use shape::{shape_of_map, show_shape, Shape, Values}; use value::FuzzValue; @@ -135,6 +135,13 @@ pub struct Case { /// and the hypotheses land on structure that exists. pub law_paths: Vec>, pub law_bytes: Vec, + /// What each law's space variables stand for in the substitution + /// instance: `Var(i)` where space `i` is left alone, otherwise a small + /// expression. See `laws.rs`. + pub law_spaces: Vec, + /// The context the congruence instance puts both sides of each law in; + /// [`Ctx::Hole`] for none. + pub law_ctx: Ctx, } /// Decode a byte string into a case. Total: every input decodes. @@ -165,7 +172,7 @@ pub fn decode(bytes: &[u8]) -> Case { .iter() .flat_map(|m| m.iter().map(|(k, _)| k).collect::>()) .collect(); - let law_paths = (0..LAW_PATHS) + let law_paths: Vec> = (0..LAW_PATHS) .map(|_| { if !keys.is_empty() && g.chance(70) { let k = &keys[g.modn(keys.len())]; @@ -185,7 +192,46 @@ pub fn decode(bytes: &[u8]) -> Case { } }) .collect(); - Case { expr, operands, builds, alphabet, law_paths, law_bytes } + // Read last, so an input that ends before here -- every corpus input from + // before these existed -- decodes to the plain laws: a zero byte leaves a + // space alone and makes no context. + let law_spaces = (0..OPERANDS) + .map(|i| if g.modn(5) >= 3 { gen_expr(&mut g, 2) } else { Expr::Var(i) }) + .collect(); + let law_ctx = gen_ctx(&mut g, &law_paths, 2); + Case { expr, operands, builds, alphabet, law_paths, law_bytes, law_spaces, law_ctx } +} + +/// A context for the congruence check: none half the time, otherwise one or +/// two operators around the hole. Its paths come from the law paths half the +/// time, so an `unwrap` around the hole lands on structure that exists. +fn gen_ctx(g: &mut Gen, paths: &[Vec], depth: usize) -> Ctx { + if depth == 0 || g.modn(2) == 0 { + return Ctx::Hole; + } + let path = |g: &mut Gen| { + if !paths.is_empty() && g.boolean() { paths[g.modn(paths.len())].clone() } else { g.path(2) } + }; + match g.modn(8) { + 0..=3 => { + let op = Op::ALL[g.modn(Op::ALL.len())]; + let e = gen_expr(g, 1); + let c = Box::new(gen_ctx(g, paths, depth - 1)); + if g.boolean() { Ctx::Right(op, e, c) } else { Ctx::Left(op, c, e) } + } + 4 => { + let p = path(g); + Ctx::Wrap(p, Box::new(gen_ctx(g, paths, depth - 1))) + } + 5 => { + let p = path(g); + Ctx::Unwrap(Box::new(gen_ctx(g, paths, depth - 1)), p) + } + _ => { + let u = Un::ALL[g.modn(Un::ALL.len())]; + Ctx::Un(u, Box::new(gen_ctx(g, paths, depth - 1))) + } + } } fn pick_build(g: &mut Gen, i: usize) -> Build { @@ -381,6 +427,13 @@ pub fn check(case: &Case) -> Vec { .expect("route 0 is the whole-map operations, which apply to everything"); let base_name = baseline_route.name(&case.expr); + // Too big to compare (see `Outcome::truncated`). Rare -- it takes a + // composition of compositions -- and the laws evaluate other expressions, + // so they still run. + if baseline.truncated() { + return check_laws(case); + } + // The model is computed up front so every divergence can say which side it // backs. Worth the one extra evaluation: the baseline is `PathMap::join` // and friends, which have defects of their own, so "route X disagrees with @@ -449,42 +502,101 @@ pub fn check(case: &Case) -> Vec { /// A law's spaces are the case's operands in order, and its paths and bytes /// are [`Case::law_paths`] and [`Case::law_bytes`]. A law whose hypotheses /// are false for those is skipped for this case: the theorem says nothing. +/// +/// Each law is then checked in up to three more forms, if the case asks +/// (see `laws.rs`): with its spaces bound to [`Case::law_spaces`] +/// (`+subst`), and the plain or substitution instance with both sides put in +/// [`Case::law_ctx`] (`+ctx`, `+subst+ctx`) once its sides agree. pub fn check_laws(case: &Case) -> Vec { - let bind = Binding { paths: &case.law_paths, bytes: &case.law_bytes }; + let plain: Vec = (0..OPERANDS).map(Expr::Var).collect(); + let bind = Binding { spaces: &plain, paths: &case.law_paths, bytes: &case.law_bytes }; + let subst = Binding { spaces: &case.law_spaces, ..bind }; + // `None` for a trie too big to compare (see `Outcome::truncated`): an + // instance that needs one is skipped, as if its hypotheses were false. let eval = |e: &Expr| { - routes::eval(Route::Pointwise(0), e, &case.operands) - .expect("route 0 applies to every expression") - .values + let o = routes::eval(Route::Pointwise(0), e, &case.operands) + .expect("route 0 applies to every expression"); + (!o.truncated()).then_some(o) + }; + let holds = |inst: &Instance| { + inst.pre.iter().all(|h| match h { + Hyp::Holds(b) => *b, + Hyp::Mem(p, e, want) => eval(e).is_some_and(|o| o.values.contains_key(p) == *want), + Hyp::Eq(l, r) => match (eval(l), eval(r)) { + (Some(l), Some(r)) => l.values == r.values, + _ => false, + }, + }) + }; + // Both sides of an instance, or `None` when the law says nothing here: + // its hypotheses are false, or a side is too big to compare. + let sides = |inst: &Instance| { + if !holds(inst) { + return None; + } + Some((eval(&inst.lhs)?, eval(&inst.rhs)?)) + }; + let report = |name: String, lhs: &Expr, rhs: &Expr, l: &Values, r: &Values, note: String| { + Divergence { + class: Class::Law, + signature: signature::("law", &name), + detail: format!( + "{name}: {}\n lhs {lhs}: {}\n rhs {rhs}: {}{note}", + shape::first_values_diff(l, r).unwrap_or_default(), + shape::show_values(l), + shape::show_values(r), + ), + } + }; + + // `C[lhs]` against `C[rhs]`, given the two sides already agreed on values. + // Skipped when both are empty and built the same: the context then sees + // two copies of nothing, and that is about half of all instances. + let congruence = |name: String, inst: &Instance, l: &routes::Outcome, r: &routes::Outcome| { + if case.law_ctx.is_hole() || (l.values.is_empty() && l.shape == r.shape) { + return None; + } + let (cl, cr) = (case.law_ctx.plug(inst.lhs.clone()), case.law_ctx.plug(inst.rhs.clone())); + let (Some(ol), Some(or)) = (eval(&cl), eval(&cr)) else { return None }; + let (vl, vr) = (ol.values, or.values); + if vl == vr { + return None; + } + // Both sides held the same set before the context saw them, so + // whatever differs between them is not a set: say what it was, when + // the route reports structure. + let inner = match (&l.shape, &r.shape) { + (Some(ls), Some(rs)) if ls != rs => format!( + "differ only in structure: {}", + shape::first_shape_diff(ls, rs).unwrap_or_default() + ), + (Some(_), Some(_)) => "have the same paths, dangling ones included".to_string(), + _ => "agree on values".to_string(), + }; + let note = format!("\n context {}; inside it, {} and {} {inner}", case.law_ctx, inst.lhs, inst.rhs); + Some(report(name, &cl, &cr, &vl, &vr, note)) }; let mut out = Vec::new(); - 'laws: for law in laws::laws::() { + for law in laws::laws::() { let inst = laws::instantiate(law, &bind); - for h in &inst.pre { - let holds = match h { - Hyp::Holds(b) => *b, - Hyp::Mem(p, e, want) => eval(e).contains_key(p) == *want, - Hyp::Eq(l, r) => eval(l) == eval(r), - }; - if !holds { - continue 'laws; + if let Some((l, r)) = sides(&inst) { + if l.values != r.values { + out.push(report(law.name.to_string(), &inst.lhs, &inst.rhs, &l.values, &r.values, String::new())); + continue; } + out.extend(congruence(format!("{}+ctx", law.name), &inst, &l, &r)); } - let (l, r) = (eval(&inst.lhs), eval(&inst.rhs)); - if l != r { - out.push(Divergence { - class: Class::Law, - signature: signature::("law", law.name), - detail: format!( - "{}: {}\n lhs {}: {}\n rhs {}: {}", - law.name, - shape::first_values_diff(&l, &r).unwrap_or_default(), - inst.lhs, - shape::show_values(&l), - inst.rhs, - shape::show_values(&r), - ), - }); + if laws::substituted(law, &case.law_spaces) { + let inst = laws::instantiate(law, &subst); + if let Some((l, r)) = sides(&inst) { + if l.values != r.values { + let name = format!("{}+subst", law.name); + out.push(report(name, &inst.lhs, &inst.rhs, &l.values, &r.values, String::new())); + continue; + } + out.extend(congruence(format!("{}+subst+ctx", law.name), &inst, &l, &r)); + } } } out @@ -786,6 +898,22 @@ pub const KNOWN: &[Known] = &[ Known { signature: "unit:law:singleton_union_composition", cause: LOSS }, Known { signature: "unit:law:union_inter_distrib", cause: LOSS }, Known { signature: "unit:law:restriction_union", cause: LOSS }, + // The same laws with their spaces bound to expressions: the same loss, + // reached through operands the crate built. Eight of these were seen in + // 2M cases; the rest are listed because they are the same law and cause. + // Congruence forms (`+ctx`) have never failed and are absent on purpose. + Known { signature: "unit:law:union_comm+subst", cause: LOSS }, + Known { signature: "unit:law:union_assoc+subst", cause: LOSS }, + Known { signature: "unit:law:union_subtr_distrib+subst", cause: LOSS }, + Known { signature: "unit:law:unwrap_union+subst", cause: LOSS }, + Known { signature: "unit:law:head_union+subst", cause: LOSS }, + Known { signature: "unit:law:tailsUnion_union+subst", cause: LOSS }, + Known { signature: "unit:law:iterC_union+subst", cause: LOSS }, + Known { signature: "unit:law:composition_union+subst", cause: LOSS }, + Known { signature: "unit:law:union_composition+subst", cause: LOSS }, + Known { signature: "unit:law:singleton_union_composition+subst", cause: LOSS }, + Known { signature: "unit:law:union_inter_distrib+subst", cause: LOSS }, + Known { signature: "unit:law:restriction_union+subst", cause: LOSS }, ]; pub fn known(signature: &str) -> Option<&'static Known> { @@ -1030,6 +1158,27 @@ pub fn describe(case: &Case) -> String { show_shape(&sh) )); } + if V::IS_SET { + let shown = |p: &Vec| expr::show_path(p); + s.push_str(&format!( + "law paths: {} bytes: {:?}\n", + case.law_paths.iter().map(shown).collect::>().join(" "), + case.law_bytes + )); + let sub: Vec = case + .law_spaces + .iter() + .enumerate() + .filter(|(i, e)| !matches!(e, Expr::Var(j) if j == i)) + .map(|(i, e)| format!("{} := {e}", (b'a' + i as u8) as char)) + .collect(); + if !sub.is_empty() { + s.push_str(&format!("law subst: {}\n", sub.join(", "))); + } + if !case.law_ctx.is_hole() { + s.push_str(&format!("law ctx: {}\n", case.law_ctx)); + } + } s } diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs index 15f7da2a..8a4733dc 100644 --- a/differential/src/algebraic/laws.rs +++ b/differential/src/algebraic/laws.rs @@ -22,6 +22,28 @@ //! carries for the purpose ([`super::Case::law_paths`]), and a law whose //! hypotheses are false for that binding is skipped for that case. //! +//! # More instances than the theorems state +//! +//! Two rules turn each theorem into many checks, with no new proof: +//! +//! * **Substitution.** A theorem holds for *every* space, and any expression +//! denotes one, so a space variable can be bound to an expression rather than +//! an operand ([`super::Case::law_spaces`]). The point is the operands a law +//! then sees: tries the crate itself produced, with whatever sharing, node +//! layout and root values its operations leave behind, instead of only the +//! ones the generator writes. Binding two variables to the same operand +//! (`a, b := a, a`) is a case of it, and makes both sides share nodes. +//! +//! * **Congruence.** If `l = r` then `C[l] = C[r]` for any context `C` +//! ([`Ctx`], [`super::Case::law_ctx`]). Both sides hold the same set and were +//! built differently, so this asks whether an operation's answer depends on +//! anything but the set it is given -- the question behind the layout and +//! sharing defects, which nothing else asks directly. +//! +//! Each is reported under its own signature (`law:+subst`, `+ctx`, +//! `+subst+ctx`), and a context is applied only to an instance whose sides +//! already agreed, so a defect is reported in the simplest form that shows it. +//! //! # Only for `()` //! //! The theorems are about `PrunedMap Unit`, a finite set of paths. They are @@ -181,8 +203,11 @@ pub mod zippy { } } -/// Paths and bytes a case offers for a law's path and byte variables. +/// What a case offers for a law's variables. pub struct Binding<'a> { + /// What space `i` stands for: `Var(i)` for the plain law, any expression + /// for a substitution instance. + pub spaces: &'a [Expr], pub paths: &'a [Vec], pub bytes: &'a [u8], } @@ -208,10 +233,10 @@ impl Binding<'_> { } } - /// The expression a term denotes, its space `i` being operand `i`. + /// The expression a term denotes, its space `i` being `spaces[i]`. pub fn expr(&self, t: &T) -> Expr { match t { - T::S(i) => Expr::Var(*i), + T::S(i) => self.spaces[*i].clone(), T::Empty => Expr::Empty, T::Singleton(p) => Expr::Singleton(self.path(p)), T::Bin(op, a, b) => Expr::bin(*op, self.expr(a), self.expr(b)), @@ -263,6 +288,62 @@ pub fn laws() -> &'static [ZippyLaw] { if V::IS_SET { LAWS.get_or_init(super::zippy_laws::laws) } else { &[] } } +/// Whether `spaces` binds any of `law`'s space variables to something other +/// than the operand of the same index -- that is, whether the substitution +/// instance differs from the plain one. +pub fn substituted(law: &ZippyLaw, spaces: &[Expr]) -> bool { + spaces[..law.spaces].iter().enumerate().any(|(i, e)| !matches!(e, Expr::Var(j) if *j == i)) +} + +/// An expression with one hole: the context a law's two sides are put in to +/// check congruence. See the module comment. +#[derive(Clone, Debug)] +pub enum Ctx { + Hole, + /// `(C op e)`. + Left(Op, Box, Expr), + /// `(e op C)`. + Right(Op, Expr, Box), + Wrap(Vec, Box), + Unwrap(Box, Vec), + Un(Un, Box), +} + +impl Ctx { + pub fn is_hole(&self) -> bool { + matches!(self, Ctx::Hole) + } + + /// `C[e]`. + pub fn plug(&self, e: Expr) -> Expr { + match self { + Ctx::Hole => e, + Ctx::Left(op, c, r) => Expr::bin(*op, c.plug(e), r.clone()), + Ctx::Right(op, l, c) => Expr::bin(*op, l.clone(), c.plug(e)), + Ctx::Wrap(p, c) => Expr::wrap(p.clone(), c.plug(e)), + Ctx::Unwrap(c, p) => Expr::unwrap(c.plug(e), p.clone()), + Ctx::Un(u, c) => Expr::un(*u, c.plug(e)), + } + } +} + +/// Written like [`Expr`], with `_` for the hole. +impl std::fmt::Display for Ctx { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use super::expr::show_path; + match self { + Ctx::Hole => write!(f, "_"), + Ctx::Left(Op::IterC, c, r) => write!(f, "iter_c({c}, {r})"), + Ctx::Right(Op::IterC, l, c) => write!(f, "iter_c({l}, {c})"), + Ctx::Left(op, c, r) => write!(f, "({c} {} {r})", op.sym()), + Ctx::Right(op, l, c) => write!(f, "({l} {} {c})", op.sym()), + Ctx::Wrap(p, c) => write!(f, "wrap{}({c})", show_path(p)), + Ctx::Unwrap(c, p) => write!(f, "unwrap({c}){}", show_path(p)), + Ctx::Un(u, c) => write!(f, "{}({c})", u.name()), + } + } +} + /// The most of each kind of variable any generated law uses. The case has to /// supply at least this many; `tests/algebraic.rs` checks the bound. pub fn arity() -> (usize, usize, usize) { diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs index 5350d6d7..c4b7a25f 100644 --- a/differential/src/algebraic/routes.rs +++ b/differential/src/algebraic/routes.rs @@ -188,6 +188,14 @@ impl Outcome { let shape = shape_of_map(m); Outcome { values: values_of_shape(&shape), shape: Some(shape) } } + + /// Whether the walk stopped at [`SHAPE_CAP`](super::shape::SHAPE_CAP). + /// The values of a truncated trie are a prefix of its real ones, so they + /// cannot be compared with anything: against the model, which has no cap, + /// every route would seem to lose the same values. + pub fn truncated(&self) -> bool { + self.shape.as_ref().is_some_and(|s| s.last().is_some_and(|(p, _)| &p[..] == TRUNCATED)) + } } /// Evaluate `e` over `operands` by `route`, or `None` if the route does not diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index de425624..179fc36d 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -469,20 +469,22 @@ fn every_law_variable_has_something_to_bind_to() { assert!(bytes <= algebraic::LAW_BYTES, "a law needs {bytes} bytes"); } -/// Every generated law holds in the flat model. +/// Every generated law holds in the flat model, plain and in the substitution +/// and congruence instances `check_laws` derives from it. /// /// The laws are theorems about Zippy's operators, and `model.rs` is those /// operators' membership lemmas read as code, with no trie anywhere. So a /// failure here is never the crate: it is the Lean-to-Rust translation, the -/// variable binding, or the model -- exactly the parts of the harness that, if -/// wrong, would make every law finding a false one. +/// variable binding, the derivation, or the model -- exactly the parts of the +/// harness that, if wrong, would make every law finding a false one. #[test] fn zippy_laws_hold_in_the_model() { - use algebraic::laws::{instantiate, laws, Binding, Hyp}; + use algebraic::laws::{instantiate, laws, substituted, Binding, Hyp, Instance}; use algebraic::routes::{eval, Route}; const CASES: usize = 3_000; let mut rng = algebraic::Rng::for_job(20261031, 0); let mut checked = vec![0usize; laws::<()>().len()]; + let (mut by_subst, mut by_ctx) = (0usize, 0usize); let mut failures = Vec::new(); let _ = with_quiet_panics(|| { for _ in 0..CASES { @@ -490,23 +492,45 @@ fn zippy_laws_hold_in_the_model() { let Ok(case) = std::panic::catch_unwind(|| algebraic::decode::<()>(&bytes)) else { continue; }; - let bind = Binding { paths: &case.law_paths, bytes: &case.law_bytes }; + let plain: Vec = (0..algebraic::OPERANDS).map(Expr::Var).collect(); + let bind = Binding { spaces: &plain, paths: &case.law_paths, bytes: &case.law_bytes }; + let subst = Binding { spaces: &case.law_spaces, ..bind }; let model = |e: &Expr| eval(Route::Model, e, &case.operands).unwrap().values; - 'laws: for (i, law) in laws::<()>().iter().enumerate() { + let holds = |inst: &Instance| { + inst.pre.iter().all(|h| match h { + Hyp::Holds(b) => *b, + Hyp::Mem(p, e, want) => model(e).contains_key(p) == *want, + Hyp::Eq(l, r) => model(l) == model(r), + }) + }; + for (i, law) in laws::<()>().iter().enumerate() { let inst = instantiate(law, &bind); - for h in &inst.pre { - let holds = match h { - Hyp::Holds(b) => *b, - Hyp::Mem(p, e, want) => model(e).contains_key(p) == *want, - Hyp::Eq(l, r) => model(l) == model(r), - }; - if !holds { - continue 'laws; + if holds(&inst) { + checked[i] += 1; + if model(&inst.lhs) != model(&inst.rhs) { + failures.push(format!("{}: {} vs {}", law.name, inst.lhs, inst.rhs)); + } + if !case.law_ctx.is_hole() { + by_ctx += 1; + let (l, r) = (case.law_ctx.plug(inst.lhs), case.law_ctx.plug(inst.rhs)); + if model(&l) != model(&r) { + failures.push(format!("{}+ctx: {l} vs {r}", law.name)); + } } } - checked[i] += 1; - if model(&inst.lhs) != model(&inst.rhs) { - failures.push(format!("{}: {} vs {}", law.name, inst.lhs, inst.rhs)); + if substituted(law, &case.law_spaces) { + let inst = instantiate(law, &subst); + if holds(&inst) { + by_subst += 1; + if model(&inst.lhs) != model(&inst.rhs) { + failures.push(format!("{}+subst: {} vs {}", law.name, inst.lhs, inst.rhs)); + } else if !case.law_ctx.is_hole() { + let (l, r) = (case.law_ctx.plug(inst.lhs), case.law_ctx.plug(inst.rhs)); + if model(&l) != model(&r) { + failures.push(format!("{}+subst+ctx: {l} vs {r}", law.name)); + } + } + } } } } @@ -520,6 +544,11 @@ fn zippy_laws_hold_in_the_model() { .map(|(l, _)| l.name) .collect(); assert!(never.is_empty(), "laws never applicable in {CASES} cases: {never:?}"); + // Both derivations have to actually fire, or a broken decoder that always + // produces the plain law would pass unnoticed. + let plain_total: usize = checked.iter().sum(); + assert!(by_subst * 5 > plain_total, "substitution instances: {by_subst} of {plain_total}"); + assert!(by_ctx * 5 > plain_total, "congruence instances: {by_ctx} of {plain_total}"); } /// Laws are checked for the set type only; see `laws.rs`. From 8c0c72a8de5e457d9f53cfbf087aa49768aceeef Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 17 Nov 2026 19:45:10 +0000 Subject: [PATCH 13/17] lean: prove Zippy's set algebra over a dangling-path-free model Port lean/PrunedModel from spec/zippy-laws-fvc, limited to the import closure of PrunedModel/Zippy.lean (Canon, Map, Zipper, Write, Spec, Lattice, Pointwise, Refine, Zippy) plus Nested.lean, which Lattice.lean refers to. Zippy.lean defines each formal.egg operator as a write-zipper program over Space = PrunedMap Unit and proves every rule. Basic.lean gains the unit value instance and the strict total order on Path that the canonical form needs; both are additions only. ZippyLaws.lean (from spec/zippy-laws) exports Zippy.lean's equational theorems as Rust for the algebraic fuzzer. Left out: the pruned differential fuzzer (PrunedModel/Fuzz.lean, PrunedMain.lean, differential/src/pruned.rs) and Project.lean, which ties the model to PathMapModel. The model follows focus_value_consistency (issue #104), which master's crate does not implement; the docs say so where they describe raw zipper operations. --- lean/PathMapModel/Basic.lean | 89 +++ lean/PathMapModel/Spec.lean | 5 +- lean/PrunedModel.lean | 10 + lean/PrunedModel/Canon.lean | 453 +++++++++++ lean/PrunedModel/Lattice.lean | 496 ++++++++++++ lean/PrunedModel/Map.lean | 309 ++++++++ lean/PrunedModel/Nested.lean | 169 ++++ lean/PrunedModel/Pointwise.lean | 331 ++++++++ lean/PrunedModel/Refine.lean | 872 +++++++++++++++++++++ lean/PrunedModel/Spec.lean | 176 +++++ lean/PrunedModel/Write.lean | 421 ++++++++++ lean/PrunedModel/Zipper.lean | 331 ++++++++ lean/PrunedModel/Zippy.lean | 1278 +++++++++++++++++++++++++++++++ lean/README.md | 25 + lean/ZippyLaws.lean | 314 ++++++++ lean/lakefile.toml | 8 +- 16 files changed, 5282 insertions(+), 5 deletions(-) create mode 100644 lean/PrunedModel.lean create mode 100644 lean/PrunedModel/Canon.lean create mode 100644 lean/PrunedModel/Lattice.lean create mode 100644 lean/PrunedModel/Map.lean create mode 100644 lean/PrunedModel/Nested.lean create mode 100644 lean/PrunedModel/Pointwise.lean create mode 100644 lean/PrunedModel/Refine.lean create mode 100644 lean/PrunedModel/Spec.lean create mode 100644 lean/PrunedModel/Write.lean create mode 100644 lean/PrunedModel/Zipper.lean create mode 100644 lean/PrunedModel/Zippy.lean create mode 100644 lean/ZippyLaws.lean diff --git a/lean/PathMapModel/Basic.lean b/lean/PathMapModel/Basic.lean index ff22667f..0faec241 100644 --- a/lean/PathMapModel/Basic.lean +++ b/lean/PathMapModel/Basic.lean @@ -71,6 +71,22 @@ def u64Ops : ValOps UInt64 where psub a b := if a == b then .none else .elem a beq a b := a == b +/-- The instance `pathmap` provides for `()` (see `impl Lattice for ()` in `src/ring.rs`). + +Both `pjoin` and `pmeet` return `Identity(SELF_IDENT | COUNTER_IDENT)` — with only +one value there is nothing to choose between, so each operand is equally "the +answer", and the node algebra is told so. `psubtract` of two `()`s annihilates, +which `src/ring.rs`'s own `option_subtract_test` asserts. + +This is the instance under which a trie is exactly a *set of paths*, and it is +the one for which the lattice laws hold in full — including commutativity, which +`u64Ops` does not satisfy. See `PrunedModel/Lattice.lean`. -/ +def unitOps : ValOps Unit where + pjoin _ _ := .identity true true + pmeet _ _ := .identity true true + psub _ _ := .none + beq _ _ := true + /-! ## Prefix order -/ /-- `p ≼ q`: `p` is a prefix of `q`. -/ @@ -120,6 +136,79 @@ def Path.le (p q : Path) : Bool := Path.lt p q || p == q instance : LT Path := ⟨fun p q => Path.lt p q = true⟩ instance : LE Path := ⟨fun p q => Path.le p q = true⟩ +/-! ### `Path.lt` is a strict total order + +Needed to show that the canonical form is *unique* — that two sorted, +duplicate-free entry lists holding the same values are the same list — which is +what lets `PrunedModel/Lattice.lean` state the lattice laws as equations rather +than as "equal at every path". Nothing else in the model needs them, which is +why they were not here before. -/ + +/-- `UInt8` order facts, routed through `toNat` so `omega` can see them. -/ +private theorem u8_lt_trans {a b c : UInt8} (h1 : a < b) (h2 : b < c) : a < c := by + rw [UInt8.lt_iff_toNat_lt] at *; omega +private theorem u8_lt_irrefl (a : UInt8) : ¬ (a < a) := by + rw [UInt8.lt_iff_toNat_lt]; omega +private theorem u8_eq_of_not_lt {a b : UInt8} (h1 : ¬ (a < b)) (h2 : ¬ (b < a)) : a = b := by + rw [UInt8.lt_iff_toNat_lt] at h1 h2 + exact UInt8.toNat_inj.mp (by omega) +private theorem u8_lt_of_lt_of_not_gt {a b c : UInt8} (h1 : a < b) (h2 : ¬ (c < b)) : a < c := by + rw [UInt8.lt_iff_toNat_lt] at *; omega + +theorem Path.lt_cons (a b : UInt8) (as bs : Path) : + Path.lt (a :: as) (b :: bs) + = if a < b then true else if b < a then false else Path.lt as bs := rfl + +@[simp] theorem Path.lt_irrefl : ∀ p : Path, Path.lt p p = false + | [] => rfl + | a :: as => by simp [Path.lt_cons, u8_lt_irrefl a, Path.lt_irrefl as] + +theorem Path.lt_trans : ∀ {p q r : Path}, + Path.lt p q = true → Path.lt q r = true → Path.lt p r = true + | [], [], _, h1, _ => by simp [Path.lt] at h1 + | [], _ :: _, [], _, h2 => by simp [Path.lt] at h2 + | [], _ :: _, _ :: _, _, _ => rfl + | _ :: _, [], _, h1, _ => by simp [Path.lt] at h1 + | _ :: _, _ :: _, [], _, h2 => by simp [Path.lt] at h2 + | a :: as, b :: bs, c :: cs, h1, h2 => by + rw [Path.lt_cons] at h1 h2 ⊢ + by_cases hab : a < b + · by_cases hcb : c < b + · -- the hypothesis forces `b < c`, which `c < b` contradicts + simp [hcb] at h2 + exact absurd (u8_lt_trans h2 hcb) (u8_lt_irrefl b) + · simp [u8_lt_of_lt_of_not_gt hab hcb] + · by_cases hba : b < a + · simp [hab, hba] at h1 + · -- a = b, so the comparison is decided one level down + have hab' : a = b := u8_eq_of_not_lt hab hba + subst hab' + simp only [hab] at h1 + by_cases hac : a < c + · simp [hac] + · by_cases hca : c < a + · simp [hca] at h2 + exact absurd (u8_lt_trans h2 hca) (u8_lt_irrefl a) + · simp only [hac, hca] at h2 ⊢ + exact Path.lt_trans h1 h2 + +theorem Path.lt_total : ∀ (p q : Path), Path.lt p q = true ∨ p = q ∨ Path.lt q p = true + | [], [] => Or.inr (Or.inl rfl) + | [], _ :: _ => Or.inl rfl + | _ :: _, [] => Or.inr (Or.inr rfl) + | a :: as, b :: bs => by + rw [Path.lt_cons, Path.lt_cons] + by_cases hab : a < b + · exact Or.inl (by simp [hab]) + · by_cases hba : b < a + · exact Or.inr (Or.inr (by simp [hba])) + · have : a = b := u8_eq_of_not_lt hab hba + subst this + rcases Path.lt_total as bs with h | h | h + · exact Or.inl (by simp [hab, h]) + · exact Or.inr (Or.inl (by simp [h])) + · exact Or.inr (Or.inr (by simp [hab, h])) + /-- Insertion into a `Path.lt`-sorted list, dropping duplicates. -/ def Path.insertSorted (p : Path) : List Path → List Path | [] => [p] diff --git a/lean/PathMapModel/Spec.lean b/lean/PathMapModel/Spec.lean index b3a6d527..882bcb1a 100644 --- a/lean/PathMapModel/Spec.lean +++ b/lean/PathMapModel/Spec.lean @@ -153,10 +153,7 @@ theorem isPrefixOf_append (p q : Path) : p ≼ (p ++ q) := by | nil => simp [isPrefixOf] | cons a as ih => simp [isPrefixOf, ih] -@[simp] theorem lt_irrefl (p : Path) : Path.lt p p = false := by - induction p with - | nil => simp [Path.lt] - | cons a as ih => simp [Path.lt, ih] +-- `Path.lt_irrefl` now lives in Basic.lean, beside `lt_trans` and `lt_total`. end Path diff --git a/lean/PrunedModel.lean b/lean/PrunedModel.lean new file mode 100644 index 00000000..9bfdab62 --- /dev/null +++ b/lean/PrunedModel.lean @@ -0,0 +1,10 @@ +import PrunedModel.Canon +import PrunedModel.Map +import PrunedModel.Zipper +import PrunedModel.Write +import PrunedModel.Spec +import PrunedModel.Lattice +import PrunedModel.Nested +import PrunedModel.Pointwise +import PrunedModel.Refine +import PrunedModel.Zippy diff --git a/lean/PrunedModel/Canon.lean b/lean/PrunedModel/Canon.lean new file mode 100644 index 00000000..8a42e8f3 --- /dev/null +++ b/lean/PrunedModel/Canon.lean @@ -0,0 +1,453 @@ +import PathMapModel.Basic + +/-! +# Canonical association lists + +`PrunedMap` carries its canonical form in its *type*: an entry list sorted +strictly by key, so there is no junk inhabitant to exclude afterwards. This file +is the list-level development that makes that possible — everything needed to +build the proof field and to read it back off, with no mention of `PrunedMap`. + +Two predicates, and the first implies the second: + +* `SortedKeys` — keys strictly increasing in `Path.lt`. This is the invariant. +* `DistinctKeys` — no key bound twice. Implied, because `Path.lt` is + irreflexive; `distinctKeys_of_sortedKeys` is the proof. + +The payoff is `eq_of_sortedKeys_of_lookup`: a sorted list is determined by its +lookup function. That is what makes `PrunedMap` equality *observational*, and +hence what lets `PrunedModel/Lattice.lean` state the lattice laws as equations +with no side conditions at all. + +These proofs were the first and last thirds of `Lattice.lean`, behind a +`Canonical` predicate every law had to carry as a hypothesis. Moving the +invariant into the type removed the hypothesis; the proofs are unchanged. +-/ + +namespace PrunedModel + +open PathMapModel + +variable {V : Type} + +/-! ## Paths and lookup -/ + +/-- Every path is a prefix of itself. -/ +theorem isPrefixOf_self : ∀ p : Path, (p ≼ p) = true + | [] => rfl + | _ :: as => by simp [Path.isPrefixOf, isPrefixOf_self as] + +/-- A key is bound: `lookup` finds whatever `map (·.1)` saw. -/ +theorem lookup_isSome_of_mem_keys {l : List (Path × V)} {p : Path} + (h : p ∈ l.map (·.1)) : (l.lookup p).isSome = true := by + obtain ⟨kv, hmem, heq⟩ := List.mem_map.mp h + exact List.lookup_isSome_iff.mpr ⟨kv, hmem, by simp [heq]⟩ + +/-- …and conversely, `lookup` only succeeds on a key. -/ +theorem mem_keys_of_lookup_isSome {l : List (Path × V)} {p : Path} + (h : (l.lookup p).isSome = true) : p ∈ l.map (·.1) := by + obtain ⟨kv, hmem, hb⟩ := List.lookup_isSome_iff.mp h + exact List.mem_map.mpr ⟨kv, hmem, (eq_of_beq hb).symm⟩ + +/-- An unbound key looks up to `none` — the contrapositive of +`mem_keys_of_lookup_isSome`. -/ +theorem lookup_eq_none_of_not_mem_keys {l : List (Path × V)} {k : Path} + (h : k ∉ l.map (·.1)) : l.lookup k = none := by + cases hl : l.lookup k with + | none => rfl + | some v => + exact absurd (mem_keys_of_lookup_isSome (l := l) (p := k) (by rw [hl]; rfl)) h + +/-! ## Canonicalisation -/ + +/-- Deduplicate an association list, keeping the *first* binding for each key. +Left-biased, matching `pathmap`'s `Identity(SELF_IDENT)` value instances. -/ +def dedupVals (l : List (Path × V)) : List (Path × V) := + l.foldl (fun acc kv => if acc.any (fun x => x.1 == kv.1) then acc else acc ++ [kv]) [] + +/-- Insert into a key-sorted association list (assumes the key is not present). -/ +def insertValSorted (kv : Path × V) : List (Path × V) → List (Path × V) + | [] => [kv] + | kv' :: rest => + if Path.lt kv.1 kv'.1 then kv :: kv' :: rest + else kv' :: insertValSorted kv rest + +/-- Canonicalise a raw association list: keep the first binding per key, sort by key. -/ +def normVals (l : List (Path × V)) : List (Path × V) := + (dedupVals l).foldl (fun acc kv => insertValSorted kv acc) [] + +/-! ## Canonicalisation moves no lookup -/ + +/-- `dedupVals` keeps the first binding for each key, so it moves no lookup. +Stated with an accumulator, which is what lets the `foldl` be inducted on. -/ +private theorem lookup_dedupAux (k : Path) : + ∀ (l acc : List (Path × V)), + (l.foldl (fun acc kv => if acc.any (fun x => x.1 == kv.1) then acc else acc ++ [kv]) acc).lookup k + = (acc.lookup k).or (l.lookup k) + | [], acc => by simp + | (key, val) :: rest, acc => by + rw [List.foldl_cons, lookup_dedupAux k rest] + cases hany : acc.any (fun x => x.1 == key) with + | true => + -- `key` is already bound, so the entry is dropped and `acc` answers for it. + simp only [if_pos, List.lookup_cons] + cases hk : k == key with + | false => simp + | true => + -- `acc.lookup k` is `some`, so it absorbs whatever comes after. + obtain ⟨p, hp, hpk⟩ := List.any_eq_true.mp hany + have hsome : (acc.lookup k).isSome = true := by + refine List.lookup_isSome_iff.mpr ⟨p, hp, ?_⟩ + have h1 : k = key := by simpa using hk + have h2 : p.1 = key := by simpa using hpk + simp [h1, h2] + cases hs : acc.lookup k with + | none => simp [hs] at hsome + | some v => simp + | false => + -- `key` is new, so the entry is appended and `lookup` sees it after `acc`. + simp only [if_neg, Bool.false_eq_true, not_false_eq_true] + cases hk : k == key <;> + simp [List.lookup_append, List.lookup_cons, hk] + +/-- `dedupVals` preserves every lookup. -/ +theorem lookup_dedupVals (l : List (Path × V)) (k : Path) : + (dedupVals l).lookup k = l.lookup k := by + rw [dedupVals] + simpa using lookup_dedupAux k l [] + +/-- Which keys `insertValSorted` leaves behind: the inserted one, and the old ones. -/ +theorem mem_keys_insertValSorted (kv : Path × V) : + ∀ (acc : List (Path × V)) (k : Path), + k ∈ (insertValSorted kv acc).map (·.1) ↔ (k = kv.1 ∨ k ∈ acc.map (·.1)) + | [], k => by simp [insertValSorted] + | kv' :: rest, k => by + rw [insertValSorted] + cases h : Path.lt kv.1 kv'.1 with + | true => simp + | false => + simp only [Bool.false_eq_true, if_false, List.map_cons, List.mem_cons, + mem_keys_insertValSorted kv rest k] + constructor + · intro hm + rcases hm with hm | hm | hm + · exact Or.inr (Or.inl hm) + · exact Or.inl hm + · exact Or.inr (Or.inr hm) + · intro hm + rcases hm with hm | hm | hm + · exact Or.inr (Or.inl hm) + · exact Or.inl hm + · exact Or.inr (Or.inr hm) + +/-- `insertValSorted` is a lookup update, as long as the key is not already +bound. That hypothesis is what rules out shadowing an existing binding, and it +is exactly what `dedupVals` establishes before the sort runs. -/ +theorem lookup_insertValSorted : + ∀ (kv : Path × V) (acc : List (Path × V)) (k : Path), kv.1 ∉ acc.map (·.1) → + (insertValSorted kv acc).lookup k = if k == kv.1 then some kv.2 else acc.lookup k + | (key, val), [], k, _ => by + cases hk : k == key <;> simp [insertValSorted, List.lookup_cons, hk] + | (key, val), (key', val') :: rest, k, hfresh => by + have hne : key ≠ key' := by intro h; exact hfresh (by simp [h]) + have hrest : key ∉ rest.map (·.1) := fun h => hfresh (by simp [h]) + rw [insertValSorted] + cases h : Path.lt key key' with + | true => cases hk : k == key <;> simp [List.lookup_cons, hk] + | false => + simp only [Bool.false_eq_true, if_false, List.lookup_cons, + lookup_insertValSorted (key, val) rest k hrest] + cases hk : k == key with + | false => simp + | true => + -- `k` is the inserted key, and `key'` is a different one, so the + -- existing head is skipped rather than answering for `k`. + have h1 : k = key := by simpa using hk + have : (k == key') = false := by simp [h1, hne] + simp [this] + + +/-- No key bound twice. Spelled recursively rather than as `List.Nodup ∘ map`, +because every proof below inducts on the list and this shape is what the +induction wants. Implied by `SortedKeys`; see `distinctKeys_of_sortedKeys`. -/ +def DistinctKeys : List (Path × V) → Prop + | [] => True + | kv :: rest => kv.1 ∉ rest.map (·.1) ∧ DistinctKeys rest + +/-- Appending a fresh key to a distinct-keyed list keeps it distinct. -/ +theorem distinctKeys_append_singleton : + ∀ (acc : List (Path × V)) (kv : Path × V), + DistinctKeys acc → kv.1 ∉ acc.map (·.1) → DistinctKeys (acc ++ [kv]) + | [], kv, _, _ => ⟨by simp, trivial⟩ + | kv' :: rest, kv, hacc, hfresh => by + refine ⟨?_, distinctKeys_append_singleton rest kv hacc.2 (fun h => hfresh (by simp [h]))⟩ + intro hm + -- the goal arrives with `List.append`, which `map_append` does not match + simp only [List.append_eq, List.map_append, List.mem_append, + List.map_cons, List.map_nil, List.mem_singleton] at hm + rcases hm with hm | hm + · exact hacc.1 hm + · exact hfresh (by simp [show kv'.1 = kv.1 by simpa using hm]) + +private theorem distinctKeys_dedupAux : + ∀ (l acc : List (Path × V)), DistinctKeys acc → + DistinctKeys (l.foldl (fun acc kv => if acc.any (fun x => x.1 == kv.1) then acc else acc ++ [kv]) acc) + | [], acc, h => h + | kv :: rest, acc, h => by + rw [List.foldl_cons] + cases hany : acc.any (fun x => x.1 == kv.1) with + | true => simpa [hany] using distinctKeys_dedupAux rest acc h + | false => + have hfresh : kv.1 ∉ acc.map (·.1) := by + intro hm + obtain ⟨p, hp, hpe⟩ := List.mem_map.mp hm + have : (acc.any (fun x => x.1 == kv.1)) = true := + List.any_eq_true.mpr ⟨p, hp, by simp [hpe]⟩ + rw [hany] at this; exact Bool.noConfusion this + simpa [hany] using + distinctKeys_dedupAux rest _ (distinctKeys_append_singleton acc kv h hfresh) + +/-- `dedupVals` leaves no key bound twice. -/ +theorem distinctKeys_dedupVals (l : List (Path × V)) : DistinctKeys (dedupVals l) := by + rw [dedupVals]; exact distinctKeys_dedupAux l [] trivial + +/-- The insertion sort moves no lookup either, given distinct keys to start from. + +The two hypotheses are what make the *last* insertion win in `insertValSorted` +agree with the *first* binding won by `lookup`: with distinct keys there is only +one of each. -/ +private theorem lookup_sortAux (k : Path) : + ∀ (ds acc : List (Path × V)), DistinctKeys ds → + (∀ x ∈ ds.map (·.1), x ∉ acc.map (·.1)) → + (ds.foldl (fun acc kv => insertValSorted kv acc) acc).lookup k + = (ds.lookup k).or (acc.lookup k) + | [], acc, _, _ => by simp + | kv :: rest, acc, hd, hdisj => by + have hfresh : kv.1 ∉ acc.map (·.1) := hdisj kv.1 (by simp) + have hdisj' : ∀ x ∈ rest.map (·.1), x ∉ (insertValSorted kv acc).map (·.1) := by + intro x hx hmem + rcases (mem_keys_insertValSorted kv acc x).mp hmem with h | h + · exact hd.1 (h ▸ hx) + · exact hdisj x (by simp [hx]) h + rw [List.foldl_cons, lookup_sortAux k rest _ hd.2 hdisj', + lookup_insertValSorted kv acc k hfresh, List.lookup_cons] + cases hk : k == kv.1 with + | true => + have : rest.lookup k = none := + lookup_eq_none_of_not_mem_keys (by + rw [show k = kv.1 by simpa using hk]; exact hd.1) + simp [this] + | false => simp + +/-- **`normVals` preserves every lookup.** Canonicalisation reorders and +deduplicates; it does not change what the list holds anywhere. -/ +theorem lookup_normVals (l : List (Path × V)) (k : Path) : + (normVals l).lookup k = l.lookup k := by + rw [normVals, lookup_sortAux k (dedupVals l) [] (distinctKeys_dedupVals l) (by simp)] + simp [lookup_dedupVals] + +/-! ## List comprehensions keyed by their own elements -/ + +/-- `lookup` into a list comprehension keyed by its own elements. -/ +theorem lookup_filterMap_self (f : Path → Option V) : + ∀ (l : List Path) (k : Path), + ((l.filterMap fun x => (f x).map (Prod.mk x)).lookup k) = if k ∈ l then f k else none + | [], k => by simp + | x :: rest, k => by + rw [List.filterMap_cons] + cases hfx : f x with + | none => + simp only [Option.map_none, List.mem_cons, + lookup_filterMap_self f rest k] + by_cases hkx : k = x + · simp [hkx, hfx] + · simp [hkx] + | some v => + simp only [Option.map_some, List.lookup_cons, List.mem_cons, + lookup_filterMap_self f rest k] + cases hk : k == x with + | true => simp [show k = x by simpa using hk, hfx] + | false => simp [show ¬ (k = x) by simpa using hk] + +/-- `Path.insertSorted` adds the inserted path and keeps the rest. -/ +theorem Path.mem_insertSorted (p : Path) : + ∀ (acc : List Path) (x : Path), x ∈ Path.insertSorted p acc ↔ (x = p ∨ x ∈ acc) + | [], x => by simp [Path.insertSorted] + | q :: qs, x => by + rw [Path.insertSorted] + cases hpq : p == q with + | true => + have hpq' : p = q := by simpa using hpq + simp only [if_pos, List.mem_cons] + constructor + · intro h; exact Or.inr h + · intro h + rcases h with h | h + · exact Or.inl (by rw [h, hpq']) + · exact h + | false => + cases hlt : Path.lt p q with + | true => simp + | false => + simp only [Bool.false_eq_true, if_false, List.mem_cons, + Path.mem_insertSorted p qs x] + constructor + · intro h + rcases h with h | h | h + · exact Or.inr (Or.inl h) + · exact Or.inl h + · exact Or.inr (Or.inr h) + · intro h + rcases h with h | h | h + · exact Or.inr (Or.inl h) + · exact Or.inl h + · exact Or.inr (Or.inr h) + +private theorem Path.mem_sortAux : + ∀ (ps acc : List Path) (x : Path), + x ∈ ps.foldl (fun acc p => Path.insertSorted p acc) acc ↔ (x ∈ ps ∨ x ∈ acc) + | [], acc, x => by simp + | p :: rest, acc, x => by + rw [List.foldl_cons, Path.mem_sortAux rest _ x, Path.mem_insertSorted] + simp only [List.mem_cons] + constructor + · intro h + rcases h with h | h | h + · exact Or.inl (Or.inr h) + · exact Or.inl (Or.inl h) + · exact Or.inr h + · intro h + rcases h with (h | h) | h + · exact Or.inr (Or.inl h) + · exact Or.inl h + · exact Or.inr (Or.inr h) + +/-- Sorting and deduplicating a path list keeps exactly its members. -/ +theorem Path.mem_sortDedup (ps : List Path) (x : Path) : + x ∈ Path.sortDedup ps ↔ x ∈ ps := by + rw [Path.sortDedup] + simpa using Path.mem_sortAux ps [] x + +/-! ## Sortedness, and the uniqueness of the canonical form -/ + +/-- Entry keys strictly increasing. Strictness folds distinctness in, so this +one predicate is the whole canonical-form invariant. -/ +def SortedKeys : List (Path × V) → Prop + | [] => True + | kv :: rest => (∀ x ∈ rest.map (·.1), Path.lt kv.1 x = true) ∧ SortedKeys rest + +/-- A path strictly below every key of a list is not one of them. -/ +theorem notMem_keys_of_all_lt {l : List (Path × V)} {k : Path} + (h : ∀ x ∈ l.map (·.1), Path.lt k x = true) : k ∉ l.map (·.1) := by + intro hm + have := h k hm + rw [Path.lt_irrefl] at this + exact Bool.noConfusion this + +/-- …so it looks up to nothing. -/ +theorem lookup_eq_none_of_all_lt {l : List (Path × V)} {k : Path} + (h : ∀ x ∈ l.map (·.1), Path.lt k x = true) : l.lookup k = none := + lookup_eq_none_of_not_mem_keys (notMem_keys_of_all_lt h) + +/-- A sorted list's head key is below every key after it, and so is anything +below the head key. -/ +theorem all_lt_of_lt_head {kv : Path × V} {rest : List (Path × V)} {k : Path} + (hs : SortedKeys (kv :: rest)) (hlt : Path.lt k kv.1 = true) : + ∀ x ∈ (kv :: rest).map (·.1), Path.lt k x = true := by + intro x hx + simp only [List.map_cons, List.mem_cons] at hx + rcases hx with hx | hx + · exact hx ▸ hlt + · exact Path.lt_trans hlt (hs.1 x hx) + +theorem sortedKeys_insertValSorted : + ∀ (kv : Path × V) (acc : List (Path × V)), SortedKeys acc → kv.1 ∉ acc.map (·.1) → + SortedKeys (insertValSorted kv acc) + | kv, [], _, _ => ⟨by simp, trivial⟩ + | kv, kv' :: rest, hs, hfresh => by + have hne : kv.1 ≠ kv'.1 := fun h => hfresh (by simp [h]) + have hrest : kv.1 ∉ rest.map (·.1) := fun h => hfresh (by simp [h]) + rw [insertValSorted] + cases hlt : Path.lt kv.1 kv'.1 with + | true => + exact ⟨all_lt_of_lt_head hs hlt, hs⟩ + | false => + -- not below `kv'`, and not equal to it, so strictly above it + have hgt : Path.lt kv'.1 kv.1 = true := by + rcases Path.lt_total kv.1 kv'.1 with h | h | h + · rw [h] at hlt; exact Bool.noConfusion hlt + · exact absurd h hne + · exact h + refine ⟨?_, sortedKeys_insertValSorted kv rest hs.2 hrest⟩ + intro x hx + rcases (mem_keys_insertValSorted kv rest x).mp hx with hx | hx + · exact hx ▸ hgt + · exact hs.1 x hx + +private theorem sortedKeys_sortAux : + ∀ (ds acc : List (Path × V)), DistinctKeys ds → SortedKeys acc → + (∀ x ∈ ds.map (·.1), x ∉ acc.map (·.1)) → + SortedKeys (ds.foldl (fun acc kv => insertValSorted kv acc) acc) + | [], acc, _, hs, _ => hs + | kv :: rest, acc, hd, hs, hdisj => by + have hfresh : kv.1 ∉ acc.map (·.1) := hdisj kv.1 (by simp) + have hdisj' : ∀ x ∈ rest.map (·.1), x ∉ (insertValSorted kv acc).map (·.1) := by + intro x hx hmem + rcases (mem_keys_insertValSorted kv acc x).mp hmem with h | h + · exact hd.1 (h ▸ hx) + · exact hdisj x (by simp [hx]) h + rw [List.foldl_cons] + exact sortedKeys_sortAux rest _ hd.2 (sortedKeys_insertValSorted kv acc hs hfresh) hdisj' + +/-- Canonicalisation really does canonicalise. -/ +theorem sortedKeys_normVals (l : List (Path × V)) : SortedKeys (normVals l) := by + rw [normVals] + exact sortedKeys_sortAux (dedupVals l) [] (distinctKeys_dedupVals l) trivial (by simp) + +/-- **The canonical form is unique.** Two sorted entry lists with the same +lookup are the same list. -/ +theorem eq_of_sortedKeys_of_lookup : + ∀ (l₁ l₂ : List (Path × V)), SortedKeys l₁ → SortedKeys l₂ → + (∀ k, l₁.lookup k = l₂.lookup k) → l₁ = l₂ + | [], [], _, _, _ => rfl + | [], (k₂, v₂) :: r₂, _, _, h => by + have := h k₂; simp at this + | (k₁, v₁) :: r₁, [], _, _, h => by + have := h k₁; simp at this + | (k₁, v₁) :: r₁, (k₂, v₂) :: r₂, hs₁, hs₂, h => by + -- Neither head key can be the smaller one, so they are equal. + have hkey : k₁ = k₂ := by + rcases Path.lt_total k₁ k₂ with hlt | heq | hgt + · exact absurd (h k₁) (by + rw [lookup_eq_none_of_all_lt (all_lt_of_lt_head hs₂ hlt)] + simp) + · exact heq + · exact absurd (h k₂) (by + rw [lookup_eq_none_of_all_lt (all_lt_of_lt_head hs₁ hgt)] + simp) + subst hkey + have hval : v₁ = v₂ := by + have := h k₁; simp at this; exact this + subst hval + -- The tails then agree everywhere: at `k₁` both are `none` by strictness. + have htail : r₁ = r₂ := by + refine eq_of_sortedKeys_of_lookup r₁ r₂ hs₁.2 hs₂.2 (fun k => ?_) + by_cases hk : k = k₁ + · subst hk + rw [lookup_eq_none_of_not_mem_keys (notMem_keys_of_all_lt hs₁.1), + lookup_eq_none_of_not_mem_keys (notMem_keys_of_all_lt hs₂.1)] + · have := h k + simp only [List.lookup_cons, show (k == k₁) = false by simp [hk]] at this + exact this + rw [htail] + +/-- **Sorted implies distinct.** `SortedKeys` asks each key to be *strictly* +below every key after it, and `Path.lt` is irreflexive, so no key can appear +twice. One predicate therefore carries the whole canonical-form invariant, which +is why `PrunedMap` needs only the single proof field. -/ +theorem distinctKeys_of_sortedKeys : + ∀ {l : List (Path × V)}, SortedKeys l → DistinctKeys l + | [], _ => trivial + | _ :: _, hs => ⟨notMem_keys_of_all_lt hs.1, distinctKeys_of_sortedKeys hs.2⟩ + +end PrunedModel diff --git a/lean/PrunedModel/Lattice.lean b/lean/PrunedModel/Lattice.lean new file mode 100644 index 00000000..bd5f6a6a --- /dev/null +++ b/lean/PrunedModel/Lattice.lean @@ -0,0 +1,496 @@ +import PrunedModel.Spec + +/-! +# The lattice laws + +`PrunedMap.join` and `PrunedMap.meet` are meant to be union and intersection. +This file proves it, in the only form that means anything: the lattice +identities, derived rather than checked on examples. + +## Why here and not in `PathMapModel` + +The laws are *false* for the other model, and instructively so. +`PathMapModel.meet` keeps a location only when it leads to a surviving value, so +a trie with a dangling path does not survive `meet a a` — idempotence fails on +exactly the states `PrunedModel` cannot represent. A specification that +reproduces the crate's dangling-path behaviour cannot also be a lattice. So +these proofs are not a bonus feature of the pruned model; they are only +available because of what it leaves out. + +## Shape of the development + +1. `valAt` sees through `mk'`: `(mk' l).valAt k = l.lookup k`. Everything rests + on this, because every operation is `mk'` of a list comprehension and every + law is then a pointwise statement about `Option V`. +2. `valAt_join` / `valAt_meet` / `valAt_sub`: each operation is *pointwise* on + `valAt`. This is the step that would be false for a model storing locations + separately from values. +3. `ext`: two maps with the same `valAt` everywhere are equal. This needs + `Path.lt` to be a strict total order, proved here, and it is what lets the + laws be stated as equations rather than as pointwise equivalences. +4. The laws for `PrunedMap V`, from a hypothesis bundle on the value operations + that does *not* include commutativity. +5. `PrunedMap Unit`, where the correspondence is exact — a trie over `()` is a + finite set of paths — and commutativity holds. +-/ + +namespace PrunedModel +namespace PrunedMap + +open PathMapModel + +variable {V : Type} + +/-! ## 1. `valAt` sees through `mk'` -/ + +/-- **`valAt` sees through `mk'`.** Canonicalisation reorders and deduplicates; +it does not change what the map holds anywhere. + +Every operation below is `mk'` of a list comprehension, so this is what turns a +statement about tries into a statement about `Option V`. -/ +theorem valAt_mk' (l : List (Path × V)) (k : Path) : (mk' l).valAt k = l.lookup k := + lookup_normVals l k + +/-! ## 2. Every operation is pointwise on `valAt` + +This is the step that would fail for a model storing locations separately from +values: there, what `meet` does at a path depends on what lies *below* it. -/ + +/-- An unbound path holds nothing. -/ +theorem valAt_eq_none_of_not_mem_keys {a : PrunedMap V} {k : Path} + (h : k ∉ a.keys) : a.valAt k = none := + lookup_eq_none_of_not_mem_keys h + +@[simp] theorem valAt_empty (k : Path) : (empty : PrunedMap V).valAt k = none := rfl + +variable (ops : ValOps V) + +/-- **Join is pointwise.** -/ +theorem valAt_join (a b : PrunedMap V) (k : Path) : + (join ops a b).valAt k = joinVal ops (a.valAt k) (b.valAt k) := by + rw [join, valAt_mk', lookup_filterMap_self] + by_cases hk : k ∈ Path.sortDedup (a.keys ++ b.keys) + · simp [hk] + · -- Outside both key lists both sides hold nothing, and `joinVal none none = none`. + have hab : k ∉ a.keys ++ b.keys := fun h => hk ((Path.mem_sortDedup _ k).mpr h) + have ha : a.valAt k = none := + valAt_eq_none_of_not_mem_keys (fun h => hab (List.mem_append.mpr (Or.inl h))) + have hb : b.valAt k = none := + valAt_eq_none_of_not_mem_keys (fun h => hab (List.mem_append.mpr (Or.inr h))) + simp [hk, ha, hb, joinVal] + +/-- **Meet is pointwise.** It enumerates `a`'s keys only, which is sound because +`meetVal none _ = none`: a path `a` does not hold cannot survive a meet. -/ +theorem valAt_meet (a b : PrunedMap V) (k : Path) : + (meet ops a b).valAt k = meetVal ops (a.valAt k) (b.valAt k) := by + rw [meet, valAt_mk', lookup_filterMap_self] + by_cases hk : k ∈ a.keys + · simp [hk] + · simp [hk, valAt_eq_none_of_not_mem_keys hk, meetVal] + +/-! ## 3. The laws + +The hypotheses are on the *value* operations, lifted to `Option V` — which is +the level `valAt_join` and `valAt_meet` hand back, and the level at which a +value type either is or is not a lattice. Commutativity is deliberately not +among them: `pathmap`'s integer instances are left-biased projections +(`pjoin` returns `Identity(SELF_IDENT)` and ignores the counterpart), so +`join` picks the destination's value on a collision and is *not* commutative. +Everything else holds. -/ + +/-- What a value type must satisfy for tries over it to form a distributive +lattice under `join` and `meet`. No commutativity; see `IsCommVals`. -/ +structure IsLatticeVals {V : Type} (ops : ValOps V) : Prop where + joinAssoc : ∀ x y z : Option V, + joinVal ops (joinVal ops x y) z = joinVal ops x (joinVal ops y z) + meetAssoc : ∀ x y z : Option V, + meetVal ops (meetVal ops x y) z = meetVal ops x (meetVal ops y z) + joinIdem : ∀ x : Option V, joinVal ops x x = x + meetIdem : ∀ x : Option V, meetVal ops x x = x + joinNone : ∀ x : Option V, joinVal ops x none = x + meetNone : ∀ x : Option V, meetVal ops x none = none + absorbMeetJoin : ∀ x y : Option V, meetVal ops x (joinVal ops x y) = x + absorbJoinMeet : ∀ x y : Option V, joinVal ops x (meetVal ops x y) = x + meetDistribJoin : ∀ x y z : Option V, + meetVal ops x (joinVal ops y z) = joinVal ops (meetVal ops x y) (meetVal ops x z) + joinDistribMeet : ∀ x y z : Option V, + joinVal ops x (meetVal ops y z) = meetVal ops (joinVal ops x y) (joinVal ops x z) + +/-- The *mirrored* absorption law: `meet (join a b) a = a`, with the join on the +left of the meet. + +In a commutative lattice this is `absorbMeetJoin` read backwards and needs no +separate assumption. `pathmap`'s join is not commutative, so the two +orientations are genuinely different statements, and only one of them is a +standard lattice axiom. Nothing in §3 needs this one — it is here because +*nesting* does: `PrunedModel/Nested.lean` lifts the lattice structure to tries +whose values are tries, and the one case of `joinDistribMeet` that no longer +collapses is exactly this law. Both of `pathmap`'s instances satisfy it. -/ +structure IsFlipAbsorb {V : Type} (ops : ValOps V) : Prop where + absorbMeetJoinFlip : ∀ x y : Option V, meetVal ops (joinVal ops x y) x = x + +/-- The extra law a *commutative* value type satisfies. `unitOps` does; +`u64Ops` does not. -/ +structure IsCommVals {V : Type} (ops : ValOps V) : Prop where + joinComm : ∀ x y : Option V, joinVal ops x y = joinVal ops y x + meetComm : ∀ x y : Option V, meetVal ops x y = meetVal ops y x + +variable {ops : ValOps V} + +/-- Two tries hold the same thing at every path. The model's observable +equality: `valAt` is the whole interface, and `beqT` — which decides +`AlgebraicStatus::Identity` — agrees with it on canonical maps. -/ +def Agree (a b : PrunedMap V) : Prop := ∀ k, a.valAt k = b.valAt k + +theorem Agree.refl (a : PrunedMap V) : Agree a a := fun _ => rfl +theorem Agree.symm {a b : PrunedMap V} (hab : Agree a b) : Agree b a := fun k => (hab k).symm +theorem Agree.trans {a b c : PrunedMap V} (hab : Agree a b) (hbc : Agree b c) : Agree a c := + fun k => (hab k).trans (hbc k) + +/-! ### Associativity -/ + +theorem join_assoc (h : IsLatticeVals ops) (a b c : PrunedMap V) : + Agree (join ops (join ops a b) c) (join ops a (join ops b c)) := by + intro k; simp only [valAt_join]; exact h.joinAssoc _ _ _ + +theorem meet_assoc (h : IsLatticeVals ops) (a b c : PrunedMap V) : + Agree (meet ops (meet ops a b) c) (meet ops a (meet ops b c)) := by + intro k; simp only [valAt_meet]; exact h.meetAssoc _ _ _ + +/-! ### Idempotence -/ + +theorem join_idem (h : IsLatticeVals ops) (a : PrunedMap V) : Agree (join ops a a) a := by + intro k; rw [valAt_join]; exact h.joinIdem _ + +theorem meet_idem (h : IsLatticeVals ops) (a : PrunedMap V) : Agree (meet ops a a) a := by + intro k; rw [valAt_meet]; exact h.meetIdem _ + +/-! ### `empty` is the identity of `join` and annihilates `meet` -/ + +theorem join_empty (h : IsLatticeVals ops) (a : PrunedMap V) : Agree (join ops a empty) a := by + intro k; rw [valAt_join, valAt_empty]; exact h.joinNone _ + +theorem meet_empty (h : IsLatticeVals ops) (a : PrunedMap V) : + Agree (meet ops a empty) (empty : PrunedMap V) := by + intro k; rw [valAt_meet, valAt_empty]; exact h.meetNone _ + +/-! ### Absorption -/ + +theorem absorb_meet_join (h : IsLatticeVals ops) (a b : PrunedMap V) : Agree (meet ops a (join ops a b)) a := by + intro k; rw [valAt_meet, valAt_join]; exact h.absorbMeetJoin _ _ + +theorem absorb_join_meet (h : IsLatticeVals ops) (a b : PrunedMap V) : Agree (join ops a (meet ops a b)) a := by + intro k; rw [valAt_join, valAt_meet]; exact h.absorbJoinMeet _ _ + +/-- The mirrored absorption, at trie level. -/ +theorem absorb_meet_join_flip (hf : IsFlipAbsorb ops) (a b : PrunedMap V) : + Agree (meet ops (join ops a b) a) a := by + intro k; rw [valAt_meet, valAt_join]; exact hf.absorbMeetJoinFlip _ _ + +/-! ### Distributivity, both ways -/ + +theorem meet_distrib_join (h : IsLatticeVals ops) (a b c : PrunedMap V) : + Agree (meet ops a (join ops b c)) (join ops (meet ops a b) (meet ops a c)) := by + intro k; simp only [valAt_meet, valAt_join]; exact h.meetDistribJoin _ _ _ + +theorem join_distrib_meet (h : IsLatticeVals ops) (a b c : PrunedMap V) : + Agree (join ops a (meet ops b c)) (meet ops (join ops a b) (join ops a c)) := by + intro k; simp only [valAt_join, valAt_meet]; exact h.joinDistribMeet _ _ _ + +/-! ### Commutativity, where the value type allows it -/ + +theorem join_comm (hc : IsCommVals ops) (a b : PrunedMap V) : + Agree (join ops a b) (join ops b a) := by + intro k; simp only [valAt_join]; exact hc.joinComm _ _ + +theorem meet_comm (hc : IsCommVals ops) (a b : PrunedMap V) : + Agree (meet ops a b) (meet ops b a) := by + intro k; simp only [valAt_meet]; exact hc.meetComm _ _ + +/-! ## 4. The two instances the crate actually provides + +`u64Ops` satisfies everything but commutativity; `unitOps` satisfies +everything. -/ + +/-- `pathmap`'s integer instance gives a distributive lattice. -/ +theorem u64_isLattice : IsLatticeVals u64Ops where + joinAssoc x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, u64Ops, ValRes.resolve] + meetAssoc x y z := by + cases x <;> cases y <;> cases z <;> simp [meetVal, u64Ops, ValRes.resolve] + joinIdem x := by cases x <;> simp [joinVal, u64Ops, ValRes.resolve] + meetIdem x := by cases x <;> simp [meetVal, u64Ops, ValRes.resolve] + joinNone x := by cases x <;> simp [joinVal] + meetNone x := by cases x <;> simp [meetVal] + absorbMeetJoin x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, u64Ops, ValRes.resolve] + absorbJoinMeet x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, u64Ops, ValRes.resolve] + meetDistribJoin x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, meetVal, u64Ops, ValRes.resolve] + joinDistribMeet x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, meetVal, u64Ops, ValRes.resolve] + +/-- …but **not** a commutative one, and this is not an artefact of the model. +`impl Lattice for u64` returns `Identity(SELF_IDENT)` from `pjoin`, ignoring the +counterpart entirely, so a collision resolves to whichever side is `self` — +which is the destination for `join_into` and the source for a join evaluated with +the operands swapped. That is also why `FINDINGS.md`'s "value bias by node +layout" class was a bug worth fixing: with a non-commutative join, *which* +operand ends up on the left is observable. -/ +theorem u64_not_isComm : ¬ IsCommVals u64Ops := by + intro hc + have h12 := hc.joinComm (some 1) (some 2) + simp only [joinVal, u64Ops, ValRes.resolve, Option.some.injEq] at h12 + exact absurd h12 (by decide) + +/-- `u64Ops` satisfies the mirrored absorption too, even though it is not +commutative: a left-biased `pjoin` makes `join x y` agree with `x` wherever `x` +has a value, which is exactly where the meet then looks. -/ +theorem u64_isFlipAbsorb : IsFlipAbsorb u64Ops where + absorbMeetJoinFlip x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, u64Ops, ValRes.resolve] + +/-- `pathmap`'s `()` instance gives a distributive lattice… -/ +theorem unit_isLattice : IsLatticeVals unitOps where + joinAssoc x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, unitOps, ValRes.resolve] + meetAssoc x y z := by + cases x <;> cases y <;> cases z <;> simp [meetVal, unitOps, ValRes.resolve] + joinIdem x := by cases x <;> simp [joinVal, unitOps, ValRes.resolve] + meetIdem x := by cases x <;> simp [meetVal, unitOps, ValRes.resolve] + joinNone x := by cases x <;> simp [joinVal] + meetNone x := by cases x <;> simp [meetVal] + absorbMeetJoin x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, unitOps, ValRes.resolve] + absorbJoinMeet x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, unitOps, ValRes.resolve] + meetDistribJoin x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, meetVal, unitOps, ValRes.resolve] + joinDistribMeet x y z := by + cases x <;> cases y <;> cases z <;> simp [joinVal, meetVal, unitOps, ValRes.resolve] + +theorem unit_isFlipAbsorb : IsFlipAbsorb unitOps where + absorbMeetJoinFlip x y := by + cases x <;> cases y <;> simp [joinVal, meetVal, unitOps, ValRes.resolve] + +/-- …and a **commutative** one. There is only one value, so there is nothing for +a biased projection to be biased about. -/ +theorem unit_isComm : IsCommVals unitOps where + joinComm x y := by cases x <;> cases y <;> simp [joinVal, unitOps, ValRes.resolve] + meetComm x y := by cases x <;> cases y <;> simp [meetVal, unitOps, ValRes.resolve] + +/-! ## 5. Over `()` the correspondence is exact + +A `PrunedMap Unit` does not merely *satisfy* the set laws — it **is** a finite +set of paths. `Option Unit` has two inhabitants, so `valAt` carries exactly one +bit per path, and `join` and `meet` are that bit's `||` and `&&`. -/ + +/-- A trie over `()` holds no information beyond *which* paths are in it. -/ +theorem unit_valAt_determined (a : PrunedMap Unit) (k : Path) : + a.valAt k = if (a.valAt k).isSome then some () else none := by + cases hv : a.valAt k with + | none => simp + | some u => cases u; simp + +/-- `join` is union of those path sets. -/ +theorem unit_join_isSome (a b : PrunedMap Unit) (k : Path) : + ((join unitOps a b).valAt k).isSome = ((a.valAt k).isSome || (b.valAt k).isSome) := by + rw [valAt_join] + cases a.valAt k <;> cases b.valAt k <;> simp [joinVal, unitOps, ValRes.resolve] + +/-- `meet` is intersection of those path sets. -/ +theorem unit_meet_isSome (a b : PrunedMap Unit) (k : Path) : + ((meet unitOps a b).valAt k).isSome = ((a.valAt k).isSome && (b.valAt k).isSome) := by + rw [valAt_meet] + cases a.valAt k <;> cases b.valAt k <;> simp [meetVal, unitOps, ValRes.resolve] + +/-- `empty` is the empty set. -/ +theorem unit_empty_isSome (k : Path) : + ((empty : PrunedMap Unit).valAt k).isSome = false := by simp + +/-! Every law of §3 therefore holds for `PrunedMap Unit` with no side condition, +commutativity included: `unit_isLattice` and `unit_isComm` discharge the +hypotheses. Concretely, for `a b c : PrunedMap Unit`: + +* `join_assoc unit_isLattice a b c`, `meet_assoc unit_isLattice a b c` +* `join_comm unit_isComm a b`, `meet_comm unit_isComm a b` +* `join_idem unit_isLattice a`, `meet_idem unit_isLattice a` +* `join_empty unit_isLattice a`, `meet_empty unit_isLattice a` +* `absorb_meet_join unit_isLattice a b`, `absorb_join_meet unit_isLattice a b` +* `meet_distrib_join unit_isLattice a b c`, `join_distrib_meet unit_isLattice a b c` + +and the same list for `PrunedMap UInt64` through `u64_isLattice`, minus the two +commutativity laws, which `u64_not_isComm` rules out. + +What is *not* claimed is a Boolean algebra proper: `Path` is infinite, so there +is no top element and hence no complement. What this is, is the lattice of +finite sets of paths — a distributive lattice with a least element. The +relative complement that would make it a *generalized* Boolean algebra is +`PrunedMap.sub`, whose pointwise characterisation needs the canonicity +hypothesis that §1's `DistinctKeys` supplies; it is not proved here. -/ + +/-! ## 6. From "equal at every path" to equal + +`Agree` is the honest observational statement, and here it simply *is* equality. +`PrunedMap` carries sortedness in its type, so a trie is the unique sorted +enumeration of its own contents (`eq_of_sortedKeys_of_lookup`) and the proof +fields are `Prop`s, equal automatically. `PrunedMap.ext` does the work. + +This section used to be a hundred lines and a `Canonical` predicate every law in +§7 carried as a hypothesis. -/ + +/-- **Agreement is equality.** No side condition: there is no non-canonical trie +for one to exclude. -/ +theorem eq_of_agree {a b : PrunedMap V} (hab : Agree a b) : a = b := PrunedMap.ext hab + +/-! ## 7. The laws, as equations + +The same ten laws as §3, now as `=`, and **with no side conditions at all**. + +They used to need `Canonical a` wherever the right-hand side was the bare `a` — +idempotence, the `empty` identity, both absorptions — because the old +representation admitted an entry list binding a key twice, and such a trie is +genuinely not equal to its own join. Carrying sortedness in the type removed the +inhabitant, and with it the hypothesis. -/ + +theorem join_assoc_eq (h : IsLatticeVals ops) (a b c : PrunedMap V) : + join ops (join ops a b) c = join ops a (join ops b c) := + eq_of_agree (join_assoc h a b c) + +theorem meet_assoc_eq (h : IsLatticeVals ops) (a b c : PrunedMap V) : + meet ops (meet ops a b) c = meet ops a (meet ops b c) := + eq_of_agree (meet_assoc h a b c) + +theorem join_idem_eq (h : IsLatticeVals ops) (a : PrunedMap V) : + join ops a a = a := + eq_of_agree (join_idem h a) + +theorem meet_idem_eq (h : IsLatticeVals ops) (a : PrunedMap V) : + meet ops a a = a := + eq_of_agree (meet_idem h a) + +theorem join_empty_eq (h : IsLatticeVals ops) (a : PrunedMap V) : + join ops a empty = a := + eq_of_agree (join_empty h a) + +theorem meet_empty_eq (h : IsLatticeVals ops) (a : PrunedMap V) : + meet ops a empty = (empty : PrunedMap V) := + eq_of_agree (meet_empty h a) + +theorem absorb_meet_join_eq (h : IsLatticeVals ops) (a : PrunedMap V) (b : PrunedMap V) : meet ops a (join ops a b) = a := + eq_of_agree (absorb_meet_join h a b) + +theorem absorb_join_meet_eq (h : IsLatticeVals ops) (a : PrunedMap V) (b : PrunedMap V) : join ops a (meet ops a b) = a := + eq_of_agree (absorb_join_meet h a b) + +theorem absorb_meet_join_flip_eq (hf : IsFlipAbsorb ops) (a : PrunedMap V) (b : PrunedMap V) : meet ops (join ops a b) a = a := + eq_of_agree (absorb_meet_join_flip hf a b) + +theorem meet_distrib_join_eq (h : IsLatticeVals ops) (a b c : PrunedMap V) : + meet ops a (join ops b c) = join ops (meet ops a b) (meet ops a c) := + eq_of_agree (meet_distrib_join h a b c) + +theorem join_distrib_meet_eq (h : IsLatticeVals ops) (a b c : PrunedMap V) : + join ops a (meet ops b c) = meet ops (join ops a b) (join ops a c) := + eq_of_agree (join_distrib_meet h a b c) + +theorem join_comm_eq (hc : IsCommVals ops) (a b : PrunedMap V) : + join ops a b = join ops b a := + eq_of_agree (join_comm hc a b) + +theorem meet_comm_eq (hc : IsCommVals ops) (a b : PrunedMap V) : + meet ops a b = meet ops b a := + eq_of_agree (meet_comm hc a b) + +/-! ### Both instances, named + +Everything above is stated for an abstract `ops` under a hypothesis, so this is +where the two value types the crate provides get their own theorems — citable +rather than merely checked. `PrunedMap Unit` gets all twelve laws; +`PrunedMap UInt64` gets ten, and the two it does not get are *proved* unavailable +below. -/ + +section Instances +variable (a b c : PrunedMap Unit) (x y z : PrunedMap UInt64) + +theorem unit_join_assoc : join unitOps (join unitOps a b) c = join unitOps a (join unitOps b c) := + join_assoc_eq unit_isLattice a b c +theorem unit_meet_assoc : meet unitOps (meet unitOps a b) c = meet unitOps a (meet unitOps b c) := + meet_assoc_eq unit_isLattice a b c +theorem unit_join_comm : join unitOps a b = join unitOps b a := join_comm_eq unit_isComm a b +theorem unit_meet_comm : meet unitOps a b = meet unitOps b a := meet_comm_eq unit_isComm a b +theorem unit_join_idem : join unitOps a a = a := join_idem_eq unit_isLattice a +theorem unit_meet_idem : meet unitOps a a = a := meet_idem_eq unit_isLattice a +theorem unit_join_empty : join unitOps a empty = a := + join_empty_eq unit_isLattice a +theorem unit_meet_empty : meet unitOps a empty = empty := meet_empty_eq unit_isLattice a +theorem unit_absorb_meet_join : meet unitOps a (join unitOps a b) = a := + absorb_meet_join_eq unit_isLattice a b +theorem unit_absorb_join_meet : join unitOps a (meet unitOps a b) = a := + absorb_join_meet_eq unit_isLattice a b +theorem unit_meet_distrib_join : + meet unitOps a (join unitOps b c) = join unitOps (meet unitOps a b) (meet unitOps a c) := + meet_distrib_join_eq unit_isLattice a b c +theorem unit_join_distrib_meet : + join unitOps a (meet unitOps b c) = meet unitOps (join unitOps a b) (join unitOps a c) := + join_distrib_meet_eq unit_isLattice a b c + +theorem u64_join_assoc : join u64Ops (join u64Ops x y) z = join u64Ops x (join u64Ops y z) := + join_assoc_eq u64_isLattice x y z +theorem u64_meet_assoc : meet u64Ops (meet u64Ops x y) z = meet u64Ops x (meet u64Ops y z) := + meet_assoc_eq u64_isLattice x y z +theorem u64_join_idem : join u64Ops x x = x := join_idem_eq u64_isLattice x +theorem u64_meet_idem : meet u64Ops x x = x := meet_idem_eq u64_isLattice x +theorem u64_join_empty : join u64Ops x empty = x := + join_empty_eq u64_isLattice x +theorem u64_meet_empty : meet u64Ops x empty = empty := meet_empty_eq u64_isLattice x +theorem u64_absorb_meet_join : meet u64Ops x (join u64Ops x y) = x := + absorb_meet_join_eq u64_isLattice x y +theorem u64_absorb_join_meet : join u64Ops x (meet u64Ops x y) = x := + absorb_join_meet_eq u64_isLattice x y +theorem u64_meet_distrib_join : + meet u64Ops x (join u64Ops y z) = join u64Ops (meet u64Ops x y) (meet u64Ops x z) := + meet_distrib_join_eq u64_isLattice x y z +theorem u64_join_distrib_meet : + join u64Ops x (meet u64Ops y z) = meet u64Ops (join u64Ops x y) (join u64Ops x z) := + join_distrib_meet_eq u64_isLattice x y z +end Instances + +/-! ### Commutativity fails over `UInt64`, at the trie level + +`u64_not_isComm` rules out the *value* hypothesis, which is not quite the same +claim: a priori the asymmetry could have been invisible once lifted to tries. It +is not. Two single-path tries disagreeing only in their value are a +counterexample, so `join` and `meet` over `UInt64` are genuinely +non-commutative operations and the missing pair of laws is missing for a reason. -/ + +private def one : PrunedMap UInt64 := mk' [([0], 1)] +private def two : PrunedMap UInt64 := mk' [([0], 2)] + +theorem u64_join_not_comm : ¬ ∀ a b : PrunedMap UInt64, join u64Ops a b = join u64Ops b a := by + intro h + have hv := congrArg (fun m => m.valAt [0]) (h one two) + simp only [one, two, valAt_join, valAt_mk'] at hv + simp [joinVal, u64Ops, ValRes.resolve] at hv + +theorem u64_meet_not_comm : ¬ ∀ a b : PrunedMap UInt64, meet u64Ops a b = meet u64Ops b a := by + intro h + have hv := congrArg (fun m => m.valAt [0]) (h one two) + simp only [one, two, valAt_meet, valAt_mk'] at hv + simp [meetVal, u64Ops, ValRes.resolve] at hv + +-- The same counterexample, run rather than reasoned about: `beqT` is the +-- equality the model uses to decide `AlgebraicStatus::Identity`, and it says the +-- two orders give different tries. +#guard !(beqT u64Ops (join u64Ops one two) (join u64Ops two one)) +#guard !(beqT u64Ops (meet u64Ops one two) (meet u64Ops two one)) +#guard (join u64Ops one two).entries == [([0], (1 : UInt64))] +#guard (join u64Ops two one).entries == [([0], (2 : UInt64))] +-- …and that it is the *values* that differ, not the paths: over `()` the same +-- two tries are the same trie. +#guard beqT unitOps (join unitOps (mk' [([0], ())]) (mk' [([0], ())])) + (join unitOps (mk' [([0], ())]) (mk' [([0], ())])) + +end PrunedMap +end PrunedModel diff --git a/lean/PrunedModel/Map.lean b/lean/PrunedModel/Map.lean new file mode 100644 index 00000000..d5257c53 --- /dev/null +++ b/lean/PrunedModel/Map.lean @@ -0,0 +1,309 @@ +import PrunedModel.Canon + +/-! +# A trie with no dangling paths + +## Why a second model + +`PathMapModel` models a `pathmap` trie as `List (Path × Option V)`: every +location that exists, carrying its value *if it has one*. That `Option` is +there because `pathmap` locations really do come in three states — absent, +present-without-a-value (a **dangling path**), and valued — and `create_path`, +`remove_val(false)` and a long list of operation-specific leaks all produce the +middle one. + +Modelling the middle state is necessary to specify those operations, but it is +also where nearly all of the specification's difficulty lives. Half of +`FINDINGS.md` is about it, `subtract` needs a special rule for "where the source +has no node at all, keep `self`'s subtree verbatim, dangling paths included", +and every algebraic operation has to say which valueless locations survive it. + +This model takes the other branch. It covers **only the subset of the API that +cannot produce a dangling path**, and in exchange it has no `Option`: + + entries : List (Path × V) + +A location exists iff some key has it as a prefix. Existence is *derived*, not +stored, so a dangling path is not merely absent from the model — it is +unrepresentable. There is no third state to specify, no prune flag to thread, +and `subtract` is pointwise. + +The claim this model makes is therefore stronger than the other one's. Where +`PathMapModel` says "here is what the crate does with dangling paths", +`PrunedModel` says "these operations never create one", and a trace divergence +is either a wrong value or a dangling path that should not be there. The +fuzzer that checks this claim against the crate (`PrunedModel/Fuzz.lean`, +`differential/src/pruned.rs`) lives on branch `spec/zippy-laws-fvc` and is not +carried here; "the fuzzer" in these files means that one. On this branch the +model is what `PrunedModel/Zippy.lean` proves Zippy's set algebra about. + +## What is shared + +`PathMapModel.Basic` — `Path` and its prefix and lexicographic orders, +`ByteMask`, `ValOps`/`ValRes`, `AlgStatus` — is vocabulary rather than model, so +it is imported rather than duplicated. Everything below is independent of +`PathMapModel`. + +## Canonical form + +`entries` is sorted by `Path.lt` with no duplicate keys, so structural equality +*is* observational equality — which is what lets the model decide +`AlgebraicStatus::Identity` against `Element`. Every constructor goes through +`mk'`, which restores that form. +-/ + +namespace PrunedModel + +open PathMapModel + +/-- A `pathmap` trie with no dangling paths: a finite path→value map. + +Two things are *derived* rather than stored, and that is the whole design. + +The set of locations that exist is the prefix closure of the keys, plus the root; +`paths` computes it. So a dangling path is not merely absent from the model, it +is unrepresentable — which is what this model is for. + +Canonical form is carried in the type rather than asserted in a docstring. +`sorted` says the keys strictly increase in `Path.lt`, which by +`distinctKeys_of_sortedKeys` also rules out a key bound twice. Two consequences: +there is no junk inhabitant, so `PrunedMap` *is* the finite path→value map rather +than a representation of one; and structural equality is observational equality +(`eq_of_sortedKeys_of_lookup`), which is what lets the lattice laws in +`Lattice.lean` be equations with no side conditions. The field used to be a bare +list with a `Canonical` predicate the laws carried as a hypothesis. -/ +structure PrunedMap (V : Type) where + /-- Every location that carries a value, with it, in depth-first order. -/ + entries : List (Path × V) + /-- Keys strictly increasing: the canonical-form invariant. -/ + sorted : SortedKeys entries + +namespace PrunedMap + +variable {V : Type} + +/-! ## Construction + +`normVals` and its lemmas live in `PrunedModel/Canon.lean`; the only thing to do +here is carry the proof it supplies. -/ + +/-- Build a map from a raw, possibly unsorted, possibly duplicate-keyed +association list. + +This is the *only* constructor, and it takes no path argument: there is nothing +to say about which locations exist, because the keys already say it. The proof +field comes from `sortedKeys_normVals` — canonicalisation is what establishes the +invariant, so every map in the model is canonical by construction. -/ +def mk' (vals : List (Path × V)) : PrunedMap V := ⟨normVals vals, sortedKeys_normVals vals⟩ + +/-- The empty trie. Its root still exists — `PathMap::new().read_zipper()` +reports `path_exists() == true` — but nothing else does. -/ +def empty : PrunedMap V := ⟨[], trivial⟩ + +/-- **Equality is observational.** Two tries holding the same value at every path +are the same trie: the entry lists are sorted, so each is the unique sorted +enumeration of its own contents, and the `sorted` fields are proofs of a `Prop` +and so equal automatically. + +This is why `Lattice.lean` can state the lattice laws as `=`. -/ +theorem ext {a b : PrunedMap V} (h : ∀ k, a.entries.lookup k = b.entries.lookup k) : a = b := by + cases a; cases b + cases eq_of_sortedKeys_of_lookup _ _ ‹SortedKeys _› ‹SortedKeys _› h + rfl + +/-- Printed as its entry list: the `sorted` field is a `Prop` and carries no +information, so `deriving Repr` cannot be used and there is nothing to lose. -/ +instance [Repr V] : Repr (PrunedMap V) where + reprPrec t n := reprPrec t.entries n + +instance : Inhabited (PrunedMap V) := ⟨empty⟩ + +/-! ## Observations + +These functions are the entire observable interface of a trie; every +specification in this model is phrased in terms of them. -/ + +/-- The valued locations, in depth-first order. -/ +def keys (t : PrunedMap V) : List Path := t.entries.map (·.1) + +/-- Every location that carries a value, with it. (`entries` under its +`PathMapModel` name, kept so the two models read alike.) -/ +def vals (t : PrunedMap V) : List (Path × V) := t.entries + +/-- `Zipper::val` / `PathMap::get_val_at`: the value at `p`, if any. -/ +def valAt (t : PrunedMap V) (p : Path) : Option V := t.entries.lookup p + +/-- `Zipper::path_exists`. + +A location exists iff it is the root or some key has it as a prefix. This is +the whole content of the model's claim: there is no way to exist *without* +leading to a value. -/ +def pathExists (t : PrunedMap V) (p : Path) : Bool := + p.isEmpty || t.keys.any (fun k => p ≼ k) + +/-- Every location that exists, in depth-first order: the prefix closure of the +keys, with the root. -/ +def paths (t : PrunedMap V) : List Path := + Path.sortDedup (([] : Path) :: t.keys.flatMap Path.prefixes) + +/-- `Zipper::child_mask`: the bytes `b` for which `p ++ [b]` exists. + +Read straight off the keys — a child exists iff some key goes through it — which +is the simplification the missing `Option` buys. -/ +def childMask (t : PrunedMap V) (p : Path) : ByteMask := + ByteMask.ofList <| t.keys.filterMap fun k => + match Path.stripPrefix p k with + | some (b :: _) => some b + | _ => none + +/-- `Zipper::child_count`. -/ +def childCount (t : PrunedMap V) (p : Path) : Nat := (t.childMask p).length + +/-- `ZipperMoving::val_count`: values at and below `p`. -/ +def valCount (t : PrunedMap V) (p : Path) : Nat := + (t.entries.filter (fun kv => p ≼ kv.1)).length + +/-- `TrieNode::node_is_empty` applied to the node *below* `p`: no descendants. -/ +def belowIsEmpty (t : PrunedMap V) (p : Path) : Bool := + t.keys.all (fun k => !(p ≼ k) || k == p) + +/-- `PathMap::is_empty`. With no dangling paths this is just "no values". -/ +def isEmptyMap (t : PrunedMap V) : Bool := t.entries.isEmpty + +/-! ## Sub-tries and grafting -/ + +/-- The subtrie rooted at `p`, **including** the value at `p` as its root value: +`make_map` / `take_map` under the default `graft_root_vals` feature, and what a +zipper rooted at `p` sees. -/ +def subtrie (t : PrunedMap V) (p : Path) : PrunedMap V := + mk' (t.entries.filterMap fun kv => (Path.stripPrefix p kv.1).map (·, kv.2)) + +/-- Remove everything at and below `p`. -/ +def removeAt (t : PrunedMap V) (p : Path) : PrunedMap V := + mk' (t.entries.filter (fun kv => !(p ≼ kv.1))) + +/-- Remove everything strictly below `p`; the value at `p` survives. -/ +def removeBelow (t : PrunedMap V) (p : Path) : PrunedMap V := + mk' (t.entries.filter (fun kv => !(p ≼ kv.1) || kv.1 == p)) + +/-- Replace everything strictly below `p` with the strictly-below part of `s`. + +The value at `p` is not touched: `graft_internal` only ever replaces a node, and +the value at a location lives in its parent's cell. Grafting an empty node here +*removes* the location, where `PathMapModel.graftBelow` leaves it dangling — +that difference is the model's main claim about `graft`, and `Fuzz.lean` says +what the crate does with it. -/ +def graftBelow (t : PrunedMap V) (p : Path) (s : PrunedMap V) : PrunedMap V := + mk' ((t.removeBelow p).entries ++ s.entries.filterMap + (fun kv => if kv.1.isEmpty then none else some (p ++ kv.1, kv.2))) + +/-! ## Point updates -/ + +/-- `ZipperWriting::set_val` / `PathMap::set_val_at`. Returns the replaced value. -/ +def setVal (t : PrunedMap V) (p : Path) (v : V) : Option V × PrunedMap V := + (t.valAt p, mk' ((p, v) :: t.entries.filter (fun kv => !(kv.1 == p)))) + +/-- `ZipperWriting::remove_val`. + +In this model removal is *inherently* pruning: the chain that led to the value +stops existing the moment the value does, because existence is derived from the +keys. There is no prune flag, and the crate's `remove_val(true)` is what this +specifies. -/ +def removeVal (t : PrunedMap V) (p : Path) : Option V × PrunedMap V := + (t.valAt p, mk' (t.entries.filter (fun kv => !(kv.1 == p)))) + +/-! ## Pruning + +`prune_path` deletes the dangling chain ending at the focus. Here there is +never one: see `Spec.no_dangling_tip`. The operation is kept in the model and in +the fuzzer's table precisely so that the crate's `0` can be checked against it — +a non-zero prune on a trie built only from this subset means something in the +subset leaked a dangling path. -/ + +/-- `ZipperWriting::prune_path`: always a no-op, always `0` bytes. -/ +def prunePath (t : PrunedMap V) (_p : Path) : Nat × PrunedMap V := (0, t) + +/-! ## Algebraic operations + +Pointwise, all of them. `PathMapModel` needs a rule per operation for which +valueless locations survive — and `subtract` needs two, because `psubtract_dyn` +short-circuits on an absent child and keeps `self`'s dangling paths there. With +no dangling paths to keep, "keep `self`'s subtree verbatim where the source has +no node" and "subtract pointwise" coincide, so the rules collapse. -/ + +variable (ops : ValOps V) + +/-- `Option::pjoin` from `src/ring.rs`. -/ +def joinVal : Option V → Option V → Option V + | none, b => b + | some a, none => some a + | some a, some b => (ops.pjoin a b).resolve a b + +/-- `Option::pmeet`: a value survives only where *both* sides have one. -/ +def meetVal : Option V → Option V → Option V + | some a, some b => (ops.pmeet a b).resolve a b + | _, _ => none + +/-- `Option::psubtract`. -/ +def subVal : Option V → Option V → Option V + | none, _ => none + | some a, none => some a + | some a, some b => (ops.psub a b).resolve a b + +/-- Join (union). -/ +def join (a b : PrunedMap V) : PrunedMap V := + mk' <| (Path.sortDedup (a.keys ++ b.keys)).filterMap fun k => + (joinVal ops (a.valAt k) (b.valAt k)).map (k, ·) + +/-- Meet (intersection). -/ +def meet (a b : PrunedMap V) : PrunedMap V := + mk' <| a.keys.filterMap fun k => (meetVal ops (a.valAt k) (b.valAt k)).map (k, ·) + +/-- Subtract. -/ +def sub (a b : PrunedMap V) : PrunedMap V := + mk' <| a.entries.filterMap fun kv => + (subVal ops (some kv.2) (b.valAt kv.1)).map (kv.1, ·) + +/-- Is `q` *validated* by `b` — does some non-empty prefix of `q` carry a value +in `b`? + +The node-level reading of `prestrict`: a node has no root value, so the empty +prefix never validates. -/ +def validatedBy (b : PrunedMap V) (q : Path) : Bool := + (List.range q.length).any fun i => (b.valAt (q.take (i + 1))).isSome + +/-- `prestrict` at node level: keep the values of `a` validated by `b`. Once a +location is validated, everything below it is kept. -/ +def restrictBelowRoot (a b : PrunedMap V) : PrunedMap V := + mk' (a.entries.filter (fun kv => validatedBy b kv.1)) + +/-- Structural — hence observational — equality. Decides +`AlgebraicStatus::Identity`, which `pathmap` reports exactly when the output +equals `self`. -/ +def beqT (ops : ValOps V) (a b : PrunedMap V) : Bool := + a.entries.length == b.entries.length && + (a.entries.zip b.entries).all fun xy => xy.1.1 == xy.2.1 && ops.beq xy.1.2 xy.2.2 + +/-! ## Path surgery -/ + +/-- `ZipperWriting::insert_prefix` at map level: put `k` in front of every path, +the root's included. -/ +def prepend (t : PrunedMap V) (k : Path) : PrunedMap V := + mk' (t.entries.map fun kv => (k ++ kv.1, kv.2)) + +/-- The existing locations exactly `k` bytes below the root, depth-first. + +Locations, not keys: `descend_first_k_path` stops at any location at that depth, +whether or not it carries a value. -/ +def kPaths (t : PrunedMap V) (k : Nat) : List Path := + t.paths.filter (fun q => q.length == k) + +/-- `drop_head` / `join_k_path_into`: strip the first `k` bytes from every path +and join the resulting subtries, root values included — so a value at depth +exactly `k` becomes a root value, and values above depth `k` are dropped. -/ +def dropHead (t : PrunedMap V) (k : Nat) : PrunedMap V := + if k == 0 then t + else (t.kPaths k).foldl (fun acc q => join ops acc (t.subtrie q)) empty + +end PrunedMap +end PrunedModel diff --git a/lean/PrunedModel/Nested.lean b/lean/PrunedModel/Nested.lean new file mode 100644 index 00000000..2a88b64f --- /dev/null +++ b/lean/PrunedModel/Nested.lean @@ -0,0 +1,169 @@ +import PrunedModel.Lattice + +/-! +# A trie can be a value + +`IsLatticeVals` is a condition on a *value* type, and `PrunedMap V` has `join`, +`meet` and `sub` of its own — so can a trie be the value type of another trie? +Does the lattice structure compose? + +It does, and the shortness of this file is the point. When the entry list was a +bare `List (Path × V)` the answer was *no*: the type admitted +`⟨[([0], 1), ([0], 2)]⟩`, a list binding one key twice, and `join` of it with +itself kept only the first binding, so `join a a = a` was false for it. Five of +the ten laws failed, and they were exactly the five whose right-hand side is an +operand rather than another operation's output — the ones that needed a +`Canonical` hypothesis. Nesting then required a subtype of canonical tries, with +the lattice structure lifted through it by hand. + +Carrying sortedness in `PrunedMap`'s type removed the inhabitant. There is now +nothing to exclude: the expression above does not typecheck, because +`SortedKeys [([0], 1), ([0], 2)]` is false. So `PrunedMap V` is itself a lattice +value type, the subtype is gone, and this file is the ten-line lift. + +One law still needs more than the `Lattice.lean` §3 bundle, and that has nothing +to do with canonicity. `joinDistribMeet` has a single case reducing to +`meet (join a b) a = a` — absorption with the join on the *left*. A commutative +lattice gets it from the standard axiom read backwards; `pathmap`'s join is not +commutative, so the two orientations are different statements and only one is an +axiom. It is `IsFlipAbsorb`, and both instances satisfy it. +-/ + +namespace PrunedModel + +open PathMapModel PrunedMap + +variable {V : Type} {ops : ValOps V} + +/-! ## Tries as a value type -/ + +/-- `PrunedMap V` as a `ValOps`: `pjoin` is `join`, and so on. Each reports +`Element`, the result being a new trie rather than one of the operands. -/ +def trieOps (ops : ValOps V) : ValOps (PrunedMap V) where + pjoin a b := .elem (join ops a b) + pmeet a b := .elem (meet ops a b) + psub a b := .elem (sub ops a b) + beq a b := beqT ops a b + +@[simp] theorem joinVal_trieOps (a b : PrunedMap V) : + joinVal (trieOps ops) (some a) (some b) = some (join ops a b) := rfl + +@[simp] theorem meetVal_trieOps (a b : PrunedMap V) : + meetVal (trieOps ops) (some a) (some b) = some (meet ops a b) := rfl + +/-- **Tries are a lattice value type.** All ten laws, no side conditions: every +case is either a `rfl` on `Option` or a §7 equation applied directly. -/ +theorem trieOps_isLattice (h : IsLatticeVals ops) (hf : IsFlipAbsorb ops) : + IsLatticeVals (trieOps ops) where + joinAssoc x y z := by + match x, y, z with + | none, _, _ => rfl + | some _, none, _ => rfl + | some _, some _, none => rfl + | some a, some b, some c => exact congrArg some (join_assoc_eq h a b c) + meetAssoc x y z := by + match x, y, z with + | none, _, _ => rfl + | some _, none, _ => rfl + | some _, some _, none => rfl + | some a, some b, some c => exact congrArg some (meet_assoc_eq h a b c) + joinIdem x := by + match x with + | none => rfl + | some a => exact congrArg some (join_idem_eq h a) + meetIdem x := by + match x with + | none => rfl + | some a => exact congrArg some (meet_idem_eq h a) + joinNone x := by cases x <;> rfl + meetNone x := by cases x <;> rfl + absorbMeetJoin x y := by + match x, y with + | none, _ => rfl + | some a, none => exact congrArg some (meet_idem_eq h a) + | some a, some b => exact congrArg some (absorb_meet_join_eq h a b) + absorbJoinMeet x y := by + match x, y with + | none, _ => rfl + | some _, none => rfl + | some a, some b => exact congrArg some (absorb_join_meet_eq h a b) + meetDistribJoin x y z := by + match x, y, z with + | none, _, _ => rfl + | some _, none, none => rfl + | some _, none, some _ => rfl + | some _, some _, none => rfl + | some a, some b, some c => exact congrArg some (meet_distrib_join_eq h a b c) + joinDistribMeet x y z := by + match x, y, z with + | none, _, _ => rfl + | some a, none, none => exact congrArg some (meet_idem_eq h a).symm + | some a, none, some c => exact congrArg some (absorb_meet_join_eq h a c).symm + -- the one case a commutative lattice would get for free + | some a, some b, none => exact congrArg some (absorb_meet_join_flip_eq hf a b).symm + | some a, some b, some c => exact congrArg some (join_distrib_meet_eq h a b c) + +/-- …and a commutative one when the values under them are. -/ +theorem trieOps_isComm (hc : IsCommVals ops) : IsCommVals (trieOps ops) where + joinComm x y := by + match x, y with + | none, none => rfl + | none, some _ => rfl + | some _, none => rfl + | some a, some b => exact congrArg some (join_comm_eq hc a b) + meetComm x y := by + match x, y with + | none, none => rfl + | none, some _ => rfl + | some _, none => rfl + | some a, some b => exact congrArg some (meet_comm_eq hc a b) + +/-- The mirrored absorption lifts too, so the construction iterates. -/ +theorem trieOps_isFlipAbsorb (h : IsLatticeVals ops) (hf : IsFlipAbsorb ops) : + IsFlipAbsorb (trieOps ops) where + absorbMeetJoinFlip x y := by + match x, y with + | none, none => rfl + | none, some _ => rfl + | some a, none => exact congrArg some (meet_idem_eq h a) + | some a, some b => exact congrArg some (absorb_meet_join_flip_eq hf a b) + +/-! ## So tries nest, to any depth + +`PrunedMap (PrunedMap Unit)` — a trie whose values are sets of paths — is a +distributive lattice with a least element, commutative. `PrunedMap (PrunedMap +UInt64)` is the same minus commutativity. And `trieOps` of either is again a +lattice value type, so it iterates. -/ + +theorem nested_unit_isLattice : IsLatticeVals (trieOps unitOps) := + trieOps_isLattice unit_isLattice unit_isFlipAbsorb +theorem nested_unit_isComm : IsCommVals (trieOps unitOps) := trieOps_isComm unit_isComm +theorem nested_unit_isFlipAbsorb : IsFlipAbsorb (trieOps unitOps) := + trieOps_isFlipAbsorb unit_isLattice unit_isFlipAbsorb +theorem nested_u64_isLattice : IsLatticeVals (trieOps u64Ops) := + trieOps_isLattice u64_isLattice u64_isFlipAbsorb +theorem nested_u64_isFlipAbsorb : IsFlipAbsorb (trieOps u64Ops) := + trieOps_isFlipAbsorb u64_isLattice u64_isFlipAbsorb + +example (a b c : PrunedMap (PrunedMap Unit)) : + join (trieOps unitOps) (join (trieOps unitOps) a b) c + = join (trieOps unitOps) a (join (trieOps unitOps) b c) := + join_assoc_eq nested_unit_isLattice a b c + +example (a b : PrunedMap (PrunedMap Unit)) : + meet (trieOps unitOps) a b = meet (trieOps unitOps) b a := + meet_comm_eq nested_unit_isComm a b + +example (a b c : PrunedMap (PrunedMap UInt64)) : + meet (trieOps u64Ops) a (join (trieOps u64Ops) b c) + = join (trieOps u64Ops) (meet (trieOps u64Ops) a b) (meet (trieOps u64Ops) a c) := + meet_distrib_join_eq nested_u64_isLattice a b c + +-- Three deep, to show the iteration is real rather than a figure of speech. +example (a b c : PrunedMap (PrunedMap (PrunedMap Unit))) : + join (trieOps (trieOps unitOps)) a (meet (trieOps (trieOps unitOps)) b c) + = meet (trieOps (trieOps unitOps)) + (join (trieOps (trieOps unitOps)) a b) (join (trieOps (trieOps unitOps)) a c) := + join_distrib_meet_eq (trieOps_isLattice nested_unit_isLattice nested_unit_isFlipAbsorb) a b c + +end PrunedModel diff --git a/lean/PrunedModel/Pointwise.lean b/lean/PrunedModel/Pointwise.lean new file mode 100644 index 00000000..49c87e25 --- /dev/null +++ b/lean/PrunedModel/Pointwise.lean @@ -0,0 +1,331 @@ +import PrunedModel.Lattice + +/-! +# Every map operation, read at a single path + +`Lattice.lean` shows that `join` and `meet` are pointwise on `valAt`. This file +does the same for the rest of `Map.lean` — the operations the write zipper is +built from: `subtrie`, `removeAt`, `removeBelow`, `graftBelow`, `setVal`, +`removeVal`, `sub`, `restrictBelowRoot` and `prepend`. + +Each lemma says what the result holds at an arbitrary path `k`, in terms of what +the arguments hold. With `PrunedMap.ext` that is a complete description of the +result, so `Zippy.lean` never has to look inside an entry list. + +Nothing here is specific to `()`: the lemmas hold for every value type. +-/ + +namespace PrunedModel + +open PathMapModel + +/-! ## Prefixes -/ + +theorem Path.isPrefixOf_iff : ∀ (p q : Path), Path.isPrefixOf p q = true ↔ ∃ r, q = p ++ r + | [], q => by simp [Path.isPrefixOf] + | a :: as, [] => by simp [Path.isPrefixOf] + | a :: as, b :: bs => by + simp only [Path.isPrefixOf, Bool.and_eq_true, beq_iff_eq, Path.isPrefixOf_iff as bs, + List.cons_append, List.cons.injEq] + constructor + · rintro ⟨rfl, r, rfl⟩; exact ⟨r, rfl, rfl⟩ + · rintro ⟨r, rfl, rfl⟩; exact ⟨rfl, r, rfl⟩ + +theorem Path.stripPrefix_eq_some : ∀ (p q r : Path), Path.stripPrefix p q = some r ↔ q = p ++ r + | [], q, r => by simp [Path.stripPrefix] + | a :: as, [], r => by simp [Path.stripPrefix] + | a :: as, b :: bs, r => by + simp only [Path.stripPrefix, List.cons_append, List.cons.injEq] + by_cases h : a = b + · subst h; simp [Path.stripPrefix_eq_some as bs r] + · simp [h, Ne.symm h] + +theorem Path.stripPrefix_append (p r : Path) : Path.stripPrefix p (p ++ r) = some r := + (Path.stripPrefix_eq_some p _ r).mpr rfl + +theorem Path.stripPrefix_eq_none (p q : Path) : + Path.stripPrefix p q = none ↔ ∀ r, q ≠ p ++ r := by + constructor + · intro h r hq; rw [hq, Path.stripPrefix_append] at h; cases h + · intro h + cases hs : Path.stripPrefix p q with + | none => rfl + | some r => exact absurd ((Path.stripPrefix_eq_some p q r).mp hs) (h r) + +theorem Path.isPrefixOf_eq_isSome_stripPrefix (p q : Path) : + Path.isPrefixOf p q = (Path.stripPrefix p q).isSome := by + cases hs : Path.stripPrefix p q with + | some r => + simp only [Option.isSome_some] + exact (Path.isPrefixOf_iff p q).mpr ⟨r, (Path.stripPrefix_eq_some p q r).mp hs⟩ + | none => + simp only [Option.isSome_none] + cases hp : Path.isPrefixOf p q with + | false => rfl + | true => + obtain ⟨r, hr⟩ := (Path.isPrefixOf_iff p q).mp hp + exact absurd hr ((Path.stripPrefix_eq_none p q).mp hs r) + +/-! ## `lookup` through list surgery -/ + +variable {V : Type} + +/-- `List.lookup` on a cons, as an `if` on `Prop` equality. -/ +theorem lookup_cons' (k : Path) (kv : Path × V) (es : List (Path × V)) : + es.lookup k = es.lookup k ∧ + (kv :: es).lookup k = if k = kv.1 then some kv.2 else es.lookup k := by + refine ⟨rfl, ?_⟩ + obtain ⟨k1, v⟩ := kv + by_cases h : k = k1 + · subst h; simp [List.lookup] + · have : (k == k1) = false := by simp [h] + simp [List.lookup, this, h] + +theorem lookup_cons_if (k : Path) (kv : Path × V) (es : List (Path × V)) : + (kv :: es).lookup k = if k = kv.1 then some kv.2 else es.lookup k := + (lookup_cons' k kv es).2 + +theorem lookup_append (l₁ l₂ : List (Path × V)) (k : Path) : + (l₁ ++ l₂).lookup k = ((l₁.lookup k).or (l₂.lookup k)) := by + induction l₁ with + | nil => simp + | cons kv rest ih => + rw [List.cons_append, lookup_cons_if, lookup_cons_if, ih] + split <;> simp + +/-- Filtering on keys alone filters lookups the same way. -/ +theorem lookup_filter_key (f : Path → Bool) (l : List (Path × V)) (k : Path) : + (l.filter (fun kv => f kv.1)).lookup k = if f k then l.lookup k else none := by + induction l with + | nil => simp + | cons kv rest ih => + rw [List.filter_cons, lookup_cons_if] + by_cases hk : k = kv.1 + · subst hk; cases hf : f kv.1 <;> simp [hf, lookup_cons_if, ih] + · by_cases hf : f kv.1 = true <;> simp [hf, ih, lookup_cons_if, hk] + +/-- Re-keying every entry by stripping `p` looks up `p ++ k`. -/ +theorem lookup_filterMap_strip (p : Path) (l : List (Path × V)) (k : Path) : + (l.filterMap fun kv => (Path.stripPrefix p kv.1).map (·, kv.2)).lookup k = l.lookup (p ++ k) := by + induction l with + | nil => simp + | cons kv rest ih => + rw [List.filterMap_cons, lookup_cons_if] + cases hs : Path.stripPrefix p kv.1 with + | none => + have hne : p ++ k ≠ kv.1 := fun h => (Path.stripPrefix_eq_none p kv.1).mp hs k h.symm + simp [ih, hne] + | some r => + have hk := (Path.stripPrefix_eq_some p kv.1 r).mp hs + simp only [Option.map_some, lookup_cons_if, ih, hk, List.append_cancel_left_eq] + +/-- Prefixing every key with `p` looks up the stripped path. -/ +theorem lookup_map_prepend (p : Path) (l : List (Path × V)) (k : Path) : + (l.map fun kv => (p ++ kv.1, kv.2)).lookup k = + match Path.stripPrefix p k with + | some r => l.lookup r + | none => none := by + induction l with + | nil => cases Path.stripPrefix p k <;> rfl + | cons kv rest ih => + rw [List.map_cons, lookup_cons_if, ih] + cases hs : Path.stripPrefix p k with + | none => + have : k ≠ p ++ kv.1 := (Path.stripPrefix_eq_none p k).mp hs kv.1 + simp [this] + | some r => + have hk := (Path.stripPrefix_eq_some p k r).mp hs + subst hk + simp [lookup_cons_if] + +/-- A comprehension that keeps each key and transforms its value, over a list with +distinct keys. -/ +theorem lookup_filterMap_val (g : Path → V → Option V) : + ∀ (l : List (Path × V)), DistinctKeys l → ∀ k, + (l.filterMap fun kv => (g kv.1 kv.2).map (kv.1, ·)).lookup k = (l.lookup k).bind (g k) + | [], _, k => by simp + | kv :: rest, hd, k => by + rw [List.filterMap_cons, lookup_cons_if] + have ih := lookup_filterMap_val g rest hd.2 k + by_cases hk : k = kv.1 + · subst hk + have hnot : kv.1 ∉ rest.map (·.1) := hd.1 + have hrest : (rest.filterMap fun kv => (g kv.1 kv.2).map (kv.1, ·)).lookup kv.1 = none := by + rw [ih, lookup_eq_none_of_not_mem_keys hnot]; rfl + cases hg : g kv.1 kv.2 with + | none => simp [hrest, hg] + | some v => simp [hg] + · cases hg : g kv.1 kv.2 <;> simp [ih, lookup_cons_if, hk] + +/-- The comprehension `graftBelow` and `insertPrefixBelow` use: drop the root +entry, prefix the rest. -/ +theorem filterMap_prepend (p : Path) (l : List (Path × V)) : + l.filterMap (fun kv => if kv.1.isEmpty then none else some (p ++ kv.1, kv.2)) = + (l.filter fun kv => !kv.1.isEmpty).map (fun kv => (p ++ kv.1, kv.2)) := by + induction l with + | nil => rfl + | cons kv rest ih => + obtain ⟨k, v⟩ := kv + simp only [List.isEmpty_iff] at ih ⊢ + cases k <;> simp [ih] + +/-! ## Each map operation, at one path -/ + +namespace PrunedMap + +theorem valAt_def (t : PrunedMap V) (k : Path) : t.valAt k = t.entries.lookup k := rfl + +theorem valAt_subtrie (t : PrunedMap V) (p k : Path) : + (t.subtrie p).valAt k = t.valAt (p ++ k) := by + rw [subtrie, valAt_mk', lookup_filterMap_strip]; rfl + +theorem valAt_removeAt (t : PrunedMap V) (p k : Path) : + (t.removeAt p).valAt k = if Path.isPrefixOf p k then none else t.valAt k := by + rw [removeAt, valAt_mk', lookup_filter_key (fun k => !(Path.isPrefixOf p k))] + cases Path.isPrefixOf p k <;> rfl + +theorem valAt_removeBelow (t : PrunedMap V) (p k : Path) : + (t.removeBelow p).valAt k = + if Path.isPrefixOf p k = true ∧ k ≠ p then none else t.valAt k := by + rw [removeBelow, valAt_mk', lookup_filter_key (fun k => !(Path.isPrefixOf p k) || k == p)] + by_cases h1 : Path.isPrefixOf p k = true <;> by_cases h2 : k = p <;> simp [h1, h2] <;> rfl + +theorem valAt_setVal (t : PrunedMap V) (p : Path) (v : V) (k : Path) : + (t.setVal p v).2.valAt k = if k = p then some v else t.valAt k := by + rw [setVal, valAt_mk', lookup_cons_if, lookup_filter_key (fun k => !(k == p))] + by_cases h : k = p <;> simp [h] <;> rfl + +theorem setVal_fst (t : PrunedMap V) (p : Path) (v : V) : (t.setVal p v).1 = t.valAt p := rfl + +theorem valAt_removeVal (t : PrunedMap V) (p k : Path) : + (t.removeVal p).2.valAt k = if k = p then none else t.valAt k := by + rw [removeVal, valAt_mk', lookup_filter_key (fun k => !(k == p))] + by_cases h : k = p <;> simp [h] <;> rfl + +theorem removeVal_fst (t : PrunedMap V) (p : Path) : (t.removeVal p).2 = (t.removeVal p).2 ∧ + (t.removeVal p).1 = t.valAt p := ⟨rfl, rfl⟩ + +/-- Below `p`, the grafted map; everywhere else — `p` itself included — the old one. -/ +theorem valAt_graftBelow (t : PrunedMap V) (p : Path) (s : PrunedMap V) (k : Path) : + (t.graftBelow p s).valAt k = + match Path.stripPrefix p k with + | some (b :: r) => s.valAt (b :: r) + | _ => t.valAt k := by + rw [graftBelow, valAt_mk', lookup_append] + have hA : (t.removeBelow p).entries.lookup k = (t.removeBelow p).valAt k := rfl + rw [hA, valAt_removeBelow] + rw [filterMap_prepend, lookup_map_prepend] + cases hs : Path.stripPrefix p k with + | none => + have : ¬ (Path.isPrefixOf p k = true ∧ k ≠ p) := by + rintro ⟨h, _⟩ + rw [Path.isPrefixOf_eq_isSome_stripPrefix, hs] at h; cases h + simp [this] + | some r => + have hk := (Path.stripPrefix_eq_some p k r).mp hs + subst hk + have hpre : Path.isPrefixOf p (p ++ r) = true := (Path.isPrefixOf_iff _ _).mpr ⟨r, rfl⟩ + cases r with + | nil => dsimp only; rw [lookup_filter_key (fun k => !k.isEmpty)]; simp + | cons b r => + have hne : p ++ b :: r ≠ p := by + intro h; have := congrArg List.length h; simp at this + simp only [hpre, ne_eq, hne, not_false_eq_true, and_self, if_true, Option.none_or] + rw [lookup_filter_key (fun k => !k.isEmpty)] + rfl + +theorem valAt_sub (ops : ValOps V) (a b : PrunedMap V) (k : Path) : + (sub ops a b).valAt k = subVal ops (a.valAt k) (b.valAt k) := by + rw [sub, valAt_mk', + lookup_filterMap_val (fun k v => subVal ops (some v) (b.valAt k)) _ + (distinctKeys_of_sortedKeys a.sorted)] + show (a.valAt k).bind _ = _ + cases a.valAt k <;> rfl + +theorem valAt_restrictBelowRoot (a b : PrunedMap V) (k : Path) : + (restrictBelowRoot a b).valAt k = if validatedBy b k then a.valAt k else none := by + rw [restrictBelowRoot, valAt_mk', lookup_filter_key (fun k => validatedBy b k)]; rfl + +theorem valAt_prepend (t : PrunedMap V) (pre k : Path) : + (t.prepend pre).valAt k = + match Path.stripPrefix pre k with + | some r => t.valAt r + | none => none := by + rw [prepend, valAt_mk', lookup_map_prepend] + cases Path.stripPrefix pre k <;> rfl + +theorem isEmptyMap_iff (t : PrunedMap V) : t.isEmptyMap = true ↔ ∀ k, t.valAt k = none := by + constructor + · intro h k + have : t.entries = [] := List.isEmpty_iff.mp h + simp [valAt_def, this] + · intro h + cases he : t.entries with + | nil => simp [isEmptyMap, he] + | cons kv rest => + have := h kv.1 + rw [valAt_def, he, lookup_cons_if] at this + simp at this + +theorem eq_empty_iff (t : PrunedMap V) : t = empty ↔ ∀ k, t.valAt k = none := by + constructor + · rintro rfl k; rfl + · intro h; exact ext fun k => (h k).trans rfl + +theorem belowIsEmpty_iff (t : PrunedMap V) (p : Path) : + t.belowIsEmpty p = true ↔ ∀ b r, t.valAt (p ++ b :: r) = none := by + rw [belowIsEmpty, keys, List.all_map] + simp only [List.all_eq_true, Function.comp, Bool.or_eq_true, Bool.not_eq_true', beq_iff_eq] + constructor + · intro h b r + cases hv : t.valAt (p ++ b :: r) with + | none => rfl + | some v => + exfalso + obtain ⟨kv, hmem, hkv⟩ := List.lookup_isSome_iff.mp (show (t.entries.lookup (p ++ b :: r)).isSome by + rw [← valAt_def, hv]; rfl) + have hk : kv.1 = p ++ b :: r := (eq_of_beq hkv).symm + rcases h kv hmem with h1 | h1 + · rw [hk] at h1 + have : Path.isPrefixOf p (p ++ b :: r) = true := (Path.isPrefixOf_iff _ _).mpr ⟨_, rfl⟩ + rw [this] at h1; cases h1 + · rw [hk] at h1 + have := congrArg List.length h1; simp at this + · intro h kv hmem + cases hp : Path.isPrefixOf p kv.1 with + | false => exact Or.inl rfl + | true => + right + obtain ⟨r, hr⟩ := (Path.isPrefixOf_iff _ _).mp hp + cases r with + | nil => simpa using hr + | cons b r => + exfalso + have h1 := h b r + have h2 : (t.entries.lookup kv.1).isSome := + lookup_isSome_of_mem_keys (List.mem_map.mpr ⟨kv, hmem, rfl⟩) + rw [← valAt_def, hr, h1] at h2; cases h2 + +theorem validatedBy_iff (b : PrunedMap V) (q : Path) : + validatedBy b q = true ↔ ∃ r s, r ≠ [] ∧ q = r ++ s ∧ (b.valAt r).isSome := by + rw [validatedBy, List.any_eq_true] + constructor + · rintro ⟨i, hi, hv⟩ + have hi' : i < q.length := List.mem_range.mp hi + refine ⟨q.take (i + 1), q.drop (i + 1), ?_, (List.take_append_drop _ _).symm, hv⟩ + intro h + rcases List.take_eq_nil_iff.mp h with h | h + · omega + · simp [h] at hi' + · rintro ⟨r, s, hr, rfl, hv⟩ + cases r with + | nil => exact absurd rfl hr + | cons c r => + refine ⟨r.length, List.mem_range.mpr (by simp; omega), ?_⟩ + have : ((c :: r) ++ s).take (r.length + 1) = c :: r := by + simp + rw [this]; exact hv + +end PrunedMap + +end PrunedModel diff --git a/lean/PrunedModel/Refine.lean b/lean/PrunedModel/Refine.lean new file mode 100644 index 00000000..78c136f4 --- /dev/null +++ b/lean/PrunedModel/Refine.lean @@ -0,0 +1,872 @@ +import PrunedModel.Write +import PrunedModel.Pointwise + +/-! +# What each write operation does to the trie + +Every write operation in `Write.lean` touches the trie only at and below the +focus. This file proves that, operation by operation, in one shape: + + (z.op …).2 = z.withTrie (z.trie.replaceAt z.focus M) + +where `replaceAt t f M` is `t` with everything at and below `f` replaced by the +map `M` (root value included), and `M` is named: `join ops z.makeMap m` for +`join_map_into`, `meet ops z.makeMap src.makeMap` for `meet_into`, and so on. + +That one equation says two things at once: + +* **frame** — nothing outside the focus's subtrie changes, and the cursor does + not move; +* **refinement** — read back at the focus (`makeMap`), the operation computes + `M`, a map-level operation on the two focused subtries. + +`Zippy.lean` builds the set algebra from these. Where `M` is *not* the obvious +set operation — `restrict` keeps the focus value, `join_into` ignores the +source's, `insert_prefix` leaves the focus value where it was — the difference +is in `M`, and `Zippy.lean` states it as a law of its own. + +Equality of values is decided by `ValOps.beq`, and two branches of the algebraic +operations return the zipper untouched when `beqT` says the result equals the +input. Those branches agree with the others only if `beq` is sound, so the +algebraic lemmas take `LawfulBeqOps ops`. `unitOps` and `u64Ops` both are. +-/ + +namespace PrunedModel + +open PathMapModel + +/-- `ValOps.beq` decides equality. -/ +def LawfulBeqOps {V : Type} (ops : ValOps V) : Prop := ∀ a b, ops.beq a b = true → a = b + +theorem unitOps_lawful : LawfulBeqOps unitOps := fun _ _ _ => rfl + +theorem u64Ops_lawful : LawfulBeqOps u64Ops := by + intro a b h + simpa [u64Ops] using h + +namespace PrunedMap + +variable {V : Type} + +/-! ## Replacing a subtrie -/ + +/-- `t` with everything at and below `f` replaced by `m`; `m`'s root value goes +to `f`. -/ +def replaceAt (t : PrunedMap V) (f : Path) (m : PrunedMap V) : PrunedMap V := + mk' ((t.removeAt f).entries ++ m.entries.map fun kv => (f ++ kv.1, kv.2)) + +theorem valAt_replaceAt (t : PrunedMap V) (f : Path) (m : PrunedMap V) (k : Path) : + (t.replaceAt f m).valAt k = + match Path.stripPrefix f k with + | some r => m.valAt r + | none => t.valAt k := by + rw [replaceAt, valAt_mk', lookup_append] + have hA : (t.removeAt f).entries.lookup k = (t.removeAt f).valAt k := rfl + rw [hA, valAt_removeAt, lookup_map_prepend, Path.isPrefixOf_eq_isSome_stripPrefix] + cases Path.stripPrefix f k <;> simp <;> rfl + +theorem valAt_replaceAt_append (t : PrunedMap V) (f : Path) (m : PrunedMap V) (r : Path) : + (t.replaceAt f m).valAt (f ++ r) = m.valAt r := by + rw [valAt_replaceAt, Path.stripPrefix_append] + +theorem valAt_replaceAt_of_not {t : PrunedMap V} {f : Path} {m : PrunedMap V} {k : Path} + (h : ∀ r, k ≠ f ++ r) : (t.replaceAt f m).valAt k = t.valAt k := by + rw [valAt_replaceAt, (Path.stripPrefix_eq_none f k).mpr h] + +/-- Replacing at the root replaces everything. -/ +theorem replaceAt_nil (t m : PrunedMap V) : t.replaceAt [] m = m := + ext fun k => by + show (t.replaceAt [] m).valAt k = m.valAt k + exact valAt_replaceAt_append t [] m k + +/-- Reading back what was written. -/ +theorem subtrie_replaceAt (t : PrunedMap V) (f : Path) (m : PrunedMap V) : + (t.replaceAt f m).subtrie f = m := + ext fun k => by + show ((t.replaceAt f m).subtrie f).valAt k = m.valAt k + rw [valAt_subtrie, valAt_replaceAt_append] + +/-- **The three-case check.** `t'` is `t` with `m` written at `f` iff they agree +away from `f`, at `f` (the root value), and strictly below `f` (the node). -/ +theorem eq_replaceAt {t t' : PrunedMap V} {f : Path} {m : PrunedMap V} + (hout : ∀ k, (∀ r, k ≠ f ++ r) → t'.valAt k = t.valAt k) + (hroot : t'.valAt f = m.valAt []) + (hbelow : ∀ b r, t'.valAt (f ++ b :: r) = m.valAt (b :: r)) : + t' = t.replaceAt f m := by + apply ext; intro k + show t'.valAt k = (t.replaceAt f m).valAt k + rw [valAt_replaceAt] + cases hs : Path.stripPrefix f k with + | none => exact hout k ((Path.stripPrefix_eq_none f k).mp hs) + | some r => + have := (Path.stripPrefix_eq_some f k r).mp hs; subst this + cases r with + | nil => simpa using hroot + | cons b r => exact hbelow b r + +/-- A path off `f`'s subtrie is not `f`. -/ +theorem ne_of_off {k f : Path} (h : ∀ r, k ≠ f ++ r) : k ≠ f := by + intro e; exact h [] (by simp [e]) + +/-- …and `graftBelow f` does not see it. -/ +theorem stripPrefix_off {k f : Path} (h : ∀ r, k ≠ f ++ r) : Path.stripPrefix f k = none := + (Path.stripPrefix_eq_none f k).mpr h + +/-- `x`'s root value over `n`'s node: what an operation that works on nodes — +and leaves the focus value alone — writes at the focus. -/ +def withRootOf (x n : PrunedMap V) : PrunedMap V := + mk' ((x.entries.filter fun kv => kv.1.isEmpty) ++ (n.entries.filter fun kv => !kv.1.isEmpty)) + +theorem valAt_withRootOf_nil (x n : PrunedMap V) : (withRootOf x n).valAt [] = x.valAt [] := by + rw [withRootOf, valAt_mk', lookup_append, lookup_filter_key (fun k => k.isEmpty), + lookup_filter_key (fun k => !k.isEmpty)] + simp; rfl + +theorem valAt_withRootOf_cons (x n : PrunedMap V) (b : UInt8) (r : Path) : + (withRootOf x n).valAt (b :: r) = n.valAt (b :: r) := by + rw [withRootOf, valAt_mk', lookup_append, lookup_filter_key (fun k => k.isEmpty), + lookup_filter_key (fun k => !k.isEmpty)] + simp; rfl + +/-- `validatedBy` reads only non-empty paths, so a root value is invisible to it. -/ +theorem validatedBy_congr {a b : PrunedMap V} (h : ∀ c r, a.valAt (c :: r) = b.valAt (c :: r)) + (q : Path) : validatedBy a q = validatedBy b q := by + apply Bool.eq_iff_iff.mpr + rw [validatedBy_iff, validatedBy_iff] + constructor + · rintro ⟨r, s, hr, hq, hv⟩ + cases r with + | nil => exact absurd rfl hr + | cons c r => exact ⟨c :: r, s, hr, hq, by rwa [← h]⟩ + · rintro ⟨r, s, hr, hq, hv⟩ + cases r with + | nil => exact absurd rfl hr + | cons c r => exact ⟨c :: r, s, hr, hq, by rwa [h]⟩ + +theorem validatedBy_empty (q : Path) : validatedBy (empty : PrunedMap V) q = false := by + cases h : validatedBy (empty : PrunedMap V) q with + | false => rfl + | true => + obtain ⟨r, s, _, _, hv⟩ := (validatedBy_iff _ _).mp h + simp at hv + +/-! ## `beqT` is equality, when `beq` is -/ + +private theorem eq_of_zip_all {ops : ValOps V} (hbeq : LawfulBeqOps ops) : + ∀ (l₁ l₂ : List (Path × V)), l₁.length = l₂.length → + (l₁.zip l₂).all (fun xy => xy.1.1 == xy.2.1 && ops.beq xy.1.2 xy.2.2) = true → l₁ = l₂ + | [], [], _, _ => rfl + | [], _ :: _, hl, _ => by simp at hl + | _ :: _, [], hl, _ => by simp at hl + | x :: xs, y :: ys, hl, h => by + simp only [List.zip_cons_cons, List.all_cons, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨h1, h2⟩, h3⟩ := h + have := eq_of_zip_all hbeq xs ys (by simpa using hl) h3 + obtain ⟨xk, xv⟩ := x; obtain ⟨yk, yv⟩ := y + simp only at h1 h2 + rw [h1, hbeq _ _ h2, this] + +theorem eq_of_beqT {ops : ValOps V} (hbeq : LawfulBeqOps ops) {a b : PrunedMap V} + (h : beqT ops a b = true) : a = b := by + rw [beqT, Bool.and_eq_true, beq_iff_eq] at h + have he := eq_of_zip_all hbeq _ _ h.1 h.2 + exact ext fun k => by rw [he] + +end PrunedMap + +namespace PZip + +open PrunedMap + +variable {V : Type} (z : PZip V) + +/-! ## Reading at the focus -/ + +@[simp] theorem withTrie_trie (t : PrunedMap V) : (z.withTrie t).trie = t := rfl +@[simp] theorem withTrie_focus (t : PrunedMap V) : (z.withTrie t).focus = z.focus := rfl +@[simp] theorem withTrie_withTrie (t u : PrunedMap V) : + (z.withTrie t).withTrie u = z.withTrie u := rfl +@[simp] theorem withTrie_self : z.withTrie z.trie = z := rfl + +theorem valAt_makeMap (k : Path) : z.makeMap.valAt k = z.trie.valAt (z.focus ++ k) := + valAt_subtrie _ _ _ + +theorem makeMap_valAt_nil : z.makeMap.valAt [] = z.val := by + rw [valAt_makeMap, List.append_nil]; rfl + +theorem valAt_focusNode (k : Path) : + z.focusNode.valAt k = if k = [] then none else z.trie.valAt (z.focus ++ k) := by + rw [focusNode, valAt_removeVal, valAt_makeMap] + +theorem valAt_focusNode_cons (b : UInt8) (r : Path) : + z.focusNode.valAt (b :: r) = z.trie.valAt (z.focus ++ b :: r) := by + rw [valAt_focusNode]; simp + +theorem focusNode_isEmptyMap_iff : + z.focusNode.isEmptyMap = true ↔ ∀ b r, z.trie.valAt (z.focus ++ b :: r) = none := by + rw [isEmptyMap_iff] + constructor + · intro h b r; rw [← valAt_focusNode_cons]; exact h _ + · intro h k + cases k with + | nil => rw [valAt_focusNode]; simp + | cons b r => rw [valAt_focusNode_cons]; exact h b r + +theorem focusNodeIsEmpty_iff : + z.focusNodeIsEmpty = true ↔ ∀ b r, z.trie.valAt (z.focus ++ b :: r) = none := + belowIsEmpty_iff _ _ + +theorem focusNodeIsEmpty_eq : z.focusNodeIsEmpty = z.focusNode.isEmptyMap := by + apply Bool.eq_iff_iff.mpr + rw [focusNodeIsEmpty_iff, focusNode_isEmptyMap_iff] + +/-! ## The value at the focus -/ + +theorem setVal_eq (v : V) : + (z.setVal v).2 = z.withTrie (z.trie.replaceAt z.focus ((z.makeMap.setVal [] v).2)) := by + have h0 : (z.setVal v).2 = z.withTrie (z.trie.setVal z.focus v).2 := rfl + rw [h0] + congr 1 + apply eq_replaceAt + · intro k hk; rw [valAt_setVal, if_neg (ne_of_off hk)] + · rw [valAt_setVal, valAt_setVal]; simp + · intro b r + rw [valAt_setVal, valAt_setVal, valAt_makeMap] + simp + +theorem removeVal_eq : + (z.removeVal).2 = z.withTrie (z.trie.replaceAt z.focus ((z.makeMap.removeVal []).2)) := by + have key : z.trie.replaceAt z.focus ((z.makeMap.removeVal []).2) = (z.trie.removeVal z.focus).2 := by + symm + apply eq_replaceAt + · intro k hk; rw [valAt_removeVal, if_neg (ne_of_off hk)] + · rw [valAt_removeVal, valAt_removeVal]; simp + · intro b r + rw [valAt_removeVal, valAt_removeVal, valAt_makeMap] + simp + rw [key] + unfold removeVal + cases hv : z.val with + | some v => rfl + | none => + simp only + have : (z.trie.removeVal z.focus).2 = z.trie := by + apply ext; intro k + show (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k + rw [valAt_removeVal] + by_cases hk : k = z.focus + · subst hk; simp only [if_true]; exact hv.symm + · simp [hk] + rw [this]; rfl + +/-! ## Grafting -/ + +theorem graftMap_eq (m : PrunedMap V) : + z.graftMap m = z.withTrie (z.trie.replaceAt z.focus m) := by + show z.withTrie _ = _ + congr 1 + apply eq_replaceAt + · intro k hk + cases m.valAt [] <;> + simp [valAt_setVal, valAt_removeVal, valAt_graftBelow, ne_of_off hk, stripPrefix_off hk] + · cases hm : m.valAt [] <;> simp [valAt_setVal, valAt_removeVal] + · intro b r + have hne : z.focus ++ b :: r ≠ z.focus := by + intro h; have := congrArg List.length h; simp at this + cases m.valAt [] <;> + simp [valAt_setVal, valAt_removeVal, valAt_graftBelow, hne, Path.stripPrefix_append] + +theorem graft_eq (src : PZip V) : z.graft src = z.withTrie (z.trie.replaceAt z.focus src.makeMap) := + graftMap_eq z _ + +/-! ## The shared tail of the algebraic operations + +Every algebraic operation ends the same way: compute a node `r`, and either +graft it below the focus or — when `beqT` says it equals what is there — leave +the zipper alone. With a lawful `beq` the two branches agree, so each operation +is "graft `r`". -/ + +theorem graftBelow_focusNode : z.trie.graftBelow z.focus z.focusNode = z.trie := by + apply ext; intro k + show (z.trie.graftBelow z.focus z.focusNode).valAt k = z.trie.valAt k + rw [valAt_graftBelow] + cases hs : Path.stripPrefix z.focus k with + | none => rfl + | some r => + cases r with + | nil => rfl + | cons b r => + dsimp only + rw [valAt_focusNode_cons, (Path.stripPrefix_eq_some _ _ _).mp hs] + +theorem keep_eq_graft (z1 : PZip V) {r : PrunedMap V} (h : r = z1.focusNode) : + z1 = z1.withTrie (z1.trie.graftBelow z1.focus r) := by + rw [h, graftBelow_focusNode]; rfl + +theorem ite_beqT_graft {ops : ValOps V} (hbeq : LawfulBeqOps ops) (z1 : PZip V) (r : PrunedMap V) : + (if ((if beqT ops r z1.focusNode = true then AlgStatus.identity else AlgStatus.element) + == AlgStatus.identity) = true then z1 + else z1.withTrie (z1.trie.graftBelow z1.focus r)) = + z1.withTrie (z1.trie.graftBelow z1.focus r) := by + by_cases h : beqT ops r z1.focusNode = true + · simp only [h, if_true]; exact keep_eq_graft z1 (eq_of_beqT hbeq h) + · simp [h] + +theorem ite_nodeStatus_graft {ops : ValOps V} (hbeq : LawfulBeqOps ops) (z1 : PZip V) + (r : PrunedMap V) : + (if (nodeStatus ops z1.focusNode r == AlgStatus.identity) = true then z1 + else z1.withTrie (z1.trie.graftBelow z1.focus r)) = + z1.withTrie (z1.trie.graftBelow z1.focus r) := by + by_cases h : (nodeStatus ops z1.focusNode r == AlgStatus.identity) = true + · rw [if_pos h] + apply keep_eq_graft + unfold nodeStatus at h + by_cases he : r.isEmptyMap = true + · simp [he] at h + · by_cases hb : beqT ops r z1.focusNode = true + · exact eq_of_beqT hbeq hb + · simp [he, hb] at h + · rw [if_neg h] + +/-- Grafting below the focus of a zipper whose trie is `T`. -/ +theorem withTrie_graft_eq (T R : PrunedMap V) : + (z.withTrie T).withTrie ((z.withTrie T).trie.graftBelow (z.withTrie T).focus R) = + z.withTrie (T.graftBelow z.focus R) := rfl + +theorem removeVal_eq' : (z.removeVal).2 = z.withTrie (z.trie.removeVal z.focus).2 := by + unfold removeVal + cases hv : z.val with + | some v => rfl + | none => + simp only + have : (z.trie.removeVal z.focus).2 = z.trie := by + apply ext; intro k + show (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k + rw [valAt_removeVal] + by_cases hk : k = z.focus + · subst hk; simp only [if_true]; exact hv.symm + · simp [hk] + rw [this]; rfl + +theorem setVal_eq' (v : V) : (z.setVal v).2 = z.withTrie (z.trie.setVal z.focus v).2 := rfl + +end PZip + +/-! ## Facts about the operations on `Option V` that hold for every value type -/ + +namespace PrunedMap +variable {V : Type} (ops : ValOps V) + +@[simp] theorem joinVal_none_right (x : Option V) : joinVal ops x none = x := by + cases x <;> rfl +@[simp] theorem joinVal_none_left (x : Option V) : joinVal ops none x = x := rfl +@[simp] theorem meetVal_none_right (x : Option V) : meetVal ops x none = none := by + cases x <;> rfl +@[simp] theorem meetVal_none_left (x : Option V) : meetVal ops none x = none := rfl +@[simp] theorem subVal_none_right (x : Option V) : subVal ops x none = x := by + cases x <;> rfl +@[simp] theorem subVal_none_left (x : Option V) : subVal ops none x = none := rfl + +end PrunedMap + +namespace PZip +open PrunedMap +variable {V : Type} (z : PZip V) + +/-! ## Finishing an operation + +After the value step the zipper is `z.withTrie T`, where `T` differs from +`z.trie` at most at the focus. The node step then either keeps it or grafts a +node `R` below the focus. These two lemmas turn either ending into the +`replaceAt` form, given what `T` and `R` hold. -/ + +theorem finish_keep (T M : PrunedMap V) + (hout : ∀ k, (∀ r, k ≠ z.focus ++ r) → T.valAt k = z.trie.valAt k) + (hroot : T.valAt z.focus = M.valAt []) + (hbelow : ∀ b r, T.valAt (z.focus ++ b :: r) = M.valAt (b :: r)) : + z.withTrie T = z.withTrie (z.trie.replaceAt z.focus M) := by + congr 1 + exact eq_replaceAt hout hroot hbelow + +theorem stripPrefix_self (p : Path) : Path.stripPrefix p p = some [] := by + simpa using Path.stripPrefix_append p [] + +theorem finish_graft (T R M : PrunedMap V) + (hout : ∀ k, k ≠ z.focus → T.valAt k = z.trie.valAt k) + (hroot : T.valAt z.focus = M.valAt []) + (hbelow : ∀ b r, R.valAt (b :: r) = M.valAt (b :: r)) : + z.withTrie (T.graftBelow z.focus R) = z.withTrie (z.trie.replaceAt z.focus M) := by + apply finish_keep + · intro k hk + rw [valAt_graftBelow, stripPrefix_off hk] + exact hout k (ne_of_off hk) + · rw [valAt_graftBelow, stripPrefix_self] + exact hroot + · intro b r + rw [valAt_graftBelow, Path.stripPrefix_append] + exact hbelow b r + +/-! ## The algebraic operations -/ + +theorem joinMapInto_eq {ops : ValOps V} (hbeq : LawfulBeqOps ops) (m : PrunedMap V) : + (z.joinMapInto ops m).2 = z.withTrie (z.trie.replaceAt z.focus (join ops z.makeMap m)) := by + have tail : ∀ T : PrunedMap V, (∀ k, k ≠ z.focus → T.valAt k = z.trie.valAt k) → + T.valAt z.focus = joinVal ops z.val (m.valAt []) → + (if (m.removeVal []).2.isEmptyMap = true then z.withTrie T + else z.withTrie (T.graftBelow z.focus (join ops (z.withTrie T).focusNode (m.removeVal []).2))) + = z.withTrie (z.trie.replaceAt z.focus (join ops z.makeMap m)) := by + intro T hout hroot + have hroot' : T.valAt z.focus = (join ops z.makeMap m).valAt [] := by + rw [valAt_join, makeMap_valAt_nil, hroot] + split + · next hE => + have hmb : ∀ b r, m.valAt (b :: r) = none := fun b r => by + have := (isEmptyMap_iff _).mp hE (b :: r); rwa [valAt_removeVal, if_neg (by simp)] at this + apply finish_keep + · intro k hk; exact hout k (ne_of_off hk) + · exact hroot' + · intro b r; rw [valAt_join, valAt_makeMap, hmb, joinVal_none_right]; exact hout _ (by simp) + · apply finish_graft _ _ _ _ hout hroot' + intro b r + rw [valAt_join, valAt_join, valAt_focusNode_cons, valAt_removeVal, if_neg (by simp), valAt_makeMap] + simp only [withTrie_trie, withTrie_focus] + rw [hout _ (by simp)] + have offFocus : ∀ (v : V) k, k ≠ z.focus → (z.trie.setVal z.focus v).2.valAt k = z.trie.valAt k := + fun v k hk => by rw [valAt_setVal, if_neg hk] + have offFocus' : ∀ k, k ≠ z.focus → (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k := + fun k hk => by rw [valAt_removeVal, if_neg hk] + unfold joinMapInto + cases hz : z.val with + | none => + cases hm : m.valAt [] with + | none => + simp only [apply_ite Prod.snd] + rw [ite_beqT_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hm]; exact hz) + | some mv => + simp only [apply_ite Prod.snd] + rw [ite_beqT_graft hbeq] + exact tail (z.trie.setVal z.focus mv).2 (offFocus mv) (by rw [valAt_setVal, if_pos rfl, hz, hm]; rfl) + | some sv => + cases hm : m.valAt [] with + | none => + simp only [apply_ite Prod.snd] + rw [ite_beqT_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hm]; exact hz) + | some mv => + cases hr : (ops.pjoin sv mv).resolve sv mv with + | none => + simp only [apply_ite Prod.snd, hr] + rw [ite_beqT_graft hbeq, removeVal_eq'] + exact tail (z.trie.removeVal z.focus).2 offFocus' (by rw [valAt_removeVal, if_pos rfl, hz, hm]; exact hr.symm) + | some v => + simp only [apply_ite Prod.snd, hr] + rw [ite_beqT_graft hbeq] + exact tail (z.trie.setVal z.focus v).2 (offFocus v) (by rw [valAt_setVal, if_pos rfl, hz, hm]; exact hr.symm) + +/-! ### `removeBelow` at the focus -/ + +theorem isPrefixOf_off {k f : Path} (h : ∀ r, k ≠ f ++ r) : Path.isPrefixOf f k = false := by + rw [Path.isPrefixOf_eq_isSome_stripPrefix, stripPrefix_off h]; rfl + +theorem valAt_removeBelow_off (T : PrunedMap V) {f k : Path} (h : ∀ r, k ≠ f ++ r) : + (T.removeBelow f).valAt k = T.valAt k := by + rw [valAt_removeBelow, isPrefixOf_off h]; simp + +theorem valAt_removeBelow_self (T : PrunedMap V) (f : Path) : + (T.removeBelow f).valAt f = T.valAt f := by + rw [valAt_removeBelow]; simp + +theorem valAt_removeBelow_cons (T : PrunedMap V) (f : Path) (b : UInt8) (r : Path) : + (T.removeBelow f).valAt (f ++ b :: r) = none := by + rw [valAt_removeBelow, if_pos ⟨(Path.isPrefixOf_iff _ _).mpr ⟨_, rfl⟩, by simp⟩] + +theorem focus_cons_ne (b : UInt8) (r : Path) : z.focus ++ b :: r ≠ z.focus := by simp + +theorem ite_beqT_graft' {ops : ValOps V} (hbeq : LawfulBeqOps ops) (z1 : PZip V) (r : PrunedMap V) : + (if beqT ops r z1.focusNode = true then z1 + else z1.withTrie (z1.trie.graftBelow z1.focus r)) = + z1.withTrie (z1.trie.graftBelow z1.focus r) := by + by_cases h : beqT ops r z1.focusNode = true + · rw [if_pos h]; exact keep_eq_graft z1 (eq_of_beqT hbeq h) + · rw [if_neg h] + +theorem meetInto_eq {ops : ValOps V} (hbeq : LawfulBeqOps ops) (src : PZip V) : + (z.meetInto ops src).2 = z.withTrie (z.trie.replaceAt z.focus (meet ops z.makeMap src.makeMap)) := by + have tail : ∀ T : PrunedMap V, (∀ k, k ≠ z.focus → T.valAt k = z.trie.valAt k) → + T.valAt z.focus = meetVal ops z.val src.val → + (if (z.withTrie T).focusNode.isEmptyMap = true then z.withTrie T + else if src.focusNode.isEmptyMap = true then z.withTrie (T.removeBelow z.focus) + else z.withTrie (T.graftBelow z.focus (meet ops (z.withTrie T).focusNode src.focusNode))) + = z.withTrie (z.trie.replaceAt z.focus (meet ops z.makeMap src.makeMap)) := by + intro T hout hroot + have hroot' : T.valAt z.focus = (meet ops z.makeMap src.makeMap).valAt [] := by + rw [valAt_meet, makeMap_valAt_nil, makeMap_valAt_nil, hroot] + have hT : ∀ b r, T.valAt (z.focus ++ b :: r) = z.trie.valAt (z.focus ++ b :: r) := + fun b r => hout _ (focus_cons_ne z b r) + split + · next hE => + apply finish_keep + · intro k hk; exact hout k (ne_of_off hk) + · exact hroot' + · intro b r + have h0 := (focusNode_isEmptyMap_iff _).mp hE b r + simp only [withTrie_trie, withTrie_focus] at h0 + rw [valAt_meet, valAt_makeMap, ← hT, h0, meetVal_none_left] + · split + · next _ hE => + apply finish_keep + · intro k hk; rw [valAt_removeBelow_off _ hk]; exact hout k (ne_of_off hk) + · rw [valAt_removeBelow_self]; exact hroot' + · intro b r + rw [valAt_removeBelow_cons, valAt_meet, valAt_makeMap src, + (focusNode_isEmptyMap_iff src).mp hE b r, meetVal_none_right] + · apply finish_graft _ _ _ _ hout hroot' + intro b r + rw [valAt_meet, valAt_meet, valAt_focusNode_cons, valAt_focusNode_cons, valAt_makeMap, + valAt_makeMap] + simp only [withTrie_trie, withTrie_focus]; rw [hT] + have offFocus : ∀ (v : V) k, k ≠ z.focus → (z.trie.setVal z.focus v).2.valAt k = z.trie.valAt k := + fun v k hk => by rw [valAt_setVal, if_neg hk] + have offFocus' : ∀ k, k ≠ z.focus → (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k := + fun k hk => by rw [valAt_removeVal, if_neg hk] + unfold meetInto + cases hz : z.val with + | none => + cases hs : src.val with + | none => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some ov => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some sv => + cases hs : src.val with + | none => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq, removeVal_eq'] + exact tail (z.trie.removeVal z.focus).2 offFocus' + (by rw [valAt_removeVal, if_pos rfl, hz, hs]; rfl) + | some ov => + cases hr : (ops.pmeet sv ov).resolve sv ov with + | none => + simp only [apply_ite Prod.snd, hr] + rw [ite_nodeStatus_graft hbeq, removeVal_eq'] + exact tail (z.trie.removeVal z.focus).2 offFocus' + (by rw [valAt_removeVal, if_pos rfl, hz, hs]; exact hr.symm) + | some v => + simp only [apply_ite Prod.snd, hr] + rw [ite_nodeStatus_graft hbeq] + exact tail (z.trie.setVal z.focus v).2 (offFocus v) + (by rw [valAt_setVal, if_pos rfl, hz, hs]; exact hr.symm) + +theorem subtractInto_eq {ops : ValOps V} (hbeq : LawfulBeqOps ops) (src : PZip V) : + (z.subtractInto ops src).2 = z.withTrie (z.trie.replaceAt z.focus (sub ops z.makeMap src.makeMap)) := by + have tail : ∀ T : PrunedMap V, (∀ k, k ≠ z.focus → T.valAt k = z.trie.valAt k) → + T.valAt z.focus = subVal ops z.val src.val → + (if src.focusNode.isEmptyMap = true then z.withTrie T + else if (z.withTrie T).focusNode.isEmptyMap = true then z.withTrie T + else z.withTrie (T.graftBelow z.focus (sub ops (z.withTrie T).focusNode src.focusNode))) + = z.withTrie (z.trie.replaceAt z.focus (sub ops z.makeMap src.makeMap)) := by + intro T hout hroot + have hroot' : T.valAt z.focus = (sub ops z.makeMap src.makeMap).valAt [] := by + rw [valAt_sub, makeMap_valAt_nil, makeMap_valAt_nil, hroot] + have hT : ∀ b r, T.valAt (z.focus ++ b :: r) = z.trie.valAt (z.focus ++ b :: r) := + fun b r => hout _ (focus_cons_ne z b r) + split + · next hE => + apply finish_keep + · intro k hk; exact hout k (ne_of_off hk) + · exact hroot' + · intro b r + rw [valAt_sub, valAt_makeMap, valAt_makeMap src, (focusNode_isEmptyMap_iff src).mp hE b r, + subVal_none_right, hT] + · split + · next _ hE => + apply finish_keep + · intro k hk; exact hout k (ne_of_off hk) + · exact hroot' + · intro b r + have h0 := (focusNode_isEmptyMap_iff _).mp hE b r + simp only [withTrie_trie, withTrie_focus] at h0 + rw [valAt_sub, valAt_makeMap, ← hT, h0, subVal_none_left] + · apply finish_graft _ _ _ _ hout hroot' + intro b r + rw [valAt_sub, valAt_sub, valAt_focusNode_cons, valAt_focusNode_cons, valAt_makeMap, + valAt_makeMap] + simp only [withTrie_trie, withTrie_focus]; rw [hT] + have offFocus : ∀ (v : V) k, k ≠ z.focus → (z.trie.setVal z.focus v).2.valAt k = z.trie.valAt k := + fun v k hk => by rw [valAt_setVal, if_neg hk] + have offFocus' : ∀ k, k ≠ z.focus → (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k := + fun k hk => by rw [valAt_removeVal, if_neg hk] + unfold subtractInto + cases hz : z.val with + | none => + cases hs : src.val with + | none => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some ov => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some sv => + cases hs : src.val with + | none => + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some ov => + cases hr : (ops.psub sv ov).resolve sv ov with + | none => + simp only [apply_ite Prod.snd, hr] + rw [ite_nodeStatus_graft hbeq, removeVal_eq'] + exact tail (z.trie.removeVal z.focus).2 offFocus' + (by rw [valAt_removeVal, if_pos rfl, hz, hs]; exact hr.symm) + | some v => + simp only [apply_ite Prod.snd, hr] + rw [ite_nodeStatus_graft hbeq] + exact tail (z.trie.setVal z.focus v).2 (offFocus v) + (by rw [valAt_setVal, if_pos rfl, hz, hs]; exact hr.symm) + +/-- `join_into` writes the join of the two subtries, focus values included. -/ +theorem joinInto_eq {ops : ValOps V} (hbeq : LawfulBeqOps ops) (src : PZip V) : + (z.joinInto ops src).2 = z.withTrie (z.trie.replaceAt z.focus (join ops z.makeMap src.makeMap)) := by + have tail : ∀ T : PrunedMap V, (∀ k, k ≠ z.focus → T.valAt k = z.trie.valAt k) → + T.valAt z.focus = joinVal ops z.val src.val → + (if src.focusNode.isEmptyMap = true then z.withTrie T + else z.withTrie (T.graftBelow z.focus (join ops (z.withTrie T).focusNode src.focusNode))) + = z.withTrie (z.trie.replaceAt z.focus (join ops z.makeMap src.makeMap)) := by + intro T hout hroot + have hroot' : T.valAt z.focus = (join ops z.makeMap src.makeMap).valAt [] := by + rw [valAt_join, makeMap_valAt_nil, makeMap_valAt_nil, hroot] + split + · next hE => + apply finish_keep + · intro k hk; exact hout k (ne_of_off hk) + · exact hroot' + · intro b r + rw [valAt_join, valAt_makeMap, valAt_makeMap src, (focusNode_isEmptyMap_iff src).mp hE b r, + joinVal_none_right] + exact hout _ (focus_cons_ne z b r) + · apply finish_graft _ _ _ _ hout hroot' + intro b r + rw [valAt_join, valAt_join, valAt_focusNode_cons, valAt_focusNode_cons, valAt_makeMap, + valAt_makeMap] + simp only [withTrie_trie, withTrie_focus] + rw [hout _ (focus_cons_ne z b r)] + have offFocus : ∀ (v : V) k, k ≠ z.focus → (z.trie.setVal z.focus v).2.valAt k = z.trie.valAt k := + fun v k hk => by rw [valAt_setVal, if_neg hk] + have offFocus' : ∀ k, k ≠ z.focus → (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k := + fun k hk => by rw [valAt_removeVal, if_neg hk] + unfold joinInto + cases hz : z.val with + | none => + cases hs : src.val with + | none => + simp only [ite_beqT_graft' hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some mv => + simp only [ite_beqT_graft' hbeq] + exact tail (z.trie.setVal z.focus mv).2 (offFocus mv) (by rw [valAt_setVal, if_pos rfl, hz, hs]; rfl) + | some sv => + cases hs : src.val with + | none => + simp only [ite_beqT_graft' hbeq] + exact tail z.trie (fun _ _ => rfl) (by rw [hz, hs]; exact hz) + | some mv => + cases hr : (ops.pjoin sv mv).resolve sv mv with + | none => + simp only [hr, ite_beqT_graft' hbeq, removeVal_eq'] + exact tail (z.trie.removeVal z.focus).2 offFocus' (by rw [valAt_removeVal, if_pos rfl, hz, hs]; exact hr.symm) + | some v => + simp only [hr, ite_beqT_graft' hbeq] + exact tail (z.trie.setVal z.focus v).2 (offFocus v) (by rw [valAt_setVal, if_pos rfl, hz, hs]; exact hr.symm) + +/-- `restrict` is `PathMap::restrict` on the two subtries: a source focus value +keeps everything, and otherwise a path is kept when a *non-empty* prefix of it is +valued in the source — so the destination's focus value goes. -/ +theorem restrict_eq {ops : ValOps V} (hbeq : LawfulBeqOps ops) (src : PZip V) : + (z.restrict ops src).2 = z.withTrie (z.trie.replaceAt z.focus + (if src.val.isSome then z.makeMap else restrictBelowRoot z.makeMap src.makeMap)) := by + unfold restrict + by_cases hs : src.val.isSome = true + · simp only [hs, if_true] + apply finish_keep + · intro _ _; rfl + · rw [makeMap_valAt_nil]; rfl + · intro b r; rw [valAt_makeMap] + · simp only [hs, Bool.false_eq_true, if_false] + have hv : ∀ q, validatedBy src.focusNode q = validatedBy src.makeMap q := + validatedBy_congr (fun c r => by rw [valAt_focusNode_cons, valAt_makeMap]) + have hroot : (z.trie.removeVal z.focus).2.valAt z.focus = + (restrictBelowRoot z.makeMap src.makeMap).valAt [] := by + rw [valAt_removeVal, if_pos rfl, valAt_restrictBelowRoot]; rfl + have hout : ∀ k, k ≠ z.focus → (z.trie.removeVal z.focus).2.valAt k = z.trie.valAt k := + fun k hk => by rw [valAt_removeVal, if_neg hk] + rw [removeVal_eq'] + simp only [apply_ite Prod.snd] + rw [ite_nodeStatus_graft hbeq] + split + · next hE => + show z.withTrie ((z.trie.removeVal z.focus).2.removeBelow z.focus) = _ + apply finish_keep + · intro k hk; rw [valAt_removeBelow_off _ hk] + exact hout k (ne_of_off hk) + · rw [valAt_removeBelow_self]; exact hroot + · intro b r + rw [valAt_removeBelow_cons, valAt_restrictBelowRoot, ← hv, + validatedBy_congr (b := empty) (fun c r => (isEmptyMap_iff _).mp hE _), validatedBy_empty] + rfl + · split + · next _ hE => + apply finish_keep _ _ _ (fun k hk => hout k (ne_of_off hk)) hroot + intro b r + have h0 := (focusNode_isEmptyMap_iff _).mp hE b r + simp only [withTrie_trie, withTrie_focus] at h0 + rw [valAt_restrictBelowRoot, valAt_makeMap, ← hout _ (focus_cons_ne z b r), h0] + split <;> rfl + · rw [withTrie_graft_eq] + apply finish_graft _ _ _ _ hout hroot + intro b r + rw [valAt_restrictBelowRoot, valAt_restrictBelowRoot, hv, valAt_focusNode_cons, valAt_makeMap] + simp only [withTrie_trie, withTrie_focus] + rw [hout _ (focus_cons_ne z b r)] + +theorem removeBranches_eq : + (z.removeBranches).2 = z.withTrie (z.trie.replaceAt z.focus (withRootOf z.makeMap empty)) := by + apply finish_keep + · intro k hk; rw [valAt_removeBelow_off _ hk] + · rw [valAt_removeBelow_self, valAt_withRootOf_nil, makeMap_valAt_nil]; rfl + · intro b r; rw [valAt_removeBelow_cons, valAt_withRootOf_cons]; rfl + +/-- Where the focus does not exist, nothing lies at or below it. -/ +theorem valAt_of_not_pathExists (h : z.pathExists = false) (r : Path) : + z.trie.valAt (z.focus ++ r) = none := by + cases hv : z.trie.valAt (z.focus ++ r) with + | none => rfl + | some v => + exfalso + have hmem : z.focus ++ r ∈ z.trie.keys := + mem_keys_of_lookup_isSome (l := z.trie.entries) + (show (z.trie.entries.lookup (z.focus ++ r)).isSome = true by + rw [show z.trie.entries.lookup (z.focus ++ r) = some v from hv]; rfl) + have he : z.trie.pathExists z.focus = true := by + simp only [PrunedMap.pathExists, Bool.or_eq_true, List.any_eq_true] + exact Or.inr ⟨_, hmem, (Path.isPrefixOf_iff _ _).mpr ⟨r, rfl⟩⟩ + rw [show z.pathExists = z.trie.pathExists z.focus from rfl, he] at h + cases h + +theorem prepend_nil (m : PrunedMap V) : m.prepend [] = m := by + apply ext; intro k + show (m.prepend []).valAt k = m.valAt k + rw [valAt_prepend] + have := Path.stripPrefix_append [] k + simp only [List.nil_append] at this + rw [this] + +/-- `insert_prefix` moves the whole subtrie, focus value included. -/ +theorem insertPrefix_eq (pre : Path) : + (z.insertPrefix pre).2 = z.withTrie (z.trie.replaceAt z.focus (z.makeMap.prepend pre)) := by + unfold insertPrefix + by_cases hx : z.pathExists = true + · simp only [hx, Bool.not_true, Bool.false_eq_true, if_false] + by_cases hp : pre.isEmpty = true + · simp only [hp, if_true] + rw [List.isEmpty_iff.mp hp, prepend_nil] + apply finish_keep + · intro _ _; rfl + · rw [makeMap_valAt_nil]; rfl + · intro b r; rw [valAt_makeMap] + · simp only [hp, Bool.false_eq_true, if_false] + exact graftMap_eq z _ + · have hx' : z.pathExists = false := by simpa using hx + simp only [hx', Bool.not_false, if_true] + have hnone : ∀ r, z.trie.valAt (z.focus ++ r) = none := valAt_of_not_pathExists z hx' + apply finish_keep + · intro _ _; rfl + · rw [valAt_prepend] + have := hnone []; rw [List.append_nil] at this; rw [this] + split <;> first | rfl | (rw [valAt_makeMap, hnone]) + · intro b r + rw [valAt_prepend, hnone] + split <;> first | rfl | (rw [valAt_makeMap, hnone]) + +/-- `meet_2` writes the meet of the two sources' subtries, focus values included. -/ +theorem meet2_eq {ops : ValOps V} (a b : PZip V) : + (z.meet2 ops a b).2 = z.withTrie (z.trie.replaceAt z.focus (meet ops a.makeMap b.makeMap)) := + graftMap_eq z _ + +/-- `join_k_path_into k` writes `dropHead` of the subtrie. -/ +theorem joinKPathInto_eq {ops : ValOps V} (k : Nat) : + (z.joinKPathInto ops k).2 = + if k == 0 then z else z.withTrie (z.trie.replaceAt z.focus (dropHead ops z.makeMap k)) := by + unfold joinKPathInto + split + · rfl + · exact graftMap_eq z _ + +/-- `meet_k_path_into k` grafts the meet of the subtries `k` bytes down, or the +empty map when there are none. -/ +theorem meetKPathInto_snd {ops : ValOps V} (k : Nat) : + (z.meetKPathInto ops k).2 = z.graftMap + ((((z.trie.subtrie z.focus).kPaths k).foldl (meetStep ops z.trie z.focus) none).getD empty) := by + unfold meetKPathInto + dsimp only + cases ((z.trie.subtrie z.focus).kPaths k).foldl (meetStep ops z.trie z.focus) none <;> rfl + +/-- `remove_prefix n` ascends, then grafts what was the subtrie at the focus. -/ +theorem removePrefix_snd (n : Nat) : + (z.removePrefix n).2 = (z.ascend n).2.graftMap z.makeMap := rfl + +/-- `take_map` removes the focus's subtrie, value included… -/ +theorem takeMap_snd : (z.takeMap).2 = z.withTrie (z.trie.replaceAt z.focus empty) := by + apply finish_keep + · intro k hk + show (z.trie.removeAt z.focus).valAt k = _ + rw [valAt_removeAt, isPrefixOf_off hk]; rfl + · show (z.trie.removeAt z.focus).valAt z.focus = _ + rw [valAt_removeAt, if_pos ((Path.isPrefixOf_iff _ _).mpr ⟨[], by simp⟩)]; rfl + · intro b r + show (z.trie.removeAt z.focus).valAt _ = _ + rw [valAt_removeAt, if_pos ((Path.isPrefixOf_iff _ _).mpr ⟨_, rfl⟩)]; rfl + +/-- …and returns it: `make_map` before the removal, or `none` when there was +nothing there. -/ +theorem takeMap_fst : (z.takeMap).1 = if z.makeMap.isEmptyMap then none else some z.makeMap := by + have htaken : (match z.val with + | some v => (z.focusNode.setVal [] v).2 + | none => z.focusNode) = z.makeMap := by + apply ext; intro k + show PrunedMap.valAt _ k = z.makeMap.valAt k + cases hv : z.val with + | some v => + simp only + rw [valAt_setVal, valAt_focusNode, valAt_makeMap] + by_cases hk : k = [] <;> simp [hk]; exact hv.symm + | none => + simp only + rw [valAt_focusNode, valAt_makeMap] + by_cases hk : k = [] <;> simp [hk]; exact hv.symm + have hemp : (z.focusNode.isEmptyMap && z.val.isNone) = z.makeMap.isEmptyMap := by + apply Bool.eq_iff_iff.mpr + rw [Bool.and_eq_true, focusNode_isEmptyMap_iff, isEmptyMap_iff, Option.isNone_iff_eq_none] + constructor + · rintro ⟨h1, h2⟩ k + cases k with + | nil => rw [makeMap_valAt_nil]; exact h2 + | cons b r => rw [valAt_makeMap]; exact h1 b r + · intro h + exact ⟨fun b r => by rw [← valAt_makeMap]; exact h _, by rw [← makeMap_valAt_nil]; exact h _⟩ + unfold takeMap + simp only + rw [hemp] + by_cases h : z.makeMap.isEmptyMap = true + · rw [if_pos h, if_pos h] + · rw [if_neg h, if_neg h]; exact congrArg some htaken + +end PZip +end PrunedModel diff --git a/lean/PrunedModel/Spec.lean b/lean/PrunedModel/Spec.lean new file mode 100644 index 00000000..ff5beab7 --- /dev/null +++ b/lean/PrunedModel/Spec.lean @@ -0,0 +1,176 @@ +import PrunedModel.Write + +/-! +# What this model claims + +`PathMapModel/Spec.lean` has to say, operation by operation, which valueless +locations survive it. This model has a single claim instead, and everything +else is a consequence. + +**There is no dangling path.** A location that exists with nothing below it +carries a value — not as an invariant the constructors maintain, but because +existence is *defined* as "some key runs through here". `no_dangling` is the +proof, and its shortness is the measure of what dropping the `Option` buys. + +The consequence the fuzzer trades on: `prune_path` has nothing to do, so the +crate must report `0` for it on any trie built from this subset. Each time it +does not, some operation in the subset leaked a location that leads nowhere. + +The `#guard`s at the end are the executable half — small concrete tries run +through the definitions and checked at elaboration time. They catch the class +of mistake that type-checks right through: a swapped argument order, a `take` +that should have been a `drop`. +-/ + +namespace PrunedModel +namespace PrunedMap + +open PathMapModel + +variable {V : Type} + +/-! ## Keys and lookup -/ + +/-- Every path is a prefix of itself. -/ +theorem isPrefixOf_self : ∀ p : Path, (p ≼ p) = true + | [] => rfl + | _ :: as => by simp [Path.isPrefixOf, isPrefixOf_self as] + +/-- A key is bound: `lookup` finds whatever `map (·.1)` saw. -/ +theorem lookup_isSome_of_mem_keys {l : List (Path × V)} {p : Path} + (h : p ∈ l.map (·.1)) : (l.lookup p).isSome = true := by + obtain ⟨kv, hmem, heq⟩ := List.mem_map.mp h + exact List.lookup_isSome_iff.mpr ⟨kv, hmem, by simp [heq]⟩ + +/-- …and conversely, `lookup` only succeeds on a key. -/ +theorem mem_keys_of_lookup_isSome {l : List (Path × V)} {p : Path} + (h : (l.lookup p).isSome = true) : p ∈ l.map (·.1) := by + obtain ⟨kv, hmem, hb⟩ := List.lookup_isSome_iff.mp h + exact List.mem_map.mpr ⟨kv, hmem, (eq_of_beq hb).symm⟩ + +/-- Holding a value entails existing. -/ +theorem pathExists_of_valAt {t : PrunedMap V} {p : Path} {v : V} + (h : t.valAt p = some v) : t.pathExists p = true := by + have hmem : p ∈ t.keys := + mem_keys_of_lookup_isSome (l := t.entries) (p := p) + (show (t.entries.lookup p).isSome = true by + rw [show t.entries.lookup p = some v from h]; rfl) + cases hp : p.isEmpty with + | true => simp [pathExists, hp] + | false => + simp only [pathExists, hp, Bool.false_or, List.any_eq_true] + exact ⟨p, hmem, isPrefixOf_self p⟩ + +/-! ## The claim -/ + +/-- **No dangling paths.** A location that some key runs through, and that has +nothing strictly below it, carries a value. + +`pathExists` admits the root unconditionally — `PathMap::new().read_zipper()` +reports `path_exists() == true`, and the root of an empty trie is the one +location that exists without leading anywhere — so the hypothesis here is its +other disjunct. Together with "nothing strictly below `p`", the key running +through `p` can only be `p` itself. -/ +theorem no_dangling {t : PrunedMap V} {p : Path} + (hx : t.keys.any (fun k => p ≼ k) = true) (hb : t.belowIsEmpty p = true) : + (t.valAt p).isSome = true := by + obtain ⟨k, hk, hpk⟩ := List.any_eq_true.mp hx + have hkp : k == p := by simpa [hpk] using (List.all_eq_true.mp hb) k hk + exact lookup_isSome_of_mem_keys (by simpa [keys, eq_of_beq hkp] using hk) + +/-- Hence `prune_path` has nothing to prune, and reports `0`… -/ +theorem prunePath_eq_zero (t : PrunedMap V) (p : Path) : (t.prunePath p).1 = 0 := rfl + +/-- …and leaves the trie alone. -/ +theorem prunePath_id (t : PrunedMap V) (p : Path) : (t.prunePath p).2 = t := rfl + +/-- The empty trie has no values, so `is_empty` and "no keys" coincide. -/ +theorem isEmptyMap_empty : (empty : PrunedMap V).isEmptyMap = true := rfl + +/-- The root of the empty trie still exists — the one location that does. -/ +theorem pathExists_root (t : PrunedMap V) : t.pathExists [] = true := by + simp [pathExists] + +/-! ## Executable checks + +Concrete tries, run through the definitions at elaboration time. `t1` branches +at the root and carries a value at an interior location; `t2` is a single chain +beside a single leaf, which is the shape every dangling-path question is about. -/ + +section Guards + +private def t1 : PrunedMap UInt64 := mk' [([0, 1], 7), ([0], 3), ([2], 9)] +private def t2 : PrunedMap UInt64 := mk' [([0, 1, 2], 5), ([3], 7)] + +-- Canonical form: sorted depth-first, so a prefix precedes its extensions. +#guard t1.keys == [[0], [0, 1], [2]] +#guard t1.paths == [[], [0], [0, 1], [2]] +#guard t1.valAt [0] == some 3 +#guard t1.valAt [1] == none +#guard t1.valCount [] == 3 && t1.valCount [0] == 2 +#guard t1.childMask [] == ([0, 2] : List UInt8) +#guard t1.childCount [0] == 1 && t1.childCount [0, 1] == 0 + +-- Existence is the prefix closure of the keys, and nothing more. +#guard t1.pathExists [0, 1] && !t1.pathExists [1] && !t1.pathExists [0, 1, 2] +#guard t2.pathExists [0] && t2.pathExists [0, 1] && !t2.pathExists [0, 2] + +-- `no_dangling`, concretely: the one location with nothing below it is valued. +#guard t1.belowIsEmpty [0, 1] && (t1.valAt [0, 1]).isSome + +-- Removing a value removes the chain that existed only to reach it… +#guard (t2.removeVal [0, 1, 2]).2.keys == [[3]] +#guard !(t2.removeVal [0, 1, 2]).2.pathExists [0] +-- …but not a location some other key still runs through. +#guard (t1.removeVal [0]).2.keys == [[0, 1], [2]] && (t1.removeVal [0]).2.pathExists [0] + +-- `set_val` reports the value it replaced. +#guard (t1.setVal [0] 11).1 == some 3 && (t1.setVal [0] 11).2.valAt [0] == some 11 +#guard (t1.setVal [5] 11).1 == none && (t1.setVal [5] 11).2.keys == [[0], [0, 1], [2], [5]] + +-- Grafting an empty node below a *valued* location keeps the location… +#guard (t1.graftBelow [0] empty).keys == [[0], [2]] +-- …and below a valueless one takes the whole chain with it. This is the +-- model's central disagreement with `pathmap` 0.4.0, which leaves `[0]` and +-- `[0,1]` behind as dangling paths. +#guard (t2.graftBelow [0, 1] empty).keys == [[3]] +#guard !(t2.graftBelow [0, 1] empty).pathExists [0] + +-- Sub-tries carry the focus value as their root value. +#guard (t1.subtrie [0]).keys == [[], [1]] && (t1.subtrie [0]).valAt [] == some 3 +#guard (t1.subtrie [9]).isEmptyMap + +-- Algebra. `u64`'s `psubtract` annihilates on equal values, and its `pjoin` +-- and `pmeet` are left-biased projections. +#guard (sub u64Ops t1 t1).isEmptyMap +#guard (sub u64Ops t1 (mk' [([0], 3)])).keys == [[0, 1], [2]] +#guard (meet u64Ops t1 t1).keys == t1.keys +#guard (meet u64Ops t1 (mk' [([0], 99)])).entries == [([0], 3)] +#guard (join u64Ops t1 empty).entries == t1.entries +#guard (join u64Ops (mk' [([0], 1)]) (mk' [([2], 4)])).entries == [([0], 1), ([2], 4)] + +-- `prestrict` validates on a non-empty prefix only, so the root value of the +-- filter is invisible at node level. +#guard (restrictBelowRoot t1 (mk' [([0], 1)])).keys == [[0], [0, 1]] +#guard (restrictBelowRoot t1 (mk' [([], 1)])).isEmptyMap + +-- `drop_head` keeps the values sitting at depth exactly `k`: `[3]` is at depth +-- 1, so its value becomes the root value of the joined map. +#guard (dropHead u64Ops t2 1).entries == [([], 7), ([1, 2], 5)] +#guard (dropHead u64Ops t2 0).entries == t2.entries + +-- A write zipper at the map root, as the fuzzer builds it. +private def z2 : PZip UInt64 := { trie := t2, root := [], path := [0, 1] } + +-- `remove_branches` at a valueless focus takes the focus with it: it has no +-- value of its own and now nothing below, so it stops existing. +#guard (PZip.removeBranches z2).1 && (PZip.removeBranches z2).2.trie.keys == [[3]] +-- Nothing to prune afterwards, which is what the crate is checked against. +#guard (PZip.prunePath (PZip.removeBranches z2).2).1 == 0 +-- `remove_val` at a location with no value is a no-op, flag and all. +#guard (PZip.removeVal z2).1 == none && (PZip.removeVal z2).2.trie.entries == t2.entries + +end Guards + +end PrunedMap +end PrunedModel diff --git a/lean/PrunedModel/Write.lean b/lean/PrunedModel/Write.lean new file mode 100644 index 00000000..8df46f17 --- /dev/null +++ b/lean/PrunedModel/Write.lean @@ -0,0 +1,421 @@ +import PrunedModel.Zipper + +/-! +# The write zipper, restricted to the dangling-path-free subset + +Two invariants shape the whole API: + +1. **A subtrie includes the value at its root.** The subtrie at a zipper's + focus therefore includes the focus value, and every operation on subtries — + `graft`, `graft_map`, `make_map`, `take_map`, `join_into`, `join_map_into`, + `meet_into`, `subtract_into`, `meet_2`, `restrict`, `insert_prefix`, + `remove_prefix`, `join_k_path_into` — treats it as part of the subtrie. This + is `focus_value_consistency` (issue #104); the node-level primitives + underneath still see only what lies strictly below a location. Master's + crate does not implement #104 yet, so for these operations the model states + what the crate should do, not what it does. + +2. **There is no prune flag.** In `PathMapModel` every mutating operation takes + one, because a write leaves a dangling path behind unless it is passed — and + even then the flag's effect is a function of where the internal node boundary + happens to fall (`PathMapModel/Fuzz.lean` therefore always passes `false` and + compares nothing). Here existence is derived from the keys, so removing the + last value under a chain removes the chain, with nothing to opt into. The + crate is driven with `prune = true` and must agree. + +## What is missing, and why + +* **`create_path`** — its entire purpose is to make a location that carries no + value. It cannot be modelled here and is not in the fuzzer's table. +* **`remove_val(false)`** — the non-pruning removal leaves the chain behind. + Only `remove_val(true)` is in the subset. +* **A write zipper below the map root** — see `PrunedModel/Zipper.lean`. + +Everything else in `ZipperWriting` is here. Several of those operations *can* +still leave a dangling path in `pathmap` 0.4.0 — `graft` of an empty source is +the clearest case — and the model says they must not. Those divergences are the +output this model exists to produce, so they are specified, not skipped; see +`PrunedModel/Fuzz.lean`. +-/ + +namespace PrunedModel +namespace PZip + +open PathMapModel + +variable {V : Type} (z : PZip V) + +/-- Replace the trie, keeping the cursor. -/ +def withTrie (t : PrunedMap V) : PZip V := { z with trie := t } + +/-! ## Values at the focus -/ + +/-- `ZipperWriting::get_val_mut` — the same observation as `val`, mutably. +Returns `some` exactly when `val` does; it never creates anything. -/ +def getValMut : Option V := z.val + +/-- `ZipperWriting::set_val`: sets the value at the focus, creating the path if +it did not exist. Returns the replaced value. -/ +def setVal (v : V) : Option V × PZip V := + let (old, t) := z.trie.setVal z.focus v + (old, z.withTrie t) + +/-- Writing through the reference `get_val_mut` returns. + +Specified as: where there is a value, this is `set_val`; where there is not, it +is a no-op — in particular it must **not** create the path, which is what +separates it from `set_val`. -/ +def getValMutWrite (v : V) : Option V × PZip V := + match z.val with + | some old => (some old, (z.setVal v).2) + | none => (none, z) + +/-- `ZipperWriting::get_val_or_set_mut`: the value at the focus, inserting +`default` if there is none. -/ +def getValOrSetMut (d : V) : V × PZip V := + match z.val with + | some v => (v, z) + | none => (d, (z.setVal d).2) + +/-- `ZipperWriting::get_val_or_set_mut_with`: as above, but the value comes from +a closure. + +The documented contract is that the closure supplies the value "if no value +exists", so it must run **exactly when the focus has no value** — running it +otherwise is observable to any caller whose closure has a side effect. The +second component records whether it ran, and the fuzzer compares that too. -/ +def getValOrSetMutWith (d : V) : V × Bool × PZip V := + match z.val with + | some v => (v, false, z) + | none => (d, true, (z.setVal d).2) + +/-- `ZipperWriting::remove_val(true)`. + +The chain above the removed value goes with it, because nothing in this model +can exist without leading to a value. `pathmap`'s own `remove_val(true)` prunes +only as far as the zipper's root, which is why the fuzzer keeps the write zipper +at the map root. -/ +def removeVal : Option V × PZip V := + match z.val with + | none => (none, z) + | some v => (some v, z.withTrie (z.trie.removeVal z.focus).2) + +/-! ## Pruning + +`prune_path` and `prune_ascend` are in the fuzzer's table but have nothing to do +here: a trie built from this subset has no dangling tip to prune (see +`Spec.no_dangling_tip`), so both are no-ops returning `0`. A non-zero count +from the crate is therefore a *finding* — it means some operation in the subset +left a dangling path for `prune_path` to find. -/ + +/-- `ZipperWriting::prune_path`: `0`, and nothing removed. -/ +def prunePath : Nat × PZip V := (0, z) + +/-- `ZipperWriting::prune_ascend`: `prune_path` followed by ascending that far, +so also a no-op. -/ +def pruneAscend : Nat × PZip V := (0, z) + +/-! ## Removing subtries -/ + +/-- `ZipperWriting::remove_branches`: delete everything strictly below the focus. +The value at the focus survives; if there is none, the focus stops existing. +Returns whether anything was removed. -/ +def removeBranches : Bool × PZip V := + (!z.focusNodeIsEmpty, z.withTrie (z.trie.removeBelow z.focus)) + +/-- `ZipperWriting::remove_unmasked_branches`: keep only the child bytes set in +`mask`; delete the rest along with their subtries. -/ +def removeUnmaskedBranches (mask : ByteMask) : PZip V := + let doomed := z.childMask.filter (fun b => !mask.contains b) + z.withTrie <| doomed.foldl (fun t b => t.removeAt (z.focus ++ [b])) z.trie + +/-! ## Grafting -/ + +/-- Replace the subtrie at the focus with `m`, treating `m` as a whole map: its +root value becomes the focus value (or clears it), and its branches become the +focus's branches. This is `ZipperWriting::graft_map`. -/ +def graftMap (m : PrunedMap V) : PZip V := + let t := z.trie.graftBelow z.focus m + z.withTrie <| + match m.valAt [] with + | some v => (t.setVal z.focus v).2 + | none => (t.removeVal z.focus).2 + +/-- `ZipperWriting::graft`: graft the subtrie at `src`'s focus, root value +included. + +Note what this says when the source is empty: the focus loses its value and its +branches, so — having nothing left to lead to — it stops existing, along with +any ancestor chain that existed only for it. `pathmap` 0.4.0 leaves that chain +behind as a dangling path. The model specifies the removal. -/ +def graft (src : PZip V) : PZip V := z.graftMap src.makeMap + +/-- `ZipperWriting::graft_src_at`: graft the subtrie `k` bytes below `src`'s +focus. -/ +def graftSrcAt (src : PZip V) (k : Path) : PZip V := + z.graftMap (src.trie.subtrie (src.focus ++ k)) + +/-- `ZipperWriting::graft_masked_branches`: graft the source's child branches for +each byte set in `mask`. + +Each set bit is a `graft_src_at` of the source's corresponding child, so the +child's *value* travels with it, and a set bit whose branch is absent from the +source leaves that branch absent here — grafting nothing removes. With +`removeUnset`, branches for clear bits are removed first, so `child_mask` +afterwards is a subset of `mask`; without it they are left alone. + +`WriteZipperCore` overrides the trait's default with a native implementation, so +this really compares two implementations of one contract. -/ +def graftMaskedBranches (src : PZip V) (mask : ByteMask) (removeUnset : Bool) : PZip V := + let z0 := if removeUnset then (z.removeBranches).2 else z + z0.withTrie <| mask.foldl (fun t b => + let child := z0.focus ++ [b] + let m := src.trie.subtrie (src.focus ++ [b]) + let t1 := t.graftBelow child m + match m.valAt [] with + | some v => (t1.setVal child v).2 + | none => (t1.removeVal child).2) z0.trie + +/-- `ZipperWriting::take_map`: remove the subtrie at the focus (value included) +and return it as a map. `none` when there was nothing to take. -/ +def takeMap : Option (PrunedMap V) × PZip V := + let rv := z.val + let below := z.focusNode + let z1 := z.withTrie (z.trie.removeAt z.focus) + let taken := + match rv with + | some v => (below.setVal [] v).2 + | none => below + (if below.isEmptyMap && rv.isNone then none else some taken, z1) + +/-! ## Path surgery -/ + +/-- `ZipperWriting::insert_prefix`: put `pre` in front of every path in the +subtrie, the path to the focus value included. The cursor stays where it is. +An empty prefix is the identity. Returns whether the focus exists; a focus that +does not leaves the trie unchanged. -/ +def insertPrefix (pre : Path) : Bool × PZip V := + if !z.pathExists then (false, z) + else if pre.isEmpty then (true, z) + else (true, z.graftMap (z.makeMap.prepend pre)) + +/-- `ZipperWriting::remove_prefix`: move the focused subtrie up by `n` bytes, +replacing the subtrie at the new focus — value included, so the old focus value +replaces the new focus's, or clears it. Returns how many bytes it ascended. -/ +def removePrefix (n : Nat) : Nat × PZip V := + let subtrie := z.makeMap + let (ascended, z1) := z.ascend n + (ascended, z1.graftMap subtrie) + +/-! ## Algebraic operations + +`AlgebraicStatus` is decided structurally: `Identity` exactly when the output +equals the input, `None` when the output is empty, `Element` otherwise. +`Identity(COUNTER_IDENT)` — the output equals the *source* — is reported as +`Element` by `pathmap`, and the model agrees, because the output still differs +from `self`. -/ + +variable (ops : ValOps V) + +/-- The status of replacing `before` with `after`. -/ +def nodeStatus (before after : PrunedMap V) : AlgStatus := + if after.isEmptyMap then .none + else if PrunedMap.beqT ops after before then .identity + else .element + +/-- `ZipperWriting::join_into`: union the subtrie at the source's focus into the +subtrie at this focus, focus values included. -/ +def joinInto (src : PZip V) : AlgStatus × PZip V := + let (valStatus, z1) := + match z.val, src.val with + | some sv, some mv => + let r := ops.pjoin sv mv + (AlgStatus.ofValRes r, + match r.resolve sv mv with + | some v => (z.setVal v).2 + | none => (z.removeVal).2) + | none, some mv => (AlgStatus.element, (z.setVal mv).2) + | some _, none => (AlgStatus.identity, z) + | none, none => (AlgStatus.none, z) + let selfB := z1.focusNode + let srcB := src.focusNode + let r := PrunedMap.join ops selfB srcB + let nodeSt := + if srcB.isEmptyMap then (if selfB.isEmptyMap then AlgStatus.none else AlgStatus.identity) + else if PrunedMap.beqT ops r selfB then AlgStatus.identity else AlgStatus.element + let z2 := + if srcB.isEmptyMap then z1 + else if PrunedMap.beqT ops r selfB then z1 + else z1.withTrie (z1.trie.graftBelow z1.focus r) + (AlgStatus.merge nodeSt valStatus true true, z2) + +/-- `ZipperWriting::join_map_into`: union a consumed map into the focus. + +It short-circuits: when the map has no root node the node status is +returned directly and the value status computed above is discarded — even though +the value has already been written. -/ +def joinMapInto (m : PrunedMap V) : AlgStatus × PZip V := + -- `merge` is called with both "was none" flags set, as the crate does, so the + -- second component is carried only for symmetry with the other operations. + let (valStatus, _valWasNone, z1) := + match z.val, m.valAt [] with + | some sv, some mv => + let r := ops.pjoin sv mv + (AlgStatus.ofValRes r, false, + match r.resolve sv mv with + | some v => (z.setVal v).2 + | none => (z.removeVal).2) + | none, some mv => (AlgStatus.element, true, (z.setVal mv).2) + | some _, none => (AlgStatus.identity, false, z) + | none, none => (AlgStatus.none, true, z) + let srcB := (m.removeVal []).2 + if srcB.isEmptyMap then + -- Note the asymmetry with `join_into`: this branch tests + -- `self.get_focus().is_none()` (does a node exist at all?), not + -- `node_is_empty()`. The two coincide here, since a location that exists + -- has something below it or a value of its own. + -- + -- The node status is *merged* with the value status rather than returned on + -- its own. It used to be returned directly -- an early `return` that + -- discarded a value the operation had already written -- which is + -- issue #139, fixed by PR #142 (`276fca0`). + (AlgStatus.merge + (if z1.pathExists then AlgStatus.identity else AlgStatus.none) valStatus true true, z1) + else + let selfB := z1.focusNode + let r := PrunedMap.join ops selfB srcB + let nodeSt := if PrunedMap.beqT ops r selfB then AlgStatus.identity else AlgStatus.element + let z2 := if nodeSt == .identity then z1 else z1.withTrie (z1.trie.graftBelow z1.focus r) + (AlgStatus.merge nodeSt valStatus true true, z2) + +/-- `ZipperWriting::meet_into`: intersect the focus's subtrie with the source's. + +The value step runs first and can prune the focus out from under the node step. -/ +def meetInto (src : PZip V) : AlgStatus × PZip V := + let (valStatus, valWasNone, z1) := + match z.val, src.val with + | some sv, some ov => + let r := ops.pmeet sv ov + (AlgStatus.ofValRes r, false, + match r.resolve sv ov with + | some v => (z.setVal v).2 + | none => (z.removeVal).2) + | none, some _ => (AlgStatus.none, true, z) + | some _, none => (AlgStatus.none, false, (z.removeVal).2) + | none, none => (AlgStatus.none, true, z) + let selfB := z1.focusNode + let srcB := src.focusNode + if selfB.isEmptyMap then + (AlgStatus.merge .none valStatus true valWasNone, z1) + else if srcB.isEmptyMap then + (AlgStatus.merge .none valStatus false valWasNone, + z1.withTrie (z1.trie.removeBelow z1.focus)) + else + let r := PrunedMap.meet ops selfB srcB + let st := nodeStatus ops selfB r + let z2 := if st == .identity then z1 else z1.withTrie (z1.trie.graftBelow z1.focus r) + (AlgStatus.merge st valStatus false valWasNone, z2) + +/-- `ZipperWriting::subtract_into`: remove the source's subtrie from the focus's. + +Pointwise. `PathMapModel` needs a second rule here — where the source has no +node at all, `self`'s subtree survives untouched, dangling paths included — and +that rule is exactly what the missing `Option` makes unnecessary: with nothing +valueless to preserve, "keep verbatim" and "subtract pointwise" agree. -/ +def subtractInto (src : PZip V) : AlgStatus × PZip V := + let (valStatus, valWasNone, z1) := + match z.val, src.val with + | some sv, some ov => + let r := ops.psub sv ov + (AlgStatus.ofValRes r, false, + match r.resolve sv ov with + | some v => (z.setVal v).2 + | none => (z.removeVal).2) + | none, some _ => (AlgStatus.none, true, z) + | some _, none => (AlgStatus.identity, false, z) + | none, none => (AlgStatus.none, true, z) + let selfB := z1.focusNode + let srcB := src.focusNode + if srcB.isEmptyMap then + (AlgStatus.merge (if selfB.isEmptyMap then .none else .identity) valStatus + selfB.isEmptyMap valWasNone, z1) + else if selfB.isEmptyMap then + (AlgStatus.merge .none valStatus true valWasNone, z1) + else + let r := PrunedMap.sub ops selfB srcB + let st := nodeStatus ops selfB r + let z2 := if st == .identity then z1 else z1.withTrie (z1.trie.graftBelow z1.focus r) + (AlgStatus.merge st valStatus false valWasNone, z2) + +/-- `ZipperWriting::meet_2`: replace the subtrie at the focus with the meet of two +source subtries, focus values included. What is already at the focus is not an +operand, so it reports `Element` or `None`, never `Identity`. -/ +def meet2 (a b : PZip V) : AlgStatus × PZip V := + let r := PrunedMap.meet ops a.makeMap b.makeMap + (if r.isEmptyMap then .none else .element, z.graftMap r) + +/-- `ZipperWriting::restrict`: keep only the paths in this subtrie that are +prefixed by a path to a value in the source's subtrie, as `PathMap::restrict` +does. A source focus value keeps the whole subtrie; without one, the focus +value goes. An empty result reports `None`. -/ +def restrict (src : PZip V) : AlgStatus × PZip V := + if src.val.isSome then + (if z.makeMap.isEmptyMap then .none else .identity, z) + else + let removedVal := z.val + let z1 := z.removeVal.2 + let srcB := src.focusNode + let selfB := z1.focusNode + if srcB.isEmptyMap then (.none, z1.withTrie (z1.trie.removeBelow z1.focus)) + else if selfB.isEmptyMap then (.none, z1) + else + let r := PrunedMap.restrictBelowRoot selfB srcB + let st := nodeStatus ops selfB r + if st == .identity then + (if removedVal.isSome then .element else .identity, z1) + else (st, z1.withTrie (z1.trie.graftBelow z1.focus r)) + +/-- `ZipperWriting::restricting`: the mirror image — `self`'s subtrie is replaced +by the source's, restricted by the paths to values in `self`. + +`false`, leaving `self` untouched, when either side has nothing below its focus. -/ +def restricting (src : PZip V) : Bool × PZip V := + if src.focusNodeIsEmpty then (false, z) + else if z.focusNodeIsEmpty then (false, z) + else (true, z.withTrie (z.trie.graftBelow z.focus + (PrunedMap.restrictBelowRoot src.focusNode z.focusNode))) + +/-! ## Collapsing path segments -/ + +/-- `ZipperWriting::join_k_path_into` (a.k.a. `drop_head`): replace the subtrie +at the focus with the join of the subtries `k` bytes below it. Values at +exactly that depth become the focus value; shallower ones, the old focus value +included, are dropped. `k = 0` is the identity. Returns whether the result is +non-empty. -/ +def joinKPathInto (k : Nat) : Bool × PZip V := + let r := PrunedMap.dropHead ops z.makeMap k + (!r.isEmptyMap, if k == 0 then z else z.graftMap r) + +/-- One step of `meet_k_path_into`: meet in the subtrie at `f ++ q`. -/ +def meetStep (t : PrunedMap V) (f : Path) (acc : Option (PrunedMap V)) (q : Path) : + Option (PrunedMap V) := + match acc with + | none => some (t.subtrie (f ++ q)) + | some a => some (PrunedMap.meet ops a (t.subtrie (f ++ q))) + +/-- `ZipperWriting::meet_k_path_into`: strip the leading `k` bytes from every +path below the focus and meet the results. + +Values at depth exactly `k` become the focus value. The meet replaces the whole +subtrie, focus value included: an empty meet is `remove_subtrie`, which is +grafting the empty map. With `k = 0` the only subtrie is the focus's own, so +it is the identity; a focus with no children meets nothing and is emptied. -/ +def meetKPathInto (k : Nat) : Bool × PZip V := + let kps := (z.trie.subtrie z.focus).kPaths k + let result : Option (PrunedMap V) := kps.foldl (meetStep ops z.trie z.focus) none + match result with + | some m => (!m.isEmptyMap, z.graftMap m) + | none => (false, z.graftMap PrunedMap.empty) + +end PZip +end PrunedModel diff --git a/lean/PrunedModel/Zipper.lean b/lean/PrunedModel/Zipper.lean new file mode 100644 index 00000000..b8da5b53 --- /dev/null +++ b/lean/PrunedModel/Zipper.lean @@ -0,0 +1,331 @@ +import PrunedModel.Map + +/-! +# The zipper, over a trie with no dangling paths + +Same cursor as `PathMapModel.Zip` — a trie, the absolute path the zipper was +created at, and the relative path to the focus — and the same read API. What +changes is what the observations *mean*: + +* `path_exists` is now "some value lies at or below here", because that is the + only way to exist. +* `child_mask` is read off the keys rather than off a separate set of locations. +* `descend_until`, `ascend_until_branch`, `to_next_step` and the `k`-path + primitives walk the prefix closure of the keys, which is the whole trie. + +Everything else is a transcription of `PathMapModel.Zipper`, and deliberately so: +the point of the second model is a different *representation* of the same +contract, not a different reading of it. Where the two models disagree, one of +them is wrong, and the fuzzer says which. + +## The write zipper is rooted at the map root + +`PrunedModel`'s fuzzer only ever builds a write zipper at the map root; see +`Fuzz.header`. A write zipper rooted below it holds a node at its own root, +which survives as a dangling path once everything below it is removed, and +`prune_path` is documented not to rise above the zipper's origin. That is a +location that exists without leading to a value, so it is outside this model by +construction rather than by a bug. Off-root *writing* is still covered — the +root-rooted zipper reaches it with `descend_to`. +-/ + +namespace PrunedModel + +open PathMapModel + +/-- A zipper: a trie, the absolute path of the zipper's root, and the relative +path to the focus. -/ +structure PZip (V : Type) where + trie : PrunedMap V + root : Path + path : Path +deriving Repr + +namespace PZip + +variable {V : Type} (z : PZip V) + +/-- `ZipperAbsolutePath::origin_path`: the absolute path of the focus. -/ +def focus : Path := z.root ++ z.path + +/-- `ZipperAbsolutePath::root_prefix_path`. -/ +def rootPrefixPath : Path := z.root + +/-- All locations of the zipper's subtrie, relative to its root, in depth-first +order. The zipper's entire visible universe. -/ +def subPaths : List Path := (z.trie.subtrie z.root).paths + +/-! ## `trait Zipper` -/ + +/-- `Zipper::path_exists`. -/ +def pathExists : Bool := z.trie.pathExists z.focus + +/-- `Zipper::is_val`. -/ +def isVal : Bool := (z.trie.valAt z.focus).isSome + +/-- `Zipper::child_mask`. -/ +def childMask : ByteMask := z.trie.childMask z.focus + +/-- `Zipper::child_count`. -/ +def childCount : Nat := z.childMask.length + +/-- `ZipperMoving::focus_byte`: the byte last descended to reach the focus. +**Unspecified at the root**; the harness masks it there. -/ +def focusByte : Option UInt8 := z.path.getLast? + +/-! ## `trait ZipperValues` -/ + +/-- `ZipperValues::val`. -/ +def val : Option V := z.trie.valAt z.focus + +/-- `ZipperValues::val_at`: the value at `k`, relative to the focus. -/ +def valAt (k : Path) : Option V := z.trie.valAt (z.focus ++ k) + +/-! ## `trait ZipperSubtries` -/ + +/-- `ZipperInfallibleSubtries::make_map`. Under the default `graft_root_vals` +feature the value at the focus becomes the new map's root value. -/ +def makeMap : PrunedMap V := z.trie.subtrie z.focus + +/-- The node below the focus — what `get_focus` returns. This, not `makeMap`, +is what the algebraic operations and `graft_internal` consume. -/ +def focusNode : PrunedMap V := (z.makeMap.removeVal []).2 + +/-- `get_focus().is_none()`: the focus has no descendants. -/ +def focusNodeIsEmpty : Bool := z.trie.belowIsEmpty z.focus + +/-! ## `trait ZipperMoving` — position -/ + +/-- The same zipper with its focus at the relative path `q`, so that an ancestor +or descendant can be named and then asked about. -/ +def atPath (q : Path) : PZip V := { z with path := q } + +/-- `ZipperMoving::at_root`. -/ +def atRoot : Bool := z.path.isEmpty + +/-- `ZipperMoving::reset`. -/ +def reset : PZip V := { z with path := [] } + +/-- `ZipperMoving::val_count`: values at and below the focus. -/ +def valCount : Nat := z.trie.valCount z.focus + +/-! ## `trait ZipperMoving` — descent -/ + +/-- `ZipperMoving::descend_to`. Never fails; the focus may end up off-trie. -/ +def descendTo (k : Path) : PZip V := { z with path := z.path ++ k } + +/-- `ZipperMoving::descend_to_byte`. -/ +def descendToByte (b : UInt8) : PZip V := z.descendTo [b] + +/-- `ZipperMoving::descend_to_check`: descend, then report existence. -/ +def descendToCheck (k : Path) : Bool × PZip V := + let z' := z.descendTo k + (z'.pathExists, z') + +/-- `ZipperMoving::descend_to_existing`: descend byte by byte, stopping where the +path stops existing. Returns the number of bytes actually descended. -/ +def descendToExisting (k : Path) : Nat × PZip V := + -- Existence is prefix-closed, so the prefixes of `k` that still exist form an + -- initial segment: the answer is the longest prefix of `k` that exists. + let reach := ((List.range (k.length + 1)).filter + (fun j => (z.descendTo (k.take j)).pathExists)).getLast?.getD 0 + (reach, z.descendTo (k.take reach)) + +/-- `ZipperMoving::descend_to_val`: descend byte by byte, stopping at the first +value encountered *below* the starting focus, or where the path stops existing. -/ +def descendToVal (k : Path) : Nat × PZip V := + let reach := ((List.range (k.length + 1)).filter + (fun j => (z.descendTo (k.take j)).pathExists)).getLast?.getD 0 + let stop := ((List.range (reach + 1)).filter + (fun j => 0 < j && (z.descendTo (k.take j)).isVal)).head?.getD reach + (stop, z.descendTo (k.take stop)) + +/-- `ZipperMoving::descend_to_existing_byte`. -/ +def descendToExistingByte (b : UInt8) : Bool × PZip V := + let z' := z.descendToByte b + if z'.pathExists then (true, z') else (false, z) + +/-- `ZipperMoving::descend_indexed_byte`: descend into the `idx`-th child in +ascending byte order, returning the byte moved to. -/ +def descendIndexedByte (idx : Nat) : Option UInt8 × PZip V := + match z.childMask.indexedBit idx with + | some b => (some b, z.descendToByte b) + | none => (none, z) + +/-- `ZipperMoving::descend_first_byte`. -/ +def descendFirstByte : Option UInt8 × PZip V := z.descendIndexedByte 0 + +/-- `ZipperMoving::descend_last_byte`. -/ +def descendLastByte : Option UInt8 × PZip V := + let c := z.childCount + if c == 0 then (none, z) else z.descendIndexedByte (c - 1) + +/-- `ZipperMoving::descend_until`: descend while there is exactly one child, +stopping on a value. A no-op on a branch, a leaf, or a non-existent path. + +The destination is the *nearest* descendant that carries a value or is not +single-childed; `subPaths` is in depth-first order, which along a chain is order +of increasing depth, so `find?` returns it. -/ +def descendUntil : Bool × PZip V := + if z.childCount != 1 then (false, z) + else + match (z.subPaths.filter (fun q => z.path ≼ q && Path.lt z.path q)).find? + (fun q => (z.atPath q).isVal || (z.atPath q).childCount != 1) with + | some q => (true, z.atPath q) + | none => (false, z) + +/-- `ZipperMoving::descend_until_observed`: `descend_until`, reporting each byte +it descends. For the `Vec` observer the reported sequence must be exactly +the path delta — the only way a blind zipper learns where it ended up. -/ +def descendUntilObserved : Bool × Path × PZip V := + let (moved, z2) := z.descendUntil + (moved, z2.path.drop z.path.length, z2) + +/-- `ZipperMoving::descend_until_max_bytes`: `descend_until`, then ascend back to +at most `maxBytes` below the starting depth. -/ +def descendUntilMaxBytes (maxBytes : Nat) : Bool × PZip V := + if maxBytes == 0 then (false, z) + else + let target := z.path.length + maxBytes + let (moved, z') := z.descendUntil + if z'.path.length > target then (moved, { z' with path := z'.path.take target }) + else (moved, z') + +/-! ## `trait ZipperMoving` — ascent -/ + +/-- `ZipperMoving::ascend`: ascend `steps` bytes, clamping at the zipper root. +Returns the number of bytes actually ascended. -/ +def ascend (steps : Nat) : Nat × PZip V := + let n := min steps z.path.length + (n, { z with path := z.path.take (z.path.length - n) }) + +/-- `ZipperMoving::ascend_byte`: `ascend(1) == 1`. -/ +def ascendByte : Bool × PZip V := + let (n, z2) := z.ascend 1 + (n == 1, z2) + +/-- `ZipperMoving::ascend_until`: ascend to the nearest strict ancestor that +carries a value or branches, or to the root. Returns the bytes ascended. + +`properPrefixes` is shortest-first, so the last qualifying element is the +deepest; the root always qualifies, so there is always an answer. -/ +def ascendUntil : Nat × PZip V := + if z.atRoot then (0, z) + else + let stops := (Path.properPrefixes z.path).filter fun a => + a.isEmpty || (z.atPath a).isVal || (z.atPath a).childCount > 1 + let a := (stops.getLast?).getD [] + (z.path.length - a.length, z.atPath a) + +/-- `ZipperMoving::ascend_until_branch`: as above, but values do not stop it. -/ +def ascendUntilBranch : Nat × PZip V := + if z.atRoot then (0, z) + else + let stops := (Path.properPrefixes z.path).filter fun a => + a.isEmpty || (z.atPath a).childCount > 1 + let a := (stops.getLast?).getD [] + (z.path.length - a.length, z.atPath a) + +/-! ## `trait ZipperMoving` — lateral movement -/ + +/-- `ZipperMoving::to_next_sibling_byte`. + +At the zipper root there is no last byte, so the documented answer — and the +`ZipperMoving` default implementation's — is "did not move". The native +`ReadZipper` instead consults the last byte of the *absolute* origin path and +can leave its own root (FINDINGS.md #3); the fuzzer skips the operation at the +root so that known bug does not mask others. -/ +def toNextSiblingByte : Option UInt8 × PZip V := + match z.focusByte with + | none => (none, z) + | some cur => + if z.atRoot then (none, z) + else + let up := (z.ascendByte).2 + match up.childMask.nextBit cur with + | some b => (some b, up.descendToByte b) + | none => (none, z) + +/-- `ZipperMoving::to_prev_sibling_byte`. -/ +def toPrevSiblingByte : Option UInt8 × PZip V := + match z.focusByte with + | none => (none, z) + | some cur => + if z.atRoot then (none, z) + else + let up := (z.ascendByte).2 + match up.childMask.prevBit cur with + | some b => (some b, up.descendToByte b) + | none => (none, z) + +/-- `ZipperMoving::move_to_path`: jump to `p` relative to the zipper root. +Returns the number of bytes shared with the old location. -/ +def moveToPath (p : Path) : Nat × PZip V := + let overlap := ((List.range (min p.length z.path.length)).takeWhile + (fun i => p[i]? == z.path[i]?)).length + (overlap, { z with path := p }) + +/-! ## `trait ZipperMoving` — depth-first stepping -/ + +/-- `ZipperMoving::to_next_step`: the next existing location in depth-first +order. On exhaustion the focus returns to the root and the result is `false`. -/ +def toNextStep : Bool × PZip V := + match z.subPaths.find? (fun q => Path.lt z.path q) with + | some q => (true, { z with path := q }) + | none => (false, z.reset) + +/-! ## `trait ZipperIteration` -/ + +/-- `ZipperIteration::to_next_val`: the next location carrying a value, in +depth-first order. Never reports the value at the starting focus. -/ +def toNextVal : Bool × PZip V := + match z.subPaths.find? + (fun q => Path.lt z.path q && (z.trie.valAt (z.root ++ q)).isSome) with + | some q => (true, { z with path := q }) + | none => (false, z.reset) + +/-- `ZipperReadOnlyIteration::to_next_get_val`. -/ +def toNextGetVal : Option V × PZip V := + let (moved, z') := z.toNextVal + (if moved then z'.val else none, z') + +/-- `ZipperIteration::descend_last_path`: follow the last child to the end of +the depth-first-greatest path below the focus. -/ +def descendLastPath : Bool × PZip V := + let cands := z.subPaths.filter (fun q => z.path ≼ q) + match cands.getLast? with + | some q => if q == z.path then (false, z) else (true, { z with path := q }) + | none => (false, z) + +/-- The shared core of `descend_first_k_path` and `to_next_k_path` +(`k_path_internal`): the depth-first-least existing location exactly `k` bytes +below the common ancestor at depth `base`, strictly after the current focus. On +failure the focus moves to that ancestor. -/ +def kPathFrom (base k : Nat) : Bool × PZip V := + let anc := z.path.take base + match z.subPaths.find? + (fun q => q.length == base + k && anc ≼ q && Path.lt z.path q) with + | some q => (true, { z with path := q }) + | none => (false, { z with path := anc }) + +/-- `ZipperIteration::descend_first_k_path`. -/ +def descendFirstKPath (k : Nat) : Bool × PZip V := z.kPathFrom z.path.length k + +/-- `ZipperIteration::to_next_k_path`: the next existing location at the same +depth, under the common ancestor `k` bytes above the focus. + +When the focus is shallower than `k` the native `ReadZipper` falls back to the +**zipper root** as the common ancestor, so the call behaves like +`descend_first_k_path(k)` from the root and can succeed; the `ZipperIteration` +default returns `false` without moving. The model follows the native one, which +is what the public API reaches. -/ +def toNextKPath (k : Nat) : Bool × PZip V := + if k ≤ z.path.length then z.kPathFrom (z.path.length - k) k else z.kPathFrom 0 k + +/-! ## `trait ZipperForking` -/ + +/-- `ZipperForking::fork_read_zipper`: a new zipper rooted at the current focus. -/ +def forkReadZipper : PZip V := { z with root := z.focus, path := [] } + +end PZip +end PrunedModel diff --git a/lean/PrunedModel/Zippy.lean b/lean/PrunedModel/Zippy.lean new file mode 100644 index 00000000..44faa4a3 --- /dev/null +++ b/lean/PrunedModel/Zippy.lean @@ -0,0 +1,1278 @@ +import PrunedModel.Refine + +/-! +# Zippy's set algebra, as laws about zippers + +[`formal.egg`](https://github.com/Adam-Vandervorst/Zippy/blob/b/formal.egg) is +the reference semantics of Zippy's space algebra: a space is a finite set of +paths, and each operator — `Union`, `Intersection`, `Subtraction`, `Wrap`, +`Unwrap`, `Composition`, `Restriction`, `Raffination`, `Head`, `TailsUnion`, +`TailsIntersection`, `IterC`, `Iter`, `Fix` — is given by egglog rewrite rules, +each annotated with the SMT proof that discharges it. The file says of itself +that "no zipper logic lives here: zippers are an optimization and must be +observationally equivalent to this reference". + +This file is that equivalence, for `pathmap`'s zippers, and then the rules. + +## A space is a `PrunedMap Unit` + +`Option Unit` is one bit, so a `PrunedMap Unit` is exactly a finite set of paths +(`Lattice.lean` §5). `Path` is `List UInt8`, so egg's `Item i64` becomes a byte; +the tour's letters `a..z = 10..35` all fit. `Eps` is `[]` and `Concat` is `++`. + +## Every operator is a zipper program + +Each operator is defined by what the model's write zipper does, not by a set +comprehension: `Union` is `join_map_into` at the root of a write zipper over the +first operand, `Unwrap` is `descend_to` then `make_map`, `Head` reads +`child_mask`, and so on (§1). `Refine.lean` proves what each zipper operation +writes at its focus, and §2 turns that into one membership lemma per operator. +Every law in §3–§9 is then a statement about zipper programs, proved from those +membership lemmas alone. + +The model follows `focus_value_consistency` (issue #104): a subtrie includes +the value at its root, and the five raw zipper operations that differ from their +egg operator at the focus value without #104 *are* it under #104 — §10 proves +each: + +* `join_into` is `Union`; +* `restrict` is `Restriction` (so §1 defines `Restriction` as `restrict`); +* `insert_prefix p` is `Wrap p`; +* `join_k_path_into 1` is `TailsUnion`; +* `meet_k_path_into 1` is `TailsIntersection` — since `482c248`, an empty meet + clears the focus value (`remove_subtrie`) rather than keeping it + (`remove_branches`). + +The two tails operators are still defined by folding `join_map_into` and +`meet_into` over `child_mask`, as egg's rules compute them. + +#104 is not on master, whose crate still differs at the focus value (for +example `join_into` into an empty destination drops the source's root value). +The algebraic fuzzer (`differential/src/algebraic/routes.rs`) therefore builds +each operator from operations that agree on master, and uses a raw operation +only where it compensates for the focus value by hand. + +## What does not carry over + +Nothing in `formal.egg` is false here. Two of its rule groups are algorithms +rather than equations — the `drop-prefix` relation and the +`tails-intersection-acc` fold — and they appear as the equations they compute. +`Fix` is egg's *axiomatisation* of a least post-fixpoint; §9 states it as a +predicate, proves the three rules are its definition, that it is unique, and +that the inflationary iteration every Zippy executor runs reaches it when `F` is +monotone. The `EB` membership-flag algebra is `Bool`'s own and needs no +statement. + +The tour's `(check …)` lines are `#guard`s at the end, `(fail (check …))` as +`#guard !…`. +-/ + +namespace PrunedModel +namespace Zippy + +open PathMapModel PrunedMap + +/-- A space: a finite set of paths. -/ +abbrev Space := PrunedMap Unit + +instance : Membership Path Space := ⟨fun s p => (s.valAt p).isSome = true⟩ + +theorem mem_def {p : Path} {s : Space} : p ∈ s ↔ (s.valAt p).isSome = true := Iff.rfl + +instance (p : Path) (s : Space) : Decidable (p ∈ s) := + inferInstanceAs (Decidable ((s.valAt p).isSome = true)) + +instance : DecidableEq Space := fun a b => + if h : a.entries = b.entries then isTrue (PrunedMap.ext fun k => by rw [h]) + else isFalse fun e => h (by rw [e]) + +/-- **Extensionality.** Two spaces with the same members are equal — which is +what lets every law below be an equation. -/ +theorem ext {a b : Space} (h : ∀ p, p ∈ a ↔ p ∈ b) : a = b := by + apply PrunedMap.ext; intro k + show a.valAt k = b.valAt k + rw [unit_valAt_determined a k, unit_valAt_determined b k] + have := h k + rw [mem_def, mem_def] at this + rw [Bool.eq_iff_iff.mpr this] + +/-- `valAt` of a space is determined by membership. -/ +theorem valAt_eq (s : Space) (p : Path) : s.valAt p = if p ∈ s then some () else none := by + rw [unit_valAt_determined s p]; rfl + +theorem not_mem_iff (s : Space) (p : Path) : p ∉ s ↔ s.valAt p = none := by + rw [mem_def]; cases s.valAt p <;> simp + +/-! ## 1. The operators, as zipper programs -/ + +/-- A write zipper at the root of `s`. -/ +def wz (s : Space) : PZip Unit := ⟨s, [], []⟩ + +/-- `Empty`. -/ +def empty : Space := PrunedMap.empty + +/-- `Singleton p`: `descend_to p`, then `set_val`. -/ +def singleton (p : Path) : Space := (((wz empty).descendTo p).setVal ()).2.trie + +/-- `Union`: `join_map_into` — which joins the root value too — at the root. -/ +def union (a b : Space) : Space := ((wz a).joinMapInto unitOps b).2.trie + +/-- `Intersection`: `meet_into`. -/ +def inter (a b : Space) : Space := ((wz a).meetInto unitOps (wz b)).2.trie + +/-- `Subtraction`: `subtract_into`. -/ +def subtr (a b : Space) : Space := ((wz a).subtractInto unitOps (wz b)).2.trie + +/-- `Wrap p s`: `descend_to p` in an empty map, then `graft_map s`. -/ +def wrap (p : Path) (s : Space) : Space := (((wz empty).descendTo p).graftMap s).trie + +/-- `Unwrap s p`: `descend_to p`, then `make_map`. -/ +def unwrap (s : Space) (p : Path) : Space := ((wz s).descendTo p).makeMap + +/-- `Restriction x y`: the paths of `x` with a prefix in `y` — `restrict`, which +under #104 consults the source's focus value and clears the destination's +when it has none, as `PathMap::restrict` does. -/ +def restriction (x y : Space) : Space := ((wz x).restrict unitOps (wz y)).2.trie + +/-- `Raffination x y`, which egg *defines* as `x \ (x <| y)`. -/ +def raffination (x y : Space) : Space := subtr x (restriction x y) + +/-- `Composition s t`: for each path `u` of `s`, `descend_to u` and +`join_map_into t`. -/ +def composition (s t : Space) : Space := + s.keys.foldl (fun acc u => (((wz acc).descendTo u).joinMapInto unitOps t).2.trie) empty + +/-- `Head s`: one single-byte path per bit of `child_mask`. -/ +def head (s : Space) : Space := (wz s).childMask.foldl (fun acc b => union acc (singleton [b])) empty + +/-- `TailsUnion s`: the union, over `child_mask`, of `descend_to_byte b` then +`make_map`. -/ +def tailsUnion (s : Space) : Space := + (wz s).childMask.foldl (fun acc b => union acc ((wz s).descendToByte b).makeMap) empty + +/-- `TailsIntersection s`: the intersection of the same children — egg's +`tails-intersection-acc` fold, started at the first head. No heads, no +tails. -/ +def tailsInter (s : Space) : Space := + match (wz s).childMask with + | [] => empty + | b :: bs => bs.foldl (fun acc c => inter acc ((wz s).descendToByte c).makeMap) + ((wz s).descendToByte b).makeMap + +/-- One arm of an iteration: the body at head `h`, over `src`'s tails under `h`. -/ +def iterArm (src : Space) (body : UInt8 → Space → Space) : Path → Space + | [h] => body h (unwrap src [h]) + | _ => empty + +/-- `IterH H src body`: the union of `body h (src's tails under h)` over the +single-byte paths `[h]` of `H`. Paths of any other length contribute nothing; +egg has no rule for them, and only `iter` builds an `IterH`. -/ +def iterH (H src : Space) (body : UInt8 → Space → Space) : Space := + H.keys.foldl (fun acc k => union acc (iterArm src body k)) empty + +/-- `Iter src body`: head-dependent iteration, which egg rewrites to +`IterH (Head src) src body` (its rule L1) — so that is its definition here. -/ +def iter (src : Space) (body : UInt8 → Space → Space) : Space := iterH (head src) src body + +/-- `IterC src b`: iteration with a loop-invariant body. -/ +def iterC (src b : Space) : Space := iter src fun _ _ => b + +/-! ## 2. What each zipper program computes -/ + +@[simp] theorem wz_trie (s : Space) : (wz s).trie = s := rfl +@[simp] theorem wz_focus (s : Space) : (wz s).focus = [] := rfl +@[simp] theorem wz_descendTo_focus (s : Space) (p : Path) : ((wz s).descendTo p).focus = p := rfl +@[simp] theorem wz_descendTo_trie (s : Space) (p : Path) : ((wz s).descendTo p).trie = s := rfl + +theorem subtrie_nil (t : Space) : t.subtrie [] = t := + PrunedMap.ext fun k => by + show (t.subtrie []).valAt k = t.valAt k + rw [valAt_subtrie]; rfl + +@[simp] theorem wz_makeMap (s : Space) : (wz s).makeMap = s := subtrie_nil s + +theorem not_mem_empty (p : Path) : p ∉ empty := by simp [mem_def, empty] + +theorem mem_singleton {p q : Path} : p ∈ singleton q ↔ p = q := by + rw [singleton, PZip.setVal_eq, PZip.withTrie_trie, mem_def, valAt_replaceAt] + simp only [wz_descendTo_focus, wz_descendTo_trie] + cases hs : Path.stripPrefix q p with + | none => + simp only [empty, valAt_empty, Option.isSome_none, Bool.false_eq_true, false_iff] + intro h; subst h; rw [PZip.stripPrefix_self] at hs; cases hs + | some r => + have := (Path.stripPrefix_eq_some q p r).mp hs; subst this + dsimp only + rw [valAt_setVal] + by_cases hr : r = [] <;> simp [hr, PZip.valAt_makeMap, empty] + +theorem union_eq_join (a b : Space) : union a b = join unitOps a b := by + rw [union, PZip.joinMapInto_eq _ unitOps_lawful, PZip.withTrie_trie, wz_focus, replaceAt_nil, + wz_makeMap] + +theorem inter_eq_meet (a b : Space) : inter a b = meet unitOps a b := by + rw [inter, PZip.meetInto_eq _ unitOps_lawful, PZip.withTrie_trie, wz_focus, replaceAt_nil, + wz_makeMap, wz_makeMap] + +theorem subtr_eq_sub (a b : Space) : subtr a b = sub unitOps a b := by + rw [subtr, PZip.subtractInto_eq _ unitOps_lawful, PZip.withTrie_trie, wz_focus, replaceAt_nil, + wz_makeMap, wz_makeMap] + +theorem mem_union {p : Path} {a b : Space} : p ∈ union a b ↔ p ∈ a ∨ p ∈ b := by + rw [union_eq_join, mem_def, unit_join_isSome, Bool.or_eq_true]; rfl + +theorem mem_inter {p : Path} {a b : Space} : p ∈ inter a b ↔ p ∈ a ∧ p ∈ b := by + rw [inter_eq_meet, mem_def, unit_meet_isSome, Bool.and_eq_true]; rfl + +theorem mem_subtr {p : Path} {a b : Space} : p ∈ subtr a b ↔ p ∈ a ∧ p ∉ b := by + rw [subtr_eq_sub, mem_def, valAt_sub, mem_def, not_mem_iff] + cases a.valAt p <;> cases hb : b.valAt p <;> simp [subVal, unitOps, ValRes.resolve] + +theorem wrap_eq (p : Path) (s : Space) : wrap p s = empty.replaceAt p s := by + rw [wrap, PZip.graftMap_eq]; rfl + +theorem mem_wrap {p q : Path} {s : Space} : p ∈ wrap q s ↔ ∃ r, p = q ++ r ∧ r ∈ s := by + rw [wrap_eq, mem_def, valAt_replaceAt] + cases hs : Path.stripPrefix q p with + | none => + simp only [empty, valAt_empty, Option.isSome_none, Bool.false_eq_true, false_iff, not_exists, + not_and] + intro r hr; exact absurd hr ((Path.stripPrefix_eq_none q p).mp hs r) + | some r => + have := (Path.stripPrefix_eq_some q p r).mp hs; subst this + constructor + · intro h; exact ⟨r, rfl, h⟩ + · rintro ⟨r', hr', h⟩ + rw [List.append_cancel_left hr']; exact h + +theorem mem_unwrap {p q : Path} {s : Space} : p ∈ unwrap s q ↔ q ++ p ∈ s := by + rw [unwrap, mem_def, PZip.valAt_makeMap]; rfl + +theorem mem_keys {k : Path} {s : Space} : k ∈ s.keys ↔ k ∈ s := by + constructor + · intro h; exact lookup_isSome_of_mem_keys h + · intro h; exact mem_keys_of_lookup_isSome h + +theorem mem_ofList (b : UInt8) (bs : List UInt8) : b ∈ ByteMask.ofList bs ↔ b ∈ bs := by + rw [ByteMask.ofList, List.mem_filterMap] + constructor + · rintro ⟨i, _, hi⟩ + simp only at hi + split at hi + · next hc => cases hi; exact List.contains_iff_mem.mp hc + · cases hi + · intro hb + refine ⟨b.toNat, List.mem_range.mpr (UInt8.toNat_lt b), ?_⟩ + simp only + rw [if_pos (by rw [UInt8.ofNat_toNat]; exact List.contains_iff_mem.mpr hb), UInt8.ofNat_toNat] + +/-- `child_mask` at the root: the first bytes of the paths. -/ +theorem mem_childMask {b : UInt8} {s : Space} : b ∈ (wz s).childMask ↔ ∃ r, b :: r ∈ s := by + show b ∈ s.childMask [] ↔ _ + rw [childMask, mem_ofList, List.mem_filterMap] + constructor + · rintro ⟨k, hk, hb⟩ + have hk' : k ∈ s := mem_keys.mp hk + cases k with + | nil => simp [Path.stripPrefix] at hb + | cons c r => + simp only [Path.stripPrefix, Option.some.injEq] at hb + subst hb; exact ⟨r, hk'⟩ + · rintro ⟨r, hr⟩ + exact ⟨b :: r, mem_keys.mpr hr, rfl⟩ + +/-- Folding a union over a list: a member of the result is a member of the +start or of some step. -/ +theorem mem_foldl_union {α : Type} (f : α → Space) (p : Path) : + ∀ (l : List α) (init : Space), + p ∈ l.foldl (fun acc x => union acc (f x)) init ↔ p ∈ init ∨ ∃ x ∈ l, p ∈ f x + | [], init => by simp + | x :: xs, init => by + rw [List.foldl_cons, mem_foldl_union f p xs, mem_union] + constructor + · rintro ((h | h) | ⟨y, hy, h⟩) + · exact Or.inl h + · exact Or.inr ⟨x, List.mem_cons_self, h⟩ + · exact Or.inr ⟨y, List.mem_cons_of_mem _ hy, h⟩ + · rintro (h | ⟨y, hy, h⟩) + · exact Or.inl (Or.inl h) + · rcases List.mem_cons.mp hy with rfl | hy + · exact Or.inl (Or.inr h) + · exact Or.inr ⟨y, hy, h⟩ + +/-- Folding an intersection over a list. -/ +theorem mem_foldl_inter {α : Type} (f : α → Space) (p : Path) : + ∀ (l : List α) (init : Space), + p ∈ l.foldl (fun acc x => inter acc (f x)) init ↔ p ∈ init ∧ ∀ x ∈ l, p ∈ f x + | [], init => by simp + | x :: xs, init => by + rw [List.foldl_cons, mem_foldl_inter f p xs, mem_inter] + constructor + · rintro ⟨⟨h0, hx⟩, h⟩ + exact ⟨h0, fun y hy => (List.mem_cons.mp hy).elim (fun e => e ▸ hx) (h y)⟩ + · rintro ⟨h0, h⟩ + exact ⟨⟨h0, h x List.mem_cons_self⟩, fun y hy => h y (List.mem_cons_of_mem _ hy)⟩ + +theorem mem_restriction {p : Path} {x y : Space} : + p ∈ restriction x y ↔ p ∈ x ∧ ∃ r s, p = r ++ s ∧ r ∈ y := by + rw [restriction, PZip.restrict_eq _ unitOps_lawful, PZip.withTrie_trie, wz_focus, replaceAt_nil, + wz_makeMap, wz_makeMap] + by_cases hy : (wz y).val.isSome = true + · rw [if_pos hy] + have hy' : [] ∈ y := hy + exact ⟨fun h => ⟨h, [], p, rfl, hy'⟩, fun h => h.1⟩ + · rw [if_neg hy, mem_def, valAt_restrictBelowRoot] + have hy' : [] ∉ y := hy + by_cases hv : validatedBy y p = true + · rw [if_pos hv] + obtain ⟨r, s, _, hrs, hr⟩ := (validatedBy_iff _ _).mp hv + exact ⟨fun h => ⟨h, r, s, hrs, hr⟩, fun h => h.1⟩ + · rw [if_neg hv] + simp only [Option.isSome_none, Bool.false_eq_true, false_iff, not_and] + rintro _ ⟨r, s, hrs, hr⟩ + apply hv + refine (validatedBy_iff _ _).mpr ⟨r, s, ?_, hrs, hr⟩ + rintro rfl; exact hy' hr + +theorem mem_composition_step {p u : Path} {acc t : Space} : + p ∈ (((wz acc).descendTo u).joinMapInto unitOps t).2.trie ↔ p ∈ acc ∨ ∃ v, p = u ++ v ∧ v ∈ t := by + rw [PZip.joinMapInto_eq _ unitOps_lawful, PZip.withTrie_trie, wz_descendTo_trie, + wz_descendTo_focus, mem_def, valAt_replaceAt] + cases hs : Path.stripPrefix u p with + | none => + have hn := (Path.stripPrefix_eq_none u p).mp hs + exact ⟨Or.inl, fun h => h.elim id (fun ⟨v, hv, _⟩ => absurd hv (hn v))⟩ + | some r => + have := (Path.stripPrefix_eq_some u p r).mp hs; subst this + dsimp only + rw [unit_join_isSome, PZip.valAt_makeMap, wz_descendTo_trie, wz_descendTo_focus, + Bool.or_eq_true] + constructor + · rintro (h | h) + · exact Or.inl h + · exact Or.inr ⟨r, rfl, h⟩ + · rintro (h | ⟨v, hv, h⟩) + · exact Or.inl h + · rw [List.append_cancel_left hv]; exact Or.inr h + +theorem mem_composition {p : Path} {s t : Space} : + p ∈ composition s t ↔ ∃ u v, p = u ++ v ∧ u ∈ s ∧ v ∈ t := by + have key : ∀ (l : List Path) (init : Space), + p ∈ l.foldl (fun acc u => (((wz acc).descendTo u).joinMapInto unitOps t).2.trie) init ↔ + p ∈ init ∨ ∃ u ∈ l, ∃ v, p = u ++ v ∧ v ∈ t := by + intro l + induction l with + | nil => intro init; simp + | cons u us ih => + intro init + rw [List.foldl_cons, ih, mem_composition_step] + constructor + · rintro ((h | h) | ⟨w, hw, h⟩) + · exact Or.inl h + · exact Or.inr ⟨u, List.mem_cons_self, h⟩ + · exact Or.inr ⟨w, List.mem_cons_of_mem _ hw, h⟩ + · rintro (h | ⟨w, hw, h⟩) + · exact Or.inl (Or.inl h) + · rcases List.mem_cons.mp hw with rfl | hw + · exact Or.inl (Or.inr h) + · exact Or.inr ⟨w, hw, h⟩ + rw [composition, key] + simp only [not_mem_empty, false_or, mem_keys] + constructor + · rintro ⟨u, hu, v, rfl, hv⟩; exact ⟨u, v, rfl, hu, hv⟩ + · rintro ⟨u, v, rfl, hu, hv⟩; exact ⟨u, hu, v, rfl, hv⟩ + +theorem mem_head {p : Path} {s : Space} : p ∈ head s ↔ ∃ b r, p = [b] ∧ b :: r ∈ s := by + rw [head, mem_foldl_union (fun b => singleton [b])] + simp only [not_mem_empty, false_or, mem_singleton, mem_childMask] + constructor + · rintro ⟨b, ⟨r, hr⟩, rfl⟩; exact ⟨b, r, rfl, hr⟩ + · rintro ⟨b, r, rfl, hr⟩; exact ⟨b, ⟨r, hr⟩, rfl⟩ + +theorem mem_child {p : Path} {s : Space} {b : UInt8} : + p ∈ ((wz s).descendToByte b).makeMap ↔ b :: p ∈ s := by + rw [mem_def, PZip.valAt_makeMap]; rfl + +theorem mem_tailsUnion {p : Path} {s : Space} : p ∈ tailsUnion s ↔ ∃ b, b :: p ∈ s := by + rw [tailsUnion, mem_foldl_union (fun b => ((wz s).descendToByte b).makeMap)] + simp only [not_mem_empty, false_or, mem_child, mem_childMask] + constructor + · rintro ⟨b, _, h⟩; exact ⟨b, h⟩ + · rintro ⟨b, h⟩; exact ⟨b, ⟨p, h⟩, h⟩ + +theorem mem_tailsInter {p : Path} {s : Space} : + p ∈ tailsInter s ↔ (∃ b r, b :: r ∈ s) ∧ ∀ b, (∃ r, b :: r ∈ s) → b :: p ∈ s := by + unfold tailsInter + split + · next hm => + simp only [not_mem_empty, false_iff, not_and] + rintro ⟨b, r, hr⟩ + have : b ∈ (wz s).childMask := mem_childMask.mpr ⟨r, hr⟩ + rw [hm] at this; cases this + · next b bs hm => + rw [mem_foldl_inter (fun c => ((wz s).descendToByte c).makeMap), mem_child] + simp only [mem_child] + have hmask : ∀ c, c ∈ b :: bs ↔ ∃ r, c :: r ∈ s := fun c => by rw [← hm, mem_childMask] + constructor + · rintro ⟨h0, h⟩ + refine ⟨⟨b, (hmask b).mp List.mem_cons_self⟩, fun c hc => ?_⟩ + rcases List.mem_cons.mp ((hmask c).mpr hc) with rfl | hc' + · exact h0 + · exact h c hc' + · rintro ⟨_, h⟩ + exact ⟨h b ((hmask b).mp List.mem_cons_self), + fun c hc => h c ((hmask c).mp (List.mem_cons_of_mem _ hc))⟩ + +theorem mem_iterH {p : Path} {H src : Space} {body : UInt8 → Space → Space} : + p ∈ iterH H src body ↔ ∃ h, [h] ∈ H ∧ p ∈ body h (unwrap src [h]) := by + rw [iterH, mem_foldl_union (iterArm src body)] + simp only [not_mem_empty, false_or, mem_keys] + constructor + · rintro ⟨k, hk, h⟩ + match k, hk, h with + | [c], hk, h => exact ⟨c, hk, h⟩ + | [], _, h => exact absurd h (not_mem_empty p) + | _ :: _ :: _, _, h => exact absurd h (not_mem_empty p) + · rintro ⟨c, hc, h⟩; exact ⟨[c], hc, h⟩ + +theorem mem_iter {p : Path} {src : Space} {body : UInt8 → Space → Space} : + p ∈ iter src body ↔ ∃ h, (∃ r, h :: r ∈ src) ∧ p ∈ body h (unwrap src [h]) := by + rw [iter, mem_iterH] + simp only [mem_head, List.cons.injEq, and_true] + constructor + · rintro ⟨h, ⟨b, r, rfl, hr⟩, hp⟩; exact ⟨h, ⟨r, hr⟩, hp⟩ + · rintro ⟨h, ⟨r, hr⟩, hp⟩; exact ⟨h, ⟨h, r, rfl, hr⟩, hp⟩ + +theorem mem_iterC {p : Path} {src b : Space} : p ∈ iterC src b ↔ (∃ h r, h :: r ∈ src) ∧ p ∈ b := by + rw [iterC, mem_iter] + constructor + · rintro ⟨h, ⟨r, hr⟩, hp⟩; exact ⟨⟨h, r, hr⟩, hp⟩ + · rintro ⟨⟨h, r, hr⟩, hp⟩; exact ⟨h, ⟨r, hr⟩, hp⟩ + +theorem mem_raffination {p : Path} {x y : Space} : + p ∈ raffination x y ↔ p ∈ x ∧ ¬ ∃ r s, p = r ++ s ∧ r ∈ y := by + rw [raffination, mem_subtr, mem_restriction] + constructor + · rintro ⟨hx, hn⟩; exact ⟨hx, fun h => hn ⟨hx, h⟩⟩ + · rintro ⟨hx, hn⟩; exact ⟨hx, fun h => hn h.2⟩ + +/-! ## 3. Membership (`formal.egg` lines 76–88) + +egg's `ElemP p s` judgment, with `EOr`/`EAnd`/`EAndNot` as `∨`/`∧`/`∧ ¬`. The +singleton-disequality case (line 85) is negation-as-failure there, and sound +only at saturation; here it is an ordinary lemma. -/ + +/-- line 83 -/ +theorem elemP_empty (p : Path) : p ∉ empty := not_mem_empty p +/-- line 84 -/ +theorem elemP_singleton (p : Path) : p ∈ singleton p := mem_singleton.mpr rfl +/-- line 85 -/ +theorem elemP_singleton_ne {p q : Path} (h : p ≠ q) : p ∉ singleton q := fun hm => h (mem_singleton.mp hm) +/-- line 86 -/ +theorem elemP_union {p : Path} {a b : Space} : p ∈ union a b ↔ p ∈ a ∨ p ∈ b := mem_union +/-- line 87 -/ +theorem elemP_inter {p : Path} {a b : Space} : p ∈ inter a b ↔ p ∈ a ∧ p ∈ b := mem_inter +/-- line 88 -/ +theorem elemP_subtr {p : Path} {a b : Space} : p ∈ subtr a b ↔ p ∈ a ∧ p ∉ b := mem_subtr + +/-! ## 4. Union, intersection, subtraction (lines 90–117) + +`join_map_into`, `meet_into` and `subtract_into` at the root of a write zipper. +`Lattice.lean` already has most of these for `join`/`meet`; here they are about +the zipper programs, and subtraction is new. -/ + +section Boolean +variable (x y z : Space) + +/-- line 90 -/ +theorem union_idem : union x x = x := ext fun p => by rw [mem_union, or_self] +/-- line 91 -/ +theorem inter_idem : inter x x = x := ext fun p => by rw [mem_inter, and_self] +/-- line 93 -/ +theorem subtr_self : subtr x x = empty := ext fun p => by + rw [mem_subtr]; exact ⟨fun h => absurd h.1 h.2, fun h => absurd h (not_mem_empty p)⟩ +/-- line 96 -/ +theorem union_comm : union x y = union y x := ext fun p => by rw [mem_union, mem_union, or_comm] +/-- line 97 -/ +theorem inter_comm : inter x y = inter y x := ext fun p => by rw [mem_inter, mem_inter, and_comm] +/-- line 99 -/ +theorem union_empty : union x empty = x := ext fun p => by + rw [mem_union]; exact ⟨fun h => h.resolve_right (not_mem_empty p), Or.inl⟩ +/-- line 100 -/ +theorem empty_union : union empty x = x := by rw [union_comm, union_empty] +/-- line 101 -/ +theorem inter_empty : inter x empty = empty := ext fun p => by + rw [mem_inter]; exact ⟨fun h => h.2, fun h => absurd h (not_mem_empty p)⟩ +/-- line 102 -/ +theorem empty_inter : inter empty x = empty := by rw [inter_comm, inter_empty] +/-- line 103 -/ +theorem union_inter_distrib : inter (union x y) z = union (inter x z) (inter y z) := ext fun p => by + simp only [mem_union, mem_inter] + by_cases hx : p ∈ x <;> by_cases hy : p ∈ y <;> by_cases hz : p ∈ z <;> simp [hx, hy, hz] +/-- line 104 -/ +theorem inter_union_distrib : inter x (union y z) = union (inter x y) (inter x z) := ext fun p => by + simp only [mem_union, mem_inter] + by_cases hx : p ∈ x <;> by_cases hy : p ∈ y <;> by_cases hz : p ∈ z <;> simp [hx, hy, hz] +/-- line 105 -/ +theorem empty_subtr : subtr empty x = empty := ext fun p => by + rw [mem_subtr]; exact ⟨fun h => h.1, fun h => absurd h (not_mem_empty p)⟩ +/-- line 106 -/ +theorem subtr_empty : subtr x empty = x := ext fun p => by + rw [mem_subtr]; exact ⟨fun h => h.1, fun h => ⟨h, not_mem_empty p⟩⟩ +/-- line 107 -/ +theorem union_subtr_distrib : subtr (union x y) z = union (subtr x z) (subtr y z) := ext fun p => by + simp only [mem_union, mem_subtr] + by_cases hx : p ∈ x <;> by_cases hy : p ∈ y <;> by_cases hz : p ∈ z <;> simp [hx, hy, hz] +/-- line 108 -/ +theorem subtr_union : subtr x (union y z) = subtr (subtr x y) z := ext fun p => by + simp only [mem_union, mem_subtr] + by_cases hx : p ∈ x <;> by_cases hy : p ∈ y <;> by_cases hz : p ∈ z <;> simp [hx, hy, hz] +/-- line 116 -/ +theorem union_assoc : union (union x y) z = union x (union y z) := ext fun p => by + simp only [mem_union, or_assoc] +/-- line 117 -/ +theorem inter_assoc : inter (inter x y) z = inter x (inter y z) := ext fun p => by + simp only [mem_inter, and_assoc] + +end Boolean + +/-- line 109 -/ +theorem singleton_subtr_singleton {p q : Path} (h : p ≠ q) : + subtr (singleton p) (singleton q) = singleton p := ext fun r => by + simp only [mem_subtr, mem_singleton] + exact ⟨fun h' => h'.1, fun h' => ⟨h', fun e => h (h'.symm.trans e)⟩⟩ +/-- line 110 -/ +theorem singleton_inter_singleton {p q : Path} (h : p ≠ q) : + inter (singleton p) (singleton q) = empty := ext fun r => by + simp only [mem_inter, mem_singleton] + exact ⟨fun ⟨h1, h2⟩ => absurd (h1.symm.trans h2) h, fun h' => absurd h' (not_mem_empty r)⟩ + +/-! Paths (lines 112–115) are `List UInt8` under `++`; these are core lemmas. -/ + +/-- line 112 -/ +theorem concat_eps (x : Path) : x ++ [] = x := List.append_nil x +/-- line 113 -/ +theorem eps_concat (x : Path) : [] ++ x = x := List.nil_append x +/-- line 115 -/ +theorem concat_assoc (x y z : Path) : (x ++ y) ++ z = x ++ (y ++ z) := List.append_assoc x y z + +/-! ## 5. Wrap and unwrap (lines 119–153, 199–200) + +`Wrap` is `graft_map` at a descended focus of an empty map; `Unwrap` is +`descend_to` then `make_map`. egg needs the `drop-prefix` relation and ten rules +to compute `Unwrap` of a singleton; here it is one equation, +`unwrap_singleton`, and those rules are its cases. -/ + +/-- line 119 -/ +theorem wrap_empty (x : Path) : wrap x empty = empty := ext fun p => by + rw [mem_wrap] + exact ⟨fun ⟨_, _, h⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 120 -/ +theorem wrap_eps (s : Space) : wrap [] s = s := ext fun p => by + rw [mem_wrap]; exact ⟨fun ⟨r, hr, h⟩ => by simpa [hr] using h, fun h => ⟨p, rfl, h⟩⟩ +/-- line 121 -/ +theorem wrap_singleton (x p : Path) : wrap x (singleton p) = singleton (x ++ p) := ext fun q => by + rw [mem_wrap, mem_singleton] + simp only [mem_singleton, exists_eq_right] +/-- line 122 -/ +theorem wrap_union (x : Path) (s t : Space) : wrap x (union s t) = union (wrap x s) (wrap x t) := + ext fun p => by + simp only [mem_wrap, mem_union] + constructor + · rintro ⟨r, rfl, h | h⟩ + · exact Or.inl ⟨r, rfl, h⟩ + · exact Or.inr ⟨r, rfl, h⟩ + · rintro (⟨r, rfl, h⟩ | ⟨r, rfl, h⟩) + · exact ⟨r, rfl, Or.inl h⟩ + · exact ⟨r, rfl, Or.inr h⟩ + +/-- line 124 -/ +theorem unwrap_empty (p : Path) : unwrap empty p = empty := ext fun q => by + rw [mem_unwrap]; exact ⟨fun h => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty _)⟩ +/-- line 125 -/ +theorem unwrap_eps (s : Space) : unwrap s [] = s := ext fun q => by rw [mem_unwrap]; rfl +/-- line 126 -/ +theorem unwrap_wrap (p : Path) (s : Space) : unwrap (wrap p s) p = s := ext fun q => by + rw [mem_unwrap, mem_wrap] + exact ⟨fun ⟨r, hr, h⟩ => by rwa [List.append_cancel_left hr], fun h => ⟨q, rfl, h⟩⟩ +/-- line 127 -/ +theorem unwrap_wrap_append (p q : Path) (s : Space) : unwrap (wrap (p ++ q) s) p = wrap q s := + ext fun r => by + rw [mem_unwrap, mem_wrap, mem_wrap] + simp only [List.append_assoc, List.append_cancel_left_eq] +/-- line 128 -/ +theorem unwrap_wrap_of_append (p q : Path) (s : Space) : unwrap (wrap p s) (p ++ q) = unwrap s q := + ext fun r => by + rw [mem_unwrap, mem_wrap, mem_unwrap] + simp only [List.append_assoc, List.append_cancel_left_eq, exists_eq_left'] +/-- line 129 -/ +theorem unwrap_union (s t : Space) (x : Path) : unwrap (union s t) x = union (unwrap s x) (unwrap t x) := + ext fun q => by simp only [mem_unwrap, mem_union] +/-- line 199 -/ +theorem unwrap_unwrap (s : Space) (p q : Path) : unwrap (unwrap s p) q = unwrap s (p ++ q) := + ext fun r => by simp only [mem_unwrap, List.append_assoc] +/-- line 200 -/ +theorem unwrap_wrap_ne {a b : UInt8} (h : a ≠ b) (s : Space) : unwrap (wrap [a] s) [b] = empty := + ext fun q => by + rw [mem_unwrap, mem_wrap] + simp only [List.cons_append, List.nil_append, List.cons.injEq] + exact ⟨fun ⟨_, ⟨e, _⟩, _⟩ => absurd e.symm h, fun h' => absurd h' (not_mem_empty q)⟩ + +/-- **Unwrapping a singleton** (lines 131–153, the `drop-prefix` relation). `p` +unwraps `{w}` to `{r}` when `w = p ++ r`, and to nothing otherwise. -/ +theorem unwrap_singleton (w p : Path) : + unwrap (singleton w) p = match Path.stripPrefix p w with + | some r => singleton r + | none => empty := by + apply ext; intro q + rw [mem_unwrap, mem_singleton] + cases hs : Path.stripPrefix p w with + | none => + have hn := (Path.stripPrefix_eq_none p w).mp hs + exact ⟨fun e => absurd e.symm (hn q), fun h => absurd h (not_mem_empty q)⟩ + | some r => + have := (Path.stripPrefix_eq_some p w r).mp hs; subst this + rw [mem_singleton, List.append_cancel_left_eq] + +/-- line 134: `drop-prefix ε` -/ +theorem dropPrefix_eps (w : Path) : unwrap (singleton w) [] = singleton w := by + rw [unwrap_singleton]; rfl +/-- line 136: the exact case -/ +theorem dropPrefix_self (p : Path) : unwrap (singleton p) p = singleton [] := by + rw [unwrap_singleton, PZip.stripPrefix_self] +/-- line 138: the proper-prefix case -/ +theorem dropPrefix_append (p r : Path) : unwrap (singleton (p ++ r)) p = singleton r := by + rw [unwrap_singleton, Path.stripPrefix_append] +/-- line 140: the descend case -/ +theorem dropPrefix_descend (p q r : Path) : + unwrap (singleton (p ++ r)) (p ++ q) = unwrap (singleton r) q := by + rw [← unwrap_unwrap, dropPrefix_append] +/-- lines 142–153: every miss — the prefix is not a prefix of the path. -/ +theorem dropPrefix_miss {w p : Path} (h : ∀ r, w ≠ p ++ r) : unwrap (singleton w) p = empty := by + rw [unwrap_singleton, (Path.stripPrefix_eq_none p w).mpr h] +/-- lines 142 and 144: an item, or an item-headed path, misses `ε`. -/ +theorem dropPrefix_miss_eps (a : UInt8) (p : Path) : unwrap (singleton []) (a :: p) = empty := + dropPrefix_miss (fun r h => by simp at h) +/-- lines 146–152: differing first items miss. -/ +theorem dropPrefix_miss_item {a b : UInt8} (h : a ≠ b) (p r : Path) : + unwrap (singleton (b :: r)) (a :: p) = empty := + dropPrefix_miss (fun r' e => by simp at e; exact h e.1.symm) + +/-! ## 6. Composition (lines 155–160) + +No `pathmap` operation computes it in one step; the program `descend_to`s each +path of the left operand and `join_map_into`s the right one there. -/ + +section Composition +variable (s t u : Space) + +/-- line 155 -/ +theorem empty_composition : composition empty t = empty := ext fun p => by + rw [mem_composition] + exact ⟨fun ⟨_, _, _, h, _⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 156 -/ +theorem composition_empty : composition s empty = empty := ext fun p => by + rw [mem_composition] + exact ⟨fun ⟨_, _, _, _, h⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 157 -/ +theorem union_composition : composition (union s t) u = union (composition s u) (composition t u) := + ext fun p => by + simp only [mem_composition, mem_union] + constructor + · rintro ⟨a, b, rfl, ha | ha, hb⟩ + · exact Or.inl ⟨a, b, rfl, ha, hb⟩ + · exact Or.inr ⟨a, b, rfl, ha, hb⟩ + · rintro (⟨a, b, rfl, ha, hb⟩ | ⟨a, b, rfl, ha, hb⟩) + · exact ⟨a, b, rfl, Or.inl ha, hb⟩ + · exact ⟨a, b, rfl, Or.inr ha, hb⟩ +/-- line 158 -/ +theorem composition_union : composition s (union t u) = union (composition s t) (composition s u) := + ext fun p => by + simp only [mem_composition, mem_union] + constructor + · rintro ⟨a, b, rfl, ha, hb | hb⟩ + · exact Or.inl ⟨a, b, rfl, ha, hb⟩ + · exact Or.inr ⟨a, b, rfl, ha, hb⟩ + · rintro (⟨a, b, rfl, ha, hb⟩ | ⟨a, b, rfl, ha, hb⟩) + · exact ⟨a, b, rfl, ha, Or.inl hb⟩ + · exact ⟨a, b, rfl, ha, Or.inr hb⟩ +/-- line 160 -/ +theorem singleton_composition (p : Path) : composition (singleton p) t = wrap p t := ext fun q => by + simp only [mem_composition, mem_wrap, mem_singleton] + constructor + · rintro ⟨a, b, rfl, rfl, hb⟩; exact ⟨b, rfl, hb⟩ + · rintro ⟨b, rfl, hb⟩; exact ⟨p, b, rfl, rfl, hb⟩ +/-- line 159 -/ +theorem singleton_union_composition (p : Path) : + composition (union (singleton p) s) t = union (wrap p t) (composition s t) := by + rw [union_composition, singleton_composition] + +end Composition + +/-! ## 7. Tails, head, restriction, raffination (lines 162–198) + +`TailsUnion` and `TailsIntersection` fold `join_map_into` and `meet_into` over +`child_mask`; `Head` reads `child_mask` alone. egg's `tails-intersection` rules +(171–182) are a fold over an enumeration of the heads, and +`tailsInter_eq_foldl` is that fold for *any* enumeration, in any order, with +repeats. -/ + +/-- line 162 -/ +theorem tailsUnion_empty : tailsUnion empty = empty := ext fun p => by + rw [mem_tailsUnion] + exact ⟨fun ⟨_, h⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 164 -/ +theorem tailsUnion_eps : tailsUnion (singleton []) = empty := ext fun p => by + rw [mem_tailsUnion] + simp only [mem_singleton, reduceCtorEq, exists_false, false_iff] + exact not_mem_empty p +/-- line 166 -/ +theorem tailsUnion_cons (h : UInt8) (t : Path) : tailsUnion (singleton (h :: t)) = singleton t := + ext fun p => by + simp only [mem_tailsUnion, mem_singleton, List.cons.injEq] + exact ⟨fun ⟨_, _, e⟩ => e, fun e => ⟨h, rfl, e⟩⟩ +/-- line 165 -/ +theorem tailsUnion_item (h : UInt8) : tailsUnion (singleton [h]) = singleton [] := tailsUnion_cons h [] +/-- line 167 -/ +theorem tailsUnion_union (s t : Space) : tailsUnion (union s t) = union (tailsUnion s) (tailsUnion t) := + ext fun p => by + simp only [mem_tailsUnion, mem_union] + constructor + · rintro ⟨b, h | h⟩ + · exact Or.inl ⟨b, h⟩ + · exact Or.inr ⟨b, h⟩ + · rintro (⟨b, h⟩ | ⟨b, h⟩) + · exact ⟨b, Or.inl h⟩ + · exact ⟨b, Or.inr h⟩ +/-- line 169 -/ +theorem tailsUnion_wrap (a : UInt8) (s : Space) : tailsUnion (wrap [a] s) = s := ext fun p => by + simp only [mem_tailsUnion, mem_wrap, List.singleton_append, List.cons.injEq] + exact ⟨fun ⟨_, _, ⟨_, e⟩, h⟩ => e ▸ h, fun h => ⟨a, p, ⟨rfl, rfl⟩, h⟩⟩ +/-- line 168 -/ +theorem tailsUnion_wrap_union (a : UInt8) (s t : Space) : + tailsUnion (union (wrap [a] s) t) = union s (tailsUnion t) := by + rw [tailsUnion_union, tailsUnion_wrap] + +/-- The head enumerations egg's fold may use: a list naming each head at least +once and nothing else. -/ +def EnumHeads (x : Space) (hs : List UInt8) : Prop := ∀ c, c ∈ hs ↔ [c] ∈ head x + +theorem enumHeads_iff {x : Space} {hs : List UInt8} : + EnumHeads x hs ↔ ∀ c, c ∈ hs ↔ ∃ r, c :: r ∈ x := by + unfold EnumHeads + simp only [mem_head, List.cons.injEq, and_true] + constructor + · intro h c; rw [h c]; exact ⟨fun ⟨_, r, rfl, hr⟩ => ⟨r, hr⟩, fun ⟨r, hr⟩ => ⟨c, r, rfl, hr⟩⟩ + · intro h c; rw [h c]; exact ⟨fun ⟨r, hr⟩ => ⟨c, r, rfl, hr⟩, fun ⟨_, r, rfl, hr⟩ => ⟨r, hr⟩⟩ + +/-- line 173: no heads, no tails. -/ +theorem tailsInter_of_head_empty {x : Space} (h : head x = empty) : tailsInter x = empty := + ext fun p => by + rw [mem_tailsInter] + refine ⟨fun ⟨⟨b, r, hr⟩, _⟩ => ?_, fun h' => absurd h' (not_mem_empty p)⟩ + have : [b] ∈ head x := mem_head.mpr ⟨b, r, rfl, hr⟩ + rw [h] at this; exact absurd this (not_mem_empty _) + +/-- lines 177–182: egg's accumulating fold, `tails-intersection-acc`, over any +enumeration `h :: rest` of the heads. -/ +theorem tailsInter_eq_foldl {x : Space} {h : UInt8} {rest : List UInt8} + (he : EnumHeads x (h :: rest)) : + tailsInter x = rest.foldl (fun acc c => inter acc (unwrap x [c])) (unwrap x [h]) := by + have he' := enumHeads_iff.mp he + apply ext; intro p + rw [mem_tailsInter, mem_foldl_inter (fun c => unwrap x [c]), mem_unwrap] + simp only [mem_unwrap, List.singleton_append] + constructor + · rintro ⟨_, hall⟩ + exact ⟨hall h ((he' h).mp List.mem_cons_self), + fun c hc => hall c ((he' c).mp (List.mem_cons_of_mem _ hc))⟩ + · rintro ⟨h0, hall⟩ + refine ⟨⟨h, (he' h).mp List.mem_cons_self⟩, fun c hc => ?_⟩ + rcases List.mem_cons.mp ((he' c).mpr hc) with rfl | hc' + · exact h0 + · exact hall c hc' + +/-- line 175: one head. -/ +theorem tailsInter_of_head_singleton {x : Space} {h : UInt8} (hh : head x = singleton [h]) : + tailsInter x = unwrap x [h] := by + rw [tailsInter_eq_foldl (rest := [])] + · rfl + · intro c; rw [hh, mem_singleton]; simp + +/-- line 184 -/ +theorem restriction_empty_left (y : Space) : restriction empty y = empty := ext fun p => by + rw [mem_restriction]; exact ⟨fun h => h.1, fun h => absurd h (not_mem_empty p)⟩ +/-- line 185 -/ +theorem restriction_empty_right (x : Space) : restriction x empty = empty := ext fun p => by + rw [mem_restriction] + exact ⟨fun ⟨_, _, _, _, h⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 186 -/ +theorem restriction_eps (x : Space) : restriction x (singleton []) = x := ext fun p => by + rw [mem_restriction] + exact ⟨fun h => h.1, fun h => ⟨h, [], p, rfl, mem_singleton.mpr rfl⟩⟩ +/-- line 187 -/ +theorem restriction_union (x p q : Space) : + restriction x (union p q) = union (restriction x p) (restriction x q) := ext fun r => by + simp only [mem_restriction, mem_union] + constructor + · rintro ⟨hx, a, b, rfl, ha | ha⟩ + · exact Or.inl ⟨hx, a, b, rfl, ha⟩ + · exact Or.inr ⟨hx, a, b, rfl, ha⟩ + · rintro (⟨hx, a, b, rfl, ha⟩ | ⟨hx, a, b, rfl, ha⟩) + · exact ⟨hx, a, b, rfl, Or.inl ha⟩ + · exact ⟨hx, a, b, rfl, Or.inr ha⟩ +/-- line 188 -/ +theorem restriction_singleton (x : Space) (p : Path) : + restriction x (singleton p) = wrap p (unwrap x p) := ext fun q => by + simp only [mem_restriction, mem_wrap, mem_unwrap, mem_singleton] + constructor + · rintro ⟨hx, a, b, rfl, rfl⟩; exact ⟨b, rfl, hx⟩ + · rintro ⟨b, rfl, hx⟩; exact ⟨hx, p, b, rfl, rfl⟩ +/-- line 197: every path of `x` has itself as a prefix. -/ +theorem restriction_self (x : Space) : restriction x x = x := ext fun p => by + rw [mem_restriction]; exact ⟨fun h => h.1, fun h => ⟨h, p, [], by simp, h⟩⟩ + +/-- line 190 -/ +theorem head_empty : head empty = empty := ext fun p => by + rw [mem_head] + exact ⟨fun ⟨_, _, _, h⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 191 -/ +theorem head_eps : head (singleton []) = empty := ext fun p => by + rw [mem_head] + simp only [mem_singleton, reduceCtorEq, and_false, exists_false, false_iff] + exact not_mem_empty p +/-- line 192 -/ +theorem head_union (x y : Space) : head (union x y) = union (head x) (head y) := ext fun p => by + simp only [mem_head, mem_union] + constructor + · rintro ⟨b, r, rfl, h | h⟩ + · exact Or.inl ⟨b, r, rfl, h⟩ + · exact Or.inr ⟨b, r, rfl, h⟩ + · rintro (⟨b, r, rfl, h⟩ | ⟨b, r, rfl, h⟩) + · exact ⟨b, r, rfl, Or.inl h⟩ + · exact ⟨b, r, rfl, Or.inr h⟩ +/-- line 193 -/ +theorem head_cons (h : UInt8) (t : Path) : head (singleton (h :: t)) = singleton [h] := ext fun p => by + simp only [mem_head, mem_singleton, List.cons.injEq] + exact ⟨fun ⟨_, _, e, rfl, _⟩ => e, fun e => ⟨h, t, e, rfl, rfl⟩⟩ +/-- line 194 -/ +theorem head_item (h : UInt8) : head (singleton [h]) = singleton [h] := head_cons h [] + +/-- line 198: raffination is *defined* as `x \ (x <| y)`. -/ +theorem raffination_def (x y : Space) : raffination x y = subtr x (restriction x y) := rfl +/-- line 198's consequence. -/ +theorem raffination_self (x : Space) : raffination x x = empty := by + rw [raffination_def, restriction_self, subtr_self] + +/-! ## 8. Iteration (lines 202–242) + +`IterC` is `Iter` with a body that ignores its arguments, so its rules are +instances of `Iter`'s. egg's comment on rule L2 makes a point worth keeping: +`IterH` distributes over a union of its *head set*, with the source held fixed; +`Iter` does **not** distribute over a union of its *source*, because a head +shared by the two operands merges their groups and the body sees the merge. +`iter_not_union_source` is that refutation (egg's N05). -/ + +/-- line 239 (L1) -/ +theorem iter_def (src : Space) (body : UInt8 → Space → Space) : + iter src body = iterH (head src) src body := rfl +/-- line 240 (L4) -/ +theorem iterH_empty (src : Space) (body : UInt8 → Space → Space) : iterH empty src body = empty := + ext fun p => by + rw [mem_iterH] + exact ⟨fun ⟨_, h, _⟩ => absurd h (not_mem_empty _), fun h => absurd h (not_mem_empty p)⟩ +/-- line 241 (L2) -/ +theorem iterH_union (a c src : Space) (body : UInt8 → Space → Space) : + iterH (union a c) src body = union (iterH a src body) (iterH c src body) := ext fun p => by + simp only [mem_iterH, mem_union] + constructor + · rintro ⟨h, ha | ha, hp⟩ + · exact Or.inl ⟨h, ha, hp⟩ + · exact Or.inr ⟨h, ha, hp⟩ + · rintro (⟨h, ha, hp⟩ | ⟨h, ha, hp⟩) + · exact ⟨h, Or.inl ha, hp⟩ + · exact ⟨h, Or.inr ha, hp⟩ +/-- line 242 (L3) -/ +theorem iterH_item (h : UInt8) (src : Space) (body : UInt8 → Space → Space) : + iterH (singleton [h]) src body = body h (unwrap src [h]) := ext fun p => by + simp only [mem_iterH, mem_singleton, List.cons.injEq, and_true] + exact ⟨fun ⟨_, e, hp⟩ => e ▸ hp, fun hp => ⟨h, rfl, hp⟩⟩ + +/-- N05: iteration does not distribute over a union of its source. `a` and `c` +share the head `1`; the body asks whether its group holds both `[0]` and `[1]`, +which only the merged group does. -/ +theorem iter_not_union_source : + ¬ ∀ (a c : Space) (body : UInt8 → Space → Space), + iter (union a c) body = union (iter a body) (iter c body) := by + intro hall + let body : UInt8 → Space → Space := fun _ g => if [0] ∈ g ∧ [1] ∈ g then singleton [] else empty + have e := hall (singleton [1, 0]) (singleton [1, 1]) body + have hl : [] ∈ iter (union (singleton [1, 0]) (singleton [1, 1])) body := by + rw [mem_iter] + refine ⟨1, ⟨[0], mem_union.mpr (Or.inl (mem_singleton.mpr rfl))⟩, ?_⟩ + have h0 : [0] ∈ unwrap (union (singleton [1, 0]) (singleton [1, 1])) [1] := + mem_unwrap.mpr (mem_union.mpr (Or.inl (mem_singleton.mpr rfl))) + have h1 : [1] ∈ unwrap (union (singleton [1, 0]) (singleton [1, 1])) [1] := + mem_unwrap.mpr (mem_union.mpr (Or.inr (mem_singleton.mpr rfl))) + show [] ∈ (if _ then _ else _) + rw [if_pos ⟨h0, h1⟩]; exact mem_singleton.mpr rfl + have hr : [] ∉ union (iter (singleton [1, 0]) body) (iter (singleton [1, 1]) body) := by + rw [mem_union, mem_iter, mem_iter] + rintro (⟨h, _, hp⟩ | ⟨h, _, hp⟩) + · show False + revert hp; show [] ∈ (if _ then _ else _) → False + rw [if_neg] + · exact not_mem_empty _ + · rintro ⟨_, h1⟩ + have := mem_singleton.mp (mem_unwrap.mp h1); simp at this + · show False + revert hp; show [] ∈ (if _ then _ else _) → False + rw [if_neg] + · exact not_mem_empty _ + · rintro ⟨h0, _⟩ + have := mem_singleton.mp (mem_unwrap.mp h0); simp at this + exact hr (e ▸ hl) + +/-- line 204 -/ +theorem iterC_empty (b : Space) : iterC empty b = empty := by + rw [iterC, iter_def, head_empty, iterH_empty] +/-- line 205: a `{ε}` source has no heads (the case egg's prover caught). -/ +theorem iterC_eps (b : Space) : iterC (singleton []) b = empty := by + rw [iterC, iter_def, head_eps, iterH_empty] +/-- line 207 -/ +theorem iterC_cons (h : UInt8) (t : Path) (b : Space) : iterC (singleton (h :: t)) b = b := by + rw [iterC, iter_def, head_cons, iterH_item] +/-- line 206 -/ +theorem iterC_item (h : UInt8) (b : Space) : iterC (singleton [h]) b = b := iterC_cons h [] b +/-- line 208: the source *does* distribute when the body cannot see its group. -/ +theorem iterC_union (s t b : Space) : iterC (union s t) b = union (iterC s b) (iterC t b) := + ext fun p => by + simp only [mem_iterC, mem_union] + constructor + · rintro ⟨⟨h, r, hr | hr⟩, hp⟩ + · exact Or.inl ⟨⟨h, r, hr⟩, hp⟩ + · exact Or.inr ⟨⟨h, r, hr⟩, hp⟩ + · rintro (⟨⟨h, r, hr⟩, hp⟩ | ⟨⟨h, r, hr⟩, hp⟩) + · exact ⟨⟨h, r, Or.inl hr⟩, hp⟩ + · exact ⟨⟨h, r, Or.inr hr⟩, hp⟩ + +/-! ## 9. Least fixpoints (lines 244–292) + +egg introduces `Fix i F` as a first-class term and *axiomatises* it with three +rules: it contains `i` (line 288), it contains `F` of itself (line 289), and it +is below every `c` that does both (Park induction, line 291). Those rules are a +definition, so here they are the fields of a predicate, `IsLeastPostFix`, and +egg's `⊑` is its own encoding, `Union a c = c`. + +What egg's comment argues and does not mechanise is that the executors compute +this: they iterate the *inflationary* operator `cur ↦ cur ∪ F cur` until it +stops changing, and when `F` is monotone the value it stops at is the least +post-fixpoint above `i`. `kleene_isLeastPostFix` proves that. Monotonicity is +used only for leastness, as egg's comment says. -/ + +/-- egg's `⊑`: `Union a b = b`. -/ +theorem union_eq_right_iff {a b : Space} : union a b = b ↔ ∀ p, p ∈ a → p ∈ b := by + constructor + · intro h p hp; rw [← h]; exact mem_union.mpr (Or.inl hp) + · intro h; exact ext fun p => by + rw [mem_union]; exact ⟨fun h' => h'.elim (h p) id, Or.inr⟩ + +/-- `X` is the least post-fixpoint of `F` above `i`: egg's `Fix i F`. -/ +structure IsLeastPostFix (i : Space) (F : Space → Space) (X : Space) : Prop where + /-- line 288: `Fix ⊒ init` -/ + init : union i X = X + /-- line 289: `Fix ⊒ F(Fix)` -/ + post : union (F X) X = X + /-- line 291: Park induction -/ + park : ∀ c, union i c = c → union (F c) c = c → union X c = c + +/-- The least post-fixpoint is unique, so `Fix i F` is well defined. -/ +theorem IsLeastPostFix.unique {i X Y : Space} {F : Space → Space} + (hX : IsLeastPostFix i F X) (hY : IsLeastPostFix i F Y) : X = Y := by + have h1 := union_eq_right_iff.mp (hX.park Y hY.init hY.post) + have h2 := union_eq_right_iff.mp (hY.park X hX.init hX.post) + exact ext fun p => ⟨h1 p, h2 p⟩ + +/-- line 287 and the tour's line 436: with the identity step, `Fix i (λX.X) = i`. -/ +theorem fix_self (i : Space) : IsLeastPostFix i id i where + init := union_idem i + post := union_idem i + park _ h _ := h + +/-- `F` preserves `⊑`. -/ +def Monotone (F : Space → Space) : Prop := ∀ a b, union a b = b → union (F a) (F b) = F b + +/-- The executors' loop: `cur := cur ∪ F(cur)`. -/ +def kleene (i : Space) (F : Space → Space) : Nat → Space + | 0 => i + | n + 1 => union (kleene i F n) (F (kleene i F n)) + +theorem init_le_kleene (i : Space) (F : Space → Space) : ∀ n p, p ∈ i → p ∈ kleene i F n + | 0, _, h => h + | n + 1, p, h => mem_union.mpr (Or.inl (init_le_kleene i F n p h)) + +/-- **The loop computes `Fix`.** When the inflationary iteration stops changing +and `F` is monotone, where it stopped is the least post-fixpoint above `i`. -/ +theorem kleene_isLeastPostFix {i : Space} {F : Space → Space} (hF : Monotone F) {n : Nat} + (hn : kleene i F (n + 1) = kleene i F n) : IsLeastPostFix i F (kleene i F n) where + init := union_eq_right_iff.mpr (init_le_kleene i F n) + post := by + rw [union_comm]; exact hn + park c hi hc := by + have hi' := union_eq_right_iff.mp hi + have hc' := union_eq_right_iff.mp hc + have key : ∀ m p, p ∈ kleene i F m → p ∈ c := by + intro m + induction m with + | zero => exact hi' + | succ m ih => + intro p hp + rcases mem_union.mp hp with h | h + · exact ih p h + · have hm := union_eq_right_iff.mp (hF _ _ (union_eq_right_iff.mpr ih)) + exact hc' p (hm p h) + exact union_eq_right_iff.mpr (key n) + +/-! ## 10. The raw zipper operations are the set operators + +`Refine.lean` says exactly what each write operation puts at its focus. Before +issue #104, `join_into`, `restrict`, `insert_prefix` and `join_k_path_into` +worked on the node below the focus and so missed the focus value, and +`meet_k_path_into` kept the focus value when its meet was empty. Under #104 +each carries the focus value with the subtrie, and each is its egg operator +outright. -/ + +/-- `join_into` is `Union`. -/ +theorem joinInto_eq_union (a b : Space) : ((wz a).joinInto unitOps (wz b)).2.trie = union a b := by + rw [PZip.joinInto_eq _ unitOps_lawful, PZip.withTrie_trie, wz_focus, replaceAt_nil, wz_makeMap, + wz_makeMap, union_eq_join] + +/-- `restrict` is `Restriction` — by definition (§1), and `mem_restriction` is the +membership law egg states for it. -/ +theorem restrict_eq_restriction (x y : Space) : + ((wz x).restrict unitOps (wz y)).2.trie = restriction x y := rfl + +/-- `insert_prefix p` is `Wrap p`. -/ +theorem insertPrefix_eq_wrap (pre : Path) (s : Space) : ((wz s).insertPrefix pre).2.trie = wrap pre s := + ext fun p => by + rw [PZip.insertPrefix_eq, PZip.withTrie_trie, wz_focus, replaceAt_nil, wz_makeMap, mem_wrap, + mem_def, valAt_prepend] + cases hs : Path.stripPrefix pre p with + | none => + simp only [Option.isSome_none, Bool.false_eq_true, false_iff, not_exists, not_and] + intro r hr; exact absurd hr ((Path.stripPrefix_eq_none pre p).mp hs r) + | some r => + have := (Path.stripPrefix_eq_some pre p r).mp hs; subst this + constructor + · intro h; exact ⟨r, rfl, h⟩ + · rintro ⟨r', hr', h⟩ + rw [List.append_cancel_left hr']; exact h + +/-- The locations one byte down are the heads. -/ +theorem mem_kPaths_one {s : Space} {q : Path} : q ∈ s.kPaths 1 ↔ ∃ b r, q = [b] ∧ b :: r ∈ s := by + rw [kPaths, List.mem_filter, PrunedMap.paths, Path.mem_sortDedup] + constructor + · rintro ⟨hm, hl⟩ + have hl : q.length = 1 := by simpa using hl + rcases List.mem_cons.mp hm with rfl | hm + · cases hl + · obtain ⟨k, hk, hq⟩ := List.mem_flatMap.mp hm + obtain ⟨n, _, rfl⟩ := List.mem_map.mp hq + match k, n with + | [], _ => simp at hl + | _ :: _, 0 => simp at hl + | b :: r, n + 1 => + refine ⟨b, r, ?_, mem_keys.mp hk⟩ + simp only [List.take_succ_cons, List.length_cons, Nat.add_eq_right, + List.length_eq_zero_iff] at hl ⊢ + rw [hl] + · rintro ⟨b, r, rfl, h⟩ + refine ⟨List.mem_cons_of_mem _ (List.mem_flatMap.mpr ⟨b :: r, mem_keys.mpr h, ?_⟩), rfl⟩ + exact List.mem_map.mpr ⟨1, List.mem_range.mpr (by simp), rfl⟩ + +/-- `join_k_path_into 1` is `TailsUnion`. -/ +theorem joinKPathInto_one_eq_tailsUnion (s : Space) : + ((wz s).joinKPathInto unitOps 1).2.trie = tailsUnion s := ext fun p => by + rw [PZip.joinKPathInto_eq, if_neg (by decide), PZip.withTrie_trie, wz_focus, replaceAt_nil, + wz_makeMap, mem_tailsUnion, dropHead, if_neg (by decide)] + have hf : (fun acc q => join unitOps acc (s.subtrie q)) = (fun acc q => union acc (s.subtrie q)) := by + funext acc q; rw [union_eq_join] + rw [hf, mem_foldl_union (fun q => s.subtrie q), or_iff_right (show p ∉ (PrunedMap.empty : Space) from not_mem_empty p)] + constructor + · rintro ⟨q, hq, hp⟩ + obtain ⟨b, r, rfl, _⟩ := mem_kPaths_one.mp hq + refine ⟨b, ?_⟩ + rw [mem_def, valAt_subtrie] at hp; exact hp + · rintro ⟨b, h⟩ + refine ⟨[b], mem_kPaths_one.mpr ⟨b, p, rfl, h⟩, ?_⟩ + rw [mem_def, valAt_subtrie]; exact h + +theorem mem_meet {p : Path} {a b : Space} : p ∈ meet unitOps a b ↔ p ∈ a ∧ p ∈ b := by + rw [mem_def, unit_meet_isSome, Bool.and_eq_true]; rfl + +theorem foldl_meetStep_eq_none (s : Space) : ∀ (L : List Path) (acc : Option Space), + L.foldl (PZip.meetStep unitOps s []) acc = none ↔ acc = none ∧ L = [] + | [], acc => by simp + | q :: L, acc => by + rw [List.foldl_cons, foldl_meetStep_eq_none s L] + cases acc <;> simp [PZip.meetStep] + +theorem mem_foldl_meetStep (s : Space) (p : Path) : ∀ (L : List Path) (acc : Option Space) (M : Space), + L.foldl (PZip.meetStep unitOps s []) acc = some M → + (p ∈ M ↔ (∀ a, acc = some a → p ∈ a) ∧ ∀ q ∈ L, q ++ p ∈ s) + | [], acc, M, h => by + simp only [List.foldl_nil] at h; subst h + simp only [List.not_mem_nil, false_imp_iff, implies_true, and_true] + exact ⟨fun hp a ha => by cases ha; exact hp, fun h => h M rfl⟩ + | q :: L, acc, M, h => by + rw [List.foldl_cons] at h + rw [mem_foldl_meetStep s p L _ M h, List.forall_mem_cons] + have hq : p ∈ s.subtrie ([] ++ q) ↔ q ++ p ∈ s := by rw [mem_def, valAt_subtrie]; simp; rfl + cases acc with + | none => + simp only [PZip.meetStep, Option.some.injEq, forall_eq', reduceCtorEq, false_imp_iff, + implies_true, true_and] + rw [hq] + | some a0 => + simp only [PZip.meetStep, Option.some.injEq, forall_eq'] + rw [mem_meet, hq, and_assoc] + +/-- `meet_k_path_into 1` is `TailsIntersection`. -/ +theorem meetKPathInto_one_eq_tailsInter (s : Space) : + ((wz s).meetKPathInto unitOps 1).2.trie = tailsInter s := ext fun p => by + rw [PZip.meetKPathInto_snd, PZip.graftMap_eq, PZip.withTrie_trie, wz_focus, replaceAt_nil, + mem_tailsInter] + simp only [wz_trie] + rw [subtrie_nil] + cases h : (s.kPaths 1).foldl (PZip.meetStep unitOps s []) none with + | none => + have hL := ((foldl_meetStep_eq_none s _ _).mp h).2 + simp only [Option.getD_none] + refine ⟨fun hp => absurd hp (not_mem_empty p), ?_⟩ + rintro ⟨⟨b, r, hb⟩, _⟩ + have := mem_kPaths_one.mpr ⟨b, r, rfl, hb⟩ + rw [hL] at this; cases this + | some M => + simp only [Option.getD_some] + rw [mem_foldl_meetStep s p _ _ M h] + have hne : s.kPaths 1 ≠ [] := fun e => by + rw [e] at h; cases h + obtain ⟨q0, hq0⟩ := List.exists_mem_of_ne_nil _ hne + obtain ⟨b0, r0, -, hb0⟩ := mem_kPaths_one.mp hq0 + simp only [reduceCtorEq, false_imp_iff, implies_true, true_and] + constructor + · intro hall + refine ⟨⟨b0, r0, hb0⟩, fun b ⟨r, hr⟩ => ?_⟩ + exact hall [b] (mem_kPaths_one.mpr ⟨b, r, rfl, hr⟩) + · rintro ⟨_, hall⟩ q hq + obtain ⟨b, r, rfl, hr⟩ := mem_kPaths_one.mp hq + exact hall b ⟨r, hr⟩ + +/-! ## 11. The tour (lines 294–436) + +Every `(check (= a b))` is a `#guard a == b`, every `(fail (check …))` a +`#guard … != …`. Items are bytes; the letters are egg's `a..z = 10..35`. -/ + +section Tour + +private def it (a : UInt8) : Space := singleton [a] +private def expr1 := union (it 10) (it 11) +private def expr2 := wrap [18] expr1 +private def expr3 := union (singleton [18, 10]) (singleton [18, 11]) +private def expr4 := unwrap expr3 [18] +private def expr_qi : Path := [26, 18] +private def expr_qi_unwrap := unwrap (wrap expr_qi expr1) expr_qi +private def expr_unwrap_prefix := unwrap (singleton [10, 11]) [10] +private def expr_unwrap_exact := unwrap (singleton [10, 11]) [10, 11] +private def expr_unwrap_miss := unwrap (singleton [10]) [11] +private def expr1_ := union (it 33) (it 34) +private def expr_prod := composition expr1_ expr1 +private def expr_prod_expanded := + union (union (singleton [33, 10]) (singleton [33, 11])) (union (singleton [34, 10]) (singleton [34, 11])) +private def expr_tailsunion1 := tailsUnion expr_prod_expanded +private def expr_tailsintersection1 := tailsInter expr_prod_expanded +private def expr1_head := head expr1 +private def expr3_head := head expr3 +private def expr_prod_head := head expr_prod_expanded +private def expr_s0 := it 0 +private def expr_restriction_keys := + union (union (composition expr1 (it 0)) (composition (union (it 10) (union (it 12) (it 13))) (it 1))) + (composition (it 12) (it 2)) +private def expr_restriction := restriction expr_restriction_keys expr1 +private def expr_restriction_tailsintersection := tailsInter expr_restriction +private def expr_restriction_res1 := + union (union (singleton [10, 0]) (singleton [10, 1])) (singleton [11, 0]) +private def expr_restriction_multi := + restriction (union (wrap [10] (it 0)) (wrap [11] (it 1))) (union (it 10) (it 11)) +private def expr_restriction_multi_res := union (singleton [10, 0]) (singleton [11, 1]) +private def expr_restriction_multi_only_a := singleton [10, 0] +private def expr_tailsintersection_duplicate_heads := + tailsInter (union (union (wrap [10] (it 0)) (wrap [10] (it 1))) (wrap [11] (it 0))) +private def restr_self := restriction expr1 expr1 +private def raff_self := raffination expr1 expr1 +private def unwrap_chain := unwrap (unwrap (singleton [10, 11, 12]) [10]) [11] +private def wrap_unwrap_miss := unwrap (wrap [32] expr1) [10] +private def tails_single := tailsUnion (singleton [10, 11]) +private def iu_body := union (it 21) (it 27) +private def iu_orig_empty := iterC empty iu_body +private def iu_distr_empty := union (iterC empty (it 21)) (iterC empty (it 27)) +private def iu_hoist_empty := union (it 21) (iterC empty (it 27)) + +#guard expr2 == expr3 +#guard expr1 == expr4 +#guard expr_qi_unwrap == expr1 +#guard expr_unwrap_prefix == it 11 +#guard expr_unwrap_exact == singleton [] +#guard expr_unwrap_miss == empty +#guard expr_prod == expr_prod_expanded +#guard expr_tailsunion1 == expr1 +#guard expr_tailsintersection1 == expr1 +#guard expr_restriction == expr_restriction_res1 +#guard expr_restriction_tailsintersection == expr_s0 +#guard expr_restriction_multi == expr_restriction_multi_res +#guard expr_restriction_multi != expr_restriction_multi_only_a +#guard expr_tailsintersection_duplicate_heads == expr_s0 +#guard expr_tailsintersection_duplicate_heads != empty +#guard restr_self == expr1 +#guard raff_self == empty +#guard unwrap_chain == it 12 +#guard wrap_unwrap_miss == empty +#guard tails_single == it 11 +#guard expr1_head == expr1 +#guard expr3_head == it 18 +#guard expr_prod_head == expr1_ +#guard iu_orig_empty == empty +#guard iu_orig_empty == iu_distr_empty +#guard iu_orig_empty != iu_hoist_empty + +/-- The tour's step `F(X) = X ∪ {b}` (line 391). -/ +private def step900 (x : Space) : Space := union x (it 11) + +private theorem step900_mono : Monotone step900 := by + intro a b h + rw [union_eq_right_iff] at h ⊢ + intro p hp + simp only [step900, mem_union] at hp ⊢ + exact hp.elim (fun h' => Or.inl (h p h')) Or.inr + +/-- line 434: `Fix({a,b}, X ↦ X ∪ {b}) = {a,b}`, as the executors' loop reaches it. -/ +theorem fix_ab : IsLeastPostFix expr1 step900 expr1 := by + have h : kleene expr1 step900 1 = kleene expr1 step900 0 := by + show union expr1 (union expr1 (it 11)) = expr1 + rw [← union_assoc, union_idem, union_comm, union_eq_right_iff] + intro p hp; exact mem_union.mpr (Or.inr (mem_singleton.mp hp ▸ mem_singleton.mpr rfl)) + exact kleene_isLeastPostFix step900_mono h + +/-- line 435: `{a}` is not it — Park must not fire there, because `{a}` is not +above the initial value. -/ +theorem fix_not_too_small : ¬ IsLeastPostFix expr1 step900 (it 10) := by + intro h + have := fix_ab.unique h + have hb : [11] ∈ expr1 := mem_union.mpr (Or.inr (mem_singleton.mpr rfl)) + rw [this] at hb + exact absurd (mem_singleton.mp hb) (by decide) + +end Tour + +end Zippy +end PrunedModel diff --git a/lean/README.md b/lean/README.md index e6827ae3..1a0c719b 100644 --- a/lean/README.md +++ b/lean/README.md @@ -156,6 +156,31 @@ focus, such that ..." — instead of as a node walk. | `PathMapModel/Fuzz.lean` | the wire format, the operation table, and the trace producer (including `--act` mode) | | `Main.lean` | the `pathmap-oracle` binary | +### Zippy's set algebra (`PrunedModel/`) + +A second, dangling-path-free model, carried here for one purpose: proving +[Zippy's `formal.egg`](https://github.com/Adam-Vandervorst/Zippy/blob/b/formal.egg) +— the reference semantics of Zippy's space algebra — about `pathmap`'s write +zipper, and exporting those laws to the algebraic fuzzer. A location exists iff +some key has it as a prefix, so a dangling path is unrepresentable. The model +follows `focus_value_consistency` (issue #104: a subtrie includes its root +value), which master's crate does not implement yet; the laws are about the +model's zipper programs, and the fuzzer builds each operator from crate +operations that agree on master. The pruned differential fuzzer that checks +this model against the crate lives on branch `spec/zippy-laws-fvc`. + +| file | contents | +| --- | --- | +| `PrunedModel/Canon.lean` | canonical association lists: keys strictly sorted, hence distinct | +| `PrunedModel/Map.lean` | `PrunedMap`: the map operations over the canonical form | +| `PrunedModel/Zipper.lean`, `Write.lean` | the read and write zipper over a `PrunedMap`, issue-#104 semantics, no prune flag | +| `PrunedModel/Spec.lean` | the model's one claim, `no_dangling`, and its consequences | +| `PrunedModel/Lattice.lean`, `Nested.lean` | the lattice laws as equations (`unitOps` makes a map a set of paths); a trie as another trie's value | +| `PrunedModel/Pointwise.lean` | `valAt` of every map operation | +| `PrunedModel/Refine.lean` | each write op as `z.withTrie (z.trie.replaceAt z.focus M)` | +| `PrunedModel/Zippy.lean` | each egg operator as a zipper program over `Space = PrunedMap Unit`, every `formal.egg` rule proved, `Fix` as a least post-fixpoint, the raw ops = egg ops under #104 (§10), the tour as `#guard`s | +| `ZippyLaws.lean` | exports Zippy.lean's equational theorems as `differential/src/algebraic/zippy_laws.rs`: `lake build PrunedModel && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs` | + ## What is proved versus what is checked Honest accounting, because it matters for how much the model is worth: diff --git a/lean/ZippyLaws.lean b/lean/ZippyLaws.lean new file mode 100644 index 00000000..62c7428f --- /dev/null +++ b/lean/ZippyLaws.lean @@ -0,0 +1,314 @@ +import Lean + +/-! +# Export `PrunedModel/Zippy.lean`'s equational laws as Rust + +Run from this directory: + + lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs + +The program imports the *elaborated* module `PrunedModel.Zippy` and walks its +theorems. A theorem is exported when every binder is a space, a path or a +byte, or a hypothesis of a supported shape (`≠` on paths or bytes, `∈`/`∉`, `=` +on spaces); its conclusion is an equation of spaces; both sides are built from +the operator vocabulary below; and its proof uses no `sorryAx`. Everything else +is listed at the end of the output with the reason it was not exported. + +Terms are translated by their application head and never unfolded: the point is +to emit the operator the theorem names. +-/ + +open Lean Meta + +namespace ZippyLaws + +def zippyNs : Name := `PrunedModel.Zippy +def zippyModule : Name := `PrunedModel.Zippy + +inductive VarKind | space | path | byte + deriving BEq + +structure St where + vars : Std.HashMap FVarId (VarKind × Nat) := {} + nSpace : Nat := 0 + nPath : Nat := 0 + nByte : Nat := 0 + +abbrev M := StateT St (ExceptT String MetaM) + +def fail {α} (msg : String) : M α := throwThe String msg + +def liftMeta {α} (x : MetaM α) : M α := monadLift x + +def clean (e : Expr) : MetaM Expr := do + return (← instantiateMVars e).consumeMData.headBeta + +def spaceTy : Expr := mkConst `PrunedModel.Zippy.Space +def pathTy : Expr := mkApp (mkConst ``List [Level.zero]) (mkConst ``UInt8) +def byteTy : Expr := mkConst ``UInt8 + +/-- Which variable kind a type is, if any. Types are compared up to +definitional equality, so `Space`, `PrunedMap Unit`, `Path` and `List UInt8` +are all recognised. -/ +def kindOf (ty : Expr) : MetaM (Option VarKind) := do + let ty ← clean ty + if ty.isSort then return none + if ← isDefEq ty spaceTy then return some .space + if ← isDefEq ty pathTy then return some .path + if ← isDefEq ty byteTy then return some .byte + return none + +def headName (e : Expr) : String := + match e.getAppFn with + | .const n _ => toString n + | .fvar _ => "a local function" + | .lam .. => "a lambda" + | .proj s i _ => s!"projection {s}.{i}" + | .letE .. => "a let" + | .lit _ => "a literal" + | f => s!"{f.ctorName}" + +/-- What a space-typed term mentions that is outside the vocabulary. -/ +def outside (e : Expr) : String := s!"mentions {headName e}" + +def varOf (e : Expr) (k : VarKind) : M (Option Nat) := do + match e with + | .fvar id => + match (← get).vars.get? id with + | some (k', i) => if k' == k then return some i else fail s!"variable of the wrong kind" + | none => fail "unbound local" + | _ => return none + +def litByte (e : Expr) : M (Option Nat) := do + -- `OfNat.ofNat UInt8 n inst` + if e.isAppOfArity ``OfNat.ofNat 3 then + let ty ← liftMeta (clean (e.getArg! 0)) + if ty.isConstOf ``UInt8 then + match (← liftMeta (clean (e.getArg! 1))) with + | .lit (.natVal n) => return some (n % 256) + | _ => return none + return none + +partial def byteTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .byte then return s!"bv({i})" + if let some n ← litByte e then return s!"lit({n})" + fail s!"byte term {outside e}" + +partial def pathTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .path then return s!"pv({i})" + if e.isAppOfArity ``List.nil 1 then return "nil()" + if e.isAppOfArity ``List.cons 3 then + return s!"cons({← byteTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" + if e.isAppOfArity ``HAppend.hAppend 6 then + return s!"app({← pathTerm (e.getArg! 4)}, {← pathTerm (e.getArg! 5)})" + if e.isAppOfArity ``List.append 3 then + return s!"app({← pathTerm (e.getArg! 1)}, {← pathTerm (e.getArg! 2)})" + fail s!"path term {outside e}" + +/-- The space operators: Lean name, Rust builder, and the kind of each +explicit argument. -/ +def ops : List (Name × String × List VarKind) := + [ (`PrunedModel.Zippy.empty, "empty", []), + (`PrunedModel.Zippy.singleton, "singleton", [.path]), + (`PrunedModel.Zippy.union, "union", [.space, .space]), + (`PrunedModel.Zippy.inter, "inter", [.space, .space]), + (`PrunedModel.Zippy.subtr, "subtr", [.space, .space]), + (`PrunedModel.Zippy.restriction, "restriction", [.space, .space]), + (`PrunedModel.Zippy.raffination, "raffination", [.space, .space]), + (`PrunedModel.Zippy.wrap, "wrap", [.path, .space]), + (`PrunedModel.Zippy.unwrap, "unwrap", [.space, .path]), + (`PrunedModel.Zippy.head, "head", [.space]), + (`PrunedModel.Zippy.tailsUnion, "tails_union", [.space]), + (`PrunedModel.Zippy.tailsInter, "tails_inter", [.space]), + (`PrunedModel.Zippy.composition, "composition", [.space, .space]), + (`PrunedModel.Zippy.iterC, "iter_c", [.space, .space]) ] + +mutual +partial def spaceTerm (e : Expr) : M String := do + let e ← liftMeta (clean e) + if let some i ← varOf e .space then return s!"s({i})" + let .const f _ := e.getAppFn | fail s!"space term {outside e}" + let some (_, rust, kinds) := ops.find? (·.1 == f) | fail (outside e) + let args := e.getAppArgs + unless args.size == kinds.length do + fail s!"{f} applied to {args.size} arguments, expected {kinds.length}" + let mut out := #[] + for (a, k) in args.toList.zip kinds do + out := out.push (← anyTerm a k) + return s!"{rust}({", ".intercalate out.toList})" + +partial def anyTerm (e : Expr) (k : VarKind) : M String := + match k with + | .space => spaceTerm e + | .path => pathTerm e + | .byte => byteTerm e +end + +/-- A hypothesis, as a precondition. -/ +def hypothesis (ty : Expr) : M String := do + let ty ← liftMeta (clean ty) + -- `a ≠ b` + if ty.isAppOfArity ``Ne 3 then + match ← liftMeta (kindOf (ty.getArg! 0)) with + | some .path => return s!"ne_path({← pathTerm (ty.getArg! 1)}, {← pathTerm (ty.getArg! 2)})" + | some .byte => return s!"ne_byte({← byteTerm (ty.getArg! 1)}, {← byteTerm (ty.getArg! 2)})" + | _ => fail "hypothesis is a disequation of neither paths nor bytes" + -- `p ∈ s` is `@Membership.mem Path Space inst s p`: collection first. + let memOf (m : Expr) : M (Option String) := do + let m ← liftMeta (clean m) + if m.isAppOfArity ``Membership.mem 5 then + unless (← liftMeta (kindOf (m.getArg! 1))) == some .space do + fail "hypothesis is membership in something other than a space" + return some s!"{← pathTerm (m.getArg! 4)}, {← spaceTerm (m.getArg! 3)}" + return none + if let some s ← memOf ty then return s!"mem({s})" + if ty.isAppOfArity ``Not 1 then + if let some s ← memOf (ty.getArg! 0) then return s!"not_mem({s})" + fail "hypothesis is a negation other than ∉" + if ty.isAppOfArity ``Eq 3 then + unless (← liftMeta (kindOf (ty.getArg! 0))) == some .space do + fail "hypothesis is an equation not of spaces" + return s!"eq_space({← spaceTerm (ty.getArg! 1)}, {← spaceTerm (ty.getArg! 2)})" + if ty.isForall then fail "hypothesis is a ∀" + fail s!"hypothesis {outside ty}" + +structure Law where + name : String + spaces : Nat + paths : Nat + bytes : Nat + pre : Array String + lhs : String + rhs : String + +def conclusionShape (e : Expr) : String := + match e.getAppFn with + | .const n _ => + if n == ``Iff then "Iff" else if n == ``Ne then "Ne" else if n == ``Not then "¬" + else if n == ``Eq then "an equation of another type" else toString n + | _ => headName e + +def translate (ty : Expr) : MetaM (Except String Law) := do + -- `forallTelescope`, not `…Reducing`: a conclusion like `p ∉ s` must not be + -- unfolded into another binder. + forallTelescope ty fun xs body => do + let go : M Law := do + let mut pre := #[] + for x in xs do + let decl ← liftMeta x.fvarId!.getDecl + let bty ← liftMeta (clean decl.type) + match ← liftMeta (kindOf bty) with + | some k => + let st ← get + let (i, st') := match k with + | .space => (st.nSpace, { st with nSpace := st.nSpace + 1 }) + | .path => (st.nPath, { st with nPath := st.nPath + 1 }) + | .byte => (st.nByte, { st with nByte := st.nByte + 1 }) + set { st' with vars := st'.vars.insert x.fvarId! (k, i) } + | none => + if ← liftMeta (isProp bty) then + pre := pre.push (← hypothesis bty) + else + fail s!"binder {decl.userName} : {← liftMeta (ppExpr bty)}" + let body ← liftMeta (clean body) + unless body.isAppOfArity ``Eq 3 do + fail s!"conclusion is not an equation of spaces ({conclusionShape body})" + unless (← liftMeta (kindOf (body.getArg! 0))) == some .space do + fail s!"conclusion is not an equation of spaces (equation of {← liftMeta (ppExpr (body.getArg! 0))})" + let lhs ← spaceTerm (body.getArg! 1) + let rhs ← spaceTerm (body.getArg! 2) + let st ← get + return { name := "", spaces := st.nSpace, paths := st.nPath, bytes := st.nByte, + pre, lhs, rhs } + match ← (go.run' {}).run with + | .ok l => return .ok l + | .error e => return .error e + +def relName (n : Name) : String := + let comps := n.components.drop zippyNs.components.length + ".".intercalate (comps.map toString) + +def skipName (env : Environment) (n : Name) : Bool := + n.isInternal || isPrivateName n || isAuxRecursor env n || isNoConfusion env n || + isMatcherCore env n || isRecCore env n || + n.components.any fun c => + let s := toString c + s == "eq_def" || s.startsWith "eq_" || s.startsWith "match_" || s.startsWith "proof_" || + (s.splitOn "_proof_").length > 1 || s.startsWith "_" || s == "inj" || s == "injEq" || + s == "sizeOf_spec" + +inductive Outcome + | law (l : Law) + | skip (reason : String) + +def run : MetaM String := do + let env ← getEnv + let some modIdx := env.getModuleIdx? zippyModule | throwError "{zippyModule} not imported" + let mut entries : Array (Nat × String × Outcome) := #[] + for (n, ci) in env.constants.toList do + unless zippyNs.isPrefixOf n && n != zippyNs do continue + unless env.getModuleIdxFor? n == some modIdx do continue + let .thmInfo info := ci | continue + if skipName env n then continue + let line := match ← findDeclarationRanges? n with + | some r => r.selectionRange.pos.line + | none => 0 + let name := relName n + let axioms ← collectAxioms n + let outcome ← + if axioms.contains ``sorryAx then pure (.skip "depends on sorryAx") + else match ← translate info.type with + | .error e => pure (.skip e) + | .ok l => + if l.spaces > 4 then pure (.skip s!"{l.spaces} space variables (more than 4)") + else if l.lhs == l.rhs then pure (.skip "both sides translate to the same term") + else pure (.law { l with name }) + entries := entries.push (line, name, outcome) + entries := entries.qsort fun a b => a.1 < b.1 || (a.1 == b.1 && a.2.1 < b.2.1) + let laws := entries.filterMap fun + | (line, _, .law l) => some (line, l) + | _ => none + let skips := entries.filterMap fun + | (line, name, .skip r) => some (line, name, r) + | _ => none + let mut out := "" + out := out ++ "// @generated by lean/ZippyLaws.lean from lean/PrunedModel/Zippy.lean.\n" + out := out ++ "// Do not edit by hand. Regenerate with:\n" + out := out ++ "// cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs\n" + out := out ++ "//\n" + out := out ++ "// Every entry is a theorem of PrunedModel.Zippy, checked sorry-free when generated.\n" + out := out ++ s!"// {laws.size} exported, {skips.size} not exported (listed at the end).\n" + out := out ++ "\n" + out := out ++ "use super::laws::zippy::*;\n" + out := out ++ "\n" + out := out ++ "pub fn laws() -> Vec {\n" + out := out ++ " vec![\n" + for (line, l) in laws do + out := out ++ s!" // Zippy.lean:{line}\n" + out := out ++ " ZippyLaw {\n" + out := out ++ s!" name: \"{l.name}\",\n" + out := out ++ s!" spaces: {l.spaces},\n" + out := out ++ s!" paths: {l.paths},\n" + out := out ++ s!" bytes: {l.bytes},\n" + out := out ++ s!" pre: vec![{", ".intercalate l.pre.toList}],\n" + out := out ++ s!" lhs: {l.lhs},\n" + out := out ++ s!" rhs: {l.rhs},\n" + out := out ++ " },\n" + out := out ++ " ]\n" + out := out ++ "}\n" + out := out ++ "\n" + out := out ++ "// Not exported:\n" + for (line, name, r) in skips do + out := out ++ s!"// Zippy.lean:{line} {name}: {r}\n" + return out + +end ZippyLaws + +def main : IO Unit := do + initSearchPath (← findSysroot) + let env ← importModules #[{ module := `PrunedModel.Zippy }] {} (trustLevel := 1024) + let (out, _) ← (ZippyLaws.run.run' {} {}).toIO + { fileName := "", fileMap := default, maxHeartbeats := 0 } { env := env } + IO.print out diff --git a/lean/lakefile.toml b/lean/lakefile.toml index 783f6a37..167a22c5 100644 --- a/lean/lakefile.toml +++ b/lean/lakefile.toml @@ -1,5 +1,5 @@ name = "pathmap-model" -defaultTargets = ["PathMapModel", "pathmap-oracle"] +defaultTargets = ["PathMapModel", "pathmap-oracle", "PrunedModel"] [[lean_lib]] name = "PathMapModel" @@ -7,3 +7,9 @@ name = "PathMapModel" [[lean_exe]] name = "pathmap-oracle" root = "Main" + +# The dangling-path-free model, carried here for Zippy's set algebra: a space +# is a `PrunedMap Unit`, and `PrunedModel/Zippy.lean` proves formal.egg's rules +# about it. `ZippyLaws.lean` exports those laws for the algebraic fuzzer. +[[lean_lib]] +name = "PrunedModel" From 91495e77215b5307f9e29824a79a587d8965783b Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 17 Nov 2026 19:45:10 +0000 Subject: [PATCH 14/17] alg_fuzz: regenerate the Zippy laws from this branch's Zippy.lean The same 70 laws as before, with new line numbers. The skipped list now has the issue-#104 equalities of section 10 instead of the old raw-op counterexamples. Point the comments at this branch's Lean, and say why the insert_prefix route still moves the root value by hand on master. --- differential/ALGEBRAIC_FUZZING.md | 6 +- differential/src/algebraic/laws.rs | 4 +- differential/src/algebraic/routes.rs | 7 +- differential/src/algebraic/zippy_laws.rs | 293 +++++++++++------------ 4 files changed, 155 insertions(+), 155 deletions(-) diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index ec70fad9..f2340c95 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -128,15 +128,15 @@ cannot catch a mistake they all share. Laws are the other half: each law is two visible even when every route computes it the same wrong way. The laws are **generated from Lean**, not written here. `lean/ZippyLaws.lean` -(branch `spec/zippy-laws`) loads the elaborated `PrunedModel.Zippy` module, takes +loads the elaborated `PrunedModel.Zippy` module, takes every theorem that is an equation between spaces over the operators above, checks its proof is `sorry`-free, and prints it as Rust: `src/algebraic/zippy_laws.rs`, 70 laws. A theorem may quantify over paths and bytes and carry hypotheses (`a ≠ b`, `p ∉ s`, `head x = empty`); each case carries a few paths and bytes for those, mostly prefixes and first bytes of the operands' own paths, and a law whose hypotheses are false for them is skipped. -The 75 theorems it does not export are listed at the bottom of the generated -file with the reason (membership lemmas, `≠` results, raw-zipper-op theorems, +The 74 theorems it does not export are listed at the bottom of the generated +file with the reason (membership lemmas, raw-zipper-op theorems, function-typed binders). ```sh diff --git a/differential/src/algebraic/laws.rs b/differential/src/algebraic/laws.rs index 8a4733dc..d7ea11bc 100644 --- a/differential/src/algebraic/laws.rs +++ b/differential/src/algebraic/laws.rs @@ -8,8 +8,8 @@ //! //! # Where the laws come from //! -//! Not from this file. They are the theorems of `lean/PrunedModel/Zippy.lean` -//! (branch `spec/zippy-laws`), which proves Adam Vandervorst's `formal.egg` -- +//! Not from this file. They are the theorems of `lean/PrunedModel/Zippy.lean`, +//! which proves Adam Vandervorst's `formal.egg` -- //! the reference semantics of Zippy's space algebra -- over the pruned model. //! `lean/ZippyLaws.lean` reads the *elaborated* theorems, keeps every equation //! between spaces whose operators the expression language has, and prints them diff --git a/differential/src/algebraic/routes.rs b/differential/src/algebraic/routes.rs index c4b7a25f..e0b25403 100644 --- a/differential/src/algebraic/routes.rs +++ b/differential/src/algebraic/routes.rs @@ -467,9 +467,10 @@ fn wrap(k: usize, p: &[u8], s: &PathMap) -> PathMap { } 1 => materialize(PrefixZipper::new(p.to_vec(), s.read_zipper())), _ => { - // `insert_prefix` moves the node and, by its documentation, leaves - // the focus value where it is (Zippy §10, `rawWrap_ne_wrap`). So - // that value is moved by hand, and what this tests is the node move. + // `insert_prefix` moves the node and, on master, leaves the focus + // value where it is (issue #104 moves it too; Zippy.lean §10, + // `insertPrefix_eq_wrap`). So that value is moved by hand, and + // what this tests is the node move. let mut out = s.clone(); { let mut wz = out.write_zipper(); diff --git a/differential/src/algebraic/zippy_laws.rs b/differential/src/algebraic/zippy_laws.rs index 8030680b..759536d8 100644 --- a/differential/src/algebraic/zippy_laws.rs +++ b/differential/src/algebraic/zippy_laws.rs @@ -1,15 +1,15 @@ -// @generated by lean/ZippyLaws.lean from lean/PrunedModel/Zippy.lean (branch spec/zippy-laws). +// @generated by lean/ZippyLaws.lean from lean/PrunedModel/Zippy.lean. // Do not edit by hand. Regenerate with: // cd lean && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs // // Every entry is a theorem of PrunedModel.Zippy, checked sorry-free when generated. -// 70 exported, 75 not exported (listed at the end). +// 70 exported, 74 not exported (listed at the end). use super::laws::zippy::*; pub fn laws() -> Vec { vec![ - // Zippy.lean:496 + // Zippy.lean:488 ZippyLaw { name: "union_idem", spaces: 1, @@ -19,7 +19,7 @@ pub fn laws() -> Vec { lhs: union(s(0), s(0)), rhs: s(0), }, - // Zippy.lean:498 + // Zippy.lean:490 ZippyLaw { name: "inter_idem", spaces: 1, @@ -29,7 +29,7 @@ pub fn laws() -> Vec { lhs: inter(s(0), s(0)), rhs: s(0), }, - // Zippy.lean:500 + // Zippy.lean:492 ZippyLaw { name: "subtr_self", spaces: 1, @@ -39,7 +39,7 @@ pub fn laws() -> Vec { lhs: subtr(s(0), s(0)), rhs: empty(), }, - // Zippy.lean:503 + // Zippy.lean:495 ZippyLaw { name: "union_comm", spaces: 2, @@ -49,7 +49,7 @@ pub fn laws() -> Vec { lhs: union(s(0), s(1)), rhs: union(s(1), s(0)), }, - // Zippy.lean:505 + // Zippy.lean:497 ZippyLaw { name: "inter_comm", spaces: 2, @@ -59,7 +59,7 @@ pub fn laws() -> Vec { lhs: inter(s(0), s(1)), rhs: inter(s(1), s(0)), }, - // Zippy.lean:507 + // Zippy.lean:499 ZippyLaw { name: "union_empty", spaces: 1, @@ -69,7 +69,7 @@ pub fn laws() -> Vec { lhs: union(s(0), empty()), rhs: s(0), }, - // Zippy.lean:510 + // Zippy.lean:502 ZippyLaw { name: "empty_union", spaces: 1, @@ -79,7 +79,7 @@ pub fn laws() -> Vec { lhs: union(empty(), s(0)), rhs: s(0), }, - // Zippy.lean:512 + // Zippy.lean:504 ZippyLaw { name: "inter_empty", spaces: 1, @@ -89,7 +89,7 @@ pub fn laws() -> Vec { lhs: inter(s(0), empty()), rhs: empty(), }, - // Zippy.lean:515 + // Zippy.lean:507 ZippyLaw { name: "empty_inter", spaces: 1, @@ -99,7 +99,7 @@ pub fn laws() -> Vec { lhs: inter(empty(), s(0)), rhs: empty(), }, - // Zippy.lean:517 + // Zippy.lean:509 ZippyLaw { name: "union_inter_distrib", spaces: 3, @@ -109,7 +109,7 @@ pub fn laws() -> Vec { lhs: inter(union(s(0), s(1)), s(2)), rhs: union(inter(s(0), s(2)), inter(s(1), s(2))), }, - // Zippy.lean:521 + // Zippy.lean:513 ZippyLaw { name: "inter_union_distrib", spaces: 3, @@ -119,7 +119,7 @@ pub fn laws() -> Vec { lhs: inter(s(0), union(s(1), s(2))), rhs: union(inter(s(0), s(1)), inter(s(0), s(2))), }, - // Zippy.lean:525 + // Zippy.lean:517 ZippyLaw { name: "empty_subtr", spaces: 1, @@ -129,7 +129,7 @@ pub fn laws() -> Vec { lhs: subtr(empty(), s(0)), rhs: empty(), }, - // Zippy.lean:528 + // Zippy.lean:520 ZippyLaw { name: "subtr_empty", spaces: 1, @@ -139,7 +139,7 @@ pub fn laws() -> Vec { lhs: subtr(s(0), empty()), rhs: s(0), }, - // Zippy.lean:531 + // Zippy.lean:523 ZippyLaw { name: "union_subtr_distrib", spaces: 3, @@ -149,7 +149,7 @@ pub fn laws() -> Vec { lhs: subtr(union(s(0), s(1)), s(2)), rhs: union(subtr(s(0), s(2)), subtr(s(1), s(2))), }, - // Zippy.lean:535 + // Zippy.lean:527 ZippyLaw { name: "subtr_union", spaces: 3, @@ -159,7 +159,7 @@ pub fn laws() -> Vec { lhs: subtr(s(0), union(s(1), s(2))), rhs: subtr(subtr(s(0), s(1)), s(2)), }, - // Zippy.lean:539 + // Zippy.lean:531 ZippyLaw { name: "union_assoc", spaces: 3, @@ -169,7 +169,7 @@ pub fn laws() -> Vec { lhs: union(union(s(0), s(1)), s(2)), rhs: union(s(0), union(s(1), s(2))), }, - // Zippy.lean:542 + // Zippy.lean:534 ZippyLaw { name: "inter_assoc", spaces: 3, @@ -179,7 +179,7 @@ pub fn laws() -> Vec { lhs: inter(inter(s(0), s(1)), s(2)), rhs: inter(s(0), inter(s(1), s(2))), }, - // Zippy.lean:548 + // Zippy.lean:540 ZippyLaw { name: "singleton_subtr_singleton", spaces: 0, @@ -189,7 +189,7 @@ pub fn laws() -> Vec { lhs: subtr(singleton(pv(0)), singleton(pv(1))), rhs: singleton(pv(0)), }, - // Zippy.lean:553 + // Zippy.lean:545 ZippyLaw { name: "singleton_inter_singleton", spaces: 0, @@ -199,7 +199,7 @@ pub fn laws() -> Vec { lhs: inter(singleton(pv(0)), singleton(pv(1))), rhs: empty(), }, - // Zippy.lean:575 + // Zippy.lean:567 ZippyLaw { name: "wrap_empty", spaces: 0, @@ -209,7 +209,7 @@ pub fn laws() -> Vec { lhs: wrap(pv(0), empty()), rhs: empty(), }, - // Zippy.lean:579 + // Zippy.lean:571 ZippyLaw { name: "wrap_eps", spaces: 1, @@ -219,7 +219,7 @@ pub fn laws() -> Vec { lhs: wrap(nil(), s(0)), rhs: s(0), }, - // Zippy.lean:582 + // Zippy.lean:574 ZippyLaw { name: "wrap_singleton", spaces: 0, @@ -229,7 +229,7 @@ pub fn laws() -> Vec { lhs: wrap(pv(0), singleton(pv(1))), rhs: singleton(app(pv(0), pv(1))), }, - // Zippy.lean:586 + // Zippy.lean:578 ZippyLaw { name: "wrap_union", spaces: 2, @@ -239,7 +239,7 @@ pub fn laws() -> Vec { lhs: wrap(pv(0), union(s(0), s(1))), rhs: union(wrap(pv(0), s(0)), wrap(pv(0), s(1))), }, - // Zippy.lean:598 + // Zippy.lean:590 ZippyLaw { name: "unwrap_empty", spaces: 0, @@ -249,7 +249,7 @@ pub fn laws() -> Vec { lhs: unwrap(empty(), pv(0)), rhs: empty(), }, - // Zippy.lean:601 + // Zippy.lean:593 ZippyLaw { name: "unwrap_eps", spaces: 1, @@ -259,7 +259,7 @@ pub fn laws() -> Vec { lhs: unwrap(s(0), nil()), rhs: s(0), }, - // Zippy.lean:603 + // Zippy.lean:595 ZippyLaw { name: "unwrap_wrap", spaces: 1, @@ -269,7 +269,7 @@ pub fn laws() -> Vec { lhs: unwrap(wrap(pv(0), s(0)), pv(0)), rhs: s(0), }, - // Zippy.lean:607 + // Zippy.lean:599 ZippyLaw { name: "unwrap_wrap_append", spaces: 1, @@ -279,7 +279,7 @@ pub fn laws() -> Vec { lhs: unwrap(wrap(app(pv(0), pv(1)), s(0)), pv(0)), rhs: wrap(pv(1), s(0)), }, - // Zippy.lean:612 + // Zippy.lean:604 ZippyLaw { name: "unwrap_wrap_of_append", spaces: 1, @@ -289,7 +289,7 @@ pub fn laws() -> Vec { lhs: unwrap(wrap(pv(0), s(0)), app(pv(0), pv(1))), rhs: unwrap(s(0), pv(1)), }, - // Zippy.lean:617 + // Zippy.lean:609 ZippyLaw { name: "unwrap_union", spaces: 2, @@ -299,7 +299,7 @@ pub fn laws() -> Vec { lhs: unwrap(union(s(0), s(1)), pv(0)), rhs: union(unwrap(s(0), pv(0)), unwrap(s(1), pv(0))), }, - // Zippy.lean:620 + // Zippy.lean:612 ZippyLaw { name: "unwrap_unwrap", spaces: 1, @@ -309,7 +309,7 @@ pub fn laws() -> Vec { lhs: unwrap(unwrap(s(0), pv(0)), pv(1)), rhs: unwrap(s(0), app(pv(0), pv(1))), }, - // Zippy.lean:623 + // Zippy.lean:615 ZippyLaw { name: "unwrap_wrap_ne", spaces: 1, @@ -319,7 +319,7 @@ pub fn laws() -> Vec { lhs: unwrap(wrap(cons(bv(0), nil()), s(0)), cons(bv(1), nil())), rhs: empty(), }, - // Zippy.lean:646 + // Zippy.lean:638 ZippyLaw { name: "dropPrefix_eps", spaces: 0, @@ -329,7 +329,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(pv(0)), nil()), rhs: singleton(pv(0)), }, - // Zippy.lean:649 + // Zippy.lean:641 ZippyLaw { name: "dropPrefix_self", spaces: 0, @@ -339,7 +339,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(pv(0)), pv(0)), rhs: singleton(nil()), }, - // Zippy.lean:652 + // Zippy.lean:644 ZippyLaw { name: "dropPrefix_append", spaces: 0, @@ -349,7 +349,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(app(pv(0), pv(1))), pv(0)), rhs: singleton(pv(1)), }, - // Zippy.lean:655 + // Zippy.lean:647 ZippyLaw { name: "dropPrefix_descend", spaces: 0, @@ -359,7 +359,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(app(pv(0), pv(2))), app(pv(0), pv(1))), rhs: unwrap(singleton(pv(2)), pv(1)), }, - // Zippy.lean:662 + // Zippy.lean:654 ZippyLaw { name: "dropPrefix_miss_eps", spaces: 0, @@ -369,7 +369,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(nil()), cons(bv(0), pv(0))), rhs: empty(), }, - // Zippy.lean:665 + // Zippy.lean:657 ZippyLaw { name: "dropPrefix_miss_item", spaces: 0, @@ -379,7 +379,7 @@ pub fn laws() -> Vec { lhs: unwrap(singleton(cons(bv(1), pv(1))), cons(bv(0), pv(0))), rhs: empty(), }, - // Zippy.lean:678 + // Zippy.lean:670 ZippyLaw { name: "empty_composition", spaces: 1, @@ -389,7 +389,7 @@ pub fn laws() -> Vec { lhs: composition(empty(), s(0)), rhs: empty(), }, - // Zippy.lean:682 + // Zippy.lean:674 ZippyLaw { name: "composition_empty", spaces: 1, @@ -399,7 +399,7 @@ pub fn laws() -> Vec { lhs: composition(s(0), empty()), rhs: empty(), }, - // Zippy.lean:686 + // Zippy.lean:678 ZippyLaw { name: "union_composition", spaces: 3, @@ -409,7 +409,7 @@ pub fn laws() -> Vec { lhs: composition(union(s(0), s(1)), s(2)), rhs: union(composition(s(0), s(2)), composition(s(1), s(2))), }, - // Zippy.lean:697 + // Zippy.lean:689 ZippyLaw { name: "composition_union", spaces: 3, @@ -419,7 +419,7 @@ pub fn laws() -> Vec { lhs: composition(s(0), union(s(1), s(2))), rhs: union(composition(s(0), s(1)), composition(s(0), s(2))), }, - // Zippy.lean:708 + // Zippy.lean:700 ZippyLaw { name: "singleton_composition", spaces: 1, @@ -429,7 +429,7 @@ pub fn laws() -> Vec { lhs: composition(singleton(pv(0)), s(0)), rhs: wrap(pv(0), s(0)), }, - // Zippy.lean:714 + // Zippy.lean:706 ZippyLaw { name: "singleton_union_composition", spaces: 2, @@ -439,7 +439,7 @@ pub fn laws() -> Vec { lhs: composition(union(singleton(pv(0)), s(0)), s(1)), rhs: union(wrap(pv(0), s(1)), composition(s(0), s(1))), }, - // Zippy.lean:729 + // Zippy.lean:721 ZippyLaw { name: "tailsUnion_empty", spaces: 0, @@ -449,7 +449,7 @@ pub fn laws() -> Vec { lhs: tails_union(empty()), rhs: empty(), }, - // Zippy.lean:733 + // Zippy.lean:725 ZippyLaw { name: "tailsUnion_eps", spaces: 0, @@ -459,7 +459,7 @@ pub fn laws() -> Vec { lhs: tails_union(singleton(nil())), rhs: empty(), }, - // Zippy.lean:738 + // Zippy.lean:730 ZippyLaw { name: "tailsUnion_cons", spaces: 0, @@ -469,7 +469,7 @@ pub fn laws() -> Vec { lhs: tails_union(singleton(cons(bv(0), pv(0)))), rhs: singleton(pv(0)), }, - // Zippy.lean:743 + // Zippy.lean:735 ZippyLaw { name: "tailsUnion_item", spaces: 0, @@ -479,7 +479,7 @@ pub fn laws() -> Vec { lhs: tails_union(singleton(cons(bv(0), nil()))), rhs: singleton(nil()), }, - // Zippy.lean:745 + // Zippy.lean:737 ZippyLaw { name: "tailsUnion_union", spaces: 2, @@ -489,7 +489,7 @@ pub fn laws() -> Vec { lhs: tails_union(union(s(0), s(1))), rhs: union(tails_union(s(0)), tails_union(s(1))), }, - // Zippy.lean:756 + // Zippy.lean:748 ZippyLaw { name: "tailsUnion_wrap", spaces: 1, @@ -499,7 +499,7 @@ pub fn laws() -> Vec { lhs: tails_union(wrap(cons(bv(0), nil()), s(0))), rhs: s(0), }, - // Zippy.lean:760 + // Zippy.lean:752 ZippyLaw { name: "tailsUnion_wrap_union", spaces: 2, @@ -509,7 +509,7 @@ pub fn laws() -> Vec { lhs: tails_union(union(wrap(cons(bv(0), nil()), s(0)), s(1))), rhs: union(s(0), tails_union(s(1))), }, - // Zippy.lean:777 + // Zippy.lean:769 ZippyLaw { name: "tailsInter_of_head_empty", spaces: 1, @@ -519,7 +519,7 @@ pub fn laws() -> Vec { lhs: tails_inter(s(0)), rhs: empty(), }, - // Zippy.lean:804 + // Zippy.lean:796 ZippyLaw { name: "tailsInter_of_head_singleton", spaces: 1, @@ -529,7 +529,7 @@ pub fn laws() -> Vec { lhs: tails_inter(s(0)), rhs: unwrap(s(0), cons(bv(0), nil())), }, - // Zippy.lean:811 + // Zippy.lean:803 ZippyLaw { name: "restriction_empty_left", spaces: 1, @@ -539,7 +539,7 @@ pub fn laws() -> Vec { lhs: restriction(empty(), s(0)), rhs: empty(), }, - // Zippy.lean:814 + // Zippy.lean:806 ZippyLaw { name: "restriction_empty_right", spaces: 1, @@ -549,7 +549,7 @@ pub fn laws() -> Vec { lhs: restriction(s(0), empty()), rhs: empty(), }, - // Zippy.lean:818 + // Zippy.lean:810 ZippyLaw { name: "restriction_eps", spaces: 1, @@ -559,7 +559,7 @@ pub fn laws() -> Vec { lhs: restriction(s(0), singleton(nil())), rhs: s(0), }, - // Zippy.lean:822 + // Zippy.lean:814 ZippyLaw { name: "restriction_union", spaces: 3, @@ -569,7 +569,7 @@ pub fn laws() -> Vec { lhs: restriction(s(0), union(s(1), s(2))), rhs: union(restriction(s(0), s(1)), restriction(s(0), s(2))), }, - // Zippy.lean:833 + // Zippy.lean:825 ZippyLaw { name: "restriction_singleton", spaces: 1, @@ -579,7 +579,7 @@ pub fn laws() -> Vec { lhs: restriction(s(0), singleton(pv(0))), rhs: wrap(pv(0), unwrap(s(0), pv(0))), }, - // Zippy.lean:840 + // Zippy.lean:832 ZippyLaw { name: "restriction_self", spaces: 1, @@ -589,7 +589,7 @@ pub fn laws() -> Vec { lhs: restriction(s(0), s(0)), rhs: s(0), }, - // Zippy.lean:844 + // Zippy.lean:836 ZippyLaw { name: "head_empty", spaces: 0, @@ -599,7 +599,7 @@ pub fn laws() -> Vec { lhs: head(empty()), rhs: empty(), }, - // Zippy.lean:848 + // Zippy.lean:840 ZippyLaw { name: "head_eps", spaces: 0, @@ -609,7 +609,7 @@ pub fn laws() -> Vec { lhs: head(singleton(nil())), rhs: empty(), }, - // Zippy.lean:853 + // Zippy.lean:845 ZippyLaw { name: "head_union", spaces: 2, @@ -619,7 +619,7 @@ pub fn laws() -> Vec { lhs: head(union(s(0), s(1))), rhs: union(head(s(0)), head(s(1))), }, - // Zippy.lean:863 + // Zippy.lean:855 ZippyLaw { name: "head_cons", spaces: 0, @@ -629,7 +629,7 @@ pub fn laws() -> Vec { lhs: head(singleton(cons(bv(0), pv(0)))), rhs: singleton(cons(bv(0), nil())), }, - // Zippy.lean:867 + // Zippy.lean:859 ZippyLaw { name: "head_item", spaces: 0, @@ -639,7 +639,7 @@ pub fn laws() -> Vec { lhs: head(singleton(cons(bv(0), nil()))), rhs: singleton(cons(bv(0), nil())), }, - // Zippy.lean:870 + // Zippy.lean:862 ZippyLaw { name: "raffination_def", spaces: 2, @@ -649,7 +649,7 @@ pub fn laws() -> Vec { lhs: raffination(s(0), s(1)), rhs: subtr(s(0), restriction(s(0), s(1))), }, - // Zippy.lean:872 + // Zippy.lean:864 ZippyLaw { name: "raffination_self", spaces: 1, @@ -659,7 +659,7 @@ pub fn laws() -> Vec { lhs: raffination(s(0), s(0)), rhs: empty(), }, - // Zippy.lean:945 + // Zippy.lean:937 ZippyLaw { name: "iterC_empty", spaces: 1, @@ -669,7 +669,7 @@ pub fn laws() -> Vec { lhs: iter_c(empty(), s(0)), rhs: empty(), }, - // Zippy.lean:948 + // Zippy.lean:940 ZippyLaw { name: "iterC_eps", spaces: 1, @@ -679,7 +679,7 @@ pub fn laws() -> Vec { lhs: iter_c(singleton(nil()), s(0)), rhs: empty(), }, - // Zippy.lean:951 + // Zippy.lean:943 ZippyLaw { name: "iterC_cons", spaces: 1, @@ -689,7 +689,7 @@ pub fn laws() -> Vec { lhs: iter_c(singleton(cons(bv(0), pv(0))), s(0)), rhs: s(0), }, - // Zippy.lean:954 + // Zippy.lean:946 ZippyLaw { name: "iterC_item", spaces: 1, @@ -699,7 +699,7 @@ pub fn laws() -> Vec { lhs: iter_c(singleton(cons(bv(0), nil())), s(0)), rhs: s(0), }, - // Zippy.lean:956 + // Zippy.lean:948 ZippyLaw { name: "iterC_union", spaces: 3, @@ -713,78 +713,77 @@ pub fn laws() -> Vec { } // Not exported: -// Zippy.lean:74 mem_def: conclusion is not an equation of spaces (Iff) -// Zippy.lean:85 ext: hypothesis is a ∀ -// Zippy.lean:94 valAt_eq: conclusion is not an equation of spaces (equation of Option Unit) -// Zippy.lean:97 not_mem_iff: conclusion is not an equation of spaces (Iff) -// Zippy.lean:180 wz_trie: mentions PrunedModel.PZip.trie -// Zippy.lean:181 wz_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) -// Zippy.lean:182 wz_descendTo_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) -// Zippy.lean:183 wz_descendTo_trie: mentions PrunedModel.PZip.trie -// Zippy.lean:185 subtrie_nil: mentions PrunedModel.PrunedMap.subtrie -// Zippy.lean:190 wz_makeMap: mentions PrunedModel.PZip.makeMap -// Zippy.lean:192 not_mem_empty: conclusion is not an equation of spaces (¬) -// Zippy.lean:194 mem_singleton: conclusion is not an equation of spaces (Iff) -// Zippy.lean:207 union_eq_join: mentions PrunedModel.PrunedMap.join -// Zippy.lean:211 inter_eq_meet: mentions PrunedModel.PrunedMap.meet -// Zippy.lean:215 subtr_eq_sub: mentions PrunedModel.PrunedMap.sub -// Zippy.lean:219 mem_union: conclusion is not an equation of spaces (Iff) -// Zippy.lean:222 mem_inter: conclusion is not an equation of spaces (Iff) -// Zippy.lean:225 mem_subtr: conclusion is not an equation of spaces (Iff) -// Zippy.lean:229 wrap_eq: mentions PrunedModel.PrunedMap.replaceAt -// Zippy.lean:232 mem_wrap: conclusion is not an equation of spaces (Iff) -// Zippy.lean:246 mem_unwrap: conclusion is not an equation of spaces (Iff) -// Zippy.lean:249 mem_keys: conclusion is not an equation of spaces (Iff) -// Zippy.lean:254 mem_ofList: conclusion is not an equation of spaces (Iff) -// Zippy.lean:268 mem_childMask: conclusion is not an equation of spaces (Iff) -// Zippy.lean:284 mem_foldl_union: binder α : Type -// Zippy.lean:302 mem_foldl_inter: binder α : Type -// Zippy.lean:314 mem_restriction: conclusion is not an equation of spaces (Iff) -// Zippy.lean:345 mem_composition_step: conclusion is not an equation of spaces (Iff) -// Zippy.lean:366 mem_composition: conclusion is not an equation of spaces (Iff) -// Zippy.lean:393 mem_head: conclusion is not an equation of spaces (Iff) -// Zippy.lean:400 mem_child: conclusion is not an equation of spaces (Iff) -// Zippy.lean:404 mem_tailsUnion: conclusion is not an equation of spaces (Iff) -// Zippy.lean:411 mem_tailsInter: conclusion is not an equation of spaces (Iff) -// Zippy.lean:434 mem_iterH: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:446 mem_iter: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:454 mem_iterC: conclusion is not an equation of spaces (Iff) -// Zippy.lean:460 mem_raffination: conclusion is not an equation of spaces (Iff) -// Zippy.lean:474 elemP_empty: conclusion is not an equation of spaces (¬) -// Zippy.lean:476 elemP_singleton: conclusion is not an equation of spaces (Membership.mem) -// Zippy.lean:478 elemP_singleton_ne: conclusion is not an equation of spaces (¬) -// Zippy.lean:480 elemP_union: conclusion is not an equation of spaces (Iff) -// Zippy.lean:482 elemP_inter: conclusion is not an equation of spaces (Iff) -// Zippy.lean:484 elemP_subtr: conclusion is not an equation of spaces (Iff) -// Zippy.lean:561 concat_eps: conclusion is not an equation of spaces (equation of PathMapModel.Path) -// Zippy.lean:563 eps_concat: conclusion is not an equation of spaces (equation of PathMapModel.Path) -// Zippy.lean:565 concat_assoc: conclusion is not an equation of spaces (equation of PathMapModel.Path) -// Zippy.lean:631 unwrap_singleton: mentions PrunedModel.Zippy.unwrap_singleton.match_1 -// Zippy.lean:659 dropPrefix_miss: hypothesis is a ∀ -// Zippy.lean:768 enumHeads_iff: conclusion is not an equation of spaces (Iff) -// Zippy.lean:786 tailsInter_eq_foldl: hypothesis mentions PrunedModel.Zippy.EnumHeads -// Zippy.lean:885 iter_def: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:888 iterH_empty: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:893 iterH_union: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:904 iterH_item: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:912 iter_not_union_source: conclusion is not an equation of spaces (¬) -// Zippy.lean:982 union_eq_right_iff: conclusion is not an equation of spaces (Iff) -// Zippy.lean:991 IsLeastPostFix.init: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:993 IsLeastPostFix.post: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:995 IsLeastPostFix.park: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:998 IsLeastPostFix.unique: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:1005 fix_self: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) -// Zippy.lean:1018 init_le_kleene: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:1024 kleene_isLeastPostFix: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space -// Zippy.lean:1053 joinInto_root: mentions PrunedModel.PZip.trie -// Zippy.lean:1062 joinInto_eq_union: mentions PrunedModel.PZip.trie -// Zippy.lean:1070 joinInto_ne_union: conclusion is not an equation of spaces (Ne) -// Zippy.lean:1082 mem_rawRestrict: conclusion is not an equation of spaces (Iff) -// Zippy.lean:1103 rawRestrict_eq_restriction: mentions PrunedModel.Zippy.rawRestrict -// Zippy.lean:1115 rawRestrict_empty_ne: conclusion is not an equation of spaces (Ne) -// Zippy.lean:1121 rawRestrict_eps_ne: conclusion is not an equation of spaces (Ne) -// Zippy.lean:1132 mem_rawWrap: conclusion is not an equation of spaces (Iff) -// Zippy.lean:1168 rawWrap_eq_wrap: mentions PrunedModel.Zippy.rawWrap -// Zippy.lean:1178 rawWrap_ne_wrap: conclusion is not an equation of spaces (Ne) -// Zippy.lean:1290 fix_ab: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) -// Zippy.lean:1299 fix_not_too_small: conclusion is not an equation of spaces (¬) +// Zippy.lean:80 mem_def: conclusion is not an equation of spaces (Iff) +// Zippy.lean:91 ext: hypothesis is a ∀ +// Zippy.lean:100 valAt_eq: conclusion is not an equation of spaces (equation of Option Unit) +// Zippy.lean:103 not_mem_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:182 wz_trie: mentions PrunedModel.PZip.trie +// Zippy.lean:183 wz_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:184 wz_descendTo_focus: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:185 wz_descendTo_trie: mentions PrunedModel.PZip.trie +// Zippy.lean:187 subtrie_nil: mentions PrunedModel.PrunedMap.subtrie +// Zippy.lean:192 wz_makeMap: mentions PrunedModel.PZip.makeMap +// Zippy.lean:194 not_mem_empty: conclusion is not an equation of spaces (¬) +// Zippy.lean:196 mem_singleton: conclusion is not an equation of spaces (Iff) +// Zippy.lean:209 union_eq_join: mentions PrunedModel.PrunedMap.join +// Zippy.lean:213 inter_eq_meet: mentions PrunedModel.PrunedMap.meet +// Zippy.lean:217 subtr_eq_sub: mentions PrunedModel.PrunedMap.sub +// Zippy.lean:221 mem_union: conclusion is not an equation of spaces (Iff) +// Zippy.lean:224 mem_inter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:227 mem_subtr: conclusion is not an equation of spaces (Iff) +// Zippy.lean:231 wrap_eq: mentions PrunedModel.PrunedMap.replaceAt +// Zippy.lean:234 mem_wrap: conclusion is not an equation of spaces (Iff) +// Zippy.lean:248 mem_unwrap: conclusion is not an equation of spaces (Iff) +// Zippy.lean:251 mem_keys: conclusion is not an equation of spaces (Iff) +// Zippy.lean:256 mem_ofList: conclusion is not an equation of spaces (Iff) +// Zippy.lean:270 mem_childMask: conclusion is not an equation of spaces (Iff) +// Zippy.lean:286 mem_foldl_union: binder α : Type +// Zippy.lean:304 mem_foldl_inter: binder α : Type +// Zippy.lean:316 mem_restriction: conclusion is not an equation of spaces (Iff) +// Zippy.lean:337 mem_composition_step: conclusion is not an equation of spaces (Iff) +// Zippy.lean:358 mem_composition: conclusion is not an equation of spaces (Iff) +// Zippy.lean:385 mem_head: conclusion is not an equation of spaces (Iff) +// Zippy.lean:392 mem_child: conclusion is not an equation of spaces (Iff) +// Zippy.lean:396 mem_tailsUnion: conclusion is not an equation of spaces (Iff) +// Zippy.lean:403 mem_tailsInter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:426 mem_iterH: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:438 mem_iter: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:446 mem_iterC: conclusion is not an equation of spaces (Iff) +// Zippy.lean:452 mem_raffination: conclusion is not an equation of spaces (Iff) +// Zippy.lean:466 elemP_empty: conclusion is not an equation of spaces (¬) +// Zippy.lean:468 elemP_singleton: conclusion is not an equation of spaces (Membership.mem) +// Zippy.lean:470 elemP_singleton_ne: conclusion is not an equation of spaces (¬) +// Zippy.lean:472 elemP_union: conclusion is not an equation of spaces (Iff) +// Zippy.lean:474 elemP_inter: conclusion is not an equation of spaces (Iff) +// Zippy.lean:476 elemP_subtr: conclusion is not an equation of spaces (Iff) +// Zippy.lean:553 concat_eps: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:555 eps_concat: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:557 concat_assoc: conclusion is not an equation of spaces (equation of PathMapModel.Path) +// Zippy.lean:623 unwrap_singleton: mentions PrunedModel.Zippy.unwrap_singleton.match_1 +// Zippy.lean:651 dropPrefix_miss: hypothesis is a ∀ +// Zippy.lean:760 enumHeads_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:778 tailsInter_eq_foldl: hypothesis mentions PrunedModel.Zippy.EnumHeads +// Zippy.lean:877 iter_def: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:880 iterH_empty: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:885 iterH_union: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:896 iterH_item: binder body : UInt8 → PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:904 iter_not_union_source: conclusion is not an equation of spaces (¬) +// Zippy.lean:974 union_eq_right_iff: conclusion is not an equation of spaces (Iff) +// Zippy.lean:983 IsLeastPostFix.init: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:985 IsLeastPostFix.post: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:987 IsLeastPostFix.park: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:990 IsLeastPostFix.unique: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:997 fix_self: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) +// Zippy.lean:1010 init_le_kleene: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:1016 kleene_isLeastPostFix: binder F : PrunedModel.Zippy.Space → PrunedModel.Zippy.Space +// Zippy.lean:1046 joinInto_eq_union: mentions PrunedModel.PZip.trie +// Zippy.lean:1052 restrict_eq_restriction: mentions PrunedModel.PZip.trie +// Zippy.lean:1056 insertPrefix_eq_wrap: mentions PrunedModel.PZip.trie +// Zippy.lean:1072 mem_kPaths_one: conclusion is not an equation of spaces (Iff) +// Zippy.lean:1094 joinKPathInto_one_eq_tailsUnion: mentions PrunedModel.PZip.trie +// Zippy.lean:1110 mem_meet: conclusion is not an equation of spaces (Iff) +// Zippy.lean:1113 foldl_meetStep_eq_none: binder L : List PathMapModel.Path +// Zippy.lean:1120 mem_foldl_meetStep: binder L : List PathMapModel.Path +// Zippy.lean:1141 meetKPathInto_one_eq_tailsInter: mentions PrunedModel.PZip.trie +// Zippy.lean:1259 fix_ab: conclusion is not an equation of spaces (PrunedModel.Zippy.IsLeastPostFix) +// Zippy.lean:1268 fix_not_too_small: conclusion is not an equation of spaces (¬) From fef8158f90774c75371fec99b3cf6869730390c9 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 17 Nov 2026 20:23:04 +0000 Subject: [PATCH 15/17] differential: fuzz the crate against the dangling-path-free model Port the pruned fuzzer from spec/zippy-laws-fvc: PrunedModel/Fuzz.lean and PrunedMain.lean (the pruned-oracle binary), differential/src/pruned.rs and bin/pruned_trace.rs, lean/pruned_differential.py, PRUNED_FINDINGS.md and the 10-input pruned corpus. Adapted to master: fork_read_zipper returns Option, so the dump goes through harness::dump_fork, and harness::Dec gains legacy() for this header-less stream. The skip:k0, skip:empty-path and childless meet_k_path_into skips that f3e442e removed are back. Master still collapses the subtrie, escapes the focus, or loops forever there, and without them inputs time out. The model specifies issue #104, which master does not implement. So remove_prefix (count vs bool) and the focus value of insert_prefix, join_into, meet_2, join_k_path_into, restrict and meet_k_path_into diverge until focus_value_consistency lands. They are reported as new divergences, not filed under KNOWN. 20000 random inputs on de125bb: 13721 diverge, all in those seven operations but one in subtract_into. --- differential/src/bin/pruned_trace.rs | 36 ++ differential/src/harness.rs | 5 + differential/src/lib.rs | 5 + differential/src/pruned.rs | 607 ++++++++++++++++++ lean/PRUNED_FINDINGS.md | 211 ++++++ lean/PrunedMain.lean | 91 +++ lean/PrunedModel.lean | 1 + lean/PrunedModel/Fuzz.lean | 551 ++++++++++++++++ lean/PrunedModel/Map.lean | 7 +- lean/PrunedModel/Write.lean | 10 +- lean/README.md | 22 +- lean/lakefile.toml | 15 +- ...graft-empty-src-creates-dangling-focus.bin | Bin 0 -> 9 bytes ...masked_branches-creates-dangling-child.bin | Bin 0 -> 10 bytes ...masked_branches-creates-dangling-focus.bin | Bin 0 -> 12 bytes ...rc_at-empty-src-creates-dangling-focus.bin | Bin 0 -> 10 bytes .../join_into-value-bias-by-node-layout.bin | Bin 0 -> 47 bytes ...map_into-status-element-when-unchanged.bin | Bin 0 -> 9 bytes ..._2-empty-result-creates-dangling-focus.bin | Bin 0 -> 12 bytes .../remove_prefix-creates-dangling-chain.bin | Bin 0 -> 14 bytes ...ct-empty-result-creates-dangling-focus.bin | Bin 0 -> 12 bytes .../restricting-creates-dangling-focus.bin | Bin 0 -> 22 bytes lean/pruned_differential.py | 186 ++++++ 23 files changed, 1733 insertions(+), 14 deletions(-) create mode 100644 differential/src/bin/pruned_trace.rs create mode 100644 differential/src/pruned.rs create mode 100644 lean/PRUNED_FINDINGS.md create mode 100644 lean/PrunedMain.lean create mode 100644 lean/PrunedModel/Fuzz.lean create mode 100644 lean/pruned-corpus/graft-empty-src-creates-dangling-focus.bin create mode 100644 lean/pruned-corpus/graft_masked_branches-creates-dangling-child.bin create mode 100644 lean/pruned-corpus/graft_masked_branches-creates-dangling-focus.bin create mode 100644 lean/pruned-corpus/graft_src_at-empty-src-creates-dangling-focus.bin create mode 100644 lean/pruned-corpus/join_into-value-bias-by-node-layout.bin create mode 100644 lean/pruned-corpus/join_map_into-status-element-when-unchanged.bin create mode 100644 lean/pruned-corpus/meet_2-empty-result-creates-dangling-focus.bin create mode 100644 lean/pruned-corpus/remove_prefix-creates-dangling-chain.bin create mode 100644 lean/pruned-corpus/restrict-empty-result-creates-dangling-focus.bin create mode 100644 lean/pruned-corpus/restricting-creates-dangling-focus.bin create mode 100755 lean/pruned_differential.py diff --git a/differential/src/bin/pruned_trace.rs b/differential/src/bin/pruned_trace.rs new file mode 100644 index 00000000..9f066582 --- /dev/null +++ b/differential/src/bin/pruned_trace.rs @@ -0,0 +1,36 @@ +//! Prints the dangling-path-free differential trace for a fuzzer input, from +//! the real crate. +//! +//! pruned_trace # or read the bytes from stdin +//! +//! `lean/.lake/build/bin/pruned-oracle` prints the same trace from +//! `PrunedModel`; `lean/pruned_differential.py` runs both and diffs them. +//! +//! `--check` needs no oracle: it asserts the zipper invariants after every +//! operation and, at the end of the run, that the write target contains no +//! dangling path -- which is the whole claim this harness's operation subset +//! makes. See `differential::pruned`. + +use differential::pruned::run; +use differential::serve; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let check = args.iter().any(|a| a == "--check"); + // Resident mode: one process, many inputs over stdin. See `serve`. + if args.iter().any(|a| a == "--server") { + serve(check, run); + return; + } + let file = args.iter().find(|a| !a.starts_with("--")).cloned(); + let bytes: Vec = match file { + Some(p) => std::fs::read(p).expect("cannot read input"), + None => { + use std::io::Read; + let mut v = Vec::new(); + std::io::stdin().read_to_end(&mut v).unwrap(); + v + } + }; + print!("{}", run(&bytes, check)); +} diff --git a/differential/src/harness.rs b/differential/src/harness.rs index c2863849..e581ee85 100644 --- a/differential/src/harness.rs +++ b/differential/src/harness.rs @@ -62,6 +62,11 @@ impl<'a> Dec<'a> { }; Some(Self { bytes, pos, op_count }) } + /// A decoder with no header handling, for streams whose caller picks the + /// operation itself (the pruned fuzzer). + pub fn legacy(bytes: &'a [u8]) -> Self { + Self { bytes, pos: 0, op_count: LEGACY_NOPS } + } pub fn op(&mut self) -> Option { self.modn(self.op_count) } diff --git a/differential/src/lib.rs b/differential/src/lib.rs index a3c5e052..fc5360ee 100644 --- a/differential/src/lib.rs +++ b/differential/src/lib.rs @@ -8,6 +8,10 @@ //! * [`server`] is the resident-process protocol the driver speaks. //! * [`repro`] turns an input back into standalone `pathmap` calls. //! * [`act`] is the `ArenaCompactTree` read source behind `act_trace`. +//! * [`pruned`] is a second, smaller harness: the subset of the API that +//! cannot leave a dangling path, checked against `lean/PrunedModel` and +//! driven by `lean/pruned_differential.py`. See its module docs for why it +//! is not `harness` with a flag. //! //! [`algebraic`] is a third fuzzer with a different question. It has no //! oracle: it evaluates one algebraic expression every way the crate offers and @@ -16,6 +20,7 @@ pub mod act; pub mod algebraic; pub mod harness; +pub mod pruned; pub mod repro; pub mod server; diff --git a/differential/src/pruned.rs b/differential/src/pruned.rs new file mode 100644 index 00000000..9332b12b --- /dev/null +++ b/differential/src/pruned.rs @@ -0,0 +1,607 @@ +//! The crate side of the **dangling-path-free** differential harness. +//! +//! `lean/.lake/build/bin/pruned-oracle` prints the same trace from +//! `PrunedModel`; `lean/pruned_differential.py` runs both and diffs them. The +//! wire format and operation table are a contract shared with +//! `lean/PrunedModel/Fuzz.lean`; any change here must be mirrored there. +//! +//! This is not [`crate::harness`] with a flag. That harness explores the whole +//! zipper API and reproduces whatever `pathmap` does with dangling paths; its +//! prune flags are pinned to `false` and compared against nothing, because the +//! flag's effect is a function of where an internal node boundary happens to +//! fall. This one explores a smaller API and makes a stronger claim about it: +//! +//! 1. **No `create_path`.** Its whole purpose is a location with no value. +//! 2. **`prune = true` everywhere**, and `prune_path` / `prune_ascend` stay in +//! the table as assertions: the model says `0`, so a non-zero count means +//! something in the subset leaked a dangling path for it to find. +//! 3. **The write zipper is rooted at the map root.** A write zipper rooted +//! below it holds a node at its own root, which survives as a location +//! leading nowhere once everything beneath it is removed, and `prune_path` +//! does not rise above the zipper's origin. Off-root *writing* is still +//! covered: the root-rooted zipper reaches every focus with `descend_to`. +//! +//! There is one read source, a `PathMap` read zipper, so no `ReadSource` trait +//! and no ACT mode — `graft_child_maps`, quarantined in the other harness, is +//! simply not in this table. +//! +//! `--check` adds in-process assertions needing no oracle: the zipper +//! invariants from [`crate::harness::check_zipper`], plus the one this harness +//! is named for — [`check_no_dangling`]. + +use pathmap::PathMap; +use pathmap::utils::ByteMask; +use pathmap::zipper::*; + +use crate::harness::{ + check_zipper, dump, dump_fork, fingerprint, hex_path, show_bool, show_byte_opt, show_status, show_val, + Dec, MAX_STEPS, +}; + +use core::fmt::Write as _; + +/// Number of distinct operations. Must match `PrunedModel.Fuzz.nops`. +pub const NOPS: usize = 54; + +/// Why an operation was skipped. Every `skip` in the trace carries one of +/// these. `lean/PrunedModel/Fuzz.lean` emits the same tokens; the two must +/// agree exactly or every input with a skip diverges. +/// +/// Note which reasons from [`crate::harness`] are *absent*: `skip:act` (there is +/// one read source here), `skip:off-root-prune` (the write zipper is always at +/// the map root, so the prune count is well-defined), and `skip:quarantined` +/// (`graft_child_maps` is not in this table). +/// +/// `to_next`/`to_prev_sibling_byte` at the zipper root, where the native read +/// zipper escapes its own root. +pub const SKIP_AT_ROOT: &str = "skip:at-root"; +/// A degenerate `k = 0` on `join_k_path_into` / `meet_k_path_into`. +pub const SKIP_K0: &str = "skip:k0"; +/// The focus has nothing below it, where the op's behaviour is a function of +/// node materialisation rather than of trie state. +pub const SKIP_EMPTY_FOCUS: &str = "skip:empty-focus"; +/// `insert_prefix("")`, which destroys the subtrie. +pub const SKIP_EMPTY_PATH: &str = "skip:empty-path"; + +/// The prune flag every operation in this subset is driven with. +/// +/// The opposite of [`crate::harness`]'s `no_prune`, and for the same reason +/// stated the other way round: there, the flag's effect is unspecifiable, so it +/// is never exercised; here, removal is *defined* to reclaim the chain, so it is +/// always exercised and always compared. +const PRUNE: bool = true; + +/// Does the focus have no descendants at all? +/// +/// Several return values (`remove_branches`, `restricting`, `join_map_into`, +/// `take_map`, `restrict`) hinge on whether an *empty node* happens to be +/// materialised at the focus rather than on the logical state, so they are +/// masked here. +fn focus_node_empty(z: &Z) -> bool { + z.child_count() == 0 +} + +/// Canonical rendering of a decoded byte mask: ascending, deduplicated, which is +/// what `ByteMask.ofList` produces on the Lean side. +fn canon_mask(m: &[u8]) -> Vec { + let mut v = m.to_vec(); + v.sort_unstable(); + v.dedup(); + v +} + +/// **The invariant this harness is named for**: no location exists without +/// leading to a value. +/// +/// Walks the whole map and asserts that every location with no children carries +/// a value. The root of an empty map is the one exception — `PathMap::new()` +/// reports `path_exists() == true` at the root, and there is nothing it could +/// lead to. +/// +/// This needs no oracle, which makes it the cheapest way to run the subset: +/// `--check` asserts it after every operation, and a failure localises the +/// leaking operation to one step without a trace diff. +pub fn check_no_dangling(map: &PathMap, label: &str) { + let mut z = map.read_zipper(); + // `to_next_step` visits every location below the root in depth-first order; + // the root itself is checked by the `is_empty` escape above. + loop { + if z.child_count() == 0 && !z.is_val() { + panic!( + "{label}: dangling path at {} -- a location with no value and no children", + hex_path(z.path()) + ); + } + if !z.to_next_step() { + break; + } + } +} + +/// Decode the header: two seeded maps and the read zipper's root. +/// +/// The write zipper's root is not decoded — it is always the map root. The read +/// zipper's root is decoded as a path and then clamped to its longest existing +/// prefix, rather than created: `create_path` is not in this subset, and a +/// zipper whose root does not exist can walk out of it (lean/FINDINGS.md #3), +/// which would contaminate every other comparison. +pub fn decode_header(d: &mut Dec) -> Option<(PathMap, PathMap, Vec)> { + let mut m0 = PathMap::::new(); + let n0 = d.modn(8)?; + for _ in 0..n0 { + let p = d.path(6)?; + let v = d.u8()? as u64; + m0.set_val_at(&p, v); + } + let mut m1 = PathMap::::new(); + let n1 = d.modn(8)?; + for _ in 0..n1 { + let p = d.path(6)?; + let v = d.u8()? as u64; + m1.set_val_at(&p, v); + } + let raw = d.path(4)?; + // Existence is prefix-closed, so the prefixes that exist form an initial + // segment: stop at the first one that does not. `PrunedModel.Fuzz`'s + // `clampToExisting` is the same computation over the model. + let mut root1: Vec = Vec::new(); + for j in 1..=raw.len() { + if m1.read_zipper_at_path(&raw[..j]).path_exists() { + root1 = raw[..j].to_vec(); + } else { + break; + } + } + Some((m0, m1, root1)) +} + +/// Decode and execute a fuzzer input. +pub fn run(bytes: &[u8], check: bool) -> String { + let mut d = Dec::legacy(bytes); + let (mut map0, map1, root1) = match decode_header(&mut d) { + Some(x) => x, + None => return "EMPTY\n".to_string(), + }; + let mut out = String::new(); + { + // NOTE: `read_zipper_at_borrowed_path` would panic (release: wrap) in + // `to_next_k_path`, whose `path_len()` underflows before the path buffer + // is prepared. Use the owned-path constructor so that known bug does + // not abort every run. + let mut rz = map1.read_zipper_at_path(&root1); + run_ops(&mut d, &mut out, &mut map0, &mut rz, &root1, check); + } + // The check needs the whole map, which the live write zipper holds, so it + // runs here rather than per step. Localising a leak to one operation is the + // trace diff's job; this is the no-oracle path. + if check { + check_no_dangling(&map0, "map0"); + } + let _ = writeln!(out, "MAP0 {}", dump(&mut map0.read_zipper())); + let _ = writeln!(out, "MAP1 {}", dump(&mut map1.read_zipper())); + // Printed for trace compatibility with the other harness, and because a + // reader of a divergence wants to see both roots stated rather than inferred. + let _ = writeln!(out, "ROOT0 {}", hex_path(&[])); + let _ = writeln!(out, "ROOT1 {}", hex_path(&root1)); + out +} + +/// Bind `$z` to the write zipper (`t == 0`) or the read zipper, then run `$e`. +macro_rules! tgt { + ($t:expr, $wz:expr, $rz:expr, $z:ident, $e:expr) => { + if $t == 0 { + let $z = &mut $wz; + $e + } else { + let $z = &mut $rz; + $e + } + }; +} + +/// Run the operation table. +pub fn run_ops( + d: &mut Dec, + out: &mut String, + map0: &mut PathMap, + rz: &mut ReadZipperUntracked<'_, '_, u64>, + root1: &[u8], + check: bool, +) { + let mut wz = map0.write_zipper(); + let root0: &[u8] = &[]; + let mut step = 0usize; + + macro_rules! get { + ($e:expr) => { + match $e { + Some(x) => x, + None => break, + } + }; + } + + loop { + if step >= MAX_STEPS { + break; + } + let op = get!(d.u8()) as usize % NOPS; + let (name, ret): (&str, String) = match op { + // ## Movement and reading, on either zipper + 0 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + tgt!(t, wz, *rz, z, z.descend_to(&p)); + ("descend_to", hex_path(&p)) + } + 1 => { + let t = get!(d.modn(2)); + let b = get!(d.path_byte()); + tgt!(t, wz, *rz, z, z.descend_to_byte(b)); + ("descend_to_byte", format!("{b:02x}")) + } + 2 => { + let t = get!(d.modn(2)); + let n = get!(d.modn(8)); + let r = tgt!(t, wz, *rz, z, z.ascend(n)); + ("ascend", format!("{r}")) + } + 3 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.ascend_byte()); + ("ascend_byte", show_bool(r).to_string()) + } + 4 => { + let t = get!(d.modn(2)); + tgt!(t, wz, *rz, z, z.reset()); + ("reset", "-".to_string()) + } + 5 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.descend_first_byte()); + ("descend_first_byte", show_byte_opt(r)) + } + 6 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.descend_last_byte()); + ("descend_last_byte", show_byte_opt(r)) + } + 7 => { + let t = get!(d.modn(2)); + let i = get!(d.modn(6)); + let r = tgt!(t, wz, *rz, z, z.descend_indexed_byte(i)); + ("descend_indexed_byte", show_byte_opt(r)) + } + 8 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.descend_until()); + ("descend_until", show_bool(r).to_string()) + } + 9 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.ascend_until()); + ("ascend_until", format!("{r}")) + } + 10 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.ascend_until_branch()); + ("ascend_until_branch", format!("{r}")) + } + 11 => { + let t = get!(d.modn(2)); + // Skipped at the zipper root: the native ReadZipper escapes its + // own root there. + if tgt!(t, wz, *rz, z, z.at_root()) { + ("to_next_sibling_byte", SKIP_AT_ROOT.to_string()) + } else { + let r = tgt!(t, wz, *rz, z, z.to_next_sibling_byte()); + ("to_next_sibling_byte", show_byte_opt(r)) + } + } + 12 => { + let t = get!(d.modn(2)); + if tgt!(t, wz, *rz, z, z.at_root()) { + ("to_prev_sibling_byte", SKIP_AT_ROOT.to_string()) + } else { + let r = tgt!(t, wz, *rz, z, z.to_prev_sibling_byte()); + ("to_prev_sibling_byte", show_byte_opt(r)) + } + } + 13 => { + let t = get!(d.modn(2)); + let r = tgt!(t, wz, *rz, z, z.to_next_step()); + ("to_next_step", show_bool(r).to_string()) + } + 14 => { + // `ZipperIteration` is read-only: the target byte is still + // consumed, but the operation always applies to `rz`. + let _t = get!(d.modn(2)); + ("to_next_val", show_bool(rz.to_next_val()).to_string()) + } + 15 => { + let _t = get!(d.modn(2)); + let k = get!(d.modn(4)); + // k == 0 is specified as an unsuccessful descent. + ("descend_first_k_path", show_bool(rz.descend_first_k_path(k)).to_string()) + } + 16 => { + let _t = get!(d.modn(2)); + let k = get!(d.modn(4)); + // A whole k-path iteration: `to_next_k_path` on its own + // continues state left by `descend_first_k_path`. + let mut v: Vec = Vec::new(); + if rz.descend_first_k_path(k) { + v.push(hex_path(rz.path())); + while v.len() < 32 && rz.to_next_k_path(k) { + v.push(hex_path(rz.path())); + } + } + ("k_path_walk", v.join(",")) + } + 17 => { + let _t = get!(d.modn(2)); + ("descend_last_path", show_bool(rz.descend_last_path()).to_string()) + } + 18 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + let n = tgt!(t, wz, *rz, z, z.move_to_path(&p)); + ("move_to_path", format!("{n}")) + } + 19 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + let n = tgt!(t, wz, *rz, z, z.descend_to_existing(&p)); + ("descend_to_existing", format!("{n}")) + } + 20 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + let n = tgt!(t, wz, *rz, z, z.descend_to_val(&p)); + ("descend_to_val", format!("{n}")) + } + 21 => { + let t = get!(d.modn(2)); + let b = get!(d.path_byte()); + let r = tgt!(t, wz, *rz, z, z.descend_to_existing_byte(b)); + ("descend_to_existing_byte", show_bool(r).to_string()) + } + 22 => { + let t = get!(d.modn(2)); + let n = get!(d.modn(8)); + let r = tgt!(t, wz, *rz, z, z.descend_until_max_bytes(n)); + ("descend_until_max_bytes", show_bool(r).to_string()) + } + 23 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + let r = tgt!(t, wz, *rz, z, z.descend_to_check(&p)); + ("descend_to_check", show_bool(r).to_string()) + } + 24 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + let v = tgt!(t, wz, *rz, z, show_val(z.val_at(&p))); + ("val_at", v) + } + 25 => { + let t = get!(d.modn(2)); + let n = if t == 0 { + wz.make_map().val_count() + } else { + rz.make_map().val_count() + }; + ("make_map_val_count", format!("{n}")) + } + 26 => { + let t = get!(d.modn(2)); + let s = if t == 0 { dump_fork(&wz) } else { dump_fork(&*rz) }; + ("dump", s) + } + 27 => { + let t = get!(d.modn(2)); + // The blind-zipper addition: `descend_until` reporting the bytes + // it descended. The observer's output is a blind zipper's only + // account of where it went, so it is compared byte for byte. + let mut obs: Vec = Vec::new(); + let r = tgt!(t, wz, *rz, z, z.descend_until_observed(&mut obs)); + ("descend_until_observed", format!("{}:{}", show_bool(r), hex_path(&obs))) + } + 28 => { + let t = get!(d.modn(2)); + let p = get!(d.path(6)); + // `get_val`/`get_val_at` must agree with `val`/`val_at`; they + // differ only in the lifetime of the reference returned. + let (g, ga, agree) = if t == 0 { + // A write zipper has no `ZipperReadOnlyValues`. + (wz.val().copied(), wz.val_at(&p).copied(), true) + } else { + let (g, ga) = (rz.get_val().copied(), rz.get_val_at(&p).copied()); + let agree = g == rz.val().copied() && ga == rz.val_at(&p).copied(); + (g, ga, agree) + }; + ( + "get_val_agrees", + format!("{}:{}:{}", show_val(g.as_ref()), show_val(ga.as_ref()), show_bool(agree)), + ) + } + 29 => { + let got = rz.to_next_get_val().copied(); + // `to_next_get_val` is specified as `to_next_val` followed by + // reading the value, so `Some` must mean it moved and must equal + // what `val` reports. + let agree = got == rz.val().copied() || (got.is_none() && rz.at_root()); + ( + "to_next_get_val", + format!("{}:{}:{}", show_bool(got.is_some()), show_val(got.as_ref()), show_bool(agree)), + ) + } + // ## Writing, on the write zipper + 30 => { + let v = get!(d.u8()) as u64; + ("set_val", show_val(wz.set_val(v).as_ref())) + } + 31 => ("remove_val", show_val(wz.remove_val(PRUNE).as_ref())), + 32 => { + // Must be `0`: a trie built from this subset has no dangling tip. + ("prune_path", format!("{}", wz.prune_path())) + } + 33 => ("prune_ascend", format!("{}", wz.prune_ascend())), + 34 => { + let leaky = focus_node_empty(&wz); + let r = wz.remove_branches(PRUNE); + // An empty node still comes back as `Some(..)` from + // `into_option()` for some representations, so `true` gets + // reported for a removal of nothing. Compared only when there + // was something below. + let s = if leaky { "?".to_string() } else { show_bool(r).to_string() }; + ("remove_branches", s) + } + 35 => { + let n = get!(d.modn(4)); + let m = get!(d.path_n(n)); + wz.remove_unmasked_branches(ByteMask::from_iter(m.iter().copied()), PRUNE); + ("remove_unmasked_branches", hex_path(&canon_mask(&m))) + } + 36 => { + wz.graft(&*rz); + ("graft", "-".to_string()) + } + 37 => { + let p = get!(d.path(6)); + wz.graft_src_at(&*rz, &p); + ("graft_src_at", hex_path(&p)) + } + 38 => ("join_into", show_status(wz.join_into(&*rz)).to_string()), + 39 => { + let leaky = focus_node_empty(&wz); + let st = wz.join_map_into(rz.make_map()); + let s = if leaky { "?".to_string() } else { show_status(st).to_string() }; + ("join_map_into", s) + } + 40 => ("meet_into", show_status(wz.meet_into(&*rz, PRUNE)).to_string()), + 41 => ("subtract_into", show_status(wz.subtract_into(&*rz, PRUNE)).to_string()), + 42 => { + let leaky = focus_node_empty(&wz); + let st = wz.restrict(&*rz); + let s = if leaky { "?".to_string() } else { show_status(st).to_string() }; + ("restrict", s) + } + 43 => { + // Skipped when either side has nothing below its focus: there + // `restricting` branches on whether an empty node happens to be + // materialised, and the branches differ in *effect*. + if focus_node_empty(&wz) || focus_node_empty(rz) { + ("restricting", SKIP_EMPTY_FOCUS.to_string()) + } else { + ("restricting", show_bool(wz.restricting(&*rz)).to_string()) + } + } + 44 => { + let k = get!(d.modn(4)); + // `join_k_path_into(0)` collapses the subtrie instead of being + // the identity. + if k == 0 { + ("join_k_path_into", SKIP_K0.to_string()) + } else { + let r = wz.join_k_path_into(k, PRUNE); + let s = if focus_node_empty(&wz) { "?".to_string() } else { show_bool(r).to_string() }; + ("join_k_path_into", s) + } + } + 45 => { + let p = get!(d.path(6)); + // `insert_prefix("")` destroys the subtrie. + if p.is_empty() { + ("insert_prefix", SKIP_EMPTY_PATH.to_string()) + } else { + ("insert_prefix", show_bool(wz.insert_prefix(&p)).to_string()) + } + } + 46 => { + let n = get!(d.modn(6)); + ("remove_prefix", wz.remove_prefix(n).to_string()) + } + 47 => { + let leaky = focus_node_empty(&wz) && wz.val().is_none(); + let r = match wz.take_map(PRUNE) { + Some(m) => { + wz.graft_map(m); + "1" + } + None => "0", + }; + ("take_map_restore", if leaky { "?".to_string() } else { r.to_string() }) + } + 48 => { + let k = get!(d.modn(4)); + // `meet_k_path_into` spins forever when the focus has no + // children, and escapes the focus subtree when k == 0. + if k == 0 { + ("meet_k_path_into", SKIP_K0.to_string()) + } else if wz.child_count() == 0 { + ("meet_k_path_into", SKIP_EMPTY_FOCUS.to_string()) + } else { + ("meet_k_path_into", show_bool(wz.meet_k_path_into(k, PRUNE)).to_string()) + } + } + 49 => { + let v = get!(d.u8()) as u64; + // Writing through the reference `get_val_mut` hands back. It + // must behave like `set_val` where a value exists and do nothing + // -- crucially, not create the path -- where one does not. + let old = match wz.get_val_mut() { + Some(slot) => { + let old = *slot; + *slot = v; + Some(old) + } + None => None, + }; + ("get_val_mut_write", show_val(old.as_ref())) + } + 50 => { + let v = get!(d.u8()) as u64; + let r = *wz.get_val_or_set_mut(v); + ("get_val_or_set_mut", show_val(Some(&r))) + } + 51 => { + let v = get!(d.u8()) as u64; + // `ran` records whether the closure was invoked; the contract is + // that it supplies the value only when none exists. + let mut ran = false; + let r = *wz.get_val_or_set_mut_with(|| { + ran = true; + v + }); + ("get_val_or_set_mut_with", format!("{}:{}", show_val(Some(&r)), show_bool(ran))) + } + 52 => { + let n = get!(d.modn(4)); + let m = get!(d.path_n(n)); + let ru = get!(d.boolean()); + wz.graft_masked_branches(&*rz, ByteMask::from_iter(m.iter().copied()), ru); + ("graft_masked_branches", format!("{}:{}", hex_path(&canon_mask(&m)), show_bool(ru))) + } + 53 => { + let p = get!(d.path(6)); + // `meet_2` takes two sources; the second is the first moved to `p`. + let mut b = rz.clone(); + b.descend_to(&p); + ("meet_2", show_status(wz.meet_2(&*rz, &b)).to_string()) + } + _ => ("nop", "-".to_string()), + }; + if check { + check_zipper(&wz, "write zipper", root0); + check_zipper(rz, "read zipper", root1); + } + let _ = writeln!( + out, + "{step} {name} ret={ret} W={} R={}", + fingerprint(&wz, root0), + fingerprint(rz, root1) + ); + step += 1; + } +} diff --git a/lean/PRUNED_FINDINGS.md b/lean/PRUNED_FINDINGS.md new file mode 100644 index 00000000..beecd529 --- /dev/null +++ b/lean/PRUNED_FINDINGS.md @@ -0,0 +1,211 @@ +# Findings from the dangling-path-free model + +What `lean/pruned_differential.py` found, driving `PrunedModel` (the oracle) +against `differential/src/pruned.rs` (the crate) on `pathmap` 0.4.0 at +`833d524`. + +This is a separate file from `FINDINGS.md` because it is a separate claim. +`FINDINGS.md` records what the crate does with dangling paths, as discovered by +a model that reproduces them. This model instead *forbids* them: its subset is +chosen so that no operation in it should be able to make a location that leads +nowhere. So every finding here has the same shape — "this operation made one" — +and the interest is in which operations, and why. + +Minimal reproducers are in `lean/pruned-corpus/`, 9–47 bytes each. Replay one +with + + ./target/release/pruned_trace lean/pruned-corpus/.bin + ./lean/.lake/build/bin/pruned-oracle lean/pruned-corpus/.bin + +or check the whole corpus with `./lean/pruned_differential.py +lean/pruned-corpus/*`. + +**On master (`de125bb`, without `focus_value_consistency`)** the model is ahead +of the crate. It specifies issue #104, so the operations #104 changes diverge +until that lands: `remove_prefix` (the model returns a count, master a bool), +and the focus value of `insert_prefix`, `join_into`, `meet_2`, +`join_k_path_into`, `restrict` and `meet_k_path_into`. These are reported as +new divergences, not filed under `KNOWN`. The `skip:k0`, `skip:empty-path` +and childless `meet_k_path_into` skips are back for the same reason: master +still collapses the subtrie, escapes the focus, or loops forever there. + +## 1. An empty write materialises the focus + +**Seven operations create or keep a dangling path when what they write is +empty.** First 300 random inputs: 63 of 70 divergences, and every one of them +this. + +| operation | reproducer | +| --- | --- | +| `graft` | `graft-empty-src-creates-dangling-focus.bin` | +| `graft_src_at` | `graft_src_at-empty-src-creates-dangling-focus.bin` | +| `graft_masked_branches` | `graft_masked_branches-creates-dangling-focus.bin` | +| `meet_2` | `meet_2-empty-result-creates-dangling-focus.bin` | +| `restrict` | `restrict-empty-result-creates-dangling-focus.bin` | +| `restricting` | `restricting-creates-dangling-focus.bin` | +| `remove_prefix` | `remove_prefix-creates-dangling-chain.bin` | + +The smallest is nine bytes. An empty `map1`, a `map0` holding one root value, a +write zipper at the map root descended one byte to a location that does not +exist, and then `graft` from a read zipper whose subtrie is empty: + + 0 descend_to_byte ret=00 W=00 o00 e0 v- c0 n0 + 1 graft ret=- W=00 o00 e0 v- c0 n0 model + 1 graft ret=- W=00 o00 e1 v- c0 n0 crate + MAP0 _:- model + MAP0 _:-,00:- crate + +`path_exists()` reports `true` at a location with no value and no children. +Nothing leads there and nothing can reach it except a zipper that already knows +the path, so it is pure overhead to every traversal — and `val_count() == 0` +beside `child_count() == 0` and `path_exists() == true` is a state no reader of +the trait documentation would expect to have to handle. + +It is worth being precise about what this is, because "forgot to prune" is only +half of it. There are two cases, and the second is the one that matters: + +* Where the focus **existed**, the operation empties it and leaves the chain + behind. That is a missing prune. +* Where the focus **did not exist**, the operation *creates* it — the write path + materialises the node chain down to the focus before discovering it has + nothing to put there, and then returns without undoing that. The seven + reproducers above are all of this kind, because the shrinker found it the + cheaper shape to reach. `graft` with an empty source is accidentally + `create_path`. + +`remove_prefix` shows the scale: it creates the whole chain, not just the tip. + + 2 remove_prefix ret=1 MAP0 _:- model + 2 remove_prefix ret=1 MAP0 _:-,00:-,0000:-,000000:- crate + +**Why these seven and not the others.** `remove_val`, `remove_branches`, +`remove_unmasked_branches`, `meet_into`, `subtract_into` and `join_k_path_into` +take a `prune: bool`, and with `prune = true` — which is what this harness +passes throughout — they clean up correctly. The seven above have no such +parameter, so a caller who wants a tidy trie has no way to ask for one. The +asymmetry looks unintended rather than designed: `meet_into` and `meet_2` are +the same operation with and without a destination, and only one of them can be +told to prune. + +Two fixes are available and they are not equivalent. Adding `prune` to the +seven makes the behaviour reachable; making the empty write a no-op on a +non-existent focus makes it correct, since an operation whose result is "nothing" +has no business creating a location. The second also fixes the `create_path` +accident, which the first does not. + +## 2. `graft_masked_branches` creates a child for a branch the source lacks + +`graft_masked_branches-creates-dangling-child.bin`, 10 bytes. Both maps empty, +write zipper at the root, mask `{0x01}`, `remove_unset = false`: + + 0 graft_masked_branches ret=01:0 W=_ o_ e1 v- c0 n0 model + 0 graft_masked_branches ret=01:0 W=_ o_ e1 v- c1 n0 crate + MAP0 _:- model + MAP0 _:-,01:- crate + +This is finding 1's mechanism one level down, and it is worse there, because the +location it creates is a *child of the focus* rather than the focus itself: the +focus's `child_mask` now has a bit set for a branch that holds nothing, and +`child_count() == 1` with `val_count() == 0`. Every consumer that uses +`child_mask` to decide where to recurse will now walk into it. + +Each set bit of the mask is specified as a `graft_src_at` of the source's +corresponding child, and grafting nothing removes — so a set bit whose branch is +absent from the source must leave that branch absent here. Instead it is +created. + +## 3. Pre-existing classes this model also reports + +Two divergence shapes are not about dangling paths. Both are already recorded +against the other model; they appear here because the operation subsets overlap, +and they are in the corpus so a regression in either shows up in whichever +harness is run. + +* **A value collision resolves to the counterpart.** + `join_into-value-bias-by-node-layout.bin`. `u64`'s `pjoin` returns + `Identity(SELF_IDENT)`, so the destination's value must survive a collision; + at one location out of six the crate kept the source's (`0301:118` against + `0301:0`). Which location depends on node layout, not on the paths — see + `FINDINGS.md` on value bias. 7 of 4000 inputs. + +* **`Identity` is not reported where nothing changed.** + `join_map_into-status-element-when-unchanged.bin`. The source map is + `{[] ↦ v}` and the destination focus already holds `v`, so both the value step + and the node step are identities and the status must be `Identity`; the crate + says `Element`. `FINDINGS.md` #8. 87 of 4000 inputs, across `join_map_into` + (most), `subtract_into` and `meet_into`. + +## 4. Against `fuzz-fixes-v3` + +Same 4000 inputs, same seed, with the harness built on `fuzz-fixes-v3` +(`ee7546e`) and the oracle unchanged. `fuzz-fixes-v3` carries 73 commits of +fixes off an older master, several of them about dangling paths, so the question +is which of the above it already answers. + +| finding | master `ec818cf` | `fuzz-fixes-v3` | +| --- | --- | --- | +| #1 + #2, empty write materialises a location | 897 + 64 | **not fixed** — 974, and all 8 reproducers still diverge | +| #3, value bias | 7 | fixed (`3dae731`, "Make meet/join value bias independent of node layout") | +| #3, `Identity` not reported | 87 | fixed | + +So the branch fixes the one class this model genuinely inherited, and neither of +the two it found. That is not surprising — `fuzz-fixes-v3` was driven by the +other model, which *reproduces* dangling paths rather than forbidding them, so no +amount of fuzzing against it could have reported finding 1. It is the clearest +argument for keeping both models: they cannot find each other's bugs. + +Two attribution traps are worth writing down, because both caught me. + +* The `Identity` row needs a qualification. Most of that class was **the models + describing a `join_map_into` status master had already changed** in PR #142 + (`276fca0`, issue #139): its empty-source-node exit used to `return` the node + status on its own, discarding a value status for a value it had already + written, and master replaced that with + `node_status.merge(val_status, true, true)`. Both models still described the + early return — corrected in the commit after this one, which takes the class + from 104 of 4000 to 8. `fuzz-fixes-v3` predates PR #142, so it scored 0 on this + not by fixing anything but by still matching what the models said. +* `3e839e8` ("Fix join_into replacing or misreporting a destination that holds + the source") looks like a candidate and is **already on master** as `1e3b1c3` + (PR #116); cherry-picking it yields only comment churn and duplicate tests. + +Check `git log master -S` before attributing anything here to v3. + +Two things in the v3 column are **not** findings and should not be read as any: + +* **420 inputs diverge in `descend_first_k_path` / `k_path_walk`.** v3 changes + the k-path walk (`7f9c59a`, "Fix the default k-path walk looping forever at a + leaf", among others) and updates its own copy of the model to match. + `PrunedModel` was ported from master's model, so it still specifies master's + behaviour. This is spec drift between the two branches, and re-measuring the + k-path operations on v3 needs the port redone against v3's model. +* **45 of 600 inputs show `subtract_into` reporting `Identity`** where the model + says `Element` — the opposite direction from finding 3. v3 deliberately + changed the integer instance (`f8a4599`, "Return Identity from the integer + psubtract when nothing was subtracted"); `Basic.u64Ops` is master's and + returns `Element(*self)`. Also spec drift. + +Both are visible only because the oracle is pinned to master while the crate is +not. The `STATUS-ONLY` shape in particular is two-directional, so the driver's +`KNOWN` note for it says to read the direction rather than the tag. + +## What is not covered + +The subset deliberately excludes three things, and a reader comparing the two +harnesses should know they are gaps here rather than absences of defects: + +* `create_path`, and `remove_val(false)` — they make dangling paths on purpose. +* A write zipper rooted below the map root. It holds a node at its own root, + which survives as a dangling path once everything below it is removed, and + `prune_path` is documented not to rise above the zipper's origin. So a + dangling root there is the documented behaviour, not a defect, and comparing + it would drown everything else. Off-root *writing* is covered: the + root-rooted zipper reaches every focus with `descend_to`. +* `graft_child_maps`, which `FINDINGS.md` #15 records as broken three ways. + +Operations the subset *does* cover are specified, not skipped, even where they +are known to leak — which is why finding 1 is reported rather than suppressed. +The four `skip:` reasons that remain (`at-root`, `k0`, `empty-focus`, +`empty-path`) are the ones where the crate's behaviour is a function of node +materialisation rather than of trie state, so there is nothing for a model to +agree with; each is commented at its site in `PrunedModel/Fuzz.lean`. diff --git a/lean/PrunedMain.lean b/lean/PrunedMain.lean new file mode 100644 index 00000000..3018be81 --- /dev/null +++ b/lean/PrunedMain.lean @@ -0,0 +1,91 @@ +import PrunedModel + +/-! +The oracle for the dangling-path-free model. + +One-shot: + + pruned-oracle -- decode and run the file's bytes + pruned-oracle -- read the bytes from stdin + +Resident: + + pruned-oracle --server -- one process, many inputs + +Spawning a fresh process per fuzzer input costs more than running the input +does, so `pruned_differential.py` keeps the oracle resident and feeds it work +over stdin. The protocol matches `differential/src/server.rs`, one command per +line: + + run-input run the decoded bytes, print the trace + quit exit 0 + +The reply is the trace lines, then exactly one terminator line, which is the +only line beginning with `!`: + + !DONE the trace above is complete + !TIMEOUT exceeded + !PANIC malformed command + +`differential/src/bin/pruned_trace.rs` prints the same trace from the real +crate for the same input bytes; `lean/pruned_differential.py` diffs them. + +The timeout argument is parsed and ignored, as in `lean/Main.lean`: no +in-process timeout is reachable from Lean's `IO.asTask`/`IO.hasFinished`, and +the driver has to enforce the deadline from outside regardless, since no +in-process timeout can save a child that has died. The model is total, so it +cannot hang, only be slow. +-/ + +open PrunedModel + +/-- Decode a lowercase/uppercase hex string. -/ +def hexDecode (s : String) : Option ByteArray := + let cs := s.toList + if cs.length % 2 != 0 then none + else + let rec go : List Char → ByteArray → Option ByteArray + | [], acc => some acc + | a :: b :: rest, acc => do + let hi ← a.toString.toNat? |>.orElse fun _ => + "0123456789abcdef".toList.idxOf? a.toLower + let lo ← b.toString.toNat? |>.orElse fun _ => + "0123456789abcdef".toList.idxOf? b.toLower + go rest (acc.push (UInt8.ofNat (hi * 16 + lo))) + | _, _ => none + go cs ByteArray.empty + +/-- The resident command loop. -/ +partial def serve : IO Unit := do + let stdin ← IO.getStdin + let stdout ← IO.getStdout + let rec loop : IO Unit := do + let line ← stdin.getLine + -- `getLine` returns "" only at EOF; a blank line is "\n". + if line.isEmpty then return + let line := line.trimAscii.toString + if line == "quit" then return + let terminator ← + match line.splitOn " " with + | "run-input" :: ms :: rest => + match ms.toNat?, hexDecode (String.intercalate " " rest) with + | some _, some bytes => do + for line in Fuzz.run bytes 256 do + stdout.putStrLn line + pure "!DONE" + | _, _ => pure "!PANIC bad run-input arguments" + | _ => pure s!"!PANIC unknown command: {line}" + stdout.putStrLn terminator + stdout.flush + loop + loop + +def main (args : List String) : IO Unit := do + if args.contains "--server" then + return ← serve + let files := args.filter (fun a => !a.startsWith "--") + let bytes ← match files with + | [] => (← IO.getStdin).readBinToEnd + | path :: _ => IO.FS.readBinFile path + for line in Fuzz.run bytes 256 do + IO.println line diff --git a/lean/PrunedModel.lean b/lean/PrunedModel.lean index 9bfdab62..c4df10fd 100644 --- a/lean/PrunedModel.lean +++ b/lean/PrunedModel.lean @@ -8,3 +8,4 @@ import PrunedModel.Nested import PrunedModel.Pointwise import PrunedModel.Refine import PrunedModel.Zippy +import PrunedModel.Fuzz diff --git a/lean/PrunedModel/Fuzz.lean b/lean/PrunedModel/Fuzz.lean new file mode 100644 index 00000000..04edeb6d --- /dev/null +++ b/lean/PrunedModel/Fuzz.lean @@ -0,0 +1,551 @@ +import PrunedModel.Spec + +/-! +# Differential-fuzzing front end for the dangling-path-free subset + +This module turns `PrunedModel` into an **oracle**: it decodes a raw fuzzer +input into a program over two maps and two zippers, runs it, and emits a trace. +`differential/src/pruned.rs` decodes the *same bytes* with the *same* rules and +emits the *same* trace format from the real crate, so a behavioural divergence +is a textual diff. `lean/pruned_differential.py` drives the pair. + +## How this differs from `PathMapModel.Fuzz` + +That harness explores the whole zipper API and reproduces whatever `pathmap` +does with dangling paths, including the parts nobody wants. Its prune flags are +therefore pinned to `false` and compared against nothing, because the flag's +effect is a function of where an internal node boundary happens to fall. + +This one explores a smaller API and makes a stronger claim about it. Three +restrictions define the subset: + +1. **No `create_path`.** Its whole purpose is a location with no value. +2. **`prune = true` everywhere.** Removal here is inherently pruning: a chain + that exists only to reach a value goes when the value does. `prune_path` and + `prune_ascend` stay in the table as *assertions* — the model says `0`, so a + non-zero count from the crate means something in the subset leaked a dangling + path for it to find. +3. **The write zipper is rooted at the map root.** A write zipper rooted below + it holds a node at its own root, which survives as a location leading nowhere + once everything beneath is removed, and `prune_path` is documented not to rise + above the zipper's origin. That is outside the model by construction rather + than by a bug. Off-root *writing* is still covered: the root-rooted zipper + reaches every focus with `descend_to`. + +The read zipper may be rooted anywhere that exists. Its root is decoded as a +path and then clamped to its longest existing prefix, so it is never a location +the seeding did not create — a read zipper whose root does not exist can walk +out of it (FINDINGS.md #3), which would contaminate every other comparison. + +Operations that *can* still leave a dangling path in `pathmap` 0.4.0 are +specified, not skipped. `graft` of an empty source is the clearest: the focus +loses its value and its branches, so the model removes it and the chain above +it, while the crate leaves both behind. Producing those divergences is what +this harness is for. + +## Wire format + +The input is consumed one byte at a time; decoding stops, and the program ends, +as soon as the input runs out. + +``` +header: + n := u8 % 8 -- entries seeded into map0 (the write target) + n × ( len := u8 % 6 ; len × pathbyte ; val := u8 ) + n := u8 % 8 -- entries seeded into map1 (the read source) + n × ( len := u8 % 6 ; len × pathbyte ; val := u8 ) + r1 := u8 % 4 ; r1 × pathbyte -- read zipper root, clamped to its + -- longest existing prefix +body: + repeated: op := u8 % 54 ; operands per op (see `step`) +``` + +Every **path byte** is masked to `b % 4`, so generated tries share prefixes +heavily — that is where the interesting shapes (branch points, single-child +runs, chains that exist only to reach one value) live. + +## Trace format + +One line per operation: + +``` + ret= W= o e<0|1> v c n f R=<...> +``` + +followed by a dump of both maps. Values are decimal, paths lowercase hex, `e` +is `path_exists`, `c` is `child_count`, `n` is `val_count`. A location with no +value renders as `-`, so a dangling path the crate left behind shows up in the +dump as an entry the model does not have. +-/ + +namespace PrunedModel +namespace Fuzz + +open PathMapModel + +/-- The value type the harness uses: `PathMap`. -/ +abbrev V := UInt64 +/-- The `Lattice`/`DistributiveLattice` instance `pathmap` provides for `u64`. -/ +def ops : ValOps V := u64Ops + +/-! ## Skip reasons + +Why an operation was skipped. Every `skip` in the trace carries one, so a +skipped op says which rule declined it. `differential/src/pruned.rs` emits the +same tokens; the two must agree exactly or every input with a skip diverges. + +Note which reasons from `PathMapModel.Fuzz` are *absent*: `skip:act` (there is +one read source here), `skip:off-root-prune` (the write zipper is always at the +map root, so the prune count is well-defined), and `skip:quarantined` +(`graft_child_maps` is not in this table at all). -/ + +/-- `to_next`/`to_prev_sibling_byte` at the zipper root, where the native read +zipper escapes its own root. -/ +def skipAtRoot : String := "skip:at-root" +/-- A degenerate `k = 0` on `join_k_path_into` / `meet_k_path_into`. -/ +def skipK0 : String := "skip:k0" +/-- The focus has nothing below it, where the op's behaviour is a function of +node materialisation rather than of trie state. -/ +def skipEmptyFocus : String := "skip:empty-focus" +/-- `insert_prefix("")`, which destroys the subtrie. -/ +def skipEmptyPath : String := "skip:empty-path" + +/-! ## Rendering -/ + +def hexDigit (n : Nat) : Char := + if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n) + +def hexByte (b : UInt8) : String := + let n := b.toNat + String.ofList [hexDigit (n / 16), hexDigit (n % 16)] + +def hexPath (p : Path) : String := + if p.isEmpty then "_" else String.join (p.map hexByte) + +/-- The byte a movement operation moved to, or `-` for "did not move". -/ +def showByteOpt : Option UInt8 → String + | none => "-" + | some b => hexByte b + +def showVal : Option V → String + | none => "-" + | some v => toString v.toNat + +def showBool (b : Bool) : String := if b then "1" else "0" + +/-- One location of a dump: its path, relative to `root`, and its value. -/ +def showEntry (t : PrunedMap V) (root : Path) (q : Path) : String := + hexPath q ++ ":" ++ showVal (t.valAt (root ++ q)) + +/-- All locations at and below `root`, depth-first, capped so a runaway trie +cannot make the trace unbounded. + +Every entry here *should* carry a value or lead to one. An entry rendering `-` +with nothing below it is a dangling path, which is the divergence this harness +exists to find. -/ +def dumpAt (t : PrunedMap V) (root : Path) : String := + let qs := (t.subtrie root).paths.take 64 + String.intercalate "," (qs.map (showEntry t root)) + +/-! ## Decoder -/ + +/-- A cursor over the fuzzer's input bytes. -/ +structure Dec where + bytes : ByteArray + pos : Nat + +/-- Read one byte; `none` once the input is exhausted, which ends the program. -/ +def Dec.u8 (d : Dec) : Option (UInt8 × Dec) := + if h : d.pos < d.bytes.size then some (d.bytes[d.pos]'h, { d with pos := d.pos + 1 }) + else none + +/-- Read one byte reduced modulo `m`. -/ +def Dec.mod (d : Dec) (m : Nat) : Option (Nat × Dec) := + d.u8.map (fun (b, d') => (if m == 0 then 0 else b.toNat % m, d')) + +/-- Read one *path* byte. Masked to a 4-letter alphabet so generated tries +share prefixes and actually branch. -/ +def Dec.pathByte (d : Dec) : Option (UInt8 × Dec) := + d.u8.map (fun (b, d') => (UInt8.ofNat (b.toNat % 4), d')) + +/-- Read `n` path bytes. -/ +def Dec.pathN (d : Dec) : Nat → Option (Path × Dec) + | 0 => some ([], d) + | n + 1 => do + let (b, d) ← d.pathByte + let (rest, d) ← d.pathN n + some (b :: rest, d) + +/-- Read a length-prefixed path (`len := u8 % lim`). -/ +def Dec.path (d : Dec) (lim : Nat := 6) : Option (Path × Dec) := do + let (n, d) ← d.mod lim + d.pathN n + +/-- Read a boolean (`u8 % 2`). -/ +def Dec.bool (d : Dec) : Option (Bool × Dec) := + d.u8.map (fun (b, d') => (b.toNat % 2 == 1, d')) + +/-! ## Interpreter state -/ + +/-- Two maps, two zippers: `wz` writes into map0 and is rooted at its root, `rz` +reads map1. Keeping the read source in a separate map is what lets the real +crate hold both zippers at once. -/ +structure St where + wz : PZip V + rz : PZip V + out : List String + step : Nat + +/-- The per-step fingerprint of one zipper. -/ +def fingerprint (z : PZip V) : String := + hexPath z.path ++ " o" ++ hexPath z.focus ++ + " e" ++ showBool z.pathExists ++ + " v" ++ showVal z.val ++ " c" ++ toString z.childCount ++ + " n" ++ toString z.valCount ++ + -- `focus_byte` is unspecified at the root, so it is only compared below it. + " f" ++ (if z.atRoot then "?" else showByteOpt z.focusByte) + +def emit (s : St) (name : String) (ret : String) : St := + { s with + out := (toString s.step ++ " " ++ name ++ " ret=" ++ ret ++ + " W=" ++ fingerprint s.wz ++ " R=" ++ fingerprint s.rz) :: s.out + step := s.step + 1 } + +/-! ## The operation table + +`op % nops` selects the operation. Ops `0`–`29` act on a target zipper chosen +by a following `u8 % 2` byte (`0` = write zipper, `1` = read zipper); ops +`30`–`53` are write-zipper operations. -/ + +/-- Number of distinct operations. Must match `NOPS` in +`differential/src/pruned.rs`. -/ +def nops : Nat := 54 + +/-- A full `k`-path iteration: `descend_first_k_path` followed by +`to_next_k_path` until it runs out (capped at 32 stops). Returns the locations +visited. This is the only well-defined way to use the `k`-path primitives: +`k_path_internal` carries iteration state, so calling `to_next_k_path` cold is +flagged by `pathmap`'s own debug assertions. -/ +def kWalk (z : PZip V) (k : Nat) : List Path × PZip V := + let (ok, z1) := z.descendFirstKPath k + if !ok then ([], z1) else go 31 z1 [z1.path] +where + go : Nat → PZip V → List Path → List Path × PZip V + | 0, z, acc => (acc.reverse, z) + | n + 1, z, acc => + let (moved, z') := z.toNextKPath k + if moved then go n z' (z'.path :: acc) else (acc.reverse, z') + +/-- Apply `f` to the zipper selected by `t`. -/ +def onTarget (s : St) (t : Nat) (f : PZip V → α × PZip V) : α × St := + if t == 0 then let (a, z) := f s.wz; (a, { s with wz := z }) + else let (a, z) := f s.rz; (a, { s with rz := z }) + +/-- Apply an observing operation to the zipper selected by `t`. -/ +def onTargetObs (s : St) (t : Nat) (f : PZip V → Bool × Path × PZip V) : Bool × Path × St := + if t == 0 then let (a, o, z) := f s.wz; (a, o, { s with wz := z }) + else let (a, o, z) := f s.rz; (a, o, { s with rz := z }) + +/-- Read the zipper selected by `t`. -/ +def getTarget (s : St) (t : Nat) : PZip V := if t == 0 then s.wz else s.rz + +/-- Decode and run one operation. `none` means the input ran out mid-operation, +which ends the program. -/ +def step (s : St) (d : Dec) : Option (St × Dec) := do + let (opRaw, d) ← d.u8 + let op := opRaw.toNat % nops + match op with + -- ## Movement and reading, on either zipper + | 0 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let (_, s) := onTarget s t (fun z => ((), z.descendTo p)) + some (emit s "descend_to" (hexPath p), d) + | 1 => do let (t, d) ← d.mod 2; let (b, d) ← d.pathByte + let (_, s) := onTarget s t (fun z => ((), z.descendToByte b)) + some (emit s "descend_to_byte" (hexByte b), d) + | 2 => do let (t, d) ← d.mod 2; let (n, d) ← d.mod 8 + let (r, s) := onTarget s t (fun z => z.ascend n) + some (emit s "ascend" (toString r), d) + | 3 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.ascendByte) + some (emit s "ascend_byte" (showBool r), d) + | 4 => do let (t, d) ← d.mod 2 + let (_, s) := onTarget s t (fun z => ((), z.reset)) + some (emit s "reset" "-", d) + | 5 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.descendFirstByte) + some (emit s "descend_first_byte" (showByteOpt r), d) + | 6 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.descendLastByte) + some (emit s "descend_last_byte" (showByteOpt r), d) + | 7 => do let (t, d) ← d.mod 2; let (i, d) ← d.mod 6 + let (r, s) := onTarget s t (fun z => z.descendIndexedByte i) + some (emit s "descend_indexed_byte" (showByteOpt r), d) + | 8 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.descendUntil) + some (emit s "descend_until" (showBool r), d) + | 9 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.ascendUntil) + some (emit s "ascend_until" (toString r), d) + | 10 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.ascendUntilBranch) + some (emit s "ascend_until_branch" (toString r), d) + | 11 => do let (t, d) ← d.mod 2 + -- Skipped at the zipper root: `ReadZipper::to_next_sibling_byte` + -- escapes its own root there. + if (getTarget s t).atRoot then some (emit s "to_next_sibling_byte" skipAtRoot, d) + else + let (r, s) := onTarget s t (fun z => z.toNextSiblingByte) + some (emit s "to_next_sibling_byte" (showByteOpt r), d) + | 12 => do let (t, d) ← d.mod 2 + if (getTarget s t).atRoot then some (emit s "to_prev_sibling_byte" skipAtRoot, d) + else + let (r, s) := onTarget s t (fun z => z.toPrevSiblingByte) + some (emit s "to_prev_sibling_byte" (showByteOpt r), d) + | 13 => do let (t, d) ← d.mod 2 + let (r, s) := onTarget s t (fun z => z.toNextStep) + some (emit s "to_next_step" (showBool r), d) + | 14 => do let (_t, d) ← d.mod 2 + -- `ZipperIteration` is read-only: the target byte is still + -- consumed, but the operation always applies to the read zipper. + let (r, z) := s.rz.toNextVal + some (emit { s with rz := z } "to_next_val" (showBool r), d) + | 15 => do let (_t, d) ← d.mod 2; let (k, d) ← d.mod 4 + -- `k = 0` is specified: `false`, focus untouched. `kPathFrom` + -- gives that with no special case, since it wants a location + -- strictly after the focus and the only one at depth base+0 is the + -- focus itself. + let (r, z) := s.rz.descendFirstKPath k + some (emit { s with rz := z } "descend_first_k_path" (showBool r), d) + | 16 => do let (_t, d) ← d.mod 2; let (k, d) ← d.mod 4 + -- The op is the whole walk, not one step; see `kWalk`. With + -- `k = 0` the descent fails, so the walk is empty and the + -- never-ending `to_next_k_path(0)` is not reached. + let (ps, z) := kWalk s.rz k + some (emit { s with rz := z } "k_path_walk" + (String.intercalate "," (ps.map hexPath)), d) + | 17 => do let (_t, d) ← d.mod 2 + let (r, z) := s.rz.descendLastPath + some (emit { s with rz := z } "descend_last_path" (showBool r), d) + | 18 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let (n, s) := onTarget s t (fun z => z.moveToPath p) + some (emit s "move_to_path" (toString n), d) + | 19 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let (n, s) := onTarget s t (fun z => z.descendToExisting p) + some (emit s "descend_to_existing" (toString n), d) + | 20 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let (n, s) := onTarget s t (fun z => z.descendToVal p) + some (emit s "descend_to_val" (toString n), d) + | 21 => do let (t, d) ← d.mod 2; let (b, d) ← d.pathByte + let (r, s) := onTarget s t (fun z => z.descendToExistingByte b) + some (emit s "descend_to_existing_byte" (showBool r), d) + | 22 => do let (t, d) ← d.mod 2; let (n, d) ← d.mod 8 + let (r, s) := onTarget s t (fun z => z.descendUntilMaxBytes n) + some (emit s "descend_until_max_bytes" (showBool r), d) + | 23 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let (r, s) := onTarget s t (fun z => z.descendToCheck p) + some (emit s "descend_to_check" (showBool r), d) + | 24 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + let z := getTarget s t + some (emit s "val_at" (showVal (z.valAt p)), d) + | 25 => do let (t, d) ← d.mod 2 + let z := getTarget s t + some (emit s "make_map_val_count" (toString (z.makeMap.valCount [])), d) + | 26 => do let (t, d) ← d.mod 2 + let z := getTarget s t + some (emit s "dump" (dumpAt z.trie z.focus), d) + | 27 => do let (t, d) ← d.mod 2 + -- The blind-zipper addition: `descend_until` reporting the bytes + -- it descended. The observer's output is a blind zipper's only + -- account of where it went, so it is compared byte for byte. + let (r, obs, s) := onTargetObs s t (fun z => z.descendUntilObserved) + some (emit s "descend_until_observed" (showBool r ++ ":" ++ hexPath obs), d) + | 28 => do let (t, d) ← d.mod 2; let (p, d) ← d.path + -- `ZipperReadOnlyValues::get_val`/`get_val_at` differ from + -- `val`/`val_at` only in the lifetime of the reference they + -- return, so they must give the same answer. `agree` is `1` in + -- the model by construction; a `0` from the crate is the point. + let z := getTarget s t + some (emit s "get_val_agrees" + (showVal z.val ++ ":" ++ showVal (z.valAt p) ++ ":1"), d) + | 29 => do -- `ZipperReadOnlyIteration::to_next_get_val` must advance exactly + -- as `to_next_val` does and hand back the value at the new focus. + let (moved, z) := s.rz.toNextVal + let v := if moved then z.val else none + some (emit { s with rz := z } "to_next_get_val" + (showBool moved ++ ":" ++ showVal v ++ ":1"), d) + -- ## Writing, on the write zipper + | 30 => do let (v, d) ← d.u8 + let (old, z) := s.wz.setVal (UInt64.ofNat v.toNat) + some (emit { s with wz := z } "set_val" (showVal old), d) + | 31 => do let (old, z) := s.wz.removeVal + some (emit { s with wz := z } "remove_val" (showVal old), d) + | 32 => do -- Must be `0`: a trie built from this subset has no dangling tip. + let (n, z) := s.wz.prunePath + some (emit { s with wz := z } "prune_path" (toString n), d) + | 33 => do let (n, z) := s.wz.pruneAscend + some (emit { s with wz := z } "prune_ascend" (toString n), d) + | 34 => do let leaky := s.wz.focusNodeIsEmpty + let (r, z) := s.wz.removeBranches + -- An empty node still comes back as `Some(..)` from + -- `into_option()` for some representations, so `true` gets + -- reported for a removal of nothing. Compared only when there was + -- something below. + some (emit { s with wz := z } "remove_branches" + (if leaky then "?" else showBool r), d) + | 35 => do let (n, d) ← d.mod 4; let (m, d) ← d.pathN n + let z := s.wz.removeUnmaskedBranches (ByteMask.ofList m) + some (emit { s with wz := z } "remove_unmasked_branches" + (hexPath (ByteMask.ofList m)), d) + | 36 => do let z := s.wz.graft s.rz + some (emit { s with wz := z } "graft" "-", d) + | 37 => do let (p, d) ← d.path + let z := s.wz.graftSrcAt s.rz p + some (emit { s with wz := z } "graft_src_at" (hexPath p), d) + | 38 => do let (st, z) := s.wz.joinInto ops s.rz + some (emit { s with wz := z } "join_into" (toString st), d) + | 39 => do let leaky := s.wz.focusNodeIsEmpty + let (st, z) := s.wz.joinMapInto ops s.rz.makeMap + some (emit { s with wz := z } "join_map_into" + (if leaky then "?" else toString st), d) + | 40 => do let (st, z) := s.wz.meetInto ops s.rz + some (emit { s with wz := z } "meet_into" (toString st), d) + | 41 => do let (st, z) := s.wz.subtractInto ops s.rz + some (emit { s with wz := z } "subtract_into" (toString st), d) + | 42 => do let leaky := s.wz.focusNodeIsEmpty + let (st, z) := s.wz.restrict ops s.rz + some (emit { s with wz := z } "restrict" + (if leaky then "?" else toString st), d) + | 43 => do -- Skipped, not merely masked, when either side has nothing below + -- its focus: there `restricting` branches on whether an empty node + -- happens to be materialised, and the two branches differ in + -- *effect*, not just in the reported bool. + if s.wz.focusNodeIsEmpty || s.rz.focusNodeIsEmpty then + some (emit s "restricting" skipEmptyFocus, d) + else + let (r, z) := s.wz.restricting s.rz + some (emit { s with wz := z } "restricting" (showBool r), d) + | 44 => do let (k, d) ← d.mod 4 + -- `join_k_path_into(0)` should be the identity but collapses the + -- subtrie in `pathmap` 0.4.0. + if k == 0 then some (emit s "join_k_path_into" skipK0, d) + else + let (r, z) := s.wz.joinKPathInto ops k + some (emit { s with wz := z } "join_k_path_into" + (if z.focusNodeIsEmpty then "?" else showBool r), d) + | 45 => do let (p, d) ← d.path + -- `insert_prefix("")` destroys the subtrie in `pathmap` 0.4.0. + if p.isEmpty then some (emit s "insert_prefix" skipEmptyPath, d) + else + let (r, z) := s.wz.insertPrefix p + some (emit { s with wz := z } "insert_prefix" (showBool r), d) + | 46 => do let (n, d) ← d.mod 6 + let (r, z) := s.wz.removePrefix n + some (emit { s with wz := z } "remove_prefix" (toString r), d) + | 47 => do let leaky := s.wz.focusNodeIsEmpty && s.wz.val.isNone + let (m, z) := s.wz.takeMap + if leaky then + some (emit { s with wz := (z.graftMap (m.getD PrunedMap.empty)) } + "take_map_restore" "?", d) + else + match m with + | some mm => some (emit { s with wz := z.graftMap mm } "take_map_restore" "1", d) + | none => some (emit { s with wz := z } "take_map_restore" "0", d) + | 48 => do let (k, d) ← d.mod 4 + -- `meet_k_path_into` is not implementable for these arguments; see + -- `PZip.meetKPathUnspecified`, whose two disjuncts are split out + -- here so the skip names which one fired. + if k == 0 then some (emit s "meet_k_path_into" skipK0, d) + else if s.wz.focusNodeIsEmpty then + some (emit s "meet_k_path_into" skipEmptyFocus, d) + else + let (r, z) := s.wz.meetKPathInto ops k + some (emit { s with wz := z } "meet_k_path_into" (showBool r), d) + | 49 => do let (v, d) ← d.u8 + -- Writing through the reference `get_val_mut` hands back. It must + -- behave like `set_val` where a value exists and do nothing -- + -- crucially, *not* create the path -- where one does not. + let (old, z) := s.wz.getValMutWrite (UInt64.ofNat v.toNat) + some (emit { s with wz := z } "get_val_mut_write" (showVal old), d) + | 50 => do let (v, d) ← d.u8 + let (r, z) := s.wz.getValOrSetMut (UInt64.ofNat v.toNat) + some (emit { s with wz := z } "get_val_or_set_mut" (showVal (some r)), d) + | 51 => do let (v, d) ← d.u8 + -- `ran` records whether the closure was invoked. The contract says + -- it supplies the value "if no value exists", so invoking it when a + -- value is already present is observable to any caller whose + -- closure has a side effect. + let (r, ran, z) := s.wz.getValOrSetMutWith (UInt64.ofNat v.toNat) + some (emit { s with wz := z } "get_val_or_set_mut_with" + (showVal (some r) ++ ":" ++ showBool ran), d) + | 52 => do let (n, d) ← d.mod 4; let (m, d) ← d.pathN n; let (ru, d) ← d.bool + let z := s.wz.graftMaskedBranches s.rz (ByteMask.ofList m) ru + some (emit { s with wz := z } "graft_masked_branches" + (hexPath (ByteMask.ofList m) ++ ":" ++ showBool ru), d) + | 53 => do let (p, d) ← d.path + -- `meet_2` takes two sources; the second is the first moved to `p`. + let b := { s.rz with path := s.rz.path ++ p } + let (st, z) := s.wz.meet2 ops s.rz b + some (emit { s with wz := z } "meet_2" (toString st), d) + | _ => some (emit s "nop" "-", d) + +/-- Run operations until the input is exhausted or `fuel` runs out. -/ +def loop : Nat → St → Dec → St + | 0, s, _ => s + | n + 1, s, d => + match step s d with + | some (s', d') => loop n s' d' + | none => s + +/-! ## Header -/ + +/-- Decode `n` seed entries and insert them into `t`. -/ +def seed (t : PrunedMap V) (d : Dec) : Nat → Option (PrunedMap V × Dec) + | 0 => some (t, d) + | n + 1 => do + let (p, d) ← d.path + let (v, d) ← d.u8 + seed (t.setVal p (UInt64.ofNat v.toNat)).2 d n + +/-- The longest prefix of `p` that exists in `t`. + +The read zipper's root is clamped this way instead of being created, because +`create_path` is not in this subset. A zipper whose root does not exist can +escape it — `to_next_sibling_byte` and `to_next_step` fall back on the parent's +child mask and walk out of the granted subtrie — and that one bug would +contaminate every other comparison. -/ +def clampToExisting (t : PrunedMap V) (p : Path) : Path := + -- Existence is prefix-closed, so the prefixes that exist form an initial + -- segment and the longest one is the answer. + p.take (((List.range (p.length + 1)).filter + (fun j => t.pathExists (p.take j))).getLast?.getD 0) + +/-- Decode the header: two seeded maps and the read zipper's root. The write +zipper is always rooted at the map root; see the module docstring. -/ +def header (d : Dec) : Option (St × Dec) := do + let (n0, d) ← d.mod 8 + let (m0, d) ← seed PrunedMap.empty d n0 + let (n1, d) ← d.mod 8 + let (m1, d) ← seed PrunedMap.empty d n1 + let (r1raw, d) ← d.path 4 + let r1 := clampToExisting m1 r1raw + some ({ wz := { trie := m0, root := [], path := [] } + rz := { trie := m1, root := r1, path := [] } + out := [], step := 0 }, d) + +/-! ## Entry point -/ + +/-- Decode and run a fuzzer input, returning the trace lines. -/ +def run (bytes : ByteArray) (maxSteps : Nat := 256) : List String := + match header { bytes, pos := 0 } with + | none => ["EMPTY"] + | some (s0, d) => + let s := loop maxSteps s0 d + let final := + ("MAP0 " ++ dumpAt s.wz.trie []) :: + ("MAP1 " ++ dumpAt s.rz.trie []) :: + ("ROOT0 " ++ hexPath s.wz.root) :: + ("ROOT1 " ++ hexPath s.rz.root) :: [] + s.out.reverse ++ final + +end Fuzz +end PrunedModel diff --git a/lean/PrunedModel/Map.lean b/lean/PrunedModel/Map.lean index d5257c53..4c656157 100644 --- a/lean/PrunedModel/Map.lean +++ b/lean/PrunedModel/Map.lean @@ -31,11 +31,8 @@ and `subtract` is pointwise. The claim this model makes is therefore stronger than the other one's. Where `PathMapModel` says "here is what the crate does with dangling paths", `PrunedModel` says "these operations never create one", and a trace divergence -is either a wrong value or a dangling path that should not be there. The -fuzzer that checks this claim against the crate (`PrunedModel/Fuzz.lean`, -`differential/src/pruned.rs`) lives on branch `spec/zippy-laws-fvc` and is not -carried here; "the fuzzer" in these files means that one. On this branch the -model is what `PrunedModel/Zippy.lean` proves Zippy's set algebra about. +is either a wrong value or a dangling path that should not be there. See +`PrunedModel/Fuzz.lean` for which operations are in the subset and why. ## What is shared diff --git a/lean/PrunedModel/Write.lean b/lean/PrunedModel/Write.lean index 8df46f17..758dfbed 100644 --- a/lean/PrunedModel/Write.lean +++ b/lean/PrunedModel/Write.lean @@ -396,6 +396,12 @@ def joinKPathInto (k : Nat) : Bool × PZip V := let r := PrunedMap.dropHead ops z.makeMap k (!r.isEmptyMap, if k == 0 then z else z.graftMap r) +/-- `meet_k_path_into` is **not implementable** for these arguments: its +provisional implementation drives `descend_first_k_path` through the +`ZipperIteration` *default* loop, which spins forever when the focus has no +children, and which escapes the focus's subtree entirely when `k = 0`. -/ +def meetKPathUnspecified (k : Nat) : Bool := k == 0 || z.childCount == 0 + /-- One step of `meet_k_path_into`: meet in the subtrie at `f ++ q`. -/ def meetStep (t : PrunedMap V) (f : Path) (acc : Option (PrunedMap V)) (q : Path) : Option (PrunedMap V) := @@ -408,8 +414,8 @@ path below the focus and meet the results. Values at depth exactly `k` become the focus value. The meet replaces the whole subtrie, focus value included: an empty meet is `remove_subtrie`, which is -grafting the empty map. With `k = 0` the only subtrie is the focus's own, so -it is the identity; a focus with no children meets nothing and is emptied. -/ +grafting the empty map. Only meaningful when `meetKPathUnspecified` is +`false`. -/ def meetKPathInto (k : Nat) : Bool × PZip V := let kps := (z.trie.subtrie z.focus).kPaths k let result : Option (PrunedMap V) := kps.foldl (meetStep ops z.trie z.focus) none diff --git a/lean/README.md b/lean/README.md index 1a0c719b..447bd2d5 100644 --- a/lean/README.md +++ b/lean/README.md @@ -165,9 +165,24 @@ zipper, and exporting those laws to the algebraic fuzzer. A location exists iff some key has it as a prefix, so a dangling path is unrepresentable. The model follows `focus_value_consistency` (issue #104: a subtrie includes its root value), which master's crate does not implement yet; the laws are about the -model's zipper programs, and the fuzzer builds each operator from crate -operations that agree on master. The pruned differential fuzzer that checks -this model against the crate lives on branch `spec/zippy-laws-fvc`. +model's zipper programs, and the algebraic fuzzer builds each operator from +crate operations that agree on master. + +`pruned_differential.py` drives this model (`pruned-oracle`) against +`differential/src/pruned.rs` (`pruned_trace`), with the same resident-child +driver as `differential.py`: + + cargo build --release -p differential --bin pruned_trace + (cd lean && lake build) + ./lean/pruned_differential.py --random 2000 -j8 + ./lean/pruned_differential.py lean/pruned-corpus/* + +What it found is in `PRUNED_FINDINGS.md`. Until `focus_value_consistency` +lands, it reports the #104 gaps on master as new divergences: `remove_prefix` +(the model returns a count), and the focus value of `insert_prefix`, +`join_into`, `meet_2`, `join_k_path_into`, `restrict` and `meet_k_path_into`. +In 20000 random inputs on `de125bb`, 13721 diverged, all of them in those +seven operations except one in `subtract_into`. | file | contents | | --- | --- | @@ -179,6 +194,7 @@ this model against the crate lives on branch `spec/zippy-laws-fvc`. | `PrunedModel/Pointwise.lean` | `valAt` of every map operation | | `PrunedModel/Refine.lean` | each write op as `z.withTrie (z.trie.replaceAt z.focus M)` | | `PrunedModel/Zippy.lean` | each egg operator as a zipper program over `Space = PrunedMap Unit`, every `formal.egg` rule proved, `Fix` as a least post-fixpoint, the raw ops = egg ops under #104 (§10), the tour as `#guard`s | +| `PrunedModel/Fuzz.lean`, `PrunedMain.lean` | the pruned fuzzer's wire format, op table and trace producer; the `pruned-oracle` binary | | `ZippyLaws.lean` | exports Zippy.lean's equational theorems as `differential/src/algebraic/zippy_laws.rs`: `lake build PrunedModel && lake env lean --run ZippyLaws.lean > ../differential/src/algebraic/zippy_laws.rs` | ## What is proved versus what is checked diff --git a/lean/lakefile.toml b/lean/lakefile.toml index 167a22c5..6f773634 100644 --- a/lean/lakefile.toml +++ b/lean/lakefile.toml @@ -1,5 +1,5 @@ name = "pathmap-model" -defaultTargets = ["PathMapModel", "pathmap-oracle", "PrunedModel"] +defaultTargets = ["PathMapModel", "pathmap-oracle", "PrunedModel", "pruned-oracle"] [[lean_lib]] name = "PathMapModel" @@ -8,8 +8,15 @@ name = "PathMapModel" name = "pathmap-oracle" root = "Main" -# The dangling-path-free model, carried here for Zippy's set algebra: a space -# is a `PrunedMap Unit`, and `PrunedModel/Zippy.lean` proves formal.egg's rules -# about it. `ZippyLaws.lean` exports those laws for the algebraic fuzzer. +# The dangling-path-free model: a second, independent specification covering +# only the subset of the API that cannot leave a dangling path (see +# PrunedModel/Map.lean), driven by pruned_differential.py. A space in Zippy's +# set algebra is a `PrunedMap Unit`, and `PrunedModel/Zippy.lean` proves +# formal.egg's rules about it; `ZippyLaws.lean` exports those laws for the +# algebraic fuzzer. [[lean_lib]] name = "PrunedModel" + +[[lean_exe]] +name = "pruned-oracle" +root = "PrunedMain" diff --git a/lean/pruned-corpus/graft-empty-src-creates-dangling-focus.bin b/lean/pruned-corpus/graft-empty-src-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..0deb53476eda8fec387d610211bfe8b1d6cd61d4 GIT binary patch literal 9 OcmZQ%WB`J_3@QKubpYf5 literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/graft_masked_branches-creates-dangling-child.bin b/lean/pruned-corpus/graft_masked_branches-creates-dangling-child.bin new file mode 100644 index 0000000000000000000000000000000000000000..17c6e393a13b2ecf54b171aa717ce3d1d10f5126 GIT binary patch literal 10 PcmZQ%WMp7qxCSHv1A+kD literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/graft_masked_branches-creates-dangling-focus.bin b/lean/pruned-corpus/graft_masked_branches-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..eefd1db7b0b499c672fcf25b6f85ac5b81b2f1ee GIT binary patch literal 12 QcmZRyV*r8W3=0?-0SD#*hyVZp literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/graft_src_at-empty-src-creates-dangling-focus.bin b/lean/pruned-corpus/graft_src_at-empty-src-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..a70093f9423f917f388d429deff3e56fee77f2ce GIT binary patch literal 10 RcmZQzU|?im$YA)(000B40cQXJ literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/join_into-value-bias-by-node-layout.bin b/lean/pruned-corpus/join_into-value-bias-by-node-layout.bin new file mode 100644 index 0000000000000000000000000000000000000000..c5f233fe3dc0dc1c216e86ab8166c51b7c816cb1 GIT binary patch literal 47 mcmZQ)WPk%!2qn&{sRD4+y?ys literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/join_map_into-status-element-when-unchanged.bin b/lean/pruned-corpus/join_map_into-status-element-when-unchanged.bin new file mode 100644 index 0000000000000000000000000000000000000000..de1bdd748870fea9f45242bdd054ea6ff97c2a72 GIT binary patch literal 9 OcmZQ%WMBXyhW`Ko9svUY literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/meet_2-empty-result-creates-dangling-focus.bin b/lean/pruned-corpus/meet_2-empty-result-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..8f777b0b29a641166f58ac2499a7d8838a9ce3f1 GIT binary patch literal 12 PcmZQ9WdMVF45kbK2>}6$ literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/remove_prefix-creates-dangling-chain.bin b/lean/pruned-corpus/remove_prefix-creates-dangling-chain.bin new file mode 100644 index 0000000000000000000000000000000000000000..294bb6d290944fdfb4a3afbbd9ff1878b9eec361 GIT binary patch literal 14 RcmZQz0D=o3;wpn4BLE8z0o4Ei literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/restrict-empty-result-creates-dangling-focus.bin b/lean/pruned-corpus/restrict-empty-result-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..1b5b012113e38a25a5c3b686d74dad23629e5811 GIT binary patch literal 12 QcmYddV31+}fx8R|00@Nvx&QzG literal 0 HcmV?d00001 diff --git a/lean/pruned-corpus/restricting-creates-dangling-focus.bin b/lean/pruned-corpus/restricting-creates-dangling-focus.bin new file mode 100644 index 0000000000000000000000000000000000000000..04ba1ff26796c581778ea14e19cbbc5300500839 GIT binary patch literal 22 Wcmcc300d1Sf?*N^10#?EVr>8-2Lc@c literal 0 HcmV?d00001 diff --git a/lean/pruned_differential.py b/lean/pruned_differential.py new file mode 100755 index 00000000..fa9dbcb0 --- /dev/null +++ b/lean/pruned_differential.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Differential runner for the dangling-path-free subset. + +Same driver as `differential.py` -- resident children, parallel workers, +timeouts, shrinkable failures -- pointed at the other model/harness pair: + + lean/.lake/build/bin/pruned-oracle PrunedModel (the oracle) + target/*/pruned_trace the real crate + + ./lean/pruned_differential.py --random 2000 -j8 + ./lean/pruned_differential.py pruned-corpus/* + +Everything about *how* inputs are run is inherited rather than copied: there is +one implementation of the resident-child protocol, the restart-on-wedge logic +and the input sourcing, and this file only says which binaries to run and which +divergences are already understood. `differential.py` reads `ORACLE`, +`TRACE_CANDIDATES` and `KNOWN` at call time, which is what makes that possible. + +## Why the KNOWN table starts almost empty + +`differential.py`'s table is large because its model reproduces `pathmap`'s +dangling-path behaviour, so the divergences left over are the subtle ones. This +model instead *forbids* dangling paths, so the first divergences it reports are +the operations that leak one -- which are the point, not noise. An entry gets +added here only once the leak is recorded in FINDINGS.md, so a new one cannot +hide behind it. +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import re + +import differential as D + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +D.ORACLE = os.path.join(ROOT, "lean", ".lake", "build", "bin", "pruned-oracle") +# PRUNED_TRACE overrides the search, for builds that live in another target dir. +D.TRACE_CANDIDATES = [os.environ.get("PRUNED_TRACE", "")] + [ + os.path.join(ROOT, "target", "release", "pruned_trace"), + os.path.join(ROOT, "target", "debug", "pruned_trace"), +] + +def _fields(line): + """The trace line's tokens, keyed by field name, per zipper. + + `0 graft ret=- W=01 o01 e1 v- c0 n0 f01 R=...` -> the W and R groups as + dicts, so a divergence can be asked which field moved. + """ + out = {} + for side in ("W", "R"): + m = re.search(r" %s=(\S+(?: \S+)*?)(?= [WR]=|$)" % side, line) + if not m: + return None + out[side] = { + (re.match(r"[A-Za-z]*", t).group(0) or t): t[len(re.match(r"[A-Za-z]*", t).group(0)):] + for t in m.group(1).split() + } + return out + + +def dangling_focus(a, b): + """The crate has locations the model does not, and none of them holds a value. + + The signature is that `e` and/or `c` moved *up* while `v` and `n` did not + move at all: `path_exists` became true, or `child_mask` gained a bit, without + a value appearing anywhere at or below the focus. So whatever the crate + created or kept leads nowhere. Both halves of + PRUNED_FINDINGS.md #1 and #2 land here -- the focus itself (`e0` -> `e1`) and + a child of it (`c0` -> `c1`), which is why the two are one entry in `KNOWN`. + + The operations that do this are the ones with no `prune` parameter to pass: + `graft`, `graft_src_at`, `graft_masked_branches`, `meet_2`, `restrict`, + `restricting`, `remove_prefix`. The ones that have one (`remove_val`, + `remove_branches`, `meet_into`, `subtract_into`) clean up correctly when it + is set, which is what this harness passes throughout. + """ + fa, fb = _fields(a), _fields(b) + if not fa or not fb: + return None + hit = False + for side in ("W", "R"): + xa, xb = fa[side], fb[side] + if xa == xb: + continue + moved = {k for k in set(xa) | set(xb) if xa.get(k) != xb.get(k)} + if not moved or not moved <= {"e", "c"}: + return None + # No value may appear: `v` at the focus and `n` below it must be equal, + # or the difference is content rather than an empty location. + if xa["v"] != xb["v"] or xa["n"] != xb["n"]: + return None + if "e" in moved and not (xa["e"] == "0" and xb["e"] == "1"): + return None + if "c" in moved and not int(xb["c"]) > int(xa["c"]): + return None + hit = True + return "DANGLING-FOCUS" if hit else None + + +def dangling_kept_dump(a, b): + """The crate's dump holds locations the model's does not, all valueless. + + The same defect seen in a trie dump rather than in a fingerprint: the model's + entries are a subsequence of the crate's, and every entry only the crate has + renders `-`. Nothing leads to those locations, so they are dangling paths + the operation declined to reclaim. + """ + ta, tb = a.split(), b.split() + if len(ta) != len(tb) or len(ta) < 2: + return None + if ta[0] != tb[0] or not (ta[0].startswith("MAP") or ta[1] == "dump"): + return None + sa, sb = ta[-1], tb[-1] + ea = [e for e in sa.split(",") if e] + eb = [e for e in sb.split(",") if e] + if len(eb) <= len(ea): + return None + # Is `ea` a subsequence of `eb`, and is every skipped entry valueless? + i, extra = 0, [] + for e in eb: + if i < len(ea) and e == ea[i]: + i += 1 + else: + extra.append(e) + if i != len(ea) or not extra: + return None + if any(not e.endswith(":-") for e in extra): + return None + return "DANGLING-DUMP" + + +_inherited_shape = D.divergence_shape + + +def divergence_shape(a, b): + """This model's shapes first, then the ones `differential.py` knows. + + Its shapes are about a model that *reproduces* dangling paths, so they + cannot name the class this one exists to report; they stay in place for + everything else. + """ + return dangling_focus(a, b) or dangling_kept_dump(a, b) or _inherited_shape(a, b) + + +D.divergence_shape = divergence_shape + +# Keyed on a substring of the divergence report, newest-understood first; see +# `differential.classify`. Each entry must name the operation *and* the +# finding, so that reading a `known` line tells you what was already decided. +D.KNOWN = [ + (["ESCAPED-ROOT"], + "a zipper left its own root: root_prefix_path() changed [root_escape]"), + # The trie-dump form, tested before the fingerprint form: a line that is + # only a dump has no fingerprint to read. + (["DANGLING-DUMP"], + "an empty write leaves locations that lead nowhere in the trie " + "(PRUNED_FINDINGS.md #1) [empty_write_materialises_focus]"), + # PRUNED_FINDINGS.md #1 and #2 -- one mechanism, seen at the focus (#1) or at + # a child of it (#2). Still present on fuzz-fixes-v3. + (["DANGLING-FOCUS"], + "an operation with no prune parameter materialises an empty location " + "(PRUNED_FINDINGS.md #1, #2) [empty_write_materialises_focus]"), + # The two classes this model shares with the other one. Both are live on + # master; `fuzz-fixes-v3` carries a fix for the value-bias one (3dae731). + # + # The STATUS-ONLY shape is two-directional and the direction is what names + # it, so read the report rather than the tag. `Identity` from the model + # against `Element` from the crate is the FINDINGS.md #8 imprecision in + # `subtract_into` and `meet_into`. The reverse direction appears only against + # fuzz-fixes-v3, whose `u64::psubtract` (f8a4599) returns Identity where + # `Basic.u64Ops` still says Element. + (["STATUS-ONLY"], + "AlgebraicStatus::Identity is not returned reliably when nothing changed, " + "in subtract_into/meet_into (FINDINGS.md #8)"), + (["VALUE-ONLY"], + "a value collision resolves to the counterpart, by node layout rather than " + "by path (FINDINGS.md value bias); fuzz-fixes-v3 fixes it with 3dae731"), +] + +if __name__ == "__main__": + if "--act" in sys.argv: + sys.exit("--act is meaningless here: there is one read source") + D.main() From 9e5348f499af5c4c1b66bd3267a92db85a751439 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 17 Nov 2026 20:56:33 +0000 Subject: [PATCH 16/17] pruned fuzzer: give inputs a versioned wire header The pruned harness decoded every input header-less, but differential.py puts the main harness's header (PMFUZZ + selector count) in front of every random input. So the pruned decoder read those 10 bytes as seed data, and every random input started with an empty write map and the same read-side entries. Saved failures also got the main harness's header, with count 56, which this harness does not use. Use the main layout with its own marker: "PMPRUN\x01\x00", then a little-endian u16 selector count (1..=256), then the program. An input with no header decodes with 54 selectors, as before, so pruned-corpus keeps its meaning. Rust and Lean both read it: harness::Dec gains with_format(magic, legacy_ops), which replaces Dec::legacy, and PrunedModel.Fuzz gains Dec.init and an opCount. input_format.py gets pruned_input_header/pruned_versioned_input, and pruned_differential.py installs them into differential.py, so generated inputs and saved failures carry the pruned header. 20000 random inputs: the corpus results are unchanged, Rust and Lean agree on the header, and known-bug hits go from 2117 to 2770 now that the seed maps vary. --- differential/src/harness.rs | 19 ++++----- differential/src/pruned.rs | 78 +++++++++++++++++++++++++++++++++++-- lean/PrunedModel/Fuzz.lean | 33 +++++++++++++--- lean/README.md | 7 ++++ lean/input_format.py | 33 ++++++++++++---- lean/pruned_differential.py | 6 +++ lean/test_input_format.py | 28 +++++++++++++ 7 files changed, 179 insertions(+), 25 deletions(-) diff --git a/differential/src/harness.rs b/differential/src/harness.rs index e581ee85..0a5aa95e 100644 --- a/differential/src/harness.rs +++ b/differential/src/harness.rs @@ -52,21 +52,22 @@ pub struct Dec<'a> { impl<'a> Dec<'a> { pub fn new(bytes: &'a [u8]) -> Option { - let (pos, op_count) = if bytes.starts_with(WIRE_MAGIC) { - let count_bytes = bytes.get(WIRE_MAGIC.len()..WIRE_MAGIC.len() + 2)?; + Self::with_format(bytes, WIRE_MAGIC, LEGACY_NOPS) + } + /// Decode an input in this wire format with another marker and op table: + /// `magic`, then a little-endian u16 selector count (1..=256), or no header + /// at all, which selects among `legacy_ops`. The pruned fuzzer uses it. + pub fn with_format(bytes: &'a [u8], magic: &[u8], legacy_ops: usize) -> Option { + let (pos, op_count) = if bytes.starts_with(magic) { + let count_bytes = bytes.get(magic.len()..magic.len() + 2)?; let count = u16::from_le_bytes([count_bytes[0], count_bytes[1]]) as usize; if !(1..=256).contains(&count) { return None; } - (WIRE_MAGIC.len() + 2, count) + (magic.len() + 2, count) } else { - (0, LEGACY_NOPS) + (0, legacy_ops) }; Some(Self { bytes, pos, op_count }) } - /// A decoder with no header handling, for streams whose caller picks the - /// operation itself (the pruned fuzzer). - pub fn legacy(bytes: &'a [u8]) -> Self { - Self { bytes, pos: 0, op_count: LEGACY_NOPS } - } pub fn op(&mut self) -> Option { self.modn(self.op_count) } diff --git a/differential/src/pruned.rs b/differential/src/pruned.rs index 9332b12b..820f239f 100644 --- a/differential/src/pruned.rs +++ b/differential/src/pruned.rs @@ -40,8 +40,26 @@ use crate::harness::{ use core::fmt::Write as _; -/// Number of distinct operations. Must match `PrunedModel.Fuzz.nops`. +/// Selector count for newly generated inputs. Must match +/// `PrunedModel.Fuzz.nops` and `PRUNED_NOPS` in `lean/input_format.py`. Keep +/// operation IDs permanently assigned: an input decodes with the count its +/// header records, never with this one. pub const NOPS: usize = 54; +/// Selector count for inputs with no header -- every input written before the +/// header existed, including `lean/pruned-corpus/`. +pub const LEGACY_NOPS: usize = 54; +/// Input header marker, followed by a little-endian u16 selector count +/// (1..=256): the layout of [`crate::harness::WIRE_MAGIC`], with its own marker +/// so an input for one harness cannot pass as a program for the other. +/// Must match `PrunedModel.Fuzz.prunedMagic`. +pub const PRUNED_MAGIC: &[u8] = b"PMPRUN\x01\x00"; + +/// Header for new inputs. +pub fn input_header() -> Vec { + let mut header = PRUNED_MAGIC.to_vec(); + header.extend_from_slice(&(NOPS as u16).to_le_bytes()); + header +} /// Why an operation was skipped. Every `skip` in the trace carries one of /// these. `lean/PrunedModel/Fuzz.lean` emits the same tokens; the two must @@ -157,7 +175,9 @@ pub fn decode_header(d: &mut Dec) -> Option<(PathMap, PathMap, Vec /// Decode and execute a fuzzer input. pub fn run(bytes: &[u8], check: bool) -> String { - let mut d = Dec::legacy(bytes); + let Some(mut d) = Dec::with_format(bytes, PRUNED_MAGIC, LEGACY_NOPS) else { + return "EMPTY\n".to_string(); + }; let (mut map0, map1, root1) = match decode_header(&mut d) { Some(x) => x, None => return "EMPTY\n".to_string(), @@ -225,7 +245,7 @@ pub fn run_ops( if step >= MAX_STEPS { break; } - let op = get!(d.u8()) as usize % NOPS; + let op = get!(d.op()); let (name, ret): (&str, String) = match op { // ## Movement and reading, on either zipper 0 => { @@ -605,3 +625,55 @@ pub fn run_ops( step += 1; } } + +#[cfg(test)] +mod input_format_tests { + use super::*; + + fn payload() -> Vec { + // Two seeded maps, a read root, then a run of every operation. + let mut p = vec![3, 2, 0, 1, 10, 1, 2, 11, 3, 0, 1, 2, 12, 2, 1, 1, 20, 1, 3, 21, 1, 1]; + for op in 0..NOPS as u8 { + p.extend_from_slice(&[op, 1, 2, 1, 0]); + } + p + } + + // `check` is off: these are about decoding, and the payload is free to hit + // a known leak (PRUNED_FINDINGS.md #1) that `--check` asserts against. + + #[test] + fn headerless_inputs_decode_as_the_current_header() { + assert_eq!(LEGACY_NOPS, NOPS, "a new op needs a legacy count of its own"); + let p = payload(); + let mut h = input_header(); + h.extend_from_slice(&p); + assert_eq!(run(&h, false), run(&p, false)); + } + + #[test] + fn header_count_controls_decoding() { + let p = payload(); + for count in [1u16, 7, 53, 54, 200, 256] { + let mut h = PRUNED_MAGIC.to_vec(); + h.extend_from_slice(&count.to_le_bytes()); + h.extend_from_slice(&p); + let trace = run(&h, false); + assert!(trace.contains("MAP0"), "count {count}: {trace}"); + if count == 1 { + // Selector 0 only: every op is descend_to. + assert!(trace.lines().filter(|l| l.contains(" ret=")).all(|l| l.contains(" descend_to ")), "{trace}"); + } + } + for count in [0u16, 257] { + let mut h = PRUNED_MAGIC.to_vec(); + h.extend_from_slice(&count.to_le_bytes()); + h.extend_from_slice(&p); + assert_eq!(run(&h, false), "EMPTY\n"); + } + // The main harness's header is not this one: read as a legacy payload. + let mut other = crate::harness::input_header(); + other.extend_from_slice(&p); + assert_ne!(run(&other, false), run(&p, false)); + } +} diff --git a/lean/PrunedModel/Fuzz.lean b/lean/PrunedModel/Fuzz.lean index 04edeb6d..8d8ef6cf 100644 --- a/lean/PrunedModel/Fuzz.lean +++ b/lean/PrunedModel/Fuzz.lean @@ -49,6 +49,10 @@ The input is consumed one byte at a time; decoding stops, and the program ends, as soon as the input runs out. ``` +wire header (optional): + "PMPRUN" 0x01 0x00 ; count := u16 LE (1..=256) + -- the main harness's layout with its own marker; an input without it + -- decodes with 54 selectors, so pre-header inputs keep their meaning header: n := u8 % 8 -- entries seeded into map0 (the write target) n × ( len := u8 % 6 ; len × pathbyte ; val := u8 ) @@ -57,7 +61,7 @@ header: r1 := u8 % 4 ; r1 × pathbyte -- read zipper root, clamped to its -- longest existing prefix body: - repeated: op := u8 % 54 ; operands per op (see `step`) + repeated: op := u8 % count ; operands per op (see `step`) ``` Every **path byte** is masked to `b % 4`, so generated tries share prefixes @@ -153,6 +157,8 @@ def dumpAt (t : PrunedMap V) (root : Path) : String := structure Dec where bytes : ByteArray pos : Nat + /-- Selector count, from the wire header (54 without one). -/ + opCount : Nat := 54 /-- Read one byte; `none` once the input is exhausted, which ends the program. -/ def Dec.u8 (d : Dec) : Option (UInt8 × Dec) := @@ -213,14 +219,31 @@ def emit (s : St) (name : String) (ret : String) : St := /-! ## The operation table -`op % nops` selects the operation. Ops `0`–`29` act on a target zipper chosen -by a following `u8 % 2` byte (`0` = write zipper, `1` = read zipper); ops +`op % count` selects the operation, `count` coming from the wire header (`nops` +without one). Ops `0`–`29` act on a target zipper chosen by a following +`u8 % 2` byte (`0` = write zipper, `1` = read zipper); ops `30`–`53` are write-zipper operations. -/ /-- Number of distinct operations. Must match `NOPS` in `differential/src/pruned.rs`. -/ def nops : Nat := 54 +/-- Input header marker, `"PMPRUN\x01\x00"`. Must match `PRUNED_MAGIC` in +`differential/src/pruned.rs`. -/ +def prunedMagic : List UInt8 := [80, 77, 80, 82, 85, 78, 1, 0] + +/-- Read the optional wire header. `none` for a selector count outside +`1..=256`, which the crate also rejects. -/ +def Dec.init (bytes : ByteArray) : Option Dec := do + if bytes.data.toList.take prunedMagic.length == prunedMagic then + let d : Dec := { bytes, pos := prunedMagic.length } + let (lo, d) ← d.u8 + let (hi, d) ← d.u8 + let count := lo.toNat + 256 * hi.toNat + if count == 0 || count > 256 then none + else some { d with opCount := count } + else some { bytes, pos := 0, opCount := nops } + /-- A full `k`-path iteration: `descend_first_k_path` followed by `to_next_k_path` until it runs out (capped at 32 stops). Returns the locations visited. This is the only well-defined way to use the `k`-path primitives: @@ -253,7 +276,7 @@ def getTarget (s : St) (t : Nat) : PZip V := if t == 0 then s.wz else s.rz which ends the program. -/ def step (s : St) (d : Dec) : Option (St × Dec) := do let (opRaw, d) ← d.u8 - let op := opRaw.toNat % nops + let op := opRaw.toNat % d.opCount match op with -- ## Movement and reading, on either zipper | 0 => do let (t, d) ← d.mod 2; let (p, d) ← d.path @@ -536,7 +559,7 @@ def header (d : Dec) : Option (St × Dec) := do /-- Decode and run a fuzzer input, returning the trace lines. -/ def run (bytes : ByteArray) (maxSteps : Nat := 256) : List String := - match header { bytes, pos := 0 } with + match Dec.init bytes >>= header with | none => ["EMPTY"] | some (s0, d) => let s := loop maxSteps s0 d diff --git a/lean/README.md b/lean/README.md index 447bd2d5..9e490890 100644 --- a/lean/README.md +++ b/lean/README.md @@ -177,6 +177,13 @@ driver as `differential.py`: ./lean/pruned_differential.py --random 2000 -j8 ./lean/pruned_differential.py lean/pruned-corpus/* +Inputs use the main harness's wire layout with their own marker: +`"PMPRUN" 0x01 0x00`, a little-endian u16 selector count, then the program +(`pruned_input_header` in `input_format.py`). An input without the header, +such as everything in `pruned-corpus/`, decodes with 54 selectors, as it did +before the header existed. The driver writes generated inputs and saved failures +with this header, never with the main harness's. + What it found is in `PRUNED_FINDINGS.md`. Until `focus_value_consistency` lands, it reports the #104 gaps on master as new divergences: `remove_prefix` (the model returns a count), and the focus value of `insert_prefix`, diff --git a/lean/input_format.py b/lean/input_format.py index 3333335f..2684d338 100644 --- a/lean/input_format.py +++ b/lean/input_format.py @@ -7,17 +7,34 @@ HEADER_SIZE = len(WIRE_MAGIC) + 2 -def input_header(count=NOPS): +def input_header(count=NOPS, magic=WIRE_MAGIC): if not 1 <= count <= 256: raise ValueError("invalid fuzzer selector count") - return WIRE_MAGIC + count.to_bytes(2, "little") + return magic + count.to_bytes(2, "little") -def versioned_input(blob): +def versioned_input(blob, magic=WIRE_MAGIC, legacy=LEGACY_NOPS): """Use the latest header while preserving the input's operation decoding.""" - if blob.startswith(WIRE_MAGIC): - if len(blob) < HEADER_SIZE: + size = len(magic) + 2 + if blob.startswith(magic): + if len(blob) < size: raise ValueError("truncated fuzzer input header") - count = int.from_bytes(blob[len(WIRE_MAGIC):HEADER_SIZE], "little") - return input_header(count) + blob[HEADER_SIZE:] - return input_header(LEGACY_NOPS) + blob + count = int.from_bytes(blob[len(magic):size], "little") + return input_header(count, magic) + blob[size:] + return input_header(legacy, magic) + blob + + +# The pruned harness (differential/src/pruned.rs, PrunedModel/Fuzz.lean): the +# same layout with its own marker and operation table. +PRUNED_MAGIC = b"PMPRUN\x01\x00" +PRUNED_LEGACY_NOPS = 54 +# Keep in sync with NOPS in differential/src/pruned.rs. +PRUNED_NOPS = 54 + + +def pruned_input_header(count=PRUNED_NOPS): + return input_header(count, PRUNED_MAGIC) + + +def pruned_versioned_input(blob): + return versioned_input(blob, PRUNED_MAGIC, PRUNED_LEGACY_NOPS) diff --git a/lean/pruned_differential.py b/lean/pruned_differential.py index fa9dbcb0..189935ee 100755 --- a/lean/pruned_differential.py +++ b/lean/pruned_differential.py @@ -33,10 +33,16 @@ import re import differential as D +from input_format import pruned_input_header, pruned_versioned_input ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) D.ORACLE = os.path.join(ROOT, "lean", ".lake", "build", "bin", "pruned-oracle") +# This harness has its own wire header (PRUNED_MAGIC + its selector count), so +# generated inputs carry it and saved failures are rewritten into it, never +# into the main harness's. `differential.py` looks both names up at call time. +D.input_header = lambda *_args, **_kw: pruned_input_header() +D.versioned_input = pruned_versioned_input # PRUNED_TRACE overrides the search, for builds that live in another target dir. D.TRACE_CANDIDATES = [os.environ.get("PRUNED_TRACE", "")] + [ os.path.join(ROOT, "target", "release", "pruned_trace"), diff --git a/lean/test_input_format.py b/lean/test_input_format.py index 300f55ab..9939c44f 100644 --- a/lean/test_input_format.py +++ b/lean/test_input_format.py @@ -52,5 +52,33 @@ def signature(blob): self.assertEqual(sig, "DIFF remove_subtrie") +class PrunedInputFormatTests(unittest.TestCase): + """The pruned harness's header: same layout, its own marker and table.""" + + def test_pruned_count_matches_rust(self): + from input_format import PRUNED_LEGACY_NOPS, PRUNED_NOPS + pruned = pathlib.Path(__file__).resolve().parents[1] / "differential/src/pruned.rs" + text = pruned.read_text() + self.assertEqual(PRUNED_NOPS, int(re.search(r"pub const NOPS: usize = (\d+);", text)[1])) + self.assertEqual(PRUNED_LEGACY_NOPS, + int(re.search(r"pub const LEGACY_NOPS: usize = (\d+);", text)[1])) + + def test_pruned_driver_generates_and_saves_pruned_headers(self): + import pruned_differential # noqa: F401 -- installs the pruned format + import differential as D + from input_format import PRUNED_MAGIC, pruned_input_header + try: + source = D.RandomInputs(7, 5, 300) + for i in range(len(source)): + self.assertTrue(source.get(i).startswith(pruned_input_header())) + self.assertEqual(D.versioned_input(b"\x01\x02"), pruned_input_header() + b"\x01\x02") + blob = PRUNED_MAGIC + (7).to_bytes(2, "little") + b"\x09" + self.assertEqual(D.versioned_input(blob), blob) + finally: + # Other tests in this process use the main harness's format. + import importlib + importlib.reload(D) + + if __name__ == "__main__": unittest.main() From 86603c8cff792863cd17f216351ed563de787b9e Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 17 Nov 2026 20:56:33 +0000 Subject: [PATCH 17/17] alg_fuzz: give inputs a versioned wire header Use the same layout as the other two harnesses with alg_fuzz's own marker: "PMALGZ\x01\x00", then a little-endian u16, then the bytes decode reads. The u16 is a layout version (1), not a selector count: this decoder has no single op table, so the version records which decoding the payload was written for. The header is optional. A header-less input is layout 1, so old inputs decode unchanged, and a cut-short header decodes as an empty payload. Rng::input puts the header in front of the same random stream, so seeds still name the same cases. --shrink reduces only the payload and writes the result with a header; a header-less input and its headered form shrink to the same bytes. --- differential/ALGEBRAIC_FUZZING.md | 21 ++++++++++++ differential/src/algebraic.rs | 56 +++++++++++++++++++++++++++---- differential/src/bin/alg_fuzz.rs | 12 +++++-- differential/tests/algebraic.rs | 36 ++++++++++++++++++++ 4 files changed, 117 insertions(+), 8 deletions(-) diff --git a/differential/ALGEBRAIC_FUZZING.md b/differential/ALGEBRAIC_FUZZING.md index f2340c95..36a2b6bd 100644 --- a/differential/ALGEBRAIC_FUZZING.md +++ b/differential/ALGEBRAIC_FUZZING.md @@ -311,6 +311,27 @@ nodes are laid out differently, and the value-loss defect needs operands that share nodes — it disappears if `b`'s entries are rebuilt into a fresh map instead of cloned. A generator that only wrote fresh tries would find neither. +### Input format + +An input is the wire header, then the bytes `decode` reads: + + "PMALGZ" 0x01 0x00 ; layout := u16 LE ; payload + +It is laid out like the main harness's (`harness::WIRE_MAGIC`, then a selector +count) and the pruned harness's (`PMPRUN`, then its count), with this fuzzer's +own marker. Where those two record how many operations their table had, this +records a *layout version* (`algebraic::LAYOUT`, now 1): its decoding has no +single table, so it is the version that says which decoding the payload was +written for. Bump it, and keep the old decoding reachable, when a change to +`decode` would give an existing input a different case. + +The header is optional. An input without one is layout 1, so every input written +before it existed decodes as it did; a cut-short header decodes as an empty +payload. `Rng::input` writes the header in front of the same random stream as +before, so a seed still names the same cases. `--shrink` reduces only the +payload and writes the result with a header, so a legacy input comes out +headered and decodes the same way. + ## Divergence classes | class | meaning | fails a run | diff --git a/differential/src/algebraic.rs b/differential/src/algebraic.rs index 2a756090..b4512b47 100644 --- a/differential/src/algebraic.rs +++ b/differential/src/algebraic.rs @@ -54,13 +54,48 @@ pub const MAX_ENTRIES: usize = 7; /// Upper bound on a generated path's length. pub const MAX_PATH_LEN: usize = 5; +/// Input header marker, followed by a little-endian u16 layout version: the +/// layout of [`crate::harness::WIRE_MAGIC`], with this fuzzer's own marker. +/// +/// The main harness records a *selector count* there, because its decoding is +/// one table that only grows. This decoder has no such table -- operators, +/// builds and law instances are drawn with hand-set weights -- so the field +/// records which decoding the bytes after it were written for. +pub const ALG_MAGIC: &[u8] = b"PMALGZ\x01\x00"; +/// Layout version of newly generated inputs. Bump it, and keep the old +/// decoding reachable, when a change to [`decode`] would give an existing +/// input a different case. +pub const LAYOUT: u16 = 1; +/// Layout of an input with no header: every input written before the header +/// existed. It is the layout [`LAYOUT`] 1 decodes. +pub const LEGACY_LAYOUT: u16 = 1; + +/// Header for new inputs. +pub fn input_header() -> Vec { + let mut h = ALG_MAGIC.to_vec(); + h.extend_from_slice(&LAYOUT.to_le_bytes()); + h +} + +/// Split an input into its layout version and the bytes [`decode`] reads. +/// +/// Total, like `decode`: a header whose version is cut short reads as layout +/// [`LAYOUT`] with nothing after it. +pub fn split_input(bytes: &[u8]) -> (u16, &[u8]) { + match bytes.strip_prefix(ALG_MAGIC) { + None => (LEGACY_LAYOUT, bytes), + Some(rest) if rest.len() < 2 => (LAYOUT, &[]), + Some(rest) => (u16::from_le_bytes([rest[0], rest[1]]), &rest[2..]), + } +} + /// Byte decoding with the out-of-input behaviour this fuzzer wants. /// /// Not `harness::Dec`: that one returns `None` when the input runs out, because -/// the Lean harness stops executing there, and it reads a wire header this -/// format does not have. Here every input has to decode to *some* case or -/// shrinking would have to care about length, so exhaustion saturates to zero -/// instead. +/// the Lean harness stops executing there. Here every input has to decode to +/// *some* case or shrinking would have to care about length, so exhaustion +/// saturates to zero instead. The header is read the same way, though: see +/// [`ALG_MAGIC`]. pub struct Gen<'a> { bytes: &'a [u8], pos: usize, @@ -70,8 +105,12 @@ pub struct Gen<'a> { } impl<'a> Gen<'a> { + /// A cursor over the input after its header. Layout 1 is the only + /// decoding there is, so the version is not consulted yet; a newer one + /// decodes as layout 1. pub fn new(bytes: &'a [u8]) -> Self { - Gen { bytes, pos: 0, alphabet: 3 } + let (_layout, payload) = split_input(bytes); + Gen { bytes: payload, pos: 0, alphabet: 3 } } pub fn byte(&mut self) -> u8 { let b = self.bytes.get(self.pos).copied().unwrap_or(0); @@ -1137,9 +1176,14 @@ impl Rng { /// An input long enough that the decoder rarely runs out mid-case -- which /// would saturate the rest to zeros and waste the draw -- and short enough /// to shrink quickly. + /// A random input: the current header, then the bytes [`decode`] reads. + /// The bytes after the header are the stream this produced before the + /// header existed, so a seed still names the same cases. pub fn input(&mut self) -> Vec { let n = 48 + (self.next() % 96) as usize; - (0..n).map(|_| (self.next() >> 24) as u8).collect() + let mut v = input_header(); + v.extend((0..n).map(|_| (self.next() >> 24) as u8)); + v } } diff --git a/differential/src/bin/alg_fuzz.rs b/differential/src/bin/alg_fuzz.rs index e5cbb860..49ead1bd 100644 --- a/differential/src/bin/alg_fuzz.rs +++ b/differential/src/bin/alg_fuzz.rs @@ -485,8 +485,15 @@ fn do_shrink(path: &Path, want: Option<&str>) { sigs.join(" ") ); - let holds = |b: &[u8]| signatures(b).iter().any(|s| *s == target); - let mut best = original; + // Only the bytes after the header shrink, and the result is written with + // the header of the layout it was decoded with -- a headerless input comes + // out headered, decoding the same way. + let (layout, payload) = algebraic::split_input(&original); + let mut header = algebraic::ALG_MAGIC.to_vec(); + header.extend_from_slice(&layout.to_le_bytes()); + let framed = |p: &[u8]| [header.as_slice(), p].concat(); + let holds = |b: &[u8]| signatures(&framed(b)).iter().any(|s| *s == target); + let mut best = payload.to_vec(); loop { let before = (best.len(), best.iter().map(|b| *b as u32).sum::()); @@ -526,6 +533,7 @@ fn do_shrink(path: &Path, want: Option<&str>) { } } + let best = framed(&best); let out = path.with_extension("min.bin"); std::fs::write(&out, &best).unwrap(); eprintln!("shrunk to {} bytes -> {}", best.len(), out.display()); diff --git a/differential/tests/algebraic.rs b/differential/tests/algebraic.rs index 179fc36d..866ddfa5 100644 --- a/differential/tests/algebraic.rs +++ b/differential/tests/algebraic.rs @@ -558,3 +558,39 @@ fn zippy_laws_apply_to_the_set_type_only() { assert!(algebraic::laws::laws::().is_empty()); assert!(algebraic::laws::laws::().is_empty()); } + +/// The wire header: optional, and invisible to decoding. A headerless input is +/// layout 1, so it and the same bytes after a header are the same case; random +/// inputs carry the header, and seeds keep naming the cases they did before it. +#[test] +fn input_header_does_not_change_the_case() { + // Building the operands can panic (the known merkleize defect); then both + // forms must panic. Decode under the quiet hook, assert outside it. + let shown = |b: &[u8]| { + std::panic::catch_unwind(|| algebraic::describe(&algebraic::decode::(b))).ok() + }; + let mut rng = algebraic::Rng::for_job(20261117, 0); + let inputs: Vec> = (0..200).map(|_| rng.input()).collect(); + let cut = algebraic::input_header()[..algebraic::ALG_MAGIC.len() + 1].to_vec(); + let (pairs, cut_pair) = with_quiet_panics(|| { + let pairs: Vec<_> = inputs + .iter() + .map(|h| (shown(h), shown(algebraic::split_input(h).1))) + .collect(); + (pairs, (shown(&cut), shown(&[]))) + }); + + for (h, (a, b)) in inputs.iter().zip(&pairs) { + assert!(h.starts_with(&algebraic::input_header())); + assert_eq!(algebraic::split_input(h).0, algebraic::LAYOUT); + assert_eq!(a, b); + } + let decoded = pairs.iter().filter(|(a, _)| a.is_some()).count(); + assert!(decoded > 100, "only {decoded} of 200 cases decoded"); + // A header cut short decodes as an empty payload, not as data. + assert_eq!(algebraic::split_input(&cut), (algebraic::LAYOUT, &[][..])); + assert_eq!(cut_pair.0, cut_pair.1); + // The other harnesses' headers are not this one: they stay payload. + let main = differential::harness::input_header(); + assert_eq!(algebraic::split_input(&main), (algebraic::LEGACY_LAYOUT, &main[..])); +}