diff --git a/agents/conductors/profiling/AGENTS.md b/agents/conductors/profiling/AGENTS.md index cf2cd2f5..d49a6bec 100644 --- a/agents/conductors/profiling/AGENTS.md +++ b/agents/conductors/profiling/AGENTS.md @@ -88,8 +88,23 @@ as malformed — only a record missing *some* of its key fields is corruption. - **Profiling records and flags; it never adjudicates library correctness** — that is autolens_workspace_test's remit. Triage classifies and routes; it never plans a library debug inside the profiling repo. -- Stdlib-only: the workspace's grid and tables are read via `ast` literal - parsing, never imported (importing would drag the JAX stack into the Brain). +- Stdlib-only: source routes and the runtime grid come from the project's versioned + `catalogue/script_routes.json`, or `dashboard/catalogue.json`'s v2 `script_routes` + extension. Local source declarations take precedence over a published copy. + Scientific modules are never imported. The routing SHA-256 identifies the bytes + read, not the measured software revision or evidence freshness. +- Pre-migration projects explicitly fall back to the legacy sweep `CELLS` AST. + Malformed/unknown new catalogues fail closed; absent/unreadable grids report + unknown coverage, never an empty successful campaign. Existing VRAM tables and + pre-migration compile transform declarations retain their literal AST readers. +- Source routing and result identity are separate: `rectangular` source folders + retain legacy `pixelization` output IDs. Runtime and compile coverage remain + separate; archived presence is unreviewed coverage, not an accepted baseline. + Missing settings and baseline acceptance stay unknown. No temporal chart is added. +- The catalogue exposes compile transforms and builder availability. A declared + unavailable/unknown compile builder emits no compile dispatch commands. Missing + local canonical sources also suppress dispatch until the project is synchronized. + Legacy checkouts retain the old decision surface, with explicit fallback status. ## Boundaries diff --git a/agents/conductors/profiling/_catalogue.py b/agents/conductors/profiling/_catalogue.py new file mode 100644 index 00000000..36315592 --- /dev/null +++ b/agents/conductors/profiling/_catalogue.py @@ -0,0 +1,121 @@ +"""Read project-owned source routing without importing scientific modules.""" + +from __future__ import annotations + +import hashlib +import json +import re +from pathlib import Path, PurePosixPath + +_TOKEN = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_-]*\Z") + + +def _token(value): + if not isinstance(value, str) or not _TOKEN.fullmatch(value): + raise ValueError(f"Invalid profiling identity: {value!r}") + return value + + +def _path(value): + if not isinstance(value, str) or "\\" in value: + raise ValueError("Invalid profiling source path") + path = PurePosixPath(value) + if (path.is_absolute() or path.as_posix() != value or ".." in path.parts + or len(path.parts) < 3 or path.parts[0] != "scripts" or path.suffix != ".py" + or not all(re.fullmatch(r"[A-Za-z0-9_.-]+", p) for p in path.parts)): + raise ValueError(f"Unsafe profiling source path: {value!r}") + return value + + +def read_catalogue(ws: Path): + """Local manifest first, then published v2 extension; None means pre-migration. + + A present but invalid new producer never falls back to executable-source AST. + File digests identify the routing bytes read, not a measurement revision. + """ + local = ws / "catalogue/script_routes.json" + published = ws / "dashboard/catalogue.json" + source = local if local.is_file() else published + if not source.is_file(): + return None + raw = source.read_bytes() + try: + doc = json.loads(raw) + except (ValueError, UnicodeError) as exc: + raise ValueError(f"Unreadable profiling catalogue: {source.relative_to(ws)}") from exc + if not isinstance(doc, dict): + raise ValueError("Profiling catalogue must be an object") + if source == published: + if doc.get("schema") != "profiling-summary" or doc.get("version") not in (1, 2): + raise ValueError("Unsupported published profiling catalogue") + if "script_routes" not in doc: + return None + if doc["version"] != 2: + raise ValueError("Source routes require profiling-summary v2") + doc = doc["script_routes"] + if not isinstance(doc, dict) or doc.get("schema") != "profiling-script-routes" or doc.get("version") != 1: + raise ValueError("Unsupported profiling script routes schema/version") + entries = doc.get("routes") + cells = doc.get("runtime_cells") + if not isinstance(entries, list) or not isinstance(cells, list) or not cells: + raise ValueError("Profiling routes and nonempty runtime_cells are required") + paths = set() + route_by_path = {} + aliases = set() + for row in entries: + if not isinstance(row, dict): + raise ValueError("Invalid profiling route entry") + path, legacy = _path(row.get("path")), _path(row.get("legacy")) + if path in paths or legacy in aliases: + raise ValueError("Duplicate profiling source route") + dataset = _token(row.get("dataset")) + model = _token(row.get("model")) + measurement = row.get("measurement") + _token(measurement[1:] if isinstance(measurement, str) and measurement.startswith("_") else measurement) + if path != f"scripts/{dataset}/{model}/{row['measurement']}.py": + raise ValueError("Route identity does not match its source path") + route_by_path[path] = row + paths.add(path) + aliases.add(legacy) + grid = [] + seen = set() + for row in cells: + if not isinstance(row, dict): + raise ValueError("Invalid runtime cell") + dataset, model = _token(row.get("dataset")), _token(row.get("model")) + instruments = row.get("instruments") + if not isinstance(instruments, list): + raise ValueError("Runtime instruments must be a list") + instruments = tuple(_token(value) for value in instruments) + if len(set(instruments)) != len(instruments) or (dataset, model) in seen: + raise ValueError("Duplicate runtime cell or instrument") + if _path(row.get("path")) not in paths: + raise ValueError("Runtime cell refers to an undeclared source route") + route = route_by_path[row["path"]] + if dataset != route["dataset"] or model not in (route["model"], PurePosixPath(route["legacy"]).stem): + raise ValueError("Runtime cell identity does not match its source route") + seen.add((dataset, model)) + grid.append((dataset, model, instruments)) + probe = doc.get("compile_probe") + if probe is not None: + if not isinstance(probe, dict): + raise ValueError("Invalid compile probe declaration") + paths.add(_path(probe.get("path"))) + if probe.get("builder_status") not in ("available", "unavailable", "unknown"): + raise ValueError("Unknown compile builder status") + transforms = probe.get("transforms") + if not isinstance(transforms, list) or not transforms: + raise ValueError("Compile transforms must be a nonempty list") + for value in transforms: + _token(value) + if len(set(transforms)) != len(transforms): + raise ValueError("Duplicate compile transform") + return { + "grid": grid, + "source": source.relative_to(ws).as_posix(), + "sha256": hashlib.sha256(raw).hexdigest(), + "version": 1, + "runtime_cells": cells, + "compile_probe": probe, + "missing_sources": sorted(path for path in paths if not (ws / path).is_file()), + } diff --git a/agents/conductors/profiling/_profiling.py b/agents/conductors/profiling/_profiling.py index 82c07766..18f7bc8d 100644 --- a/agents/conductors/profiling/_profiling.py +++ b/agents/conductors/profiling/_profiling.py @@ -25,8 +25,8 @@ workspace; library regression → file a `bug/` prompt via intake. Never debug libraries inside the profiling repo (the phase-2 boundary rule). -Stdlib-only. The workspace's python modules are read via `ast` literal -parsing (importing them would drag the JAX stack into the Brain). +Stdlib-only. The project source catalogue supplies routing; pre-migration +grids and remaining tables use literal AST readers, never scientific imports. Exit codes: 0 decision · 4 missing input · 5 usage. """ @@ -50,6 +50,9 @@ import _pyauto_root # noqa: E402 from _repo_paths import repo_path # noqa: E402 +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _catalogue import read_catalogue # noqa: E402 + PYAUTO_ROOT = _pyauto_root.pyauto_root() HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR", Path.home() / ".pyauto-heart")) @@ -124,9 +127,30 @@ def _module_literal(py_path: Path, name: str): return None +def grid_info(ws: Path) -> dict[str, Any]: + catalogue = read_catalogue(ws) + if catalogue is not None: + return catalogue + path = ws / "scripts/misc/likelihood_runtime/sweep.py" + if not path.is_file(): + raise ValueError("No source catalogue or legacy sweep grid; coverage is unknown") + cells = _module_literal(path, "CELLS") + if not cells: + raise ValueError("Legacy sweep CELLS is missing or nonliteral; coverage is unknown") + return { + "grid": cells, "source": path.relative_to(ws).as_posix(), + "version": None, "sha256": None, "runtime_cells": [], "compile_probe": None, + "missing_sources": [], + "qualification": "Legacy AST fallback: project source catalogue is not yet available.", + } + + def load_grid(ws: Path) -> list[tuple[str, str, tuple[str, ...]]]: - cells = _module_literal(ws / "scripts" / "misc" / "likelihood_runtime" / "sweep.py", "CELLS") - return cells or [] + return grid_info(ws)["grid"] + + +def routing_evidence(info): + return {key: value for key, value in info.items() if key != "grid"} def load_tables(ws: Path) -> dict[str, Any]: @@ -145,10 +169,13 @@ def compile_dir(ws: Path) -> Path: def load_transforms(ws: Path) -> tuple[str, ...]: """probe.py's transform axis, read from the workspace rather than copied. - The list is a module-level literal in `jax_compile/probe.py`, so the same - ast route `load_grid` uses keeps the Brain from drifting out of sync with - the instrument. `FALLBACK_TRANSFORMS` only covers probe.py being absent.""" - got = _module_literal(compile_dir(ws) / "probe.py", "TRANSFORMS") + The catalogue supplies transforms when declared; pre-migration probes use + a module-level literal. FALLBACK_TRANSFORMS covers an absent legacy probe.""" + catalogue = read_catalogue(ws) + if catalogue is not None and catalogue["compile_probe"] is not None: + return tuple(catalogue["compile_probe"]["transforms"]) + path = compile_dir(ws) / "probe.py" + got = _module_literal(path, "TRANSFORMS") if path.is_file() else None return tuple(got) if got else FALLBACK_TRANSFORMS @@ -229,7 +256,8 @@ def compile_tier_of(hardware: str | None) -> str: def campaign(ws: Path, tier: str) -> dict[str, Any]: if tier not in TIER_CONFIGS: return {"agent": "profiling", "mode": "campaign", "error": f"unknown tier {tier!r}"} - grid = load_grid(ws) + routing = grid_info(ws) + grid = routing["grid"] runtime = ws / "results" / "runtime" done: list[str] = [] unusable: list[str] = [] @@ -262,6 +290,9 @@ def campaign(ws: Path, tier: str) -> dict[str, Any]: submits = sorted(p.name for p in (ws / "hpc" / "batch_gpu").glob("submit_*")) dispatch = [f"sbatch hpc/batch_gpu/{s} (on the RAL checkout, post-pull)" for s in submits] + if routing["missing_sources"]: + dispatch = [] + return { "agent": "profiling", "mode": "campaign", @@ -277,8 +308,12 @@ def campaign(ws: Path, tier: str) -> dict[str, Any]: "per-call > 60 s renders unusable; both mean GPU-only " "(results/notes/design_lock_in.md)" ), + "source_routing": routing_evidence(routing), + "evidence_qualification": "Archive presence is unreviewed coverage, not an accepted baseline or current-performance claim. Missing metadata remains unknown.", "dispatch_plan": dispatch, "next_action": ( + "source routes are missing locally; synchronize the captured project before dispatch" + if routing["missing_sources"] else "all runs accounted for — proceed to ingest" if not missing else f"dispatch the {tier} plan ({len(missing)} runs outstanding)" @@ -297,7 +332,8 @@ def campaign_compile(ws: Path, tier: str) -> dict[str, Any]: if tier not in TIER_CONFIGS: return {"agent": "profiling", "mode": "campaign", "error": f"unknown tier {tier!r}"} - grid = load_grid(ws) + routing = grid_info(ws) + grid = routing["grid"] transforms = load_transforms(ws) on_grid = { (cls, model, inst) @@ -364,7 +400,7 @@ def campaign_compile(ws: Path, tier: str) -> dict[str, Any]: if tier == "local": for (cls, model, inst), tfs in sorted(missing_by_cell.items(), key=lambda kv: str(kv[0])): dispatch.append( - f"python3 scripts/misc/jax_compile/probe.py --dataset-class {cls} " + f"python3 {routing['compile_probe']['path'] if routing.get('compile_probe') else 'scripts/misc/jax_compile/probe.py'} --dataset-class {cls} " f"--model-type {model}" + (f" --instrument {inst}" if inst else "") + f" --transforms {','.join(tfs)} --cache-dir