diff --git a/agents/faculties/samplers/AGENTS.md b/agents/faculties/samplers/AGENTS.md index fceaece9..83bea4a6 100644 --- a/agents/faculties/samplers/AGENTS.md +++ b/agents/faculties/samplers/AGENTS.md @@ -25,36 +25,47 @@ samplers.sh [--json] archive (autofit_workspace_developer/searches, minus any name that is promoted again) integration (autofit_workspace_test/scripts/searches) - promoted (PyAutoFit `autofit/__init__.py` exports + _LAZY_ATTRS, - one // row per search class) + promoted (the search manifest of the PyAutoFit checkout, + `python -m autofit search-manifest --json` — one + // row per registry entry; the AST + of `autofit/__init__.py` exports + _LAZY_ATTRS is the + fallback when autofit cannot be imported) -> the findings maturation lane (below): experiment probes (autolens_workspace_developer/searches_minimal) experiment findings (the same tier's *_findings.md, name + verdict) mature (autolens_inference — one row per - sampler/dataset_class/model_type cell; - empty until autolens-inference phase 3) + sampler/dataset_class/model_type cell) + mature (autofit_inference — its cells, plus one + /: row per search + catalogue cell, catalogue/search_catalogue.json) -> the latest minimal-tier benchmark table (output/comparison.txt) -> tier gaps: prototyped-never-promoted, promoted-never-integration-tested ``` -The gap rule is keyed on exported class names, never on module directories -(one directory can hold several searches: `mle/bfgs` is BFGS + LBFGS). An -integration script covers a class when its stem, with variant suffixes such -as `_jax` stripped, equals the class name; a `searches_minimal` prototype is +The gap rule is keyed on search names, never on module directories +(one directory can hold several searches: `mle/bfgs` is BFGS + LBFGS). With +the manifest, a search is integration-tested when the file its registry +`integration_test` anchor names exists in the test checkout; on the AST +fallback, an integration script covers a class when its stem, with variant +suffixes such as `_jax` stripped, equals the class name. A `searches_minimal` prototype is promoted when its stem, with `_simple`/`_jax`/`_mlp`/`_profile`/`_sweep`… stripped, equals an exported class or a `PROTOTYPE_ALIASES` family (`dynesty`, `nuts`). Surfaces are resolved as sibling checkouts (`PYAUTO_FIT`, `PYAUTO_FIT_DEVELOPER`, `PYAUTO_FIT_TEST`, `PYAUTO_LENS_DEVELOPER`, -`PYAUTO_INFERENCE` override); absent ones are -reported, never fatal. Exit codes: `0` digest · `4` no surface · `5` usage. +`PYAUTO_INFERENCE`, `PYAUTO_FIT_INFERENCE` override); absent ones are +reported, never fatal. `--manifest FILE` reads a saved manifest dump instead +of importing the checkout. Exit codes: `0` digest · `4` no surface · `5` usage. A mature-tier cell is read from its leaf's `run_search(sampler=, -dataset_class=, model_type=)` declaration, **not** from its path — the two -disagree on the live tree (the `cluster/searches/*/mge.py` leaves declare the -`group` dataset class), and the declaration is what the runner acts on. The -lane tiers are inventory only; they feed no `gaps` rule. +dataset_class=, model_type=)` or `run_point_search(...)` declaration, **not** +from its path — the two disagree on the live tree (the +`cluster/searches/*/mge.py` leaves declare the `group` dataset class), and the +declaration is what the runner acts on. `run_point_search` leaves take the +runner's defaults (`nautilus`, `point_source`) for omitted keywords and their +stem as the model type, wherever they sit under `scripts/`. The lane tiers are +inventory only; they feed no `gaps` rule. ## Judgment: matching sampler to likelihood diff --git a/agents/faculties/samplers/_samplers.py b/agents/faculties/samplers/_samplers.py index 9d7de2ed..92fb94df 100755 --- a/agents/faculties/samplers/_samplers.py +++ b/agents/faculties/samplers/_samplers.py @@ -4,12 +4,17 @@ The **samplers faculty** is a read-only opinion sink: it inventories the organism's non-linear-search machinery — the three script tiers (minimal prototypes, the removed-sampler archive, the workspace_test integration -scripts) and the PyAutoFit search catalogue — plus the latest minimal-tier +scripts) and the PyAutoFit search catalogue — read from the versioned search +manifest (`python -m autofit search-manifest --json`, schema +`search-manifest@1`) of the PyAutoFit checkout, with an AST parse of +`autofit/__init__.py` as the fallback when it cannot be imported — plus the latest minimal-tier benchmark outputs, and flags tier gaps (prototyped but never promoted, promoted but never integration-tested). It also inventories the **findings maturation lane** (AGENTS.md "Judgment: the maturation lane"): the experiment -tier's probes and findings docs, and the mature tier's -(sampler x dataset_class x model_type) cell matrix. The consulting agent +tier's probes and findings docs, and the mature tiers' (sampler x +dataset_class x model_type) cell matrices — the lens leaves and the autofit +toy-likelihood leaves, the latter with their search catalogue's verdict +cells. The consulting agent reads the digest and reasons with AGENTS.md's judgment tables; this script never writes, never runs a sampler, and never edits anything. @@ -20,6 +25,8 @@ import argparse import ast import json +import os +import subprocess import sys from pathlib import Path @@ -143,11 +150,73 @@ def exported_searches(autofit: Path) -> dict[str, str]: def tier_promoted(autofit: Path) -> list[str]: - """Exported search classes as `//`.""" + """Exported search classes as `//` (AST fallback).""" return sorted(f"{loc}/{cls}" for cls, loc in exported_searches(autofit).items()) +MANIFEST_SCHEMA = "search-manifest@1" + + +def load_manifest(autofit: Path | None = None, + manifest_file: Path | None = None) -> dict | None: + """The search manifest, or None when it cannot be had. + + `manifest_file` reads a saved `--json` dump. Otherwise the manifest is + printed by `python -m autofit search-manifest --json` with the `autofit` + checkout first on PYTHONPATH — the registry of the very checkout this + digest inventories. Any failure (no checkout, the science stack not + importable, an older schema) returns None and the caller falls back to the + AST parse; the faculty never fails for want of a manifest. + """ + try: + if manifest_file: + text = Path(manifest_file).read_text(encoding="utf-8") + else: + if not (autofit and (autofit / "autofit" / "__init__.py").is_file()): + return None + env = dict(os.environ) + env["PYTHONPATH"] = str(autofit.resolve()) + ( + os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") + proc = subprocess.run( + [sys.executable, "-m", "autofit", "search-manifest", "--json"], + capture_output=True, text=True, env=env, timeout=60) + if proc.returncode != 0: + return None + text = proc.stdout + manifest = json.loads(text) + except (OSError, ValueError, subprocess.SubprocessError): + return None + if not isinstance(manifest, dict) or manifest.get("schema") != MANIFEST_SCHEMA: + return None + return manifest + + +def manifest_promoted(manifest: dict) -> list[str]: + """Manifest searches as `//` — the same row shape as the + AST tier, so the two sources are interchangeable downstream.""" + rows = [] + for s in manifest.get("searches", []): + module = s.get("class_path", "").rpartition(".")[0] + loc = _search_location(module) or s.get("family", "?") + rows.append(f"{loc}/{s['name']}") + return sorted(rows) + + +def manifest_integration(manifest: dict, test: Path | None) -> dict[str, bool]: + """{search name: does its manifest `integration_test` anchor exist}. + + The anchor is `:`; the path is resolved against the + integration-test checkout. A search with no anchor maps to False. + """ + out = {} + for s in manifest.get("searches", []): + anchor = s.get("integration_test") or "" + path = anchor.partition(":")[2].partition("#")[0] + out[s["name"]] = bool(path and test and (test / path).is_file()) + return out + + # -------------------------------------------------------------------------- # The findings maturation lane (AGENTS.md "Judgment: the maturation lane") # -------------------------------------------------------------------------- @@ -159,9 +228,23 @@ def tier_promoted(autofit: Path) -> list[str]: # re-spelling an instance fact. SURFACE_LENS_DEVELOPER = "autolens_workspace_developer" SURFACE_INFERENCE = "autolens_inference" +SURFACE_FIT_INFERENCE = "autofit_inference" TIER_LENS_PROBES = "experiment probes (autolens searches_minimal)" TIER_LENS_FINDINGS = "experiment findings (autolens searches_minimal)" TIER_LENS_MATURE = "mature (autolens_inference searches cells)" +TIER_FIT_MATURE = "mature (autofit_inference searches cells)" +TIER_FIT_CATALOGUE = "mature (autofit_inference search catalogue)" +FIT_CATALOGUE = Path("catalogue") / "search_catalogue.json" + +# The runner entrypoints whose call declares a mature cell, with the defaults +# each one supplies for a keyword its leaves may omit. `run_point_search` (the +# point-source runner) takes no `model_type`; the leaf's stem stands in for it. +RUNNERS = { + "run_search": {}, + "run_point_search": {"sampler": "nautilus", "dataset_class": "point_source"}, +} +# Runners whose leaves name no model_type: the leaf's stem stands in for it. +STEM_MODEL_TYPE = {"run_point_search"} def tier_lens_probes(lens_developer: Path) -> list[str]: @@ -196,7 +279,8 @@ def tier_lens_findings(lens_developer: Path) -> list[str]: def _declared_cell(leaf: Path) -> tuple[str, str, str] | None: - """Read the `run_search(sampler=, dataset_class=, model_type=)` declaration. + """Read the `run_search(sampler=, dataset_class=, model_type=)` declaration + (or `run_point_search(...)`, see RUNNERS). The declaration — NOT the path — is the cell's identity. The two genuinely disagree on the live tree: every `cluster/searches/*/mge.py` leaf declares @@ -213,26 +297,35 @@ def _declared_cell(leaf: Path) -> tuple[str, str, str] | None: continue func = node.func name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None) - if name != "run_search": + if name not in RUNNERS: continue - kw = { - k.arg: k.value.value - for k in node.keywords - if k.arg and isinstance(k.value, ast.Constant) - and isinstance(k.value.value, str) - } + given = {k.arg: k.value for k in node.keywords if k.arg} + if any(not (isinstance(v, ast.Constant) and isinstance(v.value, str)) + for k, v in given.items() + if k in ("sampler", "dataset_class", "model_type")): + # A declaration keyword that is not a string literal cannot be read + # statically; falling back to a runner default would mislabel it. + return None + kw = dict(RUNNERS[name]) + kw.update({k: v.value for k, v in given.items() + if isinstance(v, ast.Constant) and isinstance(v.value, str)}) + if name in STEM_MODEL_TYPE: + kw.setdefault("model_type", leaf.stem) if {"sampler", "dataset_class", "model_type"} <= kw.keys(): return kw["sampler"], kw["dataset_class"], kw["model_type"] return None -def tier_lens_mature(inference: Path) -> list[str]: +def tier_mature(inference: Path) -> list[str]: """Mature tier: the (sampler x dataset_class x model_type) cell matrix. - Walks `scripts//searches//.py` under the - `autolens_inference` checkout, skipping the `misc/` framework directory and - `_`-prefixed helpers. A leaf with no parsable declaration falls back to its - path shape rather than vanishing. + Walks every `scripts/**/*.py` leaf under an inference checkout, skipping + the `misc/` framework directory and `_`-prefixed helpers, and keeps the + leaves that declare a cell through a RUNNERS call — wherever they live + (the point-source leaves sit at `scripts/point_source//`, not + under a `searches/` directory). A `scripts//searches// + .py` leaf with no parsable declaration falls back to its path + shape rather than vanishing. The tier is EMPTY until autolens-inference phase 3 builds these cells (autolens_profiling#245 removed the retired inference programme's copies, @@ -245,16 +338,49 @@ def tier_lens_mature(inference: Path) -> list[str]: if not scripts.is_dir(): return [] cells = set() - for leaf in scripts.glob("*/searches/*/*.py"): - if leaf.stem.startswith("_") or leaf.parent.parent.parent.name == "misc": + for leaf in scripts.rglob("*.py"): + rel = leaf.relative_to(scripts).parts + if leaf.stem.startswith("_") or rel[0] == "misc": continue declared = _declared_cell(leaf) if declared is None: - declared = (leaf.parent.name, leaf.parent.parent.parent.name, leaf.stem) + if len(rel) == 4 and rel[1] == "searches": + declared = (rel[2], rel[0], leaf.stem) + else: + continue cells.add("/".join(declared)) return sorted(cells) +tier_lens_mature = tier_mature # the lens surface's name for the shared walk + + +def fit_catalogue(fit_inference: Path) -> tuple[list[str], dict | None]: + """The autofit inference search catalogue's verdict cells. + + Rows are `/: ` (`measured`, `deferred`, + `unsupported`, ...), one per search per requested task — the catalogue + groups by task and never ranks across tasks, so neither does this row + list. Returns ([], None) when the catalogue is absent or unreadable. + """ + path = fit_inference / FIT_CATALOGUE + try: + cat = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return [], None + rows = [] + for task, body in (cat.get("tasks") or {}).items(): + for search, cell in (body.get("searches") or {}).items(): + rows.append(f"{task}/{search}: {cell.get('status', '?')}") + meta = { + "path": str(path), + "protocol_id": cat.get("protocol_id"), + "ranking": cat.get("ranking"), + "manifest_autofit_version": (cat.get("manifest") or {}).get("autofit_version"), + } + return sorted(rows), meta + + def benchmarks(developer: Path) -> dict: out_dir = developer / "searches_minimal" / "output" result = {"comparison": None, "summaries": []} @@ -270,18 +396,24 @@ def benchmarks(developer: Path) -> dict: return result -def gaps(minimal, integration, promoted) -> list[str]: +def gaps(minimal, integration, promoted, integration_by_manifest=None) -> list[str]: """Tier-mismatch findings, phrased for the consulting conductor. `promoted` holds `//` rows (or bare class names); every - comparison is against the exported class. An integration script covers a - class when its stem, `_jax` and other variants stripped, equals the class - name (case-insensitive); a prototype is promoted when its family equals an - exported class or a PROTOTYPE_ALIASES entry names one. + comparison is against the exported class. With a manifest, + `integration_by_manifest` maps each search name to whether its manifest + `integration_test` anchor exists, and that is the coverage rule. Without + one, an integration script covers a class when its stem, `_jax` and other + variants stripped, equals the class name (case-insensitive). Either way a + prototype is promoted when its family equals an exported class or a + PROTOTYPE_ALIASES entry names one. """ classes = {row.rsplit("/", 1)[-1] for row in promoted} by_lower = {c.lower(): c for c in classes} - covered = {family_of(n) for n in integration} + if integration_by_manifest is not None: + covered = {n.lower() for n, ok in integration_by_manifest.items() if ok} + else: + covered = {family_of(n) for n in integration} out = [] for fam in sorted({family_of(n) for n in minimal}): names = PROTOTYPE_ALIASES.get(fam, (fam,)) @@ -296,7 +428,8 @@ class when its stem, `_jax` and other variants stripped, equals the class return out -def digest(autofit, developer, test, lens_developer=None, inference=None) -> dict: +def digest(autofit, developer, test, lens_developer=None, inference=None, + fit_inference=None, manifest_file=None) -> dict: d = { "surfaces_present": [], "tiers": {}, @@ -310,6 +443,7 @@ def digest(autofit, developer, test, lens_developer=None, inference=None) -> dic } minimal = integration = [] promoted = [] + manifest = None if developer and developer.is_dir(): d["surfaces_present"].append("autofit_workspace_developer") minimal = tier_minimal(developer) @@ -320,10 +454,30 @@ def digest(autofit, developer, test, lens_developer=None, inference=None) -> dic d["surfaces_present"].append("autofit_workspace_test") integration = tier_integration(test) d["tiers"]["integration (scripts/searches)"] = integration + if manifest_file or (autofit and autofit.is_dir()): + manifest = load_manifest(autofit, manifest_file) if autofit and autofit.is_dir(): d["surfaces_present"].append("PyAutoFit") + elif manifest is not None: + d["surfaces_present"].append("search manifest") + if manifest is not None: + promoted = manifest_promoted(manifest) + d["tiers"]["promoted (autofit exports)"] = promoted + # A checkout's __version__ string is not a release; name the checkout. + d["manifest"] = {"source": f"file {manifest_file}" if manifest_file + else f"search manifest of the checkout {autofit}", + "schema": manifest["schema"], + "autofit_version": manifest.get("autofit_version")} + elif autofit and autofit.is_dir(): promoted = tier_promoted(autofit) d["tiers"]["promoted (autofit exports)"] = promoted + d["manifest"] = {"source": (f"AST fallback (--manifest {manifest_file} " + f"unreadable or not {MANIFEST_SCHEMA})") + if manifest_file else + "AST fallback (autofit not importable)"} + elif manifest_file: + d["manifest"] = {"source": f"unusable: --manifest {manifest_file} " + f"unreadable or not {MANIFEST_SCHEMA}"} if "archive (searches)" in d["tiers"]: d["tiers"]["archive (searches)"] = tier_archive( developer, [row.rsplit("/", 1)[-1] for row in promoted]) @@ -333,17 +487,35 @@ def digest(autofit, developer, test, lens_developer=None, inference=None) -> dic d["tiers"][TIER_LENS_FINDINGS] = tier_lens_findings(lens_developer) if inference and inference.is_dir(): d["surfaces_present"].append(SURFACE_INFERENCE) - d["tiers"][TIER_LENS_MATURE] = tier_lens_mature(inference) + d["tiers"][TIER_LENS_MATURE] = tier_mature(inference) + if fit_inference and fit_inference.is_dir(): + d["surfaces_present"].append(SURFACE_FIT_INFERENCE) + d["tiers"][TIER_FIT_MATURE] = tier_mature(fit_inference) + rows, meta = fit_catalogue(fit_inference) + d["tiers"][TIER_FIT_CATALOGUE] = rows + if meta: + d["fit_inference_catalogue"] = meta # The lane tiers are inventory only: `gaps` stays keyed on the autofit # promotion tiers, so adding them introduces no new judgment. if minimal or promoted: - d["gaps"] = gaps(minimal, integration, promoted) + by_manifest = (manifest_integration(manifest, test) + if manifest is not None and test and test.is_dir() else None) + d["gaps"] = gaps(minimal, integration, promoted, by_manifest) return d def emit_human(d: dict) -> None: print("== SamplerSurface (read-only) ==") print(f"surfaces present: {', '.join(d['surfaces_present']) or 'NONE'}") + if d.get("manifest"): + m = d["manifest"] + version = (f" (reports __version__ {m['autofit_version']})" + if m.get("autofit_version") else "") + print(f"search catalogue from: {m['source']}{version}") + if d.get("fit_inference_catalogue"): + c = d["fit_inference_catalogue"] + print(f"fit inference catalogue: protocol {c['protocol_id']}, " + f"ranking {c['ranking']}") for tier, names in d["tiers"].items(): print(f"\n-- {tier}: {len(names)}") for n in names: @@ -375,6 +547,12 @@ def main(argv=None) -> int: "(lane experiment tier)") ap.add_argument("--inference", default="", help="autolens_inference checkout (lane mature tier)") + ap.add_argument("--fit-inference", default="", dest="fit_inference", + help="autofit_inference checkout (mature cells + search " + "catalogue)") + ap.add_argument("--manifest", default="", + help="saved `python -m autofit search-manifest --json` " + "dump (default: print it from the --autofit checkout)") ap.add_argument("--json", action="store_true", dest="as_json") a = ap.parse_args(argv) autofit = Path(a.autofit) if a.autofit else None @@ -382,11 +560,15 @@ def main(argv=None) -> int: test = Path(a.test) if a.test else None lens_developer = Path(a.lens_developer) if a.lens_developer else None inference = Path(a.inference) if a.inference else None - d = digest(autofit, developer, test, lens_developer, inference) + fit_inference = Path(a.fit_inference) if a.fit_inference else None + manifest_file = Path(a.manifest) if a.manifest else None + d = digest(autofit, developer, test, lens_developer, inference, + fit_inference, manifest_file) if not d["surfaces_present"]: print("samplers: no sampler surface found (PyAutoFit / " "autofit_workspace_developer / autofit_workspace_test / " - "autolens_workspace_developer / autolens_inference absent)", + "autolens_workspace_developer / autolens_inference / " + "autofit_inference absent)", file=sys.stderr) return 4 print(json.dumps(d, indent=2)) if a.as_json else emit_human(d) diff --git a/agents/faculties/samplers/samplers.sh b/agents/faculties/samplers/samplers.sh index 85b354b7..b77ea981 100755 --- a/agents/faculties/samplers/samplers.sh +++ b/agents/faculties/samplers/samplers.sh @@ -9,7 +9,9 @@ # the latest minimal-tier benchmark table, with tier-gap findings (prototyped # but never promoted; promoted but never integration-tested). It also covers # the findings maturation lane: the experiment tier's probes + findings docs -# and the mature tier's (sampler x dataset_class x model_type) cells. The consulting +# and the mature tiers' (sampler x dataset_class x model_type) cells, plus the +# autofit inference search catalogue. The PyAutoFit tiers key on the search +# manifest (python -m autofit search-manifest --json), AST as the fallback. The consulting # agent reads the digest and reasons with AGENTS.md's judgment tables # (sampler<->likelihood match, gradient/JAX constraints, initialization # chaining). Read-only: never runs a sampler, never writes, never dispatches. @@ -31,6 +33,9 @@ test_ws="$(_resolve_dir PYAUTO_FIT_TEST autofit_workspace_test 2>/dev/null || tr # lane") — present-if-checked-out, exactly like the autofit-side surfaces. lens_developer="$(_resolve_dir PYAUTO_LENS_DEVELOPER autolens_workspace_developer 2>/dev/null || true)" inference="$(_resolve_dir PYAUTO_INFERENCE autolens_inference 2>/dev/null || true)" +# The autofit toy-likelihood benchmark: its mature cells and the search +# catalogue's per-task verdict cells. +fit_inference="$(_resolve_dir PYAUTO_FIT_INFERENCE autofit_inference 2>/dev/null || true)" exec python3 "$HERE/_samplers.py" \ ${autofit:+--autofit "$autofit"} \ @@ -38,4 +43,5 @@ exec python3 "$HERE/_samplers.py" \ ${test_ws:+--test "$test_ws"} \ ${lens_developer:+--lens-developer "$lens_developer"} \ ${inference:+--inference "$inference"} \ + ${fit_inference:+--fit-inference "$fit_inference"} \ "$@" diff --git a/skills/sampler_pipeline/reference.md b/skills/sampler_pipeline/reference.md index 94cfbff5..b5622d95 100644 --- a/skills/sampler_pipeline/reference.md +++ b/skills/sampler_pipeline/reference.md @@ -119,6 +119,20 @@ table. ## Stage 3 — promotion: the PyAutoFit implementation +**Start from the template**: copy +`autofit/non_linear/search/_template/search.py` (a complete, runnable +hill-climber that passes the search conformance suite) to +`autofit/non_linear/search///search.py`; its header lists the +six PyAutoFit touch points of a new search. The search is promoted when its +**registry entry** (`autofit/non_linear/search/registry.py`) exists: the +versioned search manifest (`python -m autofit search-manifest --json`, +schema `search-manifest@1`) is generated from that registry, and the manifest +feeds the capability matrix, the generated rosters (PyAutoHands +`regenerate_search_roster`) and this faculty's promoted tier. The registry +entry's `example` / `integration_test` anchors must name real files — +the workspaces' `navigator_check` roster leg resolves them against the +installed release. + **Reference implementations** (read before writing a line): `nest/nss/` — JAX nested sampler, chunked-vmap internals, ~600-line `search.py`; `mcmc/blackjax/nuts/` — gradient consumer wired through @@ -145,7 +159,9 @@ A new search package `autofit/non_linear/search///` needs: 2. **`samples.py`** — a `Samples` subclass converting sampler output into autofit samples (cf. `NSSamples(SamplesNest)` — ~25 lines on top of `SamplesNest`). -3. **Public export** — `autofit/__init__.py` (`af.` is the API). +3. **Public export and registry entry** — `autofit/__init__.py` + (`af.` is the API) and `registry.py` (the manifest row: family, + requirements, `example` and `integration_test` anchors). 4. **Dependency** — optional extra in `pyproject.toml`. Gotcha: PyPI rejects git-URL dependencies in uploaded wheels ("400 Can't have direct dependency") — fork-only deps get a manual-install comment in @@ -178,11 +194,18 @@ cd autofit_workspace_test && python scripts/searches/.py ## Stage 5 — documentation -A search is not promoted until the surfaces that list searches name it. No -registry generates these yet, so this is the interim checklist (library -first; generated files — notebooks, `llms-full.txt`, `workspace_index.json` -— regenerate via PyAutoHands and are never hand-edited). Skip a row only when -its condition does not apply. +Rosters are generated, not edited: every fenced `search-roster` block +(autofit_workspace `llms.txt` and `scripts/searches/README.md`, the af/al/ag +assistants' `*_configure_search.md` and catalogue pages) is re-rendered from +the installed release's manifest with PyAutoHands +`autohands regenerate_search_roster --root `, and `check_search_roster` +fails CI when one drifts. They change when a PyAutoFit release carrying the +registry entry is installed — regenerate them then, never by hand. Notebooks, +`llms-full.txt` and `workspace_index.json` likewise regenerate via PyAutoHands. + +What stays hand-written is the list below — prose, pick tables and judgment +that say *when* to use a search, which no manifest can generate. Library +first; skip a row only when its condition does not apply. **PyAutoFit** - `docs/api/searches.rst` entry and the committed @@ -195,11 +218,11 @@ its condition does not apply. - `AGENTS.md` package-map line **autofit_workspace** -- `scripts/searches/.py` section (smoke-tested) and - `scripts/searches/README.md` +- `scripts/searches/.py` section (smoke-tested; it is the + registry's `example` anchor, `__Search: __`) - `scripts/cookbooks/search.py` — mirror of the RTD cookbook section - `scripts/plot/_plotter.py` (search-specific plots only) -- `llms.txt`, `CITATIONS.md` +- `CITATIONS.md` **autofit_workspace_test / autofit_workspace_developer** - the Stage 4 integration script(s) @@ -211,9 +234,11 @@ its condition does not apply. `tutorial_6_gradients.py`; `CITATIONS.md` **Downstream libraries and workspaces** (kept in lockstep) -- `guides/modeling/searches.py` in autolens_workspace and - autogalaxy_workspace (plus `guides/plot/searches.py` when the search has - plots) +- `scripts/guides/modeling/searches.py` in autolens_workspace and + autogalaxy_workspace — domain advice only, when the search earns a + lensing/galaxy recommendation (every `search = af.(...)` there is + drift-checked against the manifest); plus `guides/plot/searches.py` when + the search has plots - `chapter_optional/tutorial_searches.py` in HowToLens and HowToGalaxy - `docs/api/modeling.rst` in PyAutoLens, PyAutoGalaxy and PyAutoCTI - `docs/general/citations.*` in PyAutoLens, PyAutoGalaxy and PyAutoCTI; @@ -223,14 +248,13 @@ its condition does not apply. dependency only) **Assistants** -- autofit_assistant: `skills/af_configure_search.md`, - `wiki/core/concepts/non_linear_search.md` (roster table), the family page - under `wiki/core/concepts/`, `initialization_and_chaining.md` - (provider/consumer role), `wiki/core/stack/autofit.md` -- autolens_assistant: `skills/al_configure_search.md`, - `wiki/core/concepts/non_linear_search.md` -- autogalaxy_assistant: `skills/ag_configure_search.md`, - `wiki/core/concepts/non_linear_search.md` +- the hand-written pick tables and branches only (the roster blocks are + generated): autofit_assistant `wiki/core/concepts/non_linear_search.md` + "Choosing", the family page under `wiki/core/concepts/`, + `initialization_and_chaining.md` (provider/consumer role), + `wiki/core/stack/autofit.md`; autolens_assistant and autogalaxy_assistant + `wiki/core/api/searches.md` "Picking a search at a glance" and the + `*_configure_search.md` branches **Organs and galleries** - the samplers faculty's `AGENTS.md` judgment tables diff --git a/tests/test_samplers_surface.py b/tests/test_samplers_surface.py index 93cac216..67b91d1f 100644 --- a/tests/test_samplers_surface.py +++ b/tests/test_samplers_surface.py @@ -239,3 +239,144 @@ def test_gap_rule_reports_only_true_gaps(tmp_path): # NSS was re-mainlined, so its archive copy is not a second tier entry assert d["tiers"]["archive (searches)"] == ["pyswarms"] assert sum("NSS" in g for g in gaps) == 0 + + +# -------------------------------------------------------------------------- +# The search manifest as the catalogue's source of truth +# -------------------------------------------------------------------------- + + +def _manifest_file(root: Path, searches) -> Path: + """A `search-manifest@1` dump; `searches` is [(name, module, anchor)].""" + doc = { + "schema": "search-manifest@1", + "autofit_version": "9.9.9", + "families": {}, + "capability_attributes": [], + "searches": [ + {"name": name, "class_path": f"autofit.{module}.{name}", + "family": module.split(".")[2], "integration_test": anchor} + for name, module, anchor in searches + ], + } + path = root / "manifest.json" + path.write_text(json.dumps(doc)) + return path + + +def test_manifest_keys_promoted_and_gaps(tmp_path): + paths = _make_fit_family(tmp_path) + manifest = _manifest_file(tmp_path, [ + ("Nautilus", "non_linear.search.nest.nautilus.search", + "ws_test:scripts/searches/Nautilus_jax.py"), + ("LBFGS", "non_linear.search.mle.bfgs.search", + "ws_test:scripts/searches/LBFGS.py"), + ("Fresh", "non_linear.search.mle.fresh.search", + "ws_test:scripts/searches/Fresh.py"), + ]) + d = _digest("--autofit", str(paths["autofit"]), + "--developer", str(paths["developer"]), + "--test", str(paths["test"]), + "--manifest", str(manifest)) + assert d["manifest"]["autofit_version"] == "9.9.9" + # the manifest, not the AST of __init__.py, is the promoted tier + assert d["tiers"]["promoted (autofit exports)"] == [ + "mle/bfgs/LBFGS", "mle/fresh/Fresh", "nest/nautilus/Nautilus"] + missing = sorted(g.split("'")[1] for g in d["gaps"] + if "integration script" in g) + # coverage is the manifest anchor resolving: Nautilus is covered by the + # file its anchor names, Fresh's anchored file does not exist + assert missing == ["Fresh"] + + +def test_unreadable_manifest_falls_back_to_the_ast(tmp_path): + paths = _make_fit_family(tmp_path) + bad = tmp_path / "bad.json" + bad.write_text(json.dumps({"schema": "search-manifest@0", "searches": []})) + d = _digest("--autofit", str(paths["autofit"]), "--manifest", str(bad)) + # the explicit file's failure is named, not hidden behind "not importable" + assert d["manifest"]["source"].startswith("AST fallback (--manifest") + assert "nest/nss/NSS" in d["tiers"]["promoted (autofit exports)"] + + +def test_manifest_file_alone_is_a_surface(tmp_path): + manifest = _manifest_file(tmp_path, [ + ("Nautilus", "non_linear.search.nest.nautilus.search", None)]) + d = _digest("--manifest", str(manifest)) + assert "search manifest" in d["surfaces_present"] + assert d["tiers"]["promoted (autofit exports)"] == ["nest/nautilus/Nautilus"] + + +def test_checkout_manifest_subprocess_path(tmp_path): + """No --manifest: the manifest is printed by `python -m autofit` with the + checkout first on PYTHONPATH, and a failing module degrades to the AST.""" + good = tmp_path / "good" + (good / "autofit").mkdir(parents=True) + (good / "autofit" / "__init__.py").write_text("") + (good / "autofit" / "__main__.py").write_text( + "import json\nprint(json.dumps({'schema': 'search-manifest@1', " + "'autofit_version': '0.0.1', 'searches': [{'name': 'Zeta', " + "'class_path': 'autofit.non_linear.search.mcmc.zeta.search.Zeta'}]}))\n") + d = _digest("--autofit", str(good)) + assert d["tiers"]["promoted (autofit exports)"] == ["mcmc/zeta/Zeta"] + assert d["manifest"]["source"].startswith("search manifest of the checkout") + broken = tmp_path / "broken" + (broken / "autofit").mkdir(parents=True) + (broken / "autofit" / "__init__.py").write_text(_AUTOFIT_INIT) + (broken / "autofit" / "__main__.py").write_text("raise SystemExit(3)\n") + d = _digest("--autofit", str(broken)) + assert d["manifest"]["source"] == "AST fallback (autofit not importable)" + + +# -------------------------------------------------------------------------- +# run_point_search leaves and the autofit inference surface +# -------------------------------------------------------------------------- + + +def test_point_runner_leaf_declares_a_cell_outside_searches(tmp_path): + root = _make_mature(tmp_path) + leaf = root / "scripts" / "point_source" / "simple" + leaf.mkdir(parents=True) + (leaf / "baseline.py").write_text( + "from searches._point_runner import run_point_search\n" + "run_point_search(sampler=\"nautilus\", default_instrument=\"simple\")\n" + ) + (leaf / "notes.py").write_text("# not a cell: no runner call, not searches-shaped\n") + # a run_search helper with no model_type is not a cell (no stem default)... + (leaf / "helper.py").write_text( + "run_search(sampler=\"emcee\", dataset_class=\"imaging\")\n") + # ...and a non-literal sampler is unreadable, never the runner default + (leaf / "dynamic.py").write_text("run_point_search(sampler=SAMPLER)\n") + cells = _digest("--inference", str(root))["tiers"][_samplers.TIER_LENS_MATURE] + # dataset_class comes from the runner's default, model_type from the stem + assert cells == ["nautilus/group/mge", "nautilus/imaging/mge", + "nautilus/point_source/baseline"] + + +def test_fit_inference_surface_lists_cells_and_catalogue(tmp_path): + root = tmp_path / "fit_inference" + _cell(root, "toy_blend", "emcee", "toy") + (root / "catalogue").mkdir() + (root / "catalogue" / "search_catalogue.json").write_text(json.dumps({ + "protocol_id": "toy@1", "ranking": "none", + "manifest": {"autofit_version": "9.9.9"}, + "tasks": { + "posterior": {"searches": {"Emcee": {"status": "measured"}}}, + "evidence": {"searches": {"NSS": {"status": "deferred"}}}, + }, + })) + d = _digest("--fit-inference", str(root)) + assert _samplers.SURFACE_FIT_INFERENCE in d["surfaces_present"] + assert d["tiers"][_samplers.TIER_FIT_MATURE] == ["emcee/toy_blend/toy"] + assert d["tiers"][_samplers.TIER_FIT_CATALOGUE] == [ + "evidence/NSS: deferred", "posterior/Emcee: measured"] + assert d["fit_inference_catalogue"]["protocol_id"] == "toy@1" + assert d["gaps"] == [] # inventory only + + +def test_fit_inference_without_catalogue_is_not_fatal(tmp_path): + root = tmp_path / "fit_inference" + root.mkdir() + d = _digest("--fit-inference", str(root)) + assert d["tiers"][_samplers.TIER_FIT_CATALOGUE] == [] + assert "fit_inference_catalogue" not in d