okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
62413d835
main
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.""" 29return 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 : 38return _py (f"import sys; sys.exit(0 if ' { word } ' in open('doc.txt').read() else 1)" ) 39 40 41class TimeSkipCase (unittest .TestCase ): 42def setUp (self )-> None : 43self .tmp = Path (tempfile .mkdtemp (prefix = "strata-timeskip-" )) 44self .ws = self .tmp / "workspace" 45self .ws .mkdir () 46 (self .ws / "doc.txt" ).write_text ("one\ntwo\n" ,encoding = "utf-8" ) 47self .store = ts .TimeSkipStore (self .tmp / "runs" ) 48 49def tearDown (self )-> None : 50shutil .rmtree (self .tmp ,ignore_errors = True ) 51 52# ---- helpers --------------------------------------------------------- 53 54def checks (self ,* specs )-> list [ts .CheckSpec ]: 55return [ts .CheckSpec .from_dict (s )for s in specs ] 56 57def 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. 60run = ts .TimeSkipRun (self .tmp / "runs" ,self .ws ,"improve the document" , 61checks if checks is not None else self .checks ( 62 {"id" :"nonempty" ,"command" :NONEMPTY }, 63 ), 64max_attempts = max_attempts ) 65result = run .run (revise ) 66return run ,result 67 68 69class TestCandidateImproves (TimeSkipCase ): 70"""A candidate that fixes a failing check is kept.""" 71 72def test_improvement_is_retained (self ): 73# `third` is missing, so the baseline fails; the revision adds it. 74def revise (candidate :Path ,prompt :str ,index :int )-> str : 75 (candidate / "doc.txt" ).write_text ("one\ntwo\nthree\n" ,encoding = "utf-8" ) 76return "added the missing line" 77 78run ,result = self .start (revise ,checks = self .checks ( 79 {"id" :"has-three" ,"command" :_has ("three" )}, 80 )) 81self .assertEqual (result ["state" ],"completed" ) 82self .assertEqual (run .attempts [0 ].decision ,"keep" ) 83self .assertEqual (result ["decision" ]["outcome" ],"accepted" ) 84self .assertIn ("has-three" ,result ["decision" ]["improvements" ]) 85self .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 90version must survive.""" 91 92def test_regression_rejects_and_keeps_last_good (self ): 93def revise (candidate :Path ,prompt :str ,index :int )-> str : 94 (candidate / "doc.txt" ).write_text ("one\n" ,encoding = "utf-8" )# drops `two` 95return "shortened it" 96 97run ,result = self .start (revise ,checks = self .checks ( 98 {"id" :"has-two" ,"command" :_has ("two" )}, 99 )) 100self .assertEqual (run .attempts [0 ].decision ,"reject" ) 101self .assertIn ("has-two" ,run .attempts [0 ].reason ) 102# The retained checkpoint is still the baseline, and the workspace was never touched. 103self .assertEqual (result ["decision" ]["retained" ],"cp1-baseline" ) 104self .assertEqual (result ["decision" ]["outcome" ],"inconclusive" ) 105self .assertTrue (result ["decision" ]["needs_user_review" ]) 106self .assertEqual ((self .ws / "doc.txt" ).read_text (encoding = "utf-8" ),"one\ntwo\n" ) 107 108def test_rejected_candidate_stays_inspectable (self ): 109def revise (candidate :Path ,prompt :str ,index :int )-> str : 110 (candidate / "doc.txt" ).write_text ("one\n" ,encoding = "utf-8" ) 111return "shortened it" 112 113run ,_ = self .start (revise ,checks = self .checks ( 114 {"id" :"has-two" ,"command" :_has ("two" )}, 115 )) 116rejected = Path (run .attempts [0 ].path )/ "doc.txt" 117self .assertTrue (rejected .exists (),"a rejected candidate must remain on disk to inspect" ) 118self .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 124def test_unchanged_candidate_is_inconclusive (self ): 125def revise (candidate :Path ,prompt :str ,index :int )-> str : 126return "did nothing" 127 128run ,result = self .start (revise ,checks = self .checks ( 129 {"id" :"nonempty" ,"command" :NONEMPTY }, 130 )) 131self .assertEqual (run .attempts [0 ].decision ,"inconclusive" ) 132self .assertEqual (result ["decision" ]["outcome" ],"inconclusive" ) 133self .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 139def test_missing_program_is_unknown_not_passed (self ): 140def revise (candidate :Path ,prompt :str ,index :int )-> str : 141return "no-op" 142 143run ,result = self .start (revise ,checks = self .checks ( 144 {"id" :"impossible" ,"command" :"definitely-not-a-real-program-xyz --check" }, 145 )) 146outcome = run .attempts [0 ].checks [0 ]["outcome" ] 147self .assertEqual (outcome ,"unknown" ) 148self .assertEqual (run .attempts [0 ].decision ,"inconclusive" ) 149self .assertTrue (result ["decision" ]["needs_user_review" ]) 150 151def test_unknown_is_counted_not_hidden (self ): 152results = [ 153ts .CheckResult ("a" ,"deterministic" ,"passed" ), 154ts .CheckResult ("b" ,"deterministic" ,"unknown" ), 155ts .CheckResult ("c" ,"deterministic" ,"failed" ), 156 ] 157s = ts .summarise (results ) 158self .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 164def test_timeout_is_unknown (self ): 165spec = ts .CheckSpec (id = "slow" ,command = _py ("import time; time.sleep(30)" ),timeout_s = 0.3 ) 166started = time .time () 167r = ts .run_check (spec ,self .ws ) 168self .assertEqual (r .outcome ,"unknown" ) 169self .assertIn ("timed out" ,r .detail ) 170self .assertLess (time .time ()- started ,20 ,"the program the shell started must be stopped too" ) 171 172def test_an_existing_program_that_fails_is_failed_not_unknown (self ): 173r = ts .run_check (ts .CheckSpec (id = "real" ,command = _py ("import sys; sys.exit(1)" )),self .ws ) 174self .assertEqual ((r .outcome ,r .exit_code ), ("failed" ,1 )) 175 176def test_a_missing_program_is_unknown_with_the_shells_not_found_code (self ): 177r = ts .run_check (ts .CheckSpec (id = "gone" ,command = "definitely-not-a-real-program-xyz --check" ),self .ws ) 178self .assertEqual (r .outcome ,"unknown" ) 179self .assertIn ("could not be run" ,r .detail ) 180 181@ unittest . skipUnless ( sys . platform == "win32" , "cmd.exe's code" ) 182def test_cmd_exit_9009_is_unknown (self ): 183r = ts .run_check (ts .CheckSpec (id = "nine" ,command = "exit 9009" ),self .ws ) 184self .assertEqual (r .outcome ,"unknown" ) 185 186def test_exit_127_means_not_found_only_where_the_shell_says_so (self ): 187r = ts .run_check (ts .CheckSpec (id = "c127" ,command = "exit 127" ),self .ws ) 188self .assertEqual (r .outcome ,"failed" if sys .platform == "win32" else "unknown" ) 189 190def test_nonzero_exit_is_failed (self ): 191spec = ts .CheckSpec (id = "fails" ,command = "exit 3" ) 192r = ts .run_check (spec ,self .ws ) 193self .assertEqual (r .outcome ,"failed" ) 194self .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 200def test_advice_alone_cannot_keep_a_candidate (self ): 201def revise (candidate :Path ,prompt :str ,index :int )-> str : 202return "the model says this is better" 203 204run ,_ = self .start (revise ,checks = self .checks ( 205 {"id" :"opinion" ,"command" :TRUE ,"kind" :"advice" }, 206 )) 207self .assertEqual (run .attempts [0 ].decision ,"inconclusive" ) 208self .assertIn ("no deterministic checks" ,run .attempts [0 ].reason ) 209 210def test_advice_does_not_rescue_a_failing_deterministic_check (self ): 211def revise (candidate :Path ,prompt :str ,index :int )-> str : 212 (candidate / "doc.txt" ).write_text ("" ,encoding = "utf-8" ) 213return "the model says this is better" 214 215run ,_ = self .start (revise ,checks = self .checks ( 216 {"id" :"nonempty" ,"command" :NONEMPTY }, 217 {"id" :"opinion" ,"command" :TRUE ,"kind" :"advice" }, 218 )) 219self .assertEqual (run .attempts [0 ].decision ,"reject" ) 220 221 222class TestCancellation (TimeSkipCase ): 223"""Cancelling stops the run and retains the last complete checkpoint.""" 224 225def test_cancel_retains_checkpoint (self ): 226"""Cancellation is observed at a phase boundary and leaves the last checkpoint selected. 227 228The cancel is requested from inside the revision runner rather than from a timer thread: 229a stub run finishes in milliseconds, so a timing-based cancel is a race, and a test that 230passes by luck is worse than no test. This seam is the same one a real canceller uses — the 231run checks its flag at every boundary. 232""" 233def revise (candidate :Path ,prompt :str ,index :int )-> str : 234run .request_cancel () 235return "attempted" 236 237run = ts .TimeSkipRun (self .tmp / "runs" ,self .ws ,"p" , 238self .checks ({"id" :"nonempty" ,"command" :NONEMPTY }), 239max_attempts = 5 ) 240result = run .run (revise ) 241self .assertEqual (result ["state" ],"cancelled" ) 242self .assertIsNotNone (result ["selected_checkpoint" ], 243"a cancelled run must still have a retained checkpoint" ) 244self .assertEqual ((self .ws / "doc.txt" ).read_text (encoding = "utf-8" ),"one\ntwo\n" ) 245 246def test_the_workspace_is_never_written_during_a_run (self ): 247"""No phase may touch the user's workspace; only an explicit apply does.""" 248before = (self .ws / "doc.txt" ).read_text (encoding = "utf-8" ) 249 250def revise (candidate :Path ,prompt :str ,index :int )-> str : 251 (candidate / "doc.txt" ).write_text ("speculative\n" ,encoding = "utf-8" ) 252return "changed the candidate only" 253 254self .start (revise ,checks = self .checks ({"id" :"nonempty" ,"command" :NONEMPTY })) 255self .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 261def test_apply_is_refused_after_a_concurrent_user_edit (self ): 262def revise (candidate :Path ,prompt :str ,index :int )-> str : 263 (candidate / "doc.txt" ).write_text ("one\ntwo\nthree\n" ,encoding = "utf-8" ) 264return "added three" 265 266run ,_ = 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" ) 271outcome = run .apply () 272self .assertFalse (outcome ["applied" ]) 273self .assertTrue (outcome ["conflict" ]) 274self .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 278def test_dry_run_writes_nothing (self ): 279def revise (candidate :Path ,prompt :str ,index :int )-> str : 280 (candidate / "doc.txt" ).write_text ("one\ntwo\nthree\n" ,encoding = "utf-8" ) 281return "added three" 282 283run ,_ = self .start (revise ,checks = self .checks ( 284 {"id" :"has-three" ,"command" :_has ("three" )}, 285 )) 286before = (self .ws / "doc.txt" ).read_text (encoding = "utf-8" ) 287outcome = run .apply (dry_run = True ) 288self .assertTrue (outcome ["dry_run" ]) 289self .assertIn ("doc.txt" ,outcome ["would_write" ]) 290self .assertEqual ((self .ws / "doc.txt" ).read_text (encoding = "utf-8" ),before ) 291 292def test_apply_then_restore_round_trips (self ): 293def revise (candidate :Path ,prompt :str ,index :int )-> str : 294 (candidate / "doc.txt" ).write_text ("one\ntwo\nthree\n" ,encoding = "utf-8" ) 295return "added three" 296 297run ,_ = self .start (revise ,checks = self .checks ( 298 {"id" :"has-three" ,"command" :_has ("three" )}, 299 )) 300original = (self .ws / "doc.txt" ).read_text (encoding = "utf-8" ) 301outcome = run .apply () 302self .assertTrue (outcome ["applied" ],outcome ) 303self .assertIn ("three" , (self .ws / "doc.txt" ).read_text (encoding = "utf-8" )) 304run .restore_original () 305self .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 311def test_state_is_reloadable_and_carries_hashes (self ): 312def revise (candidate :Path ,prompt :str ,index :int )-> str : 313 (candidate / "doc.txt" ).write_text ("one\ntwo\nthree\n" ,encoding = "utf-8" ) 314return "added three" 315 316run ,_ = self .start (revise ,checks = self .checks ( 317 {"id" :"has-three" ,"command" :_has ("three" )}, 318 )) 319reloaded = self .store .get (run .id ) 320self .assertEqual (reloaded ["id" ],run .id ) 321self .assertEqual (reloaded ["state" ],"completed" ) 322self .assertTrue (reloaded ["checkpoints" ],"checkpoints must be persisted" ) 323for cp in reloaded ["checkpoints" ]: 324self .assertTrue (cp ["digest" ],"every checkpoint carries a content digest" ) 325self .assertTrue (cp ["inventory" ],"every checkpoint carries a file inventory" ) 326self .assertEqual (len (self .store .list ()),1 ) 327 328def test_no_checks_file_means_inconclusive_not_success (self ): 329run ,result = self .start (lambda c ,p ,i :"noop" ,checks = []) 330self .assertEqual (result ["state" ],"completed" ) 331self .assertEqual (result ["decision" ]["outcome" ],"inconclusive" ) 332self .assertTrue (result ["decision" ]["needs_user_review" ]) 333 334 335class TestDeclaredChecks (TimeSkipCase ): 336"""Checks are declared per workspace, and a malformed declaration is refused.""" 337 338def test_reads_checks_file (self ): 339d = self .ws / ".strata" 340d .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" ) 345specs = self .store .load_checks (self .ws ) 346self .assertEqual ([s .id for s in specs ], ["a" ,"b" ]) 347self .assertEqual (specs [1 ].kind ,"advice" ) 348 349def test_absent_checks_file_is_empty_not_an_error (self ): 350self .assertEqual (self .store .load_checks (self .ws ), []) 351 352def test_check_without_id_is_refused (self ): 353with self .assertRaises (ts .TimeSkipError ): 354ts .CheckSpec .from_dict ({"command" :TRUE }) 355 356def test_check_without_command_or_file_is_refused (self ): 357with self .assertRaises (ts .TimeSkipError ): 358ts .CheckSpec .from_dict ({"id" :"x" }) 359 360 361class TestBoundedAttempts (TimeSkipCase ): 362"""Attempts are bounded, and a later attempt builds on the retained checkpoint.""" 363 364def test_attempt_limit_is_respected (self ): 365seen = [] 366 367def revise (candidate :Path ,prompt :str ,index :int )-> str : 368seen .append (index ) 369return f"attempt { index } " 370 371run ,_ = self .start (revise ,checks = self .checks ( 372 {"id" :"nonempty" ,"command" :NONEMPTY }, 373 ),max_attempts = 2 ) 374self .assertEqual (seen , [1 ,2 ]) 375self .assertEqual (len (run .attempts ),2 ) 376 377def test_zero_attempts_is_a_checkpoint_only_run (self ): 378run ,result = self .start (lambda c ,p ,i :"nope" ,checks = self .checks ( 379 {"id" :"nonempty" ,"command" :NONEMPTY }, 380 ),max_attempts = 0 ) 381self .assertEqual (run .attempts , []) 382self .assertEqual (result ["decision" ]["outcome" ],"inconclusive" ) 383self .assertIsNotNone (result ["selected_checkpoint" ]) 384 385def 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. 387def revise (candidate :Path ,prompt :str ,index :int )-> str : 388text = (candidate / "doc.txt" ).read_text (encoding = "utf-8" ) 389if index == 1 : 390 (candidate / "doc.txt" ).write_text (text + "three\n" ,encoding = "utf-8" ) 391return "added three" 392assert "three" in text ,"attempt 2 must build on the retained checkpoint" 393 (candidate / "doc.txt" ).write_text (text + "four\n" ,encoding = "utf-8" ) 394return "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. 400run ,_ = 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. 409self .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. 412self .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. 415produced = (Path (run .attempts [1 ].path )/ "doc.txt" ).read_text (encoding = "utf-8" ) 416self .assertIn ("three" ,produced ) 417self .assertIn ("four" ,produced ) 418 419 420if __name__ == "__main__" : 421unittest .main ()