Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions agents/validation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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),
Expand All @@ -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()
Expand Down
11 changes: 10 additions & 1 deletion meta_harness/runner_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"])
Expand Down
3 changes: 2 additions & 1 deletion meta_harness/runners/generic_transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
RunnerContractError,
paired_permutation_test,
recompute_metric,
sha256_file,
validate_final_results,
)

Expand All @@ -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:
Expand Down
90 changes: 90 additions & 0 deletions tests/test_runner_artifact_hash_memory.py
Original file line number Diff line number Diff line change
@@ -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)
Loading