From 65f5b14dc7455adc2450a5afa51006c860c0b8dd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:51:06 +0000 Subject: [PATCH 1/8] docs(chart): describe the forest-equality differential in the README The precedence section gains a bullet naming ForestDiff, the V1 side and the candidate, and the tests that show the comparison can fail before the recognizer changes, ahead of the code (live document first). The shared section is rewritten whole by the milestone's docs issue. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/internal/chart/README.md b/internal/chart/README.md index 7d11556cf..2aeb604ac 100644 --- a/internal/chart/README.md +++ b/internal/chart/README.md @@ -2746,6 +2746,32 @@ grammar's tables and its precedence: no Earley item gains a fact. after a scalar is `{PERLY_BRACE_OPEN}` alone. Each constructed input therefore carries set 1626 one or two tokens after a completion (a word, or a glob's `*` and name, between), which the test requires and logs per input. +- **The forest-equality differential** (`forest/equality.go`, the V2 design's + §5). `ForestDiff` compares a candidate's forest with V1's: accept or + refuse, the set of nodes reachable from the root, and each reachable + node's kept alternatives in order. Nodes are matched by what they derive + (symbol, rule position and span), never by index, so a renumbered forest + compares equal and a node unreachable from the root is not compared. The + V1 side (`V1Forest`, `V1ToyForest`) is the old pipeline: the recognizer + `V1Recognizer` builds, which is only ever the unjudged one, then `Build`, + `LibraryOperators` (for a source) and `Constrain`. The candidate + (`CandidateForest`, `CandidateToyForest`) is production's forest before + resolve, and later issues may swap it. Until the recognizer judges + precedence the two sides agree by construction, so + `TestForestEqualityDetectsPerturbation` shows a dropped alternative, + reordered alternatives, an added and a removed reachable node, a flipped + verdict and a changed rule position each reported, and a renumbered forest, + a change to an unreachable node and two refusals not reported; + `TestForestEqualityV1SideRecognizesPrecedenceRefusals` that the V1 side's + chart accepts `print $fh [];`, `$a <=> $b <=> $c;` and `1 .. 2 .. 3;` and + its `Constrain` refuses each; and `TestForestEqualityV1SideRunsOldPipeline` + that the V1 side enters its own `Constrain` and `LibraryOperators` once per + input. It runs over the toys (`TestForestEqualityToys`), the seed-4 and + seed-44 generated sentences (`TestForestEqualityGeneratedSentences`) and a + constructed input on which V1 keeps one node's alternatives under two + contexts with two different non-empty sets, the union `Constrain`'s + `shortcut:` takes (`TestForestEqualityUnionShortcut`). Each logs how many + inputs it compared of how many it loaded. Known limits, measured on `perly.y`: none in the parser states or their lookaheads, which are bison's (each reduction's LALR(1) lookahead is From 86245a9460a874c83fb11a6191b57f8960474daa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:06:04 +0000 Subject: [PATCH 2/8] test(chart): compare forests by what their reachable nodes derive ForestDiff compares a candidate's forest with V1's: the verdict, the nodes reachable from the root, matched by symbol, rule position and span rather than by index, and each reachable node's kept alternatives in order. TestForestEqualityDetectsPerturbation shows a dropped alternative, reordered alternatives, an added and a removed reachable node, a flipped verdict and a changed rule or dot each reported by the comparison that owns it, and equal forests, a renumbered forest and an added unreachable node reported by none. Each comparison was disabled in turn and its subtest went red. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/forest/equality.go | 94 +++++++++++ internal/chart/forest/equality_test.go | 211 +++++++++++++++++++++++++ 2 files changed, 305 insertions(+) create mode 100644 internal/chart/forest/equality.go create mode 100644 internal/chart/forest/equality_test.go diff --git a/internal/chart/forest/equality.go b/internal/chart/forest/equality.go new file mode 100644 index 000000000..91f175787 --- /dev/null +++ b/internal/chart/forest/equality.go @@ -0,0 +1,94 @@ +// ABOUTME: The forest-equality differential: a candidate's forest against V1's pipeline, accept or refuse and reachable nodes. +// ABOUTME: Nodes are matched by symbol, rule position and span; the V1 side, the candidate and ForestDiff are exported for reuse. + +package forest + +import ( + "cmp" + "fmt" + "maps" + "slices" +) + +// NodeKey is what a node derives, by which ForestDiff matches nodes across forests: its symbol (-1 for a rule +// position), its rule position (Rule and Dot; Rule -1 for a symbol) and its span. +type NodeKey struct{ Sym, Rule, Dot, From, To int32 } + +// noNode is the key of an absent child, index 0, which no node's key equals. +var noNode = NodeKey{-1, -1, -1, -1, -1} + +// altKey is one kept alternative by what it derives: its rule and its children's keys. +type altKey struct { + Rule int32 + Left, Right NodeKey +} + +// ForestDiff is where cand's forest differs from v1's, nil for a refusal: the verdict, then a node reachable from +// the root in one only, then the first reachable node, by key, whose kept alternatives differ in content or order; +// "" where they are equal. A node unreachable from the root is never compared. +func ForestDiff(cand, v1 *Forest) string { + switch { + case cand == nil && v1 == nil: + return "" + case cand == nil: + return "the candidate refuses, V1 accepts" + case v1 == nil: + return "the candidate accepts, V1 refuses" + } + c, v := reachableAlts(cand), reachableAlts(v1) + keys := slices.SortedFunc(maps.Keys(c), cmpNodeKey) + for _, k := range slices.SortedFunc(maps.Keys(v), cmpNodeKey) { + if _, ok := c[k]; !ok { + return fmt.Sprintf("node %+v is reachable in V1 only", k) + } + } + for _, k := range keys { + if _, ok := v[k]; !ok { + return fmt.Sprintf("node %+v is reachable in the candidate only", k) + } + } + for _, k := range keys { + if !slices.Equal(c[k], v[k]) { + return fmt.Sprintf("node %+v: the candidate keeps %+v, V1 %+v", k, c[k], v[k]) + } + } + return "" +} + +// reachableAlts is each node reachable from f's root, by key, with its kept alternatives in order. +func reachableAlts(f *Forest) map[NodeKey][]altKey { + key := func(n int32) NodeKey { + if n == 0 { + return noNode + } + nd := f.Nodes[n] + return NodeKey{nd.Sym, nd.Rule, nd.Dot, nd.From, nd.To} + } + out := map[NodeKey][]altKey{} + seen := make([]bool, len(f.Nodes)) + work := []int32{f.Root} + for len(work) > 0 { + n := work[len(work)-1] + work = work[:len(work)-1] + if seen[n] { + continue + } + seen[n] = true + alts := []altKey{} + for a := f.Nodes[n].Alt; a != 0; a = f.Alts[a].Next { + x := f.Alts[a] + alts = append(alts, altKey{x.Rule, key(x.Left), key(x.Right)}) + for _, ch := range []int32{x.Left, x.Right} { + if ch != 0 { + work = append(work, ch) + } + } + } + out[key(n)] = alts + } + return out +} + +func cmpNodeKey(x, y NodeKey) int { + return cmp.Or(cmp.Compare(x.From, y.From), cmp.Compare(x.To, y.To), cmp.Compare(x.Sym, y.Sym), cmp.Compare(x.Rule, y.Rule), cmp.Compare(x.Dot, y.Dot)) +} diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go new file mode 100644 index 000000000..22de4e05f --- /dev/null +++ b/internal/chart/forest/equality_test.go @@ -0,0 +1,211 @@ +// ABOUTME: Tests the forest-equality differential: perturbed forests reported, renumbered and unreachable changes not. +// ABOUTME: Runs the candidate against V1's pipeline over the toys, seeds 4 and 44, and a union-shortcut fixture. + +package forest + +import ( + "slices" + "strings" + "testing" + + "tamarou.com/pvm/internal/chart/recognize" +) + +// perturbationForest is an ambiguous toy forest with rule-position nodes: S ::= S S S | S S | A over four A's. +func perturbationForest(t *testing.T) *Forest { + t.Helper() + tab := toyTables(t, "S ::= S S S | S S | A") + f, _, _ := toyForest(t, tab, []string{"A", "A", "A", "A"}, recognize.Options{}) + if f == nil { + t.Fatal("the chart refuses A A A A") + } + return f +} + +// reachableNodes is the indexes of f's nodes reachable from its root. +func reachableNodes(f *Forest) []int32 { + seen := make([]bool, len(f.Nodes)) + var out []int32 + work := []int32{f.Root} + for len(work) > 0 { + n := work[len(work)-1] + work = work[:len(work)-1] + if seen[n] { + continue + } + seen[n] = true + out = append(out, n) + for a := f.Nodes[n].Alt; a != 0; a = f.Alts[a].Next { + for _, c := range []int32{f.Alts[a].Left, f.Alts[a].Right} { + if c != 0 { + work = append(work, c) + } + } + } + } + return out +} + +// dropAlt unlinks alternative a from node n's list. +func dropAlt(f *Forest, n, a int32) { + p := &f.Nodes[n].Alt + for *p != a { + p = &f.Alts[*p].Next + } + *p = f.Alts[a].Next +} + +// findDrop is a reachable node of f and one of its alternatives whose removal leaves the reachable node count +// unchanged (same), or lowers it (!same). +func findDrop(t *testing.T, f *Forest, same bool) (int32, int32) { + t.Helper() + before := len(reachableNodes(f)) + for _, n := range reachableNodes(f) { + alts := keptAlts(f, int(n)) + if len(alts) < 2 { + continue + } + for _, a := range alts { + g := f.Copy() + dropAlt(g, n, a) + if (len(reachableNodes(g)) == before) == same { + return n, a + } + } + } + t.Fatalf("no reachable node with an alternative whose removal keeps the node count same=%v", same) + return 0, 0 +} + +// renumbered is f with its nodes and alternatives stored in reverse order, every index remapped. +func renumbered(f *Forest) *Forest { + g := &Forest{Nodes: make([]Node, len(f.Nodes)), Alts: make([]Alt, len(f.Alts))} + node := func(n int32) int32 { return map0(n, len(f.Nodes)) } + alt := func(a int32) int32 { return map0(a, len(f.Alts)) } + g.Root = node(f.Root) + for n, nd := range f.Nodes[1:] { + nd.Alt = alt(nd.Alt) + g.Nodes[node(int32(n+1))] = nd + } + for a, x := range f.Alts[1:] { + x.Left, x.Right, x.Next = node(x.Left), node(x.Right), alt(x.Next) + g.Alts[alt(int32(a+1))] = x + } + return g +} + +// map0 is index i of n reversed, 0 (none) kept: 1 becomes n-1. +func map0(i int32, n int) int32 { + if i == 0 { + return 0 + } + return int32(n) - i +} + +// TestForestEqualityDetectsPerturbation: ForestDiff reports each kind of difference through the comparison that +// owns it, and reports nothing for equal forests, a renumbered forest or a change no root derivation reaches. +func TestForestEqualityDetectsPerturbation(t *testing.T) { + base := perturbationForest(t) + reports := func(t *testing.T, cand, v1 *Forest, want string) { + t.Helper() + if d := ForestDiff(cand, v1); !strings.Contains(d, want) { + t.Errorf("ForestDiff = %q, want a report containing %q", d, want) + } + } + quiet := func(t *testing.T, cand, v1 *Forest) { + t.Helper() + if d := ForestDiff(cand, v1); d != "" { + t.Errorf("ForestDiff = %q, want no difference", d) + } + } + + t.Run("equal", func(t *testing.T) { quiet(t, base.Copy(), base.Copy()) }) + + t.Run("drop-alternative", func(t *testing.T) { + g := base.Copy() + n, a := findDrop(t, g, true) + dropAlt(g, n, a) + reports(t, g, base, "keeps") + reports(t, base, g, "keeps") + }) + + t.Run("reorder-alternatives", func(t *testing.T) { + g := base.Copy() + n := slices.IndexFunc(reachableNodes(g), func(n int32) bool { return len(keptAlts(g, int(n))) >= 2 }) + if n < 0 { + t.Fatal("no reachable node with two alternatives") + } + m := reachableNodes(g)[n] + alts := keptAlts(g, int(m)) + g.Nodes[m].Alt = 0 + for _, a := range alts { // add puts each first, so the list ends reversed + g.Nodes[m].Alt, g.Alts[a].Next = a, g.Nodes[m].Alt + } + if slices.Equal(keptAlts(g, int(m)), alts) { + t.Fatal("the alternatives were not reordered") + } + reports(t, g, base, "keeps") + }) + + t.Run("add-reachable-node", func(t *testing.T) { + g := base.Copy() + leaf := g.Nodes[g.Alts[g.Nodes[g.Root].Alt].Right] + leaf.From, leaf.To, leaf.Alt = 100, 101, 0 // a span no node of base has + x := g.newNode(leaf) + g.add(g.Root, Alt{Rule: g.Alts[g.Nodes[g.Root].Alt].Rule, Right: x}) + reports(t, g, base, "reachable in the candidate only") + }) + + t.Run("remove-reachable-node", func(t *testing.T) { + g := base.Copy() + n, a := findDrop(t, g, false) + dropAlt(g, n, a) + reports(t, g, base, "reachable in V1 only") + }) + + t.Run("flip-accept", func(t *testing.T) { + reports(t, nil, base, "the candidate refuses") + reports(t, base, nil, "V1 refuses") + }) + + t.Run("rule-position", func(t *testing.T) { + at := slices.IndexFunc(reachableNodes(base), func(n int32) bool { return base.Nodes[n].Sym < 0 }) + if at < 0 { + t.Fatal("no reachable rule-position node") + } + n := reachableNodes(base)[at] + other := base.Nodes[n].Rule + 1 // any other rule + for name, change := range map[string]func(*Node){ + "rule": func(nd *Node) { nd.Rule = other }, + "dot": func(nd *Node) { nd.Dot-- }, + } { + g := base.Copy() + change(&g.Nodes[n]) + if g.Nodes[n].Sym != base.Nodes[n].Sym || g.Nodes[n].From != base.Nodes[n].From || g.Nodes[n].To != base.Nodes[n].To { + t.Fatalf("%s: the symbol or span moved", name) + } + if d := ForestDiff(g, base); !strings.Contains(d, "reachable") { + t.Errorf("%s changed on node %d: ForestDiff = %q, want the node reported", name, n, d) + } + } + }) + + t.Run("renumbered-nodes-equal", func(t *testing.T) { + g := renumbered(base) + if g.Root == base.Root { + t.Fatalf("the root kept index %d", g.Root) + } + quiet(t, g, base) + quiet(t, base, g) + }) + + t.Run("unreachable-node-ignored", func(t *testing.T) { + g := base.Copy() + x := g.newNode(Node{Sym: g.Nodes[g.Root].Sym, Rule: -1, From: 0, To: g.Nodes[g.Root].To + 1}) + g.add(x, Alt{Rule: g.Alts[g.Nodes[g.Root].Alt].Rule, Left: g.Root, Right: g.Root}) + if slices.Contains(reachableNodes(g), x) { + t.Fatal("the added node is reachable") + } + quiet(t, g, base) + }) +} From 21d33474c2a1cb0bd40aa60bb98caf1658264afd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:13:08 +0000 Subject: [PATCH 3/8] test(chart): build the differential's V1 side from the unjudged recognizer V1Forest and V1ToyForest are V1's pipeline: the recognizer V1Recognizer builds, which only ever judges no precedence, then Build, LibraryOperators for a source, then Constrain, each stage entered through the V1 side's own hooks. The V1 side's chart accepts print $fh [];, $a <=> $b <=> $c; and 1 .. 2 .. 3; and its Constrain refuses each, so a V1 side running the judged recognizer fails; and it enters its own LibraryOperators and Constrain once per input, so a V1 side wired to production's output fails. Each was shown red by mutation: Constrain skipped, the chart refusing, the side wired to ParseWith, and either hook bypassed. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/forest/equality.go | 57 +++++++++++++++++ internal/chart/forest/equality_test.go | 86 ++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) diff --git a/internal/chart/forest/equality.go b/internal/chart/forest/equality.go index 91f175787..cec9a9b2f 100644 --- a/internal/chart/forest/equality.go +++ b/internal/chart/forest/equality.go @@ -8,6 +8,10 @@ import ( "fmt" "maps" "slices" + + "tamarou.com/pvm/internal/chart/grammar" + "tamarou.com/pvm/internal/chart/lex" + "tamarou.com/pvm/internal/chart/recognize" ) // NodeKey is what a node derives, by which ForestDiff matches nodes across forests: its symbol (-1 for a rule @@ -92,3 +96,56 @@ func reachableAlts(f *Forest) map[NodeKey][]altKey { func cmpNodeKey(x, y NodeKey) int { return cmp.Or(cmp.Compare(x.From, y.From), cmp.Compare(x.To, y.To), cmp.Compare(x.Sym, y.Sym), cmp.Compare(x.Rule, y.Rule), cmp.Compare(x.Dot, y.Dot)) } + +// V1Recognizer is the V1 side's recognizer over tab, and the only place the V1 side gets one: always the +// recognizer that judges no precedence, never production's. Today that is recognize.New's. +func V1Recognizer(tab *grammar.Tables) *recognize.Recognizer { + return recognize.New(tab, recognize.Options{}) +} + +// v1LibraryOperators and v1Constrain are the V1 side's own stages, variables so a test can count its entries. +var ( + v1LibraryOperators = libraryOperators + v1Constrain = (*Forest).Constrain +) + +// V1Forest is V1's forest of src: V1Recognizer's chart, Build, LibraryOperators under scope, then Constrain under +// perly.y's precedence (the V2 design's §5). Where it refuses, the forest is nil and the Refusal names the stage +// that refused (grammar, scope or precedence) with Byte 0: the differential compares verdicts, not bytes. +func V1Forest(tab *grammar.Tables, src []byte, scope Scope) (*Forest, Refusal) { + s, _ := lex.Lex(src, tab.Tokens) + l := lex.Linear(s) + c, err := recognize.Recognize(V1Recognizer(tab), l) + if err != nil { + return nil, Refusal{Reason: err.Error()} + } + if !c.Accepted() { + return nil, Refusal{Reason: "grammar"} + } + f := Build(tab, c, l) + if v1LibraryOperators(tab, f, s, src, scope) >= 0 { + return nil, Refusal{Reason: "scope"} + } + prec, err := ParsePrecedence(tab) + if err != nil { + return nil, Refusal{Reason: err.Error()} + } + if !v1Constrain(f, prec) { + return nil, Refusal{Reason: "precedence"} + } + return f, Refusal{} +} + +// V1ToyForest is V1's forest of a toy grammar's lattice l under the toy's precedence p: V1Recognizer's chart, +// Build, then Constrain; nil where it refuses. A toy has no source, so it has no library operators. +func V1ToyForest(tab *grammar.Tables, l *lex.Lattice[lex.None], p *Precedence) (*Forest, error) { + c, err := recognize.Recognize(V1Recognizer(tab), l) + if err != nil || !c.Accepted() { + return nil, err + } + f := Build(tab, c, l) + if !v1Constrain(f, p) { + return nil, nil + } + return f, nil +} diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go index 22de4e05f..6f12b9270 100644 --- a/internal/chart/forest/equality_test.go +++ b/internal/chart/forest/equality_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" + "tamarou.com/pvm/internal/chart/grammar" + "tamarou.com/pvm/internal/chart/lex" "tamarou.com/pvm/internal/chart/recognize" ) @@ -209,3 +211,87 @@ func TestForestEqualityDetectsPerturbation(t *testing.T) { quiet(t, g, base) }) } + +// precedenceRefusals are three inputs V1 refuses only by precedence: recognition accepts each and Parse refuses it +// as precedence (measured at e3432c0f). +var precedenceRefusals = []struct{ name, src string }{ + {"indirob", "print $fh [];"}, + {"nceqop-chain", "$a <=> $b <=> $c;"}, + {"dotdot-chain", "1 .. 2 .. 3;"}, +} + +// TestForestEqualityV1SideRecognizesPrecedenceRefusals: the V1 side's chart accepts each input V1 refuses only by +// precedence, and its own Constrain refuses it, so a V1 side whose recognizer judged precedence would refuse at +// the chart, as grammar, and fail here. +func TestForestEqualityV1SideRecognizesPrecedenceRefusals(t *testing.T) { + tab := committedTables(t) + for _, in := range precedenceRefusals { + t.Run(in.name, func(t *testing.T) { + c, err := recognize.Recognize(V1Recognizer(tab), lex.Linear(lexOnly(tab, in.src))) + if err != nil { + t.Fatal(err) + } + if !c.Accepted() { + t.Errorf("%q: the V1 recognizer's chart refuses it", in.src) + } + if f, ref := V1Forest(tab, []byte(in.src), Scope{}); f != nil || ref.Reason != "precedence" { + t.Errorf("%q: V1Forest = (forest %v, %+v), want no forest and a precedence refusal", in.src, f != nil, ref) + } + }) + } +} + +// lexOnly is src's token stream over tab. +func lexOnly(tab *grammar.Tables, src string) *lex.Stream { + s, _ := lex.Lex([]byte(src), tab.Tokens) + return s +} + +// TestForestEqualityV1SideRunsOldPipeline: V1Forest enters its own LibraryOperators and Constrain once per input the +// chart accepts, and V1ToyForest its own Constrain once per toy sentence the chart accepts, counted through the V1 +// side's stage hooks, so a V1 side wired to production's output, which never passes those hooks, fails. +func TestForestEqualityV1SideRunsOldPipeline(t *testing.T) { + libs, cons := 0, 0 + lib0, con0 := v1LibraryOperators, v1Constrain + t.Cleanup(func() { v1LibraryOperators, v1Constrain = lib0, con0 }) + v1LibraryOperators = func(tab *grammar.Tables, f *Forest, s *lex.Stream, src []byte, scope Scope) int { + libs++ + return lib0(tab, f, s, src, scope) + } + v1Constrain = func(f *Forest, p *Precedence) bool { + cons++ + return con0(f, p) + } + + tab := committedTables(t) + srcs := []string{"1;", "$x = 1 + 2 * 3;", "f(1, 2);", "print $fh [];", "1 .. 2 .. 3;"} + accepted := 0 + for _, src := range srcs { + if f, _ := V1Forest(tab, []byte(src), Scope{}); f != nil { + accepted++ + } + } + if libs != len(srcs) || cons != len(srcs) { + t.Errorf("over %d inputs the chart accepts: LibraryOperators entered %d times, Constrain %d; want %d each", len(srcs), libs, cons, len(srcs)) + } + if accepted == 0 || accepted == len(srcs) { + t.Errorf("V1Forest accepted %d of %d; want some accepted and some refused by Constrain", accepted, len(srcs)) + } + + ty := loadToy(t, "ladder") + cons = 0 + for _, s := range ty.sentences[:20] { + if _, err := V1ToyForest(ty.tab, toyLattice(ty.tab, s.words), ty.prec); err != nil { + t.Fatal(err) + } + } + want := 0 + for _, s := range ty.sentences[:20] { + if f, _, _ := toyForest(t, ty.tab, s.words, recognize.Options{}); f != nil { + want++ + } + } + if want == 0 || cons != want { + t.Errorf("V1ToyForest entered Constrain %d times over %d ladder sentences the chart accepts; want one each", cons, want) + } +} From ea7059f92d08495d6884fc1d76da79006a01026a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:23:17 +0000 Subject: [PATCH 4/8] test(chart): compare production's forest with V1's over the toys and seeds 4 and 44 CandidateForest is production's forest before resolve: parseStream now ends at constrainedStream, which resolve and the readings count follow, so the candidate is what ParseWith judges with nothing taken away. CandidateToyForest is production's recognizer, Build and Constrain over a toy's own precedence. Both are variables a later issue can point at the judged recognizer. TestForestEqualityToys compares 4395 of 4395 toy sentences and TestForestEqualityGeneratedSentences 20083 of 20083 seed-4 and 15000 of 15000 seed-44 sentences, each requiring both verdicts among them; the seed generators are now functions both differentials share. TestForestEqualityHarnessesUseCandidate swaps in a candidate that refuses everything and requires both loops to report it, so neither compares V1 with itself. empty-input and both-refuse join the perturbation subtests. Shown red by mutation: each loop comparing V1 with itself, compared counting only accepted inputs, and either candidate skipping Constrain. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/forest/equality.go | 21 +++ internal/chart/forest/equality_test.go | 139 ++++++++++++++++++ internal/chart/forest/forest.go | 17 ++- .../chart/forest/precedence_reference_test.go | 24 ++- 4 files changed, 191 insertions(+), 10 deletions(-) diff --git a/internal/chart/forest/equality.go b/internal/chart/forest/equality.go index cec9a9b2f..b0176dcbe 100644 --- a/internal/chart/forest/equality.go +++ b/internal/chart/forest/equality.go @@ -149,3 +149,24 @@ func V1ToyForest(tab *grammar.Tables, l *lex.Lattice[lex.None], p *Precedence) ( } return f, nil } + +// CandidateForest is the forest the differential compares with V1Forest's: production's, before resolve. A later +// issue may point it at another recognizer. +var CandidateForest = func(tab *grammar.Tables, src []byte, scope Scope) (*Forest, Refusal) { + f, _, ref := constrainedStream(tab, recognize.New(tab, recognize.Options{}), src, scope) + return f, ref +} + +// CandidateToyForest is the toy forest the differential compares with V1ToyForest's: production's recognizer, +// Build, then Constrain under p; nil where it refuses. A later issue may point it at another recognizer. +var CandidateToyForest = func(tab *grammar.Tables, l *lex.Lattice[lex.None], p *Precedence) (*Forest, error) { + c, err := recognize.Recognize(recognize.New(tab, recognize.Options{}), l) + if err != nil || !c.Accepted() { + return nil, err + } + f := Build(tab, c, l) + if !f.Constrain(p) { + return nil, nil + } + return f, nil +} diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go index 6f12b9270..625aff1ae 100644 --- a/internal/chart/forest/equality_test.go +++ b/internal/chart/forest/equality_test.go @@ -4,6 +4,7 @@ package forest import ( + "fmt" "slices" "strings" "testing" @@ -210,6 +211,32 @@ func TestForestEqualityDetectsPerturbation(t *testing.T) { } quiet(t, g, base) }) + + tab := committedTables(t) + sides := func(t *testing.T, src string) (cand, v1 *Forest) { + t.Helper() + cand, _ = CandidateForest(tab, []byte(src), Scope{}) + v1, _ = V1Forest(tab, []byte(src), Scope{}) + return cand, v1 + } + + t.Run("empty-input", func(t *testing.T) { + cand, v1 := sides(t, "") + if v1 == nil { + t.Fatal("V1 refuses the empty input") + } + quiet(t, cand, v1) + }) + + t.Run("both-refuse", func(t *testing.T) { + for _, src := range []string{"1 +;", "1 .. 2 .. 3;"} { // refused by the chart, and by Constrain + cand, v1 := sides(t, src) + if cand != nil || v1 != nil { + t.Fatalf("%q: candidate forest %v, V1 forest %v; want both refused", src, cand != nil, v1 != nil) + } + quiet(t, cand, v1) + } + }) } // precedenceRefusals are three inputs V1 refuses only by precedence: recognition accepts each and Parse refuses it @@ -295,3 +322,115 @@ func TestForestEqualityV1SideRunsOldPipeline(t *testing.T) { t.Errorf("V1ToyForest entered Constrain %d times over %d ladder sentences the chart accepts; want one each", cons, want) } } + +// toyDiffs compares the candidate's forest of each of ty's sentences with V1's under ty's precedence: how many it +// compared, how many V1 accepts, and each difference. +func toyDiffs(t *testing.T, ty toy) (compared, accepted int, diffs []string) { + t.Helper() + for _, s := range ty.sentences { + l := toyLattice(ty.tab, s.words) + cand, err := CandidateToyForest(ty.tab, l, ty.prec) + if err != nil { + t.Fatalf("%v: candidate: %v", s.words, err) + } + v1, err := V1ToyForest(ty.tab, l, ty.prec) + if err != nil { + t.Fatalf("%v: V1: %v", s.words, err) + } + compared++ + if v1 != nil { + accepted++ + } + if d := ForestDiff(cand, v1); d != "" { + diffs = append(diffs, strings.Join(s.words, " ")+": "+d) + } + } + return compared, accepted, diffs +} + +// sentenceDiffs compares the candidate's forest of each source with V1's under the empty scope: how many it +// compared, how many V1 accepts, and each difference. +func sentenceDiffs(tab *grammar.Tables, srcs []string) (compared, accepted int, diffs []string) { + for _, src := range srcs { + cand, _ := CandidateForest(tab, []byte(src), Scope{}) + v1, _ := V1Forest(tab, []byte(src), Scope{}) + compared++ + if v1 != nil { + accepted++ + } + if d := ForestDiff(cand, v1); d != "" { + diffs = append(diffs, fmt.Sprintf("%q: %s", src, d)) + } + } + return compared, accepted, diffs +} + +// reportDiffs fails t with the first ten of diffs and their count over compared. +func reportDiffs(t *testing.T, what string, compared int, diffs []string) { + t.Helper() + for _, d := range diffs[:min(10, len(diffs))] { + t.Errorf("%s %s", what, d) + } + if len(diffs) > 0 { + t.Errorf("%s: %d of %d forests differ from V1's", what, len(diffs), compared) + } +} + +// TestForestEqualityToys: on every toy fixture sentence, the candidate's toy forest under the toy's own precedence +// equals V1's. It logs how many it compared of how many it loaded, and requires each toy to have sentences V1 +// accepts and sentences it refuses, so the comparison is not of refusals alone. +func TestForestEqualityToys(t *testing.T) { + loaded, compared := 0, 0 + for _, name := range toyNames { + ty := loadToy(t, name) + n, accepted, diffs := toyDiffs(t, ty) + loaded += len(ty.sentences) + compared += n + if accepted == 0 || accepted == n { + t.Errorf("%s: V1 accepts %d of %d sentences; want some of each verdict", name, accepted, n) + } + reportDiffs(t, name, n, diffs) + } + t.Logf("toys: compared %d of %d sentences", compared, loaded) + if compared == 0 || compared != loaded { + t.Errorf("compared %d of %d toy sentences; want every one, and some", compared, loaded) + } +} + +// TestForestEqualityGeneratedSentences: decision §2's seed-4 and seed-44 generated sentences, the candidate's +// forest against V1's on each. Each seed logs how many it compared of how many it generated, and requires +// sentences V1 accepts and sentences it refuses. +func TestForestEqualityGeneratedSentences(t *testing.T) { + tab := committedTables(t) + for _, seed := range []struct { + name string + srcs []string + }{{"4", operatorSentences()}, {"44", chainSentences()}} { + t.Logf("seed %s: %d sentences", seed.name, len(seed.srcs)) + compared, accepted, diffs := sentenceDiffs(tab, seed.srcs) + t.Logf("seed %s: compared %d of %d sentences, V1 accepts %d", seed.name, compared, len(seed.srcs), accepted) + if compared == 0 || compared != len(seed.srcs) { + t.Errorf("seed %s: compared %d of %d; want every one, and some", seed.name, compared, len(seed.srcs)) + } + if accepted == 0 || accepted == compared { + t.Errorf("seed %s: V1 accepts %d of %d; want some of each verdict", seed.name, accepted, compared) + } + reportDiffs(t, "seed "+seed.name, compared, diffs) + } +} + +// TestForestEqualityHarnessesUseCandidate: with the candidate swapped for one that refuses everything, the toy and +// sentence loops report every input V1 accepts, so neither compares V1 with itself. +func TestForestEqualityHarnessesUseCandidate(t *testing.T) { + src0, toy0 := CandidateForest, CandidateToyForest + t.Cleanup(func() { CandidateForest, CandidateToyForest = src0, toy0 }) + CandidateForest = func(*grammar.Tables, []byte, Scope) (*Forest, Refusal) { return nil, Refusal{Reason: "test"} } + CandidateToyForest = func(*grammar.Tables, *lex.Lattice[lex.None], *Precedence) (*Forest, error) { return nil, nil } + + if _, accepted, diffs := sentenceDiffs(committedTables(t), []string{"1;", "$x = 1 + 2;", "1 +;"}); accepted != 2 || len(diffs) != accepted { + t.Errorf("sentences: V1 accepts %d, %d reported; want 2 accepted and each reported", accepted, len(diffs)) + } + if _, accepted, diffs := toyDiffs(t, loadToy(t, "ladder")); accepted == 0 || len(diffs) != accepted { + t.Errorf("toys: V1 accepts %d, %d reported; want each accepted sentence reported", accepted, len(diffs)) + } +} diff --git a/internal/chart/forest/forest.go b/internal/chart/forest/forest.go index 57bfc73c6..f9bf377f7 100644 --- a/internal/chart/forest/forest.go +++ b/internal/chart/forest/forest.go @@ -110,6 +110,19 @@ func ParseWith(tab *grammar.Tables, r *recognize.Recognizer, src []byte, scope S // parseStream is ParseWith, with the token stream the forest is over. func parseStream(tab *grammar.Tables, r *recognize.Recognizer, src []byte, scope Scope) (*Forest, *lex.Stream, Refusal) { + f, s, ref := constrainedStream(tab, r, src, scope) + if f == nil { + return nil, s, ref + } + if at := resolve(tab, f, s, src, scope); at >= 0 { + return nil, s, Refusal{Byte: at, Reason: "scope"} + } + f.Readings = f.CountReadings(tab) + return f, s, Refusal{} +} + +// constrainedStream is parseStream before resolve: the forest the forest-equality differential's candidate is. +func constrainedStream(tab *grammar.Tables, r *recognize.Recognizer, src []byte, scope Scope) (*Forest, *lex.Stream, Refusal) { s, unmapped := lex.Lex(src, tab.Tokens) l := lex.Linear(s) c, err := recognize.Recognize(r, l) @@ -140,10 +153,6 @@ func parseStream(tab *grammar.Tables, r *recognize.Recognizer, src []byte, scope // locate it at the first span left with no derivation when a gate compares refusal bytes. return nil, s, Refusal{Reason: "precedence"} } - if at := resolve(tab, f, s, src, scope); at >= 0 { - return nil, s, Refusal{Byte: at, Reason: "scope"} - } - f.Readings = f.CountReadings(tab) return f, s, Refusal{} } diff --git a/internal/chart/forest/precedence_reference_test.go b/internal/chart/forest/precedence_reference_test.go index a175575aa..6db385a49 100644 --- a/internal/chart/forest/precedence_reference_test.go +++ b/internal/chart/forest/precedence_reference_test.go @@ -216,9 +216,15 @@ var operatorCrafted = []string{ "$x = { my $y {0} };", "@x = map { my $y [0] } @z;", "@x = grep { $_ == 1 == 2 } @z;", } -// TestPrecedenceOperatorSentencesMatchReference is decision §2's seed-4 generator: the 83 handcrafted sentences and -// 20,000 random operator sentences, production against the reference on each. +// TestPrecedenceOperatorSentencesMatchReference is decision §2's seed-4 generator, production against the reference +// on each sentence. func TestPrecedenceOperatorSentencesMatchReference(t *testing.T) { + sentencesMatchReference(t, operatorSentences()) +} + +// operatorSentences is decision §2's seed-4 generator: the 83 handcrafted sentences and 20,000 random operator +// sentences. +func operatorSentences() []string { terms := []string{"$x", "$y", "1", "@a", "%h", "f()", "(1)", "[1]", "{1}", "\"s\"", "$h{1}", "$a[0]", "$r->[0]", "my $m", "my ($p)", "local $l", "our $o", "_", "STDOUT", "$fh", "{$fh}"} pre := []string{"-", "!", "\\", "~", "+", "not ", "defined ", "ref ", "-e ", "-f ", "++", "--", "scalar ", "print ", "print $fh ", "print {$fh} ", "sort ", "sort $s ", "return ", "my ", "lc ", "exists ", "delete ", "rand ", "-M "} bin := []string{"+", "-", "*", "/", "**", "==", "!=", "<=>", "<", ">", "lt", "eq", "cmp", "&&", "||", "//", "and", "or", "xor", "=", "+=", "**=", "..", "...", "=~", "!~", "x", ".", ",", "=>", "?", ":", "->", "&", "|", "^", "<<", ">>", "isa"} @@ -248,12 +254,18 @@ func TestPrecedenceOperatorSentencesMatchReference(t *testing.T) { for range 20000 { srcs = append(srcs, fmt.Sprintf(wraps[rng.Intn(len(wraps))], gen(3))) } - sentencesMatchReference(t, srcs) + return srcs } -// TestPrecedenceChainSentencesMatchReference is decision §2's seed-44 generator: 15,000 Leo chains of 1 to 25 links, -// some wrapped in a nullable context, production against the reference on each. +// TestPrecedenceChainSentencesMatchReference is decision §2's seed-44 generator, production against the reference on +// each sentence. func TestPrecedenceChainSentencesMatchReference(t *testing.T) { + sentencesMatchReference(t, chainSentences()) +} + +// chainSentences is decision §2's seed-44 generator: 15,000 Leo chains of 1 to 25 links, some wrapped in a nullable +// context. +func chainSentences() []string { links := []string{"$a = ", "$a ||= ", "$a **= ", "not ", "!", "-", "\\", "~", "defined ", "ref ", "print ", "return ", "$a ? $b : ", "$a ** ", "$a .. ", "$a x ", "$a // ", "$a || ", "$a or ", "$a && ", "$a and ", "$a <=> ", "$a == ", "$a . ", "$a + ", "my $m = ", "local $l = ", "sort ", "lc ", "-e ", "f ", "$a, ", "$a => ", "($a) x ", "scalar "} tails := []string{"$z", "$z ** $y", "$z + $y * $w", "$z ? $y : $w", "$z = $y", "$z->[0]", "$z++", "--$z", "@z", "()", "[]", "{}", "f()", "$z <=> $y", "$z .. $y", "$z [0]", "$fh [1]", "$fh []", "{$fh} []", "$z or $y", "1"} nulls := []string{"for (;;) { %s }", "%s for ();", "sub f :lvalue { %s }", "my $x = () = (%s);", "@x = (%s,);", "do {} until %s;", "{ ; %s ; }", "return;", "print;", "%s"} @@ -274,5 +286,5 @@ func TestPrecedenceChainSentencesMatchReference(t *testing.T) { } srcs = append(srcs, s) } - sentencesMatchReference(t, srcs) + return srcs } From 6438449e467286d948542e5042e47194963f88b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:33:44 +0000 Subject: [PATCH 5/8] test(chart): exercise V1's union shortcut in the forest-equality differential No corpus file takes Constrain's shortcut: (C5), so the differential gains a constructed input, STDOUT isa my $m | 1;, on which V1's judgement keeps the term over isa my $m | 1 under two contexts with two different non-empty alternative sets, {35} and {34 35}, and keeps their union. contextAltSets reads each context's set apart by mark's own loop without marking; the test logs and requires contexts: 2, distinct non-empty alternative sets: 2, holds the measurement to Constrain's kept set as a union on every node of 2413 accepted inputs (the toys, the 83 handcrafted sentences, _ - $h{1} - $fh; and TestPrecedenceMarkFirstFilter's toy), and requires the candidate's forest to equal V1's. Shown red by mutation: contexts merged, mark's first-terminal filter or reduce check dropped, V1 skipping Constrain, the candidate skipping Constrain, and an input that takes no shortcut. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/forest/equality_test.go | 188 +++++++++++++++++++++++++ 1 file changed, 188 insertions(+) diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go index 625aff1ae..f998fc7db 100644 --- a/internal/chart/forest/equality_test.go +++ b/internal/chart/forest/equality_test.go @@ -5,6 +5,7 @@ package forest import ( "fmt" + "maps" "slices" "strings" "testing" @@ -434,3 +435,190 @@ func TestForestEqualityHarnessesUseCandidate(t *testing.T) { t.Errorf("toys: V1 accepts %d, %d reported; want each accepted sentence reported", accepted, len(diffs)) } } + +// contextAltSets is, for each node of f, the alternatives each of its contexts keeps on its own under V1's +// judgement by p, in the order of the node's list: a context is eval's (the terminal after the node, its spine top, +// its parent item), and what it keeps is mark's choice over every first terminal it was marked with. Constrain +// keeps the union of a node's sets (its shortcut:); this reads them apart. f is not changed. +func contextAltSets(f *Forest, p *Precedence) map[int32][][]int32 { + j := newJudgement(f, p) + if len(j.eval(f.Root, p.tab.EOF, rootTop, -1)) == 0 { + return nil + } + j.mark(f.Root, p.tab.EOF, rootTop, -1, -1) + out := map[int32][][]int32{} + for n := range f.Nodes { + type ctx struct{ t, top, pi int32 } + var order []ctx + sets := map[ctx][]int32{} + for e := j.markAt[n]; e != 0; e = j.marks[e].next { + m := j.marks[e] + k := ctx{m.t, m.top, m.pi} + if _, ok := sets[k]; !ok { + order = append(order, k) + sets[k] = []int32{} + } + keep := func(x int32) bool { return m.first < 0 || x == m.first } + for a := f.Nodes[n].Alt; a != 0; a = f.Alts[a].Next { // mark's loop, without marking + r, mm, at := j.alt(int32(n), a, m.top) + if f.Nodes[n].Sym >= 0 && !p.reducesFree(r, int(m.t), m.pi) { + continue + } + if !slices.Contains(sets[k], a) && slices.ContainsFunc(j.seq(a, r, mm, int(m.t), at, nil), keep) { + sets[k] = append(sets[k], a) + } + } + } + for _, k := range order { + out[int32(n)] = append(out[int32(n)], sets[k]) + } + } + return out +} + +// shortcutNode is the first node of f at which two contexts keep two different non-empty sets of alternatives +// under p, with every context's set there and how many distinct non-empty sets they hold; -1 where there is none. +func shortcutNode(f *Forest, p *Precedence) (n int32, sets [][]int32, distinct int) { + all := contextAltSets(f, p) + for _, n := range slices.Sorted(maps.Keys(all)) { + var seen [][]int32 + for _, s := range all[n] { + if len(s) > 0 && !slices.ContainsFunc(seen, func(d []int32) bool { return sameAlts(d, s) }) { + seen = append(seen, s) + } + } + if len(seen) >= 2 { + return n, all[n], len(seen) + } + } + return -1, nil, 0 +} + +// unionDiff is where judged, Constrain's judgement of a copy of built, keeps on some node other than the union of +// that node's contexts' sets in built under p, in the node's order; "" where it keeps the union on every node. +func unionDiff(built, judged *Forest, p *Precedence) string { + all := contextAltSets(built, p) + for n := range built.Nodes { + var union []int32 + for _, a := range keptAlts(built, n) { + if slices.ContainsFunc(all[int32(n)], func(s []int32) bool { return slices.Contains(s, a) }) { + union = append(union, a) + } + } + if !slices.Equal(keptAlts(judged, n), union) { + return fmt.Sprintf("node %d: Constrain keeps %v, the union of its contexts' sets is %v", n, keptAlts(judged, n), union) + } + } + return "" +} + +// sameAlts is whether a and b hold the same alternatives, in any order. +func sameAlts(a, b []int32) bool { + return len(a) == len(b) && !slices.ContainsFunc(a, func(x int32) bool { return !slices.Contains(b, x) }) +} + +// unionShortcutInput is a constructed input on which V1 keeps a node's alternatives under two contexts with two +// different non-empty sets, the union Constrain's shortcut: takes (C5): the term over `isa my $m | 1` keeps one +// alternative in one context and two in the other. No corpus file exercises it. +const unionShortcutInput = "STDOUT isa my $m | 1;" + +// TestForestEqualityUnionShortcut: on unionShortcutInput, V1's judgement keeps one node's alternatives under two +// contexts with two different non-empty sets, which it logs; V1Forest keeps on every node the union of its +// contexts' sets, so the measurement reads Constrain's own choice; and the candidate's forest equals V1's. +func TestForestEqualityUnionShortcut(t *testing.T) { + tab := committedTables(t) + prec, err := ParsePrecedence(tab) + if err != nil { + t.Fatal(err) + } + src := []byte(unionShortcutInput) + s, _ := lex.Lex(src, tab.Tokens) + l := lex.Linear(s) + c, err := recognize.Recognize(V1Recognizer(tab), l) + if err != nil || !c.Accepted() { + t.Fatalf("%q: the V1 chart refuses it (%v)", src, err) + } + built := Build(tab, c, l) + if LibraryOperators(tab, built, s, src, Scope{}) >= 0 { + t.Fatalf("%q: LibraryOperators refuses it", src) + } + n, sets, distinct := shortcutNode(built, prec) + if n < 0 { + t.Fatalf("%q: no node keeps different non-empty alternative sets under two contexts", src) + } + nd := built.Nodes[n] + name := "a rule position" + if nd.Sym >= 0 { + name = tab.Symbols[nd.Sym].Name + } + t.Logf("%q: node %d (%s, %d-%d), alternatives %v: contexts: %d, distinct non-empty alternative sets: %d, sets %v", + src, n, name, nd.From, nd.To, keptAlts(built, int(n)), len(sets), distinct, sets) + if len(sets) != 2 || distinct != 2 { + t.Errorf("contexts %d, distinct non-empty alternative sets %d; want 2 and 2", len(sets), distinct) + } + + v1, ref := V1Forest(tab, src, Scope{}) + if v1 == nil { + t.Fatalf("%q: V1 refuses it: %+v", src, ref) + } + if g := v1.Nodes[n]; g.Sym != nd.Sym || g.Rule != nd.Rule || g.Dot != nd.Dot || g.From != nd.From || g.To != nd.To { + t.Fatalf("V1Forest's node %d is %+v, the built forest's %+v", n, g, nd) + } + if d := unionDiff(built, v1, prec); d != "" { + t.Errorf("%q: %s", src, d) + } + + // The measurement is held to Constrain beyond this input: every toy sentence and the 83 handcrafted operator + // sentences V1 accepts, `_ - $h{1} - $fh;`, where its reduce check decides, and TestPrecedenceMarkFirstFilter's + // toy, where mark's first-terminal filter does. + checked := 0 + ftab, fp := markFirstFilterToy(t) + fl := toyLattice(ftab, []string{"C", "A", "Q1"}) + ftab.TerminalSets = append(ftab.TerminalSets, []int{symbol(ftab, "A"), symbol(ftab, "B")}) + fl.Edges[1].Token.TerminalSet = len(ftab.TerminalSets) - 1 + fv1, err := V1ToyForest(ftab, fl, fp) + fc, cerr := recognize.Recognize(V1Recognizer(ftab), fl) + if err != nil || cerr != nil || fv1 == nil { + t.Fatalf("the mark-first-filter toy: V1 refuses C {A B} Q1 (%v, %v)", err, cerr) + } + if d := unionDiff(Build(ftab, fc, fl), fv1, fp); d != "" { + t.Errorf("the mark-first-filter toy: %s", d) + } + checked++ + for _, name := range toyNames { + ty := loadToy(t, name) + for _, s := range ty.sentences { + l := toyLattice(ty.tab, s.words) + v1, err := V1ToyForest(ty.tab, l, ty.prec) + if err != nil || v1 == nil { + continue + } + b, _, _ := toyForest(t, ty.tab, s.words, recognize.Options{}) + if d := unionDiff(b, v1, ty.prec); d != "" { + t.Errorf("%s %s: %s", name, strings.Join(s.words, " "), d) + } + checked++ + } + } + for _, src := range append(slices.Clone(operatorCrafted), "_ - $h{1} - $fh;") { + v1, _ := V1Forest(tab, []byte(src), Scope{}) + if v1 == nil { + continue + } + s, _ := lex.Lex([]byte(src), tab.Tokens) + l := lex.Linear(s) + c, _ := recognize.Recognize(V1Recognizer(tab), l) + b := Build(tab, c, l) + LibraryOperators(tab, b, s, []byte(src), Scope{}) + if d := unionDiff(b, v1, prec); d != "" { + t.Errorf("%q: %s", src, d) + } + checked++ + } + t.Logf("the per-context measurement matches Constrain's kept set on every node of %d accepted inputs", checked) + + cand, _ := CandidateForest(tab, src, Scope{}) + if d := ForestDiff(cand, v1); d != "" { + t.Errorf("%q: %s", src, d) + } +} From 7661a9f55c9687e62717773747196e8537073814 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:11:22 +0000 Subject: [PATCH 6/8] test(chart): tidy the forest-equality tests and name the harness check The simplify pass inlines a single-use lexer helper and computes each subtest's reachable nodes once. The README's differential bullet names TestForestEqualityHarnessesUseCandidate, which holds that neither loop compares V1 with itself. make test passes with T1_CORPUS set. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/README.md | 4 +++- internal/chart/forest/equality_test.go | 19 ++++++++----------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/internal/chart/README.md b/internal/chart/README.md index 2aeb604ac..29aa55a73 100644 --- a/internal/chart/README.md +++ b/internal/chart/README.md @@ -2766,7 +2766,9 @@ grammar's tables and its precedence: no Earley item gains a fact. chart accepts `print $fh [];`, `$a <=> $b <=> $c;` and `1 .. 2 .. 3;` and its `Constrain` refuses each; and `TestForestEqualityV1SideRunsOldPipeline` that the V1 side enters its own `Constrain` and `LibraryOperators` once per - input. It runs over the toys (`TestForestEqualityToys`), the seed-4 and + input; `TestForestEqualityHarnessesUseCandidate` swaps in a candidate that + refuses everything and requires the loops to report it, so none compares V1 + with itself. It runs over the toys (`TestForestEqualityToys`), the seed-4 and seed-44 generated sentences (`TestForestEqualityGeneratedSentences`) and a constructed input on which V1 keeps one node's alternatives under two contexts with two different non-empty sets, the union `Constrain`'s diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go index f998fc7db..d1c76a4ac 100644 --- a/internal/chart/forest/equality_test.go +++ b/internal/chart/forest/equality_test.go @@ -135,11 +135,12 @@ func TestForestEqualityDetectsPerturbation(t *testing.T) { t.Run("reorder-alternatives", func(t *testing.T) { g := base.Copy() - n := slices.IndexFunc(reachableNodes(g), func(n int32) bool { return len(keptAlts(g, int(n))) >= 2 }) + reach := reachableNodes(g) + n := slices.IndexFunc(reach, func(n int32) bool { return len(keptAlts(g, int(n))) >= 2 }) if n < 0 { t.Fatal("no reachable node with two alternatives") } - m := reachableNodes(g)[n] + m := reach[n] alts := keptAlts(g, int(m)) g.Nodes[m].Alt = 0 for _, a := range alts { // add puts each first, so the list ends reversed @@ -173,11 +174,12 @@ func TestForestEqualityDetectsPerturbation(t *testing.T) { }) t.Run("rule-position", func(t *testing.T) { - at := slices.IndexFunc(reachableNodes(base), func(n int32) bool { return base.Nodes[n].Sym < 0 }) + reach := reachableNodes(base) + at := slices.IndexFunc(reach, func(n int32) bool { return base.Nodes[n].Sym < 0 }) if at < 0 { t.Fatal("no reachable rule-position node") } - n := reachableNodes(base)[at] + n := reach[at] other := base.Nodes[n].Rule + 1 // any other rule for name, change := range map[string]func(*Node){ "rule": func(nd *Node) { nd.Rule = other }, @@ -255,7 +257,8 @@ func TestForestEqualityV1SideRecognizesPrecedenceRefusals(t *testing.T) { tab := committedTables(t) for _, in := range precedenceRefusals { t.Run(in.name, func(t *testing.T) { - c, err := recognize.Recognize(V1Recognizer(tab), lex.Linear(lexOnly(tab, in.src))) + s, _ := lex.Lex([]byte(in.src), tab.Tokens) + c, err := recognize.Recognize(V1Recognizer(tab), lex.Linear(s)) if err != nil { t.Fatal(err) } @@ -269,12 +272,6 @@ func TestForestEqualityV1SideRecognizesPrecedenceRefusals(t *testing.T) { } } -// lexOnly is src's token stream over tab. -func lexOnly(tab *grammar.Tables, src string) *lex.Stream { - s, _ := lex.Lex([]byte(src), tab.Tokens) - return s -} - // TestForestEqualityV1SideRunsOldPipeline: V1Forest enters its own LibraryOperators and Constrain once per input the // chart accepts, and V1ToyForest its own Constrain once per toy sentence the chart accepts, counted through the V1 // side's stage hooks, so a V1 side wired to production's output, which never passes those hooks, fails. From e9168e685b0d4b51ad10fe0229d9aca5f665d1ef Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:36:32 +0000 Subject: [PATCH 7/8] docs(chart): scope the compared-of-loaded log to the toy and sentence differentials Gate finding F2: TestForestEqualityUnionShortcut logs one input, not a compared-of-loaded count, so the README's claim names the two differentials that make it. The bullet also says the harness test holds that the candidates never enter the V1 side's stages (F1), ahead of the test. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/internal/chart/README.md b/internal/chart/README.md index 29aa55a73..c2127b5bd 100644 --- a/internal/chart/README.md +++ b/internal/chart/README.md @@ -2766,14 +2766,15 @@ grammar's tables and its precedence: no Earley item gains a fact. chart accepts `print $fh [];`, `$a <=> $b <=> $c;` and `1 .. 2 .. 3;` and its `Constrain` refuses each; and `TestForestEqualityV1SideRunsOldPipeline` that the V1 side enters its own `Constrain` and `LibraryOperators` once per - input; `TestForestEqualityHarnessesUseCandidate` swaps in a candidate that - refuses everything and requires the loops to report it, so none compares V1 - with itself. It runs over the toys (`TestForestEqualityToys`), the seed-4 and + input; `TestForestEqualityHarnessesUseCandidate` that the candidates never + enter the V1 side's stages, and that the loops report a swapped-in candidate + that refuses everything, so none compares V1 with itself. It runs over the toys (`TestForestEqualityToys`), the seed-4 and seed-44 generated sentences (`TestForestEqualityGeneratedSentences`) and a constructed input on which V1 keeps one node's alternatives under two contexts with two different non-empty sets, the union `Constrain`'s - `shortcut:` takes (`TestForestEqualityUnionShortcut`). Each logs how many - inputs it compared of how many it loaded. + `shortcut:` takes (`TestForestEqualityUnionShortcut`). The toy and + generated-sentence differentials each log how many inputs they compared of + how many they loaded. Known limits, measured on `perly.y`: none in the parser states or their lookaheads, which are bison's (each reduction's LALR(1) lookahead is From d6fe1e0813100cf6b4589ae65a6f86eaaf3d547e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:36:32 +0000 Subject: [PATCH 8/8] test(chart): require the differential's candidates to stay off the V1 side Gate finding F1: TestForestEqualityHarnessesUseCandidate proved the loops call the candidate variables but not what those variables are, so CandidateForest = V1Forest (M15) or CandidateToyForest = V1ToyForest (M16) left every TestForestEquality test green. The new subtest candidates-are-not-v1 wraps the V1 side's LibraryOperators and Constrain hooks to count, runs CandidateForest on three sources and CandidateToyForest on twenty ladder sentences, and requires no entry. Under M15 and M16 it goes red, entered 6 times each; green as committed. Implements: 01a21447-d0ba-7afb-8ead-01525fd151d7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDSkrXBzd3pd6nDkewof8N --- internal/chart/forest/equality_test.go | 64 +++++++++++++++++++++----- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/internal/chart/forest/equality_test.go b/internal/chart/forest/equality_test.go index d1c76a4ac..26beccf77 100644 --- a/internal/chart/forest/equality_test.go +++ b/internal/chart/forest/equality_test.go @@ -417,20 +417,60 @@ func TestForestEqualityGeneratedSentences(t *testing.T) { } } -// TestForestEqualityHarnessesUseCandidate: with the candidate swapped for one that refuses everything, the toy and -// sentence loops report every input V1 accepts, so neither compares V1 with itself. +// TestForestEqualityHarnessesUseCandidate: the candidates never enter the V1 side's stages, so neither is the V1 +// side under another name; and with the candidate swapped for one that refuses everything, the toy and sentence +// loops report every input V1 accepts, so neither compares V1 with itself. func TestForestEqualityHarnessesUseCandidate(t *testing.T) { - src0, toy0 := CandidateForest, CandidateToyForest - t.Cleanup(func() { CandidateForest, CandidateToyForest = src0, toy0 }) - CandidateForest = func(*grammar.Tables, []byte, Scope) (*Forest, Refusal) { return nil, Refusal{Reason: "test"} } - CandidateToyForest = func(*grammar.Tables, *lex.Lattice[lex.None], *Precedence) (*Forest, error) { return nil, nil } + t.Run("candidates-are-not-v1", func(t *testing.T) { + entries := 0 + lib0, con0 := v1LibraryOperators, v1Constrain + t.Cleanup(func() { v1LibraryOperators, v1Constrain = lib0, con0 }) + v1LibraryOperators = func(tab *grammar.Tables, f *Forest, s *lex.Stream, src []byte, scope Scope) int { + entries++ + return lib0(tab, f, s, src, scope) + } + v1Constrain = func(f *Forest, p *Precedence) bool { + entries++ + return con0(f, p) + } + tab := committedTables(t) + accepted := 0 + for _, src := range []string{"1;", "$x = 1 + 2 * 3;", "print $fh [];"} { + if f, _ := CandidateForest(tab, []byte(src), Scope{}); f != nil { + accepted++ + } + } + ty := loadToy(t, "ladder") + for _, s := range ty.sentences[:20] { + f, err := CandidateToyForest(ty.tab, toyLattice(ty.tab, s.words), ty.prec) + if err != nil { + t.Fatal(err) + } + if f != nil { + accepted++ + } + } + if accepted == 0 { + t.Fatal("the candidates accepted nothing, so a V1 stage had nothing to enter") + } + if entries != 0 { + t.Errorf("the candidates entered the V1 side's LibraryOperators or Constrain %d times; want none", entries) + } + }) - if _, accepted, diffs := sentenceDiffs(committedTables(t), []string{"1;", "$x = 1 + 2;", "1 +;"}); accepted != 2 || len(diffs) != accepted { - t.Errorf("sentences: V1 accepts %d, %d reported; want 2 accepted and each reported", accepted, len(diffs)) - } - if _, accepted, diffs := toyDiffs(t, loadToy(t, "ladder")); accepted == 0 || len(diffs) != accepted { - t.Errorf("toys: V1 accepts %d, %d reported; want each accepted sentence reported", accepted, len(diffs)) - } + t.Run("loops-report-a-refusing-candidate", func(t *testing.T) { + src0, toy0 := CandidateForest, CandidateToyForest + t.Cleanup(func() { CandidateForest, CandidateToyForest = src0, toy0 }) + CandidateForest = func(*grammar.Tables, []byte, Scope) (*Forest, Refusal) { return nil, Refusal{Reason: "test"} } + CandidateToyForest = func(*grammar.Tables, *lex.Lattice[lex.None], *Precedence) (*Forest, error) { return nil, nil } + + if _, accepted, diffs := sentenceDiffs(committedTables(t), []string{"1;", "$x = 1 + 2;", "1 +;"}); accepted != 2 || len(diffs) != accepted { + t.Errorf("sentences: V1 accepts %d, %d reported; want 2 accepted and each reported", accepted, len(diffs)) + } + if _, accepted, diffs := toyDiffs(t, loadToy(t, "ladder")); accepted == 0 || len(diffs) != accepted { + t.Errorf("toys: V1 accepts %d, %d reported; want each accepted sentence reported", accepted, len(diffs)) + } + }) } // contextAltSets is, for each node of f, the alternatives each of its contexts keeps on its own under V1's