Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Reuse scoped validation receipts and preserve completed checks (#623)

Dee97953440661b
diff --git a/AGENTS.md b/AGENTS.md
index 78a0f764e..52963af04 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -11,7 +11,9 @@ validation and shipping, use [docs/validation-and-release.md](docs/validation-an
equivalent CI has passed just because it is time to merge or release.
- Reuse evidence only for the source and environment it covers. A squash with the same
tree does not invalidate it; conflict resolutions, dependencies, or relevant code
- changes do. See the validation guide for recording that evidence.
+ changes do. For deterministic checks, declare complete input/toolchain scopes in
+ the validation plan and pass the prior receipt with `--reuse`; inspect the diff
+ for new interactions. See the validation guide for recording that evidence.
- Time-bound tests and baseline diagnosis. An unchanged, already documented failure
does not need another full baseline run for every release. New failures and failures
in changed behavior still need investigation. Never describe an incomplete or failed
diff --git a/docs/performance/2026-10-02-premerge-validation.json b/docs/performance/2026-10-02-premerge-validation.json
new file mode 100644
index 000000000..49ec131f3
--- /dev/null
+++ b/docs/performance/2026-10-02-premerge-validation.json
@@ -0,0 +1,112 @@
+{
+ "schema": 1,
+ "baseCommit": "f537725295864d8150d439289dc24cf4f870e226",
+ "runnerSha256": "6cacfbdbf7401d445f47231372561681b452934c16c0626225ff423d844d4ca0",
+ "environment": "macOS arm64; Flutter 3.47.2; Dart 3.13.2; locally cached dependencies prepared with --offline --enforce-lockfile",
+ "scope": "Real native-toolbar and status-menu unit tests; unrelated documentation added between runs; no product implementation changes",
+ "limitations": [
+ "Execution then reuse, not a controlled cold/warm performance benchmark",
+ "Initial tests, mutable integration checks and platform verification are not skipped",
+ "Unexplained hours in the original toolbar handoff are not attributed to testing"
+ ],
+ "runs": [
+ {
+ "started_at": "2026-10-02T14:50:24.161149+00:00",
+ "finished_at": "2026-10-02T14:50:54.068634+00:00",
+ "duration_seconds": 29.632,
+ "status": "passed",
+ "source": {
+ "commit": "f537725295864d8150d439289dc24cf4f870e226",
+ "tree": "885e4c0fc11f7cbef5038aba9392802a3a0d12c8",
+ "working_changes_sha256": "5aa746bb9336c6f71882ceb803b9aee63a31f1a378cbf63af28ea8dd07dd0b75",
+ "dirty": true
+ },
+ "source_after": {
+ "commit": "f537725295864d8150d439289dc24cf4f870e226",
+ "tree": "885e4c0fc11f7cbef5038aba9392802a3a0d12c8",
+ "working_changes_sha256": "5aa746bb9336c6f71882ceb803b9aee63a31f1a378cbf63af28ea8dd07dd0b75",
+ "dirty": true
+ },
+ "check": {
+ "name": "desktop-toolbar",
+ "argv": [
+ "flutter",
+ "test",
+ "--no-pub",
+ "--concurrency=2",
+ "--timeout=60s",
+ "test/native_toolbar_sync_test.dart",
+ "test/status_menu_test.dart"
+ ],
+ "reuse": {
+ "inputs": [
+ "desktop"
+ ],
+ "toolchain": [
+ [
+ "flutter",
+ "--version",
+ "--machine"
+ ]
+ ]
+ },
+ "started_at": "2026-10-02T14:50:26.240060+00:00",
+ "finished_at": "2026-10-02T14:50:51.971860+00:00",
+ "duration_seconds": 25.69,
+ "status": "passed",
+ "reuse_key": "658eb6a165146836f7ccef8a4df4dcc41be947bc061968a3152f4604496aeea7",
+ "log_sha256": "bd5f224436133f2f3f482ca5ef79a0595a3d26ed972a2afe5a2f56ce3235d51b"
+ }
+ },
+ {
+ "started_at": "2026-10-02T14:52:09.933522+00:00",
+ "finished_at": "2026-10-02T14:52:14.140729+00:00",
+ "duration_seconds": 3.929,
+ "status": "passed",
+ "source": {
+ "commit": "f537725295864d8150d439289dc24cf4f870e226",
+ "tree": "885e4c0fc11f7cbef5038aba9392802a3a0d12c8",
+ "working_changes_sha256": "97b30ccf96729738d026a529fae69a4fdbee66f0b5855cf845e6fd4e95dbb5d9",
+ "dirty": true
+ },
+ "source_after": {
+ "commit": "f537725295864d8150d439289dc24cf4f870e226",
+ "tree": "885e4c0fc11f7cbef5038aba9392802a3a0d12c8",
+ "working_changes_sha256": "97b30ccf96729738d026a529fae69a4fdbee66f0b5855cf845e6fd4e95dbb5d9",
+ "dirty": true
+ },
+ "check": {
+ "name": "desktop-toolbar",
+ "argv": [
+ "flutter",
+ "test",
+ "--no-pub",
+ "--concurrency=2",
+ "--timeout=60s",
+ "test/native_toolbar_sync_test.dart",
+ "test/status_menu_test.dart"
+ ],
+ "reuse": {
+ "inputs": [
+ "desktop"
+ ],
+ "toolchain": [
+ [
+ "flutter",
+ "--version",
+ "--machine"
+ ]
+ ]
+ },
+ "started_at": "2026-10-02T14:50:26.240060+00:00",
+ "finished_at": "2026-10-02T14:50:51.971860+00:00",
+ "duration_seconds": 0,
+ "status": "reused",
+ "reuse_key": "658eb6a165146836f7ccef8a4df4dcc41be947bc061968a3152f4604496aeea7",
+ "log_sha256": "bd5f224436133f2f3f482ca5ef79a0595a3d26ed972a2afe5a2f56ce3235d51b",
+ "original_duration_seconds": 25.69,
+ "reused_at": "2026-10-02T14:52:12.022570+00:00"
+ }
+ }
+ ]
+}
diff --git a/docs/performance/2026-10-02-premerge-validation.md b/docs/performance/2026-10-02-premerge-validation.md
new file mode 100644
index 000000000..895db6c35
--- /dev/null
+++ b/docs/performance/2026-10-02-premerge-validation.md
@@ -0,0 +1,87 @@
+# Pre-merge validation — October 2, 2026
+
+The Desktop 1.2.52 release workflow took 11m30s, but that excludes pre-merge work.
+[PR #614](https://github.com/autonomous-ai/openharness/pull/614) and its
+[validation record](2026-10-02-native-toolbar-updates.json) provide this clock:
+
+| Phase | UTC | Elapsed |
+| --- | --- | --- |
+| Current-base validation phase | approximately 13:36–13:59:15 | approximately 23m15s |
+| Validation record ready to PR created | 13:59:15–14:01:42 | 2m27s |
+| PR open to merged | 14:01:42–14:02:38 | 56s |
+| Merge to release trigger | 14:02:38–14:04:32 | 1m54s |
+| Release trigger to completed workflow | 14:04:32–14:16:02 | 11m30s |
+
+The PR has no GitHub review submissions or pending check runs. Its 56-second open
+period does not measure review performed before opening it. The validation phase
+includes result recording and performance measurements; per-command start/end
+times were not preserved, so 23m15s is not a measured test execution duration.
+The earlier 05:52–13:35 interval is unexplained in the handoff. Local task history
+for this toolbar release was unavailable here; do not label that interval as
+testing, review or idle time without additional evidence.
+
+## Observed rework
+
+- Of 196 affected unit/widget tests, 192 passed initially. A WebSocket runner-load
+ failure prevented one file from loading; its four tests passed separately.
+- Six of eight selected native journeys passed initially. Two contained obsolete
+ expectations that Cmd-N retained a dismissed draft. #614 corrected those
+ expectations and reran only those two journeys, retaining terminal assertions.
+- The same day's [PR #604](https://github.com/autonomous-ai/openharness/pull/604)
+ reported a validation-wrapper cleanup permission error after 116 Flutter tests
+ and analysis had completed successfully. The preserved logs show 23 seconds of
+ tests and 4.4 seconds of analysis, but that run has no completed receipt.
+ Signaling an already-reaped process group could abort the runner before saving
+ the successful results.
+
+The toolbar PR already avoided another full suite after an unrelated rebase.
+The remaining improvement is to make that evidence comparison explicit and
+repeatable instead of reconstructing file fingerprints and rerunning by default.
+
+## Changes
+
+`scripts/validate-change.py --reuse RECEIPT` accepts prior passing evidence only
+for checks with declared input and toolchain scopes. It compares source bytes,
+new/deleted files, file modes, tool versions, executable, command, OS, environment
+and runner implementation. Unrelated commits do not invalidate a scoped check.
+Failed checks still run; independently passing checks can be reused. Original
+timestamps and logs are retained and verified by hash, and reuse is labeled.
+Missing evidence, unstable source and failed cleanup cannot count as passes.
+
+Cleanup now checks whether an exited parent's group still exists before signaling
+it. A live fixture child is still terminated. A real cleanup failure is recorded
+with the check's result and log, rather than discarding the run's evidence.
+Toolchain probes are also bounded and clean up their own process groups.
+
+Scope remains a review responsibility. Reuse is for deterministic local checks
+whose inputs are fully declared and dependencies installed from the matching lock.
+Mutable services, real engines, hardware, visual inspection and host-sensitive
+performance measurements need fresh evidence. See the
+[validation guide](../validation-and-release.md#reuse-evidence-without-hiding-regressions).
+
+## Verification
+
+The process regression suite covers unchanged inputs across an unrelated commit,
+source/toolchain/environment/command changes, new and deleted files, mixed
+pass/failure results, modified/missing logs, changing source, blocked toolchains,
+macOS cleanup errors, and child processes left by an exited parent.
+
+The real Flutter trial runs 13 existing native-toolbar and status-menu unit
+tests on Flutter 3.47.2 / Dart 3.13.2. Its first attempt correctly failed and saved
+a receipt when this checkout had no dependency configuration. Dependencies were
+then prepared from the existing local cache with the lockfile enforced.
+
+| Trial | Result | Total runner time | Test command time |
+| --- | --- | ---: | ---: |
+| Execute selected Flutter tests | passed | 29.632s | 25.690s |
+| Add unrelated documentation, then reuse the receipt | reused | 3.929s | no test execution |
+
+The original log hash and timestamps were preserved. Source and toolchain checks
+ran before and after both invocations. This is execution followed by evidence
+reuse, not a controlled cold/warm benchmark. The [machine-readable record](2026-10-02-premerge-validation.json)
+contains source fingerprints, commands, times and log hashes without environment
+values or local absolute paths.
+
+This removes repeat execution of unchanged checks; it does not shorten their
+first run, skip required platform checks, or establish a new end-to-end release
+duration. The next product release must still be timed from request to completion.
diff --git a/docs/validation-and-release.md b/docs/validation-and-release.md
index 995bdadac..9868f612f 100644
--- a/docs/validation-and-release.md
+++ b/docs/validation-and-release.md
@@ -118,6 +118,47 @@ before merge and then again on the merged commit. Check the merged source identi
and rerun only validation invalidated by the merge. Native checks absent from CI
still need their own evidence.
+For deterministic local checks, the runner can do that comparison and reuse the
+original logs. Add an explicit `reuse` contract to each eligible check:
+
+```json
+{
+ "name": "desktop-toolbar",
+ "cwd": "desktop",
+ "argv": ["flutter", "test", "--no-pub", "--concurrency=2", "--timeout=60s", "test/native_toolbar_sync_test.dart", "test/status_menu_test.dart"],
+ "timeout_seconds": 180,
+ "reuse": {
+ "inputs": ["desktop"],
+ "toolchain": [["flutter", "--version", "--machine"]]
+ }
+}
+```
+
+Run the plan normally first. After a documentation edit, rebase or squash, pass
+its receipt to `make validate ARGS=".harness/validation-plan.json --reuse
+.harness/validation/RUN/receipt.json"` (on one line). Unchanged eligible checks
+are labeled `reused`, with the original timestamps, log and duration; changed or
+failed checks run. A mixed failed run can contribute its independent passing
+checks. There are no automatic retries and no test selection inferred from paths.
+
+Inputs are literal checkout-relative files/directories and include tracked and
+untracked source, deletions and file modes. Declare every relevant component,
+fixture, configuration and dependency lock; prefer a whole component to an
+incomplete hand-picked file list. Supply version commands for every tool involved.
+The runner also compares the check command, executable, checkout, OS, inherited
+environment and its own implementation. Tool/environment values are hashed, not
+written to receipts. Missing/modified logs, changing source, failed cleanup and
+an unavailable toolchain cannot satisfy reuse. Install dependencies from the
+declared lock; generated or ignored build/dependency directories are not source
+inputs. Reinstalling or manually modifying them requires a fresh run.
+
+Leave out `reuse` for real engines, mutable services/hardware, native visual or
+physical input checks, and performance measurements affected by host load. Their
+external state needs fresh evidence. A reuse contract documents a reviewed scope;
+it cannot prove that the author included every dependency. The
+[October 2 pre-merge audit](performance/2026-10-02-premerge-validation.md) records
+the motivating failures and the measured effect.
+
For a failure, isolate the failing test once. If its code, fixtures, dependencies,
or environment changed, investigate it as a possible regression. Otherwise check
existing baseline evidence before starting another baseline run. Link the exact
diff --git a/scripts/tests/test_validate_change.py b/scripts/tests/test_validate_change.py
index e267ae1d6..b67c225ff 100644
--- a/scripts/tests/test_validate_change.py
+++ b/scripts/tests/test_validate_change.py
@@ -7,6 +7,7 @@ import sys
import tempfile
import time
import unittest
+from unittest import mock
SCRIPT = Path(__file__).resolve().parents[1] / "validate-change.py"
spec = importlib.util.spec_from_file_location("validate_change", SCRIPT)
@@ -33,14 +34,23 @@ class ValidationTests(unittest.TestCase):
def check(self, name, code, timeout=3):
return {"name": name, "argv": [sys.executable, "-c", code], "timeout_seconds": timeout}
- def run_plan(self, checks, minimum=0):
+ def run_plan(self, checks, minimum=0, reuse=None, env=None):
plan = self.root / ".harness" / "plan.json"
plan.write_text(json.dumps({"reason": "Validation runner integration fixtures", "minimum_free_gib": minimum, "checks": checks}))
- result = subprocess.run([sys.executable, str(SCRIPT), str(plan)], cwd=self.root, capture_output=True, text=True, timeout=10)
+ command = [sys.executable, str(SCRIPT), str(plan)]
+ if reuse:
+ command.extend(["--reuse", str(reuse)])
+ result = subprocess.run(command, cwd=self.root, capture_output=True, text=True, timeout=15, env=env)
paths = sorted((self.root / ".harness" / "validation").glob("*/receipt.json"))
self.assertTrue(paths, result.stderr + result.stdout)
+ self.last_receipt = paths[-1]
return result, json.loads(paths[-1].read_text())
+ def counted_check(self, name="counted"):
+ check = self.check(name, "from pathlib import Path; p=Path('.harness/count'); p.write_text(str(int(p.read_text())+1) if p.exists() else '1'); print('checked')")
+ check["reuse"] = {"inputs": ["source.txt"], "toolchain": [[sys.executable, "--version"]]}
+ return check
+
def test_independent_checks_really_overlap_and_capture_logs(self):
checks = []
for name, other in [("one", "two"), ("two", "one")]:
@@ -108,6 +118,130 @@ class ValidationTests(unittest.TestCase):
with self.assertRaises(ValueError):
runner.read_plan(plan, self.root)
+ def test_passed_evidence_survives_unrelated_commit_and_keeps_original_log(self):
+ check = self.counted_check()
+ result, original = self.run_plan([check])
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ previous = self.last_receipt
+ (self.root / "notes.md").write_text("unrelated documentation\n")
+ self.git("add", "notes.md")
+ self.git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "docs only")
+ result, receipt = self.run_plan([check], reuse=previous)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual(receipt["checks"][0]["status"], "reused")
+ self.assertEqual(receipt["checks"][0]["log"], original["checks"][0]["log"])
+ self.assertNotEqual(receipt["source"]["commit"], original["source"]["commit"])
+ self.assertEqual((self.root / ".harness/count").read_text(), "1")
+ # Reuse chains retain the original execution duration, not a fictitious run.
+ _, chained = self.run_plan([check], reuse=self.last_receipt)
+ self.assertEqual(chained["checks"][0]["original_duration_seconds"], original["checks"][0]["duration_seconds"])
+
+ def test_source_toolchain_environment_and_command_changes_each_rerun(self):
+ check = self.counted_check()
+ version = self.root / ".harness/tool-version"
+ version.write_text("one")
+ check["reuse"]["toolchain"] = [[sys.executable, "-c", "from pathlib import Path; print(Path('.harness/tool-version').read_text())"]]
+ env = dict(os.environ, VALIDATION_FIXTURE_ENV="one")
+ self.run_plan([check], env=env)
+ changes = [
+ lambda: (self.root / "source.txt").write_text("new source"),
+ lambda: version.write_text("new toolchain"),
+ lambda: env.update(VALIDATION_FIXTURE_ENV="two"),
+ lambda: check["argv"].append("new argument"),
+ ]
+ for number, change in enumerate(changes, 2):
+ previous = self.last_receipt
+ change()
+ result, receipt = self.run_plan([check], reuse=previous, env=env)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ self.assertEqual((self.root / ".harness/count").read_text(), str(number))
+
+ def test_new_and_deleted_files_in_a_declared_directory_invalidate_evidence(self):
+ folder = self.root / "component"
+ folder.mkdir()
+ (folder / "original.txt").write_text("original")
+ self.git("add", "component")
+ check = self.counted_check()
+ check["reuse"]["inputs"] = ["component"]
+ self.run_plan([check])
+ previous = self.last_receipt
+ (folder / "new.txt").write_text("untracked source")
+ _, receipt = self.run_plan([check], reuse=previous)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ previous = self.last_receipt
+ (folder / "original.txt").unlink()
+ _, receipt = self.run_plan([check], reuse=previous)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ self.assertEqual((self.root / ".harness/count").read_text(), "3")
+
+ def test_failed_checks_rerun_without_repeating_independent_passes(self):
+ good = self.counted_check()
+ bad = self.check("failed", "raise SystemExit(7)")
+ bad["reuse"] = good["reuse"]
+ self.run_plan([good, bad])
+ result, receipt = self.run_plan([good, bad], reuse=self.last_receipt)
+ self.assertEqual(result.returncode, 1)
+ checks = {item["name"]: item for item in receipt["checks"]}
+ self.assertEqual(checks["counted"]["status"], "reused")
+ self.assertEqual(checks["failed"]["status"], "failed")
+ self.assertEqual((self.root / ".harness/count").read_text(), "1")
+
+ def test_missing_or_tampered_logs_and_changing_source_are_not_reusable(self):
+ check = self.counted_check()
+ _, receipt = self.run_plan([check])
+ previous = self.last_receipt
+ Path(receipt["checks"][0]["log"]).write_text("different evidence")
+ _, receipt = self.run_plan([check], reuse=previous)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ previous = self.last_receipt
+ Path(receipt["checks"][0]["log"]).unlink()
+ _, receipt = self.run_plan([check], reuse=previous)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ # This edit is outside the declared inputs, so only the unstable source
+ # receipt (not a different per-check key) prevents reuse on the next run.
+ check["argv"][2] += "; Path('unrelated.txt').write_text('changed during check')"
+ _, receipt = self.run_plan([check])
+ self.assertEqual(receipt["status"], "source_changed")
+ _, receipt = self.run_plan([check], reuse=self.last_receipt)
+ self.assertEqual(receipt["checks"][0]["status"], "passed")
+ self.assertEqual((self.root / ".harness/count").read_text(), "5")
+
+ def test_toolchain_failure_saves_a_blocked_receipt_before_tests_start(self):
+ check = self.counted_check()
+ check["reuse"]["toolchain"] = [[sys.executable, "-c", "raise SystemExit(4)"]]
+ result, receipt = self.run_plan([check])
+ self.assertEqual(result.returncode, 1)
+ self.assertEqual(receipt["status"], "blocked")
+ self.assertEqual(receipt["checks"][0]["status"], "not_run")
+ self.assertFalse((self.root / ".harness/count").exists())
+
+ def test_finished_empty_group_is_not_signaled(self):
+ process = mock.Mock(pid=12345)
+ process.poll.return_value = 0
+ with mock.patch.object(runner.subprocess, "check_output", return_value=" 999\n"), mock.patch.object(runner.os, "killpg", side_effect=PermissionError("macOS denied")) as kill:
+ self.assertIsNone(runner.stop_group(process))
+ kill.assert_not_called()
+
+ def test_finished_parent_does_not_leave_its_fixture_child_running(self):
+ child = "import signal,time; from pathlib import Path; signal.signal(signal.SIGTERM, signal.SIG_IGN)\nwhile True:\n with Path('.harness/beats').open('a') as f: f.write('x')\n time.sleep(.02)"
+ parent = f"import subprocess,sys,time; subprocess.Popen([sys.executable, '-c', {child!r}]); time.sleep(.15)"
+ result, receipt = self.run_plan([self.check("exited", parent)])
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ size = (self.root / ".harness/beats").stat().st_size
+ self.assertGreater(size, 0)
+ time.sleep(.15)
+ self.assertEqual((self.root / ".harness/beats").stat().st_size, size)
+
+ def test_cleanup_errors_preserve_results_and_cannot_report_a_pass(self):
+ output = self.root / ".harness"
+ with mock.patch.object(runner, "stop_group", return_value="permission denied"):
+ checks = runner.run_checks({"checks": [self.check("complete", "print('all tests finished')")]}, self.root, output, 1)
+ self.assertEqual(checks[0]["status"], "cleanup_failed")
+ self.assertEqual(checks[0]["exit_code"], 0)
+ self.assertEqual(checks[0]["cleanup_error"], "permission denied")
+ self.assertIn("all tests finished", Path(checks[0]["log"]).read_text())
+
if __name__ == "__main__":
unittest.main()
diff --git a/scripts/validate-change.py b/scripts/validate-change.py
index f0acdb56b..abc8aa53e 100644
--- a/scripts/validate-change.py
+++ b/scripts/validate-change.py
@@ -10,6 +10,7 @@ import json
import math
import os
from pathlib import Path
+import platform
import re
import shutil
import signal
@@ -73,15 +74,145 @@ def read_plan(path, root):
cwd = (root / check.get("cwd", ".")).resolve()
if not cwd.is_dir() or not cwd.is_relative_to(root):
raise ValueError(f"{name}: cwd must be a directory in this checkout")
+ if "reuse" in check:
+ reuse = check["reuse"]
+ if not isinstance(reuse, dict):
+ raise ValueError(f"{name}: reuse must declare inputs and toolchain")
+ inputs = reuse.get("inputs")
+ if not isinstance(inputs, list) or not inputs:
+ raise ValueError(f"{name}: reuse.inputs must name source/dependency paths")
+ for item in inputs:
+ if not isinstance(item, str) or not item or Path(item).is_absolute() or ".." in Path(item).parts or any(c in item for c in "*?["):
+ raise ValueError(f"{name}: reuse inputs must be literal checkout-relative files or directories")
+ commands = reuse.get("toolchain")
+ if not isinstance(commands, list) or not commands or any(
+ not isinstance(command, list) or not command or not all(isinstance(arg, str) and arg for arg in command)
+ for command in commands
+ ):
+ raise ValueError(f"{name}: reuse.toolchain must contain version-command argv arrays")
return plan
+def file_sha256(path):
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def tool_fingerprint(command, cwd):
+ process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ stdin=subprocess.DEVNULL, start_new_session=True)
+ try:
+ stdout, stderr = process.communicate(timeout=30)
+ finally:
+ cleanup_error = stop_group(process)
+ if cleanup_error:
+ raise ValueError(f"toolchain process cleanup failed: {cleanup_error}")
+ if process.returncode:
+ raise subprocess.CalledProcessError(process.returncode, command)
+ return hashlib.sha256(stdout + b"\0" + stderr).hexdigest()
+
+
+def reuse_keys(plan, root):
+ """Opt-in evidence identity, independent of commit IDs and unrelated files.
+
+ Scope selection remains explicit. Version commands must describe every tool
+ used by a check; inputs must include its sources, fixtures, config and locks.
+ Environment values and tool output are hashed, never written to receipts.
+ """
+ reusable = [check for check in plan["checks"] if "reuse" in check]
+ if not reusable:
+ return {}
+ names = set(filter(None, subprocess.check_output(
+ ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], cwd=root,
+ ).decode().split("\0")))
+ runtime = {
+ "root": str(root), "platform": platform.platform(), "machine": platform.machine(),
+ "python": sys.version, "runner": file_sha256(Path(__file__)),
+ # Shell bookkeeping may change between invocations without changing a
+ # check. All other inherited values participate, including PATH/SDK flags.
+ "environment": {key: value for key, value in os.environ.items() if key not in {"_", "SHLVL", "PWD", "OLDPWD"}},
+ }
+ files, versions, keys = {}, {}, {}
+ for check in reusable:
+ selected = set()
+ for item in check["reuse"]["inputs"]:
+ path = Path(item).as_posix().rstrip("/")
+ matches = {name for name in names if path == "." or name == path or name.startswith(path + "/")}
+ if not matches:
+ raise ValueError(f"{check['name']}: reuse input matches no source files: {item}")
+ selected.update(matches)
+ for name in selected:
+ if name in files:
+ continue
+ path = root / name
+ if path.is_symlink() or not path.resolve().is_relative_to(root):
+ raise ValueError(f"{check['name']}: reuse input must not traverse a symlink: {name}")
+ files[name] = (file_sha256(path), path.stat().st_mode & 0o777) if path.exists() else None
+ cwd = root / check.get("cwd", ".")
+ tool_ids = []
+ for command in check["reuse"]["toolchain"]:
+ identity = (str(cwd), tuple(command))
+ if identity not in versions:
+ versions[identity] = tool_fingerprint(command, cwd)
+ tool_ids.append(versions[identity])
+ command = check["argv"][0]
+ search_path = os.pathsep.join(str(cwd / entry) for entry in os.get_exec_path())
+ executable = str(cwd / command) if "/" in command else shutil.which(command, path=search_path)
+ if executable is None:
+ raise ValueError(f"{check['name']}: executable unavailable: {check['argv'][0]}")
+ executable_path = Path(executable)
+ if not executable_path.is_absolute():
+ executable_path = cwd / executable_path
+ identity = dict(runtime, check=check, files={name: files[name] for name in sorted(selected)},
+ toolchain=tool_ids, executable=str(executable_path.resolve()), executable_sha256=file_sha256(executable_path))
+ keys[check["name"]] = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
+ return keys
+
+
+def reusable_checks(path, keys):
+ if path is None:
+ return {}
+ receipt = json.loads(path.read_text())
+ # A partial run can contribute successful checks, but a changing source or
+ # incomplete receipt cannot. Never treat failed/blocked/timed-out checks as hits.
+ if receipt.get("schema") != 2 or receipt.get("status") not in {"passed", "failed"} or receipt.get("source") != receipt.get("source_after"):
+ return {}
+ reused = {}
+ for check in receipt.get("checks", []):
+ name = check.get("name")
+ if name not in keys or check.get("reuse_key") != keys[name] or check.get("status") not in {"passed", "reused"}:
+ continue
+ log = Path(check["log"])
+ if not log.is_file() or file_sha256(log) != check.get("log_sha256"):
+ continue
+ reused[name] = dict(check, status="reused", duration_seconds=0,
+ reused_from=str(path.resolve()), reused_at=utc_now(),
+ original_duration_seconds=check.get("original_duration_seconds", check["duration_seconds"]))
+ return reused
+
+
def stop_group(process):
"""Only our new session's process group, never global pkill/tmux cleanup."""
+ if process.poll() is not None:
+ # A reaped Flutter parent often has no remaining children. macOS can
+ # reject killpg even for that vanished group. Inspect before signaling;
+ # do still terminate children left by an exited parent.
+ try:
+ groups = subprocess.check_output(["ps", "-A", "-o", "pgid="], text=True, timeout=5)
+ if str(process.pid) not in groups.split():
+ return None
+ except (OSError, subprocess.SubprocessError) as error:
+ return f"cannot inspect owned process group: {error}"
+ errors = []
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
+ except OSError as error:
+ errors.append(str(error))
try:
process.wait(timeout=0.5)
except subprocess.TimeoutExpired:
@@ -91,10 +222,17 @@ def stop_group(process):
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
- process.wait(timeout=5)
+ except OSError as error:
+ errors.append(str(error))
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired as error:
+ errors.append(str(error))
+ return "; ".join(errors) or None
-def run_checks(plan, root, output, jobs):
+def run_checks(plan, root, output, jobs, keys=None, reused=None):
+ keys, reused = keys or {}, reused or {}
pending = list(plan["checks"])
active = []
results = []
@@ -102,7 +240,13 @@ def run_checks(plan, root, output, jobs):
while pending or active:
while pending and len(active) < jobs:
check = pending.pop(0)
+ if check["name"] in reused:
+ results.append(reused[check["name"]])
+ print(f"{check['name']}: reused ({reused[check['name']]['log']})", flush=True)
+ continue
result = dict(check, started_at=utc_now(), status="running")
+ if check["name"] in keys:
+ result["reuse_key"] = keys[check["name"]]
log_path = output / (check["name"] + ".log")
result["log"] = str(log_path)
log = log_path.open("wb")
@@ -128,9 +272,14 @@ def run_checks(plan, root, output, jobs):
if code is None and elapsed < result["timeout_seconds"]:
continue
result["status"] = "timeout" if code is None else ("passed" if code == 0 else "failed")
- stop_group(process)
+ cleanup_error = stop_group(process)
log.close()
+ if cleanup_error:
+ result["cleanup_error"] = cleanup_error
+ if result["status"] == "passed":
+ result["status"] = "cleanup_failed"
result.update(exit_code=process.returncode, duration_seconds=round(elapsed, 3), finished_at=utc_now())
+ result["log_sha256"] = file_sha256(Path(result["log"]))
active.remove(item)
results.append(result)
print(f"{result['name']}: {result['status']} ({elapsed:.1f}s), {result['log']}", flush=True)
@@ -156,6 +305,7 @@ def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("plan", type=Path)
parser.add_argument("--jobs", type=int, default=2, help="independent checks at once (default: 2)")
+ parser.add_argument("--reuse", type=Path, help="reuse passing checks with identical explicit inputs, toolchain and environment")
args = parser.parse_args(argv)
if os.name != "posix":
parser.error("process-group cleanup currently requires macOS or Linux")
@@ -165,7 +315,7 @@ def main(argv=None):
plan = read_plan(args.plan, root)
output = root / ".harness" / "validation" / (datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ") + f"-{os.getpid()}")
output.mkdir(parents=True)
- receipt = dict(started_at=utc_now(), reason=plan["reason"], source=source_state(root), checks=[])
+ receipt = dict(schema=2, started_at=utc_now(), reason=plan["reason"], source=source_state(root), checks=[])
started = time.monotonic()
free = shutil.disk_usage(root).free / 1024 ** 3
receipt["free_gib_before"] = round(free, 3)
@@ -174,12 +324,20 @@ def main(argv=None):
receipt["checks"] = [dict(check, status="not_run") for check in plan["checks"]]
print(receipt["error"], file=sys.stderr)
else:
- receipt["checks"] = run_checks(plan, root, output, args.jobs)
- receipt["source_after"] = source_state(root)
- if receipt["source"] != receipt["source_after"]:
- receipt.update(status="source_changed", error="Source changed during validation; results do not identify one tested tree")
- else:
- receipt["status"] = "passed" if all(c["status"] == "passed" for c in receipt["checks"]) else "failed"
+ try:
+ keys = reuse_keys(plan, root)
+ reused = reusable_checks(args.reuse, keys)
+ receipt["checks"] = run_checks(plan, root, output, args.jobs, keys, reused)
+ keys_after = reuse_keys(plan, root)
+ receipt["source_after"] = source_state(root)
+ if receipt["source"] != receipt["source_after"] or keys != keys_after:
+ receipt.update(status="source_changed", error="Source or toolchain changed during validation; results do not identify one tested environment")
+ else:
+ receipt["status"] = "passed" if all(c["status"] in {"passed", "reused"} for c in receipt["checks"]) else "failed"
+ except (ValueError, OSError, subprocess.SubprocessError) as error:
+ receipt.update(status="blocked", error=str(error))
+ if not receipt["checks"]:
+ receipt["checks"] = [dict(check, status="not_run") for check in plan["checks"]]
receipt.update(finished_at=utc_now(), duration_seconds=round(time.monotonic() - started, 3))
path = output / "receipt.json"
path.write_text(json.dumps(receipt, indent=2) + "\n")