From bdf0a2ed4f0d6ede963dbf63b86dfad5f913e2ab Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 8 Oct 2026 08:36:53 +0100 Subject: [PATCH 1/2] samplers: key the tier-gap rule on exported search classes The SamplerSurface gap rule compared module-directory names with integration-script stems, which broke wherever one directory holds several searches: `mle/multi_start_gradient` was flagged although MultiStartAdam.py exists, SMC hid behind BlackJAXNUTS in `mcmc/blackjax`, BFGS hid behind LBFGS in `mle/bfgs`, and the re-mainlined NSS was listed as both archived and promoted. The promoted tier is now parsed from `autofit/__init__.py` (eager `from .non_linear.search... import` lines plus `_LAZY_ATTRS`), one `//` row per exported search. Integration coverage matches class against script stem with `_jax` and other variant suffixes stripped; `searches_minimal` prototypes strip stacked suffixes including `_mlp`, `_profile` and `_sweep`; archive directories that are promoted again are dropped. Unit tests reproduce each trap. Refs PyAutoLabs/PyAutoFit#1668 (search-extensibility A0c part 1, item 10). Co-Authored-By: Claude Fable 5.1 --- agents/faculties/samplers/AGENTS.md | 14 ++- agents/faculties/samplers/_samplers.py | 157 +++++++++++++++++++------ tests/test_samplers_surface.py | 96 +++++++++++++++ 3 files changed, 228 insertions(+), 39 deletions(-) diff --git a/agents/faculties/samplers/AGENTS.md b/agents/faculties/samplers/AGENTS.md index d076c686..fceaece9 100644 --- a/agents/faculties/samplers/AGENTS.md +++ b/agents/faculties/samplers/AGENTS.md @@ -22,9 +22,11 @@ The entrypoint inventories the sampler machinery deterministically: ``` samplers.sh [--json] -> tiers: minimal (autofit_workspace_developer/searches_minimal) - archive (autofit_workspace_developer/searches) + archive (autofit_workspace_developer/searches, minus any + name that is promoted again) integration (autofit_workspace_test/scripts/searches) - promoted (PyAutoFit autofit/non_linear/search//) + promoted (PyAutoFit `autofit/__init__.py` exports + _LAZY_ATTRS, + one // row per search class) -> the findings maturation lane (below): experiment probes (autolens_workspace_developer/searches_minimal) experiment findings (the same tier's *_findings.md, name + verdict) @@ -35,6 +37,14 @@ samplers.sh [--json] -> 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 +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 diff --git a/agents/faculties/samplers/_samplers.py b/agents/faculties/samplers/_samplers.py index c290e8c7..9d7de2ed 100755 --- a/agents/faculties/samplers/_samplers.py +++ b/agents/faculties/samplers/_samplers.py @@ -23,21 +23,30 @@ import sys from pathlib import Path -# Map script/module basenames to a canonical sampler family so tiers can be -# compared. Suffixes like _jax/_jit/_grad/_simple are variants, not families. -VARIANT_SUFFIXES = ("_simple", "_jax", "_jit", "_grad") -ALIASES = { - "nuts": "nuts", "blackjaxnuts": "nuts", "blackjax": "nuts", - "dynestystatic": "dynesty", "dynestydynamic": "dynesty", - "bfgs": "lbfgs", +# Script basenames carry variant suffixes that are not part of the sampler's +# name: `nautilus_jax_mlp` is a Nautilus prototype, `Nautilus_jax` a Nautilus +# integration script. Stripped repeatedly from the right, so stacked variants +# (`_jax_mlp`) collapse to the family. +VARIANT_SUFFIXES = ("_simple", "_jax", "_jit", "_grad", "_mlp", "_profile", + "_sweep") +# A prototype stem that names a family rather than one exported class. Every +# other stem matches an exported class by case-insensitive equality. +PROTOTYPE_ALIASES = { + "dynesty": ("DynestyStatic", "DynestyDynamic"), + "nuts": ("BlackJAXNUTS",), } def family_of(name: str) -> str: + """Lower-cased stem with every trailing variant suffix removed.""" base = name.lower() - for suf in VARIANT_SUFFIXES: - base = base.removesuffix(suf) - return ALIASES.get(base, base) + while True: + for suf in VARIANT_SUFFIXES: + if base.endswith(suf) and len(base) > len(suf): + base = base[: -len(suf)] + break + else: + return base def _py_stems(directory: Path) -> list[str]: @@ -51,33 +60,94 @@ def tier_minimal(developer: Path) -> list[str]: return _py_stems(developer / "searches_minimal") -def tier_archive(developer: Path) -> list[str]: +def tier_archive(developer: Path, promoted_classes=()) -> list[str]: + """Removed-sampler archive directories, minus any that are promoted. + + A search can be archived and later re-mainlined; its archive copy is then + superseded, and listing it here would count one search in two tiers. + """ root = developer / "searches" if not root.is_dir(): return [] + live = {c.lower() for c in promoted_classes} return sorted(d.name for d in root.iterdir() - if d.is_dir() and not d.name.startswith(("_", "."))) + if d.is_dir() and not d.name.startswith(("_", ".")) + and d.name.lower() not in live) def tier_integration(test: Path) -> list[str]: return _py_stems(test / "scripts" / "searches") -def tier_promoted(autofit: Path) -> list[str]: - """Package inventory: autofit/non_linear/search///.""" - root = autofit / "autofit" / "non_linear" / "search" - if not root.is_dir(): - return [] - out = [] - for group in sorted(root.iterdir()): - if not group.is_dir() or group.name.startswith("_"): - continue - for pkg in sorted(group.iterdir()): - if pkg.is_dir() and not pkg.name.startswith("_"): - out.append(f"{group.name}/{pkg.name}") +_SEARCH_PKG = "non_linear.search." + + +def _search_location(module: str) -> str | None: + """`/` for a concrete search module, else None. + + A concrete search lives at `non_linear.search..[...].search[...]` + (e.g. `mcmc.blackjax.nuts.search`, `nest.dynesty.search.static`). Helpers in + the same tree (`abstract_search`, `mcmc.auto_correlations`, + `mle.multi_start_gradient.convergence`) have no `search` segment below the + group and are not searches. + """ + module = module.removeprefix("autofit.") + if not module.startswith(_SEARCH_PKG): + return None + parts = module[len(_SEARCH_PKG):].split(".") + if len(parts) < 3 or "search" not in parts[2:]: + return None + return f"{parts[0]}/{parts[1]}" + + +def exported_searches(autofit: Path) -> dict[str, str]: + """{class name: `/`} for every search `autofit` exports. + + Parsed (never imported) from `autofit/__init__.py`: the eager + `from .non_linear.search... import X` lines plus the `_LAZY_ATTRS` table, + which is how optional-dependency searches (NSS, SMC) are exported. Keyed on + the exported class, not the module directory, because one directory can + hold several searches (`mle/bfgs`: BFGS + LBFGS; `mcmc/blackjax`: + BlackJAXNUTS + SMC; `mle/multi_start_gradient`: four MultiStart*). + """ + init = autofit / "autofit" / "__init__.py" + if not init.is_file(): + return {} + try: + tree = ast.parse(init.read_text(encoding="utf-8", errors="replace")) + except SyntaxError: + return {} + out: dict[str, str] = {} + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module: + loc = _search_location(node.module) + if loc: + for alias in node.names: + out[alias.asname or alias.name] = loc + targets = [] + if isinstance(node, ast.Assign): + targets = [t.id for t in node.targets if isinstance(t, ast.Name)] + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + targets = [node.target.id] + if "_LAZY_ATTRS" in targets and isinstance(node.value, ast.Dict): + for key, val in zip(node.value.keys, node.value.values): + if not (isinstance(key, ast.Constant) + and isinstance(val, ast.Tuple) and val.elts + and isinstance(val.elts[0], ast.Constant) + and isinstance(val.elts[0].value, str)): + continue + loc = _search_location(val.elts[0].value) + if loc: + out[key.value] = loc return out +def tier_promoted(autofit: Path) -> list[str]: + """Exported search classes as `//`.""" + return sorted(f"{loc}/{cls}" + for cls, loc in exported_searches(autofit).items()) + + # -------------------------------------------------------------------------- # The findings maturation lane (AGENTS.md "Judgment: the maturation lane") # -------------------------------------------------------------------------- @@ -201,18 +271,28 @@ def benchmarks(developer: Path) -> dict: def gaps(minimal, integration, promoted) -> list[str]: - """Tier-mismatch findings, phrased for the consulting conductor.""" - min_fams = {family_of(n) for n in minimal} - int_fams = {family_of(n) for n in integration} - pro_fams = {family_of(n.split("/", 1)[1]) for n in promoted} + """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. + """ + 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} out = [] - for fam in sorted(min_fams - pro_fams): - out.append(f"'{fam}' is prototyped in searches_minimal but has no " - f"PyAutoFit implementation — promotion candidate") - for fam in sorted(pro_fams - int_fams): - out.append(f"promoted search '{fam}' has no " - f"autofit_workspace_test/scripts/searches integration " - f"script") + for fam in sorted({family_of(n) for n in minimal}): + names = PROTOTYPE_ALIASES.get(fam, (fam,)) + if not any(n.lower() in by_lower for n in names): + out.append(f"'{fam}' is prototyped in searches_minimal but has no " + f"PyAutoFit implementation — promotion candidate") + for cls in sorted(classes): + if cls.lower() not in covered: + out.append(f"promoted search '{cls}' has no " + f"autofit_workspace_test/scripts/searches integration " + f"script") return out @@ -234,7 +314,7 @@ def digest(autofit, developer, test, lens_developer=None, inference=None) -> dic d["surfaces_present"].append("autofit_workspace_developer") minimal = tier_minimal(developer) d["tiers"]["minimal (searches_minimal)"] = minimal - d["tiers"]["archive (searches)"] = tier_archive(developer) + d["tiers"]["archive (searches)"] = [] # filled once promoted is known d["benchmarks"] = benchmarks(developer) if test and test.is_dir(): d["surfaces_present"].append("autofit_workspace_test") @@ -243,7 +323,10 @@ def digest(autofit, developer, test, lens_developer=None, inference=None) -> dic if autofit and autofit.is_dir(): d["surfaces_present"].append("PyAutoFit") promoted = tier_promoted(autofit) - d["tiers"]["promoted (autofit/non_linear/search)"] = promoted + d["tiers"]["promoted (autofit exports)"] = promoted + if "archive (searches)" in d["tiers"]: + d["tiers"]["archive (searches)"] = tier_archive( + developer, [row.rsplit("/", 1)[-1] for row in promoted]) if lens_developer and lens_developer.is_dir(): d["surfaces_present"].append(SURFACE_LENS_DEVELOPER) d["tiers"][TIER_LENS_PROBES] = tier_lens_probes(lens_developer) diff --git a/tests/test_samplers_surface.py b/tests/test_samplers_surface.py index ef56e006..23c6fb68 100644 --- a/tests/test_samplers_surface.py +++ b/tests/test_samplers_surface.py @@ -143,3 +143,99 @@ def test_empty_mature_surface_yields_no_cells(tmp_path): (empty / "scripts" / "imaging" / "likelihood_runtime" / "mge.py").write_text("x = 1\n") d = _digest("--inference", str(empty)) assert d["tiers"][_samplers.TIER_LENS_MATURE] == [] + + +# -------------------------------------------------------------------------- +# The tier-gap rule, keyed on exported class names +# -------------------------------------------------------------------------- + +_AUTOFIT_INIT = '''\ +from .non_linear.search.abstract_search import NonLinearSearch +from .non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings +from .non_linear.search.mcmc.blackjax.nuts.search import BlackJAXNUTS +from .non_linear.search.nest.nautilus.search import Nautilus +from .non_linear.search.nest.dynesty.search.static import DynestyStatic +from .non_linear.search.mle.drawer.search import Drawer +from .non_linear.search.mle.bfgs.search import BFGS +from .non_linear.search.mle.bfgs.search import LBFGS +from .non_linear.search.mle.multi_start_gradient.search import MultiStartAdam +from .non_linear.search.mle.multi_start_gradient.search import MultiStartLion +from .non_linear.search.mle.multi_start_gradient.convergence import ( + ConvergenceSettings, +) + +_LAZY_ATTRS = { + "NSS": ("autofit.non_linear.search.nest.nss.search", "NSS"), + "SMC": ("autofit.non_linear.search.mcmc.blackjax.smc.search", "SMC"), + "Aggregator": ("autofit.database.aggregator", "Aggregator"), + "db": ("autofit.database", None), +} +''' + + +def _make_fit_family(root: Path) -> dict: + """Library + developer + test checkouts reproducing every live trap: one + module dir holding several classes (bfgs, blackjax, multi_start_gradient), + lazily exported searches, an archived search that was re-mainlined, and + prototype stems with stacked variant suffixes.""" + autofit = root / "PyAutoFit" + (autofit / "autofit").mkdir(parents=True) + (autofit / "autofit" / "__init__.py").write_text(_AUTOFIT_INIT) + developer = root / "developer" + for name in ("nss", "pyswarms"): + (developer / "searches" / name).mkdir(parents=True) + minimal = developer / "searches_minimal" + minimal.mkdir(parents=True) + for stem in ("nautilus_simple", "nautilus_jax_mlp", "nautilus_profile", + "nautilus_sweep", "dynesty_simple", "nuts_jax", + "cmaes_simple"): + (minimal / f"{stem}.py").write_text("# prototype\n") + test = root / "test" + searches = test / "scripts" / "searches" + searches.mkdir(parents=True) + for stem in ("BlackJAXNUTS", "Nautilus_jax", "DynestyStatic", "LBFGS", + "MultiStartAdam", "MultiStartResurrect", "NSS", "__init__"): + (searches / f"{stem}.py").write_text("# integration\n") + return {"autofit": autofit, "developer": developer, "test": test} + + +def test_promoted_tier_is_keyed_on_exported_classes(tmp_path): + autofit = _make_fit_family(tmp_path)["autofit"] + assert _samplers.exported_searches(autofit) == { + "BlackJAXNUTS": "mcmc/blackjax", "SMC": "mcmc/blackjax", + "Nautilus": "nest/nautilus", "DynestyStatic": "nest/dynesty", + "NSS": "nest/nss", "Drawer": "mle/drawer", "BFGS": "mle/bfgs", + "LBFGS": "mle/bfgs", "MultiStartAdam": "mle/multi_start_gradient", + "MultiStartLion": "mle/multi_start_gradient", + } + + +def test_family_of_strips_stacked_variant_suffixes(): + assert _samplers.family_of("nautilus_jax_mlp") == "nautilus" + assert _samplers.family_of("nautilus_profile") == "nautilus" + assert _samplers.family_of("nautilus_sweep") == "nautilus" + assert _samplers.family_of("Nautilus_jax") == "nautilus" + assert _samplers.family_of("MultiStartAdam") == "multistartadam" + + +def test_gap_rule_reports_only_true_gaps(tmp_path): + paths = _make_fit_family(tmp_path) + d = _digest("--autofit", str(paths["autofit"]), + "--developer", str(paths["developer"]), + "--test", str(paths["test"])) + gaps = d["gaps"] + missing = sorted(g.split("'")[1] for g in gaps + if "integration script" in g) + # SMC shares mcmc/blackjax with BlackJAXNUTS and BFGS shares mle/bfgs with + # LBFGS — a directory-keyed rule hid both. MultiStartAdam.py covers its + # class, so the multi_start_gradient directory is no longer a false + # positive; MultiStartLion, with no script, is a true gap. + assert missing == ["BFGS", "Drawer", "MultiStartLion", "SMC"] + candidates = sorted(g.split("'")[1] for g in gaps + if "promotion candidate" in g) + # nautilus variants collapse onto the exported class; only the genuinely + # unpromoted prototype remains + assert candidates == ["cmaes"] + # 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 From da631b6dacfc6e94a1b7f64c9406de58ec60e94f Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 8 Oct 2026 08:58:19 +0100 Subject: [PATCH 2/2] tests: neutral fixture directory name so the tenant firewall stays clean The samplers-surface fixture named its fake library checkout 'PyAutoFit', which the firewall counts as an instance fact in an unlisted file. Co-Authored-By: Claude Fable 5.1 --- tests/test_samplers_surface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_samplers_surface.py b/tests/test_samplers_surface.py index 23c6fb68..93cac216 100644 --- a/tests/test_samplers_surface.py +++ b/tests/test_samplers_surface.py @@ -178,7 +178,7 @@ def _make_fit_family(root: Path) -> dict: module dir holding several classes (bfgs, blackjax, multi_start_gradient), lazily exported searches, an archived search that was re-mainlined, and prototype stems with stacked variant suffixes.""" - autofit = root / "PyAutoFit" + autofit = root / "library" (autofit / "autofit").mkdir(parents=True) (autofit / "autofit" / "__init__.py").write_text(_AUTOFIT_INIT) developer = root / "developer"