diff --git a/docs/plans/rfc008-validation-completion.md b/docs/plans/rfc008-validation-completion.md index 84303e606b..ddf43bb16a 100644 --- a/docs/plans/rfc008-validation-completion.md +++ b/docs/plans/rfc008-validation-completion.md @@ -168,8 +168,11 @@ writes the amendment, and the Hub pipeline team implements the operator panel. ### 4. Determinism, replay and leakage graders -`semantic.verifier_determinism`, `semantic.verifier_portability`, -`semantic.replayability` and `semantic.no_solution_leakage` have no graders. +`semantic.verifier_determinism` now grades Harbor tasks with a separate verifier: +the first oracle run's collected artifacts are graded three times, each in a fresh +environment, and every reward map must be equal. A shared verifier is a named SKIP. +`semantic.verifier_portability`, `semantic.replayability` and +`semantic.no_solution_leakage` have no graders. Harbor tasks now establish `runtime.episode_determinism` when an oracle replay in a fresh container reproduces every reward and the oracle exit code. Each trial is a one-shot episode with no per-step observations. Served environments retain the diff --git a/docs/source/reference/cli.md b/docs/source/reference/cli.md index 3c1e743e37..f5c573fd23 100644 --- a/docs/source/reference/cli.md +++ b/docs/source/reference/cli.md @@ -111,7 +111,8 @@ HF Jobs: a do-nothing agent, the oracle (`solution/solve.sh`), an oracle replay and any canaries declared in the contract. A canary is a known-wrong `solve.sh` replacement. The results report under `runtime.startup`, `runtime.reward_well_formed`, `runtime.episode_determinism`, `semantic.oracle_max`, -`semantic.floor_gap` and `semantic.canary_floor`, and `harbor-evidence.json` keeps +`semantic.floor_gap`, `semantic.canary_floor` and `semantic.verifier_determinism`, +and `harbor-evidence.json` keeps the raw trial evidence in the report bundle. Other checks are named SKIPs, so a passing task still reports WARN. This validates task packages, not the outer `harbor_env` server. @@ -178,6 +179,14 @@ uploads `tests/` at grading time, so test files never need to be in the image. A separate verifier with its own image, either `verifier.environment.docker_image` or a `tests/Dockerfile`, is unsupported. +At the semantic level, a separate verifier grades the first oracle run's collected +artifacts three times, each time in a new job. Once `runtime.episode_determinism` +passes, `semantic.verifier_determinism` passes if all three calls return reward maps +that are equal as exact rationals. It is a named SKIP when Harbor's artifact record +misses a verifier input, including the implicit artifact directory. A shared +verifier runs in the agent's container, which Harbor stops after one verification, +so the check is a named SKIP there and on Docker. + Each job, including a separate verifier's, carries `openenv-validation-run` and `openenv-validation-role` labels. At `AGENT_START` the validator reads the job back and requires the pinned image, the diff --git a/rfcs/008-environment-auto-validation.md b/rfcs/008-environment-auto-validation.md index d058a447b8..1786758d8e 100644 --- a/rfcs/008-environment-auto-validation.md +++ b/rfcs/008-environment-auto-validation.md @@ -822,13 +822,14 @@ Results map to RFC check ids: | `semantic.oracle_max` | Both oracle runs exit 0 and meet the oracle bound in the semantic contract above. A task without `solution/solve.sh` fails. | | `semantic.floor_gap` | Both floor-gap conditions in the semantic contract above hold for every oracle run. | | `semantic.canary_floor` | Every declared canary earns no more than the measured floor. Selected only when canaries are declared. | +| `semantic.verifier_determinism` | A separate verifier grades the first oracle run's collected artifacts three times, each in a fresh environment, and every reward map is equal. A shared verifier, or an artifact record that misses a verifier input, gives a named SKIP. | The semantic ids depend on `runtime.episode_determinism`, so a diverging replay SKIPs them with the dependency named. Oracle tolerance and floor margin are fractions of the declared range, with `width = max - min`. Reward comparisons use exact rationals parsed from the raw verifier output. Every other local check is a named SKIP for this binding. It produces no WebSocket exchange, containment or resource -measurement, second verification of one final state, or leakage scan. A passing run is therefore +measurement, or leakage scan. A passing run is therefore WARN, and full RFC qualification still rejects these SKIPs. Canaries are operator-declared, known-wrong `solve.sh` replacements, at most eight diff --git a/src/openenv/validation/graders/semantic/__init__.py b/src/openenv/validation/graders/semantic/__init__.py index 08aadc2e4d..5e3a96be3a 100644 --- a/src/openenv/validation/graders/semantic/__init__.py +++ b/src/openenv/validation/graders/semantic/__init__.py @@ -1,5 +1,15 @@ """Semantic-level graders.""" -from .oracle import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader +from .oracle import ( + CanaryFloorGrader, + FloorGapGrader, + OracleMaxGrader, + VerifierDeterminismGrader, +) -__all__ = ["CanaryFloorGrader", "FloorGapGrader", "OracleMaxGrader"] +__all__ = [ + "CanaryFloorGrader", + "FloorGapGrader", + "OracleMaxGrader", + "VerifierDeterminismGrader", +] diff --git a/src/openenv/validation/graders/semantic/oracle.py b/src/openenv/validation/graders/semantic/oracle.py index 9dd8a8d9f3..f1e24a1146 100644 --- a/src/openenv/validation/graders/semantic/oracle.py +++ b/src/openenv/validation/graders/semantic/oracle.py @@ -1,4 +1,4 @@ -"""Verifier sanity over oracle, do-nothing and canary rewards (#778 tests #25, #28). +"""Verifier sanity over oracle, do-nothing and canary rewards (#778 tests #25, #28, #39). The execution binding measures the rewards; these graders only compare them with the manifest's declared range, tolerance and margin. Comparisons use exact rationals so a @@ -143,3 +143,33 @@ def check(self, evidence, *, maximum, width, tolerance, margin): name: float(reward) for name, reward in evidence.canaries }, } + + +class VerifierDeterminismGrader(_SemanticGrader): + """ + Every verifier call on one final oracle state returns the same reward map. The + maps must be equal as exact rationals because the verifier is a script, not an + LLM judge. + """ + + check_id = "semantic.verifier_determinism" + passed = "every verifier call on one final state returned the same rewards" + remediation = ( + "Make the tests depend only on the final state, without clocks, randomness " + "or network calls." + ) + + def check(self, evidence, *, maximum, width, tolerance, margin): + calls = evidence.verifier_rewards + problems = [ + f"verifier call {call} returned different rewards from verifier call " + f"{len(calls)}" + for call, rewards in enumerate(calls[:-1], start=1) + if rewards != calls[-1] + ] + return problems, { + "verifier_rewards": [ + {key: float(value) for key, value in rewards.items()} + for rewards in calls + ] + } diff --git a/src/openenv/validation/harbor.py b/src/openenv/validation/harbor.py index 6932562ecb..9d8be76b48 100644 --- a/src/openenv/validation/harbor.py +++ b/src/openenv/validation/harbor.py @@ -3,7 +3,9 @@ No served-protocol evidence is synthesized. On local Docker, a do-nothing trial builds the image, or pulls the task's digest-pinned one, and the oracle, its replay and any canaries run pinned to that image. On `hf-sandbox`, every trial starts at -once from the task's digest-pinned image, each in its own Hugging Face Job. +once from the task's digest-pinned image, each in its own Hugging Face Job. At the +semantic level, a separate verifier grades the first oracle run's collected artifacts +three times. """ import asyncio @@ -28,7 +30,12 @@ from pathlib import Path from .graders import GraderRegistry -from .graders.semantic import CanaryFloorGrader, FloorGapGrader, OracleMaxGrader +from .graders.semantic import ( + CanaryFloorGrader, + FloorGapGrader, + OracleMaxGrader, + VerifierDeterminismGrader, +) from .parsers.harbor_toml import ( _unique_object, canary_scripts, @@ -73,7 +80,15 @@ "semantic.oracle_max", "semantic.floor_gap", "semantic.canary_floor", + "semantic.verifier_determinism", +} +_REWARD_FAILURES = { + "RewardFileNotFoundError", + "RewardFileEmptyError", + "VerifierOutputParseError", } +# semantic.verifier_determinism verifies one final oracle state this many times. +_VERIFIER_CALLS = 3 class NativeEvidenceError(ValueError): @@ -502,6 +517,24 @@ def _unsupported(task, contract, sandbox): return None +def _artifact_problems(trial): + # Harbor's regrade check: every verifier input, including the implicit artifact + # directory, is recorded and on disk where the separate verifier's upload reads it. + from harbor.trial.regrade import read_artifact_manifest, RegradeError, RegradeTrial + + try: + entries = read_artifact_manifest(trial.paths.trial_dir) + except RegradeError: + return ["Harbor recorded no artifact manifest"] + return RegradeTrial._artifact_coverage_problems( + trial, + source_artifacts_dir=trial.paths.artifacts_dir, + source_record_dir=trial.paths.trial_dir, + entries=entries, + declared_artifacts=[*trial.task.config.artifacts, *trial.config.artifacts], + ) + + async def _create_trial(config, register_job=None): from harbor.environments.hf_sandbox import HFSandboxEnvironment from harbor.trial.trial import Trial @@ -720,6 +753,7 @@ async def _trial( source_binding, expected=None, canary=None, + repeat_verifier=False, ): from harbor.models.environment_type import EnvironmentType from harbor.models.trial.config import ( @@ -745,6 +779,7 @@ async def _trial( "cleanup": {"verified": False}, } raw_files = {} + repeats = [] trial = None phase = "trial creation" registered = False @@ -854,6 +889,41 @@ async def build_and_start(*, force_build): phase = "agent setup" trial.agent_environment.start = build_and_start + if repeat_verifier: + verify = trial._run_verifier + + async def verify_repeatedly(): + # Harbor's own call runs last, so the trial's result and reward files + # are its own. Each call starts a fresh verifier environment from the + # artifacts Harbor collected once. + problems = await asyncio.to_thread(_artifact_problems, trial) + if problems: + record["artifact_problems"] = problems + await verify() + return + for call in range(1, _VERIFIER_CALLS): + outcome = {"raw": {}} + try: + try: + await verify() + outcome["parsed"] = trial.result.verifier_result.rewards + finally: + for filename, path in ( + ("reward.json", trial.paths.reward_json_path), + ("reward.txt", trial.paths.reward_text_path), + ): + raw = _read_output(path, trial.paths.trial_dir) + if raw is not None: + outcome["raw"][filename] = raw + raw_files[f"verifier-call-{call}/{filename}"] = raw + # A final call that fails early must not inherit these. + path.unlink(missing_ok=True) + except Exception as exc: + outcome["failure"] = type(exc).__name__ + repeats.append(outcome) + await verify() + + trial._run_verifier = verify_repeatedly async def environment_start(_event): nonlocal phase @@ -905,11 +975,7 @@ async def verification_start(_event): ) if result.exception_info is not None: failure = result.exception_info.exception_type - if failure in { - "RewardFileNotFoundError", - "RewardFileEmptyError", - "VerifierOutputParseError", - }: + if failure in _REWARD_FAILURES: if "container_id" not in record: raise NativeEvidenceError( "Harbor reward failure has no container identity" @@ -934,6 +1000,13 @@ async def verification_start(_event): f"Harbor subject failed during {subject_phase} ({failure})" ) raise NativeEvidenceError("Harbor Trial returned exception_info") + for call, outcome in enumerate(repeats, start=1): + if outcome.get("failure") == "VerifierTimeoutError": + record["subject_error"] = "verifier" + raise NativeEvidenceError( + f"Harbor subject failed during verifier call {call} " + "(VerifierTimeoutError)" + ) if "container_id" not in record: raise NativeEvidenceError("Harbor Trial has no actual AGENT_START identity") for filename, path in ( @@ -956,6 +1029,22 @@ async def verification_start(_event): parsed = result.verifier_result.rewards if result.verifier_result else None record["reward_error"] = True record["rewards"] = _reward(raw_files, parsed, contract) + if repeats: + record["verifier_calls"] = [] + for call, outcome in enumerate(repeats, start=1): + failure = outcome.get("failure") + # Harbor's VerifierResult rejects a reward file that holds a JSON scalar. + if failure in _REWARD_FAILURES or ( + failure == "ValidationError" and outcome["raw"] + ): + raise NativeEvidenceError( + f"Harbor verifier reward failed on verifier call {call} ({failure})" + ) + record["verifier_calls"].append( + {"failure": failure} + if failure + else {"rewards": _reward(outcome["raw"], outcome["parsed"], contract)} + ) record.pop("reward_error") except (Exception, KeyboardInterrupt) as exc: record["failure"] = type(exc).__name__ @@ -1029,7 +1118,15 @@ async def verification_start(_event): return record, raw_files -async def _collect(root, contract, work, inspector, source_binding, canaries=()): +async def _collect( + root, + contract, + work, + inspector, + source_binding, + canaries=(), + repeat_verifier=False, +): run_id = uuid.uuid4().hex # The replay makes episode determinism measurable before any semantic check. plan = [ @@ -1060,14 +1157,28 @@ async def _collect(root, contract, work, inspector, source_binding, canaries=()) if isinstance(inspector, HFJobsInspector): # A pinned image needs no build, so every trial starts at once. outcomes = await asyncio.gather( - *(run_trial(role, agent, canary=canary) for role, agent, canary in plan) + *( + run_trial( + role, + agent, + canary=canary, + repeat_verifier=repeat_verifier and role == "oracle", + ) + for role, agent, canary in plan + ) ) else: outcomes = [] for role, agent, canary in plan: expected = outcomes[0][0] if outcomes else None outcomes.append( - await run_trial(role, agent, expected=expected, canary=canary) + await run_trial( + role, + agent, + expected=expected, + canary=canary, + repeat_verifier=repeat_verifier and role == "oracle", + ) ) if "failure" in outcomes[-1][0]: break @@ -1134,6 +1245,11 @@ def validate_harbor( namespace=None, ): """Run fresh native Harbor trials and grade them up to the requested level.""" + from harbor.models.task.verifier_mode import ( + resolve_task_verifier_mode, + VerifierEnvironmentMode, + ) + from .runner import source_digest started = time.monotonic() @@ -1167,6 +1283,9 @@ def validate_harbor( attempted = False task = read_harbor_task(subject.root) problem = _unsupported(task, contract, sandbox) + separate = ( + resolve_task_verifier_mode(task.config) is VerifierEnvironmentMode.SEPARATE + ) if sandbox == "hf-sandbox": inspector = HFJobsInspector( task.config.environment.docker_image, @@ -1199,6 +1318,7 @@ def validate_harbor( "unmet dependency: native Harbor trials", ) evidence = None + verifier_check = None checks = [] semantic_graded = False if ( @@ -1240,6 +1360,7 @@ def validate_harbor( inspector, digest_before, canaries, + repeat_verifier=semantic and separate, ) ) record["trials"] = trials @@ -1409,6 +1530,41 @@ def validate_harbor( and trial["cleanup"]["verified"] ), ) + calls = [ + *oracle.get("verifier_calls", ()), + {"rewards": oracle["rewards"]}, + ] + failed = [ + f"verifier call {number} failed ({call['failure']})" + for number, call in enumerate(calls, start=1) + if "failure" in call + ] + if "artifact_problems" in oracle: + verifier_check = _result( + "semantic.verifier_determinism", + CheckStatus.SKIP, + "unmet dependency: a Harbor artifact record of every " + "verifier input", + {"artifact_problems": oracle["artifact_problems"]}, + ) + elif failed: + verifier_check = CheckResult( + check_id="semantic.verifier_determinism", + status=CheckStatus.ERROR, + evidence=failed, + duration_s=0, + ) + elif semantic and separate: + evidence = replace( + evidence, + verifier_rewards=tuple( + { + name: Fraction(value) + for name, value in call["rewards"].items() + } + for call in calls + ), + ) except (Exception, KeyboardInterrupt) as exc: record["failure"] = type(exc).__name__ reason = f"native Harbor collection failed ({type(exc).__name__})" @@ -1426,6 +1582,7 @@ def validate_harbor( OracleMaxGrader(), FloorGapGrader(), CanaryFloorGrader(), + VerifierDeterminismGrader(), ): registry.register(grader) selected = registry.select(subject.manifest, max_level) @@ -1442,6 +1599,25 @@ def validate_harbor( "unmet dependency: complete canary trials with verified cleanup", ) ) + if not separate: + verifier_check = _result( + "semantic.verifier_determinism", + CheckStatus.SKIP, + f"unsupported by {HARBOR_PROFILE}: a shared verifier runs " + "in the agent container, which Harbor stops after one " + "verification", + ) + # Without episode determinism, the grader's dependency SKIP wins. + if ( + verifier_check is not None + and determinism.status is CheckStatus.PASS + ): + selected = [ + grader + for grader in selected + if grader.check_id != "semantic.verifier_determinism" + ] + checks.append(verifier_check) checks.extend( execute_graders( selected, diff --git a/src/openenv/validation/runtime/contracts.py b/src/openenv/validation/runtime/contracts.py index 478ba53ace..61ffc7bea4 100644 --- a/src/openenv/validation/runtime/contracts.py +++ b/src/openenv/validation/runtime/contracts.py @@ -704,12 +704,16 @@ class OracleEvidence: Exit code of each oracle run, in run order. canaries (`tuple[tuple[str, Fraction], ...]`, *optional*): Name and reward of each declared canary run. + verifier_rewards (`tuple[dict[str, Fraction], ...]`, *optional*): + Reward map of each verifier call on the first oracle run's final state, + in call order. Empty unless the binding verified that state more than once. """ floor: Fraction oracle: tuple[Fraction, ...] oracle_exit_codes: tuple[int, ...] canaries: tuple[tuple[str, Fraction], ...] = () + verifier_rewards: tuple[dict[str, Fraction], ...] = () @dataclass(frozen=True) diff --git a/tests/test_validation/test_harbor_validation.py b/tests/test_validation/test_harbor_validation.py index d7764a21dd..c445ab1a6a 100644 --- a/tests/test_validation/test_harbor_validation.py +++ b/tests/test_validation/test_harbor_validation.py @@ -87,6 +87,9 @@ def boundary(monkeypatch, task): on_start=None, on_stop=None, start_barrier=None, + verifier_rewards={}, + verifier_failures={}, + artifact_status={}, ) class Inspector: @@ -152,6 +155,7 @@ def __init__(self, config): reward_json_path=directory / "verifier/reward.json", reward_text_path=directory / "verifier/reward.txt", agent_dir=directory / "agent", + artifacts_dir=directory / "artifacts", ) self.agent_environment = SimpleNamespace( session_id=config.trial_name + "__env", @@ -161,7 +165,13 @@ def __init__(self, config): ) self.hooks = {} self._openenv_cancelled_compose = [] - environment = read_harbor_task(config.task.path).config.environment + from harbor.models.trial.paths import EnvironmentPaths + + self.task = read_harbor_task(config.task.path) + environment = self.task.config.environment + self.agent_env_paths = EnvironmentPaths.for_os(environment.os) + self.result = SimpleNamespace(verifier_result=None) + self.verifier_calls = 0 self._environment_build_timeout_sec = environment.build_timeout_sec self.docker_image = environment.docker_image state.excluded_copied.append( @@ -249,9 +259,7 @@ async def run(self): ) if state.timeout: raise TimeoutError() - raw = state.rewards.get(self.role, state.rewards[self.agent]) - if raw is not None: - self.paths.reward_json_path.write_bytes(raw) + self.raw = state.rewards.get(self.role, state.rewards[self.agent]) if self.agent == "oracle" and state.oracle_exit is not None: (self.paths.agent_dir / "exit-code.txt").write_text( str(state.oracle_exit) @@ -268,28 +276,82 @@ async def run(self): (self.config.task.path / "instruction.md").write_text( "changed execution source" ) - for hook in self.hooks.get("verification-start", []): - await hook(None) - try: - rewards = json.loads(raw) if raw else None - except ValueError: - rewards = None + from harbor.models.task.verifier_mode import resolve_task_verifier_mode + + if resolve_task_verifier_mode(self.task.config).value == "separate": + self.collect_artifacts() exception_type = state.exception_type - if raw is None: - exception_type = "RewardFileNotFoundError" - elif raw == b"": - exception_type = "RewardFileEmptyError" - elif raw in (b'{"reward":NaN}', b'{"reward":Infinity}', b'{"reward":"0"}'): - exception_type = "VerifierOutputParseError" + try: + await self._run_verifier() + except Exception as exc: + # Harbor records a failed verification as the trial's exception. + exception_type = type(exc).__name__ if state.exception: exception_type = "TestError" return SimpleNamespace( exception_info=SimpleNamespace(exception_type=exception_type) if exception_type else None, - verifier_result=SimpleNamespace(rewards=rewards), + verifier_result=self.result.verifier_result, ) + def collect_artifacts(self): + # Harbor's manifest: the implicit artifact directory, then each declared one. + from harbor.models.task.artifacts import with_convention_entry + from harbor.trial.artifact_handler import artifact_host_path + + entries = [] + for artifact in with_convention_entry( + self.task.config.artifacts, + convention_source=self.agent_env_paths.artifacts_dir.as_posix(), + ): + status = state.artifact_status.get(artifact.source, "ok") + if status == "unrecorded": + continue + host = artifact_host_path(self.paths.artifacts_dir, artifact) + if status == "ok": + host.mkdir(parents=True) + entries.append( + { + "source": artifact.source, + "destination": host.relative_to( + self.paths.trial_dir + ).as_posix(), + "type": "directory", + # Recorded as collected, but gone from disk. + "status": "ok" if status == "missing" else status, + "exclude": list(artifact.exclude), + } + ) + self.paths.artifacts_dir.mkdir(exist_ok=True) + (self.paths.artifacts_dir / "manifest.json").write_text(json.dumps(entries)) + + async def _run_verifier(self): + for hook in self.hooks.get("verification-start", []): + await hook(None) + self.verifier_calls += 1 + call = (self.role, self.verifier_calls) + if call in state.verifier_failures: + raise _harbor_error(state.verifier_failures[call]) + raw = state.verifier_rewards.get(call, self.raw) + # Like Harbor's verifier, every call first discards earlier rewards. + self.paths.reward_json_path.unlink(missing_ok=True) + if raw is None: + raise _harbor_error("RewardFileNotFoundError") + self.paths.reward_json_path.write_bytes(raw) + if raw == b"": + raise _harbor_error("RewardFileEmptyError") + if raw in (b'{"reward":NaN}', b'{"reward":Infinity}', b'{"reward":"0"}'): + raise _harbor_error("VerifierOutputParseError") + try: + rewards = json.loads(raw) + except ValueError: + rewards = None + if isinstance(rewards, (int, float)): + # Harbor's VerifierResult rejects a reward that is not a map. + raise _harbor_error("ValidationError") + self.result.verifier_result = SimpleNamespace(rewards=rewards) + async def create(config, register_job=None): return Trial(config) @@ -401,6 +463,11 @@ def docker(self, *args): return state +def _harbor_error(name): + # The binding sees only the type name of a Harbor exception. + return type(name, (Exception,), {})() + + def _role(trial_name): # openenv-validation-- return trial_name.split("-", 3)[3] @@ -1551,6 +1618,153 @@ def test_hf_sandbox_runs_a_separate_verifier_from_the_task_image( assert "outside hf-sandbox" in result(report, "runtime.startup").evidence[0] +@pytest.fixture +def separate(task, boundary, hf_jobs): + (task / "task.toml").write_text(SEPARATE_VERIFIER) + return boundary + + +def verifier_calls(boundary): + return {trial.role: trial.verifier_calls for trial in boundary.trials} + + +def test_shared_verifier_names_why_verifier_determinism_is_skipped(task, boundary): + report = run_validation(task) + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.SKIP + assert check.evidence == [ + "unsupported by harbor-semantic-v1: a shared verifier runs in the agent " + "container, which Harbor stops after one verification" + ] + assert verifier_calls(boundary) == {"nop": 1, "oracle": 1, "oracle-replay": 1} + + +@pytest.mark.parametrize("app", ["ok", "empty"]) +def test_separate_verifier_grades_three_calls_on_one_final_state( + task, separate, tmp_path, app +): + separate.artifact_status["/app"] = app + artifacts = tmp_path / "verifier-calls" + report = run_validation(task, sandbox="hf-sandbox", artifacts_dir=artifacts) + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.PASS + assert check.measured == {"verifier_rewards": [{"reward": 1.0}] * 3} + # Only the first oracle run verifies its final state again. + assert verifier_calls(separate) == {"nop": 1, "oracle": 3, "oracle-replay": 1} + native = json.loads((artifacts / "harbor-evidence.json").read_text()) + oracle = native["trials"][1] + assert oracle["verifier_calls"] == [{"rewards": {"reward": 1}}] * 2 + for call in (1, 2): + name = f"verifier-call-{call}/reward.json" + raw = (artifacts / "harbor-trials/oracle" / name).read_bytes() + assert raw == b'{"reward":1}' + assert oracle["raw_rewards"][name]["sha256"] == hashlib.sha256(raw).hexdigest() + + +@pytest.mark.parametrize("call", [1, 2]) +def test_a_differing_verifier_call_fails_while_the_replay_agrees(task, separate, call): + separate.verifier_rewards[("oracle", call)] = b'{"reward":1,"partial":0.5}' + report = run_validation(task, sandbox="hf-sandbox") + assert report.verdict is Verdict.FAIL + assert result(report, "runtime.episode_determinism").status is CheckStatus.PASS + assert result(report, "semantic.oracle_max").status is CheckStatus.PASS + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.FAIL + assert check.evidence == [ + f"verifier call {call} returned different rewards from verifier call 3" + ] + rewards = [{"reward": 1.0}] * 3 + rewards[call - 1] = {"reward": 1.0, "partial": 0.5} + assert check.measured == {"verifier_rewards": rewards} + + +@pytest.mark.parametrize("raw", [b'{"reward":2}', b"", b"0"]) +def test_a_malformed_verifier_call_fails_the_reward_contract_and_skips_after_it( + task, separate, tmp_path, raw +): + separate.verifier_rewards[("oracle", 1)] = raw + artifacts = tmp_path / "malformed-call" + report = run_validation(task, sandbox="hf-sandbox", artifacts_dir=artifacts) + assert result(report, "runtime.reward_well_formed").status is CheckStatus.FAIL + episode = result(report, "runtime.episode_determinism") + assert episode.status is CheckStatus.SKIP + assert episode.evidence == ["unmet dependency: runtime.reward_well_formed"] + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.SKIP + assert check.evidence == ["unmet dependencies: runtime.episode_determinism"] + assert ( + artifacts / "harbor-trials/oracle/verifier-call-1/reward.json" + ).read_bytes() == raw + + +@pytest.mark.parametrize("separate_verifier", [True, False]) +def test_replay_divergence_skips_verifier_determinism( + task, boundary, hf_jobs, separate_verifier +): + if separate_verifier: + (task / "task.toml").write_text(SEPARATE_VERIFIER) + boundary.rewards["oracle-replay"] = b'{"reward":0.5}' + report = run_validation(task, sandbox="hf-sandbox") + assert result(report, "runtime.episode_determinism").status is CheckStatus.FAIL + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.SKIP + assert check.evidence == ["unmet dependencies: runtime.episode_determinism"] + + +@pytest.mark.parametrize( + "source,status,problem", + [ + ("/app", "failed", "collection failed"), + ("/app", "skipped", "skipped in the source trial"), + ("/app", "missing", "no longer exists on disk"), + ("/logs/artifacts", "unrecorded", "never collected"), + ], +) +def test_an_incomplete_artifact_record_skips_without_more_verifier_jobs( + task, separate, source, status, problem +): + separate.artifact_status[source] = status + report = run_validation(task, sandbox="hf-sandbox") + assert result(report, "semantic.oracle_max").status is CheckStatus.PASS + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.SKIP + assert check.evidence == [ + "unmet dependency: a Harbor artifact record of every verifier input" + ] + (found,) = check.measured["artifact_problems"] + assert found.startswith(source + ":") and problem in found + assert verifier_calls(separate)["oracle"] == 1 + + +def test_a_failed_verifier_call_is_an_error(task, separate): + separate.verifier_failures[("oracle", 2)] = "EnvironmentStartTimeoutError" + report = run_validation(task, sandbox="hf-sandbox") + assert result(report, "semantic.oracle_max").status is CheckStatus.PASS + check = result(report, "semantic.verifier_determinism") + assert check.status is CheckStatus.ERROR + assert check.evidence == ["verifier call 2 failed (EnvironmentStartTimeoutError)"] + assert verifier_calls(separate)["oracle"] == 3 + + +@pytest.mark.parametrize("call", [1, 2]) +def test_a_verifier_timeout_on_an_extra_call_fails_the_package(task, separate, call): + separate.verifier_failures[("oracle", call)] = "VerifierTimeoutError" + report = run_validation(task, sandbox="hf-sandbox") + startup = result(report, "runtime.startup") + assert startup.status is CheckStatus.FAIL + assert startup.evidence[0] == "native Harbor subject failed during verifier" + assert startup.measured["failures"] == [ + f"Harbor subject failed during verifier call {call} (VerifierTimeoutError)" + ] + assert result(report, "semantic.verifier_determinism").status is CheckStatus.SKIP + + +def test_verifier_calls_repeat_only_at_the_semantic_level(task, separate): + report = run_validation(task, sandbox="hf-sandbox", max_level=Level.RUNTIME) + assert result(report, "runtime.episode_determinism").status is CheckStatus.PASS + assert verifier_calls(separate) == {"nop": 1, "oracle": 1, "oracle-replay": 1} + + @pytest.mark.parametrize( "shape,reason", [