run.py
benches/rrt/tools/run.py
1#!/usr/bin/env python32"""Run the fixed ordinary Heavy16 workload with unchanged-source and trace guards."""3import argparse4import hashlib5import json6import os7import re8from pathlib import Path9import subprocess10import sys11import time1213ROOT = Path(__file__).resolve().parents[3]141516def digest(path):17 return hashlib.sha256(Path(path).read_bytes()).hexdigest()181920def records(value):21 if isinstance(value, dict):22 if isinstance(value.get("path"), str) and isinstance(value.get("sha256"), str):23 yield value24 for child in value.values():25 yield from records(child)26 elif isinstance(value, list):27 for child in value:28 yield from records(child)293031def dependency_inputs(package, name, wanted):32 """Pin an exact registry version or the complete frozen local package."""33 metadata = (package / "node_modules" / name / "package.json").resolve()34 assert metadata.is_file(), f"install or link pinned {name} in {package}; do not use Bun auto-install"35 installed = json.loads(metadata.read_text())36 assert installed["name"] == name, f"installed package name differs: {name}"37 entry = {"name": name, "version": installed["version"],38 "path": str(metadata), "sha256": digest(metadata)}39 if wanted.startswith("file:"):40 expected = (package / wanted.removeprefix("file:")).resolve(strict=True)41 expected_metadata = json.loads((expected / "package.json").read_text())42 assert expected_metadata["name"] == name, f"local package name differs: {name}"43 assert installed["version"] == expected_metadata["version"], f"local package version differs: {name}"44 def package_files(root):45 # npm installs nested dependencies separately from package source.46 return {path.relative_to(root): path for path in root.rglob("*")47 if path.is_file() and path.relative_to(root).parts[0] != "node_modules"}48 source_files = package_files(expected)49 installed_files = package_files(metadata.parent)50 assert source_files.keys() == installed_files.keys(), f"local package file set differs: {name}"51 inputs = {}52 for relative, source_file in sorted(source_files.items()):53 actual_file = installed_files[relative]54 assert source_file.read_bytes() == actual_file.read_bytes(), f"local package content differs: {name}/{relative}"55 for path in (source_file, actual_file):56 inputs[str(path)] = {"path": str(path), "sha256": digest(path)}57 entry["local_source"] = str(expected)58 entry["inputs"] = list(inputs.values())59 else:60 assert installed["version"] == wanted, f"{name}: installed {installed['version']}, expected {wanted}"61 return entry626364def host_dependencies(source):65 """Reject Bun cache fallback before creating any canisters."""66 installed = []67 for relative in ("benches/rrt", "tests/pocketic"):68 package = source / relative69 wanted = json.loads((package / "package.json").read_text())["dependencies"]70 for name, requirement in wanted.items():71 installed.append({"package": relative, **dependency_inputs(package, name, requirement)})72 return installed73747576def runtime_input(manifest, environment):77 runtime = Path(manifest["wireRuntime"]["module"]["path"])78 codec = Path(manifest["wireRuntime"]["codec"]["path"])79 assert runtime.is_absolute() and runtime.name == "wire-runtime.mjs", "invalid runtime module"80 assert codec == runtime.with_name("wire-codec.mjs"), "runtime codec must share its module directory"81 selected = environment.get("CDK_RSX_WIRE_RUNTIME")82 if selected:83 assert Path(selected).is_absolute() and Path(selected).resolve() == runtime.resolve(), "selected runtime differs from artifact"84 return runtime.resolve()858687def main():88 parser = argparse.ArgumentParser(description=__doc__)89 parser.add_argument("--artifact", required=True, type=Path)90 parser.add_argument("--output", required=True, type=Path)91 parser.add_argument("--source-root", default=ROOT, type=Path)92 parser.add_argument("--source-revision", help="40-hex provenance revision for an independently pinned frozen source copy")93 args = parser.parse_args()94 if args.source_revision is not None and not re.fullmatch(r"[0-9a-f]{40}", args.source_revision):95 parser.error("--source-revision must be a full lowercase 40-hex revision")96 source, artifact, output = args.source_root.resolve(), args.artifact.resolve(), args.output.resolve()97 sdk = source / "cdk-rsx"98 manifest_path = artifact / "manifest.json"99 manifest = json.loads(manifest_path.read_text())100 assert manifest["app"] == "rrt"101 assert manifest["format"] == "rrt-typed-root-artifacts-v1"102 assert manifest["package"] == "rrt-fourcans-canister"103 assert manifest["features"] in ([], ["tripwire"], ["tripwire", "tripwire-workload"]), "select one exact benchmark codec image"104 wasm_sha256 = manifest["wasmSha256"]105 assert manifest["sourceUnchangedDuringBuild"] is True106 dependencies = host_dependencies(source)107 pinned = {row["path"]: row["sha256"] for row in records(manifest)}108 for path, expected in pinned.items():109 assert digest(path) == expected, f"changed build input/output: {path}"110 pinned[str(manifest_path)] = digest(manifest_path)111 for dependency in dependencies:112 for row in records(dependency):113 pinned[row["path"]] = row["sha256"]114 # The benchmark archives these exact source bytes. Keep both compile inputs115 # and its complete host harness fixed through final maintenance inspection.116 for directory in ("benches/rrt/host", "benches/rrt/support"):117 for path in (source / directory).glob("*.mjs"):118 pinned[str(path)] = digest(path)119 for relative in ("tests/pocketic/reactor-wire.mjs",120 "tests/pocketic/rechain-verification.mjs",121 "benches/rrt/package.json",122 "benches/rrt/package-lock.json",123 "benches/rrt/tools/audit.mjs", "tests/pocketic/session.mjs",124 "tests/pocketic/strict-tick.mjs", "tests/pocketic/resources.mjs",125 "tests/pocketic/verify-build.mjs", "tests/pocketic/instruction-profile.mjs",126 "tests/pocketic/native-memory-trace.mjs", "tests/pocketic/wire-client.mjs",127 "tests/pocketic/package.json",128 "tests/pocketic/package-lock.json"):129 pinned[str(source / relative)] = digest(source / relative)130 runtime = runtime_input(manifest, os.environ)131 pinned[str(source / "tests/pocketic/wire-runtime.mjs")] = digest(source / "tests/pocketic/wire-runtime.mjs")132 pinned[str(Path(__file__).resolve())] = digest(Path(__file__))133 audit = Path(__file__).with_name("audit.mjs").resolve()134 for path in (audit, audit.with_name("artifact.mjs")):135 pinned[str(path)] = digest(path)136 runner = source / "benches/rrt"137 server = manifest["server"]138 command = ["bun", "host/benchmark.mjs", "--canisters=16", "--workload=heavy", "--rates=1000",139 "--arrival-rounds=30", "--round-ms=600", "--batches=1024", "--budget=500000000",140 "--concurrency=4096", "--callbacks=40", "--batch-bytes=1900000", "--max-rounds=1000",141 "--topology=same", "--memory-tracing=true", "--trace-scope=complete",142 f"--pocket-ic={server['path']}", f"--build-dir={artifact}",143 f"--build-manifest={manifest_path}", f"--expected-wasm-sha256={wasm_sha256}",144 f"--results-dir={output}"]145 output.mkdir(parents=True, exist_ok=False)146 launch = {"command": command, "cwd": str(runner), "manifest_sha256": digest(manifest_path),147 "wasm_sha256": wasm_sha256, "server_sha256": server["sha256"], "source_before": pinned,148 "wire_runtime": str(runtime), "server_url": os.environ.get("RRT_PIC_SERVER_URL"), "runner_sha256": digest(Path(__file__)),149 "host_dependencies": dependencies, "source_root": str(source),150 "source_commit": args.source_revision or subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=source, text=True).strip(),151 "source_revision_origin": "explicit-frozen-source" if args.source_revision else "git-head",152 "auditor": {"path": str(audit), "sha256": digest(audit)}}153 (output / "launch.json").write_text(json.dumps(launch, indent=2) + "\n")154 started = time.monotonic()155 with (output / "process.log").open("w") as log:156 process = subprocess.run(command, cwd=runner,157 env={**os.environ, "TAKT_BUILD_DIR": str(artifact), "CDK_RSX_WIRE_RUNTIME": str(runtime)}, stdout=log, stderr=subprocess.STDOUT)158 changed = [path for path, expected in pinned.items() if not Path(path).is_file() or digest(path) != expected]159 receipt = {"returncode": process.returncode, "source_unchanged": not changed, "changed_inputs": changed,160 "process_host_seconds": time.monotonic() - started, "runner_sha256": digest(Path(__file__))}161 (output / "process-receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")162 if process.returncode:163 # Surface the child diagnostic in the harness task log and CI artifact.164 # The complete private log remains beside the unchanged run receipt.165 print((output / "process.log").read_text(errors="replace")[-32_768:], file=sys.stderr, flush=True)166 assert process.returncode == 0, f"Heavy16 failed (exit {process.returncode}); see {output / 'process.log'}"167 assert not changed, f"inputs changed during Heavy16: {changed}"168 with (output / "heavy16-audit.json").open("w") as report:169 subprocess.run(["node", str(audit), str(output), str(artifact)], cwd=source, check=True, stdout=report)170 print(output / "heavy16-audit.json")171172173if __name__ == "__main__":174 main()