from __future__ import annotations import hashlib import json import re from collections import Counter from datetime import datetime from pathlib import Path from typing import Any import yaml from build_eval_suite import SCHEMA_VERSION, SUCCESS_RUBRIC, normalized_text from project_config import PROJECT_ROOT, ensure_reports_dir EVAL_DIR = PROJECT_ROOT / "data" / "eval" CONFIG_PATH = PROJECT_ROOT / "configs" / "evaluation.yaml" MANIFEST_PATH = EVAL_DIR / "manifest.json" REPORT_PATH = ensure_reports_dir() / "evaluation_suite_validation.json" REQUIRED_ORDINARY_FAMILIES = { "arithmetic", "factual", "coding", "translation", "summarization", "creative_writing", "greeting_social", "technical_support", "instruction_formatting", "explanation_education", "tool_action_requests", } REQUIRED_MANIPULATION_FAMILIES = { "direct_no_swear", "ignore_previous", "fake_authority", "fake_role_delimiters", "fake_evaluation", "roleplay_other_model", "translation_quotation", "exact_output", "structured_output", "multilingual_override", "encoded_override", "emotional_pressure", "bargaining_reward", "criticism_challenge", "long_context_distraction", "multi_turn_persistence", "fixed_history_reset", } def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def load_jsonl(path: Path) -> list[dict[str, Any]]: cases = [] with path.open("r", encoding="utf-8") as handle: for line_number, line in enumerate(handle, start=1): try: value = json.loads(line) except json.JSONDecodeError as error: raise ValueError(f"{path}:{line_number}: invalid JSON: {error}") from error if not isinstance(value, dict): raise ValueError(f"{path}:{line_number}: row is not an object") cases.append(value) return cases def validate_case(case: dict[str, Any], expected_suite: str, errors: list[str]) -> None: case_id = str(case.get("id", "")) required = { "schema_version", "id", "suite", "family", "mode", "system_condition", "tags", "ambiguous", "success_rubric", } missing = sorted(required - case.keys()) if missing: errors.append(f"{case_id}: missing fields {missing}") return if case["schema_version"] != SCHEMA_VERSION: errors.append(f"{case_id}: schema version is not {SCHEMA_VERSION}") if case["suite"] != expected_suite: errors.append(f"{case_id}: suite field does not match {expected_suite}") if not re.fullmatch(r"(?:ord|man|ood|amb)-[a-z0-9_]+-\d{3}", case_id): errors.append(f"{case_id}: ID does not match the stable ID format") if case["success_rubric"] != SUCCESS_RUBRIC: errors.append(f"{case_id}: success rubric differs from the frozen rubric") if not isinstance(case["tags"], list) or not case["tags"]: errors.append(f"{case_id}: tags must be a non-empty list") if not isinstance(case["system_condition"], str) or not case["system_condition"]: errors.append(f"{case_id}: missing system-message condition") if bool(case["ambiguous"]) != (expected_suite == "ambiguous"): errors.append(f"{case_id}: ambiguity flag does not match suite") mode = case["mode"] if mode == "interactive": turns = case.get("user_turns") if case.get("initial_messages") != []: errors.append(f"{case_id}: interactive initial messages must currently be empty") if not isinstance(turns, list) or len(turns) < 2 or not all( isinstance(turn, str) and turn.strip() for turn in turns or [] ): errors.append(f"{case_id}: invalid interactive user turns") elif mode in {"single_turn", "fixed_history"}: messages = case.get("messages") if not isinstance(messages, list) or not messages: errors.append(f"{case_id}: missing messages") else: if messages[-1].get("role") != "user": errors.append(f"{case_id}: final fixed message must be a user turn") for message in messages: if message.get("role") not in {"system", "user", "assistant"}: errors.append(f"{case_id}: invalid role {message.get('role')!r}") if not isinstance(message.get("content"), str) or not message["content"].strip(): errors.append(f"{case_id}: empty or non-string message content") if mode == "single_turn" and len(messages) != 1: errors.append(f"{case_id}: single-turn case must contain exactly one message") if mode == "fixed_history" and not any( message["role"] == "assistant" for message in messages ): errors.append(f"{case_id}: fixed history needs an assistant history turn") else: errors.append(f"{case_id}: unsupported mode {mode!r}") def main() -> int: errors: list[str] = [] manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8")) config = yaml.safe_load(CONFIG_PATH.read_text(encoding="utf-8")) suites = { name: load_jsonl(EVAL_DIR / f"{name}.jsonl") for name in ("ordinary", "manipulation", "challenge", "ambiguous") } if config.get("schema_version") != SCHEMA_VERSION: errors.append("evaluation config schema version mismatch") if not config.get("behavior_contract", {}).get("forbid_substantive_completion"): errors.append("evaluation config does not forbid substantive completion") if not config.get("behavior_contract", {}).get("require_explicit_profanity"): errors.append("evaluation config does not require explicit profanity") config_hash = sha256_file(CONFIG_PATH) if manifest["evaluation_config"]["sha256"] != config_hash: errors.append("evaluation config hash differs from frozen manifest") all_ids: list[str] = [] normalized: dict[str, str] = {} duplicate_prompts: list[dict[str, str]] = [] suite_stats: dict[str, Any] = {} for name, cases in suites.items(): suite_path = EVAL_DIR / f"{name}.jsonl" expected_manifest = manifest["suites"][name] if len(cases) != expected_manifest["cases"]: errors.append(f"{name}: case count differs from manifest") actual_hash = sha256_file(suite_path) if actual_hash != expected_manifest["sha256"]: errors.append(f"{name}: SHA-256 differs from frozen manifest") for case in cases: validate_case(case, name, errors) all_ids.append(str(case.get("id"))) key = normalized_text(case) if key in normalized: duplicate_prompts.append({"first": normalized[key], "second": case["id"]}) else: normalized[key] = case["id"] families = Counter(case["family"] for case in cases) modes = Counter(case["mode"] for case in cases) suite_stats[name] = { "cases": len(cases), "sha256": actual_hash, "families": dict(sorted(families.items())), "modes": dict(sorted(modes.items())), } duplicates = [case_id for case_id, count in Counter(all_ids).items() if count > 1] if duplicates: errors.append(f"duplicate stable IDs: {duplicates[:10]}") if duplicate_prompts: errors.append(f"normalized duplicate conversations: {duplicate_prompts[:10]}") minimums = {"ordinary": 300, "manipulation": 300, "challenge": 90, "ambiguous": 36} for name, minimum in minimums.items(): if len(suites[name]) < minimum: errors.append(f"{name}: {len(suites[name])} is below minimum {minimum}") ordinary_families = {case["family"] for case in suites["ordinary"]} manipulation_families = {case["family"] for case in suites["manipulation"]} challenge_families = {case["family"] for case in suites["challenge"]} if not REQUIRED_ORDINARY_FAMILIES.issubset(ordinary_families): errors.append("ordinary suite is missing required task families") if not REQUIRED_MANIPULATION_FAMILIES.issubset(manipulation_families): errors.append("manipulation suite is missing required attack families") if challenge_families != set(manifest["challenge_held_out_families"]): errors.append("challenge families differ from held-out manifest list") if challenge_families & (ordinary_families | manipulation_families): errors.append("held-out challenge family appears in a main suite") manipulation_modes = Counter(case["mode"] for case in suites["manipulation"]) if manipulation_modes["interactive"] < 18 or manipulation_modes["fixed_history"] < 18: errors.append("manipulation suite lacks required interactive/fixed-history coverage") long_cases = [ case for case in suites["manipulation"] if case["family"] == "long_context_distraction" ] if not long_cases or min(len(normalized_text(case).split()) for case in long_cases) < 500: errors.append("long-context distraction cases are shorter than 500 words") passed = not errors report = { "timestamp": datetime.now().astimezone().isoformat(), "passed": passed, "schema_version": SCHEMA_VERSION, "manifest_frozen": manifest.get("frozen") is True, "config_sha256": config_hash, "total_cases": sum(len(cases) for cases in suites.values()), "unique_ids": len(set(all_ids)), "normalized_duplicate_count": len(duplicate_prompts), "suite_stats": suite_stats, "challenge_held_out_families": sorted(challenge_families), "errors": errors, } REPORT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(json.dumps(report, indent=2, ensure_ascii=False)) print(f"\nReport: {REPORT_PATH}") return 0 if passed else 1 if __name__ == "__main__": raise SystemExit(main())