GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — FrontierCS-2/scripts/validate_task_layout.py at main · FrontierCS/FrontierCS-2 Expand file tree/ Copy pathvalidate_task_layout.pyMore file actions 2076 lines (1958 loc) · 82.8 KB / Copy pathvalidate_task_layout.pyFile metadata and controls2076 lines (1958 loc) · 82.8 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #!/usr/bin/env python3 """Validate Preview's public task sources and their complete source inventories. This check uses the bundled policies, Dockerfiles and locks. It needs neither FrontierSmith's private pipeline nor image/registry/cloud credentials. """ from __future__ import annotations import argparse import ast import copy import hashlib import importlib.util import json import math import re import shlex import subprocess import sys import tomllib from pathlib import Path import image_namespace import task_layers import task_manifest from native_datasets import check_tar_dataset, dataset_hashes, dataset_path DEFAULT_PROBLEMS_ROOT = Path(__file__).resolve().parents[1] / "tasks/problems" # Reviewed public-copy exceptions, keyed by (task, image role). None are needed # by the current catalog; the mechanism stays for imported tasks. PUBLIC_COPY_REVIEWS: dict[tuple[str, str], Path] = {} FEEDBACK_STATEMENT_REVIEWS = { "ckks_composable_noise": ( Path(__file__).resolve().parent / "reference/ckks-feedback-statement-reviewed-v1.json" ), } # Every workload measures and gates every declared metric. These tasks still declare # workloads that carry only part of the metric set and are reported as # warnings until their own fixes land. Any other such task fails, and an entry # must be removed once its task complies. NONUNIFORM_WORKLOAD_METRICS_EXEMPT: dict[str, str] = {} class LayoutFailure(ValueError): pass def warn(root: Path, message: str) -> None: print(f"WARN {root.name}: {message}", file=sys.stderr) def require(condition: bool, message: str) -> None: if not condition: raise LayoutFailure(message) def regular(path: Path) -> Path: require(path.is_file() and not path.is_symlink(), f"missing regular file: {path}") return path def relative_path(value: object) -> str: require( isinstance(value, str) and bool(value) and not value.startswith("/") and all(part not in {"", ".", ".."} for part in value.split("/")), f"unsafe source or payload path: {value!r}", ) return value def document(path: Path) -> dict: def unique(pairs): result = {} for key, value in pairs: require(key not in result, f"duplicate JSON key in {path}: {key}") result[key] = value return result try: value = json.loads(regular(path).read_text(), object_pairs_hook=unique) except (OSError, UnicodeError, json.JSONDecodeError) as error: raise LayoutFailure(f"invalid JSON document: {path}") from error require(isinstance(value, dict), f"JSON object required: {path}") return value def digest(path: Path) -> str: with regular(path).open("rb") as stream: return "sha256:" + hashlib.file_digest(stream, "sha256").hexdigest() def copy_source(root: Path, value: str, role: str = "") -> str: if task_manifest.is_native(root) and value.startswith( task_manifest.GENERATED + "/" ): return ( value # written by the build from task.toml (task_manifest.generated_files) ) # Docker accepts a directory's trailing slash. Do not normalize traversal, # repeated slashes, symlinks, or a slash appended to a regular file. trailing = value.endswith("/") source = relative_path(value[:-1] if trailing else value) path = root for component in source.split("/"): path = path / component require(not path.is_symlink(), f"symlink COPY source: {source}") label = f"{role} " if role else "" require(path.is_file() or path.is_dir(), f"missing {label}COPY source: {source}") require( not trailing or path.is_dir(), f"COPY trailing slash needs directory: {source}" ) return source def check_reviewed_public_copies(root: Path, role: str, sources: set[str]) -> None: """Bind exceptional public inputs to a reviewed recipe and complete bytes. This is an Agent visibility review, not a generic runtime-context allowlist or an assertion of image publication rights. The full task inventory is still independently checked by validate_task. """ review_path = PUBLIC_COPY_REVIEWS.get((root.name, role)) require( review_path is not None, f"non-public Agent COPY sources: {sorted(sources)}" ) review = document(review_path) require( review.get("schema") == "preview.reviewed-public-copies/v1" and review.get("problem_id") == root.name and review.get("role") == role, "public COPY review identity mismatch", ) bindings = review.get("bindings", {}) require( set(bindings) == {"upstream.lock.json", "policy.json", f"{role}/Dockerfile"}, "public COPY review needs lock, policy and recipe bindings", ) for name, expected in bindings.items(): require( digest(root / name) == expected, f"public COPY binding mismatch: {name}" ) copies = review.get("copies", {}) require(set(copies) == sources, "unreviewed public COPY source set") observed_files, observed_directories = set(), set() for source, kind in copies.items(): path = root / copy_source(root, source) require(kind in {"file", "directory"}, "invalid reviewed COPY kind") require( path.is_dir() == (kind == "directory"), f"public COPY kind mismatch: {source}", ) members = [path, *path.rglob("*")] if path.is_dir() else [path] for member in members: require( not member.is_symlink() and (member.is_file() or member.is_dir()), f"non-regular public COPY member: {member}", ) target = observed_files if member.is_file() else observed_directories target.add(member.relative_to(root).as_posix()) records = review.get("files", {}) require(set(records) == observed_files, "public COPY file inventory mismatch") require( set(review.get("directories", [])) == observed_directories, "public COPY directory inventory mismatch", ) for name, record in records.items(): path = root / relative_path(name) require( path.stat().st_size == record.get("bytes") # Match Git/source-identity executable semantics, not the author's # umask (0664 and a fresh checkout's 0644 describe the same source). and bool(path.stat().st_mode & 0o111) == record.get("executable") and digest(path) == record.get("sha256"), f"reviewed public COPY bytes or executable bit mismatch: {name}", ) def check_dockerfile(root: Path, role: str) -> None: paths = task_manifest.layout(root) if paths.native: check_native_dockerfile(root, role) return recipe = regular(root / role / "Dockerfile").read_text() if role == "agent-base": require( "agent-base/frontier/task" in recipe, "Agent must copy its native public task tree", ) exceptional = set() for line in recipe.splitlines(): if not line.startswith("COPY "): continue fields = shlex.split(line)[1:] if any(field.startswith("--from=") for field in fields): continue fields = [field for field in fields if not field.startswith("--")] require(len(fields) == 2, f"use one task-root source per COPY in {role}") source = copy_source(root, fields[0], role) if role.startswith("agent"): public = ( source == "agent-base/frontier/task" or source.startswith("agent-base/frontier/task/") or source == "agent-gpu/task_runtime.py" ) if not public: exceptional.add(source) if exceptional: check_reviewed_public_copies(root, role, exceptional) NATIVE_BASE_ROLE = {"agent-base": "agent", "verifier": "verifier"} NATIVE_AGENT_SOURCES = ("README.md", "repo", "starter", "bin") NATIVE_GENERATED_AGENT = f"{task_manifest.GENERATED}/agent/" # COPY --from=<registry>/<repository>@sha256:<64 hex>: task-private judge data or toolchains, # pinned by digest; Verifier recipes only. PINNED_COPY_ROLES = frozenset({"verifier", "verifier-gpu"}) PINNED_IMAGE = re.compile( r"(?:[a-z0-9-]+\.)+[a-z0-9-]+(?::[0-9]+)?(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+" r"@sha256:[0-9a-f]{64}" ) def check_no_platform_numbers(root: Path) -> None: """A task.toml task's statement and own README never restate platform numbers: the generated /frontier/task/README.md states them from task.toml, so a copy elsewhere could only drift.""" task = task_manifest.read_task(root) quota, submission = task["quota"], task["submission"] def forms(value: int) -> str: return rf"(?:{value}|{value:,})" patterns = { "answering window": rf"\b{forms(quota['wall_time_seconds'])}\s*(?:-\s*)?s(?:ec(?:ond)?s?)?\b", "train calls": rf"\b{quota['max_train_calls']}\s+(?:accepted\s+)?train\s+calls?\b", "train wall time": rf"\b{forms(quota['max_train_wall_seconds'])}\s*(?:-\s*)?s(?:ec(?:ond)?s?)?\b", "evaluation timeout": rf"\b{forms(quota['eval_timeout_seconds'])}\s*(?:-\s*)?s(?:ec(?:ond)?s?)?\b", "submission size": rf"\b{forms(submission['max_bytes'])}\s*(?:-\s*)?bytes?\b", } for name in ("README.md", "repo/README.md"): path = root / name if not path.is_file(): continue text = path.read_text(encoding="utf-8") for what, pattern in patterns.items(): match = re.search(pattern, text, re.IGNORECASE) require( match is None, f"{name} restates the {what} ({match.group(0) if match else ''}); the generated " "/frontier/task/README.md states platform numbers, so refer to it instead", ) # The statement template (repo/README.md of a task.toml task): one title, then these sections. STATEMENT_SECTIONS = ( "Task", "What you may change", "Interface", "Correctness", "Workload", "Scoring", ) STATEMENT_OPTIONAL_SECTIONS = ("Running locally", "Environment", "Notes") STATEMENT_MAX_WORDS = 1600 STATEMENT_WARN_WORDS = 1200 # The shared generated README states the objective and scoring rules; a task README never does. TASK_README_FORBIDDEN_SECTION = re.compile(r"scor|objective|priorit", re.IGNORECASE) def _markdown_headings(text: str) -> list[tuple[int, str]]: """(level, title) of every ATX heading outside fenced code blocks.""" headings, fence = [], None for line in text.splitlines(): stripped = line.lstrip() if stripped.startswith(("```", "~~~")): marker = stripped[:3] fence = None if fence == marker else (fence or marker) continue if fence is None: match = re.match(r"(#{1,6})\s+(.*?)\s*#*\s*$", line) if match: headings.append((len(match.group(1)), match.group(2))) return headings def check_statement_structure(root: Path) -> None: """A task.toml task's statement follows the statement template: exactly one title, the required sections in order, then only the optional ones in order; at most STATEMENT_MAX_WORDS words. Its task README has no scoring, objective or priority section.""" paths = task_manifest.layout(root) text = regular(paths.repo / "README.md").read_text(encoding="utf-8") headings = _markdown_headings(text) require( sum(1 for level, _ in headings if level == 1) == 1, "repo/README.md must have exactly one '# ' title", ) sections = [title for level, title in headings if level == 2] required = list(STATEMENT_SECTIONS) extra = sections[len(required) :] optional = [name for name in STATEMENT_OPTIONAL_SECTIONS if name in extra] require( sections[: len(required)] == required and extra == optional, "repo/README.md sections must be, in order: " + ", ".join(required) + ", then optionally " + ", ".join(STATEMENT_OPTIONAL_SECTIONS) + f"; found {sections}", ) scoring = text.split("\n## Scoring", 1)[1].split("\n## ", 1)[0] require( re.search(r"(?:^|\n\s*\n)\*\*Beats the reference\*\*", scoring) is not None, "repo/README.md's Scoring section needs a paragraph starting with " "'**Beats the reference**' (the generated README's Objective points to it)", ) words = len(text.split()) require( words <= STATEMENT_MAX_WORDS, f"repo/README.md has {words} words; the limit is {STATEMENT_MAX_WORDS}", ) if words > STATEMENT_WARN_WORDS: warn( root, f"repo/README.md has {words} words (target at most {STATEMENT_WARN_WORDS})", ) own = regular(root / "README.md").read_text(encoding="utf-8") for _, title in _markdown_headings(own): require( TASK_README_FORBIDDEN_SECTION.search(title) is None, f"README.md has a {title!r} section; scoring and the objective are stated by " "the statement and the generated README", ) def base_argument(name: str) -> str: return "${" + name + "}" ROLE_ARGUMENT = { role: name for name, role in task_manifest.SHARED_BASE_ARGUMENTS.items() } def check_shared_base_arguments(path: Path, recipe: str) -> dict[str, str]: """A recipe names the shared bases only by build argument (`ARG VERIFIER_BASE`, then `FROM ${VERIFIER_BASE}`); the build injects tasks/shared/bases.json. Returns stage alias -> shared role for the `FROM ${...} AS <stage>` stages.""" code = "\n".join( line for line in recipe.splitlines() if not line.lstrip().startswith("#") ) literal = SHARED_IMAGE_REFERENCE.search(code) require( literal is None, f"{path.name} names {literal.group(0) if literal else ''} by reference; take a shared " "base by build argument (ARG AGENT_BASE / VERIFIER_BASE / GPU_TOOLS, then " "FROM ${NAME}), which the build injects from tasks/shared/bases.json", ) lines = code.splitlines() first = next( (i for i, line in enumerate(lines) if line.startswith("FROM ")), len(lines) ) declared = { line.split()[1] for line in lines[:first] if line.startswith("ARG ") and len(line.split()) == 2 } stages = {} for line in lines: if not line.startswith("FROM "): continue words = line.split() name = next( ( n for n in task_manifest.SHARED_BASE_ARGUMENTS if words[1] == base_argument(n) ), None, ) if name is None: continue require( name in declared, f"{path.name} uses ${{{name}}} without a global `ARG {name}` (no default) " "before its first FROM", ) if len(words) == 4 and words[2] == "AS": stages[words[3]] = task_manifest.SHARED_BASE_ARGUMENTS[name] return stages def check_native_dockerfile(root: Path, role: str) -> None: """A task.toml task's recipe takes the shared bases by build argument (its final stage FROM its role's base) and the Agent image copies only the statement, the starter repo and generated Agent files.""" path = task_manifest.layout(root).dockerfile(role) recipe = regular(path).read_text() task_manifest.read_task(root) froms = [ line.split()[1] for line in recipe.splitlines() if line.startswith("FROM ") ] require(bool(froms), f"{path.name} has no FROM") shared_stages = check_shared_base_arguments(path, recipe) shared = {base_argument(name) for name in task_manifest.SHARED_BASE_ARGUMENTS} if role in NATIVE_BASE_ROLE: expected = base_argument(ROLE_ARGUMENT[NATIVE_BASE_ROLE[role]]) # The image is the last stage; earlier stages only name other shared bases. require( froms[-1] == expected, f"{path.name} must build its final stage FROM {expected}", ) require( all(ref in shared for ref in froms[:-1]), f"{path.name}: an earlier stage may only be FROM a shared base build argument", ) # The other stages a task.toml recipe may copy from: the shared gpu-tools stage, and for a # Verifier recipe the shared verifier base stage (the shared verifier modules). allowed_roles = {"gpu-tools"} | ( {"verifier"} if role.startswith("verifier") else set() ) tools_stages = { stage for stage, base in shared_stages.items() if base in allowed_roles } own_stages = { line.split()[3] for line in recipe.splitlines() if line.startswith("FROM ") and len(line.split()) == 4 and line.split()[2] == "AS" } for line in recipe.splitlines(): if not line.startswith("COPY "): continue stage = next( ( f.removeprefix("--from=") for f in shlex.split(line) if f.startswith("--from=") ), None, ) if stage is not None: # A Verifier recipe may also copy task-private judge data or toolchains from an # image named by full repository and digest (never a tag); an Agent recipe never. # An Agent GPU recipe may carry over public Agent-side data from the task's own # published Agent images (never a Verifier image), pinned by digest. own_agent = re.compile( re.escape(image_namespace.repository(f"fcs2-task-{root.name}")) + r"-agent(?:-gpu)?@sha256:[0-9a-f]{64}" ) # A service or test-sandbox recipe (judge-side only) may also copy from its own # earlier stages. require( stage in tools_stages or (role.startswith("sidecar-") and stage in own_stages) or ( (role in PINNED_COPY_ROLES or role.startswith("sidecar-")) and PINNED_IMAGE.fullmatch(stage) is not None ) or (role == "agent-gpu" and own_agent.fullmatch(stage) is not None), f"{path.name} copies from {stage!r}; only a shared base stage " "(FROM ${GPU_TOOLS}" + ("" if role.startswith("agent") else " or ${VERIFIER_BASE}") + " AS <stage>) is allowed" + ( "" if role.startswith("agent") else ", or a <registry>/<repository>@sha256:<digest> image" ), ) continue fields = [f for f in shlex.split(line)[1:] if not f.startswith("--")] require(len(fields) == 2, f"use one task-root source per COPY in {path.name}") source = copy_source(root, fields[0], role) if role.startswith("agent"): require( source.split("/")[0] in NATIVE_AGENT_SOURCES or source.startswith(NATIVE_GENERATED_AGENT) or (role == "agent-gpu" and source == "gpu/task_runtime.py"), f"Agent image copies a non-public source: {source}", ) # A reference to one of the shared images in a recipe (FROM, COPY --from), with tag and digest. SHARED_IMAGE_REFERENCE = re.compile( r"\S*/frontier-(?:agent-base|verifier-base|gpu-tools)(?:[:@]\S*)?" ) def check_gpu_adapter_pins(root: Path) -> None: """A task.toml that sets `[gpu.verifier] lease_seconds`, or declares a command test sandbox, needs the shared verifier and adapter that implement them (an older fcs2_verifier.py does not know the control placement and silently ships the whole verification to one runner, or drops the Driver bearer run_sandboxes() leases machines with): its control Verifier takes the adapter from a `${GPU_TOOLS}` stage and, for a Verifier-GPU task, its GPU Verifier the verifier modules from a `${VERIFIER_BASE}` stage, both the tasks/shared/bases.json releases. The same holds for GPU runners and CPU machines: the judge runs on the control image.""" raw = tomllib.loads((root / task_manifest.MANIFEST).read_text(encoding="utf-8")) settings = raw.get("gpu", {}).get("verifier", {}) uses = [] if "lease_seconds" in settings: uses.append("[gpu.verifier] lease_seconds") if task_manifest.command_sandboxes(raw): uses.append('[test_sandboxes] access = "command"') if not uses: return feature = " and ".join(uses) roles = (("verifier", "GPU_TOOLS"),) + ( (("verifier-gpu", "VERIFIER_BASE"),) if "verifier" in raw.get("gpu", {}) else () ) for role, name in roles: path = task_manifest.layout(root).dockerfile(role) stages = check_shared_base_arguments(path, regular(path).read_text()) require( task_manifest.SHARED_BASE_ARGUMENTS[name] in stages.values(), f"{path.name} needs a `FROM ${{{name}}} AS <stage>` stage: task.toml sets " f"{feature}, which the tasks/shared/bases.json shared verifier and GPU adapter " "implement", ) def check_bases() -> None: """tasks/shared/bases.json: each role's tag is derived from its sources (src-<tree hash>, scripts/build_base_images.py), pinned by digest; a source change without a new release, or a hand-picked tag, fails here.""" import build_base_images recorded = task_manifest.bases() require( set(recorded) == {*task_manifest.BASE_ROLES, "schema_version"}, "tasks/shared/bases.json must name exactly agent, verifier and gpu-tools", ) for role in task_manifest.BASE_ROLES: tag = build_base_images.source_tag(role) expected = ( rf"docker\.io/[a-z0-9_-]+/{re.escape(build_base_images.IMAGE_NAMES[role])}:" rf"{re.escape(tag)}@sha256:[0-9a-f]{{64}}" ) require( re.fullmatch(expected, recorded[role]) is not None, f"tasks/shared/bases.json {role} is {recorded[role]}, but its sources are {tag}: " f"build and push the release (scripts/build_base_images.py --roles {role} --push)", ) def check_inventory(root: Path) -> None: lock_path = root / "upstream.lock.json" lock = document(lock_path) require(lock.get("problem_id") == root.name, "source lock problem_id mismatch") records = lock.get("files") require( isinstance(records, list) and lock.get("file_count") == len(records), "source lock needs an exact file inventory", ) observed = {} for path in root.rglob("*"): relative = path.relative_to(root) require( not {"__pycache__", ".pytest_cache"}.intersection(relative.parts) and path.suffix not in {".pyc", ".pyo"}, f"generated Python cache is not task source: {relative}", ) require( not path.is_symlink() and (path.is_file() or path.is_dir()), f"source must contain regular files and directories: {path}", ) if path.is_file() and path != lock_path: observed[path.relative_to(root).as_posix()] = path seen = set() for record in records: require(isinstance(record, dict), "source lock record must be an object") name = relative_path(record.get("path")) require( name not in seen and name in observed, f"unexpected or duplicate source lock member: {name}", ) seen.add(name) path = observed[name] require( record.get("bytes") == path.stat().st_size and record.get("sha256") == digest(path), f"source lock mismatch: {name}", ) require(seen == set(observed), "source lock does not cover the complete task tree") def check_feedback_statement(root: Path, statement: str, visible: list[str]) -> None: for name in ( "beat_spec_progress", "passed", "failed", "total", "pass_percent", "fail_percent", ): require( name in statement, f"public statement does not describe beat-spec feedback {name}", ) missing = [name for name in visible if name not in statement] if not missing: return review_path = FEEDBACK_STATEMENT_REVIEWS.get(root.name) require( review_path is not None, f"public statement does not describe beat-spec feedback {missing}", ) review = document(review_path) require( review.get("schema") == "preview.reviewed-feedback-statement/v1" and review.get("problem_id") == root.name, "feedback statement review identity mismatch", ) bindings = review.get("bindings", {}) require( set(bindings) == { "upstream.lock.json", "policy.json", "judge/beat_spec.json", "agent-base/frontier/task/README.md", "agent-base/frontier/task/repo/README.md", }, "feedback statement review needs exact source bindings", ) for name, expected in bindings.items(): require( digest(root / name) == expected, f"feedback statement binding mismatch: {name}", ) descriptions = review.get("fields", {}) require(set(descriptions) == set(visible), "unreviewed feedback field set") sentence = review.get("sentence") require( isinstance(sentence, str) and bool(sentence) and sentence in statement and all( isinstance(text, str) and bool(text) and text in sentence for text in descriptions.values() ), "public statement omits reviewed absolute development summaries", ) def _nonempty(value: object) -> bool: return isinstance(value, str) and bool(value.strip()) def _finite_number(value: object) -> bool: if isinstance(value, bool) or not isinstance(value, (int, float)): return False try: return math.isfinite(float(value)) except (OverflowError, ValueError): return False def check_beat_spec_schema(spec: dict, evaluation: dict) -> tuple[list[str], list[str]]: """Check the portable schema used by FrontierSmith's beat-spec design pass. Absence is deliberately an error for Preview releases. The private pipeline tolerates historical tasks without a spec; a newly published layout cannot. """ for field in ("unit", "beats_reference", "statement_sentences"): require(_nonempty(spec.get(field)), f"beat_spec.json needs non-empty {field}") names_by_field = {} for field in ("metrics", "solver_feedback"): entries = spec.get(field) require(isinstance(entries, list), f"beat_spec.json {field} must be a list") require( field != "metrics" or bool(entries), "beat_spec.json must name at least one metric", ) names = [] for entry in entries: require( isinstance(entry, dict), f"beat_spec.json {field} entries must be objects", ) name = entry.get("name") require( isinstance(name, str) and re.fullmatch(r"[a-z0-9]+(?:_[a-z0-9]+)*", name) is not None and name not in names, f"beat_spec.json {field} has an invalid or duplicate metric name", ) names.append(name) require(_nonempty(entry.get("means")), f"beat_spec.json {name} needs means") if field == "metrics": for key in ("source", "clears_when", "tolerance"): require( _nonempty(entry.get(key)), f"beat_spec.json {name} needs {key}" ) require( entry.get("better") in {"higher", "lower"}, f"beat_spec.json {name} has invalid better direction", ) else: answer = entry.get("reveals_reference") require( _nonempty(answer) and re.match(r"no\b\W+\S", answer.strip(), re.IGNORECASE) is not None, f"beat_spec.json {name} needs a no-with-reason privacy explanation", ) require( "reference" not in name and "margin" not in name and not name.startswith("beats") and name not in {"beat_spec_workload_passes", "beat_spec_progress"}, f"beat_spec.json solver_feedback names a private or reserved field: {name}", ) names_by_field[field] = names withheld = spec.get("withheld") require( isinstance(withheld, list) and all(_nonempty(name) for name in withheld) and len(set(withheld)) == len(withheld), "beat_spec.json withheld must be unique non-empty strings", ) visible = names_by_field["solver_feedback"] require( not set(visible).intersection(withheld), "beat_spec.json exposes a withheld field", ) declared = evaluation.get("solver_visible_metrics") require( isinstance(declared, list) and all(isinstance(name, str) for name in declared) and len(set(declared)) == len(declared) and set(declared) == set(visible), "policy solver_visible_metrics must exactly match beat_spec.json solver_feedback", ) if "beats_reference_aggregation" in spec: aggregation = spec["beats_reference_aggregation"] require( isinstance(aggregation, dict), "beat_spec.json aggregation must be an object when declared", ) kind = aggregation.get("kind") if kind == "conjunction": require( set(aggregation) == {"kind"}, "conjunction aggregation contains unknown fields", ) else: require( kind == "score_majority_coverage", "unsupported beats_reference aggregation kind", ) fields = { "kind", "minimum_score_margin", "minimum_comparison_pass_fraction_exclusive", "require_each_workload", "require_each_metric", } require( set(aggregation) == fields, "score_majority_coverage aggregation requires exactly its declared fields", ) margin = aggregation["minimum_score_margin"] fraction = aggregation["minimum_comparison_pass_fraction_exclusive"] require( _finite_number(margin) and margin >= 0, "aggregation minimum_score_margin must be finite and non-negative", ) require( _finite_number(fraction) and 0 <= fraction < 1, "aggregation pass fraction must be finite and in [0, 1)", ) require( all( type(aggregation[key]) is bool for key in ("require_each_workload", "require_each_metric") ), "aggregation coverage flags must be boolean", ) return names_by_field["metrics"], visible def declared_workload_metrics(spec: dict, names: list[str]) -> dict[str, set[str]]: """Map each workload row or group the beat spec declares to its metrics. Rows are listed under any top-level key ending in "workloads". A row carries its own "metrics" when given, else the spec's matching "<prefix>metrics" list (for example final_only_workloads with final_only_metrics), else every declared metric. """ declared = {} groups = spec.get("workload_groups") if groups is not None: require(isinstance(groups, dict) and bool(groups), "invalid workload groups") for group, record in groups.items(): require( isinstance(record, dict) and isinstance(record.get("metrics"), list), "invalid workload group metrics", ) declared[f"workload_groups.{group}"] = set(record["metrics"]) for key, rows in spec.items(): if not key.endswith("workloads"): continue require(isinstance(rows, list), f"beat_spec.json {key} must be a list") prefix = key[: -len("workloads")] shared = spec.get(f"{prefix}metrics") if prefix else None for index, row in enumerate(rows): if isinstance(row, str): row = {"name": row} require( isinstance(row, dict) and _nonempty(row.get("name")), f"beat_spec.json {key}[{index}] needs a workload name", ) carried = row.get("metrics", shared) if carried is None: carried = names require( isinstance(carried, (list, dict)) and all(isinstance(name, str) for name in carried), f"beat_spec.json {key}[{index}] has invalid metrics", ) declared[f"{key}[{row['name']}]"] = set(carried) return declared def check_uniform_workload_metrics(root: Path, spec: dict, names: list[str]) -> None: """Every workload the beat spec declares measures every declared metric.""" expected = set(names) problems = [] if "workload_groups" in spec: problems.append("workload_groups is retired") for row, carried in declared_workload_metrics(spec, names).items(): if carried != expected: detail = [] if expected - carried: detail.append(f"lacks {sorted(expected - carried)}") if carried - expected: detail.append(f"names undeclared {sorted(carried - expected)}") problems.append(f"{row} {' and '.join(detail)}") exemption = NONUNIFORM_WORKLOAD_METRICS_EXEMPT.get(root.name) if not problems: require( exemption is None, f"remove the stale exemption for {root.name}: " "every declared workload now measures every metric", ) return shown = "; ".join(problems[:3]) if len(problems) > 3: shown += f"; and {len(problems) - 3} more" message = f"every workload must measure every declared metric: {shown}" require(exemption is not None, message) warn(root, f"{message} (exempt: {exemption})") def check_beat_spec_feedback( root: Path, spec: dict, names: list[str], visible: list[str] ) -> None: """Exercise the shipped, dependency-free feedback boundary without a workload. Compile in memory to keep validation from adding __pycache__ to a locked source tree. This does not import or execute the private evaluator. """ helper = regular(task_manifest.layout(root).beat_spec_helper) namespace = {"__name__": "preview_feedback_check", "__file__": str(helper)} try: exec(compile(helper.read_text(), str(helper), "exec"), namespace) public_metrics = namespace["public_metrics"] values = {name: [1.0, 2.0] for name in visible} values.update( { "beat_spec_workload_passes": [ { "workload": f"private-layout-probe-{index}", "metrics": {name: True for name in names}, } for index in range(2) ], "beats_reference": 1, "reference_score": 50.0, "margin": spec.get("beats_reference_aggregation", {}).get( "minimum_score_margin", 0.0 ), } ) kwargs = { "beat_spec_path": root / "judge/beat_spec.json", "configured_visible": visible, } totals = {name: 2 for name in names} groups = spec.get("workload_groups") if groups is not None: # Retired layout, probed only for an exempt task whose shipped # helper still requires grouped rows. require( root.name in NONUNIFORM_WORKLOAD_METRICS_EXEMPT, "beat_spec.json workload_groups is retired: every workload " "must measure every declared metric", ) require( isinstance(groups, dict) and bool(groups), "invalid workload groups" ) rows = [] totals = {} for group_name, group in groups.items(): require(isinstance(group, dict), "invalid workload group") counts = group.get("counts") require(isinstance(counts, dict), "invalid workload group counts") count = counts.get("train") metrics = group.get("metrics") require( type(count) is int and 0 < count <= 100000, "invalid or excessive grouped feedback probe count", ) require( isinstance(metrics, list) and bool(metrics), "invalid workload group metrics", ) require( len(rows) + count <= 100000, "grouped feedback probe exceeds bounded layout budget", ) for name in metrics: require( name in names and name not in totals, "workload groups must partition declared metrics", ) totals[name] = count first = len(rows) rows.extend( { "workload": f"private-layout-probe-{first + index}", "group": group_name, "metrics": {name: True for name in metrics}, } for index in range(count) ) require(set(totals) == set(names), "workload groups omit metrics") values["beat_spec_workload_passes"] = rows values["beat_spec_suite_role"] = "train" actual = public_metrics(values, **kwargs) expected = {name: values[name] for name in visible} expected["beat_spec_progress"] = { name: { "passed": totals[name], "failed": 0, "total": totals[name], "pass_percent": 100.0, "fail_percent": 0.0, } for name in names } require( actual == expected, "beat-spec helper exposes private fields or returns incorrect progress", ) invalid_payloads = [] inconsistent = copy.deepcopy(values) inconsistent["beats_reference"] = 0 invalid_payloads.append((inconsistent, "inconsistent beats_reference")) duplicate = copy.deepcopy(values) duplicate["beat_spec_workload_passes"].append( copy.deepcopy(duplicate["beat_spec_workload_passes"][0]) ) invalid_payloads.append((duplicate, "duplicate workload")) wrong_metric = copy.deepcopy(values) wrong_metric["beat_spec_workload_passes"][0]["metrics"][ "undeclared_probe_metric" ] = True invalid_payloads.append((wrong_metric, "undeclared row metric")) if root.name not in NONUNIFORM_WORKLOAD_METRICS_EXEMPT: partial = copy.deepcopy(values) partial["beat_spec_workload_passes"][0]["metrics"].pop(names[0]) invalid_payloads.append((partial, "workload row missing a declared metric")) if visible: identity = copy.deepcopy(values) identity[visible[0]] = {"nested": [{"private-layout-probe-0": 1.0}]} invalid_payloads.append( (identity, "private workload identity in visible metrics") ) if groups is not None: missing_role = copy.deepcopy(values) missing_role.pop("beat_spec_suite_role") invalid_payloads.append((missing_role, "missing grouped suite role")) missing_row = copy.deepcopy(values) missing_row["beat_spec_workload_passes"].pop() invalid_payloads.append((missing_row, "missing grouped workload")) wrong_group = copy.deepcopy(values) wrong_group["beat_spec_workload_passes"][0]["group"] = "undeclared-group" invalid_payloads.append((wrong_group, "unknown workload group")) for payload, reason in invalid_payloads: try: public_metrics(payload, **kwargs) except ValueError: continue |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |