Datasets:
File size: 9,646 Bytes
e1ced61 | 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 | """``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())
|