diff --git a/CLAUDE.md b/CLAUDE.md index 69f7fe2..694d1f6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,6 @@ uv run pytest # all Python tests uv run pytest tests/unit/test_native.py::test_version_matches_the_package uv run pytest tests/corpus # every committed fixture and its answer key uv run pytest tests/corpus/test_native_agrees_with_validator.py # Rust geometry against the validator -uv run pytest -m "not slow" # without the whole searches that take tens of seconds uv run pytest -m "not source" # without the tropical-puzzle-lab checkout HYPOTHESIS_PROFILE=ci uv run pytest # the derandomized, larger property runs CI uses uv run ruff check && uv run ruff format --check @@ -94,7 +93,7 @@ Rules: - **Search rules are switches, and the measurement is the product.** The question is what makes a puzzle hard and what helps, not how fast a solver is. A pruning rule, an ordering or a symmetry reduction added to a solver is an option that can be turned off, is tested not to change what the whole search finds, and gets its row in the ablation table of `docs/algorithms.md`. A rule that costs more than it saves stays, switched off, with its numbers. - **Experiments are callers.** `experiments/` goes through `api.solve` like any user, and nothing outside it imports it. Only `experiments/plotting.py` imports matplotlib; running a manifest needs no plotting stack. - **A committed table has no times.** `benchmarks/results/*.md` are written with `--no-times`: statuses and counts, which a deterministic solver reproduces exactly and a test compares. Times, CP-SAT's own counts and the `.jsonl` records belong to a machine and are not committed. When a solver change moves a count, regenerate the table with the command and say why in the commit. -- **Slow tests still run.** The `slow` marker is for deselecting locally (`-m "not slow"`); CI runs everything. +- **The suite does not run million-node searches.** The footprints in `corpus.EXPENSIVE` (`tests/support/corpus.py`: `cor1-flat`, `new1-flat`, `new2-flat`) are left out of the per-fixture tests, and the table tests reproduce every other row with `maxplus-bench run --only`. Their rows are checked against a search only by running the full command, so a solver change that could move them means running it by hand. There is no `slow` marker; a test that needs one is a test to make smaller. - **Completeness and uniqueness are explicit claims.** A result says whether the search was exhaustive and over which candidate set. "No solution found" and CP-SAT `INFEASIBLE` are relative to the candidates generated unless completeness is proven. - **Layering is one-way:** core ← geometry ← search ← py. Python reaches Rust only through `_native`. - **Production solvers cross the Python/Rust boundary once per solve.** Prototypes may call individual geometry primitives; a Rust solver receives the instance and runs to completion. `cp_sat.placements` makes its one call for the list of placements and their conflicts; everything it then needs, down to which placement a tray rotation turns each into, is in that answer. diff --git a/benchmarks/manifests/corpus.toml b/benchmarks/manifests/corpus.toml index 2ea4e4a..3679c08 100644 --- a/benchmarks/manifests/corpus.toml +++ b/benchmarks/manifests/corpus.toml @@ -5,7 +5,8 @@ The two searches that would not end, cor1-flat's, stop at a node limit well abov any other corpus puzzle needs (new1-flat: 1 064 878), so that where they stop does not depend on the machine. `maxplus-bench run benchmarks/manifests/corpus.toml --no-times` reproduces -benchmarks/results/corpus.md; a test holds the two together. +benchmarks/results/corpus.md; a test holds the two together on every fixture but the +expensive footprints (tests/support/corpus.py), whose rows only this command checks. """ fixtures = ["corpus"] diff --git a/benchmarks/manifests/edge_to_edge.toml b/benchmarks/manifests/edge_to_edge.toml index 9217438..002dfd9 100644 --- a/benchmarks/manifests/edge_to_edge.toml +++ b/benchmarks/manifests/edge_to_edge.toml @@ -4,7 +4,9 @@ What the edge-to-edge assumption is worth. Every corpus puzzle is searched to it rust.contact_dfs in its own regime, assuming nothing and assuming that the pieces meet edge to edge, and under the assumption with each of its two rules on and off. `maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times` reproduces -benchmarks/results/edge_to_edge.md; a test holds the two together. Rows that assume +benchmarks/results/edge_to_edge.md; a test holds the two together on every fixture but +the expensive footprints (tests/support/corpus.py), whose rows only this command +checks. Rows that assume nothing are the corpus table's, for comparison; rows under the assumption answer a narrower question and are not comparable with them. As there, a search that assumes nothing stops at 1 500 000 nodes: only cor1-flat's reaches the limit. diff --git a/docs/experiments.md b/docs/experiments.md index eee1a49..9f8e7ee 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14,9 +14,9 @@ uv run maxplus-bench table benchmarks/results/corpus.jsonl # the tab uv run maxplus-bench proxies --results benchmarks/results/corpus.jsonl # difficulty proxies and rank correlations ``` -`run` writes one JSON line per run to `benchmarks/results/.jsonl` (`--out` to choose), prints the table, and with `--table FILE` writes it too. It exits with 1 if any run could not be made. `--no-times` leaves out times and CP-SAT's own counts, which depend on the machine and the OR-Tools build; what is left is reproduced exactly by a deterministic solver. +`run` writes one JSON line per run to `benchmarks/results/.jsonl` (`--out` to choose), prints the table, and with `--table FILE` writes it too. It exits with 1 if any run could not be made. `--no-times` leaves out times and CP-SAT's own counts, which depend on the machine and the OR-Tools build; what is left is reproduced exactly by a deterministic solver. `--only FIXTURE...` runs a manifest on some of its fixtures, every run on them unchanged: its table is the full table's rows for those fixtures. -`benchmarks/results/corpus.md` is the committed table of the corpus manifest: every registered solver on every corpus puzzle it can run. The command above reproduces it, and `tests/corpus/test_benchmark.py` holds that. The `.jsonl` files are not committed. +`benchmarks/results/corpus.md` is the committed table of the corpus manifest: every registered solver on every corpus puzzle it can run. The command above reproduces it. `tests/corpus/test_benchmark.py` reproduces all of it but the rows of the footprints that take a million nodes or more (`cor1-flat`, `new1-flat`, `new2-flat`) and of `rat2-flat`, where CP-SAT takes over a minute: it runs the command `--only` on the rest and compares those rows exactly. The rows it leaves out are checked only by running the full command, about six minutes; the test reads them to hold them to what the documents say of them. The `.jsonl` files are not committed. Needs the `validate` extra for the validity columns and the `cp-sat` extra for `cp_sat.placements`. A run whose solver cannot be loaded is recorded as an error and the rest go on. @@ -252,7 +252,7 @@ Correlations are taken within a regime only. Across both, any number that differ ## Edge to edge -`maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times` reproduces `benchmarks/results/edge_to_edge.md`: every corpus puzzle in its own regime, assuming nothing and assuming that the pieces meet edge to edge, with the assumption's two rules crossed. A manifest says `assume = "edge-to-edge"`, or a list with `"none"` to cross it with the other factors; the table then shows an `assumes` column on every row. What the numbers say is in [algorithms.md](algorithms.md#assuming-the-pieces-meet-edge-to-edge): the footprints that took up to a million nodes take 14 to 80, fewer than their relief twins took assuming nothing, and of `rat1-flat`'s 101 assemblies and `rat2-flat`'s 2 only the answer has no T. `cor1` stays hard under it: 967 nodes with its roofs, and 44 539 and 48 assemblies without them, where the search that assumes nothing does not end. +`maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times` reproduces `benchmarks/results/edge_to_edge.md` (the test reproduces all but the rows of `cor1-flat`, `new1-flat` and `new2-flat`, as for the corpus table): every corpus puzzle in its own regime, assuming nothing and assuming that the pieces meet edge to edge, with the assumption's two rules crossed. A manifest says `assume = "edge-to-edge"`, or a list with `"none"` to cross it with the other factors; the table then shows an `assumes` column on every row. What the numbers say is in [algorithms.md](algorithms.md#assuming-the-pieces-meet-edge-to-edge): the footprints that took up to a million nodes take 14 to 80, fewer than their relief twins took assuming nothing, and of `rat1-flat`'s 101 assemblies and `rat2-flat`'s 2 only the answer has no T. `cor1` stays hard under it: 967 nodes with its roofs, and 44 539 and 48 assemblies without them, where the search that assumes nothing does not end. `proxies.static(instance, edge_to_edge=True)` gives the edge-graph proxies under the assumption: mean degree 0.8 to 2.4 on the footprints, against 23 to 84 without it. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3836e5c..7c3d4dc 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -204,6 +204,14 @@ Done, with these decisions: - `cor1` joined the corpus in this phase, re-imported from Tropical Puzzle Lab's main branch, so the corpus is 18 fixtures. `cor1-flat` is the first corpus puzzle whose plain search has not been seen to end. Tests that compare against the end of that search leave it out by name (`support.corpus.UNFINISHED`) and test it apart; the corpus and edge-to-edge manifests stop a search that assumes nothing at 1 500 000 nodes, well above the 1 064 878 of `new1-flat`, so where it stops does not depend on the machine. The exit criteria of phases 5 and 6 cover the corpus minus that one fixture. - Findings, in [algorithms.md](algorithms.md#assuming-the-pieces-meet-edge-to-edge): the 16-piece footprints drop from a million nodes to about fifty; footprint and relief costs nearly coincide; only the answer of `rat1-flat` and `rat2-flat` is edge to edge. +## Later change to the exit criteria: no million-node searches in the suite + +2026-11-15. The `slow` tests, nine whole searches run again and again, had grown to thirteen minutes, too long to be run. The exit criteria of phases 5 to 8 are narrowed rather than run less often: + +- `support.corpus.EXPENSIVE` names the footprints whose whole search costs 909 750 nodes or more: `cor1-flat`, `new1-flat` and `new2-flat`. The exit criteria of phases 5 and 8 cover the corpus minus these; phase 6's also leaves out `rat2-flat`, where CP-SAT takes over a minute. +- The exit criterion of phase 7 and the table test of phase 8 run their manifest with `maxplus-bench run --only` on the other fixtures and compare those rows of the committed table exactly. The rows they leave out are read, not reproduced: a test holds them to what the documents claim of them (where `cor1-flat` stops, the margin under the node limit, one assembly where one is claimed). +- What is given up: no automated test searches `new1-flat` and `new2-flat` to the end. Their results stand in the committed tables, checked against a search only when the full command is run by hand. The `slow` marker is gone. + ## Backlog Unordered, to be scheduled once phase 7 shows where the interesting questions are: diff --git a/pyproject.toml b/pyproject.toml index 9418581..22dfcd6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,7 +66,6 @@ xfail_strict = true filterwarnings = ["error"] markers = [ "source: needs a checkout of tropical-puzzle-lab (skipped locally if absent, required in CI)", - "slow: takes more than a few seconds", ] [tool.ruff] diff --git a/python/maxplus_solvers/experiments/cli.py b/python/maxplus_solvers/experiments/cli.py index 37f90dd..be27d33 100644 --- a/python/maxplus_solvers/experiments/cli.py +++ b/python/maxplus_solvers/experiments/cli.py @@ -13,7 +13,7 @@ from typing import Any from maxplus_solvers.experiments import benchmark, proxies, report -from maxplus_solvers.experiments.manifest import ManifestError, load +from maxplus_solvers.experiments.manifest import ManifestError, load, restrict from maxplus_solvers.io.instance import load_instance DEFAULT_FIXTURES = Path("benchmarks") / "fixtures" @@ -38,6 +38,12 @@ def _parser() -> argparse.ArgumentParser: action="store_true", help="leave out times and other machine-dependent columns: the reproducible table", ) + run.add_argument( + "--only", + nargs="+", + metavar="FIXTURE", + help="run only these of the manifest's fixtures: the full table's rows for them", + ) run.add_argument("--quiet", action="store_true", help="do not report each run as it ends") table = commands.add_parser("table", help="print the table of a results file") @@ -159,6 +165,8 @@ def main(argv: Sequence[str] | None = None) -> int: try: if args.command == "run": manifest = load(args.manifest) + if args.only is not None: + manifest = restrict(manifest, args.only, benchmark.read_index(args.fixtures)) out = args.out or DEFAULT_RESULTS / f"{manifest.name}.jsonl" out.parent.mkdir(parents=True, exist_ok=True) records = benchmark.run( diff --git a/python/maxplus_solvers/experiments/manifest.py b/python/maxplus_solvers/experiments/manifest.py index 3636b55..b4410e9 100644 --- a/python/maxplus_solvers/experiments/manifest.py +++ b/python/maxplus_solvers/experiments/manifest.py @@ -30,7 +30,7 @@ import itertools import tomllib from collections.abc import Iterator, Mapping, Sequence -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any @@ -232,6 +232,22 @@ def fixture_ids(manifest: Manifest, index: Mapping[str, Any]) -> list[str]: return [fixture for fixture in known if fixture in wanted] +def restrict(manifest: Manifest, only: Sequence[str], index: Mapping[str, Any]) -> Manifest: + """The manifest with its fixtures cut down to ``only``, each of which it must name. + + Every run on those fixtures is kept as it is, so the table of the + restricted manifest is the full table's rows for those fixtures. + """ + named = fixture_ids(manifest, index) + missing = [fixture for fixture in only if fixture not in named] + if missing: + listed = ", ".join(repr(fixture) for fixture in missing) + raise ManifestError(f"only: {listed} not among the fixtures of manifest {manifest.name!r}") + if not only: + raise ManifestError("only: an empty list leaves nothing to run") + return replace(manifest, fixtures=tuple(only)) + + def expand(manifest: Manifest, fixtures: Sequence[str]) -> Iterator[Run]: """Every run of the manifest, in a fixed order: block, fixture, then the factors.""" for block in manifest.runs: diff --git a/tests/corpus/test_benchmark.py b/tests/corpus/test_benchmark.py index 50e04ad..b1ed02a 100644 --- a/tests/corpus/test_benchmark.py +++ b/tests/corpus/test_benchmark.py @@ -4,7 +4,10 @@ registered solver on every corpus puzzle and prints the table committed as ``benchmarks/results/corpus.md``. The table holds statuses, solution counts and search counts, which a deterministic solver reproduces exactly; times and -CP-SAT's own counts belong to a machine and are not in it. +CP-SAT's own counts belong to a machine and are not in it. The test runs the +same command ``--only`` on the fixtures that are cheap to search, and compares +their rows; the rows of the expensive footprints (``support/corpus.py``) are +checked by running the full command by hand. The other tests here hold the committed manifests to what the runner accepts, and the difficulty proxies to what can be said about them without a search. @@ -41,50 +44,72 @@ def by(records: list[dict[str, Any]], solver: str) -> dict[str, dict[str, Any]]: # --- the exit criterion ------------------------------------------------------------------- -@pytest.mark.slow def test_one_command_reproduces_the_corpus_table( tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: + """The committed table's rows, but for the footprints that are expensive to search. + + ``maxplus-bench run benchmarks/manifests/corpus.toml --no-times`` + reproduces the whole table; this runs the same manifest ``--only`` on the + rest and compares those rows exactly. Left out are the three footprints of a + million nodes, and ``rat2-flat``, where CP-SAT takes over a minute. + """ + cheap = [f for f in CORPUS if f not in corpus.EXPENSIVE_FOR_CP_SAT] + committed = (RESULTS / "corpus.md").read_text(encoding="utf-8") out, table = tmp_path / "corpus.jsonl", tmp_path / "corpus.md" arguments = ["run", str(MANIFESTS / "corpus.toml"), "--fixtures", str(corpus.FIXTURES)] - code = main([*arguments, "--out", str(out), "--table", str(table), "--no-times", "--quiet"]) - assert code == 0, "some run could not be made" + options = ["--out", str(out), "--table", str(table), "--no-times", "--quiet"] + assert main([*arguments, *options, "--only", *cheap]) == 0, "some run could not be made" produced = table.read_text(encoding="utf-8") assert capsys.readouterr().out == produced - assert produced == (RESULTS / "corpus.md").read_text(encoding="utf-8") + assert produced == corpus.table_rows(committed, cheap) records = benchmark.read(out) - # The whole corpus, across all registered solvers. + # Those fixtures, across all registered solvers. assert {record["solver"] for record in records} == set(solvers.available()) - assert sorted(by(records, "rust.contact_dfs")) == sorted(CORPUS) - assert sorted(by(records, "cp_sat.placements")) == sorted(CORPUS) - # The prototype's list was fixed before cor1 joined the corpus; it would stop there too. - assert sorted(by(records, "python.contact_dfs")) == sorted(set(FLAT) - corpus.UNFINISHED) + assert sorted(by(records, "rust.contact_dfs")) == sorted(cheap) + assert sorted(by(records, "cp_sat.placements")) == sorted(cheap) + assert sorted(by(records, "python.contact_dfs")) == sorted(set(FLAT) & set(cheap)) for record in records: - # Whatever was returned passes the validator. - assert record["status"] in ("solved", "interrupted"), record["fixture"] + # Every search here ends, and whatever was returned passes the validator. + assert record["status"] == "solved" and record["exhaustive"], record["fixture"] assert record["validSolutions"] == record["solutions"], record["fixture"] # Enough to run it again. assert record["solverVersion"] assert record["config"]["tolerances"]["contactNoiseMm"] > 0 assert record["config"]["seed"] == 0 assert record["instanceHash"] == HASHES[record["fixture"]] + + +def test_the_rows_the_suite_does_not_reproduce_say_what_the_documents_say() -> None: + """What the committed table claims of the whole corpus, read from it. + + Not a reproduction: only the full command checks the expensive rows against + a search. This holds the table to what the manifest and the documents say + of it. + """ + rows = corpus.table((RESULTS / "corpus.md").read_text(encoding="utf-8")) + nodes = {(r["Solver"], r["Fixture"]): int(r["Nodes"].replace(" ", "")) for r in rows} + for row in rows: + assert row["Solutions"] == row["Valid"], (row["Solver"], row["Fixture"]) # The two production solvers finish everything but cor1-flat, stopped at the node # limit before it found anything; the prototype is stopped on the largest. - for solver in ("rust.contact_dfs", "cp_sat.placements"): - results = by(records, solver) - unfinished = sorted(f for f, record in results.items() if not record["exhaustive"]) + for solver in ("`rust.contact_dfs`", "`cp_sat.placements`"): + mine = [row for row in rows if row["Solver"] == solver] + assert sorted(row["Fixture"] for row in mine) == sorted(CORPUS) + unfinished = sorted(row["Fixture"] for row in mine if row["Whole search"] == "no") assert unfinished == sorted(corpus.UNFINISHED), solver for fixture in unfinished: - assert results[fixture]["status"] == "interrupted" - assert results[fixture]["metrics"]["nodes"] == NODE_LIMIT + assert nodes[solver, fixture] == NODE_LIMIT # The limit is far above what any finished search needed. - finished = [r["metrics"]["nodes"] for f, r in results.items() if f not in unfinished] + finished = [nodes[solver, row["Fixture"]] for row in mine if row["Whole search"] == "yes"] assert max(finished) < NODE_LIMIT / 1.4 - prototype = by(records, "python.contact_dfs") - stopped = [fixture for fixture, record in prototype.items() if not record["exhaustive"]] - assert sorted(stopped) == ["new1-flat", "new2-flat", "rat2-flat"] - assert all(prototype[fixture]["metrics"]["nodes"] == 50_000 for fixture in stopped) + prototype = [row for row in rows if row["Solver"] == "`python.contact_dfs`"] + # The prototype's list was fixed before cor1 joined the corpus; it would stop there too. + assert sorted(row["Fixture"] for row in prototype) == sorted(set(FLAT) - corpus.UNFINISHED) + stopped = sorted(row["Fixture"] for row in prototype if row["Whole search"] == "no") + assert stopped == ["new1-flat", "new2-flat", "rat2-flat"] + assert all(nodes["`python.contact_dfs`", fixture] == 50_000 for fixture in stopped) def test_the_committed_table_is_the_reproducible_kind() -> None: diff --git a/tests/corpus/test_cp_sat.py b/tests/corpus/test_cp_sat.py index f072bb5..260d1af 100644 --- a/tests/corpus/test_cp_sat.py +++ b/tests/corpus/test_cp_sat.py @@ -5,7 +5,9 @@ are compared polygon by polygon with the test oracle. Both exhaust on every fixture but ``cor1-flat``, added after the phase closed, whose search has not been seen to end; CP-SAT lists its placements with that search, so it is left -out by name. +out by name. So are ``new1-flat``, ``new2-flat`` and ``rat2-flat``, which both +exhaust but at a cost of minutes: that they agree there is recorded in the +committed corpus table, which only the full command reproduces. The agreement is less than it sounds and more than nothing. CP-SAT chooses among the placements a run of the same search listed, so it cannot find an @@ -35,18 +37,13 @@ RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") SYNTHETIC = corpus.fixture_ids(kind="synthetic") SMALL = [f for f in FLAT if PIECES[f] <= 11] -# Listing the placements of these is a whole search of tens of seconds, and the -# model has thousands of them. -SLOW = {"new1-flat", "new2-flat", "rat2-flat"} +# Listing the placements of these is a whole search of up to a million nodes, and the +# model has thousands of them: not run here (support/corpus.py). Their rows of the +# committed corpus table are where the two solvers' agreement on them is recorded. +LEFT_OUT = corpus.EXPENSIVE_FOR_CP_SAT +CHECKED = [f for f in CORPUS if f not in LEFT_OUT] # As in test_rust_contact_dfs.py. Not in this table: one. -ASSEMBLIES = {"rat1-flat": 101, "rat2-flat": 2} - - -def marked(fixture_ids: list[str]) -> list[Any]: - return [ - pytest.param(f, marks=pytest.mark.slow) if f in SLOW else pytest.param(f) - for f in fixture_ids - ] +ASSEMBLIES = {"rat1-flat": 101} def instance_of(fixture_id: str) -> PuzzleInstance: @@ -86,13 +83,15 @@ def alike(x: Any, y: Any) -> bool: def test_the_exit_criterion_covers_every_fixture() -> None: assert len(EVERY) == 18 and len(CORPUS) == 17 and len(SYNTHETIC) == 4 assert sorted(set(EVERY) - set(CORPUS)) == ["cor1-flat"] - assert set(FLAT) >= SLOW | set(ASSEMBLIES) + # Only footprints are left out, only those named, and all of the relief puzzles stay. + assert sorted(set(CORPUS) - set(CHECKED)) == ["new1-flat", "new2-flat", "rat2-flat"] + assert set(CHECKED) >= set(RELIEF) | set(ASSEMBLIES) # --- the exit criterion ------------------------------------------------------------------- -@pytest.mark.parametrize("fixture_id", marked(CORPUS + SYNTHETIC)) +@pytest.mark.parametrize("fixture_id", CHECKED + SYNTHETIC) def test_cp_sat_and_the_search_return_the_same_assemblies(fixture_id: str) -> None: instance = instance_of(fixture_id) chosen = solve(instance, whole(instance.regime), validate=True) @@ -182,7 +181,7 @@ def test_without_the_anchor_the_turns_are_found_and_recognised() -> None: # --- what the model looks like ------------------------------------------------------------ -@pytest.mark.parametrize("fixture_id", [f for f in CORPUS if f not in SLOW]) +@pytest.mark.parametrize("fixture_id", CHECKED) def test_the_list_is_far_shorter_than_the_search_that_made_it(fixture_id: str) -> None: """A finding: the search puts the same few placements down again and again. diff --git a/tests/corpus/test_edge_to_edge.py b/tests/corpus/test_edge_to_edge.py index ece34db..c112c63 100644 --- a/tests/corpus/test_edge_to_edge.py +++ b/tests/corpus/test_edge_to_edge.py @@ -12,8 +12,12 @@ (``support.geometry.is_edge_to_edge``, by twin edges) calls edge to edge; the answer key is among it and the validator passes all of it. ``cor1-flat``, whose plain search has not been seen to end, is tested apart: everything the assumed -search returns is valid and edge to edge by the oracle, and the key is among it. The counts are -relative to the candidates the search generates, in ``f64`` with tolerances. +search returns is valid and edge to edge by the oracle, and the key is among it. +``new1-flat`` and ``new2-flat``, whose plain searches take a million nodes, are +not compared here; their rows of the committed table, which only the full +command reproduces, record one assembly with and without the assumption. The +counts are relative to the candidates the search generates, in ``f64`` with +tolerances. """ from pathlib import Path @@ -50,8 +54,9 @@ EDGE_TO_EDGE_ASSEMBLIES = {"cor1-flat": 48} # Where a search assuming nothing stops in the committed table (benchmarks/manifests). NODE_LIMIT = 1_500_000 -# Whole plain searches of these take tens of seconds. -SLOW = {"new1-flat", "new2-flat"} +# Whole plain searches of these are a million nodes each: not run here (support/corpus.py). +LEFT_OUT = corpus.EXPENSIVE - corpus.UNFINISHED +CHECKED = [f for f in CORPUS if f not in LEFT_OUT] RULES = [ {"equal_edges": True, "wall_edges": True}, {"equal_edges": True, "wall_edges": False}, @@ -60,13 +65,6 @@ ] -def marked(fixture_ids: list[str]) -> list[Any]: - return [ - pytest.param(f, marks=pytest.mark.slow) if f in SLOW else pytest.param(f) - for f in fixture_ids - ] - - def instance_of(fixture_id: str) -> PuzzleInstance: return PuzzleInstance.from_dict(corpus.fixture(fixture_id)) @@ -91,7 +89,11 @@ def test_every_answer_key_meets_edge_to_edge() -> None: assert geometry.is_edge_to_edge(world, target, TWIN_MM), fixture_id -@pytest.mark.parametrize("fixture_id", marked(CORPUS)) +def test_only_the_million_node_footprints_are_left_out() -> None: + assert sorted(set(EVERY) - set(CHECKED)) == ["cor1-flat", "new1-flat", "new2-flat"] + + +@pytest.mark.parametrize("fixture_id", CHECKED) def test_the_assumption_finds_exactly_the_edge_to_edge_assemblies(fixture_id: str) -> None: instance = instance_of(fixture_id) plain = solve(instance, SolverConfig(DFS, mode=instance.regime, max_solutions=None)) @@ -162,31 +164,61 @@ def test_the_footprints_with_several_assemblies_have_one_that_meets_edge_to_edge # --- the committed table and the edge graph ----------------------------------------------- -@pytest.mark.slow def test_one_command_reproduces_the_edge_to_edge_table( tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: + """The committed table's rows, but for the footprints whose plain search is expensive. + + ``maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times`` + reproduces the whole table; this runs the same manifest ``--only`` on the + rest and compares those rows exactly. + """ + cheap = [f for f in EVERY if f not in corpus.EXPENSIVE] + committed = (RESULTS / "edge_to_edge.md").read_text(encoding="utf-8") out, table = tmp_path / "edge_to_edge.jsonl", tmp_path / "edge_to_edge.md" arguments = ["run", str(MANIFESTS / "edge_to_edge.toml"), "--fixtures", str(corpus.FIXTURES)] - code = main([*arguments, "--out", str(out), "--table", str(table), "--no-times", "--quiet"]) - assert code == 0, "some run could not be made" + options = ["--out", str(out), "--table", str(table), "--no-times", "--quiet"] + assert main([*arguments, *options, "--only", *cheap]) == 0, "some run could not be made" produced = table.read_text(encoding="utf-8") assert capsys.readouterr().out == produced - assert produced == (RESULTS / "edge_to_edge.md").read_text(encoding="utf-8") + assert produced == corpus.table_rows(committed, cheap) records = benchmark.read(out) - # Each corpus puzzle once assuming nothing, and four times assuming edge to edge. - assert len(records) == 5 * len(EVERY) + # Each puzzle once assuming nothing, and four times assuming edge to edge. + assert len(records) == 5 * len(cheap) for record in records: fixture, assumed = record["fixture"], bool(record["config"]["assumptions"]) - if fixture in corpus.UNFINISHED and not assumed: - assert record["status"] == "interrupted" and not record["exhaustive"], fixture - assert record["metrics"]["nodes"] == NODE_LIMIT - continue assert record["status"] == "solved" and record["exhaustive"], fixture expected = (EDGE_TO_EDGE_ASSEMBLIES if assumed else ASSEMBLIES).get(fixture, 1) assert record["validSolutions"] == record["solutions"] == expected, fixture +def test_the_rows_the_suite_does_not_reproduce_say_what_the_documents_say() -> None: + """What the committed table claims for the expensive footprints, read from it. + + Not a reproduction: only the full command checks these numbers against a + search. This holds the table to the claims made of it in the documents. + """ + rows = [ + row + for row in corpus.table((RESULTS / "edge_to_edge.md").read_text(encoding="utf-8")) + if row["Fixture"] in corpus.EXPENSIVE + ] + assert len(rows) == 5 * len(corpus.EXPENSIVE) + for row in rows: + fixture, assumed = row["Fixture"], row["assumes"] == "edge-to-edge" + if fixture in corpus.UNFINISHED and not assumed: + assert (row["Status"], row["Whole search"], row["Solutions"]) == ( + "interrupted", + "no", + "0", + ) + assert int(row["Nodes"].replace(" ", "")) == NODE_LIMIT + continue + assert (row["Status"], row["Whole search"]) == ("solved", "yes"), fixture + expected = (EDGE_TO_EDGE_ASSEMBLIES if assumed else ASSEMBLIES).get(fixture, 1) + assert row["Solutions"] == row["Valid"] == str(expected), fixture + + @pytest.mark.parametrize("fixture_id", EVERY) def test_the_assumption_thins_the_edge_graph(fixture_id: str) -> None: """Without roofs an edge could lie against dozens of others; assuming edge to diff --git a/tests/corpus/test_rust_contact_dfs.py b/tests/corpus/test_rust_contact_dfs.py index 6939bde..6cee5b8 100644 --- a/tests/corpus/test_rust_contact_dfs.py +++ b/tests/corpus/test_rust_contact_dfs.py @@ -3,7 +3,9 @@ Each fixture is searched to the end in its own regime. That was all 16 when the phase closed; ``cor1``, added since, is searched to the end with its roofs and not without them, and ``cor1-flat`` is tested for what an unfinished search can -say. Every assembly returned +say. ``new1-flat`` and ``new2-flat``, a million nodes each, are no longer +searched here: their rows of the committed corpus table, which only the full +command reproduces, record that they end with the answer. Every assembly returned passes the independent validator, the answer key is among them, and the times to the first solution and to the end of the search are reported separately. On the fixtures the Python prototype can finish, the two solvers find the same @@ -44,8 +46,9 @@ SYNTHETIC = corpus.fixture_ids(kind="synthetic") # What the prototype finishes in seconds: the footprints of up to 11 pieces. SMALL = [f for f in FLAT if PIECES[f] <= 11] -# Whole searches of these take tens of seconds. -SLOW = {"new1-flat", "new2-flat"} +# Whole searches of these are a million nodes each: not run here (support/corpus.py). +LEFT_OUT = corpus.EXPENSIVE - corpus.UNFINISHED +CHECKED = [f for f in CORPUS if f not in LEFT_OUT] # Relief puzzles built to be hard for this search (cor1: level creases at shared heights). HARD_RELIEF = {"cor1"} @@ -54,13 +57,6 @@ ASSEMBLIES = {"rat1-flat": 101, "rat2-flat": 2} -def marked(fixture_ids: list[str]) -> list[Any]: - return [ - pytest.param(f, marks=pytest.mark.slow) if f in SLOW else pytest.param(f) - for f in fixture_ids - ] - - def instance_of(fixture_id: str) -> PuzzleInstance: return PuzzleInstance.from_dict(corpus.fixture(fixture_id)) @@ -102,13 +98,14 @@ def test_the_exit_criterion_covers_the_whole_corpus() -> None: assert sorted(set(EVERY) - set(CORPUS)) == sorted(corpus.UNFINISHED) == ["cor1-flat"] assert set(RELIEF) >= HARD_RELIEF assert sorted(SMALL) == ["new3-flat", "new4-flat", "new5-flat", "rat1-flat", "rev2-flat"] - assert set(FLAT) >= SLOW | set(ASSEMBLIES) + assert sorted(LEFT_OUT) == ["new1-flat", "new2-flat"] + assert set(CHECKED) >= set(RELIEF) | set(ASSEMBLIES) # --- the exit criterion ------------------------------------------------------------------- -@pytest.mark.parametrize("fixture_id", marked(CORPUS)) +@pytest.mark.parametrize("fixture_id", CHECKED) def test_every_fixture_is_solved_and_validated_in_its_own_regime(fixture_id: str) -> None: instance = instance_of(fixture_id) result = solve(instance, whole(instance.regime), validate=True) @@ -145,7 +142,7 @@ def test_every_fixture_is_solved_and_validated_in_its_own_regime(fixture_id: str assert metrics["exhausted_s"] == metrics["wall_time_s"] -@pytest.mark.parametrize("fixture_id", [f for f in CORPUS if f not in SLOW]) +@pytest.mark.parametrize("fixture_id", CHECKED) def test_the_first_solution_is_reported_before_the_search_is_finished(fixture_id: str) -> None: """Stopped at its first solution, the search claims a solution and nothing more.""" instance = instance_of(fixture_id) diff --git a/tests/support/corpus.py b/tests/support/corpus.py index d64ca12..c3db22c 100644 --- a/tests/support/corpus.py +++ b/tests/support/corpus.py @@ -6,6 +6,7 @@ import json import os +from collections.abc import Collection from pathlib import Path from typing import Any @@ -22,6 +23,15 @@ # that search leave these out by name, and test them separately for what can be said. UNFINISHED = frozenset({"cor1-flat"}) +# Corpus fixtures whose whole search, assuming nothing, the test suite does not run: +# 909 750 nodes and more (cor1-flat stops at the corpus manifest's limit of 1 500 000), +# against at most 128 230 for the rest (benchmarks/results/corpus.md). Run again and +# again across the tests they took over ten minutes. The suite reproduces the other rows +# of the committed tables; these rows are checked by running the full command by hand. +EXPENSIVE = frozenset({"cor1-flat", "new1-flat", "new2-flat"}) +# CP-SAT on rat2-flat: whole, but 80 s of choosing among its listed placements. +EXPENSIVE_FOR_CP_SAT = EXPENSIVE | {"rat2-flat"} + def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) @@ -48,6 +58,27 @@ def key(fixture_id: str) -> dict[str, Any]: return read_json(KEYS / f"{fixture_id}.json") +def _cells(line: str) -> list[str]: + return [cell.strip() for cell in line.strip().strip("|").split("|")] + + +def table(text: str) -> list[dict[str, str]]: + """The rows of a committed Markdown results table, by column title, ``Fixture`` bare.""" + lines = text.splitlines() + header = _cells(lines[0]) + rows = [dict(zip(header, _cells(line), strict=True)) for line in lines[2:]] + for row in rows: + row["Fixture"] = row["Fixture"].strip("`") + return rows + + +def table_rows(text: str, fixtures: Collection[str]) -> str: + """A committed Markdown results table cut down to its header and these fixtures' rows.""" + lines = text.splitlines(keepends=True) + kept = [line for line in lines[2:] if _cells(line)[0].strip("`") in fixtures] + return "".join(lines[:2] + kept) + + def schema() -> dict[str, Any]: return read_json(SCHEMA) diff --git a/tests/unit/test_experiments.py b/tests/unit/test_experiments.py index 3438305..fb9bc16 100644 --- a/tests/unit/test_experiments.py +++ b/tests/unit/test_experiments.py @@ -15,7 +15,14 @@ from maxplus_solvers import PuzzleInstance, SolverConfig, solve from maxplus_solvers.experiments import benchmark, proxies, report from maxplus_solvers.experiments.cli import main -from maxplus_solvers.experiments.manifest import ManifestError, expand, fixture_ids, load, parse +from maxplus_solvers.experiments.manifest import ( + ManifestError, + expand, + fixture_ids, + load, + parse, + restrict, +) from support import documents INDEX = { @@ -172,6 +179,38 @@ def test_a_fixture_nobody_has_is_refused() -> None: fixture_ids(parse(manifest_of(runs=[block])), INDEX) +def test_restricting_keeps_every_run_on_the_fixtures_kept() -> None: + """By hand: the manifest above names four runs; on ``toy`` alone, the last two.""" + manifest = parse( + manifest_of( + fixtures=["all"], + runs=[ + {"solver": "rust.contact_dfs"}, + {"solver": "python.contact_dfs", "fixtures": ["toy"]}, + ], + ) + ) + kept = restrict(manifest, ["toy"], INDEX) + assert [(r.solver, r.fixture) for r in expand(kept, fixture_ids(kept, INDEX))] == [ + ("rust.contact_dfs", "toy"), + ("python.contact_dfs", "toy"), + ] + # A block kept to fixtures that are all cut runs nothing. + kept = restrict(manifest, ["strips"], INDEX) + assert [(r.solver, r.fixture) for r in expand(kept, fixture_ids(kept, INDEX))] == [ + ("rust.contact_dfs", "strips"), + ] + + +def test_restricting_to_a_fixture_the_manifest_does_not_name_is_refused() -> None: + manifest = parse(manifest_of(fixtures=["corpus"])) + # "toy" is in the index but is synthetic, so the manifest does not name it. + with pytest.raises(ManifestError, match="'toy' not among the fixtures of manifest 'hand'"): + restrict(manifest, ["strips", "toy"], INDEX) + with pytest.raises(ManifestError, match="empty list"): + restrict(manifest, [], INDEX) + + def test_a_manifest_file_that_is_not_toml_says_where(tmp_path: Path) -> None: path = tmp_path / "broken.toml" path.write_text("name = \n", encoding="utf-8") @@ -540,6 +579,29 @@ def test_the_command_runs_a_manifest_and_prints_its_table( assert capsys.readouterr().out == table.read_text(encoding="utf-8") +def test_the_command_can_run_part_of_a_manifest( + fixtures_dir: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """``--only`` gives the full table's rows for the fixtures named, and nothing else.""" + manifest = write_manifest( + tmp_path, 'name = "hand"\nfixtures = ["corpus"]\n[[runs]]\nsolver = "rust.contact_dfs"\n' + ) + arguments = ["run", str(manifest), "--fixtures", str(fixtures_dir), "--no-times", "--quiet"] + assert main([*arguments, "--out", str(tmp_path / "all.jsonl")]) == 0 + full = capsys.readouterr().out.splitlines() + assert main([*arguments, "--out", str(tmp_path / "part.jsonl"), "--only", "strips"]) == 0 + part = capsys.readouterr().out.splitlines() + # A header, a rule and two rows; the first row is the flat strips'. + assert len(full) == 4 + assert part == full[:3] + assert part[2].startswith("| `strips` |") + + with pytest.raises(SystemExit) as stopped: + main([*arguments, "--out", str(tmp_path / "x.jsonl"), "--only", "toy"]) + assert stopped.value.code == 2 + assert "'toy' not among the fixtures" in capsys.readouterr().err + + def test_the_command_fails_when_a_run_could_not_be_made( fixtures_dir: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: