Artifact 9c405f7fe5a081fd60723024e8813aede8a464adc1496ee975eb059e9316e09e:
- File
tools/remote/collect.py
— part of check-in
[03114f7dbf]
at
2026-11-18 19:29:42
on branch stage-2
— Run pic under Fil-C remotely and fix a varargs over-read it found
The remote tooling gains a pic mode: a hashed snapshot of the sources, larger guarded limits, and a payload that builds pic with the pinned Fil-C compiler and runs every suite. The first run caught record_reply passing six bind types for five values; run_stmt now refuses a type count that differs from the statement. The second run passed every suite, and teardown verified the host clean. (user: dmestas, size: 8275) [annotate] [blame] [check-ins using] [more...]
#!/usr/bin/env python3 """Local-only collection validation. Never launches a process or qualifies teardown.""" import argparse import hashlib import json from pathlib import Path, PurePosixPath import re import tarfile MAX_BYTES = 256 * 1024 * 1024 MAX_FILES = 1024 # pic mode uploads its sources (about 370 files) and returns them class InvalidEvidence(ValueError): """Missing, changed, or unsafe evidence is a failure, not a skipped pass.""" def digest(body): return hashlib.sha256(body).hexdigest() def safe_name(name): if name.startswith("./"): name = name[2:] if not name or name.startswith("/") or ".." in name.split("/"): raise InvalidEvidence("unsafe archive/index path") if "\\" in name or any(ord(char) < 32 for char in name): raise InvalidEvidence("unsafe archive/index characters") return str(PurePosixPath(name)) def read_archive(path): if Path(path).stat().st_size > MAX_BYTES: raise InvalidEvidence("transport archive exceeds collection budget") files = {} total = 0 with tarfile.open(path, "r:") as archive: for count, member in enumerate(archive, 1): if count > MAX_FILES: raise InvalidEvidence("too many archive entries") if member.isdir(): if member.name not in (".", "./"): safe_name(member.name) continue name = safe_name(member.name) if name in ("collection.json", ".collection-verified"): raise InvalidEvidence("archive attempts to supply local validation metadata") if not member.isfile() or name in files: raise InvalidEvidence("nonregular or duplicate archive entry") total += member.size if total > MAX_BYTES: raise InvalidEvidence("archive exceeds collection budget") stream = archive.extractfile(member) if stream is None: raise InvalidEvidence("unreadable archive entry") with stream: body = stream.read(MAX_BYTES + 1) if len(body) != member.size: raise InvalidEvidence("truncated archive entry") files[name] = body return files def index(body): rows = {} for line in body.decode("utf-8").splitlines(): match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) if not match: raise InvalidEvidence("malformed SHA256 index") name = safe_name(match[2]) if name in rows: raise InvalidEvidence("duplicate SHA256 index entry") rows[name] = match[1] if not rows: raise InvalidEvidence("empty SHA256 index") return rows def worker_fields(body, nonce): units = {} current = None for line in body.decode("utf-8").splitlines(): if "=" not in line: continue key, value = line.split("=", 1) if key == "Id": current = {} if value in units: raise InvalidEvidence("duplicate unit record") units[value] = current elif current is not None: current[key] = value worker = units.get(f"pi-c-s0-{nonce}-worker.service") if not worker: raise InvalidEvidence("worker supervisor record missing") return worker def collect(archive, expected_sources, output, nonce, mode): if not re.fullmatch(r"[0-9a-f]{16}", nonce): raise InvalidEvidence("invalid nonce") if mode not in ("noop", "disconnect", "timeout", "filc", "pic"): raise InvalidEvidence("invalid mode") files = read_archive(archive) required = {"sources.sha256", "SHA256SUMS", "worker.log", "supervisor.txt", "toolchain-before.txt", "toolchain-after.txt", ".pi-c-owner", ".upload-complete", ".work-started"} if not required <= files.keys(): raise InvalidEvidence("required artifact absent") hashes = index(files["SHA256SUMS"]) if hashes.keys() != files.keys() - {"SHA256SUMS"}: raise InvalidEvidence("artifact index is incomplete") for name, expected in hashes.items(): if digest(files[name]) != expected: raise InvalidEvidence("artifact hash mismatch: " + name) if files["sources.sha256"] != Path(expected_sources).read_bytes(): raise InvalidEvidence("source index changed") for name, expected in index(files["sources.sha256"]).items(): if name not in files or digest(files[name]) != expected: raise InvalidEvidence("uploaded source changed: " + name) for name in (".pi-c-owner", ".upload-complete", ".work-started"): if files[name] != (nonce + "\n").encode(): raise InvalidEvidence("ownership/upload marker mismatch") if files["toolchain-before.txt"] != files["toolchain-after.txt"]: raise InvalidEvidence("borrowed compiler/runtime fingerprint changed") worker = worker_fields(files["supervisor.txt"], nonce) result = worker.get("Result", "missing") success = (result == "success" and worker.get("ExecMainStatus") == "0" and worker.get("SubState") == "exited" and files.get("result.txt") == b"PASS\n") if mode == "filc" and success: log = files["worker.log"] required_lines = (b"qualification: 10 tests passed", b"oracle-mutant: 8 verdicts checked") if not all(line in log.splitlines() for line in required_lines): raise InvalidEvidence("qualification output absent") if not re.search(rb"^replay: 7 files, [1-9][0-9]* sequences checked$", log, re.M): raise InvalidEvidence("saved corpus replay output absent") for binary in ("test_qualification", "test_oracle_mutant", "replay"): if not files.get("run/" + binary) or not files.get("run/" + binary + ".argv"): raise InvalidEvidence("binary/argv evidence absent") if mode == "pic" and success: log = files["worker.log"].splitlines() required_lines = (b"sse: all cases pass, whole and byte by byte", b"decode: all recorded streams match", b"http: all cases pass, whole and byte by byte", b"PASS: parallel-after-result-2 (ledger=1 exec=done failed-generations=0)", b"PASS: the API key never reaches the journal or output") if not all(line in log for line in required_lines): raise InvalidEvidence("pic suite output absent") output = Path(output) output.mkdir(mode=0o700) for name, body in files.items(): target = output / name target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) target.write_bytes(body) target.chmod(0o600) report = { "version": 1, "scope": "qualification_fixture", "status": "NOT RUN" if success else "FAIL", "reason": ("Collection verified; teardown and operator review still required." if success else "Worker failed or completion evidence absent."), "collection_verified": True, "worker_result": result, "host": "hetzner-hel", "mode": mode, "nonce": nonce, "archive_sha256": digest(Path(archive).read_bytes()), "artifacts": [{"path": str(output / name), "sha256": digest(body)} for name, body in sorted(files.items())], } (output / "collection.json").write_text(json.dumps(report, indent=2) + "\n") (output / ".collection-verified").write_text(nonce + "\n") return report def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("sources", type=Path) parser.add_argument("output", type=Path) parser.add_argument("nonce") parser.add_argument("mode") args = parser.parse_args() try: report = collect(args.archive, args.sources, args.output, args.nonce, args.mode) except (OSError, ValueError, tarfile.TarError, InvalidEvidence) as exc: print("FAIL: invalid remote collection: " + str(exc)) return 1 print(report["status"] + ": " + report["reason"]) return int(report["status"] == "FAIL") if __name__ == "__main__": raise SystemExit(main())