|
| 1 | +"""Frontier-CS entry point for the public structured-LWE evaluator.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import math |
| 7 | +import os |
| 8 | +import stat |
| 9 | +import sys |
| 10 | +from collections.abc import Mapping |
| 11 | +from functools import lru_cache |
| 12 | +from pathlib import Path |
| 13 | +from typing import TypeAlias |
| 14 | + |
| 15 | + |
| 16 | +JsonScalar: TypeAlias = None | bool | int | float | str |
| 17 | +PlainData: TypeAlias = JsonScalar | list["PlainData"] | dict[str, "PlainData"] |
| 18 | + |
| 19 | +try: |
| 20 | + _SOURCE_PUBLIC_DIR = ( |
| 21 | + Path(__file__).resolve().parent / "harbor" / "app" / "public" |
| 22 | + ) |
| 23 | + _INITIAL_CATALOG_OVERRIDE = os.environ.get("FCS_STRUCTURED_LWE_CATALOG") |
| 24 | + _IMPORT_PUBLIC_DIR = Path( |
| 25 | + _SOURCE_PUBLIC_DIR |
| 26 | + if _INITIAL_CATALOG_OVERRIDE is not None |
| 27 | + else os.environ.get("FRONTIER_PUBLIC_DIR", _SOURCE_PUBLIC_DIR) |
| 28 | + ).resolve() |
| 29 | + _IMPORT_PUBLIC_DIR_TEXT = str(_IMPORT_PUBLIC_DIR) |
| 30 | + while _IMPORT_PUBLIC_DIR_TEXT in sys.path: |
| 31 | + sys.path.remove(_IMPORT_PUBLIC_DIR_TEXT) |
| 32 | + sys.path.insert(0, _IMPORT_PUBLIC_DIR_TEXT) |
| 33 | + |
| 34 | + from lwe_challenge.evaluator_core import evaluate_path # noqa: E402 |
| 35 | + from lwe_challenge.schema import MAX_CATALOG_BYTES, Catalog # noqa: E402 |
| 36 | +except Exception: |
| 37 | + if __name__ == "__main__": |
| 38 | + print("infrastructure_error", file=sys.stderr) |
| 39 | + raise SystemExit(1) from None |
| 40 | + raise |
| 41 | + |
| 42 | + |
| 43 | +_SIDECAR_BYTES = len(f"{'0' * 64} catalog.jsonl\n".encode("ascii")) |
| 44 | + |
| 45 | + |
| 46 | +def _catalog_path() -> Path: |
| 47 | + override = os.environ.get("FCS_STRUCTURED_LWE_CATALOG") |
| 48 | + if override is not None: |
| 49 | + return Path(override).resolve() |
| 50 | + public_dir = Path( |
| 51 | + os.environ.get("FRONTIER_PUBLIC_DIR", _SOURCE_PUBLIC_DIR) |
| 52 | + ).resolve() |
| 53 | + return (public_dir / "catalog.jsonl").resolve() |
| 54 | + |
| 55 | + |
| 56 | +def _catalog() -> Catalog: |
| 57 | + path = _catalog_path() |
| 58 | + production = os.environ.get("FCS_STRUCTURED_LWE_CATALOG") is None |
| 59 | + catalog_bytes = _read_regular_bytes(path, max_bytes=MAX_CATALOG_BYTES) |
| 60 | + digest = hashlib.sha256(catalog_bytes).hexdigest() |
| 61 | + if production: |
| 62 | + expected_sidecar = f"{digest} catalog.jsonl\n".encode("ascii") |
| 63 | + try: |
| 64 | + sidecar = _read_regular_bytes( |
| 65 | + path.with_name("catalog.sha256"), max_bytes=_SIDECAR_BYTES |
| 66 | + ) |
| 67 | + except ValueError: |
| 68 | + raise ValueError("catalog.sha256 is not a valid sidecar") from None |
| 69 | + if sidecar != expected_sidecar: |
| 70 | + raise ValueError("catalog.sha256 does not match catalog.jsonl") |
| 71 | + return _load_catalog(str(path), digest, production) |
| 72 | + |
| 73 | + |
| 74 | +def _read_regular_bytes(path: Path, *, max_bytes: int) -> bytes: |
| 75 | + flags = ( |
| 76 | + os.O_RDONLY |
| 77 | + | os.O_NONBLOCK |
| 78 | + | getattr(os, "O_CLOEXEC", 0) |
| 79 | + | getattr(os, "O_NOFOLLOW", 0) |
| 80 | + ) |
| 81 | + fd = os.open(path, flags) |
| 82 | + try: |
| 83 | + if not stat.S_ISREG(os.fstat(fd).st_mode): |
| 84 | + raise ValueError("catalog assets must be regular files") |
| 85 | + data = bytearray() |
| 86 | + limit = max_bytes + 1 |
| 87 | + while len(data) < limit: |
| 88 | + chunk = os.read(fd, min(1024 * 1024, limit - len(data))) |
| 89 | + if not chunk: |
| 90 | + break |
| 91 | + data.extend(chunk) |
| 92 | + finally: |
| 93 | + os.close(fd) |
| 94 | + if len(data) > max_bytes: |
| 95 | + raise ValueError("catalog asset exceeds its byte limit") |
| 96 | + return bytes(data) |
| 97 | + |
| 98 | + |
| 99 | +@lru_cache(maxsize=8) |
| 100 | +def _load_catalog(path: str, digest: str, production: bool) -> Catalog: |
| 101 | + catalog = Catalog.load(path) |
| 102 | + if catalog.catalog_id != digest: |
| 103 | + raise RuntimeError("catalog changed while it was being verified") |
| 104 | + if production and len(catalog.instances) != 200: |
| 105 | + raise ValueError("production catalog must contain exactly 200 instances") |
| 106 | + return catalog |
| 107 | + |
| 108 | + |
| 109 | +def _plain_data(value: object) -> PlainData: |
| 110 | + if isinstance(value, float) and not math.isfinite(value): |
| 111 | + raise TypeError("public metrics require finite float values") |
| 112 | + if value is None or isinstance(value, (bool, int, float, str)): |
| 113 | + return value |
| 114 | + if isinstance(value, Mapping): |
| 115 | + copied: dict[str, PlainData] = {} |
| 116 | + for key, item in value.items(): |
| 117 | + if not isinstance(key, str): |
| 118 | + raise TypeError("public metrics mappings require string keys") |
| 119 | + copied[key] = _plain_data(item) |
| 120 | + return copied |
| 121 | + if isinstance(value, tuple): |
| 122 | + return [_plain_data(item) for item in value] |
| 123 | + raise TypeError("public metrics contain a non-JSON value") |
| 124 | + |
| 125 | + |
| 126 | +def prepare() -> dict[str, object]: |
| 127 | + catalog = _catalog() |
| 128 | + return { |
| 129 | + "instance_count": len(catalog.instances), |
| 130 | + "catalog_id": catalog.catalog_id, |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | +def evaluate(solution_path: str) -> tuple[float, float, str, dict[str, object]]: |
| 135 | + catalog = _catalog() |
| 136 | + result = evaluate_path(solution_path, catalog=catalog) |
| 137 | + metrics = _plain_data(result.metrics) |
| 138 | + if not isinstance(metrics, dict): |
| 139 | + raise TypeError("evaluator metrics must be a mapping") |
| 140 | + return result.score, result.score_unbounded, result.message, metrics |
| 141 | + |
| 142 | + |
| 143 | +def main(argv: list[str]) -> int: |
| 144 | + if len(argv) != 2: |
| 145 | + print("usage: evaluator.py SOLUTION_JSON", file=sys.stderr) |
| 146 | + return 2 |
| 147 | + try: |
| 148 | + score, score_unbounded, message, _metrics = evaluate(argv[1]) |
| 149 | + except Exception: |
| 150 | + print("infrastructure_error", file=sys.stderr) |
| 151 | + return 1 |
| 152 | + print(message, file=sys.stderr) |
| 153 | + print(f"{score:.12f} {score_unbounded:.12f}") |
| 154 | + return 0 |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == "__main__": |
| 158 | + raise SystemExit(main(sys.argv)) |
0 commit comments