Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions agents/conductors/profiling/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
121 changes: 121 additions & 0 deletions agents/conductors/profiling/_catalogue.py
Original file line number Diff line number Diff line change
@@ -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()),
}
93 changes: 76 additions & 17 deletions agents/conductors/profiling/_profiling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""

Expand All @@ -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"))

Expand Down Expand Up @@ -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]:
Expand All @@ -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


Expand Down Expand Up @@ -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] = []
Expand Down Expand Up @@ -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",
Expand All @@ -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)"
Expand All @@ -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)
Expand Down Expand Up @@ -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 <dir> --tag <cold|warm>"
Expand All @@ -373,6 +409,11 @@ def campaign_compile(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]

probe = routing.get("compile_probe")
unavailable = probe is not None and probe["builder_status"] != "available"
if unavailable or routing["missing_sources"]:
dispatch = []

return {
"agent": "profiling",
"mode": "campaign",
Expand All @@ -393,8 +434,14 @@ def campaign_compile(ws: Path, tier: str) -> dict[str, Any]:
"within (hardware, jax_version, mixed_precision, cache state). This "
"mode reports COVERAGE only — it never compares two timings."
),
"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
"compile dispatch unavailable: " + str(probe.get("reason", "builder status is unknown"))
if unavailable else
"compile grid fully covered on this tier"
if not missing
else f"dispatch the {tier} compile plan ({len(missing)} cell/transform runs outstanding)"
Expand Down Expand Up @@ -819,6 +866,12 @@ def emit_human(d: dict[str, Any]) -> None:
if d.get("error"):
print(f"ERROR: {d['error']}")
return
if d.get("source_routing"):
print(f"Source routing: {d['source_routing']['source']}")
if d["source_routing"].get("qualification"):
print(d["source_routing"]["qualification"])
if d.get("evidence_qualification"):
print(f"Qualification: {d['evidence_qualification']}")
if d["mode"] == "campaign" and d.get("axis") == "compile":
print(f"Tier: {d['tier']}")
print(f"Transforms: {', '.join(d['transforms'])}")
Expand Down Expand Up @@ -935,12 +988,18 @@ def main(argv=None) -> int:
print(f"profiling: workspace not found: {ws}", file=sys.stderr)
return 4

if a.mode == "campaign":
d = campaign_compile(ws, a.tier) if a.axis == "compile" else campaign(ws, a.tier)
elif a.mode == "ingest":
d = ingest_compile(ws) if a.axis == "compile" else ingest(ws)
else:
d = triage_compile(ws) if a.axis == "compile" else triage(ws)
try:
if a.mode == "campaign":
d = campaign_compile(ws, a.tier) if a.axis == "compile" else campaign(ws, a.tier)
elif a.mode == "ingest":
d = ingest_compile(ws) if a.axis == "compile" else ingest(ws)
else:
d = triage_compile(ws) if a.axis == "compile" else triage(ws)
except (ValueError, OSError, SyntaxError) as exc:
d = {"agent": "profiling", "mode": a.mode, "error": str(exc),
"evidence_qualification": "Source routing unavailable; coverage is unknown."}
print(json.dumps(d, indent=2)) if a.as_json else emit_human(d)
return 4

d = _strip_internal(d)
print(json.dumps(d, indent=2)) if a.as_json else emit_human(d)
Expand Down
16 changes: 16 additions & 0 deletions skills/profiling/profiling.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,19 @@ not an argument).
The Profiling Agent **reasons; it never runs sweeps or edits source.** The
classification is the result for CPU-unusable cells; full timings for those
belong to the A100 rows.

## Source catalogue and evidence qualification

Read the project's `catalogue/script_routes.json` first, then the published v2
catalogue's `script_routes` extension. The conductor validates this stdlib-only
contract and reports its source/digest. Legacy sweep AST routing remains only for
projects without the new producer; invalid new data is an error, not a fallback.

Model-first source paths do not rename historical cell IDs or result paths.
Archive coverage is unreviewed evidence, never baseline acceptance or a claim of
current performance. Missing metadata stays unknown. An unavailable compile
builder or absent canonical source suppresses dispatch, with the reason visible.
Campaign commands are plans only; baseline measurement and acceptance require a
separate human-authorized campaign. CPU caps and the RAL CPU partition policy
remain unchanged. Pulse owns campaign intent, Cortex scientific records and Mind
bounded implementation tasks; this routing change moves none of that ownership.
Loading
Loading