From c2d68f750d07efb73e6ba09b00d4acf78ab34d91 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 29 Oct 2026 01:01:20 +0100 Subject: [PATCH 1/5] STRA-326: cross-check the declared machine against hardware.machine_role / gpu_name validity.py trusted --machine alone, so laptop records declared "server" skipped the 100 W power floor and the owner attestation. derive_pairs now refuses (MACHINE_MISMATCH, exit 3, run ids named) records whose hardware.machine_role differs from the declared machine and a "server" declaration over a Laptop GPU. A schedule `machine` key pre-registers the machine; run_core finalize reads it from there (--machine only a fallback) and refuses a conflicting flag. The golden fixture builder stamps machine_role = machine; golden cases unchanged (0 differences). Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/evidence/capture.py | 3 +- scripts/e2e/evidence/golden/gen_validity.py | 1 + scripts/e2e/evidence/run_core.py | 6 +- scripts/e2e/evidence/test_run_core.py | 33 ++++++++++ scripts/e2e/evidence/test_validity.py | 69 +++++++++++++++++++++ scripts/e2e/evidence/validity.py | 55 ++++++++++++++-- 6 files changed, 160 insertions(+), 7 deletions(-) diff --git a/scripts/e2e/evidence/capture.py b/scripts/e2e/evidence/capture.py index 53e5007e..4ccfc2f8 100644 --- a/scripts/e2e/evidence/capture.py +++ b/scripts/e2e/evidence/capture.py @@ -22,7 +22,8 @@ How the pieces are obtained by SUBPROCESS and its `--csv` output is parsed (STRA-251 round-5 re-cut). The two logs are staged under their fixed names (strata-next.log, inference.log) in a private temporary directory, with CRLF folded to LF (raw bytes are never stored; comparisons are on the normalised text), because the script reads a RUN directory. - --meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine and + --meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine (a real series writes laptop|server: validity.py requires + hardware.machine_role == the declared machine, STRA-326) and ours_build_id (an object commit / target_triple / cargo_features / profile_value_sha256 = the FROZEN build id, STRA-304/322). Optional: owner_attestation {present, identifier, time_utc}, foreign_load {samples}, synthetic, long_session_argv, source_snapshot_sha256. --replay-output: the run JSON of replay_session.py (STRA-308); status must be "ok". diff --git a/scripts/e2e/evidence/golden/gen_validity.py b/scripts/e2e/evidence/golden/gen_validity.py index 2658c8e9..5cc8270f 100644 --- a/scripts/e2e/evidence/golden/gen_validity.py +++ b/scripts/e2e/evidence/golden/gen_validity.py @@ -262,6 +262,7 @@ def build_record(templates, machine, n, arm, order, sched_hash, spec, valid, rea ident["pair_id"] = pair_id(n) rec["synthetic"] = True rec["thresholds_source"] = "S3.7" + rec["hardware"]["machine_role"] = machine # STRA-326: validity.py cross-checks the declared machine against the record rec["hardware"]["owner_attestation"] = {"present": True, "identifier": "golden-attestation-1", "time_utc": "2026-01-01T00:00:00Z"} base = machine_defaults(machine) if base is not None: diff --git a/scripts/e2e/evidence/run_core.py b/scripts/e2e/evidence/run_core.py index e8fd6408..4e02e6e7 100644 --- a/scripts/e2e/evidence/run_core.py +++ b/scripts/e2e/evidence/run_core.py @@ -17,7 +17,9 @@ CLI v1 (fixed by the leaf) Additions (same exit-code table) run_core.py finish --ledger FILE --run-id ID --state DONE|INVALID [--outcome O --attributed-to C] [--records DIR] [--run-dir DIR] run_core.py unlock --run-root DIR --run-id ID [--lock-dir DIR] [--mode file|mkdir] - run_core.py finalize --records DIR --schedule FILE --ledger FILE --machine laptop|server + run_core.py finalize --records DIR --schedule FILE --ledger FILE [--machine laptop|server] + the machine is read from the pre-registered schedule (`machine` key, hashed with it); --machine is only a fallback for a + schedule without the key and a flag that conflicts with the schedule is refused (exit 3, MACHINE_MISMATCH; STRA-326) Exit codes 0 ok | 2 not the next scheduled slot (the message names the scheduled slot) | 3 malformed input or command-line usage error @@ -842,7 +844,7 @@ def main(argv=None, ctx=None): p.add_argument("--records", required=True) p.add_argument("--schedule", required=True) p.add_argument("--ledger", required=True) - p.add_argument("--machine", required=True, choices=["laptop", "server"]) + p.add_argument("--machine", choices=["laptop", "server"], help="only for a schedule without a `machine` key; must agree with it otherwise") args = parser.parse_args(argv) try: if args.command == "start": diff --git a/scripts/e2e/evidence/test_run_core.py b/scripts/e2e/evidence/test_run_core.py index 8b0c1000..fa2fd58c 100644 --- a/scripts/e2e/evidence/test_run_core.py +++ b/scripts/e2e/evidence/test_run_core.py @@ -629,6 +629,39 @@ class TestFinalize(Base): self.assertIn("pair-0001.ours", out + err) + def _with_schedule_machine(self, sched, machine): + with open(sched, "r", encoding="utf-8") as fh: + doc = json.load(fh) + doc["machine"] = machine + with open(sched, "w", encoding="utf-8", newline="\n") as fh: + json.dump(doc, fh) + + def test_finalize_takes_the_machine_from_the_schedule(self): # STRA-326 AC4 + records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}}) + self._with_schedule_machine(sched, "laptop") + rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger) + self.assertEqual(rc, 0, err) + self.assertEqual(json.loads(out)["valid_pairs"], 1) + + def test_finalize_refuses_a_flag_that_conflicts_with_the_schedule(self): # STRA-326 AC4 + records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}}) + self._with_schedule_machine(sched, "laptop") + rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "server") + self.assertEqual(rc, RC.EXIT_MALFORMED) + self.assertIn("MACHINE_MISMATCH", out + err) + + def test_finalize_refuses_laptop_records_declared_server(self): # STRA-326 AC1 through the runner + records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}}) + rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "server") + self.assertEqual(rc, RC.EXIT_MALFORMED) + self.assertIn("MACHINE_MISMATCH", out + err) + + def test_finalize_without_any_machine_is_refused(self): + records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}}) + rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger) + self.assertEqual(rc, RC.EXIT_MALFORMED) + + class TestMachineFacts(Base): def test_pid_alive_and_dead(self): self.assertTrue(RC.pid_alive(os.getpid())) diff --git a/scripts/e2e/evidence/test_validity.py b/scripts/e2e/evidence/test_validity.py index 7d0fd1bd..e1060ce2 100644 --- a/scripts/e2e/evidence/test_validity.py +++ b/scripts/e2e/evidence/test_validity.py @@ -302,5 +302,74 @@ class ImportedFunctions(unittest.TestCase): self.assertEqual(DOC["thresholds"]["vanilla_rerun_cap"], V.VANILLA_RERUN_CAP) +LAPTOP_GPU = "NVIDIA GeForce RTX 5090 Laptop GPU" + + +class MachineCrossCheck(unittest.TestCase): + """STRA-326: the declared machine must match what the records say; the flag alone never selects the rule set.""" + + BELOW_FLOOR = pw(51.0, 51.0, 51.0) # a laptop sample below the 100 W floor + + def test_laptop_records_declared_server_fail_with_a_named_error(self): # AC1 + fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"ours": self.BELOW_FLOOR}}]) + fx.machine = "server" + rc, out, err = fx.run() + self.assertEqual(rc, 3, err) + self.assertIn("MACHINE_MISMATCH", err) + self.assertIn("pair-0001.ours", err) + + def test_laptop_gpu_name_under_a_server_declaration_fails(self): # AC1, the second half of the item + fx = Fixture(self, "server", [{"pair": 1, "arms": {"ours": {"set": {"hardware.gpu_name": LAPTOP_GPU}}}}]) + rc, out, err = fx.run() + self.assertEqual(rc, 3, err) + self.assertIn("MACHINE_MISMATCH", err) + self.assertIn("Laptop GPU", err) + + def test_server_records_declared_laptop_fail(self): # AC2 + fx = Fixture(self, "server", [{"pair": 1, "arms": {}}]) + fx.machine = "laptop" + rc, out, err = fx.run() + self.assertEqual(rc, 3, err) + self.assertIn("MACHINE_MISMATCH", err) + + def test_missing_machine_role_is_refused(self): + fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"ours": {"unset": ["hardware.machine_role"]}}}]) + self.assertEqual(fx.run()[0], 3) + + def test_matching_declarations_behave_as_before(self): # AC3 (the golden vectors are the bulk of it) + for machine in ("laptop", "server"): + fx = Fixture(self, machine, [{"pair": 1, "arms": {}}]) + rc, out, err = fx.run() + self.assertEqual(rc, 0, err) + self.assertTrue(by_pair(out)[1]["valid"]) + + def test_in_process_error_is_a_malformed_subclass(self): + self.assertTrue(issubclass(V.MachineMismatch, V.Malformed)) + + def test_schedule_machine_is_used_and_a_conflicting_flag_is_refused(self): # AC4 (validity side) + sched = {"arms": ["ours"], "machine": "laptop"} + self.assertEqual(V.resolve_machine(sched, None), "laptop") + self.assertEqual(V.resolve_machine(sched, "laptop"), "laptop") + with self.assertRaises(V.MachineMismatch): + V.resolve_machine(sched, "server") + self.assertEqual(V.resolve_machine({"arms": []}, "server"), "server") # a schedule without the key falls back to the flag + with self.assertRaises(V.Malformed): + V.resolve_machine({"arms": []}, None) + with self.assertRaises(V.Malformed): + V.resolve_machine({"machine": "desktop"}, None) + + def test_cli_machine_flag_is_optional_when_the_schedule_has_it(self): + fx = Fixture(self, "laptop", [{"pair": 1, "arms": {}}]) + with open(fx.schedule, "r", encoding="utf-8") as fh: + sched = json.load(fh) + sched["machine"] = "laptop" + fx.write(fx.schedule, sched) + rc, out, err = run_cli("pairs", "--records", fx.records, "--schedule", fx.schedule, "--ledger", fx.ledger) + self.assertEqual(rc, 0, err) + rc, out, err = run_cli("pairs", "--records", fx.records, "--schedule", fx.schedule, "--ledger", fx.ledger, "--machine", "server") + self.assertEqual(rc, 3, err) + self.assertIn("MACHINE_MISMATCH", err) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/e2e/evidence/validity.py b/scripts/e2e/evidence/validity.py index a96daa81..e587eba8 100644 --- a/scripts/e2e/evidence/validity.py +++ b/scripts/e2e/evidence/validity.py @@ -8,7 +8,7 @@ dabfd08e) and the balanced-schedule rule of E1 (D5) are coded. The runner (STRA- Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no network. Writes nothing unless --out is given. INTERFACE v1 - validity.py pairs --records --schedule --ledger --machine laptop|server [--out FILE] + validity.py pairs --records --schedule --ledger [--machine laptop|server] [--out FILE] stdout: {"pairs": [{"pair": i, "valid": bool, "reasons": [...], "event": null|"FAIL"|"RERUN"|"OWNER"}], "manifest_ok": bool, "invalid_rate": x} validity.py schedule --check [--out FILE] @@ -19,6 +19,12 @@ INTERFACE v1 Machine: the `--machine` argument (the same one that selects the E2(1) laptop/server power rules) also selects the E2(2) rule: the owner attestation is required on laptop pairs only (ATTESTATION_MISSING / OWNER); a server pair needs none and a present one is ignored. +The declaration is cross-checked (STRA-326): every record's hardware.machine_role must equal the declared machine, and a `server` +declaration is refused for a record whose hardware.gpu_name names a Laptop GPU. The runner writes machine_role = laptop|server into +--meta (capture.py). A mismatch is MALFORMED INPUT (exit 3, MACHINE_MISMATCH naming the run ids): the power floor and the attestation +rule are never skipped by typing the wrong flag. A schedule that carries a `machine` key pre-registers the machine (it is part of the +schedule hash); a conflicting --machine is refused (resolve_machine). + Reason codes: POWER, WORKLOAD, CACHE, INFRASTRUCTURE, ATTESTATION_MISSING, FOREIGN_LOAD, COUNTABLE_MISMATCH. Events: RERUN (attributable infrastructure failure, build-id mismatch, vanilla failure not attributable up to the cap), OWNER (missing attestation, third non-attributable vanilla failure of a slot), FAIL (ours failure not attributable; the series stops FAILED). @@ -53,6 +59,7 @@ VANILLA_RERUN_CAP = 2 # E2(5): a vanilla failure not attributable # SC14: the foreign-load threshold itself is read from the schedule file (TL proposal: 5 percent of a core for 2 s; BA to confirm). INFRA_CAUSES = ("POWER", "WORKLOAD", "CACHE", "LOCK", "WATCHDOG", "TELEMETRY") # E2(5): causes a failed attempt can be attributed to OUTCOMES = ("CRASH", "TIMEOUT", "INTEGRITY_FAILURE") +MACHINES = ("laptop", "server") EVENT_RANK = {"RERUN": 1, "OWNER": 2, "FAIL": 3} GROUP_SIZE = 6 # D5: three arms -> all 6 permutations per group of 6 pairs METADATA_PATHS = ( # E2(3): the metadata of the common paragraph must be complete @@ -67,6 +74,10 @@ class Malformed(Exception): """Input that cannot be interpreted (exit 3).""" +class MachineMismatch(Malformed): + """The machine the series declares (--machine, schedule `machine`) disagrees with what a record says it was captured on (exit 3).""" + + class Refusal(Exception): """Ledger/manifest refusal (exit 2); .names lists the offending run ids.""" @@ -350,15 +361,51 @@ def check_manifest(records, last): raise Refusal("; ".join(parts), orphans + unlisted) +def resolve_machine(sched, flag): + """The machine a series is judged as. A schedule `machine` key (pre-registered, hashed with the schedule) wins; a --machine flag that + disagrees with it is refused (MachineMismatch). A schedule without the key falls back to the flag (the golden schedules have none); + the per-record cross-check in check_machine() still applies. Returns "laptop" or "server".""" + declared = sched.get("machine") if isinstance(sched, dict) else None + if declared is not None and declared not in MACHINES: + raise Malformed("schedule machine %r is not one of %s" % (declared, ", ".join(MACHINES))) + if flag is not None and flag not in MACHINES: + raise Malformed("machine must be laptop or server") + if declared is not None and flag is not None and declared != flag: + raise MachineMismatch("MACHINE_MISMATCH: the schedule pre-registers machine %r but %r was given on the command line" % (declared, flag)) + machine = declared if declared is not None else flag + if machine is None: + raise Malformed("no machine: the schedule has no `machine` key and no --machine was given") + return machine + + +def check_machine(records, machine): + """STRA-326: the declared machine must match what the records say they were captured on. Raises MachineMismatch naming run ids.""" + wrong, laptop_gpu = [], [] + for rid in sorted(records): + role = get_path(records[rid], "hardware.machine_role") + if role != machine: + wrong.append("%s (hardware.machine_role=%r)" % (rid, role)) + gpu = get_path(records[rid], "hardware.gpu_name") + if machine == "server" and isinstance(gpu, str) and "laptop" in gpu.lower(): + laptop_gpu.append("%s (hardware.gpu_name=%r)" % (rid, gpu)) + if wrong or laptop_gpu: + parts = [] + if wrong: + parts.append("record(s) whose hardware.machine_role is not %r: %s" % (machine, ", ".join(wrong))) + if laptop_gpu: + parts.append("record(s) of a Laptop GPU under a `server` declaration: %s" % ", ".join(laptop_gpu)) + raise MachineMismatch("MACHINE_MISMATCH: declared machine %r; %s" % (machine, "; ".join(parts))) + + def derive_pairs(records, sched, last, machine): """The pairs command as a function. records: run_id -> record; last: run_id -> last ledger line. Returns the result dict; raises Refusal (exit 2) or Malformed (exit 3).""" - if machine not in ("laptop", "server"): - raise Malformed("machine must be laptop or server") if not isinstance(sched, dict) or not isinstance(sched.get("arms"), list): raise Malformed("schedule has no arms list") + machine = resolve_machine(sched, machine) arms = list(sched["arms"]) check_manifest(records, last) + check_machine(records, machine) by_pair = {} for rid, line in last.items(): by_pair.setdefault(_pair_number(line), []).append((rid, line)) @@ -406,7 +453,7 @@ def main(argv=None): p.add_argument("--records", required=True) p.add_argument("--schedule", required=True) p.add_argument("--ledger", required=True) - p.add_argument("--machine", required=True, choices=["laptop", "server"]) + p.add_argument("--machine", choices=list(MACHINES), help="required unless the schedule carries a `machine` key; must agree with it") p.add_argument("--out", help="also write the JSON result here (run roots outside Git)") s = sub.add_parser("schedule", help="schedule checks") s.add_argument("--check", required=True, metavar="SCHEDULE_JSON") From c27e26407d9d70185b116248f212059198f689dd Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 29 Oct 2026 01:10:27 +0100 Subject: [PATCH 2/5] STRA-327: laptop run wiring - mandatory run root, STOP/lock checks, launcher, heartbeat reader, tolerant unlock run_core start now requires --run-root and checks, before any ledger line: STOP file (exit 10), then a foreign / stale / unreadable lock (exit 4, LOCK_FOREIGN / LOCK_STALE / LOCK_UNREADABLE), then the run-root guard. The Windows lock path needs a run root named `runs` (exit 3 otherwise) because watchdog.ps1 and guard.ps1 only look in \locks. unlock exits 0 when the lock is already gone (guard.ps1 releases it after the cool-down); another run's lock is still exit 4. heartbeat.json gets a reader: `run_core.py heartbeat` (exit 13 when missing/unreadable/stale) and `resume` reports a live owner whose heartbeat is stale. New launch_arm.py is the only way to start an arm: the arm is the child of watchdog.ps1, so no watchdog (script missing, not startable, or ended without starting the arm) means no arm; the slot is then closed INVALID. Mock/dry tests only; no PowerShell, no GPU. PowerShell scripts are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/evidence/launch_arm.py | 170 +++++++++++++++++++++++ scripts/e2e/evidence/run_core.py | 99 ++++++++++++-- scripts/e2e/evidence/test_launch_arm.py | 174 ++++++++++++++++++++++++ scripts/e2e/evidence/test_run_core.py | 164 ++++++++++++++++++++++ 4 files changed, 597 insertions(+), 10 deletions(-) create mode 100644 scripts/e2e/evidence/launch_arm.py create mode 100644 scripts/e2e/evidence/test_launch_arm.py diff --git a/scripts/e2e/evidence/launch_arm.py b/scripts/e2e/evidence/launch_arm.py new file mode 100644 index 00000000..b264d2de --- /dev/null +++ b/scripts/e2e/evidence/launch_arm.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Launcher of one laptop arm under the watchdog (STRA-327): the only way the runner starts an arm on the Windows laptop. + +Why it exists: run_core.py (STRA-316) owns the schedule, ledger and lock; scripts/laptop/win/watchdog.ps1 (STRA-291, which adopts the +containment of guard.ps1, STRA-320) owns the GPU safeguards. Nothing tied them together, so an arm could be started without the watchdog. +This launcher never runs the arm itself: the arm is the CHILD of watchdog.ps1 (-ChildCommand), so an arm exists only while a watchdog +process exists, and a watchdog that cannot be started means no arm. Before anything is started it enforces, in this order and before the +first ledger line: the watchdog script exists; no STOP file; no foreign / stale / unreadable lock; the run-root guard (git-ignored, not in a +linked worktree, >= 20 GB free). Then it starts the slot (ledger QUEUED + STARTED), takes the lock for the slot's run id (watchdog.ps1 +verifies a lock of its own -RunId and makes no second one), writes heartbeat.json in the run directory (read by `run_core.py heartbeat` +and `resume`) and starts the watchdog. + +Stdlib only, Python >= 3.9. Offline. It changes no power, display, lock-screen, sleep, execution-policy or registry setting; the +PowerShell child is started with a per-process `-ExecutionPolicy Bypass` as the watchdog's own usage note says. + + launch_arm.py --schedule FILE --slot ID --run-root DIR --timeout-s N [--leaf NAME] [--ledger FILE] [--free-gb N] [--rerun] + [--watchdog PATH] [--powershell EXE] -- [arm arguments...] + +Exit codes: run_core.py's table for the refusals (2 wrong slot, 3 usage, 4 lock, 5/6 run root, 7, 8, 9, 10 STOP, 11) and + 13 no live watchdog (script missing, could not be started, or it ended without starting the arm; the slot is closed INVALID with + attributed_to WATCHDOG / LOCK / POWER and the lock is released) + otherwise the exit code of watchdog.ps1 (0 the arm exited 0, 1 non-zero, 5/6/7 aborted / timeout / STALL: the lock is KEPT for the + guard and the owner; DONE / INVALID for a run that did start is left to the runner after capture, `run_core.py finish`). +""" +import argparse +import importlib.util +import json +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.abspath(os.path.join(HERE, "..", "..", "..")) +DEFAULT_WATCHDOG = os.path.join(REPO, "scripts", "laptop", "win", "watchdog.ps1") +EXIT_NO_WATCHDOG = 13 +# watchdog.ps1 exit codes that mean the arm was never started, and the cause the slot is attributed to (validity.INFRA_CAUSES) +NOT_STARTED_CAUSE = {2: "WATCHDOG", 3: "LOCK", 4: "POWER", 8: "WATCHDOG"} +KEEP_LOCK_CODES = (5, 6, 7) # aborted / timeout / STALL: the watchdog and guard decide when the lock goes (STALL keeps it for the owner) + + +def _load_run_core(): + cached = sys.modules.get("_launch_arm_run_core") + if cached is not None: + return cached + spec = importlib.util.spec_from_file_location("_launch_arm_run_core", os.path.join(HERE, "run_core.py")) + module = importlib.util.module_from_spec(spec) + sys.modules["_launch_arm_run_core"] = module + spec.loader.exec_module(module) + return module + + +def watchdog_command(powershell, script, child, child_args, timeout_s, run_id, leaf, artifacts_root, watchdog_run_root): + """The argv that starts watchdog.ps1 with the arm as its child (usage note in the header of watchdog.ps1).""" + return [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, + "-ChildCommand", child, "-ChildArguments", subprocess.list2cmdline(list(child_args)), "-TimeoutSeconds", repr(float(timeout_s)), + "-RunId", run_id, "-Leaf", leaf, "-ArtifactsRoot", artifacts_root, "-RunRoot", watchdog_run_root] + + +def _spawn(argv): + return subprocess.Popen(argv, stdin=subprocess.DEVNULL) + + +def _read_summary(watchdog_run_root): + try: + with open(os.path.join(watchdog_run_root, "watchdog_summary.json"), "r", encoding="utf-8-sig") as fh: + doc = json.load(fh) + return doc if isinstance(doc, dict) else {} + except (OSError, ValueError): + return {} + + +def launch(schedule, slot, run_root, child_cmd, timeout_s, leaf="STRA-257", ledger=None, mode=None, free_gb=None, rerun=False, + watchdog=None, powershell="powershell", spawn=None, settle_s=2.0, poll_s=1.0, sleep=time.sleep, clock=time.monotonic, + ctx=None, heartbeat_interval=None): + """Starts one arm under the watchdog. Returns the info dict (with exit_code); raises run_core.RunCoreError for a refusal. + spawn(argv) -> object with poll() and wait() (default subprocess.Popen); sleep / clock are injectable for the tests.""" + rc = _load_run_core() + ctx = ctx or rc.Context() + spawn = spawn or _spawn + script = os.path.abspath(watchdog or DEFAULT_WATCHDOG) + if not child_cmd: + raise rc.RunCoreError(rc.EXIT_MALFORMED, "no arm command given after --") + if not os.path.isfile(script): # before anything is written: no watchdog, no run + raise rc.RunCoreError(EXIT_NO_WATCHDOG, "no live watchdog: %s does not exist; no ledger line written, no arm started" % script) + run_root = os.path.abspath(run_root) + ledger = ledger or os.path.join(run_root, "ledger.jsonl") + rc.check_start_preconditions(run_root, slot, None, mode, free_gb, ctx) + info = rc.start_slot(schedule, slot, ledger, rerun, ctx) + run_id, run_dir = info["run_id"], info["run_dir"] + watchdog_run_root = os.path.join(run_dir, "watchdog") + result = {"run_id": run_id, "run_dir": run_dir, "watchdog_run_root": watchdog_run_root, "arm_started": False, "watchdog_exit": None} + beat = None + lock_taken = False + + def close_slot(cause, why): + """The arm never started: close the slot INVALID (kept, never deleted), release the lock we took, refuse with 13.""" + if beat is not None: + beat.stop() # before the run directory is renamed + rc.finish_run(ledger, run_id, "INVALID", outcome="CRASH", attributed_to=cause, run_dir=run_dir, ctx=ctx) + if lock_taken: + rc.release_lock(run_root, run_id, None, mode) + raise rc.RunCoreError(EXIT_NO_WATCHDOG, "no live watchdog: %s; the arm was not started, slot %s is INVALID (attributed to %s)" % ( + why, run_id, cause), **result) + + try: + rc.acquire_lock(run_root, run_id, leaf, None, mode, ctx) + lock_taken = True + kwargs = {} if heartbeat_interval is None else {"interval": heartbeat_interval, "poll_s": min(1.0, heartbeat_interval / 2.0)} + beat = rc.Heartbeat(os.path.join(run_dir, "heartbeat.json"), run_id, **kwargs).start() + argv = watchdog_command(powershell, script, child_cmd[0], child_cmd[1:], timeout_s, run_id, leaf, os.path.dirname(run_root), + watchdog_run_root) + try: + proc = spawn(argv) + except OSError as exc: + close_slot("WATCHDOG", "the watchdog could not be started (%s)" % exc) + t0 = clock() + while clock() - t0 < settle_s and proc.poll() is None: # a watchdog that dies at once never had an arm + sleep(min(poll_s, 0.2)) + while proc.poll() is None: + sleep(poll_s) + code = proc.poll() + result["watchdog_exit"] = code + summary = _read_summary(watchdog_run_root) + result["arm_started"] = summary.get("child_pid") is not None + if not result["arm_started"] and code in NOT_STARTED_CAUSE: + close_slot(NOT_STARTED_CAUSE[code], "watchdog.ps1 exited %s before starting the arm (%s)" % (code, summary.get("reason") or "no reason recorded")) + if code not in KEEP_LOCK_CODES: + rc.release_lock(run_root, run_id, None, mode) # tolerant: the watchdog / guard may have released it already + return dict(result, exit_code=code) + finally: + if beat is not None: + beat.stop() + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + child = [] + if "--" in argv: + i = argv.index("--") + argv, child = argv[:i], argv[i + 1:] + rc = _load_run_core() + parser = rc._Parser(prog="launch_arm.py", description=__doc__.split("\n")[0]) + parser.add_argument("--schedule", required=True) + parser.add_argument("--slot", required=True) + parser.add_argument("--run-root", required=True) + parser.add_argument("--timeout-s", required=True, type=float) + parser.add_argument("--leaf", default="STRA-257") + parser.add_argument("--ledger") + parser.add_argument("--mode", choices=["file", "mkdir"]) + parser.add_argument("--free-gb", type=float, help="override the measured free space (tests only)") + parser.add_argument("--rerun", action="store_true") + parser.add_argument("--watchdog", help="default: scripts/laptop/win/watchdog.ps1 of this tree") + parser.add_argument("--powershell", default="powershell") + args = parser.parse_args(argv) + try: + info = launch(args.schedule, args.slot, args.run_root, child, args.timeout_s, args.leaf, args.ledger, args.mode, args.free_gb, + args.rerun, args.watchdog, args.powershell) + rc._emit(info) + return info["exit_code"] if info["exit_code"] is not None else 8 + except rc.RunCoreError as exc: + sys.stderr.write("REFUSED (exit %d): %s\n" % (exc.code, exc)) + body = {"refused": str(exc), "exit": exc.code} + body.update(exc.extra) + sys.stdout.write(json.dumps(body, default=str) + "\n") + return exc.code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/evidence/run_core.py b/scripts/e2e/evidence/run_core.py index 4e02e6e7..96ab910f 100644 --- a/scripts/e2e/evidence/run_core.py +++ b/scripts/e2e/evidence/run_core.py @@ -10,13 +10,16 @@ Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no network. It never changes registry setting (SC3), never deletes a run directory (an invalid run is RENAMED and kept, SC11) and never steals a lock (SC13). CLI v1 (fixed by the leaf) - run_core.py start --schedule FILE --slot ID [--ledger FILE] [--run-root DIR] [--free-gb N] [--rerun] + run_core.py start --schedule FILE --slot ID --run-root DIR [--ledger FILE] [--lock-dir DIR] [--mode file|mkdir] [--free-gb N] [--rerun] + --run-root is MANDATORY (STRA-327): the STOP file, the lock and the run-root guard are checked before any ledger line run_core.py lock --run-root DIR --run-id ID --leaf NAME [--lock-dir DIR] [--mode file|mkdir] run_core.py guard --run-root DIR [--free-gb N] run_core.py resume --ledger FILE [--schedule FILE] [--run-root DIR] Additions (same exit-code table) run_core.py finish --ledger FILE --run-id ID --state DONE|INVALID [--outcome O --attributed-to C] [--records DIR] [--run-dir DIR] run_core.py unlock --run-root DIR --run-id ID [--lock-dir DIR] [--mode file|mkdir] + exit 0 also when no lock exists any more (guard.ps1 releases it after the cool-down); another run's lock is still exit 4 + run_core.py heartbeat --run-dir DIR [--max-age S] reader of heartbeat.json: exit 0 fresh, 13 missing / unreadable / stale run_core.py finalize --records DIR --schedule FILE --ledger FILE [--machine laptop|server] the machine is read from the pre-registered schedule (`machine` key, hashed with it); --machine is only a fallback for a schedule without the key and a flag that conflicts with the schedule is refused (exit 3, MACHINE_MISMATCH; STRA-326) @@ -26,6 +29,7 @@ Exit codes 4 lock held (never waits, never steals) | 5 run root not ignored / inside a linked worktree | 6 less than 20 GB free 7 context_tokens below the 256k class (262144) | 8 schedule differs from the one in the ledger (pre-registration violated) 9 a run is still in flight or not yet resumed | 10 STOP file present | 11 run directory already exists | 12 ledger/manifest refusal (finalize) + 13 heartbeat missing, unreadable or stale (heartbeat); launch_arm.py also uses 13 for 'no live watchdog' Files schedule JSON {seed, arms, n_pairs, blocks: [{block, order: [arm, ...]}], context_tokens, cache_residency_band: {min, max}, @@ -41,8 +45,8 @@ Files line, INVALID with outcome CRASH, attributed_to null and interrupted true. An interrupted pair is therefore invalid (SC3) and read by validity.py as an unattributed failure (ours: FAIL, vanilla: RERUN up to its cap). run dir /// ; heartbeat.json (60 s) in it. Invalid run dirs are renamed .invalid-[-n]. - lock Windows: /../locks/LAPTOP_GPU.lock when the run root is named `runs` (artifacts\\runs -> artifacts\\locks), else - /locks/LAPTOP_GPU.lock; created with CreateFileW CREATE_NEW and share mode 0 (FileShare.None), written, fsynced and + lock Windows: /../locks/LAPTOP_GPU.lock; the run root MUST be named `runs` (artifacts\\runs -> artifacts\\locks, where + watchdog.ps1 and guard.ps1 look) unless --lock-dir is given, any other name is refused (exit 3, STRA-327); created with CreateFileW CREATE_NEW and share mode 0 (FileShare.None), written, fsynced and CLOSED at once (watchdog.ps1 and guard.ps1 open it with a shared read to verify the run id). Linux: atomic mkdir of /run.lock with the `owner` file inside. Contents (JSON): leaf, run_id, pid, utc, boot_time, created_by (+ boot_id). STOP /STOP (artifacts\\runs\\STOP of guard.ps1 / STRA-320). start and guard refuse while it exists; resume creates it @@ -77,6 +81,7 @@ EXIT_IN_FLIGHT = 9 EXIT_STOP_FILE = 10 EXIT_RUN_DIR_EXISTS = 11 EXIT_LEDGER_REFUSAL = 12 +EXIT_HEARTBEAT = 13 CONTEXT_FLOOR_TOKENS = 262144 # 256k class; a schedule below it is refused (the equality is validity.py's rule) MIN_FREE_GB = 20.0 # SC11, a DEVOPS proposal (comment 7b25fb7b); GB = 2**30 bytes as in `df -B1G` @@ -516,7 +521,7 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None): sched, sha = read_schedule(schedule_path) check_same_schedule(lines, sha) slots = schedule_slots(sched) - interrupted, in_flight, reboot, stop = [], [], False, None + interrupted, in_flight, stale_heartbeat, reboot, stop = [], [], [], False, None current_boot = ctx.boot() for run_id in sorted(last): cur = last[run_id] @@ -528,6 +533,9 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None): alive = same and ctx.alive(cur.get("pid")) if alive: in_flight.append(run_id) + beat = read_heartbeat(run_dir_for(ledger_path, cur)) + if beat["state"] != "fresh": # STRA-327: the owner's pid is alive but its heartbeat is not: reported, never acted on + stale_heartbeat.append(run_id) continue reason = "process %s is gone" % cur.get("pid") if same else "boot time %s differs from the current boot %s" % (cur.get("boot_time"), current_boot) append_ledger(ledger_path, make_line(ctx, cur["schedule_sha256"], cur, run_id, "INTERRUPTED", attempt=cur.get("attempt", 1), @@ -546,7 +554,7 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None): if slots is not None: _, last = read_ledger(ledger_path) nxt = next_slot(slots, last) if slots is not None else None - return {"interrupted": interrupted, "in_flight": in_flight, "reboot_detected": reboot, "stop_file": stop, + return {"interrupted": interrupted, "in_flight": in_flight, "stale_heartbeat": stale_heartbeat, "reboot_detected": reboot, "stop_file": stop, "next_slot": nxt["run_id"] if nxt else None, "schedule_complete": (slots is not None and nxt is None)} @@ -605,8 +613,13 @@ def lock_location(run_root, lock_dir=None, mode=None): raise RunCoreError(EXIT_MALFORMED, "lock mode must be file or mkdir") root = os.path.abspath(run_root) if mode == "file": - directory = os.path.abspath(lock_dir) if lock_dir else ( - os.path.join(os.path.dirname(root), "locks") if os.path.basename(root).lower() == "runs" else os.path.join(root, "locks")) + if lock_dir: + directory = os.path.abspath(lock_dir) + elif os.path.basename(root).lower() == "runs": + directory = os.path.join(os.path.dirname(root), "locks") + else: # STRA-327: watchdog.ps1 / guard.ps1 only look in \\locks; a lock elsewhere would be invisible to them + raise RunCoreError(EXIT_MALFORMED, "run root %s is not named `runs`: the lock would not be at \\locks where " + "watchdog.ps1 and guard.ps1 look; name the run root `runs` or pass --lock-dir" % root) path = os.path.join(directory, LOCK_FILE_NAME) return mode, directory, path, path path = os.path.abspath(lock_dir) if lock_dir else os.path.join(root, LOCK_DIR_NAME) @@ -692,6 +705,8 @@ def acquire_lock(run_root, run_id, leaf, lock_dir=None, mode=None, ctx=None): def release_lock(run_root, run_id, lock_dir=None, mode=None): """Releases the lock of THIS run id only; any other lock is refused (4).""" mode, directory, path, owner = lock_location(run_root, lock_dir, mode) + if not os.path.exists(path): # STRA-327: guard.ps1 releases the lock itself after the cool-down; nothing left to release is success + return {"released": None, "already_released": True, "lock": owner} holder = _read_holder(owner) if holder is None or holder.get("run_id") != run_id: raise RunCoreError(EXIT_LOCK_HELD, "the lock at %s is not held by run %s; not released" % (path, run_id), holder=holder) @@ -701,6 +716,61 @@ def release_lock(run_root, run_id, lock_dir=None, mode=None): return {"released": owner} +# -------------------------------------------------------------------------------------------------------------------------------- +# start preconditions (STRA-327): STOP file and lock are checked before a slot is started, not only by the PowerShell side +# -------------------------------------------------------------------------------------------------------------------------------- +def check_stop(run_root): + """Refuses (10) while /STOP exists. Cheap and first: it needs no git and no disk probe.""" + stop = os.path.join(os.path.abspath(run_root), STOP_FILE_NAME) + if os.path.exists(stop): + raise RunCoreError(EXIT_STOP_FILE, "STOP file present at %s; only the owner's recorded inspection clears it (SC3)" % stop) + + +def check_lock(run_root, slot_id, lock_dir=None, mode=None, ctx=None): + """Refuses (4) with a named reason when a lock is in the way of starting `slot_id`: LOCK_UNREADABLE, LOCK_FOREIGN (another run id) or + LOCK_STALE (this slot's lock, but its process is gone or it dates from another boot). No lock, or this slot's live lock (taken by + its own runner), passes. Never removes or takes over anything.""" + ctx = ctx or Context() + mode, directory, path, owner = lock_location(run_root, lock_dir, mode) + if not os.path.exists(path): + return {"lock": None} + holder = _read_holder(owner) + if holder is None: + raise RunCoreError(EXIT_LOCK_HELD, "LOCK_UNREADABLE: " + _holder_text(None, path, None), holder=None, lock=path, reason="LOCK_UNREADABLE") + if holder.get("run_id") != slot_id: + raise RunCoreError(EXIT_LOCK_HELD, "LOCK_FOREIGN: " + _holder_text(holder, path, None), holder=holder, lock=path, reason="LOCK_FOREIGN") + alive = same_boot(holder.get("boot_time"), ctx.boot()) and holder.get("pid") is not None and ctx.alive(holder.get("pid")) + if not alive: + raise RunCoreError(EXIT_LOCK_HELD, "LOCK_STALE: " + _holder_text(holder, path, False), holder=holder, lock=path, reason="LOCK_STALE") + return {"lock": path, "holder": holder} + + +def check_start_preconditions(run_root, slot_id, lock_dir=None, mode=None, free_gb=None, ctx=None): + """STOP file, then lock, then the run-root guard (git-ignored, outside a linked worktree, >= 20 GB free, STOP again).""" + check_stop(run_root) + check_lock(run_root, slot_id, lock_dir, mode, ctx) + return guard_run_root(run_root, free_gb) + + +# -------------------------------------------------------------------------------------------------------------------------------- +# heartbeat reader (STRA-327) +# -------------------------------------------------------------------------------------------------------------------------------- +def read_heartbeat(run_dir, max_age_s=None, now=None): + """Reads /heartbeat.json. Returns {"state": fresh|stale|missing|unreadable, "age_s": float|None, "heartbeat": doc|None}. + Stale means older than max_age_s (default: three times the interval the writer recorded, 180 s for the 60 s default).""" + path = os.path.join(run_dir, "heartbeat.json") + if not os.path.isfile(path): + return {"state": "missing", "age_s": None, "heartbeat": None, "path": path} + doc = _read_holder(path) + if doc is None or _parse_instant(doc.get("utc")) is None: + return {"state": "unreadable", "age_s": None, "heartbeat": doc, "path": path} + when = _parse_instant(doc["utc"]) + current = _parse_instant(now) if now else time.time() + age = current - when + limit = float(max_age_s) if max_age_s is not None else 3.0 * float(doc.get("interval_s") or HEARTBEAT_INTERVAL_S) + return {"state": "fresh" if age <= limit else "stale", "age_s": round(age, 3), "heartbeat": doc, "path": path, "max_age_s": limit} + + # -------------------------------------------------------------------------------------------------------------------------------- # run-root guard (SC11) # -------------------------------------------------------------------------------------------------------------------------------- @@ -814,7 +884,9 @@ def main(argv=None, ctx=None): p.add_argument("--schedule", required=True) p.add_argument("--slot", required=True) p.add_argument("--ledger") - p.add_argument("--run-root", help="when given the run-root guard runs first") + p.add_argument("--run-root", required=True, help="mandatory: STOP file, lock and run-root guard are checked before the slot starts") + p.add_argument("--lock-dir") + p.add_argument("--mode", choices=["file", "mkdir"]) p.add_argument("--free-gb", type=float, help="override the measured free space (tests only)") p.add_argument("--rerun", action="store_true", help="re-run the earliest INVALID slot (the retry policy is STRA-257's)") p = sub.add_parser("finish", help="DONE or INVALID for a STARTED run") @@ -837,6 +909,9 @@ def main(argv=None, ctx=None): p.add_argument("--leaf", required=True) p.add_argument("--lock-dir") p.add_argument("--mode", choices=["file", "mkdir"]) + p = sub.add_parser("heartbeat", help="read heartbeat.json of a run directory (exit 13 when missing, unreadable or stale)") + p.add_argument("--run-dir", required=True) + p.add_argument("--max-age", type=float, help="seconds; default three times the interval the writer recorded") p = sub.add_parser("guard", help="run-root guard") p.add_argument("--run-root", required=True) p.add_argument("--free-gb", type=float, help="override the measured free space (tests only)") @@ -848,8 +923,7 @@ def main(argv=None, ctx=None): args = parser.parse_args(argv) try: if args.command == "start": - if args.run_root: - guard_run_root(args.run_root, args.free_gb) + check_start_preconditions(args.run_root, args.slot, args.lock_dir, args.mode, args.free_gb, ctx) _emit(start_slot(args.schedule, args.slot, _default_ledger(args), args.rerun, ctx)) elif args.command == "finish": _emit(finish_run(args.ledger, args.run_id, args.state, args.outcome, args.attributed_to, args.records, args.run_dir, ctx)) @@ -861,6 +935,11 @@ def main(argv=None, ctx=None): _emit(release_lock(args.run_root, args.run_id, args.lock_dir, args.mode)) elif args.command == "guard": _emit(guard_run_root(args.run_root, args.free_gb)) + elif args.command == "heartbeat": + info = read_heartbeat(args.run_dir, args.max_age) + _emit(info) + if info["state"] != "fresh": + raise RunCoreError(EXIT_HEARTBEAT, "heartbeat of %s is %s" % (args.run_dir, info["state"]), **info) elif args.command == "finalize": _emit(finalize_records(args.records, args.schedule, args.ledger, args.machine)) return EXIT_OK diff --git a/scripts/e2e/evidence/test_launch_arm.py b/scripts/e2e/evidence/test_launch_arm.py new file mode 100644 index 00000000..b3373f23 --- /dev/null +++ b/scripts/e2e/evidence/test_launch_arm.py @@ -0,0 +1,174 @@ +"""Tests of launch_arm.py (STRA-327): no arm without a live watchdog, STOP / lock / run-root checks before every arm. + +Run: python -m unittest test_launch_arm -v (from scripts/e2e/evidence, or scripts.e2e.evidence.test_launch_arm from the repository root) +Mock only: the watchdog is a fake process object, no PowerShell, no nvidia-smi, no GPU. Stdlib only, Python >= 3.9. +""" +import importlib.util +import itertools +import json +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +_RUN_CORE_TESTS = _load("test_run_core_for_launch", os.path.join(HERE, "test_run_core.py")) +Base = _RUN_CORE_TESTS.Base +BOOT = _RUN_CORE_TESTS.BOOT +LA = _load("launch_arm_under_test", os.path.join(HERE, "launch_arm.py")) +RC = LA._load_run_core() # the module launch_arm raises its errors from (a second copy of run_core would be a different class) +SLOT = "pair-0001.ours" + + +class FakeWatchdog(object): + """A watchdog process that is alive for `polls` polls and then exits with `code`. When `starts_arm`, it records the arm the way + watchdog.ps1 does (child_pid in watchdog_summary.json). `arms` collects the arms that were started.""" + + def __init__(self, argv, code, polls, starts_arm, arms, reason=""): + self.argv, self.code, self.polls, self.n = argv, code, polls, 0 + root = argv[argv.index("-RunRoot") + 1] + os.makedirs(root, exist_ok=True) + summary = {"outcome": "COMPLETED" if starts_arm else "REFUSED", "reason": reason, "child_pid": 1234 if starts_arm else None} + with open(os.path.join(root, "watchdog_summary.json"), "w", encoding="utf-8") as fh: + json.dump(summary, fh) + if starts_arm: + arms.append(argv[argv.index("-ChildCommand") + 1]) + + def poll(self): + self.n += 1 + return None if self.n <= self.polls else self.code + + +class TestLaunchArm(Base): + def setUp(self): + self.repo = self.git_repo("artifacts/") + self.root = os.path.join(self.repo, "artifacts", "runs") + os.makedirs(self.root) + self.d = self.tmpdir() + self.sched = self.schedule_file(self.d) + self.ledger = os.path.join(self.root, "ledger.jsonl") + self.arms, self.spawned = [], [] + ticks = itertools.count() + self.clock = lambda: float(next(ticks)) + self.watchdog_script = os.path.join(self.d, "watchdog.ps1") + with open(self.watchdog_script, "w") as fh: + fh.write("# stand-in: never executed") + + def spawner(self, code=0, polls=3, starts_arm=True, reason="", raises=None): + def spawn(argv): + self.spawned.append(argv) + if raises: + raise raises + return FakeWatchdog(argv, code, polls, starts_arm, self.arms, reason) + return spawn + + def launch(self, spawn, **kwargs): + args = dict(watchdog=self.watchdog_script, spawn=spawn, sleep=lambda s: None, clock=self.clock, settle_s=2.0, mode="file", + free_gb=50.0, ctx=self.ctx(boot=BOOT), heartbeat_interval=60.0) + args.update(kwargs) + return LA.launch(self.sched, SLOT, self.root, ["arm.exe", "--serve", "x y"], 1800, **args) + + def states(self): + return [(ln["run_id"], ln["state"], ln.get("attributed_to")) for ln in self.ledger_lines(self.ledger)] + + def lock_path(self): + return RC.lock_location(self.root, mode="file")[3] + + def test_ac3_no_arm_starts_when_the_watchdog_cannot_be_started(self): + with self.assertRaises(RC.RunCoreError) as cm: + self.launch(self.spawner(raises=OSError("powershell not found"))) + self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG) + self.assertIn("no live watchdog", str(cm.exception)) + self.assertEqual(self.arms, [], "no arm started") + self.assertEqual(self.states()[-1], (SLOT, "INVALID", "WATCHDOG")) + self.assertFalse(os.path.exists(self.lock_path()), "the lock the launcher took is released") + + def test_ac3_a_missing_watchdog_script_refuses_before_anything_is_written(self): + with self.assertRaises(RC.RunCoreError) as cm: + self.launch(self.spawner(), watchdog=os.path.join(self.d, "nope.ps1")) + self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG) + self.assertEqual(self.spawned, []) + self.assertFalse(os.path.exists(self.ledger), "no ledger line") + self.assertFalse(os.path.exists(self.lock_path())) + + def test_ac3_a_watchdog_that_refuses_at_once_never_had_an_arm(self): + for code, cause in ((4, "POWER"), (3, "LOCK"), (2, "WATCHDOG"), (8, "WATCHDOG")): + self.tearDown_state() + with self.assertRaises(RC.RunCoreError) as cm: + self.launch(self.spawner(code=code, polls=0, starts_arm=False, reason="preflight refused")) + self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG, code) + self.assertEqual(self.arms, []) + self.assertEqual(self.states()[-1], (SLOT, "INVALID", cause), code) + + def tearDown_state(self): # a fresh run root for the next iteration of a loop + self.root = os.path.join(self.repo, "artifacts", "runs") + for name in os.listdir(self.root): + path = os.path.join(self.root, name) + if os.path.isfile(path): + os.remove(path) + else: + os.rename(path, path + ".old%d" % len(os.listdir(self.root))) + self.ledger = os.path.join(self.root, "ledger.jsonl") + lock_dir = os.path.dirname(self.lock_path()) + if os.path.isdir(lock_dir): + for name in os.listdir(lock_dir): + os.remove(os.path.join(lock_dir, name)) + + def test_stop_file_foreign_lock_and_stale_lock_start_no_watchdog(self): + stop = os.path.join(self.root, "STOP") + with open(stop, "w") as fh: + fh.write("{}") + with self.assertRaises(RC.RunCoreError) as cm: + self.launch(self.spawner()) + self.assertEqual(cm.exception.code, RC.EXIT_STOP_FILE) + os.remove(stop) + lock = self.lock_path() + os.makedirs(os.path.dirname(lock), exist_ok=True) + with open(lock, "w") as fh: + json.dump({"leaf": "x", "run_id": "pair-0009.ours", "pid": 1, "utc": "2026-10-28T00:00:00Z", "boot_time": BOOT}, fh) + with self.assertRaises(RC.RunCoreError) as cm: + self.launch(self.spawner()) + self.assertEqual((cm.exception.code, cm.exception.extra["reason"]), (RC.EXIT_LOCK_HELD, "LOCK_FOREIGN")) + self.assertEqual(self.spawned, [], "the watchdog (and so the arm) is never started") + self.assertFalse(os.path.exists(self.ledger)) + + def test_happy_path_the_arm_is_the_watchdogs_child_and_the_heartbeat_is_written(self): + info = self.launch(self.spawner(code=0, polls=5)) + self.assertEqual((info["exit_code"], info["arm_started"]), (0, True)) + argv = self.spawned[0] + self.assertEqual(argv[argv.index("-ChildCommand") + 1], "arm.exe") + self.assertEqual(argv[argv.index("-ChildArguments") + 1], '--serve "x y"') + self.assertEqual(argv[argv.index("-RunId") + 1], SLOT) + self.assertEqual(argv[argv.index("-ArtifactsRoot") + 1], os.path.dirname(os.path.abspath(self.root))) + self.assertEqual(argv[argv.index("-TimeoutSeconds") + 1], "1800.0") + self.assertEqual(self.arms, ["arm.exe"]) + self.assertEqual([s[:2] for s in self.states()], [(SLOT, "QUEUED"), (SLOT, "STARTED")], "DONE / INVALID of a started run is the runner's") + self.assertEqual(RC.read_heartbeat(info["run_dir"])["heartbeat"]["run_id"], SLOT) + self.assertFalse(os.path.exists(self.lock_path()), "lock released after a normal finish") + + def test_a_stall_or_abort_keeps_the_lock(self): + info = self.launch(self.spawner(code=7, polls=2, starts_arm=True)) + self.assertEqual(info["exit_code"], 7) + self.assertTrue(os.path.exists(self.lock_path()), "STALL keeps the lock for the guard and the owner") + + def test_no_arm_command_is_refused(self): + with self.assertRaises(RC.RunCoreError) as cm: + LA.launch(self.sched, SLOT, self.root, [], 60, watchdog=self.watchdog_script, spawn=self.spawner(), free_gb=50.0) + self.assertEqual(cm.exception.code, RC.EXIT_MALFORMED) + + def test_command_line_without_an_arm_is_a_usage_error(self): + rc = LA.main(["--schedule", self.sched, "--slot", SLOT, "--run-root", self.root, "--timeout-s", "60"]) + self.assertEqual(rc, RC.EXIT_MALFORMED) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/e2e/evidence/test_run_core.py b/scripts/e2e/evidence/test_run_core.py index fa2fd58c..3528f336 100644 --- a/scripts/e2e/evidence/test_run_core.py +++ b/scripts/e2e/evidence/test_run_core.py @@ -69,7 +69,18 @@ class Base(unittest.TestCase): return RC.Context(now=lambda: "2026-10-28T10:00:%02d.000000Z" % (next(ticks) % 60), pid=lambda: pid, boot=lambda: boot, alive=alive or (lambda p: False)) + def start_root(self): + """A git-ignored run root named `runs` in a throw-away repository (`start` needs --run-root since STRA-327).""" + if getattr(self, "_start_repo", None) is None: + self._start_repo = self.git_repo("artifacts/") + return os.path.join(self._start_repo, "artifacts", "runs") + def cli(self, *args): + args = list(args) + if args and args[0] == "start" and "--run-root" not in args: # the pre-STRA-327 tests of the slot logic: supply a valid root + if "--ledger" not in args: # they expect the ledger next to the schedule file + args += ["--ledger", os.path.join(os.path.dirname(os.path.abspath(args[args.index("--schedule") + 1])), "ledger.jsonl")] + args += ["--run-root", self.start_root(), "--free-gb", "50"] proc = subprocess.run([sys.executable, RUN_CORE] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=REPO, timeout=120) return proc.returncode, proc.stdout, proc.stderr @@ -662,6 +673,159 @@ class TestFinalize(Base): self.assertEqual(rc, RC.EXIT_MALFORMED) +class TestStartWiring(Base): + """STRA-327: the preconditions the PowerShell side enforces are enforced by the runner before a slot starts (no GPU, no PowerShell).""" + + def raw(self, *args): + proc = subprocess.run([sys.executable, RUN_CORE] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, + universal_newlines=True, cwd=REPO, timeout=120) + return proc.returncode, proc.stdout, proc.stderr + + def runs_root(self): + d = self.tmpdir() + root = os.path.join(d, "artifacts", "runs") + os.makedirs(root) + return d, root + + def put_lock(self, root, holder, mode="file"): + _, _, path, owner = RC.lock_location(root, mode=mode) + os.makedirs(os.path.dirname(owner), exist_ok=True) + with open(owner, "w", encoding="utf-8") as fh: + fh.write(holder if isinstance(holder, str) else json.dumps(holder)) + return owner + + def dead_pid(self): + dead = subprocess.Popen([sys.executable, "-c", "pass"]) + dead.wait(timeout=30) + return dead.pid + + def test_ac1_start_without_run_root_fails(self): + d = self.tmpdir() + sched = self.schedule_file(d) + rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours") + self.assertEqual(rc, RC.EXIT_MALFORMED) + self.assertIn("--run-root", err) + self.assertFalse(os.path.exists(os.path.join(d, "ledger.jsonl"))) + + def test_ac1_stop_file_refuses_start_with_exit_10_and_writes_nothing(self): + d, root = self.runs_root() # not even a git repository: the STOP check comes first and needs none + with open(os.path.join(root, "STOP"), "w") as fh: + fh.write("{}") + sched = self.schedule_file(d) + rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--free-gb", "50") + self.assertEqual(rc, RC.EXIT_STOP_FILE, err) + self.assertIn("STOP file present", err) + self.assertFalse(os.path.exists(os.path.join(root, "ledger.jsonl"))) + + def test_ac2_foreign_lock_refuses_start_with_a_named_reason(self): + d, root = self.runs_root() + owner = self.put_lock(root, {"leaf": "other", "run_id": "pair-0009.ours", "pid": os.getpid(), "utc": "2026-10-28T00:00:00Z", + "boot_time": BOOT, "created_by": "x"}) + sched = self.schedule_file(d) + rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file") + self.assertEqual(rc, RC.EXIT_LOCK_HELD, err) + self.assertIn("LOCK_FOREIGN", err) + self.assertIn("pair-0009.ours", err) + self.assertTrue(os.path.exists(owner), "never removed") + self.assertFalse(os.path.exists(os.path.join(root, "ledger.jsonl"))) + + def test_ac2_stale_and_unreadable_locks_refuse_start(self): + d, root = self.runs_root() + sched = self.schedule_file(d) + owner = self.put_lock(root, {"leaf": "l", "run_id": "pair-0001.ours", "pid": self.dead_pid(), "utc": "2026-10-28T00:00:00Z", + "boot_time": RC.boot_time_iso(), "created_by": "x"}) + rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file") + self.assertEqual((rc, "LOCK_STALE" in err), (RC.EXIT_LOCK_HELD, True), err) + with open(owner, "w") as fh: + fh.write("not json") + rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file") + self.assertEqual((rc, "LOCK_UNREADABLE" in err), (RC.EXIT_LOCK_HELD, True), err) + self.assertTrue(os.path.exists(owner)) + + def test_the_own_live_lock_of_the_slot_passes_the_check(self): + d, root = self.runs_root() + self.put_lock(root, {"leaf": "l", "run_id": "pair-0001.ours", "pid": 4242, "utc": "2026-10-28T00:00:00Z", "boot_time": BOOT, + "created_by": "x"}) + ctx = self.ctx(boot=BOOT, alive=lambda p: p == 4242) + self.assertEqual(RC.check_lock(root, "pair-0001.ours", mode="file", ctx=ctx)["holder"]["pid"], 4242) + with self.assertRaises(RC.RunCoreError) as cm: + RC.check_lock(root, "pair-0001.ours", mode="file", ctx=self.ctx(boot=OTHER_BOOT, alive=lambda p: True)) + self.assertEqual(cm.exception.extra["reason"], "LOCK_STALE") + with self.assertRaises(RC.RunCoreError) as cm: + RC.check_lock(root, "pair-0002.ours", mode="file", ctx=ctx) + self.assertEqual(cm.exception.extra["reason"], "LOCK_FOREIGN") + + def test_no_lock_and_clean_root_start_succeeds(self): + d = self.tmpdir() + sched = self.schedule_file(d) + rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours") + self.assertEqual(rc, 0, err) + + def test_run_root_must_be_named_runs_for_the_windows_lock(self): + d = self.tmpdir() + with self.assertRaises(RC.RunCoreError) as cm: + RC.lock_location(os.path.join(d, "series1"), mode="file") + self.assertEqual(cm.exception.code, RC.EXIT_MALFORMED) + self.assertIn("runs", str(cm.exception)) + rc, out, err = self.raw("lock", "--run-root", os.path.join(d, "series1"), "--run-id", "R", "--leaf", "l", "--mode", "file") + self.assertEqual(rc, RC.EXIT_MALFORMED, err) + self.assertFalse(os.path.exists(os.path.join(d, "series1", "locks")), "no lock where the watchdog cannot see it") + explicit = os.path.join(d, "mylocks") # an explicit lock directory is still allowed + self.assertEqual(RC.lock_location(os.path.join(d, "series1"), lock_dir=explicit, mode="file")[1], os.path.abspath(explicit)) + self.assertEqual(RC.lock_location(os.path.join(d, "runs"), mode="file")[1], os.path.join(d, "locks")) + + def test_ac5_unlock_after_the_guard_removed_the_lock_exits_0(self): + d, root = self.runs_root() + for mode in ("file", "mkdir"): + rc, out, err = self.raw("lock", "--run-root", root, "--run-id", "R1", "--leaf", "l", "--mode", mode) + self.assertEqual(rc, 0, err) + owner = json.loads(out)["lock"] + os.remove(owner) # what guard.ps1 does after the cool-down + if mode == "mkdir": + os.rmdir(os.path.dirname(owner)) + rc, out, err = self.raw("unlock", "--run-root", root, "--run-id", "R1", "--mode", mode) + self.assertEqual(rc, 0, mode + err) + self.assertTrue(json.loads(out)["already_released"]) + # the exemption is for a missing lock only: a lock of another run is still refused + self.raw("lock", "--run-root", root, "--run-id", "R2", "--leaf", "l", "--mode", "file") + rc, out, err = self.raw("unlock", "--run-root", root, "--run-id", "R1", "--mode", "file") + self.assertEqual(rc, RC.EXIT_LOCK_HELD) + + def test_ac4_heartbeat_reader(self): + d = self.tmpdir() + self.assertEqual(RC.read_heartbeat(d)["state"], "missing") + hb = RC.Heartbeat(os.path.join(d, "heartbeat.json"), "pair-0001.ours", now=lambda: "2026-10-28T10:00:00.000000Z") + hb.beat() + self.assertEqual(RC.read_heartbeat(d, now="2026-10-28T10:01:30.000000Z")["state"], "fresh") + info = RC.read_heartbeat(d, now="2026-10-28T10:05:00.000000Z") + self.assertEqual((info["state"], info["age_s"]), ("stale", 300.0)) + self.assertEqual(RC.read_heartbeat(d, max_age_s=400, now="2026-10-28T10:05:00.000000Z")["state"], "fresh") + with open(os.path.join(d, "heartbeat.json"), "w") as fh: + fh.write("{broken") + self.assertEqual(RC.read_heartbeat(d)["state"], "unreadable") + + def test_ac4_heartbeat_cli_exit_codes(self): + d = self.tmpdir() + rc, out, err = self.raw("heartbeat", "--run-dir", d) + self.assertEqual(rc, RC.EXIT_HEARTBEAT, err) + RC.Heartbeat(os.path.join(d, "heartbeat.json"), "pair-0001.ours").beat() # real clock: written just now + rc, out, err = self.raw("heartbeat", "--run-dir", d) + self.assertEqual(rc, 0, err) + self.assertEqual(json.loads(out)["state"], "fresh") + + def test_ac4_resume_reports_a_live_owner_with_a_stale_heartbeat(self): + d = self.tmpdir() + sched = self.schedule_file(d) + ledger = os.path.join(d, "ledger.jsonl") + RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx(pid=4242)) + live = self.ctx(pid=4242, alive=lambda p: p == 4242) + res = RC.resume_ledger(ledger, sched, ctx=live) + self.assertEqual(res["in_flight"], ["pair-0001.ours"]) + self.assertEqual(res["stale_heartbeat"], ["pair-0001.ours"], "no heartbeat.json at all") + RC.Heartbeat(os.path.join(d, "pair-0001", "ours", "heartbeat.json"), "pair-0001.ours").beat() + self.assertEqual(RC.resume_ledger(ledger, sched, ctx=live)["stale_heartbeat"], []) + + class TestMachineFacts(Base): def test_pid_alive_and_dead(self): self.assertTrue(RC.pid_alive(os.getpid())) From 9750539d4dec4985699628d9a70f04a4d92b8020 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 29 Oct 2026 01:26:26 +0100 Subject: [PATCH 3/5] STRA-329: native-cpu-expert AVX2 IQ4_XS multi-token route, fused Q2_0 correction, KAB1 ext case set Confirmed against the C++ in engine/strata and fixed: - rust_native_general.rs group_dot_bytes_policy omitted the `gu == 23 && !avx512` multi-token branch of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`); rust_pool.rs had it since STRA-324. The choice is now one function, gu_multi_route, shared in shape with the pool. Regression: a differential test (re-runs itself with STRATA_FORCE_AVX2=1 on an AVX-512 CPU) fails with a 1-ULP difference on the old code, plus a routing-table test. - rust_legacy.rs row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) now fuses `corr += d*(hx0+hx1)` like expert.cpp row_dot (line 242) and row_dot_multi (line 294) under GCC -mfma. Regression: scalar model, fails on old code. NOT changed, unconfirmed (need the pinned ggml source, which is not in the repo): rust_kq.rs small_dot `sums += m*s`, rust_k_blocks.rs mins_sum, rust_ggml_extra.rs iq1 scalar. KAB1: new `--cases ext` (72 cases; the 40 of `all` are untouched) adds token counts 4-7 for the row-type list and IQ2_XXS / IQ2_XS at 1..8 tokens; GateUpFormat gains Iq2Xxs / Iq2Xs (additive; the runtime still admits only 18/21/22/23/42). The C++ driver edits are list-only and were NOT compiled here (no ggml). 16 tokens exceed MAXT and the KAB1 header and are not covered. New Rust-only test token_count_invariance: the first two tokens of a group are bit-identical for groups of 2..8 tokens on all 14 gate/up x down pairs. Co-Authored-By: Claude Sonnet 5.5 --- .../native-cpu-expert/examples/kernel_ab.rs | 4 +- crates/native-cpu-expert/src/lib.rs | 6 +- crates/native-cpu-expert/src/rust_legacy.rs | 25 +++++- .../src/rust_native_general.rs | 66 +++++++++++++- .../tests/borrowed_group_parity.rs | 2 + .../native-cpu-expert/tests/cpu_pool_probe.rs | 2 + .../tests/token_count_invariance.rs | 86 +++++++++++++++++++ tools/kernel-ab/README.md | 4 +- tools/kernel-ab/cpp/kab.cpp | 14 ++- tools/kernel-ab/verify_manifest.py | 9 +- 10 files changed, 204 insertions(+), 14 deletions(-) create mode 100644 crates/native-cpu-expert/tests/token_count_invariance.rs diff --git a/crates/native-cpu-expert/examples/kernel_ab.rs b/crates/native-cpu-expert/examples/kernel_ab.rs index fa710b78..0d98dc71 100644 --- a/crates/native-cpu-expert/examples/kernel_ab.rs +++ b/crates/native-cpu-expert/examples/kernel_ab.rs @@ -68,12 +68,14 @@ thread_local! { static BUFFERS: Cell = const { Cell::new(0) }; } // ------------------------------------------------------------------------------------------------ formats /// (ggml id, format, block elements, block bytes, name) as `lib.rs kind()/block()`. -const GATE_UP: [(i32, GateUpFormat, usize, usize, &str); 5] = [ +const GATE_UP: [(i32, GateUpFormat, usize, usize, &str); 7] = [ (18, GateUpFormat::Iq3Xxs, 256, 98, "IQ3_XXS"), (21, GateUpFormat::Iq3S, 256, 110, "IQ3_S"), (22, GateUpFormat::Iq2S, 256, 82, "IQ2_S"), (23, GateUpFormat::Iq4Xs, 256, 136, "IQ4_XS"), (42, GateUpFormat::Q2_0, 64, 18, "Q2_0"), + (16, GateUpFormat::Iq2Xxs, 256, 66, "IQ2_XXS"), + (17, GateUpFormat::Iq2Xs, 256, 74, "IQ2_XS"), ]; const DOWN: [(i32, DownFormat, usize, usize, &str); 2] = [(20, DownFormat::Iq4Nl, 32, 18, "IQ4_NL"), (42, DownFormat::Q2_0, 64, 18, "Q2_0")]; diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index 1007a8df..c6b4fda2 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -63,12 +63,12 @@ pub const MAX_BATCH_BYTES: usize = 96 * 1024 * 1024; pub enum Error { Shape, Unsupported, Allocation, NonFinite, NativeFailure, BudgetExceeded, Closed } pub type Result = std::result::Result; #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GateUpFormat { Iq3Xxs, Iq3S, Iq2S, Iq4Xs, Q2_0 } +pub enum GateUpFormat { Iq3Xxs, Iq3S, Iq2S, Iq4Xs, Q2_0, Iq2Xxs, Iq2Xs } // Iq2Xxs / Iq2Xs: kernel-A/B coverage (STRA-329); the runtime does not admit them #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DownFormat { Iq4Nl, Q2_0 } impl GateUpFormat { - fn kind(self) -> i32 { match self { Self::Iq3Xxs => 18, Self::Iq3S => 21, Self::Iq2S => 22, Self::Iq4Xs => 23, Self::Q2_0 => 42 } } - fn block(self) -> (usize, usize) { match self { Self::Iq3Xxs => (256,98), Self::Iq3S => (256,110), Self::Iq2S => (256,82), Self::Iq4Xs => (256,136), Self::Q2_0 => (64,18) } } + fn kind(self) -> i32 { match self { Self::Iq3Xxs => 18, Self::Iq3S => 21, Self::Iq2S => 22, Self::Iq4Xs => 23, Self::Q2_0 => 42, Self::Iq2Xxs => 16, Self::Iq2Xs => 17 } } + fn block(self) -> (usize, usize) { match self { Self::Iq3Xxs => (256,98), Self::Iq3S => (256,110), Self::Iq2S => (256,82), Self::Iq4Xs => (256,136), Self::Q2_0 => (64,18), Self::Iq2Xxs => (256,66), Self::Iq2Xs => (256,74) } } } impl DownFormat { fn kind(self) -> i32 { match self { Self::Iq4Nl => 20, Self::Q2_0 => 42 } } diff --git a/crates/native-cpu-expert/src/rust_legacy.rs b/crates/native-cpu-expert/src/rust_legacy.rs index 145033a4..d634dc4f 100644 --- a/crates/native-cpu-expert/src/rust_legacy.rs +++ b/crates/native-cpu-expert/src/rust_legacy.rs @@ -52,13 +52,15 @@ unsafe fn unpack32(p:*const u8)->__m256i{unsafe{ unsafe fn dot32(p:*const u8,q:*const i8)->__m256i{unsafe{ _mm256_dpbusd_epi32(_mm256_setzero_si256(),unpack32(p),_mm256_loadu_si256(q.cast())) }} +// The correction `corr += d*(hx0+hx1)` is ONE fused multiply-add, as in the pinned C++ (expert.cpp row_dot line 242 and row_dot_multi line 294, +// GCC contracts it under -mfma); a separate mul+add rounds twice (STRA-329; the same rule as rust_q2.rs, STRA-324). #[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] unsafe fn row256(codes:&[u8],scales:&[u8],a:&[&ActQ],out:&mut[f32]){unsafe{ let mut acc=[_mm256_setzero_ps();MAX_ROWS];let mut corr=[0.0f32;MAX_ROWS]; assert!(scales.len()/2<=40&&codes.len()>=scales.len()/2*16&&a.len()<=MAX_ROWS); for b in 0..scales.len()/2{let d=half(&scales[b*2..]);let lo=unpack32(codes.as_ptr().add(b*16));let hi=unpack32(codes.as_ptr().add(b*16+8)); for t in 0..a.len(){let x=a[t];let sl=_mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(),lo,_mm256_loadu_si256(x.q.as_ptr().add(b*64).cast())));let sh=_mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(),hi,_mm256_loadu_si256(x.q.as_ptr().add(b*64+32).cast()))); - acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2]),sl,acc[t]);acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2+1]),sh,acc[t]);corr[t]+=d*(x.hx[b*2]+x.hx[b*2+1]); + acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2]),sl,acc[t]);acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2+1]),sh,acc[t]);corr[t]=d.mul_add(x.hx[b*2]+x.hx[b*2+1],corr[t]); } }for t in 0..a.len(){out[t]=hsum_original(acc[t])-corr[t];} }} @@ -149,4 +151,25 @@ mod tests { assert!(catch_unwind(AssertUnwindSafe(||row(&codes[..40*16],&scales[..40*2],&[&a],&mut out,oracle))).is_ok(),"40 blocks, oracle={oracle}"); } } + + // STRA-329: row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) fuses the weight-scale times activation-sum correction like expert.cpp:242/:294. + // With an all-zero activation the integer dots vanish, so the result is exactly -corr and the scalar model below is the whole kernel. + #[test] + fn row256_correction_is_one_fused_multiply_add() { + if !legacy_supported(){eprintln!("SKIP: Original AVX-512 capability required");return;} + let mut seed=0x0329_5eed_1234_abcdu64;let mut next=||{seed^=seed<<13;seed^=seed>>7;seed^=seed<<17;seed}; + let mut differed=0; + for round in 0..8 { + let nb=40usize;let mut scales=vec![0u8;nb*2];let mut a=ActQ::default();let mut codes=vec![0u8;nb*16]; + for v in codes.iter_mut(){*v=next()as u8;} + for b in 0..nb {let e=10+(next()%6)as u16;let m=(next()&0x3ff)as u16;scales[b*2..b*2+2].copy_from_slice(&((e<<10)|m).to_le_bytes()); + for h in 0..2 {a.hx[b*2+h]=((next()%2_000_001)as f32-1_000_000.0)*(0.001+0.37*round as f32);}} + let (mut fused,mut unfused)=(0.0f32,0.0f32); + for b in 0..nb {let d=half(&scales[b*2..]);let s=a.hx[b*2]+a.hx[b*2+1];fused=d.mul_add(s,fused);unfused+=d*s;} + let mut out=[0.0f32];/* SAFETY: legacy_supported() above; 40 blocks of 16 code bytes / 2 scale bytes, the ActQ holds 80 chunks. */unsafe{row256(&codes,&scales,&[&a],&mut out);} + assert_eq!(out[0].to_bits(),(-fused).to_bits(),"round {round}: -corr must be the fused chain"); + if fused.to_bits()!=unfused.to_bits(){differed+=1;} + } + assert!(differed>0,"the fixture must separate the fused and the unfused chain, or the test proves nothing"); + } } diff --git a/crates/native-cpu-expert/src/rust_native_general.rs b/crates/native-cpu-expert/src/rust_native_general.rs index 11f42645..2fcaa9cd 100644 --- a/crates/native-cpu-expert/src/rust_native_general.rs +++ b/crates/native-cpu-expert/src/rust_native_general.rs @@ -24,6 +24,16 @@ pub fn native_gu_rows(f:&NativeFormat,blob:&[u8],act:&[&NativeActivation],ff:&mu pub fn native_down_rows(f:&NativeFormat,blob:&[u8],hq:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()> { f.validate()?;if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}if blob.len()!=f.bytes||hq.is_empty()||hq.len()>i32::MAX as usize||hq.len()!=out.len()||r0>r1||r1>f.n_embd||out.iter().any(|v|v.len()!=f.n_embd){return Err(Error::Shape);}for a in hq{a.check(f.down,f.n_ff)?;}let d=super::rust_simd::dispatch();for r in r0..r1{let row=&blob[f.down_offset+r*f.down_row..f.down_offset+(r+1)*f.down_row];for at in (0..hq.len()).step_by(8){let end=(at+8).min(hq.len());let chunk=&hq[at..end];let mut v=[0.0;8];/* SAFETY: module header; avx2_ok() checked above, `row` is a whole down row of a validated blob. */unsafe{group_dot_policy(f.down,row,chunk,&mut v[..chunk.len()],d,false,hq.len());}for t in 0..chunk.len(){out[at+t][r]=v[t];}}}Ok(()) } +/// Multi-token gate/up kernel choice of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`): +/// Some(true) = the 512-bit kernel, Some(false) = the 256-bit one, None = ggml's per-token dot. IQ4_XS (23) has only the 256-bit kernel and +/// takes it on an AVX2-only tree (STRA-329: this site omitted it, rust_pool.rs `f.gu==23&&!d.avx512` has it since STRA-324). +pub(super) fn gu_multi_route(k:i32,policy_nt:i32,d:&super::rust_simd::Dispatch)->Option { + if policy_nt(kind:Kind,row:&[u8],act:&[&NativeActivation],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool){unsafe{let mut raw:[&[u8];8]=[&[];8];for t in 0..act.len(){raw[t]=act[t].raw();}group_dot_bytes(kind,row,act[0].n,&raw[..act.len()],out,d,gu)}} pub(super) unsafe fn group_dot_bytes(kind:Kind,row:&[u8],n:usize,act:&[&[u8]],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool){unsafe{ @@ -32,7 +42,7 @@ pub(super) unsafe fn group_dot_bytes(kind:Kind,row:&[u8],n:usize,act:&[&[u8]],ou unsafe fn group_dot_policy(kind:Kind,row:&[u8],act:&[&NativeActivation],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool,policy_nt:usize){unsafe{let mut raw:[&[u8];8]=[&[];8];for t in 0..act.len(){raw[t]=act[t].raw();}group_dot_bytes_policy(kind,row,act[0].n,&raw[..act.len()],out,d,gu,policy_nt)}} unsafe fn group_dot_bytes_policy(kind:Kind,row:&[u8],n:usize,act:&[&[u8]],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool,policy_nt:usize){unsafe{ let nt=act.len();let k=kind.original_id();static KQ:std::sync::OnceLock=std::sync::OnceLock::new();let kq=*KQ.get_or_init(||std::env::var("STRATA_KQ256").ok().is_some_and(|s|super::rust_simd::atoi(&s)!=0));if kq&&policy_nt>=2&&((gu&&k==12)||(!gu&&matches!(k,7|8))){if k==12{let mut a=[&[][..];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast::(),n/256);}super::rust_kq::q4_k_dot(row,&a[..nt],out);}else if k==7{let mut a:[&[Q8One];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_kq::q5_one_dot(row,&a[..nt],out);}else{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_kq::q8_zero_dot(row,&a[..nt],out);}return;} - if gu&&(policy_nt as i32)>=d.mt_min&&matches!(k,16|17|18|21|22)&&(d.iq512||d.iq256){let mut a:[&[Q8K];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/256);}if d.iq512{super::rust_iq::dot_multi512(k,row,&a[..nt],out);}else{super::rust_iq::dot_multi256(k,row,&a[..nt],out);}return;} + if gu&&let Some(wide)=gu_multi_route(k,policy_nt as i32,d){let mut a:[&[Q8K];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/256);}if wide{super::rust_iq::dot_multi512(k,row,&a[..nt],out);}else{super::rust_iq::dot_multi256(k,row,&a[..nt],out);}return;} if !gu&&(policy_nt as i32)>=d.mt_min&&k==20&&d.iq4nl{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_iq::iq4nl(row,&a[..nt],out,false);return;} for t in 0..nt{out[t]=super::rust_ggml::dot_raw(kind,row,n,act[t]);} }} @@ -77,3 +87,57 @@ pub fn q2_rows(weights:&[u8],width:usize,act:&[&super::rust_legacy::PlanarActiva if width==0||width>super::H||act.is_empty()||act.len()>8||act.len()!=out.len()||r0>r1{return Err(Error::Shape);}let stride=Kind::Q2Zero.row_bytes(width)?;if weights.len()%stride!=0||r1>weights.len()/stride||out.iter().any(|o|o.len()!=weights.len()/stride)||act.iter().any(|a|a.0.nchunks!= (width/32)as i32){return Err(Error::Shape);}if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);} let empty=super::rust_types::ActQ::default();let mut a=[∅8];for t in 0..act.len(){a[t]=&act[t].0;}let mut values=[0.0;8];/* SAFETY: avx2_ok() (+dq_ok() if avx512_ok()) checked above; rows are `stride = width/64*18 <= 720` bytes (width <= H) and act.len() <= 8 (see rust_q2 bounds). */unsafe{for r in r0..r1{let row=&weights[r*stride..(r+1)*stride];if super::rust_simd::avx512_ok(){super::rust_q2::dot512(row,&a[..act.len()],&mut values[..act.len()]);}else{super::rust_q2::dot256(row,&a[..act.len()],&mut values[..act.len()]);}for t in 0..act.len(){out[t][r]=values[t];}}}Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use super::super::rust_simd::{avx2_ok,avx512_ok,Dispatch}; + fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s} + fn dispatch_of(iq512:bool,iq256:bool,avx512:bool)->Dispatch {Dispatch{iq512,iq256,iq4nl:true,mt_min:2,gather:false,prefetch:0,avx512}} + // native_expert.cpp native_gu_rows: `nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`, then AVX-512 kernel first, else AVX2. + #[test] + fn gu_multi_route_follows_native_gu_rows() { + let avx2_tree=dispatch_of(false,true,false);let avx512_tree=dispatch_of(true,true,true);let no_iq512=dispatch_of(false,true,true);let no_iq256=dispatch_of(true,false,true);let no_iq256_avx2=dispatch_of(false,false,false); + for k in [16,17,18,21,22] { + assert_eq!(gu_multi_route(k,2,&avx2_tree),Some(false),"k {k} avx2 tree");assert_eq!(gu_multi_route(k,1,&avx2_tree),None,"k {k} one token is ggml's dot"); + assert_eq!(gu_multi_route(k,3,&avx512_tree),Some(true),"k {k} avx512 tree");assert_eq!(gu_multi_route(k,3,&no_iq512),Some(false),"k {k} STRATA_NO_IQ512"); + assert_eq!(gu_multi_route(k,3,&no_iq256),Some(true),"k {k} STRATA_NO_IQ256 keeps the 512-bit kernel");assert_eq!(gu_multi_route(k,3,&no_iq256_avx2),None); + } + // IQ4_XS: the 256-bit kernel only, and only where there is no AVX-512 CPU (an AVX-512 CPU keeps ggml's dot for it). + assert_eq!(gu_multi_route(23,2,&avx2_tree),Some(false));assert_eq!(gu_multi_route(23,8,&avx2_tree),Some(false));assert_eq!(gu_multi_route(23,1,&avx2_tree),None); + assert_eq!(gu_multi_route(23,3,&avx512_tree),None);assert_eq!(gu_multi_route(23,3,&no_iq512),None);assert_eq!(gu_multi_route(23,3,&no_iq256_avx2),None); + for k in [2,12,20,42] {assert_eq!(gu_multi_route(k,4,&avx2_tree),None,"k {k} has no multi-token IQ kernel");} + } + // Differential: native_gu_rows with an IQ4_XS gate/up at 2..8 tokens on the AVX2 tree == the multi-token kernel row by row. + // The tree is chosen once per process (OnceLock), so on an AVX-512 CPU the test re-runs itself in a child with STRATA_FORCE_AVX2=1. + #[test] + fn iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel() { + if !avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} + if avx512_ok() { + assert!(std::env::var_os("LELEKA_TEST_AVX2_CHILD").is_none(),"STRATA_FORCE_AVX2=1 did not select the AVX2 tree"); + let path=module_path!();let path=&path[path.find("::").unwrap()+2..]; + let status=std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact",&format!("{path}::iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel"),"--nocapture"]) + .env("STRATA_FORCE_AVX2","1").env("LELEKA_TEST_AVX2_CHILD","1").status().unwrap(); + assert!(status.success(),"child run on the AVX2 tree failed");return; + } + let (n_embd,n_ff)=(512usize,32usize);let f=NativeFormat::new(Kind::Iq4Xs,Kind::Iq4Nl,n_embd,n_ff).unwrap(); + let mut seed=0x5eed_0329_abcd_ef01u64; + for round in 0..3 { + let mut blob=vec![0u8;f.bytes];for v in blob.iter_mut(){*v=xorshift(&mut seed)as u8;} + for b in blob[..f.down_offset].chunks_exact_mut(136){let e=8+(xorshift(&mut seed)%8)as u16;let m=(xorshift(&mut seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} + for nt in [2usize,3,5,8] { + let mut acts:Vec=(0..nt).map(|_|NativeActivation::default()).collect(); + for a in acts.iter_mut(){let x:Vec=(0..n_embd).map(|_|((xorshift(&mut seed)%20001)as f32-10000.0)*(0.001+round as f32)).collect();a.quantize(Kind::Iq4Xs,&x).unwrap();} + let refs:Vec<&NativeActivation>=acts.iter().collect();let mut ff=vec![vec![0.0f32;n_ff];nt]; + {let mut outs:Vec<&mut [f32]>=ff.iter_mut().map(|v|v.as_mut_slice()).collect();native_gu_rows(&f,&blob,&refs,&mut outs,0,n_ff).unwrap();} + let ys:Vec<&[Q8K]>=acts.iter().map(|a|/* SAFETY: quantize(Iq4Xs, n_embd) wrote n_embd/256 Q8K blocks at offset 0 of the 64-aligned activation. */unsafe{std::slice::from_raw_parts(a.raw().as_ptr().cast::(),n_embd/256)}).collect(); + for r in 0..n_ff { + let (mut g,mut u)=([0.0f32;8],[0.0f32;8]); + // SAFETY: avx2_ok() above; rows are whole IQ4_XS rows of the validated blob and every activation has n_embd/256 blocks. + unsafe{super::super::rust_iq::dot_multi256(23,&blob[r*f.gu_row..(r+1)*f.gu_row],&ys,&mut g[..nt]);super::super::rust_iq::dot_multi256(23,&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row],&ys,&mut u[..nt]);} + for t in 0..nt {assert_eq!(ff[t][r].to_bits(),super::super::rust_simd::silu(g[t],u[t]).to_bits(),"round {round} nt {nt} row {r} token {t}");} + } + } + } + } +} diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs index 6d1f3202..51026d65 100644 --- a/crates/native-cpu-expert/tests/borrowed_group_parity.rs +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -35,6 +35,8 @@ fn gate_up_block(f: GateUpFormat) -> (usize, usize) { GateUpFormat::Iq3S => (256, 110), GateUpFormat::Iq2S => (256, 82), GateUpFormat::Iq4Xs => (256, 136), + GateUpFormat::Iq2Xxs => (256, 66), + GateUpFormat::Iq2Xs => (256, 74), GateUpFormat::Q2_0 => (64, 18), } } diff --git a/crates/native-cpu-expert/tests/cpu_pool_probe.rs b/crates/native-cpu-expert/tests/cpu_pool_probe.rs index 5f40c2ce..f1f40f4d 100644 --- a/crates/native-cpu-expert/tests/cpu_pool_probe.rs +++ b/crates/native-cpu-expert/tests/cpu_pool_probe.rs @@ -20,6 +20,8 @@ fn gate_up_block(f: GateUpFormat) -> (usize, usize) { GateUpFormat::Iq3S => (256, 110), GateUpFormat::Iq2S => (256, 82), GateUpFormat::Iq4Xs => (256, 136), + GateUpFormat::Iq2Xxs => (256, 66), + GateUpFormat::Iq2Xs => (256, 74), GateUpFormat::Q2_0 => (64, 18), } } diff --git a/crates/native-cpu-expert/tests/token_count_invariance.rs b/crates/native-cpu-expert/tests/token_count_invariance.rs new file mode 100644 index 00000000..895b2c77 --- /dev/null +++ b/crates/native-cpu-expert/tests/token_count_invariance.rs @@ -0,0 +1,86 @@ +//! STRA-329: a token's expert output must not depend on how many other tokens share its expert once the multi-token kernels are in +//! (from `STRATA_IQ_MT_MIN`, default 2 tokens; native_expert.cpp native_gu_rows "#152"). Checks every gate/up x down pair, including the +//! IQ2_XXS / IQ2_XS gate/up the KAB1 `ext` case set adds, at every token count 2..=8: the first two tokens of a group of n tokens must +//! equal, bit for bit, the same two tokens run as a group of two. One token is excluded on purpose (ggml's per-token dot rounds +//! differently, the very reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, finite FP16 scales. +//! +//! cargo test -p leleka-native-cpu-expert --test token_count_invariance +use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob}; + +const H: usize = 2560; +const FF: usize = 640; + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } +} + +fn gate_up_block(f: GateUpFormat) -> (usize, usize) { + match f { + GateUpFormat::Iq3Xxs => (256, 98), + GateUpFormat::Iq3S => (256, 110), + GateUpFormat::Iq2S => (256, 82), + GateUpFormat::Iq4Xs => (256, 136), + GateUpFormat::Q2_0 => (64, 18), + GateUpFormat::Iq2Xxs => (256, 66), + GateUpFormat::Iq2Xs => (256, 74), + } +} +fn down_block(f: DownFormat) -> (usize, usize) { + match f { + DownFormat::Iq4Nl => (32, 18), + DownFormat::Q2_0 => (64, 18), + } +} + +fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec { + let mut out: Vec = (0..bytes).map(|_| rng.next() as u8).collect(); + for at in (0..bytes).step_by(block) { + let exponent = 5 + (rng.next() % 5) as u16; + let half = ((rng.next() & 1) as u16) << 15 | exponent << 10 | (rng.next() as u16 & 0x3ff); + out[at..at + 2].copy_from_slice(&half.to_le_bytes()); + } + out +} + +fn run(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, blobs: &[Vec; 3], tokens: &[f32], n: usize) -> Vec { + let job = PreparedJob::new( + gu, + down, + blobs[0].clone().into_boxed_slice(), + blobs[1].clone().into_boxed_slice(), + blobs[2].clone().into_boxed_slice(), + tokens[..n * H].to_vec().into_boxed_slice(), + n, + ) + .expect("job"); + let done = pool.start(vec![job], 48 << 20).expect("start").join().unwrap_or_else(|e| panic!("join {gu:?} + {down:?} n={n}: {e:?}")); + done.into_iter().next().expect("one job").into_values().to_vec() +} + +#[test] +fn the_first_two_tokens_do_not_depend_on_the_group_size() { + let mut pool = CpuPool::new(1).expect("pool"); + let mut rng = Rng(0x0329_5eed_9e37_79b9); + let gates = [GateUpFormat::Iq2Xxs, GateUpFormat::Iq2Xs, GateUpFormat::Iq3Xxs, GateUpFormat::Iq3S, GateUpFormat::Iq2S, GateUpFormat::Iq4Xs, GateUpFormat::Q2_0]; + for gu in gates { + for down in [DownFormat::Iq4Nl, DownFormat::Q2_0] { + let (gq, gb) = gate_up_block(gu); + let (dq, db) = down_block(down); + let blobs = [matrix(&mut rng, H / gq * gb * FF, gb), matrix(&mut rng, H / gq * gb * FF, gb), matrix(&mut rng, FF / dq * db * H, db)]; + let tokens: Vec = (0..8 * H).map(|_| ((rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0)).collect(); + let base = run(&mut pool, gu, down, &blobs, &tokens, 2); + for n in 3..=8 { + let wide = run(&mut pool, gu, down, &blobs, &tokens, n); + for i in 0..2 * H { + assert_eq!(wide[i].to_bits(), base[i].to_bits(), "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}"); + } + } + } + } +} diff --git a/tools/kernel-ab/README.md b/tools/kernel-ab/README.md index a799fbbd..452a8eb7 100644 --- a/tools/kernel-ab/README.md +++ b/tools/kernel-ab/README.md @@ -62,7 +62,7 @@ timing load (SC14). `--cases all` is 40 cases: every (gate/up, down) pair of the row-type list, gate/up in {18, 21, 22, 23, 42} x down in {20, 42}, at 1, 2, 3 and 8 tokens (one token takes the single-token dot paths; two and three take the multi-token kernels of the #152 rule; 8 is -`MAXT`). `--cases gu:down:rows[,...]` selects others. Data is synthetic and the seed is informational (KAB1: inputs are always +`MAXT`). `--cases ext` (STRA-329, not yet run: the C++ driver needs the pinned ggml, see the leaf) adds 72 cases and leaves the 40 of `all` untouched: the token counts 4, 5, 6 and 7 for the 10 pairs of the row-type list, and the gate/up types IQ2_XXS (16) and IQ2_XS (17) with both down types at 1..8 tokens. 16 tokens are not covered: KAB1 `rows` is 1..8 (`MAXT`). `verify_manifest.py --ids` accepts the id set of `all` or that set plus {16, 17}. `--cases gu:down:rows[,...]` selects others. Data is synthetic and the seed is informational (KAB1: inputs are always the dumped bytes). ## Contract KAB1 (normative copy of the leaf text; files only, no FFI) @@ -126,7 +126,7 @@ the C++ `ExpertJobMulti.nt`; the dispatch keys on `nt` (`mt_min`, #152), so the ## Not covered here * Rust reader, comparison, alternation: STRA-289; the Rust `time` mode: STRA-318. MSVC build: STRA-255. The A/A class (slower/equal/faster): STRA-313. -* Row types outside the KAB1 list (the K-quants, NVFP4, the trellis types, IQ2_XXS / IQ2_XS / IQ1_*): not generated. +* Row types outside the KAB1 list (the K-quants, NVFP4, the trellis types, IQ1_*): not generated. IQ2_XXS / IQ2_XS only in `--cases ext`. * CMake itself was not run (see above). `GGML_NATIVE=ON` ties the ggml-cpu half to the build host's CPU. ## Timing (`kab time`, `aa.sh`; STRA-317 / S0.8a2) diff --git a/tools/kernel-ab/cpp/kab.cpp b/tools/kernel-ab/cpp/kab.cpp index 225820ab..43ff97fb 100644 --- a/tools/kernel-ab/cpp/kab.cpp +++ b/tools/kernel-ab/cpp/kab.cpp @@ -56,12 +56,13 @@ constexpr uint32_t kTreeAvx512 = 0, kTreeAvx2 = 1; struct Fmt { int id; const char* name; int qk; int bytes; }; // elements per block, bytes per block (lib.rs block()) constexpr Fmt kFmts[] = {{18, "IQ3_XXS", 256, 98}, {21, "IQ3_S", 256, 110}, {22, "IQ2_S", 256, 82}, - {23, "IQ4_XS", 256, 136}, {42, "Q2_0", 64, 18}, {20, "IQ4_NL", 32, 18}}; + {23, "IQ4_XS", 256, 136}, {42, "Q2_0", 64, 18}, {20, "IQ4_NL", 32, 18}, + {16, "IQ2_XXS", 256, 66}, {17, "IQ2_XS", 256, 74}}; const Fmt* fmt_of(int id) { for (const Fmt& f : kFmts) if (f.id == id) return &f; return nullptr; } -bool gu_ok(int id) { return id == 18 || id == 21 || id == 22 || id == 23 || id == 42; } +bool gu_ok(int id) { return id == 16 || id == 17 || id == 18 || id == 21 || id == 22 || id == 23 || id == 42; } bool down_ok(int id) { return id == 20 || id == 42; } size_t gu_bytes(const Fmt& f) { return (size_t) (H / f.qk) * (size_t) f.bytes * (size_t) FF; } size_t down_bytes(const Fmt& f) { return (size_t) (FF / f.qk) * (size_t) f.bytes * (size_t) H; } @@ -399,6 +400,15 @@ std::vector parse_cases(const std::string& spec, uint64_t seed) { for (int gu : {18, 21, 22, 23, 42}) for (int dn : {20, 42}) for (int rows : {1, 2, 3, 8}) add(gu, dn, rows); + } else if (spec == "ext") { + // STRA-329 (the 40 cases of "all" are unchanged): the token counts 4, 5, 6 and 7 of the row-type list, and IQ2_XXS / IQ2_XS + // (gate/up types 16 and 17) with both down types at every token count 1..8. 16 tokens exceed MAXT (8) and the KAB1 header. + for (int gu : {18, 21, 22, 23, 42}) + for (int dn : {20, 42}) + for (int rows : {4, 5, 6, 7}) add(gu, dn, rows); + for (int gu : {16, 17}) + for (int dn : {20, 42}) + for (int rows : {1, 2, 3, 4, 5, 6, 7, 8}) add(gu, dn, rows); } else { size_t at = 0; while (at < spec.size()) { diff --git a/tools/kernel-ab/verify_manifest.py b/tools/kernel-ab/verify_manifest.py index 4a169522..6fff737d 100755 --- a/tools/kernel-ab/verify_manifest.py +++ b/tools/kernel-ab/verify_manifest.py @@ -21,11 +21,12 @@ MAGIC_IN = 0x4942414B # 'KABI' MAGIC_OUT = 0x4F42414B # 'KABO' VERSION = 1 H, FF = 2560, 640 -GU_IDS = (18, 21, 22, 23, 42) +GU_IDS = (16, 17, 18, 21, 22, 23, 42) # 16 / 17 only in the `ext` case set (STRA-329) DOWN_IDS = (20, 42) REQUIRED_IDS = {18, 20, 21, 22, 23, 42} +EXT_IDS = REQUIRED_IDS | {16, 17} # ggml id -> (elements per block, bytes per block): crates/native-cpu-expert/src/lib.rs block() -BLOCK = {18: (256, 98), 21: (256, 110), 22: (256, 82), 23: (256, 136), 42: (64, 18), 20: (32, 18)} +BLOCK = {18: (256, 98), 21: (256, 110), 22: (256, 82), 23: (256, 136), 42: (64, 18), 20: (32, 18), 16: (256, 66), 17: (256, 74)} TREE_ID = {"avx512": 0, "avx2": 1} IN_HEADER = 64 OUT_HEADER = 20 @@ -156,8 +157,8 @@ def verify(d, want_ids): raise Refused("manifest.json", "is older than another file: it must be written last") if want_ids: print("{" + ", ".join(str(i) for i in sorted(ids)) + "}") - if ids != REQUIRED_IDS: - raise Refused("manifest.json", "id set %s is not the row-type list %s" % (sorted(ids), sorted(REQUIRED_IDS))) + if ids not in (REQUIRED_IDS, EXT_IDS): + raise Refused("manifest.json", "id set %s is not the row-type list %s (or, for the ext case set, %s)" % (sorted(ids), sorted(REQUIRED_IDS), sorted(EXT_IDS))) except Refused as e: print("REFUSED %s" % e, file=sys.stderr) return 1 From 104659b07b01371b7401ad637ec7c41410d1725f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 29 Oct 2026 01:26:26 +0100 Subject: [PATCH 4/5] series_eval: state the E3 standard error and degrees-of-freedom wording explicitly The module docstring (the in-repo spec of the E3 statistics) now says the standard error is sd / sqrt(n_eff), and that dof = max(1, floor(n_eff - 1)) is floored first and never below 1. Wording only; no code change. Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/evidence/series_eval.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/e2e/evidence/series_eval.py b/scripts/e2e/evidence/series_eval.py index 836da923..5b0f93a7 100644 --- a/scripts/e2e/evidence/series_eval.py +++ b/scripts/e2e/evidence/series_eval.py @@ -23,8 +23,11 @@ DEFINITIONS (the golden vectors of STRA-310 fix what the BA text leaves open; se l_i ln(V_i / O_i) for wall_norm and ttft_sum (lower is better), ln(O_i / V_i) for decode_tps (higher is better); positive = ours better. Only valid pairs, ordered by pair number; the first N valid pairs form the series (later pairs are outside the schedule, E6). r1 lag-1 autocorrelation sum_{i 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1. - CI mean +- t(1 - alpha/2, dof) * sd / sqrt(n_eff); alpha = 0.05 for the verdicts, 0.0221 for the interim SLOWER test. + n_eff n (1 - r1) / (1 + r1) when r1 > 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1: the floor of n_eff - 1 is + taken first and the result is never below 1 (n_eff < 2 gives dof 1, not 0). + se the standard error of the mean is sd / sqrt(n_eff) (sd / sqrt(n) when r1 <= 0, where n_eff = n), NOT sd / sqrt(n): the lag-1 + correction acts on the standard error and on the degrees of freedom together (E3; STRA-329 wording fix). + CI mean +- t(1 - alpha/2, dof) * se; alpha = 0.05 for the verdicts, 0.0221 for the interim SLOWER test. mde 2.8 * sd / sqrt(n) (log-ratio units, charter 4.3 / E1). EPS 1e-12: a bound within EPS of a threshold counts as ON it (so an sd = 0 CI exactly on 0 or on ln 0.99 is well defined). strict (wall_norm) PASS lo > 0; SLOWER hi < 0; TIE CI contains 0 and lies in [ln 0.99, ln 1.01]; else INCONCLUSIVE. From 7788651476c6ac1173258e7f06d3c85a40813fe6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 29 Oct 2026 01:32:25 +0100 Subject: [PATCH 5/5] STRA-328: paired reply-tail equivalence check (plan, tool, tests) and consistent prefix-cache doc No default changes. scripts/e2e/prefix_tail_equivalence.py scores the `reply` prefix-cache tail live: record an agent session against the reply arm (history built from its own output, so it resumes from its own reply checkpoint), replay the exact request bodies on a cold server (--prefix-cache-mib 0), and judge greedy identity of every output item, tool-call integrity of each arm (declared name, call_id, JSON arguments against the tool schema, streamed deltas == done == item, response.completed), restore evidence (cached_tokens) and, with --control, cold-vs-cold determinism. Verdicts PASS / FAIL_* / INCONCLUSIVE_*. Two sequential phases because one 5090 cannot hold two serve instances. Tested on in-process fake servers (15 tests); it has NOT been run against the engine. The plan (scripts/e2e/prefix_tail_equivalence_plan.md) also records the open numeric-gate decision (q_tail_gate needs teacher-forced captures). docs/prefix-cache.md: the stale "EXPERIMENTAL: off by default" lines now agree with the measured paragraph, and both say that the rtx5090-32g profile sets the tail while the live equivalence gate is open. Co-Authored-By: Claude Sonnet 5.5 --- docs/prefix-cache.md | 10 +- scripts/e2e/prefix_tail_equivalence.py | 445 ++++++++++++++++++++ scripts/e2e/prefix_tail_equivalence_plan.md | 70 +++ scripts/e2e/test_prefix_tail_equivalence.py | 205 +++++++++ 4 files changed, 726 insertions(+), 4 deletions(-) create mode 100644 scripts/e2e/prefix_tail_equivalence.py create mode 100644 scripts/e2e/prefix_tail_equivalence_plan.md create mode 100644 scripts/e2e/test_prefix_tail_equivalence.py diff --git a/docs/prefix-cache.md b/docs/prefix-cache.md index 8544c229..937de378 100644 --- a/docs/prefix-cache.md +++ b/docs/prefix-cache.md @@ -140,7 +140,7 @@ physical owner invalidates it with the stack. | --- | --- | --- | | `--prefix-cache-mib auto\|N\|0` | off | Host-RAM budget; `auto` per the profile above. Turning it on replaces the conversation cache. | | `--prefix-cache-block TOKENS` | the prefill capacity | Block size and chunk grid; a multiple of 256, at most the prefill capacity. | -| `--prefix-cache-tail off\|prompt\|reply` | off | Also checkpoint where the agent's next turn resumes (request-end checkpoints, below). `reply` is EXPERIMENTAL. | +| `--prefix-cache-tail off\|prompt\|reply` | off | Also checkpoint where the agent's next turn resumes (request-end checkpoints, below). `reply` is off in the engine; the `rtx5090-32g` profile sets it, and its live equivalence gate is still OPEN (STRA-328). | | `LELEKA_PREFIX_TRACE=1` | off | One line per admitted checkpoint. | Logs (stderr, `leleka-serve ...`): `prefix cache on: ...` at open; per request `prefix request: n= hit= resume= shared= @@ -165,7 +165,9 @@ summary. A request that resumes from a tail reads its suffix with the neutral cu * `reply`: also one at the end of the decode, at the end of prompt + committed reply, where the next turn resumes. This needs the session settled (`settle_state`) and the draft ring in step; the controller drafts the last window too (`set_final_draft`) so the ring stands at the session's position after EOS. The cells past the prompt were produced by the decode, so the state is not what a prefill would produce (the Original's live continuation). - EXPERIMENTAL: off by default, and not to be defaulted before the agreement gate below passes. + Off by default in the engine. The `rtx5090-32g` profile sets it (see the paragraph below), but the live gate that would justify a lossy default -- reply + restore vs a cold prefill of the same tokens, greedy identity and tool-call integrity -- has NOT been run (STRA-328, plan and tool: + `scripts/e2e/prefix_tail_equivalence_plan.md`). * Exactness: grid nodes stay exact by construction. A tail is not canonical: `prompt` differs from a grid-only full read by where the chunks were cut (rounding level, same as any chunk-size change), `reply` also by decode-produced cells. The gate is empirical: replay with the static tier, seed off, `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0`, arms G (grid only) / P / R in one process (`LELEKA_REPLAY_ARMS=G=off,P=prompt,R=reply`, @@ -188,8 +190,8 @@ every node for a **retention time of wall-clock minutes since its last use** (`r `when_the_budget_runs_out_the_session_idle_longest_is_displaced_first` (the policy takes the wall time from the caller, so they are exact). `--prefix-cache-tail reply` is the slot-equivalent resume (the checkpoint stands where the agent's next turn continues, built from the -decode-produced cells exactly as the Original's live continuation; it includes the `prompt` checkpoint). **Measured and now the default of the -`rtx5090-32g` profile** (`memory.prefix_cache_tail`): live Codex CRM sessions (jobs 945d grid-only, 9e2 `prompt`, 9e3 `reply`, 64-72 requests +decode-produced cells exactly as the Original's live continuation; it includes the `prompt` checkpoint). **Measured, and the default of the +`rtx5090-32g` profile although its equivalence gate is open (STRA-328)** (`memory.prefix_cache_tail`): live Codex CRM sessions (jobs 945d grid-only, 9e2 `prompt`, 9e3 `reply`, 64-72 requests of ~70k tokens each): median prefill 2265 -> 1094 -> 706 ms, p90 3620 -> 2394 -> 1064 ms, re-prefilled tokens per request 2743 -> 1869 -> 1630, decode unchanged (130.1 / 131.5 / 130.7 tok/s), no failures. Agreement (job 9d4, 40 requests of 9e3 teacher-forced along their recorded tokens, top-16 log-probabilities of 64k rows per arm, `scripts/quality/q_tail_gate.py`): d_top1 p99 0.394 (`prompt`) / 0.401 (`reply`), flips 1.49 % / diff --git a/scripts/e2e/prefix_tail_equivalence.py b/scripts/e2e/prefix_tail_equivalence.py new file mode 100644 index 00000000..27ea513b --- /dev/null +++ b/scripts/e2e/prefix_tail_equivalence.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""Paired equivalence check of the prefix-cache `reply` tail (STRA-328): reply-checkpoint restore vs a cold prefill of the same tokens. + +OFFLINE TEST DRIVER, stdlib only, Python >= 3.9; never part of serving. It launches no engine and touches no GPU by itself: the operator runs two +`leleka-serve` instances on the 5090 (not at the same time as other GPU jobs) and this script talks to both over /v1/responses. + +THE QUESTION. With `--prefix-cache-tail reply` the next turn of an agent session resumes from a checkpoint taken after the committed reply, so the +cells past the prompt were written by the DECODE kernels, not by prefill (docs/prefix-cache.md, "Request-end checkpoints"). A cold prefill of the +very same tokens writes them with the prefill kernels. The two states are not bit-identical by construction; the existing evidence (job 9d4, +flips 1.45 % vs a chunk-cut control 1.45 %) shows only that `reply` sits at the noise floor and could not score `reply` itself (a replay's greedy +replies diverge from the recorded ones). This script scores it live: the SAME input goes to both arms at every request of a multi-turn agent +session, the history being built from the reply-arm's own output (so the reply arm resumes from its own reply checkpoint, as in production). + +ARMS (identical in everything except the cache; the operator starts them, this script only checks what it can see) + cold `--prefix-cache-mib 0` (no prefix cache, every request prefilled from token 0) [or a fresh process per request: see --cold-note] + reply `--prefix-cache-mib --prefix-cache-tail reply` + Same model digest, context, KV type, speculation settings, seed policy and `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0` (docs/prefix-cache.md: the + static tier, so the expert placement does not move between arms). Greedy: every request carries temperature 0. + +PER REQUEST (one pair = the same body to both arms; request order inside a pair is reply first, then cold, so the reply arm's cache state is the +production one) + 1. outputs: the output items (message text, function_call name and arguments string, reasoning text) must be IDENTICAL, string for string. + 2. tool-call integrity, checked on EACH arm separately: every function_call has a declared name, a non-empty call_id, `arguments` that parses as a + JSON object and satisfies the tool's schema (types of the properties, required keys), the streamed argument deltas concatenate to the `done` + arguments and to the item's, and the stream ends with response.completed (a cut-off or failed stream is an integrity failure). + 3. restore evidence: the reply arm reports `usage.input_tokens_details.cached_tokens`; a request after the first counts as RESTORED when + cached_tokens >= --min-cached-fraction of its input_tokens (default 0.5); the cold arm must report ~0. Without restores the run proves nothing. + 4. control (--control): the cold request is sent TWICE; if the two cold outputs differ, greedy decoding is not run-to-run deterministic on this + setup and no difference between the arms can be attributed to the restore (INCONCLUSIVE_NONDETERMINISTIC). + +VERDICT (pure function `judge()`, unit-tested in test_prefix_tail_equivalence.py) + PASS every pair identical, no integrity failure on either arm, restores observed on >= --min-restore-fraction of the + requests after the first, control (when used) deterministic. + FAIL_OUTPUT_DIFFERS some pair differs (the first differing request, item and character are recorded). + FAIL_TOOL_CALL_INTEGRITY a function_call (or a stream) of either arm is malformed; arm and request recorded. Reported before OUTPUT_DIFFERS. + INCONCLUSIVE_NO_RESTORE the reply arm restored on too few requests (check the server flags / cache budget); the outputs are not evidence. + INCONCLUSIVE_NONDETERMINISTIC the control found cold != cold. + INCONCLUSIVE_COLD_ARM_WARM the cold arm itself served cached tokens (it is not cold: start it with `--prefix-cache-mib 0`). + ERROR transport or protocol failure. + Exit code: 0 PASS, 1 FAIL_*, 2 INCONCLUSIVE_*, 3 usage, 4 ERROR. + +The numeric complement (AC1: q_pair / class gate numbers) is separate and uses the logs of the same two arms: see +scripts/e2e/prefix_tail_equivalence_plan.md, section "Numeric gate". + +TWO PHASES. A 5090 cannot hold two serve instances, so the normal run is sequential: `record` against the reply arm (phase 1), then restart the +server WITHOUT the prefix cache and `replay` the recorded requests unchanged against it (phase 2). `run` does both at once when two servers fit. + +COMMANDS (server; nothing else on the GPU) + 1. reply arm up (`--prefix-cache-mib --prefix-cache-tail reply`): + python3 scripts/e2e/prefix_tail_equivalence.py record --reply-url http://127.0.0.1:8081 --model --key-file \\ + --context-file --turns 12 --record-out /tail-record.json + 2. stop it; start the cold arm with the same flags except `--prefix-cache-mib 0`: + python3 scripts/e2e/prefix_tail_equivalence.py replay --cold-url http://127.0.0.1:8081 --record /tail-record.json --control \\ + --key-file --out /tail-equivalence.json + (both arms at once: `run --cold-url U1 --reply-url U2 --model M ... --control --out F`) + +The result file holds prompts' hashes and the reply text: keep it outside Git. The API key is never written to any output. +""" +import argparse +import hashlib +import json +import os +import sys +import time +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +EXIT = {"PASS": 0, "FAIL_OUTPUT_DIFFERS": 1, "FAIL_TOOL_CALL_INTEGRITY": 1, "INCONCLUSIVE_NO_RESTORE": 2, "INCONCLUSIVE_NONDETERMINISTIC": 2, + "INCONCLUSIVE_COLD_ARM_WARM": 2, "ERROR": 4} +MAX_TOOL_ROUNDS = 4 +DEFAULT_TURNS = [ + "Use the shell tool to list the files in the current directory (run `ls -la`).", + "Use the read_file tool to read the file src/main.rs, lines 1 to 40, then summarise it in two sentences.", + "Use the update_plan tool to record a three step plan: inspect the code (completed), fix the bug (in_progress), run the tests (pending).", + "Now say in one sentence what you would do next. Do not call a tool.", +] + + +def sha256_text(text): + return hashlib.sha256(text.encode("utf8")).hexdigest() + + +# ---- schema check (small subset of JSON Schema: type, properties, required, items) ------------------------------------------------------------- +def _type_ok(t, v): + return {"object": isinstance(v, dict), "array": isinstance(v, list), "string": isinstance(v, str), "boolean": isinstance(v, bool), + "integer": isinstance(v, int) and not isinstance(v, bool), + "number": isinstance(v, (int, float)) and not isinstance(v, bool), "null": v is None}.get(t, True) + + +def schema_errors(schema, v, path="$"): + errs = [] + t = schema.get("type") + if t and not _type_ok(t, v): + return ["%s: expected %s" % (path, t)] + if isinstance(v, dict): + for k in schema.get("required", []): + if k not in v: + errs.append("%s: missing required key %s" % (path, k)) + for k, sub in (schema.get("properties") or {}).items(): + if k in v: + errs.extend(schema_errors(sub, v[k], path + "." + k)) + if schema.get("additionalProperties") is False: + errs.extend("%s: unexpected key %s" % (path, k) for k in v if k not in (schema.get("properties") or {})) + if isinstance(v, list) and isinstance(schema.get("items"), dict): + for i, x in enumerate(v): + errs.extend(schema_errors(schema["items"], x, "%s[%d]" % (path, i))) + return errs + + +# ---- one streamed request ---------------------------------------------------------------------------------------------------------------------- +def stream_request(base, key, body, timeout=3600): + """Returns {items, usage, status, terminal, deltas_ok, error}. items: the output items as the server finished them.""" + headers = {"Content-Type": "application/json"} + if key: + headers["Authorization"] = "Bearer " + key + req = urllib.request.Request(base.rstrip("/") + "/v1/responses", json.dumps(body).encode(), headers) + out = {"items": [], "usage": {}, "status": None, "terminal": None, "arg_deltas": {}, "arg_done": {}, "error": None} + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + for raw in r: + line = raw.decode("utf8", "replace").strip() + if not line.startswith("data:"): + continue + try: + d = json.loads(line[5:]) + except ValueError: + continue + ty = d.get("type", "") + if ty == "response.output_item.done": + out["items"].append((d.get("output_index"), d.get("item") or {})) + elif ty == "response.function_call_arguments.delta": + out["arg_deltas"].setdefault(d.get("output_index"), []).append(d.get("delta", "")) + elif ty == "response.function_call_arguments.done": + out["arg_done"][d.get("output_index")] = d.get("arguments") + elif ty in ("response.completed", "response.incomplete", "response.failed"): + resp = d.get("response") or {} + out["terminal"], out["status"], out["usage"] = ty, resp.get("status"), resp.get("usage") or {} + if not out["items"] and isinstance(resp.get("output"), list): + out["items"] = list(enumerate(resp["output"])) + except (urllib.error.URLError, OSError, ValueError) as exc: + out["error"] = "%s: %s" % (type(exc).__name__, exc) + out["items"] = [item for _, item in sorted(out["items"], key=lambda p: (p[0] is None, p[0]))] + return out + + +def normalise(items): + """The comparable form of an arm's output: type + the text-bearing fields only (ids and timestamps differ by construction).""" + norm = [] + for it in items: + ty = it.get("type") + if ty == "function_call": + norm.append({"type": ty, "name": it.get("name"), "arguments": it.get("arguments")}) + elif ty == "message": + norm.append({"type": ty, "text": "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict))}) + elif ty == "reasoning": + norm.append({"type": ty, "text": "".join(c.get("text", "") for c in (it.get("content") or []) if isinstance(c, dict))}) + else: + norm.append({"type": ty}) + return norm + + +def first_difference(a, b): + """(item index, 'type'|'field'|'char', detail) of the first difference between two normalised outputs, or None.""" + for i in range(max(len(a), len(b))): + if i >= len(a) or i >= len(b): + return {"item": i, "what": "item count", "a": len(a), "b": len(b)} + if a[i] == b[i]: + continue + for field in sorted(set(a[i]) | set(b[i])): + x, y = a[i].get(field), b[i].get(field) + if x != y: + at = next((j for j in range(min(len(x or ""), len(y or ""))) if (x or "")[j] != (y or "")[j]), min(len(x or ""), len(y or ""))) \ + if isinstance(x, str) and isinstance(y, str) else None + return {"item": i, "what": field, "char": at} + return None + + +def integrity_errors(res, tools): + """Tool-call and stream integrity of ONE arm's response. Returns a list of strings (empty = intact).""" + errs = [] + if res["error"]: + return ["transport: " + res["error"]] + if res["terminal"] != "response.completed": + errs.append("stream ended with %s (status %s), not response.completed" % (res["terminal"], res["status"])) + by = dict((t["name"], t) for t in tools if isinstance(t, dict) and t.get("name")) + for k, it in enumerate(res["items"]): + if it.get("type") != "function_call": + continue + name = it.get("name") + if name not in by: + errs.append("item %d: call to undeclared tool %r" % (k, name)) + if not it.get("call_id"): + errs.append("item %d: no call_id" % k) + try: + args = json.loads(it.get("arguments", "")) + except ValueError as exc: + errs.append("item %d: arguments do not parse as JSON (%s): %.120r" % (k, exc, it.get("arguments", ""))) + continue + if not isinstance(args, dict): + errs.append("item %d: arguments are not a JSON object" % k) + elif name in by: + errs.extend("item %d: %s" % (k, e) for e in schema_errors(by[name].get("parameters", {}), args)) + deltas = "".join(res["arg_deltas"].get(k, [])) + done = res["arg_done"].get(k) + if done is not None and done != it.get("arguments"): + errs.append("item %d: arguments.done differs from the item's arguments" % k) + if deltas and deltas != it.get("arguments"): + errs.append("item %d: streamed argument deltas differ from the item's arguments" % k) + return errs + + +# ---- the verdict, a pure function of the pair records ------------------------------------------------------------------------------------------ +def judge(pairs, min_restore_fraction=0.8, control=False): + """pairs: list of dicts {index, equal, diff, restored (None for the first request), integrity: {reply: [...], cold: [...]}, control_equal (or None), + error (or None)}. Returns {verdict, reasons, restored, restore_candidates}.""" + reasons = [] + if not pairs: + return {"verdict": "ERROR", "reasons": ["no request was completed"], "restored": 0, "restore_candidates": 0} + errors = [p for p in pairs if p.get("error")] + if errors: + return {"verdict": "ERROR", "reasons": ["request %s: %s" % (p["index"], p["error"]) for p in errors], "restored": 0, "restore_candidates": 0} + cands = [p for p in pairs if p.get("restored") is not None] + restored = sum(1 for p in cands if p["restored"]) + broken = [(p["index"], arm, e) for p in pairs for arm in ("reply", "cold") for e in p["integrity"].get(arm, [])] + if broken: + return {"verdict": "FAIL_TOOL_CALL_INTEGRITY", "reasons": ["request %s, %s arm: %s" % b for b in broken[:10]], "restored": restored, + "restore_candidates": len(cands)} + warm = [p["index"] for p in pairs if p.get("cold_warm")] + if warm: + return {"verdict": "INCONCLUSIVE_COLD_ARM_WARM", "reasons": ["the cold arm reported cached tokens at request(s) %s" % warm], "restored": restored, + "restore_candidates": len(cands)} + if control and any(p.get("control_equal") is False for p in pairs): + bad = [p["index"] for p in pairs if p.get("control_equal") is False] + return {"verdict": "INCONCLUSIVE_NONDETERMINISTIC", "reasons": ["two cold runs of the same request differ at request(s) %s" % bad], + "restored": restored, "restore_candidates": len(cands)} + differ = [p for p in pairs if not p["equal"]] + if differ: + return {"verdict": "FAIL_OUTPUT_DIFFERS", "reasons": ["request %d: %s" % (p["index"], json.dumps(p["diff"])) for p in differ[:10]], + "restored": restored, "restore_candidates": len(cands)} + if not cands or restored < min_restore_fraction * len(cands): + return {"verdict": "INCONCLUSIVE_NO_RESTORE", "reasons": ["the reply arm restored %d of %d requests after the first (need %.0f %%)" % ( + restored, len(cands), 100 * min_restore_fraction)], "restored": restored, "restore_candidates": len(cands)} + return {"verdict": "PASS", "reasons": reasons, "restored": restored, "restore_candidates": len(cands)} + + +# ---- the session -------------------------------------------------------------------------------------------------------------------------------- +def message(role, text): + return {"type": "message", "role": role, "content": [{"type": "input_text" if role != "assistant" else "output_text", "text": text}]} + + +def load_scenario(args): + import e2e_client as ec # stdlib-only sibling: TOOLS and the canned tool results of the wire-behaviour scenarios + tools = ec.TOOLS + results = dict(ec.TOOL_RESULTS) + turns = list(DEFAULT_TURNS) + if args.scenario: + with open(args.scenario, "r", encoding="utf-8") as fh: + doc = json.load(fh) + tools, results, turns = doc.get("tools", tools), doc.get("tool_results", results), doc.get("user_turns", turns) + context = [] + for path in args.context_file or []: + with open(path, "r", encoding="utf-8", errors="replace") as fh: + context.append(message("user", fh.read())) + return tools, results, turns, context + + +def request_body(args, tools, history): + body = {"model": args.model, "input": history, "tools": tools, "tool_choice": "auto", "parallel_tool_calls": False, "store": False, + "stream": True, "temperature": 0, "max_output_tokens": args.max_output} + if args.instructions: + body["instructions"] = args.instructions + return body + + +def res_to_json(res): + return {"items": res["items"], "usage": res["usage"], "status": res["status"], "terminal": res["terminal"], "error": res["error"], + "arg_deltas": dict((str(k), v) for k, v in res["arg_deltas"].items()), "arg_done": dict((str(k), v) for k, v in res["arg_done"].items())} + + +def res_from_json(doc): + return {"items": doc["items"], "usage": doc["usage"], "status": doc["status"], "terminal": doc["terminal"], "error": doc["error"], + "arg_deltas": dict((int(k), v) for k, v in doc["arg_deltas"].items()), "arg_done": dict((int(k), v) for k, v in doc["arg_done"].items())} + + +def read_key(args): + if getattr(args, "key_file", None): + with open(args.key_file, "r", encoding="utf-8") as fh: + return fh.read().strip() + return None + + +def drive_reply(args, send=stream_request): + """Phase 1: the agent session against the REPLY arm only. The history is always built from that arm's own output, as an agent's next request would + be, so every request after the first can resume from the arm's reply checkpoint. Returns {tools, records}; a record holds the exact request body + and the arm's response, which phase 2 sends unchanged to the cold arm.""" + key = read_key(args) + tools, results, turns, history = load_scenario(args) + records = [] + for turn_no, user_text in enumerate(turns[:args.turns], 1): + history.append(message("user", user_text)) + for _round in range(MAX_TOOL_ROUNDS): + body = request_body(args, tools, history) + reply = send(args.reply_url, key, body) + records.append({"index": len(records) + 1, "turn": turn_no, "body": json.loads(json.dumps(body)), "reply": res_to_json(reply)}) # a copy: history grows + if reply["error"]: + return {"tools": tools, "records": records} + calls = [it for it in reply["items"] if it.get("type") == "function_call"] + for it in reply["items"]: + if it.get("type") == "message": + history.append(message("assistant", "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict)))) + elif it.get("type") == "function_call": + history.append({"type": "function_call", "call_id": it.get("call_id"), "name": it.get("name"), "arguments": it.get("arguments")}) + if not calls: + break + for it in calls: + history.append({"type": "function_call_output", "call_id": it.get("call_id"), "output": results.get(it.get("name"), "ok")}) + return {"tools": tools, "records": records} + + +def score(args, recorded, send=stream_request): + """Phase 2: the recorded bodies, unchanged, to the COLD arm (twice with --control); compare, check integrity, judge.""" + key = read_key(args) + tools = recorded["tools"] + t0 = time.monotonic() + pairs = [] + for rc in recorded["records"]: + reply = res_from_json(rc["reply"]) + body = rc["body"] + index = rc["index"] + rec = {"index": index, "turn": rc["turn"], "prompt_items": len(body["input"]), "prompt_sha256": sha256_text(json.dumps(body["input"], sort_keys=True)), + "error": None} + if reply["error"]: + rec["error"] = "reply arm: %s" % reply["error"] + pairs.append(rec) + break + cold = send(args.cold_url, key, body) + cold2 = send(args.cold_url, key, body) if args.control else None + if cold["error"]: + rec["error"] = "cold arm: %s" % cold["error"] + a, b = normalise(reply["items"]), normalise(cold["items"]) + rec["equal"] = a == b + rec["diff"] = None if rec["equal"] else first_difference(a, b) + rec["integrity"] = {"reply": integrity_errors(reply, tools), "cold": integrity_errors(cold, tools)} + rec["control_equal"] = None if cold2 is None else (normalise(cold2["items"]) == b) + ru, cu = reply["usage"], cold["usage"] + cached = lambda u: (u.get("input_tokens_details") or {}).get("cached_tokens") # noqa: E731 + rec["usage"] = {"reply": {"input": ru.get("input_tokens"), "cached": cached(ru), "output": ru.get("output_tokens")}, + "cold": {"input": cu.get("input_tokens"), "cached": cached(cu), "output": cu.get("output_tokens")}} + rec["restored"] = None + rec["cold_warm"] = bool(cu.get("input_tokens") and (cached(cu) or 0) >= args.min_cached_fraction * cu.get("input_tokens")) + if index > 1: + inp, cch = ru.get("input_tokens"), cached(ru) + rec["restored"] = bool(inp and cch is not None and cch >= args.min_cached_fraction * inp) + pairs.append(rec) + if rec["error"]: + break + j = judge(pairs, args.min_restore_fraction, args.control) + return {"schema": "prefix-tail-equivalence-v1", "verdict": j["verdict"], "reasons": j["reasons"], "restored": j["restored"], + "restore_candidates": j["restore_candidates"], "requests": len(pairs), "control": bool(args.control), + "min_cached_fraction": args.min_cached_fraction, "min_restore_fraction": args.min_restore_fraction, "elapsed_s": round(time.monotonic() - t0, 1), + "tools": [t.get("name") for t in tools], "pairs": pairs} + + +def run_session(args, send=stream_request): + """Both phases in one process (both arms up at the same time: needs room for two servers).""" + return score(args, drive_reply(args, send), send) + + +def write_json(path, doc): + with open(path, "w", encoding="utf-8", newline="\n") as fh: + fh.write(json.dumps(doc, indent=2) + "\n") + + +class _Parser(argparse.ArgumentParser): + def error(self, message): + sys.stderr.write("%s: error: %s\n" % (self.prog, message)) + raise SystemExit(3) + + +def add_session_options(p): + p.add_argument("--model", required=True) + p.add_argument("--key-file") + p.add_argument("--scenario", help="JSON {tools, tool_results, user_turns}; default: the tools and canned results of e2e_client.py") + p.add_argument("--context-file", action="append", help="text prepended as a user message (repeatable); use ~60-70k tokens for the production regime") + p.add_argument("--instructions") + p.add_argument("--turns", type=int, default=len(DEFAULT_TURNS)) + p.add_argument("--max-output", type=int, default=512) + + +def add_score_options(p): + p.add_argument("--control", action="store_true", help="send every cold request twice (determinism control)") + p.add_argument("--min-cached-fraction", type=float, default=0.5) + p.add_argument("--min-restore-fraction", type=float, default=0.8) + + +def report(result, out): + write_json(out, result) + sys.stdout.write("%s: %d requests, restored %d of %d, %s\n" % (result["verdict"], result["requests"], result["restored"], result["restore_candidates"], + "; ".join(result["reasons"][:3]))) + return EXIT[result["verdict"]] + + +def main(argv=None): + parser = _Parser(prog="prefix_tail_equivalence.py", description=__doc__.split("\n")[0]) + sub = parser.add_subparsers(dest="command") + sub.required = True + p = sub.add_parser("run", help="both arms up at once: record against the reply arm, replay against the cold arm, judge") + p.add_argument("--cold-url", required=True) + p.add_argument("--reply-url", required=True) + p.add_argument("--out", required=True, help="result JSON (run roots outside Git)") + add_session_options(p) + add_score_options(p) + p = sub.add_parser("record", help="phase 1, reply arm only: drive the session and write the exact requests and the arm's answers") + p.add_argument("--reply-url", required=True) + p.add_argument("--record-out", required=True, help="recording JSON (holds prompts and replies: outside Git)") + add_session_options(p) + p = sub.add_parser("replay", help="phase 2, cold arm only (restart the server without the cache first): send the recorded requests, judge") + p.add_argument("--cold-url", required=True) + p.add_argument("--record", required=True) + p.add_argument("--key-file") + p.add_argument("--out", required=True) + add_score_options(p) + args = parser.parse_args(argv) + try: + if args.command == "run": + return report(run_session(args), args.out) + if args.command == "record": + recorded = drive_reply(args) + write_json(args.record_out, recorded) + bad = [r["index"] for r in recorded["records"] if r["reply"]["error"]] + sys.stdout.write("recorded %d requests%s\n" % (len(recorded["records"]), (", transport error at %s" % bad) if bad else "")) + return EXIT["ERROR"] if bad else 0 + with open(args.record, "r", encoding="utf-8") as fh: + recorded = json.load(fh) + return report(score(args, recorded), args.out) + except (OSError, ValueError, ImportError) as exc: + sys.stderr.write("ERROR: %s\n" % exc) + return EXIT["ERROR"] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/e2e/prefix_tail_equivalence_plan.md b/scripts/e2e/prefix_tail_equivalence_plan.md new file mode 100644 index 00000000..c82be706 --- /dev/null +++ b/scripts/e2e/prefix_tail_equivalence_plan.md @@ -0,0 +1,70 @@ +# Test plan: prefix-cache `reply` tail, restore vs cold prefill (STRA-328) + +Status: plan and tool ready; **not run** (needs the 5090, which was not available to this work). Nothing here changes a default. +`rtx5090-32g` still ships `memory.prefix_cache_tail = reply`; the verdict of this plan decides whether that stays (AGENTS.md: a lossy default needs +its quality gate). + +## What is being tested + +After a request the `reply` tail stores a checkpoint at the end of prompt + committed reply +(`crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs`, around lines 511-526). The cells past the prompt were written by the decode +kernels. The next agent turn resumes from there; a cold prefill of the same tokens would write them with the prefill kernels. The states are not +bit-identical by construction, so the question is whether the continuation is the same and whether tool calls stay intact. + +Existing evidence (`docs/prefix-cache.md`, job 9d4/9d5, `scripts/quality/q_tail_gate.py`): d_top1 p99 0.401 and flips 1.45 % for `reply` against 0.394 and +1.45 % for a chunk-cut control, teacher-forced on 40 requests. That shows the noise floor only. A replay cannot score `reply` itself (an arm's own greedy +replies diverge from the recorded ones, so the next recorded prompt no longer extends them) and no tool-call integrity check was recorded. + +## Design + +Paired, live, greedy, same tokens: `scripts/e2e/prefix_tail_equivalence.py`. + +1. **Record (reply arm).** A multi-turn agent session (shell / read_file / update_plan tools with canned tool results, a 60-70k-token context file) + is driven against the reply arm. The history of every request is built from that arm's own output, so each request after the first resumes + from its own reply checkpoint, as in production. The exact request bodies and the arm's answers are written to a recording. +2. **Replay (cold arm).** The server is restarted with `--prefix-cache-mib 0` (everything else identical) and the recorded bodies are sent unchanged: + a cold prefill of identical tokens. With `--control` every cold request is sent twice to establish that greedy decoding is run-to-run + deterministic on this setup; without that control a difference cannot be blamed on the restore. +3. **Judge** (`judge()`): per request, output items identical string for string (message text, function_call name and arguments, reasoning text); + tool-call integrity on each arm (declared name, call_id, arguments parse as a JSON object and satisfy the tool schema, streamed argument deltas == + done == item, stream ends with `response.completed`); restore evidence (`usage.input_tokens_details.cached_tokens` of the reply arm >= 50 % of the + input on at least 80 % of the requests after the first; the cold arm must report none). + +Verdicts and exit codes: `PASS` 0; `FAIL_OUTPUT_DIFFERS`, `FAIL_TOOL_CALL_INTEGRITY` 1; `INCONCLUSIVE_NO_RESTORE`, `INCONCLUSIVE_NONDETERMINISTIC`, +`INCONCLUSIVE_COLD_ARM_WARM` 2; usage 3; `ERROR` 4. An inconclusive run is not evidence for the default. + +## Preconditions on the server + +* The 5090 free of other jobs (one serve instance at a time; the two phases are sequential for that reason). Memory headroom first (`mem_ok`-style + check): the server hung on 2026-10-29 around 23:25Z under memory pressure. +* Same binary, model digest, context, KV type, speculation settings; `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0` (static tier) in both phases. +* Outputs in a run root outside Git (they hold prompts and replies). Record the hardware, software, model digest, flags, token counts and cached + tokens as the charter requires (the result JSON carries per-request input / cached / output tokens). + +## Commands + +``` +python3 scripts/e2e/prefix_tail_equivalence.py record --reply-url http://127.0.0.1:8081 --model --key-file \ + --context-file <60-70k-token text> --turns 12 --record-out /tail-record.json +# stop the server; start it again with the same flags but --prefix-cache-mib 0 +python3 scripts/e2e/prefix_tail_equivalence.py replay --cold-url http://127.0.0.1:8081 --record /tail-record.json --control \ + --key-file --out /tail-equivalence.json +``` + +Run it on at least three independent sessions (different context files / task scripts) before reading anything into a PASS; one session is one sample. + +## Numeric gate (acceptance item AC1, q_pair / class numbers) + +`scripts/quality/q_pair.py LOG_A LOG_B [--control LOG_A2]` compares the top-16 log-probability rows of two port smoke logs of the SAME teacher-forced +corpus bit for bit; `scripts/quality/q_tail_gate.py REPLAY_LOG CAPTURE_DIR [--control LOG2]` applies the rule p99, max and flip rate each <= 1.25 x the +chunk-cut control. Both need teacher-forced logs, and the recording above is not in the capture format `q_tail_gate.py` reads. Open decision for the +owner / TL: either convert the recorded session to a capture directory (the reply arm's tokens as the forced path) or take captures from live +sessions of job 9e3. Until then this plan gives the greedy-identity and tool-call evidence, not the numeric class. + +## Decision rule + +* `PASS` on all sessions and the numeric gate within the control: keep `reply` as the default; add the evidence (verdict JSONs, command lines, + hardware / software / digest) to `docs/prefix-cache.md`. +* Any `FAIL_*`: make `prompt` (or `off`) the profile default and mark `reply` as an explicitly experimental mode. That is a separate change that + needs the owner. +* `INCONCLUSIVE_*`: fix the setup and re-run; the default stays as it is, flagged as unproven. diff --git a/scripts/e2e/test_prefix_tail_equivalence.py b/scripts/e2e/test_prefix_tail_equivalence.py new file mode 100644 index 00000000..ae73d958 --- /dev/null +++ b/scripts/e2e/test_prefix_tail_equivalence.py @@ -0,0 +1,205 @@ +"""Tests of prefix_tail_equivalence.py (STRA-328): the verdict logic on in-process fake servers. No engine, no GPU, no network beyond 127.0.0.1. + +Run: python -m unittest test_prefix_tail_equivalence -v (from scripts/e2e) +""" +import argparse +import hashlib +import http.server +import json +import os +import sys +import tempfile +import threading +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import prefix_tail_equivalence as PT # noqa: E402 + + +class Arm(http.server.BaseHTTPRequestHandler): + """A fake /v1/responses server. cfg: arm ('reply'|'cold') and mode (see the tests); state in server.calls.""" + + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + srv = self.server + srv.calls += 1 + items_in = body["input"] + digest = hashlib.sha256(json.dumps(items_in, sort_keys=True).encode()).hexdigest()[:8] + last = items_in[-1] + out = [] + text = None + if last.get("type") == "function_call_output": + text = "done %d" % len(items_in) + elif "Use the" not in json.dumps(last): + text = "answer %s" % digest + if text is not None: + if srv.mode == "diverge" and srv.arm == "reply" and len(items_in) >= 6: + text += " (decode-state drift)" + if srv.mode == "nondet" and srv.arm == "cold": + text += " #%d" % srv.calls + out.append({"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}) + else: + args = '{"command": ["ls", "-la"]}' + if srv.mode == "bad_args" and srv.arm == "reply": + args = '{"command": ["ls", "-la"' + if srv.mode == "bad_tool" and srv.arm == "reply": + out_name = "rm_rf" + else: + out_name = "shell" + out.append({"type": "function_call", "call_id": "call_" + digest, "name": out_name, "arguments": args}) + n_in = 100 * len(items_in) + cached = 0 + if srv.arm == "reply" and srv.mode != "no_cache" and len(items_in) > 2: + cached = n_in - 50 + if srv.arm == "cold" and srv.mode == "warm_cold" and len(items_in) > 2: + cached = n_in - 50 + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + for k, it in enumerate(out): + if it["type"] == "function_call": + a = it["arguments"] + for part in (a[:5], a[5:]): + self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.delta", "output_index": k, "delta": part}) + "\n\n").encode()) + self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.done", "output_index": k, "arguments": a}) + "\n\n").encode()) + self.wfile.write(("data: " + json.dumps({"type": "response.output_item.done", "output_index": k, "item": it}) + "\n\n").encode()) + done = {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": n_in, "output_tokens": 7, + "input_tokens_details": {"cached_tokens": cached}}}} + if srv.mode == "cut" and srv.arm == "reply": + done = None # the stream just ends + if done: + self.wfile.write(("data: " + json.dumps(done) + "\n\n").encode()) + + +def start(arm, mode): + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Arm) + srv.arm, srv.mode, srv.calls = arm, mode, 0 + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv + + +class Session(unittest.TestCase): + def run_pair(self, reply_mode="ok", cold_mode="ok", control=False, turns=4): + reply, cold = start("reply", reply_mode), start("cold", cold_mode) + for srv in (reply, cold): + self.addCleanup(srv.server_close) + self.addCleanup(srv.shutdown) + args = argparse.Namespace(cold_url="http://127.0.0.1:%d" % cold.server_address[1], reply_url="http://127.0.0.1:%d" % reply.server_address[1], + model="m", key_file=None, scenario=None, context_file=None, instructions=None, turns=turns, max_output=64, + control=control, min_cached_fraction=0.5, min_restore_fraction=0.8) + return PT.run_session(args) + + def test_identical_arms_with_restores_pass(self): + res = self.run_pair(control=True) + self.assertEqual(res["verdict"], "PASS", res["reasons"]) + self.assertGreaterEqual(res["requests"], 5, "tool rounds are requests too") + self.assertEqual(res["restored"], res["restore_candidates"]) + self.assertTrue(any(p["integrity"]["reply"] == [] for p in res["pairs"])) + + def test_a_drifting_reply_arm_fails_with_the_first_difference(self): + res = self.run_pair("diverge") + self.assertEqual(res["verdict"], "FAIL_OUTPUT_DIFFERS") + self.assertIn("char", res["reasons"][0]) + + def test_malformed_tool_arguments_on_the_reply_arm_fail_integrity(self): + res = self.run_pair("bad_args") + self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY") + self.assertIn("reply arm", res["reasons"][0]) + self.assertIn("JSON", res["reasons"][0]) + + def test_an_undeclared_tool_name_fails_integrity(self): + res = self.run_pair("bad_tool") + self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY") + self.assertIn("undeclared tool", res["reasons"][0]) + + def test_a_cut_off_stream_fails_integrity(self): + res = self.run_pair("cut") + self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY") + self.assertIn("response.completed", res["reasons"][0]) + + def test_no_restore_means_no_evidence(self): + res = self.run_pair("no_cache") + self.assertEqual(res["verdict"], "INCONCLUSIVE_NO_RESTORE") + + def test_a_warm_cold_arm_is_not_a_cold_arm(self): + res = self.run_pair(cold_mode="warm_cold") + self.assertEqual(res["verdict"], "INCONCLUSIVE_COLD_ARM_WARM") + + def test_nondeterministic_cold_runs_are_inconclusive(self): + res = self.run_pair(cold_mode="nondet", control=True) + self.assertEqual(res["verdict"], "INCONCLUSIVE_NONDETERMINISTIC") + + def test_transport_error_is_an_error(self): + args = argparse.Namespace(cold_url="http://127.0.0.1:9", reply_url="http://127.0.0.1:9", model="m", key_file=None, scenario=None, + context_file=None, instructions=None, turns=1, max_output=8, control=False, min_cached_fraction=0.5, + min_restore_fraction=0.8) + self.assertEqual(PT.run_session(args)["verdict"], "ERROR") + + def test_cli_exit_codes_and_no_key_in_the_output(self): + reply, cold = start("reply", "diverge"), start("cold", "ok") + for srv in (reply, cold): + self.addCleanup(srv.server_close) + self.addCleanup(srv.shutdown) + with tempfile.TemporaryDirectory() as tmp: + keyf = os.path.join(tmp, "key") + with open(keyf, "w") as fh: + fh.write("sk-secret-test-key") + out = os.path.join(tmp, "res.json") + rc = PT.main(["run", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1], + "--model", "m", "--key-file", keyf, "--out", out, "--turns", "4"]) + self.assertEqual(rc, 1) + with open(out, "r", encoding="utf-8") as fh: + text = fh.read() + self.assertNotIn("sk-secret-test-key", text) + self.assertEqual(json.loads(text)["verdict"], "FAIL_OUTPUT_DIFFERS") + + def test_two_phases_record_then_replay_on_a_restarted_server(self): + """The production workflow: the reply arm is recorded, stopped, and the recorded bodies are replayed on a cold server.""" + for reply_mode, want_rc, want in (("ok", 0, "PASS"), ("diverge", 1, "FAIL_OUTPUT_DIFFERS"), ("bad_args", 1, "FAIL_TOOL_CALL_INTEGRITY")): + reply = start("reply", reply_mode) + with tempfile.TemporaryDirectory() as tmp: + rec = os.path.join(tmp, "record.json") + rc = PT.main(["record", "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1], "--model", "m", "--turns", "4", "--record-out", rec]) + reply.shutdown() + reply.server_close() + self.assertEqual(rc, 0, reply_mode) + cold = start("cold", "ok") # a new process on another port, without the cache + out = os.path.join(tmp, "res.json") + rc = PT.main(["replay", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--record", rec, "--control", "--out", out]) + cold.shutdown() + cold.server_close() + self.assertEqual((rc, json.load(open(out, "r", encoding="utf-8"))["verdict"]), (want_rc, want), reply_mode) + + def test_usage_error_exits_3(self): + with self.assertRaises(SystemExit) as cm: + PT.main(["run", "--model", "m"]) + self.assertEqual(cm.exception.code, 3) + + +class Pure(unittest.TestCase): + def test_schema_errors(self): + schema = {"type": "object", "properties": {"command": {"type": "array", "items": {"type": "string"}}, "timeout_ms": {"type": "integer"}}, + "required": ["command"], "additionalProperties": False} + self.assertEqual(PT.schema_errors(schema, {"command": ["ls"]}), []) + self.assertTrue(PT.schema_errors(schema, {})) + self.assertTrue(PT.schema_errors(schema, {"command": [1]})) + self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "extra": 1})) + self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "timeout_ms": True})) + + def test_first_difference_names_item_and_char(self): + a = [{"type": "message", "text": "abcdef"}] + b = [{"type": "message", "text": "abcxef"}] + self.assertEqual(PT.first_difference(a, b), {"item": 0, "what": "text", "char": 3}) + self.assertIsNone(PT.first_difference(a, a)) + self.assertEqual(PT.first_difference(a, a + a)["what"], "item count") + + def test_judge_empty_is_error(self): + self.assertEqual(PT.judge([])["verdict"], "ERROR") + + +if __name__ == "__main__": + unittest.main()