From 3247622dadf30f4a3fda7a1562f8cd14d51c73eb Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 2 Dec 2026 17:18:06 +0800 Subject: [PATCH] perf: stream runner artifact hashes with bounded memory --- agents/validation_loop.py | 6 +- meta_harness/runner_contract.py | 11 ++- meta_harness/runners/generic_transformers.py | 3 +- tests/test_runner_artifact_hash_memory.py | 90 ++++++++++++++++++++ 4 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 tests/test_runner_artifact_hash_memory.py diff --git a/agents/validation_loop.py b/agents/validation_loop.py index fa2d4c8..c4bf259 100644 --- a/agents/validation_loop.py +++ b/agents/validation_loop.py @@ -51,6 +51,7 @@ from db import database as db from meta_harness.runner_contract import ( RunnerContractError, + sha256_file, validate_final_results, verify_metric_from_artifacts, ) @@ -2184,7 +2185,8 @@ def _record_contract_artifacts( "artifact_contract_violation", str(artifact_type) ) expected = str(hashes.get(artifact_type) or "") - if expected and hashlib.sha256(path.read_bytes()).hexdigest() != expected: + actual_hash = sha256_file(path) + if expected and actual_hash != expected: raise RunnerContractError("artifact_hash_mismatch", str(artifact_type)) _record_artifact( int(run_id), @@ -2198,7 +2200,7 @@ def _record_contract_artifacts( ), metadata={ "contract_type": "RunnerArtifact", - "sha256": expected or hashlib.sha256(path.read_bytes()).hexdigest(), + "sha256": actual_hash, }, ) db.commit() diff --git a/meta_harness/runner_contract.py b/meta_harness/runner_contract.py index 030ad1b..d9e02d5 100644 --- a/meta_harness/runner_contract.py +++ b/meta_harness/runner_contract.py @@ -70,6 +70,15 @@ def emit_final_results(self) -> Mapping[str, Any]: ... DEFAULT_PERMUTATIONS = 1000 +def sha256_file(path: Path) -> str: + """Hash a runner artifact with bounded temporary memory.""" + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + def _as_float(value: Any) -> float | None: try: number = float(value) @@ -426,7 +435,7 @@ def verify_metric_from_artifacts( if not raw_ref.is_absolute(): raw_ref = final_path.parent / raw_ref expected_hash = str(payload["artifact_hashes"].get("raw_predictions") or "") - actual_hash = hashlib.sha256(raw_ref.read_bytes()).hexdigest() + actual_hash = sha256_file(raw_ref) if actual_hash != expected_hash: raise RunnerContractError("artifact_hash_mismatch", "raw_predictions") baseline_method = str(payload["baseline_method"]) diff --git a/meta_harness/runners/generic_transformers.py b/meta_harness/runners/generic_transformers.py index 9a79eef..d996bec 100644 --- a/meta_harness/runners/generic_transformers.py +++ b/meta_harness/runners/generic_transformers.py @@ -21,6 +21,7 @@ RunnerContractError, paired_permutation_test, recompute_metric, + sha256_file, validate_final_results, ) @@ -33,7 +34,7 @@ def _dump(path: Path, payload: Any) -> None: def _sha256(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() + return sha256_file(path) def _normalized_input_sha256(value: str) -> str: diff --git a/tests/test_runner_artifact_hash_memory.py b/tests/test_runner_artifact_hash_memory.py new file mode 100644 index 0000000..a8b3831 --- /dev/null +++ b/tests/test_runner_artifact_hash_memory.py @@ -0,0 +1,90 @@ +import hashlib +import json +import tracemalloc + +import pytest + +from agents import validation_loop +from meta_harness.runner_contract import RunnerContractError, verify_metric_from_artifacts +from meta_harness.runners.generic_transformers import _sha256 + + +@pytest.fixture +def artifacts(tmp_path): + directory = tmp_path / "results" + directory.mkdir() + raw = directory / "raw_predictions.jsonl" + rows = [ + {"method": "baseline", "prediction": "no", "target": "yes"}, + {"method": "baseline", "prediction": "yes", "target": "yes"}, + {"method": "candidate", "prediction": "yes", "target": "yes"}, + {"method": "candidate", "prediction": "no", "target": "no"}, + ] + with raw.open("wb") as stream: + for row in rows: + stream.write((json.dumps(row) + "\n").encode()) + # Blank JSONL lines keep decoded-row memory small while exercising a + # real 16 MiB artifact in each production hashing path. + for _ in range(8192): + stream.write(b" " * 2047 + b"\n") + digest = hashlib.sha256(raw.read_bytes()).hexdigest() + refs = {"raw_predictions": {"path": raw.name}} + for name in ("environment_manifest", "dataset_manifest", "model_manifest"): + path = directory / f"{name}.json" + path.write_text("{}", encoding="utf-8") + refs[name] = {"path": path.name} + refs["final_results"] = {"path": "final_results.json"} + payload = { + "task_protocol": "sequence_classification", "dataset_id": "org/data", + "dataset_revision": "a" * 40, "model_id": "org/model", + "model_revision": "b" * 40, "seeds": [0], "num_examples": 2, + "baseline_method": "baseline", "candidate_method": "candidate", + "metric_name": "accuracy", "metric_direction": "higher", + "metric_value": 1.0, "baseline_metric_value": 0.5, "best_metric_value": 1.0, + "statistical_tests": {"paired_permutation_p": 0.03}, + "label_fallback_used": False, + "per_method": {"baseline": {"accuracy": 0.5}, "candidate": {"accuracy": 1.0}}, + "gpu_environment": {"available": True}, + "artifacts": refs, "artifact_hashes": {"raw_predictions": digest}, + } + final = directory / "final_results.json" + final.write_text(json.dumps(payload), encoding="utf-8") + return raw, final, payload, digest + + +@pytest.mark.parametrize("consumer", ["runner", "verifier", "registry"]) +def test_hashing_does_not_allocate_the_whole_artifact(artifacts, monkeypatch, consumer): + raw, final, payload, digest = artifacts + recorded = [] + monkeypatch.setattr(validation_loop, "_record_artifact", lambda *a, **kw: recorded.append(kw)) + monkeypatch.setattr(validation_loop.db, "commit", lambda: None) + tracemalloc.start() + try: + if consumer == "runner": + assert _sha256(raw) == digest + elif consumer == "verifier": + verified = verify_metric_from_artifacts(final) + assert verified.recomputed_candidate == 1.0 + else: + validation_loop._record_contract_artifacts(1, final.parent.parent, payload) + assert len(recorded) == 5 + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + print(f"{consumer} hashing peak: {peak} bytes") + assert peak < 4 * 1024 * 1024 + + +@pytest.mark.parametrize("content", [b"", b"\x00\xffbinary\r\n", b"x" * (1024 * 1024 + 7)]) +def test_empty_binary_and_partial_final_chunks_keep_the_same_digest(tmp_path, content): + path = tmp_path / "artifact" + path.write_bytes(content) + assert _sha256(path) == hashlib.sha256(content).hexdigest() + + +def test_tampering_is_still_refused_before_metric_recomputation(artifacts): + raw, final, _, _ = artifacts + with raw.open("ab") as stream: + stream.write(b"tampered") + with pytest.raises(RunnerContractError, match="artifact_hash_mismatch"): + verify_metric_from_artifacts(final)