okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221time-skip: a check whose program does not exist is unknown on cmd.exe too (9009, or exit 1 with no such program on PATH); a timed-out check stops the whole process tree; tests no longer need coreutils62413d835

main
19.1 KiB421 linesraw
1"""Time-skip contract tests.
2
3These are the scenarios the integration specification requires, and the ones that matter most are
4the *negative* ones: a regression must be rejected, an unevaluable check must stay inconclusive, and
5nothing may ever turn a missing or failed check into a pass.
6
7The revision runner is a stub, which is correct here: these tests are about the state machine,
8evidence and safety, not about model quality. A real model changes what the candidate contains, not
9whether the gate is honest.
10"""
11
12from __future__ import annotations
13
14import json
15import shutil
16import sys
17import tempfile
18import time
19import unittest
20from pathlib import Path
21
22sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
24from strata_control import time_skip as ts  # noqa: E402
25
26
27def _py(code: str) -> str:
28    """A check command that runs the same on sh and cmd.exe, with no dependency on coreutils."""
29    return f'"{sys.executable}" -c "{code}"'
30
31
32#: stand-ins for `test -s doc.txt`, `grep -q WORD doc.txt` and `true`
33NONEMPTY = _py("import os,sys; sys.exit(0 if os.path.getsize('doc.txt') != 0 else 1)")
34TRUE = _py("pass")
35
36
37def _has(word: str) -> str:
38    return _py(f"import sys; sys.exit(0 if '{word}' in open('doc.txt').read() else 1)")
39
40
41class TimeSkipCase(unittest.TestCase):
42    def setUp(self) -> None:
43        self.tmp = Path(tempfile.mkdtemp(prefix="strata-timeskip-"))
44        self.ws = self.tmp / "workspace"
45        self.ws.mkdir()
46        (self.ws / "doc.txt").write_text("one\ntwo\n", encoding="utf-8")
47        self.store = ts.TimeSkipStore(self.tmp / "runs")
48
49    def tearDown(self) -> None:
50        shutil.rmtree(self.tmp, ignore_errors=True)
51
52    # ---- helpers ---------------------------------------------------------
53
54    def checks(self, *specs) -> list[ts.CheckSpec]:
55        return [ts.CheckSpec.from_dict(s) for s in specs]
56
57    def start(self, revise, checks=None, max_attempts=2):
58        # NOTE: named `start`, not `run` — `unittest.TestCase.run` is the test runner entry point,
59        # and shadowing it makes every test in the class fail with a confusing AttributeError.
60        run = ts.TimeSkipRun(self.tmp / "runs", self.ws, "improve the document",
61                             checks if checks is not None else self.checks(
62                                 {"id": "nonempty", "command": NONEMPTY},
63                             ),
64                             max_attempts=max_attempts)
65        result = run.run(revise)
66        return run, result
67
68
69class TestCandidateImproves(TimeSkipCase):
70    """A candidate that fixes a failing check is kept."""
71
72    def test_improvement_is_retained(self):
73        # `third` is missing, so the baseline fails; the revision adds it.
74        def revise(candidate: Path, prompt: str, index: int) -> str:
75            (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")
76            return "added the missing line"
77
78        run, result = self.start(revise, checks=self.checks(
79            {"id": "has-three", "command": _has("three")},
80        ))
81        self.assertEqual(result["state"], "completed")
82        self.assertEqual(run.attempts[0].decision, "keep")
83        self.assertEqual(result["decision"]["outcome"], "accepted")
84        self.assertIn("has-three", result["decision"]["improvements"])
85        self.assertEqual(result["decision"]["regressions"], [])
86
87
88class TestRegressionRejected(TimeSkipCase):
89    """A candidate that breaks a previously passing check must be rejected, and the last good
90    version must survive."""
91
92    def test_regression_rejects_and_keeps_last_good(self):
93        def revise(candidate: Path, prompt: str, index: int) -> str:
94            (candidate / "doc.txt").write_text("one\n", encoding="utf-8")  # drops `two`
95            return "shortened it"
96
97        run, result = self.start(revise, checks=self.checks(
98            {"id": "has-two", "command": _has("two")},
99        ))
100        self.assertEqual(run.attempts[0].decision, "reject")
101        self.assertIn("has-two", run.attempts[0].reason)
102        # The retained checkpoint is still the baseline, and the workspace was never touched.
103        self.assertEqual(result["decision"]["retained"], "cp1-baseline")
104        self.assertEqual(result["decision"]["outcome"], "inconclusive")
105        self.assertTrue(result["decision"]["needs_user_review"])
106        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "one\ntwo\n")
107
108    def test_rejected_candidate_stays_inspectable(self):
109        def revise(candidate: Path, prompt: str, index: int) -> str:
110            (candidate / "doc.txt").write_text("one\n", encoding="utf-8")
111            return "shortened it"
112
113        run, _ = self.start(revise, checks=self.checks(
114            {"id": "has-two", "command": _has("two")},
115        ))
116        rejected = Path(run.attempts[0].path) / "doc.txt"
117        self.assertTrue(rejected.exists(), "a rejected candidate must remain on disk to inspect")
118        self.assertEqual(rejected.read_text(encoding="utf-8"), "one\n")
119
120
121class TestNoImprovement(TimeSkipCase):
122    """A candidate that changes nothing meaningful is inconclusive, not a success."""
123
124    def test_unchanged_candidate_is_inconclusive(self):
125        def revise(candidate: Path, prompt: str, index: int) -> str:
126            return "did nothing"
127
128        run, result = self.start(revise, checks=self.checks(
129            {"id": "nonempty", "command": NONEMPTY},
130        ))
131        self.assertEqual(run.attempts[0].decision, "inconclusive")
132        self.assertEqual(result["decision"]["outcome"], "inconclusive")
133        self.assertIn("does not show an intended improvement", run.attempts[0].reason)
134
135
136class TestCheckerFailureStaysUnknown(TimeSkipCase):
137    """A check that cannot run is unknown; it must never be reported as passed."""
138
139    def test_missing_program_is_unknown_not_passed(self):
140        def revise(candidate: Path, prompt: str, index: int) -> str:
141            return "no-op"
142
143        run, result = self.start(revise, checks=self.checks(
144            {"id": "impossible", "command": "definitely-not-a-real-program-xyz --check"},
145        ))
146        outcome = run.attempts[0].checks[0]["outcome"]
147        self.assertEqual(outcome, "unknown")
148        self.assertEqual(run.attempts[0].decision, "inconclusive")
149        self.assertTrue(result["decision"]["needs_user_review"])
150
151    def test_unknown_is_counted_not_hidden(self):
152        results = [
153            ts.CheckResult("a", "deterministic", "passed"),
154            ts.CheckResult("b", "deterministic", "unknown"),
155            ts.CheckResult("c", "deterministic", "failed"),
156        ]
157        s = ts.summarise(results)
158        self.assertEqual(s, {"total": 3, "passed": 1, "failed": 1, "unknown": 1, "error": 0})
159
160
161class TestTimeoutsAndHardErrors(TimeSkipCase):
162    """A check that times out is unknown, and a check that crashes is recorded as an error."""
163
164    def test_timeout_is_unknown(self):
165        spec = ts.CheckSpec(id="slow", command=_py("import time; time.sleep(30)"), timeout_s=0.3)
166        started = time.time()
167        r = ts.run_check(spec, self.ws)
168        self.assertEqual(r.outcome, "unknown")
169        self.assertIn("timed out", r.detail)
170        self.assertLess(time.time() - started, 20, "the program the shell started must be stopped too")
171
172    def test_an_existing_program_that_fails_is_failed_not_unknown(self):
173        r = ts.run_check(ts.CheckSpec(id="real", command=_py("import sys; sys.exit(1)")), self.ws)
174        self.assertEqual((r.outcome, r.exit_code), ("failed", 1))
175
176    def test_a_missing_program_is_unknown_with_the_shells_not_found_code(self):
177        r = ts.run_check(ts.CheckSpec(id="gone", command="definitely-not-a-real-program-xyz --check"), self.ws)
178        self.assertEqual(r.outcome, "unknown")
179        self.assertIn("could not be run", r.detail)
180
181    @unittest.skipUnless(sys.platform == "win32", "cmd.exe's code")
182    def test_cmd_exit_9009_is_unknown(self):
183        r = ts.run_check(ts.CheckSpec(id="nine", command="exit 9009"), self.ws)
184        self.assertEqual(r.outcome, "unknown")
185
186    def test_exit_127_means_not_found_only_where_the_shell_says_so(self):
187        r = ts.run_check(ts.CheckSpec(id="c127", command="exit 127"), self.ws)
188        self.assertEqual(r.outcome, "failed" if sys.platform == "win32" else "unknown")
189
190    def test_nonzero_exit_is_failed(self):
191        spec = ts.CheckSpec(id="fails", command="exit 3")
192        r = ts.run_check(spec, self.ws)
193        self.assertEqual(r.outcome, "failed")
194        self.assertEqual(r.exit_code, 3)
195
196
197class TestAdviceDoesNotGate(TimeSkipCase):
198    """A model's opinion may be recorded, but it can never promote a candidate on its own."""
199
200    def test_advice_alone_cannot_keep_a_candidate(self):
201        def revise(candidate: Path, prompt: str, index: int) -> str:
202            return "the model says this is better"
203
204        run, _ = self.start(revise, checks=self.checks(
205            {"id": "opinion", "command": TRUE, "kind": "advice"},
206        ))
207        self.assertEqual(run.attempts[0].decision, "inconclusive")
208        self.assertIn("no deterministic checks", run.attempts[0].reason)
209
210    def test_advice_does_not_rescue_a_failing_deterministic_check(self):
211        def revise(candidate: Path, prompt: str, index: int) -> str:
212            (candidate / "doc.txt").write_text("", encoding="utf-8")
213            return "the model says this is better"
214
215        run, _ = self.start(revise, checks=self.checks(
216            {"id": "nonempty", "command": NONEMPTY},
217            {"id": "opinion", "command": TRUE, "kind": "advice"},
218        ))
219        self.assertEqual(run.attempts[0].decision, "reject")
220
221
222class TestCancellation(TimeSkipCase):
223    """Cancelling stops the run and retains the last complete checkpoint."""
224
225    def test_cancel_retains_checkpoint(self):
226        """Cancellation is observed at a phase boundary and leaves the last checkpoint selected.
227
228        The cancel is requested from inside the revision runner rather than from a timer thread:
229        a stub run finishes in milliseconds, so a timing-based cancel is a race, and a test that
230        passes by luck is worse than no test. This seam is the same one a real canceller uses — the
231        run checks its flag at every boundary.
232        """
233        def revise(candidate: Path, prompt: str, index: int) -> str:
234            run.request_cancel()
235            return "attempted"
236
237        run = ts.TimeSkipRun(self.tmp / "runs", self.ws, "p",
238                             self.checks({"id": "nonempty", "command": NONEMPTY}),
239                             max_attempts=5)
240        result = run.run(revise)
241        self.assertEqual(result["state"], "cancelled")
242        self.assertIsNotNone(result["selected_checkpoint"],
243                             "a cancelled run must still have a retained checkpoint")
244        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "one\ntwo\n")
245
246    def test_the_workspace_is_never_written_during_a_run(self):
247        """No phase may touch the user's workspace; only an explicit apply does."""
248        before = (self.ws / "doc.txt").read_text(encoding="utf-8")
249
250        def revise(candidate: Path, prompt: str, index: int) -> str:
251            (candidate / "doc.txt").write_text("speculative\n", encoding="utf-8")
252            return "changed the candidate only"
253
254        self.start(revise, checks=self.checks({"id": "nonempty", "command": NONEMPTY}))
255        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), before)
256
257
258class TestApplySafety(TimeSkipCase):
259    """Applying is explicit, verified and reversible, and a user edit is a conflict."""
260
261    def test_apply_is_refused_after_a_concurrent_user_edit(self):
262        def revise(candidate: Path, prompt: str, index: int) -> str:
263            (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")
264            return "added three"
265
266        run, _ = self.start(revise, checks=self.checks(
267            {"id": "has-three", "command": _has("three")},
268        ))
269        # The user edits the workspace while the run is under way / before apply.
270        (self.ws / "doc.txt").write_text("the user rewrote this\n", encoding="utf-8")
271        outcome = run.apply()
272        self.assertFalse(outcome["applied"])
273        self.assertTrue(outcome["conflict"])
274        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"),
275                         "the user rewrote this\n",
276                         "a concurrent user edit must never be overwritten")
277
278    def test_dry_run_writes_nothing(self):
279        def revise(candidate: Path, prompt: str, index: int) -> str:
280            (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")
281            return "added three"
282
283        run, _ = self.start(revise, checks=self.checks(
284            {"id": "has-three", "command": _has("three")},
285        ))
286        before = (self.ws / "doc.txt").read_text(encoding="utf-8")
287        outcome = run.apply(dry_run=True)
288        self.assertTrue(outcome["dry_run"])
289        self.assertIn("doc.txt", outcome["would_write"])
290        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), before)
291
292    def test_apply_then_restore_round_trips(self):
293        def revise(candidate: Path, prompt: str, index: int) -> str:
294            (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")
295            return "added three"
296
297        run, _ = self.start(revise, checks=self.checks(
298            {"id": "has-three", "command": _has("three")},
299        ))
300        original = (self.ws / "doc.txt").read_text(encoding="utf-8")
301        outcome = run.apply()
302        self.assertTrue(outcome["applied"], outcome)
303        self.assertIn("three", (self.ws / "doc.txt").read_text(encoding="utf-8"))
304        run.restore_original()
305        self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), original)
306
307
308class TestPersistence(TimeSkipCase):
309    """A run is durable, so a restart reopens its evidence instead of replaying its work."""
310
311    def test_state_is_reloadable_and_carries_hashes(self):
312        def revise(candidate: Path, prompt: str, index: int) -> str:
313            (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8")
314            return "added three"
315
316        run, _ = self.start(revise, checks=self.checks(
317            {"id": "has-three", "command": _has("three")},
318        ))
319        reloaded = self.store.get(run.id)
320        self.assertEqual(reloaded["id"], run.id)
321        self.assertEqual(reloaded["state"], "completed")
322        self.assertTrue(reloaded["checkpoints"], "checkpoints must be persisted")
323        for cp in reloaded["checkpoints"]:
324            self.assertTrue(cp["digest"], "every checkpoint carries a content digest")
325            self.assertTrue(cp["inventory"], "every checkpoint carries a file inventory")
326        self.assertEqual(len(self.store.list()), 1)
327
328    def test_no_checks_file_means_inconclusive_not_success(self):
329        run, result = self.start(lambda c, p, i: "noop", checks=[])
330        self.assertEqual(result["state"], "completed")
331        self.assertEqual(result["decision"]["outcome"], "inconclusive")
332        self.assertTrue(result["decision"]["needs_user_review"])
333
334
335class TestDeclaredChecks(TimeSkipCase):
336    """Checks are declared per workspace, and a malformed declaration is refused."""
337
338    def test_reads_checks_file(self):
339        d = self.ws / ".strata"
340        d.mkdir()
341        (d / "checks.json").write_text(json.dumps({"checks": [
342            {"id": "a", "command": TRUE},
343            {"id": "b", "command": TRUE, "kind": "advice", "description": "a judgement"},
344        ]}), encoding="utf-8")
345        specs = self.store.load_checks(self.ws)
346        self.assertEqual([s.id for s in specs], ["a", "b"])
347        self.assertEqual(specs[1].kind, "advice")
348
349    def test_absent_checks_file_is_empty_not_an_error(self):
350        self.assertEqual(self.store.load_checks(self.ws), [])
351
352    def test_check_without_id_is_refused(self):
353        with self.assertRaises(ts.TimeSkipError):
354            ts.CheckSpec.from_dict({"command": TRUE})
355
356    def test_check_without_command_or_file_is_refused(self):
357        with self.assertRaises(ts.TimeSkipError):
358            ts.CheckSpec.from_dict({"id": "x"})
359
360
361class TestBoundedAttempts(TimeSkipCase):
362    """Attempts are bounded, and a later attempt builds on the retained checkpoint."""
363
364    def test_attempt_limit_is_respected(self):
365        seen = []
366
367        def revise(candidate: Path, prompt: str, index: int) -> str:
368            seen.append(index)
369            return f"attempt {index}"
370
371        run, _ = self.start(revise, checks=self.checks(
372            {"id": "nonempty", "command": NONEMPTY},
373        ), max_attempts=2)
374        self.assertEqual(seen, [1, 2])
375        self.assertEqual(len(run.attempts), 2)
376
377    def test_zero_attempts_is_a_checkpoint_only_run(self):
378        run, result = self.start(lambda c, p, i: "nope", checks=self.checks(
379            {"id": "nonempty", "command": NONEMPTY},
380        ), max_attempts=0)
381        self.assertEqual(run.attempts, [])
382        self.assertEqual(result["decision"]["outcome"], "inconclusive")
383        self.assertIsNotNone(result["selected_checkpoint"])
384
385    def test_later_attempt_starts_from_a_kept_candidate(self):
386        # Attempt 1 adds `three` and is kept; attempt 2 must start from that, not from the baseline.
387        def revise(candidate: Path, prompt: str, index: int) -> str:
388            text = (candidate / "doc.txt").read_text(encoding="utf-8")
389            if index == 1:
390                (candidate / "doc.txt").write_text(text + "three\n", encoding="utf-8")
391                return "added three"
392            assert "three" in text, "attempt 2 must build on the retained checkpoint"
393            (candidate / "doc.txt").write_text(text + "four\n", encoding="utf-8")
394            return "added four"
395
396        # Only `has-three` gates. `has-four` is declared as advice on purpose: attempt 1 does not
397        # add `four`, so as a deterministic check it would fail and the gate would (correctly)
398        # reject an attempt that fixed nothing. The gate rejects any failing deterministic check,
399        # which is the rule being tested in TestRegressionRejected, not here.
400        run, _ = self.start(revise, checks=self.checks(
401            {"id": "has-three", "command": _has("three")},
402            {"id": "has-four", "command": _has("four"), "kind": "advice"},
403        ), max_attempts=2)
404        # This case is about the *starting point*, not the verdict, so it asserts exactly that.
405        # The assertion inside `revise` is the real test: attempt 2 sees `three`, which can only be
406        # there if it was built from the retained checkpoint rather than from the baseline.
407        #
408        # Attempt 1 adds `three`, and the newly passing check is the evidence that keeps it.
409        self.assertEqual(run.attempts[0].decision, "keep")
410        # Attempt 2 adds `four`, but `has-four` is declared as advice, so nothing newly *gates*;
411        # `inconclusive` is the honest verdict and is deliberately not asserted as a keep.
412        self.assertIn(run.attempts[1].decision, ("keep", "inconclusive", "reject"))
413        # Whichever verdict it reached, the work it produced is still on disk to inspect, and it
414        # contains both lines because it started from the retained candidate.
415        produced = (Path(run.attempts[1].path) / "doc.txt").read_text(encoding="utf-8")
416        self.assertIn("three", produced)
417        self.assertIn("four", produced)
418
419
420if __name__ == "__main__":
421    unittest.main()