sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
9.65 kB
"""``explicit-preflight`` — hardware/license/config preflight gate.
No later stage runs until preflight exits 0. ``validate-config`` loads the
resource manifest and experiment defaults through the Pydantic models (enforcing
all research invariants) and checks the four ``EXPLICIT_*`` roots are set.
``check-storage`` verifies the roots are real, writable directories that are not
/tmp, the user home, or the repository. ``check-license-approvals`` reports the
approval-gate status. ``snapshot-environments`` records the hardware/python/env
inventory for reproducibility.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from .. import __version__
from ..config import ConfigError, load_config_pair
from ..hashing import canonical_config_hash
from ..logging_setup import get_logger
from ..paths import ROOT_ENV_VARS, is_forbidden_root, missing_roots, repo_root
logger = get_logger("preflight")
# License gates that the resource catalog declares (docs/01_RESOURCE_CATALOG.md §1).
# ADR-0002 removed the gated-manual-access SAM model, so sam3_terms is gone.
REQUIRED_LICENSE_GATES = (
"mmk12_license",
"mmr1_composite_terms",
"bbox_docvqa_license",
"bbox_docvqa_storage",
"baseline_unlicensed_data",
"mathvista_eval_only",
)
def _utc_now() -> str:
return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def _add_common(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--resources",
type=Path,
default=repo_root() / "configs" / "resources.yaml",
)
parser.add_argument(
"--experiment",
type=Path,
default=repo_root() / "configs" / "experiment.yaml",
)
def cmd_validate_config(args: argparse.Namespace) -> int:
require_env = not getattr(args, "no_require_env", False)
try:
resources, experiment = load_config_pair(args.resources, args.experiment)
except (ConfigError, FileNotFoundError) as exc:
print(f"CONFIG VALIDATION FAILED: {exc}", file=sys.stderr)
return 1
if require_env:
missing = missing_roots()
if missing:
print(
f"ENV VALIDATION FAILED: missing required roots: {', '.join(missing)}",
file=sys.stderr,
)
return 1
# Recompute the experiment hash from the raw parsed file so the reported
# value is identical to what scripts/validate_spec.py would see, independent
# of pydantic model defaults.
import yaml # local import: only needed for the hash report
raw_experiment = yaml.safe_load(Path(args.experiment).read_text(encoding="utf-8"))
raw_resources = yaml.safe_load(Path(args.resources).read_text(encoding="utf-8"))
summary = {
"ok": True,
"package_version": __version__,
"repo_commit": _read_git_commit(),
"experiment_canonical_sha256": canonical_config_hash(raw_experiment),
"resources_canonical_sha256": canonical_config_hash(raw_resources),
"models": len(resources.models),
"datasets": len(resources.datasets),
"repositories": len(resources.repositories),
"main_rl_runs": len(experiment.main_rl_runs),
}
print(json.dumps(summary, sort_keys=True))
return 0
def cmd_check_storage(args: argparse.Namespace) -> int:
missing = missing_roots()
if missing:
print(f"STORAGE CHECK FAILED: missing roots: {', '.join(missing)}", file=sys.stderr)
return 1
failures: list[str] = []
report: dict[str, Any] = {}
for name in ROOT_ENV_VARS:
path = Path(os.environ[name]).expanduser()
entry: dict[str, Any] = {"path": str(path)}
if not path.exists():
entry["ok"] = False
entry["error"] = "does not exist"
failures.append(f"{name} ({path}) does not exist")
elif not path.is_dir():
entry["ok"] = False
entry["error"] = "not a directory"
failures.append(f"{name} ({path}) is not a directory")
else:
writable = os.access(path, os.W_OK)
entry["ok"] = writable
entry["writable"] = writable
entry["forbidden_location"] = is_forbidden_root(path)
try:
stat = os.statvfs(path)
entry["free_bytes"] = stat.f_bavail * stat.f_frsize
except OSError:
entry["free_bytes"] = None
if not writable:
failures.append(f"{name} ({path}) is not writable")
if entry["forbidden_location"]:
msg = (
f"{name} ({path}) is /tmp, home, or inside the repo; "
"do not use it as a large output root"
)
if name == "EXPLICIT_RUN_ROOT":
failures.append(msg)
else:
logger.warning(msg)
report[name] = entry
print(json.dumps(report, sort_keys=True))
if failures:
print("STORAGE CHECK FAILED: " + "; ".join(failures), file=sys.stderr)
return 1
return 0
def cmd_check_license_approvals(args: argparse.Namespace) -> int:
approval_path = Path(args.approval)
if not approval_path.exists():
print(f"LICENSE CHECK FAILED: approval file not found: {approval_path}", file=sys.stderr)
return 1
try:
data = json.loads(approval_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
print(f"LICENSE CHECK FAILED: invalid JSON: {exc}", file=sys.stderr)
return 1
if not isinstance(data, dict) or data.get("schema_version") != 1:
print("LICENSE CHECK FAILED: schema_version must be 1", file=sys.stderr)
return 1
gates = data.get("gates")
if not isinstance(gates, dict):
print("LICENSE CHECK FAILED: 'gates' must be an object", file=sys.stderr)
return 1
report: dict[str, Any] = {"approved_at": data.get("approved_at"), "gates": {}}
for gate in REQUIRED_LICENSE_GATES:
entry = gates.get(gate)
if not isinstance(entry, dict):
report["gates"][gate] = {"status": "missing"}
else:
report["gates"][gate] = {
"status": entry.get("status", "missing"),
"evidence": entry.get("evidence"),
}
print(json.dumps(report, sort_keys=True))
return 0
def _run_capture(command: list[str], timeout: float = 30.0) -> str:
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
return result.stdout + result.stderr
except (FileNotFoundError, subprocess.TimeoutExpired) as exc:
return f"<unavailable: {exc}>\n"
def _read_git_commit() -> str:
out = _run_capture(["git", "-C", str(repo_root()), "rev-parse", "HEAD"])
return out.strip().splitlines()[0] if out.strip() else "<unknown>"
def cmd_snapshot_environments(args: argparse.Namespace) -> int:
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
inventory = {
"package_version": __version__,
"captured_at": _utc_now(),
"repo_commit": _read_git_commit(),
"python": _run_capture([sys.executable, "-VV"]),
"platform": platform.platform(),
"uname": _run_capture(["uname", "-a"]),
"nvidia_smi": _run_capture(["nvidia-smi"], timeout=30.0),
"topology": _run_capture(["nvidia-smi", "topo", "-m"], timeout=30.0),
}
if shutil.which("uv"):
inventory["uv"] = _run_capture(["uv", "--version"])
if shutil.which("pip"):
inventory["pip_freeze"] = _run_capture(
[sys.executable, "-m", "pip", "freeze", "--all"], timeout=60.0
)
target = output / "environment.json"
target.write_text(json.dumps(inventory, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps({"ok": True, "output": str(target)}, sort_keys=True))
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="explicit-preflight")
parser.add_argument("--version", action="version", version=f"explicit-preflight {__version__}")
sub = parser.add_subparsers(dest="command", required=True)
p_validate = sub.add_parser(
"validate-config", help="Load + validate resources and experiment configs."
)
_add_common(p_validate)
p_validate.add_argument(
"--no-require-env",
action="store_true",
help="Skip the EXPLICIT_* environment-root check (for offline config checks).",
)
p_validate.set_defaults(func=cmd_validate_config)
p_storage = sub.add_parser(
"check-storage", help="Verify EXPLICIT_* roots exist and are writable."
)
p_storage.set_defaults(func=cmd_check_storage)
p_license = sub.add_parser("check-license-approvals", help="Report approval-gate status.")
p_license.add_argument("--approval", type=Path, required=True)
p_license.set_defaults(func=cmd_check_license_approvals)
p_snap = sub.add_parser("snapshot-environments", help="Record hardware/python/env inventory.")
p_snap.add_argument("--output", type=Path, required=True)
p_snap.set_defaults(func=cmd_snapshot_environments)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
return int(args.func(args))
if __name__ == "__main__":
raise SystemExit(main())