diff --git a/README.md b/README.md index 4167f0e7..1eb39b6c 100644 --- a/README.md +++ b/README.md @@ -278,15 +278,27 @@ concept alignment evidence, Axiom concept validation status, and stage-report validity. To build the downstream integration artifact Microcosm can inspect, merge -available source-package suites for a year into one bundle: +available source-package suites for a year into one bundle. Give each run its +own output directory: `--replace` deletes the directory first, so runs that +share an `--out` path delete each other's output. ```bash -uv run chronicle build-bundle --year 2023 --out /tmp/ledger-us-2023 --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --year 2023 --out "$RUN_DIR/ledger-us-2023" --slim ``` This writes a root `consumer_facts.jsonl`, `source_packages.json`, `coverage.json`, and `reports/build_bundle.json`. Source-specific suite outputs -remain nested under `sources//`. The bundle coverage report +remain nested under `sources//`. `--slim` deletes each suite's +`source_rows.jsonl`, `source_cells.jsonl`, `facts.jsonl` and `ledger.db` as soon +as that suite finishes and lists them in `reports/pruned_intermediates.json`. +Slim changes no file the bundle keeps: the merged and per-suite +`consumer_facts.jsonl`, `coverage.json`, `source_packages.json` and every +report match a full build's byte for byte, so `source_packages.json` and each +suite's `datapackage.json` still name the deleted files. Without `--slim`, the 2023 default bundle keeps tens of GB of +them: each BEA NIPA suite writes a 496 MB `source_rows.jsonl` and a 1 GB +`ledger.db` for under 100 KB of consumer facts. Leave `--slim` off only to +inspect those files, or build the one package with `build-suite`. The bundle coverage report includes counts by source, geography, entity, period, observed measure, and concept plus duplicate `aggregate_fact_key` and `semantic_fact_key` diagnostics. The row-level downstream contract is `consumer_facts.jsonl`; the other bundle @@ -311,8 +323,9 @@ For the UK source-package feed, build the curated UK suite and then a facts-only consumer artifact: ```bash -uv run chronicle build-bundle --suite uk --out /tmp/chronicle-uk --replace -uv run chronicle build-consumer-artifact --facts /tmp/chronicle-uk --out /tmp/chronicle-uk-artifact --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --suite uk --out "$RUN_DIR/chronicle-uk" --slim +uv run chronicle build-consumer-artifact --facts "$RUN_DIR/chronicle-uk" --out "$RUN_DIR/chronicle-uk-artifact" ``` The command writes a `policyengine_ledger.consumer_artifact.v2` artifact containing @@ -326,8 +339,9 @@ The US off-year bundle behavior is unchanged and out of scope here. The New Zealand feed builds the same way from the curated NZ suite: ```bash -uv run chronicle build-bundle --suite nz --out /tmp/chronicle-nz --replace -uv run chronicle build-consumer-artifact --facts /tmp/chronicle-nz --out /tmp/chronicle-nz-artifact --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --suite nz --out "$RUN_DIR/chronicle-nz" --slim +uv run chronicle build-consumer-artifact --facts "$RUN_DIR/chronicle-nz" --out "$RUN_DIR/chronicle-nz-artifact" ``` `NZ_BUNDLE_SOURCES` in `chronicle/bundle.py` lists every package under @@ -344,8 +358,9 @@ cannot be combined with `--source`. The Belgian feed builds from the curated BE suite: ```bash -uv run chronicle build-bundle --suite be --out /tmp/chronicle-be --replace -uv run chronicle build-consumer-artifact --facts /tmp/chronicle-be --out /tmp/chronicle-be-artifact --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --suite be --out "$RUN_DIR/chronicle-be" --slim +uv run chronicle build-consumer-artifact --facts "$RUN_DIR/chronicle-be" --out "$RUN_DIR/chronicle-be-artifact" ``` `BE_BUNDLE_SOURCES` in `chronicle/bundle.py` lists every package under the diff --git a/changelog.d/slim-bundle-intermediates.added.md b/changelog.d/slim-bundle-intermediates.added.md new file mode 100644 index 00000000..40e4b930 --- /dev/null +++ b/changelog.d/slim-bundle-intermediates.added.md @@ -0,0 +1 @@ +Add `chronicle build-bundle --slim` (`build_bundle(..., keep_suite_intermediates=False)`), which deletes each source suite's `source_rows.jsonl`, `source_cells.jsonl`, `facts.jsonl` and `ledger.db` as the suite finishes and lists them in `reports/pruned_intermediates.json`; slim mode changes no file the bundle keeps. The full-bundle test and the documented bundle commands use it, and the docs build each bundle in a fresh `mktemp -d` directory instead of a shared `/tmp` path. diff --git a/chronicle/bundle.py b/chronicle/bundle.py index a38aa556..063b0899 100644 --- a/chronicle/bundle.py +++ b/chronicle/bundle.py @@ -33,6 +33,17 @@ BUNDLE_COVERAGE_SCHEMA_VERSION = schema_id("bundle_coverage") BUNDLE_SOURCES_SCHEMA_VERSION = schema_id("bundle_sources") DEFAULT_BUNDLE_SOURCES = tuple(sorted(SOURCE_PACKAGE_ALIASES)) +# Per-source suite files that bundle assembly never reads back: it merges each +# suite's consumer_facts.jsonl and keeps its reports. A slim bundle +# (keep_suite_intermediates=False) deletes these as each suite finishes; the +# BEA NIPA suites alone write a 1 GB ledger.db each for under 100 KB of facts. +SUITE_INTERMEDIATE_FILES = ( + "source_rows.jsonl", + "source_cells.jsonl", + "facts.jsonl", + "ledger.db", +) +PRUNED_INTERMEDIATES_REPORT = "pruned_intermediates.json" UK_BUNDLE_SOURCE_PREFIXES = ( "desnz", "dfc_ni", @@ -829,8 +840,18 @@ def build_bundle( axiom_roots: Sequence[str | Path] = (), require_axiom_validation: bool = False, replace: bool = False, + keep_suite_intermediates: bool = True, ) -> BuildBundleReport: - """Build source-package suites and merge their consumer-contract facts.""" + """Build source-package suites and merge their consumer-contract facts. + + With ``keep_suite_intermediates=False`` each suite's + ``SUITE_INTERMEDIATE_FILES`` are deleted as soon as that suite finishes, + whether or not it built, and ``reports/pruned_intermediates.json`` lists + what was deleted. Slim mode changes no file the bundle keeps, so its + reports and sidecars still name or hash the deleted files + (tests/test_chronicle_bundle_slim.py compares every kept file with a full + build's, byte for byte). + """ build_created_at() # Refuse a malformed SOURCE_DATE_EPOCH before writing. output_path = Path(output_dir) _prepare_output_dir(output_path, replace=replace) @@ -865,6 +886,7 @@ def build_bundle( # for the default bundle's 1.74M rows, close to the runner's memory. The file # takes its final name once every package is in it; a failed build removes it. coverage_counts = _BundleCoverage() + pruned_suites: list[dict[str, Any]] = [] consumer_facts_path = output_path / "consumer_facts.jsonl" partial_facts_path = output_path / "consumer_facts.jsonl.partial" partial_facts_path.write_text("", encoding="utf-8") @@ -891,6 +913,17 @@ def build_bundle( ) ) continue + finally: + if not keep_suite_intermediates: + pruned_files = _prune_suite_intermediates(suite_dir) + if pruned_files: + pruned_suites.append( + { + "source": source, + "output_dir": str(suite_dir), + "files": pruned_files, + } + ) if not suite_report.valid: errors.append( @@ -1002,6 +1035,19 @@ def build_bundle( warnings=tuple(warnings), ) _write_report(report_path, report.to_dict()) + if not keep_suite_intermediates: + _write_report( + reports_path / PRUNED_INTERMEDIATES_REPORT, + { + "pruned_file_names": list(SUITE_INTERMEDIATE_FILES), + "suite_count": len(pruned_suites), + "file_count": sum(len(suite["files"]) for suite in pruned_suites), + "bytes": sum( + file["bytes"] for suite in pruned_suites for file in suite["files"] + ), + "suites": pruned_suites, + }, + ) return report @@ -1547,6 +1593,19 @@ def _canonical_concept_key(row: dict[str, Any]) -> str | None: return row.get("concept_alignment", {}).get("canonical_concept") +def _prune_suite_intermediates(suite_dir: Path) -> list[dict[str, Any]]: + """Delete a suite's intermediate files and return each one's name and size.""" + pruned: list[dict[str, Any]] = [] + for name in SUITE_INTERMEDIATE_FILES: + path = suite_dir / name + if not path.is_file(): + continue + size = path.stat().st_size + path.unlink() + pruned.append({"name": name, "bytes": size}) + return pruned + + def _safe_source_dir_name(source: str) -> str: safe = re.sub(r"[^A-Za-z0-9._-]+", "-", source).strip("-") return safe or "source" diff --git a/chronicle/harness.py b/chronicle/harness.py index 22832851..68154c47 100644 --- a/chronicle/harness.py +++ b/chronicle/harness.py @@ -274,6 +274,7 @@ def build_bundle_dir( axiom_roots: list[str | Path] | None = None, require_axiom_validation: bool = False, replace: bool = False, + keep_suite_intermediates: bool = True, ) -> BuildBundleReport: """Build a merged Chronicle consumer bundle from source-package suites.""" if suite is not None: @@ -290,6 +291,7 @@ def build_bundle_dir( axiom_roots=axiom_roots or (), require_axiom_validation=require_axiom_validation, replace=replace, + keep_suite_intermediates=keep_suite_intermediates, ) @@ -776,6 +778,16 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help="Fail agent acceptance unless every canonical concept is checked.", ) + bundle_parser.add_argument( + "--slim", + action="store_true", + help=( + "Delete each source suite's source_rows.jsonl, source_cells.jsonl, " + "facts.jsonl and ledger.db once the suite finishes; the bundle's " + "consumer facts and reports are unchanged. " + "reports/pruned_intermediates.json lists what was deleted." + ), + ) consumer_artifact_parser = subparsers.add_parser( "build-consumer-artifact", @@ -1341,6 +1353,7 @@ def main(argv: list[str] | None = None) -> int: axiom_roots=args.axiom_root, require_axiom_validation=args.require_axiom_validation, replace=args.replace, + keep_suite_intermediates=not args.slim, ) print(json.dumps(report.to_dict(), indent=2, sort_keys=True)) return 0 if report.valid else 1 diff --git a/docs/agent-source-package-harness.md b/docs/agent-source-package-harness.md index b5c57f79..d6ebb1b4 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -688,22 +688,32 @@ aggregate facts, a relational SQLite DB artifact, and per-stage JSON reports und `ro-crate-metadata.json` sidecars so the generated artifacts can be described with common data-package conventions while Chronicle keeps its native schema strict. For downstream integration, agents should use the merged year bundle after -individual source packages pass: +individual source packages pass. Build each bundle in its own fresh directory: +concurrent agents that share an `--out` path delete each other's output. ```bash -uv run chronicle build-bundle --year 2023 --out /tmp/ledger-us-2023 --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --year 2023 --out "$RUN_DIR/ledger-us-2023" --slim ``` The bundle emits a root `consumer_facts.jsonl`, `source_packages.json`, `coverage.json`, and `reports/build_bundle.json`, while preserving each -source-package suite under `sources//`. +source-package suite under `sources//`. `--slim` deletes each +suite's `source_rows.jsonl`, `source_cells.jsonl`, `facts.jsonl` and +`ledger.db` once that suite finishes and lists them in +`reports/pruned_intermediates.json`; without it the 2023 default bundle keeps +tens of GB of these files. Slim changes no file the bundle keeps: consumer +facts, coverage, `source_packages.json` and every report match a full build's +byte for byte. To inspect one package's intermediates, run `build-suite` on that +package. For the UK source-package feed, use the curated UK suite and build a facts-only consumer artifact: ```bash -uv run chronicle build-bundle --suite uk --out /tmp/chronicle-uk --replace -uv run chronicle build-consumer-artifact --facts /tmp/chronicle-uk --out /tmp/chronicle-uk-artifact --replace +RUN_DIR="$(mktemp -d)" +uv run chronicle build-bundle --suite uk --out "$RUN_DIR/chronicle-uk" --slim +uv run chronicle build-consumer-artifact --facts "$RUN_DIR/chronicle-uk" --out "$RUN_DIR/chronicle-uk-artifact" ``` `--year` is inert for `--suite uk` because the UK packages are year-pinned. diff --git a/tests/test_chronicle_bundle.py b/tests/test_chronicle_bundle.py index 417382be..3c370a71 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -18,6 +18,8 @@ BUNDLE_SCHEMA_VERSION, BUNDLE_SOURCES_SCHEMA_VERSION, NZ_BUNDLE_SOURCES, + PRUNED_INTERMEDIATES_REPORT, + SUITE_INTERMEDIATE_FILES, UK_BUNDLE_SOURCES, build_bundle, build_bundle_coverage, @@ -365,31 +367,6 @@ def test_build_bundle_cli_rejects_an_unknown_suite(tmp_path, fake_build_bundle, assert fake_build_bundle == [] -@pytest.fixture -def prune_suite_intermediates(monkeypatch): - """Delete each source suite's intermediates once the suite is built. - - Every suite in the default bundle writes source_rows.jsonl, - source_cells.jsonl, facts.jsonl and a per-source ledger.db, and - build_bundle then reads back only its consumer_facts.jsonl. A BEA NIPA - suite alone writes a 496 MB source_rows.jsonl and a 1 GB ledger.db for - under 100 KB of consumer facts. Suite runs that reached this test left - 24 GB (2026-09-20) and 19.7 GB (2026-10-07) in pytest's temp directory. - The suites are still built, validated and merged exactly as before; only - files nothing reads afterwards are removed, so they no longer pile up - across the bundle's 268 source packages. - """ - build_source_suite = chronicle.bundle.build_source_suite - - def build_then_prune(*args, **kwargs): - report = build_source_suite(*args, **kwargs) - for output in ("source_rows", "source_cells", "facts", "database"): - Path(report.outputs[output]).unlink(missing_ok=True) - return report - - monkeypatch.setattr(chronicle.bundle, "build_source_suite", build_then_prune) - - def _skip_unless_r2_only_artifacts_available() -> None: """The merged bundle reads every package's artifact. Those stored in R2 only come from the cache or, with LEDGER_SOURCE_ARTIFACT_FETCH=1 as CI sets, a download; @@ -402,19 +379,31 @@ def _skip_unless_r2_only_artifacts_available() -> None: pytest.skip(f"R2-only source artifact unavailable: {error}") -@pytest.mark.usefixtures("prune_suite_intermediates") def test_build_bundle_writes_merged_consumer_contract(tmp_path): _skip_unless_r2_only_artifacts_available() output_dir = tmp_path / "bundle" - report = build_bundle(output_dir, year=2023) + # Slim: a full default bundle keeps tens of GB of per-suite intermediates + # this test never reads (24 GB on 2026-09-20). Slim mode changes no file + # the bundle keeps (tests/test_chronicle_bundle_slim.py). + report = build_bundle(output_dir, year=2023, keep_suite_intermediates=False) summary = json.loads((output_dir / "reports" / "build_bundle.json").read_text()) rows_path = output_dir / "consumer_facts.jsonl" source_packages = json.loads((output_dir / "source_packages.json").read_text()) coverage = json.loads((output_dir / "coverage.json").read_text()) + pruned = json.loads( + (output_dir / "reports" / PRUNED_INTERMEDIATES_REPORT).read_text() + ) assert report.valid, _bundle_failure_diagnostics(summary) assert summary["valid"] + assert pruned["suite_count"] == summary["counts"]["source_package_count"] + assert pruned["file_count"] == pruned["suite_count"] * len(SUITE_INTERMEDIATE_FILES) + assert not [ + path + for name in SUITE_INTERMEDIATE_FILES + for path in (output_dir / "sources").glob(f"*/{name}") + ] # chronicle#209's NZ WFF package adds 330 TY2024 facts: 329 families and 1 # person, in one new publisher, package, source table and country. # MBIE adds 5,663 August 2025–July 2026 dwelling/bond-record facts, one diff --git a/tests/test_chronicle_bundle_slim.py b/tests/test_chronicle_bundle_slim.py new file mode 100644 index 00000000..5f4c0452 --- /dev/null +++ b/tests/test_chronicle_bundle_slim.py @@ -0,0 +1,308 @@ +"""Slim bundles: ``build_bundle(keep_suite_intermediates=False)`` and ``--slim``. + +A slim bundle deletes each source suite's ``SUITE_INTERMEDIATE_FILES`` once the +suite finishes. Invariants: + +- with the build clock pinned, every file a slim bundle keeps is + byte-identical to a full build's, and the slim bundle holds exactly the full + build's files minus the intermediates plus ``reports/pruned_intermediates.json`` + (``ledger.db`` stores its build time, which the suite sidecars hash); +- pruning deletes only the intermediate files that exist as regular files, and + is idempotent; +- the default keeps every intermediate and writes no pruning report. +""" + +from __future__ import annotations + +import gc +import hashlib +import itertools +import json +import sqlite3 +from pathlib import Path + +from chronicle.bundle import ( + PRUNED_INTERMEDIATES_REPORT, + SUITE_INTERMEDIATE_FILES, + _prune_suite_intermediates, + build_bundle, +) +from chronicle.harness import build_bundle_dir +from chronicle.harness import main as harness_main + +# Three explicit packages that build in seconds. +SMALL_SOURCES = ( + "soi-table-1-1", + "cbo-revenue-projections-income-by-source-2026-02", + "ssa-ssi-table-7b1-2024", +) +PRUNED_REPORT_PATH = f"reports/{PRUNED_INTERMEDIATES_REPORT}" +# Suite files a slim bundle keeps, a sample of each kind build_source_suite writes. +KEPT_SUITE_FILES = ( + "consumer_facts.jsonl", + "source_regions.jsonl", + "datapackage.json", + "ro-crate-metadata.json", + "reports/build_summary.json", + "reports/database.json", +) + + +def _file_hashes(root: Path) -> dict[str, str]: + return { + path.relative_to(root).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(root.rglob("*")) + if path.is_file() + } + + +def test_slim_bundle_matches_full_bundle_byte_for_byte(tmp_path): + # ledger.db's build time comes from SOURCE_DATE_EPOCH, not the clock (#316). + # One output path for both builds: reports embed absolute output paths. + output_dir = tmp_path / "bundle" + + full = build_bundle(output_dir, year=2023, sources=SMALL_SOURCES) + full_files = _file_hashes(output_dir) + full_sizes = {name: (output_dir / name).stat().st_size for name in full_files} + slim = build_bundle( + output_dir, + year=2023, + sources=SMALL_SOURCES, + replace=True, + keep_suite_intermediates=False, + ) + slim_files = _file_hashes(output_dir) + + intermediates = { + f"sources/{source}/{name}" + for source in SMALL_SOURCES + for name in SUITE_INTERMEDIATE_FILES + } + kept = full_files.keys() - intermediates + assert full.valid + assert slim.valid + assert intermediates <= full_files.keys() + assert PRUNED_REPORT_PATH not in full_files + assert slim_files.keys() == kept | {PRUNED_REPORT_PATH} + for name in ( + "consumer_facts.jsonl", + "coverage.json", + "source_packages.json", + "reports/build_bundle.json", + ): + assert slim_files[name] == full_files[name], name + assert {name: slim_files[name] for name in kept} == { + name: full_files[name] for name in kept + } + assert slim.to_dict() == full.to_dict() + + pruned = json.loads((output_dir / PRUNED_REPORT_PATH).read_text()) + assert pruned == { + "pruned_file_names": list(SUITE_INTERMEDIATE_FILES), + "suite_count": len(SMALL_SOURCES), + "file_count": len(intermediates), + "bytes": sum(full_sizes[name] for name in intermediates), + "suites": [ + { + "source": source, + "output_dir": str(output_dir / "sources" / source), + "files": [ + {"name": name, "bytes": full_sizes[f"sources/{source}/{name}"]} + for name in SUITE_INTERMEDIATE_FILES + ], + } + for source in SMALL_SOURCES + ], + } + + +def test_slim_bundle_prunes_a_suite_that_fails_partway(tmp_path, monkeypatch): + def failing_suite(source, output_dir, **kwargs): + suite_dir = Path(output_dir) + (suite_dir / "reports").mkdir(parents=True) + for name in SUITE_INTERMEDIATE_FILES: + (suite_dir / name).write_text("partial") + (suite_dir / "reports" / "source_rows.json").write_text("{}") + raise RuntimeError("parser failed") + + monkeypatch.setattr("chronicle.bundle.build_source_suite", failing_suite) + output_dir = tmp_path / "bundle" + + report = build_bundle( + output_dir, + year=2023, + sources=["soi-table-1-1"], + keep_suite_intermediates=False, + ) + + suite_dir = output_dir / "sources" / "soi-table-1-1" + assert [issue.code for issue in report.errors] == ["source_suite_build_failed"] + assert sorted(_file_hashes(suite_dir)) == ["reports/source_rows.json"] + pruned = json.loads((output_dir / PRUNED_REPORT_PATH).read_text()) + assert pruned["suites"] == [ + { + "source": "soi-table-1-1", + "output_dir": str(suite_dir), + "files": [ + {"name": name, "bytes": len("partial")} + for name in SUITE_INTERMEDIATE_FILES + ], + } + ] + + +def test_slim_bundle_records_no_suite_that_wrote_nothing(tmp_path, monkeypatch): + def empty_failure(source, output_dir, **kwargs): + raise RuntimeError("no artifact") + + monkeypatch.setattr("chronicle.bundle.build_source_suite", empty_failure) + output_dir = tmp_path / "bundle" + + build_bundle( + output_dir, + year=2023, + sources=["soi-table-1-1"], + keep_suite_intermediates=False, + ) + + pruned = json.loads((output_dir / PRUNED_REPORT_PATH).read_text()) + assert pruned["suites"] == [] + assert (pruned["suite_count"], pruned["file_count"], pruned["bytes"]) == (0, 0, 0) + + +def _open_sqlite_paths_under(root: Path) -> list[Path]: + """Database files under ``root`` that some live connection still holds open.""" + held = [] + for obj in gc.get_objects(): + if not isinstance(obj, sqlite3.Connection): + continue + try: + databases = obj.execute("PRAGMA database_list").fetchall() + except sqlite3.ProgrammingError: + continue # closed, or owned by another thread + for _, _, filename in databases: + if filename and Path(filename).resolve().is_relative_to(root.resolve()): + held.append(Path(filename)) + return held + + +def test_slim_bundle_leaves_no_pruned_ledger_db_open(tmp_path): + """A deleted ledger.db frees its storage only once its connection closes. + + With the collector off, a connection left in a reference cycle stays open + and keeps the unlinked file's blocks allocated for the whole bundle build. + """ + output_dir = tmp_path / "bundle" + probe_path = tmp_path / "probe.db" + collector_was_enabled = gc.isenabled() + gc.disable() + try: + build_bundle( + output_dir, + year=2023, + sources=SMALL_SOURCES, + keep_suite_intermediates=False, + ) + held = _open_sqlite_paths_under(output_dir) + # Positive control: the scan must see a connection left open, and stop + # seeing it once it is closed, or an empty result proves nothing. + probe = sqlite3.connect(probe_path) + probe_open = _open_sqlite_paths_under(tmp_path) + probe.close() + probe_closed = _open_sqlite_paths_under(tmp_path) + finally: + if collector_was_enabled: + gc.enable() + + assert held == [] + assert [path.resolve() for path in probe_open] == [probe_path.resolve()] + assert probe_closed == [] + + +def test_prune_suite_intermediates_exhaustively(tmp_path): + """Each intermediate absent, a file or a directory, beside kept files or none. + + Kept files are never candidates for deletion, so they vary together. + """ + intermediate_states = ("absent", "file", "directory") + combinations = itertools.product( + itertools.product(intermediate_states, repeat=len(SUITE_INTERMEDIATE_FILES)), + ( + ("absent",) * len(KEPT_SUITE_FILES), + ("file",) * len(KEPT_SUITE_FILES), + ), + ) + for case, (intermediate_case, kept_case) in enumerate(combinations): + suite_dir = tmp_path / str(case) + suite_dir.mkdir() + expected: list[dict[str, object]] = [] + for index, (name, state) in enumerate( + zip(SUITE_INTERMEDIATE_FILES, intermediate_case, strict=True) + ): + if state == "file": + (suite_dir / name).write_bytes(b"x" * index) + expected.append({"name": name, "bytes": index}) + elif state == "directory": + (suite_dir / name).mkdir() + (suite_dir / name / "inner").write_text(name) + for name, state in zip(KEPT_SUITE_FILES, kept_case, strict=True): + if state == "file": + (suite_dir / name).parent.mkdir(parents=True, exist_ok=True) + (suite_dir / name).write_text(f"{case}:{name}") + before = _file_hashes(suite_dir) + removed = {item["name"] for item in expected} + + assert _prune_suite_intermediates(suite_dir) == expected, case + after = _file_hashes(suite_dir) + assert after == { + name: digest for name, digest in before.items() if name not in removed + }, case + assert _prune_suite_intermediates(suite_dir) == [], case + assert _file_hashes(suite_dir) == after, case + + +def test_prune_suite_intermediates_ignores_a_missing_suite_dir(tmp_path): + assert _prune_suite_intermediates(tmp_path / "never-built") == [] + + +def test_build_bundle_dir_passes_keep_suite_intermediates(tmp_path, monkeypatch): + captured = [] + + def fake_build_bundle(output_dir, **kwargs): + captured.append(kwargs["keep_suite_intermediates"]) + + monkeypatch.setattr("chronicle.harness.build_bundle", fake_build_bundle) + + build_bundle_dir(tmp_path / "default", year=2023) + build_bundle_dir(tmp_path / "slim", year=2023, keep_suite_intermediates=False) + + assert captured == [True, False] + + +def test_build_bundle_cli_slim_deletes_suite_intermediates(tmp_path, capsys): + full_dir = tmp_path / "full" + slim_dir = tmp_path / "slim" + common = ["build-bundle", "--year", "2023", "--source", "soi-table-1-1"] + + full_status = harness_main([*common, "--out", str(full_dir)]) + full_payload = json.loads(capsys.readouterr().out) + slim_status = harness_main([*common, "--out", str(slim_dir), "--slim"]) + slim_payload = json.loads(capsys.readouterr().out) + + assert (full_status, slim_status) == (0, 0) + assert slim_payload["valid"] + assert slim_payload["counts"] == full_payload["counts"] + full_suite = full_dir / "sources" / "soi-table-1-1" + slim_suite = slim_dir / "sources" / "soi-table-1-1" + for name in SUITE_INTERMEDIATE_FILES: + assert (full_suite / name).is_file() + assert not (slim_suite / name).exists() + assert (slim_suite / "consumer_facts.jsonl").read_bytes() == ( + full_suite / "consumer_facts.jsonl" + ).read_bytes() + assert not (full_dir / PRUNED_REPORT_PATH).exists() + pruned = json.loads((slim_dir / PRUNED_REPORT_PATH).read_text()) + assert (pruned["suite_count"], pruned["file_count"]) == ( + 1, + len(SUITE_INTERMEDIATE_FILES), + )