From 507de00c8516f2fbe166989bcb0584fa05445dbc Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 19 Nov 2026 15:39:50 -0500 Subject: [PATCH] test(model_loop): model repetition runs and check similarity against difflib `repetition.with_settings` builds a watch without reading saved settings, so repetition_test can replay generated steps (repeated, changed, waiting-only, multi-cell) against a model of the documented run rule. A new `similarity` contract sends generated string pairs, including long popular runs that trigger autojunk and multibyte scalars, to Python's difflib and checks `similarity.at_least` at, and just either side of, each ratio. Nothing checked that claim before. Replaces these end-to-end cases: - repetition_test.test_steps_whose_code_changes_are_not_repeats (a streak surviving changed code) by repetition_test and the contract; - repetition_test.test_steps_that_only_wait_are_not_repeats (waiting-only steps counted) by repetition_test. The kept cases cover the kernel trace naming a step's bindings and the note reaching the model and the transcript. --- .../src/albedo/model_loop/repetition.gleam | 5 + apps/albedo/test/albedo/contract/runner.gleam | 6 + .../test/albedo/contract/similarity.gleam | 106 ++++++++++++++ .../albedo/model_loop/repetition_test.gleam | 131 ++++++++++++++++++ e2e/repetition_test.py | 36 +---- test/contract/similarity.py | 27 ++++ 6 files changed, 279 insertions(+), 32 deletions(-) create mode 100644 apps/albedo/test/albedo/contract/similarity.gleam create mode 100644 apps/albedo/test/albedo/model_loop/repetition_test.gleam create mode 100644 test/contract/similarity.py diff --git a/apps/albedo/src/albedo/model_loop/repetition.gleam b/apps/albedo/src/albedo/model_loop/repetition.gleam index 1327dc097..d1e3107f0 100644 --- a/apps/albedo/src/albedo/model_loop/repetition.gleam +++ b/apps/albedo/src/albedo/model_loop/repetition.gleam @@ -40,6 +40,11 @@ pub fn new() -> Watch { Watch(None, None, 0) } +/// A watch that uses `settings` instead of reading the saved ones. +pub fn with_settings(settings: Settings) -> Watch { + Watch(Some(settings), None, 0) +} + /// Bindings that only wait for or read back earlier work: a step that calls /// nothing else is waiting, not repeating, and ends a run. const waiting = [ diff --git a/apps/albedo/test/albedo/contract/runner.gleam b/apps/albedo/test/albedo/contract/runner.gleam index 36de6ac06..5d6a7e8cd 100644 --- a/apps/albedo/test/albedo/contract/runner.gleam +++ b/apps/albedo/test/albedo/contract/runner.gleam @@ -11,6 +11,7 @@ import albedo/contract/kernel_frames import albedo/contract/peer.{type Peer} +import albedo/contract/similarity import albedo_env import albedo_protect import gleam/dynamic/decode @@ -31,6 +32,11 @@ fn properties() -> List(#(String, String, fn(Peer) -> Nil)) { "the kernel refuses broken daemon frames", kernel_frames.the_kernel_refuses_broken_daemon_frames, ), + #( + similarity.contract, + "code similarity agrees with difflib", + similarity.at_least_agrees_with_difflib, + ), ] } diff --git a/apps/albedo/test/albedo/contract/similarity.gleam b/apps/albedo/test/albedo/contract/similarity.gleam new file mode 100644 index 000000000..d5691cbe3 --- /dev/null +++ b/apps/albedo/test/albedo/contract/similarity.gleam @@ -0,0 +1,106 @@ +//// Code similarity, the daemon's side of the contract. +//// +//// `similarity.at_least` reimplements `difflib.SequenceMatcher(None, a, +//// b).ratio() >= threshold`, with its autojunk heuristic, over Unicode +//// scalars, and repetition detection relies on it agreeing with the +//// documented difflib ratio. Only Python's difflib can say whether it does, +//// so the property sends each batch of generated pairs to +//// `test/contract/similarity.py` and compares the answers. + +import albedo/contract/peer.{type Peer} +import albedo/model_loop/similarity +import albedo_property +import gleam/dynamic/decode +import gleam/float +import gleam/int +import gleam/json +import gleam/list +import gleam/string +import qcheck.{type Generator} + +pub const contract = "similarity" + +/// Scalars from a small alphabet, so pairs share runs, plus multibyte ones. +fn text() -> Generator(String) { + let scalar = + qcheck.from_generators(qcheck.return("a"), [ + qcheck.return("b"), + qcheck.return("c"), + qcheck.return(" "), + qcheck.return("\n"), + qcheck.return("é"), + qcheck.return("日"), + qcheck.return("😀"), + ]) + let chunk = + qcheck.from_weighted_generators( + #(4, qcheck.map(qcheck.list_from(scalar), string.concat)), + [ + // A long run of one scalar makes it popular: past 200 scalars, + // autojunk ignores scalars that make up more than 1% of the text. + #(1, qcheck.map2(scalar, qcheck.bounded_int(150, 400), string.repeat)), + ], + ) + qcheck.generic_list(chunk, qcheck.bounded_int(0, 4)) + |> qcheck.map(string.concat) +} + +/// A pair that is often nearly alike: `b` is `a` with an edit. +fn pair() -> Generator(#(String, String)) { + let edited = { + use a, cut, insert <- qcheck.map3( + text(), + qcheck.bounded_int(0, 400), + text(), + ) + let length = string.length(a) + let at = case length { + 0 -> 0 + _ -> cut % { length + 1 } + } + #(a, string.slice(a, 0, at) <> insert <> string.drop_start(a, at + 3)) + } + qcheck.from_weighted_generators(#(3, edited), [ + #(1, qcheck.tuple2(text(), text())), + ]) +} + +pub fn at_least_agrees_with_difflib(peer: Peer) -> Nil { + use pairs <- albedo_property.run( + 20, + qcheck.generic_list(pair(), qcheck.bounded_int(1, 40)), + ) + let ratios = + peer.call( + peer, + contract, + "ratios", + list.map(pairs, fn(pair) { + json.object([#("a", json.string(pair.0)), #("b", json.string(pair.1))]) + }), + ) + list.zip(pairs, ratios) + |> list.each(fn(entry) { + let #(#(a, b), ratio) = entry + let assert Ok(ratio) = + decode.run( + ratio, + decode.one_of(decode.float, [decode.map(decode.int, int.to_float)]), + ) + // At the ratio itself and just either side of it, plus thresholds + // repetition uses. Settings keep thresholds within (0, 1]. + [ratio, ratio -. 1.0e-9, ratio +. 1.0e-9, 0.8, 0.5] + |> list.filter(fn(threshold) { threshold >. 0.0 && threshold <=. 1.0 }) + |> list.each(fn(threshold) { + assert similarity.at_least(a, b, threshold) == { ratio >=. threshold } + as { + "difflib ratio " + <> float.to_string(ratio) + <> " threshold " + <> float.to_string(threshold) + <> " for " + <> string.inspect(#(a, b)) + } + }) + }) +} diff --git a/apps/albedo/test/albedo/model_loop/repetition_test.gleam b/apps/albedo/test/albedo/model_loop/repetition_test.gleam new file mode 100644 index 000000000..906a76988 --- /dev/null +++ b/apps/albedo/test/albedo/model_loop/repetition_test.gleam @@ -0,0 +1,131 @@ +//// Repetition detection over a turn's steps (`repetition.step`). +//// +//// Defects: a run that never reports, a report one step early or late, a +//// streak that survives a step with different bindings, different code, or +//// only waiting, and a run that keeps reporting on every step after the +//// first report. The rule is the module's documentation, written as a model: +//// a run counts consecutive steps that call the same bindings (other than +//// the waiting ones) with code at least `similarity` percent alike, and is +//// reported, then restarted, at every `steps`-th step. Code variants are +//// either identical or share no scalar, so the model needs no ratio. Whether +//// the ratio itself matches difflib is the `similarity` contract. + +import albedo/model_loop/repetition.{Cell, Repeated, Settings} +import albedo_property +import albedo_sdk/settings +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string +import qcheck.{type Generator} + +const waiting = ["cells.read", "output.read"] + +fn cell() -> Generator(repetition.Cell) { + let calls = + qcheck.generic_list( + qcheck.from_generators(qcheck.return("files.find"), [ + qcheck.return("shell.run"), + qcheck.return("cells.read"), + qcheck.return("output.read"), + ]), + qcheck.bounded_int(0, 2), + ) + // Code that is identical within a variant and shares no scalar but a space + // across them. + let code = + qcheck.from_generators(qcheck.return("aaaa bbbb aaaa"), [ + qcheck.return("xyzxyz qqq"), + qcheck.return("1234 5678 90"), + ]) + qcheck.map2(code, calls, Cell) +} + +/// Steps of one or two cells, so a step's bindings and code are the union of +/// its cells'. Most steps repeat the one before, so runs reach the limit and +/// pass it. +fn steps() -> Generator(List(List(repetition.Cell))) { + let fresh = + qcheck.from_weighted_generators(#(4, qcheck.map(cell(), list.wrap)), [ + #(1, qcheck.generic_list(cell(), qcheck.bounded_int(0, 2))), + ]) + let choice = + qcheck.from_weighted_generators(#(3, qcheck.return(None)), [ + #(1, qcheck.map(fresh, Some)), + ]) + use choices <- qcheck.map(qcheck.generic_list( + choice, + qcheck.bounded_int(0, 30), + )) + let #(steps, _) = + list.fold(choices, #([], []), fn(state, choice) { + let #(steps, previous) = state + let step = option.unwrap(choice, previous) + #([step, ..steps], step) + }) + list.reverse(steps) +} + +/// A step's signature as the documentation states it: its distinct bindings, +/// sorted, and its code, or nothing when it only waits. +fn signature(cells: List(repetition.Cell)) -> Option(#(List(String), String)) { + let calls = + list.flat_map(cells, fn(cell) { cell.calls }) + |> list.unique + |> list.sort(string.compare) + case list.any(calls, fn(call) { !list.contains(waiting, call) }) { + False -> None + True -> + Some(#(calls, string.join(list.map(cells, fn(cell) { cell.code }), "\n"))) + } +} + +/// The reports the model expects after each step. +fn expected( + steps: List(List(repetition.Cell)), + limit: Int, +) -> List(Option(repetition.Repeated)) { + let #(_, _, reports) = + list.fold(steps, #(None, 0, []), fn(state, cells) { + let #(last, run, reports) = state + case signature(cells) { + None -> #(None, 0, [None, ..reports]) + Some(step) -> { + let run = case last == Some(step) { + True -> run + 1 + False -> 1 + } + case run == limit { + True -> #(None, 0, [Some(Repeated(limit, step.0)), ..reports]) + False -> #(Some(step), run, [None, ..reports]) + } + } + } + }) + list.reverse(reports) +} + +pub fn repeats_are_reported_at_every_limit_test() -> Nil { + let generator = qcheck.tuple2(steps(), qcheck.bounded_int(2, 4)) + use #(steps, limit) <- albedo_property.run(300, generator) + let watch = repetition.with_settings(Settings(settings.Limited(limit), 80)) + let #(_, reports) = + list.fold(steps, #(watch, []), fn(state, cells) { + let #(watch, reports) = state + let #(watch, report) = repetition.step(watch, cells) + #(watch, [report, ..reports]) + }) + assert list.reverse(reports) == expected(steps, limit) +} + +/// An unlimited setting never reports. +pub fn an_unlimited_watch_never_reports_test() -> Nil { + use steps <- albedo_property.run(50, steps()) + let watch = repetition.with_settings(Settings(settings.Unlimited, 80)) + let _ = + list.fold(steps, watch, fn(watch, cells) { + let #(watch, report) = repetition.step(watch, cells) + assert report == None + watch + }) + Nil +} diff --git a/e2e/repetition_test.py b/e2e/repetition_test.py index fd4362fce..64d3eb852 100644 --- a/e2e/repetition_test.py +++ b/e2e/repetition_test.py @@ -1,12 +1,12 @@ """A turn whose steps keep calling the same bindings with nearly the same code. Catches: a model looping across the steps of one turn (each reply fine on its -own) going unnoticed, and the opposite, a note for a turn whose steps change -their code or only wait. Only the real loop, kernel and trace together decide -which bindings a step called and when a run of repeats is long enough. +own) going unnoticed. Only the real loop, kernel and trace together decide +which bindings a step called. When a run of steps is a repeat is checked in +apps/albedo/test/albedo/model_loop/repetition_test.gleam, and the similarity +ratio against difflib by the `similarity` contract. """ -import difflib import unittest from harness import Albedo, Provider, python, text @@ -21,18 +21,6 @@ def repeating(step): ) -# Each step searches too, but in code too different from the one before it. -VARIED = [ - "\n".join( - [f"{name} = await files.find({name!r}, '.', max_results={step + 1})"] - + [f"print({name!r} * {k}, len(str({name})))" for k in range(step % 3 + 1)] - ) - for step, name in enumerate( - ["alpha", "brook", "cinder", "dune", "ember", "fjord", "grove", "heath"] - ) -] - - class RepetitionTest(unittest.TestCase): def run_turn(self, cells): def script(request): @@ -78,22 +66,6 @@ class RepetitionTest(unittest.TestCase): self.assertIn("files.find", notes[8][0]) self.assertTrue(shown, "the user sees no repetition note") - def test_steps_whose_code_changes_are_not_repeats(self): - for before, after in zip(VARIED, VARIED[1:]): - self.assertLess(difflib.SequenceMatcher(None, before, after).ratio(), 0.8) - notes, shown = self.run_turn(VARIED) - self.assertEqual(len(notes), 9) - self.assertFalse(any(notes)) - self.assertEqual(shown, []) - - def test_steps_that_only_wait_are_not_repeats(self): - notes, shown = self.run_turn( - [f"print(len(await cells.list()), {step})" for step in range(8)] - ) - self.assertEqual(len(notes), 9) - self.assertFalse(any(notes)) - self.assertEqual(shown, []) - def test_repeating_syntax_error_steps_still_trigger_the_note(self): notes, shown = self.run_turn( [ diff --git a/test/contract/similarity.py b/test/contract/similarity.py new file mode 100644 index 000000000..a0e1888a5 --- /dev/null +++ b/test/contract/similarity.py @@ -0,0 +1,27 @@ +"""Code similarity: the Python side of the contract. + +`albedo/model_loop/similarity.gleam` claims to answer whether +`difflib.SequenceMatcher(None, a, b).ratio() >= threshold`, over Unicode +scalars with autojunk on. ``PYTHON_OPS`` computes that ratio for the Gleam +runner's batches of string pairs. +""" + +from __future__ import annotations + +import difflib +from collections.abc import Callable + + +def _ratios(cases: list[object]) -> list[object]: + results: list[object] = [] + for case in cases: + assert isinstance(case, dict) + a, b = case["a"], case["b"] + assert isinstance(a, str) and isinstance(b, str) + results.append(difflib.SequenceMatcher(None, a, b).ratio()) + return results + + +PYTHON_OPS: dict[str, Callable[[list[object]], list[object]]] = { + "ratios": _ratios, +} -- knotmirror 0.0.1