JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
6.75 kB
"""The single released API Reliability driver."""
from __future__ import annotations
from copy import deepcopy
import hashlib
import json
from pathlib import Path, PurePosixPath
from rescopebench.lifecycle import approved_schedule
from .adapter import ROLE
from .spec import BUSINESS_BUDGET, CASE_VERSION, DATA, PROMPT, TASK_IDS, provider_tools, public_task
from .world import ApiReliabilityWorld
CASE_DIR = Path(__file__).resolve().parent
PACKAGE_ROOT = CASE_DIR.parents[1]
BINDING = CASE_DIR / "formal-binding.json"
MANIFEST = CASE_DIR / "case-manifest.json"
def _read(path: Path):
return json.loads(path.read_text(encoding="utf-8"))
def _checked_path(root: Path, name: str) -> Path:
relative = PurePosixPath(name)
if (relative.is_absolute() or ".." in relative.parts or not relative.parts
or relative.as_posix() != name or "\\" in name):
raise ValueError("unsafe API package member")
path = root / relative
if not path.resolve().is_relative_to(root) or path.is_symlink():
raise ValueError("API package member escapes its root")
return path
class ApiReliabilityDriver:
case_id = "api_reliability"
case_version = CASE_VERSION
prompt = deepcopy(PROMPT)
lifecycle_schedule = approved_schedule(case_id)
def __init__(self, artifact_root: Path | str = DATA) -> None:
self.directory = Path(artifact_root).resolve()
self.tools = provider_tools()
self.tasks = []
for position, task_id in enumerate(TASK_IDS, 1):
task = public_task(task_id, self.directory)
self.tasks.append({
"position": position, "private_task_id": task_id, "event_id": task["event_id"],
"query": json.dumps(task, sort_keys=True),
"business_budget": deepcopy(task["budget"]), "completion": deepcopy(task["completion"]),
})
def source_files(self) -> list[Path]:
manifest = _read(MANIFEST)
paths = {MANIFEST}
paths.update(_checked_path(CASE_DIR, name) for name in manifest["files"])
paths.update(_checked_path(PACKAGE_ROOT, name) for name in manifest["shared_sources"])
if any(not path.is_file() for path in paths):
raise ValueError("API source closure contains missing files")
return sorted(paths)
def validate(self) -> dict:
manifest = _read(MANIFEST)
errors = []
if (manifest.get("schema") != "rescopebench-case-files/v1"
or manifest.get("case_id") != self.case_id or manifest.get("case_version") != self.case_version
or not manifest.get("files") or not manifest.get("shared_sources")):
raise ValueError("invalid API case manifest")
for root, records in ((CASE_DIR, manifest["files"]), (PACKAGE_ROOT, manifest["shared_sources"])):
for name, expected in records.items():
path = _checked_path(root, name)
if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != expected:
errors.append("source or data checksum mismatch: " + name)
actual = {path.relative_to(CASE_DIR).as_posix() for path in CASE_DIR.rglob("*")
if path.is_file() and path != MANIFEST and "__pycache__" not in path.parts}
if actual != set(manifest["files"]):
errors.append("API package inventory differs")
compilation = _read(self.directory / "private/compilation.json")
world = self.create_world()
initial = world.snapshot()
world.restore(deepcopy(initial))
expected_tasks = [public_task(task_id, self.directory) for task_id in TASK_IDS]
loaded_tasks = [json.loads(task["query"]) for task in self.tasks]
task_text = "\n".join(json.dumps(task, sort_keys=True).lower() for task in self.tasks)
leaked_recipe_tokens = ("query credential", "query recovery evidence", "call list_api_credentials",
"call list_retry_budgets", "call search_recovery_evidence",
"with both exact filters", "limit=1")
checks = {
"source_and_data_integrity": not errors,
"released_data_directory": self.directory == DATA,
"initial_snapshot_round_trip": world.snapshot() == initial,
"frozen_initial_state": initial == _read(self.directory / "private/initial.json"),
"sixteen_unique_tasks": len(self.tasks) == 16 and len({t["event_id"] for t in self.tasks}) == 16,
"four_targets_per_task": all(len(task["targets"]) == 4 for task in expected_tasks),
"business_allowance_is_57": all(t["business_budget"]["limits"][0]["allowance"] == BUSINESS_BUDGET for t in self.tasks),
"public_tasks_do_not_leak_discovery_recipe": not any(token in task_text for token in leaked_recipe_tokens),
"joint_compilation": compilation["status"] == "passed" and all(compilation["checks"].values()),
"all_sixteen_reference_tasks": len(compilation["reference"]) == 16,
"public_task_parity": compilation["public_tasks"] == expected_tasks == loaded_tasks,
"schedule_parity": compilation["schedule"] == self.lifecycle_schedule,
"same_tools": self.tools == _read(self.directory / "public/tools.json"),
"common_evidence_retention_prompt": self.prompt == PROMPT,
"loaded_binding_exact": getattr(self, "binding_spec", _read(BINDING)) == _read(BINDING),
}
return {"status": "passed" if all(checks.values()) else "failed", "case_version": CASE_VERSION,
"checks": checks, "errors": errors,
"scope": "Package integrity and legal reference evidence, not natural model performance."}
def create_world(self) -> ApiReliabilityWorld:
return ApiReliabilityWorld()
def begin(self, world: ApiReliabilityWorld, task: dict) -> dict:
return world.activate_task(task["private_task_id"])
def call(
self,
world: ApiReliabilityWorld,
name: str,
arguments: dict,
) -> dict:
return world.dispatch(name, arguments, ROLE)
def grade(self, world: ApiReliabilityWorld, task: dict) -> dict:
return world.grade(task["private_task_id"])
def public_grade(self, grade: dict) -> dict:
return {
"score": grade["score"],
"public_components": {
f"artifact_{index}": {
"correct": int(bool(row.get("complete"))),
"total": 1,
}
for index, row in enumerate(grade["targets"], 1)
},
}
def close(self, _world: ApiReliabilityWorld) -> None:
return None