From 59dfad13bf964ad0e1e2c72c57330fab41784ff2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 7 Oct 2026 11:02:16 -0400 Subject: [PATCH 1/5] Add a slim build-bundle mode that drops per-suite intermediates build_bundle reads back only each source suite's consumer_facts.jsonl, yet every suite keeps its source_rows.jsonl, source_cells.jsonl, facts.jsonl and ledger.db. For the 2023 default bundle that is tens of GB (24 GB left by one test run on 2026-09-20): each BEA NIPA suite writes a 496 MB source_rows.jsonl and a 1 GB ledger.db for under 100 KB of consumer facts. build_bundle(..., keep_suite_intermediates=False) and `chronicle build-bundle --slim` delete those four files as each suite finishes, whether or not it built, and list them in reports/pruned_intermediates.json. Every file the bundle keeps is byte-identical to a full build's. The default is unchanged. The full default-bundle test now builds slim, and the README and harness doc build each bundle in a fresh mktemp directory with --slim instead of a shared /tmp path. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 +- .../slim-bundle-intermediates.added.md | 1 + chronicle/bundle.py | 60 +++- chronicle/harness.py | 13 + docs/agent-source-package-harness.md | 19 +- tests/test_chronicle_bundle.py | 17 +- tests/test_chronicle_bundle_slim.py | 265 ++++++++++++++++++ 7 files changed, 385 insertions(+), 12 deletions(-) create mode 100644 changelog.d/slim-bundle-intermediates.added.md create mode 100644 tests/test_chronicle_bundle_slim.py diff --git a/README.md b/README.md index 43877c96..ba0a35ce 100644 --- a/README.md +++ b/README.md @@ -272,15 +272,26 @@ 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`. +Every file a slim bundle keeps is byte-identical to a full build's, 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 @@ -297,8 +308,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 diff --git a/changelog.d/slim-bundle-intermediates.added.md b/changelog.d/slim-bundle-intermediates.added.md new file mode 100644 index 00000000..7dfdca5f --- /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`; every file the bundle keeps is byte-identical to a full build's. 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 5d40661f..ebef6e1b 100644 --- a/chronicle/bundle.py +++ b/chronicle/bundle.py @@ -26,6 +26,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", @@ -386,8 +397,17 @@ 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. Every file the bundle keeps is byte-identical to a full + build's, including the reports and sidecars that still name or hash the + deleted files. + """ output_path = Path(output_dir) _prepare_output_dir(output_path, replace=replace) reports_path = output_path / "reports" @@ -417,6 +437,7 @@ def build_bundle( dimension_labels: dict[str, dict[str, list[str]]] = {} geography_names: dict[tuple[str, str], dict[str, list[str]]] = {} value_labels: dict[tuple[str, str], dict[str, list[str]]] = {} + pruned_suites: list[dict[str, Any]] = [] for source in build_sources: suite_dir = sources_path / _safe_source_dir_name(source) @@ -439,6 +460,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( @@ -543,6 +575,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 @@ -1010,6 +1055,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 298a1380..6ba73515 100644 --- a/chronicle/harness.py +++ b/chronicle/harness.py @@ -272,6 +272,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 == "uk": @@ -287,6 +288,7 @@ def build_bundle_dir( axiom_roots=axiom_roots or (), require_axiom_validation=require_axiom_validation, replace=replace, + keep_suite_intermediates=keep_suite_intermediates, ) @@ -751,6 +753,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", @@ -1274,6 +1286,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 c8cec774..ebf2081c 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -651,22 +651,31 @@ 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. Every other file is byte-identical to a full +build's. 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 063eb806..b6a9e63d 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -14,6 +14,8 @@ BUNDLE_COVERAGE_SCHEMA_VERSION, BUNDLE_SCHEMA_VERSION, BUNDLE_SOURCES_SCHEMA_VERSION, + PRUNED_INTERMEDIATES_REPORT, + SUITE_INTERMEDIATE_FILES, UK_BUNDLE_SOURCES, _load_jsonl as load_bundle_jsonl, build_bundle, @@ -151,14 +153,27 @@ def build_then_prune(*args, **kwargs): def test_build_bundle_writes_merged_consumer_contract(tmp_path): 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 and full bundles keep + # byte-identical files (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 = _load_jsonl(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 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. assert summary["counts"] == { diff --git a/tests/test_chronicle_bundle_slim.py b/tests/test_chronicle_bundle_slim.py new file mode 100644 index 00000000..fd0da3bc --- /dev/null +++ b/tests/test_chronicle_bundle_slim.py @@ -0,0 +1,265 @@ +"""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: + +- 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``; +- 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 hashlib +import itertools +import json +from datetime import datetime +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", +) + + +class _FrozenDatetime(datetime): + """``ledger.db`` stores its build time; pin it so two builds match byte for byte.""" + + @classmethod + def now(cls, tz=None): + return cls(2026, 1, 1, tzinfo=tz) + + +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, monkeypatch): + monkeypatch.setattr("chronicle.database.datetime", _FrozenDatetime) + # 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 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), + ) From b7bee513e4396af449ade43549241f126f03d56a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 7 Oct 2026 11:20:09 -0400 Subject: [PATCH 2/5] State slim-bundle byte identity as precisely as it holds Every ledger.db stores a wall-clock ledger_builds.created_at, and each suite's datapackage.json and ro-crate-metadata.json hash it, so those two sidecars differ between any two builds, slim or not. The consumer facts, coverage, source_packages.json and every report are byte-identical; the differential test pins the build clock to compare the sidecars too. Say that, instead of "every kept file is byte-identical to a full build's". Co-Authored-By: Claude Opus 5.5 --- README.md | 7 ++++--- changelog.d/slim-bundle-intermediates.added.md | 2 +- chronicle/bundle.py | 7 ++++--- docs/agent-source-package-harness.md | 5 +++-- tests/test_chronicle_bundle.py | 4 ++-- tests/test_chronicle_bundle_slim.py | 7 ++++--- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index ba0a35ce..8e6e19bf 100644 --- a/README.md +++ b/README.md @@ -286,9 +286,10 @@ This writes a root `consumer_facts.jsonl`, `source_packages.json`, 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`. -Every file a slim bundle keeps is byte-identical to a full build's, 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 +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 diff --git a/changelog.d/slim-bundle-intermediates.added.md b/changelog.d/slim-bundle-intermediates.added.md index 7dfdca5f..40e4b930 100644 --- a/changelog.d/slim-bundle-intermediates.added.md +++ b/changelog.d/slim-bundle-intermediates.added.md @@ -1 +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`; every file the bundle keeps is byte-identical to a full build's. 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. +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 ebef6e1b..dcc0ec82 100644 --- a/chronicle/bundle.py +++ b/chronicle/bundle.py @@ -404,9 +404,10 @@ def build_bundle( 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. Every file the bundle keeps is byte-identical to a full - build's, including the reports and sidecars that still name or hash the - deleted files. + 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). """ output_path = Path(output_dir) _prepare_output_dir(output_path, replace=replace) diff --git a/docs/agent-source-package-harness.md b/docs/agent-source-package-harness.md index ebf2081c..0a6634fa 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -665,8 +665,9 @@ 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. Every other file is byte-identical to a full -build's. To inspect one package's intermediates, run `build-suite` on that +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 diff --git a/tests/test_chronicle_bundle.py b/tests/test_chronicle_bundle.py index b6a9e63d..2cbec84f 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -154,8 +154,8 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): output_dir = tmp_path / "bundle" # Slim: a full default bundle keeps tens of GB of per-suite intermediates - # this test never reads (24 GB on 2026-09-20). Slim and full bundles keep - # byte-identical files (tests/test_chronicle_bundle_slim.py). + # 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 = _load_jsonl(output_dir / "consumer_facts.jsonl") diff --git a/tests/test_chronicle_bundle_slim.py b/tests/test_chronicle_bundle_slim.py index fd0da3bc..2c59d69b 100644 --- a/tests/test_chronicle_bundle_slim.py +++ b/tests/test_chronicle_bundle_slim.py @@ -3,9 +3,10 @@ A slim bundle deletes each source suite's ``SUITE_INTERMEDIATE_FILES`` once the suite finishes. Invariants: -- 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``; +- 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 fe2a450dfba488775bed6c84f6360dbb7d7a5cdf Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 7 Oct 2026 15:42:55 -0400 Subject: [PATCH 3/5] Replace #312's test fixture with the slim flag and test connection release PolicyEngine/chronicle#312 added a prune_suite_intermediates fixture that wrapped build_source_suite to delete the same four files this branch's keep_suite_intermediates=False deletes. With both active, the slim prune finds nothing and the bundle test's pruned_intermediates assertions fail, so the fixture goes and the full-bundle test runs the production path alone. #312 also closes each SQLite connection on return. Before that, a deleted ledger.db kept its storage until the garbage collector closed its connection. test_slim_bundle_leaves_no_pruned_ledger_db_open builds a slim bundle with the collector off and checks that no live sqlite3.Connection still holds a file under the bundle. It fails on 0f2cd96 with this branch's flag (three held open) and passes on top of #312. Co-Authored-By: Claude Opus 5.5 --- tests/test_chronicle_bundle.py | 27 ------------------- tests/test_chronicle_bundle_slim.py | 40 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/tests/test_chronicle_bundle.py b/tests/test_chronicle_bundle.py index 2cbec84f..ce7e7eed 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -9,7 +9,6 @@ import pytest -import chronicle.bundle from chronicle.bundle import ( BUNDLE_COVERAGE_SCHEMA_VERSION, BUNDLE_SCHEMA_VERSION, @@ -124,32 +123,6 @@ def fake_build_bundle_dir(output_dir, **kwargs): assert captured["suite"] == "uk" -@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) - - -@pytest.mark.usefixtures("prune_suite_intermediates") def test_build_bundle_writes_merged_consumer_contract(tmp_path): output_dir = tmp_path / "bundle" diff --git a/tests/test_chronicle_bundle_slim.py b/tests/test_chronicle_bundle_slim.py index 2c59d69b..a0f0fbb8 100644 --- a/tests/test_chronicle_bundle_slim.py +++ b/tests/test_chronicle_bundle_slim.py @@ -14,9 +14,11 @@ from __future__ import annotations +import gc import hashlib import itertools import json +import sqlite3 from datetime import datetime from pathlib import Path @@ -177,6 +179,44 @@ def empty_failure(source, output_dir, **kwargs): 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" + gc.disable() + try: + build_bundle( + output_dir, + year=2023, + sources=SMALL_SOURCES, + keep_suite_intermediates=False, + ) + held = _open_sqlite_paths_under(output_dir) + finally: + gc.enable() + + assert held == [] + + def test_prune_suite_intermediates_exhaustively(tmp_path): """Each intermediate absent, a file or a directory, beside kept files or none. From 39f2c5fbc1b8ced9873b637f90ff9877df3845ca Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 7 Oct 2026 15:51:08 -0400 Subject: [PATCH 4/5] Give the connection-release test a positive control The scan for open SQLite connections returned an empty list both when nothing was held and when it could not see connections at all. It now opens a probe connection under tmp_path, asserts the scan reports it, closes it and asserts the scan stops reporting it. The test also restores the collector's prior state instead of always re-enabling it. Both from the delta review of fe2a450. Co-Authored-By: Claude Opus 5.5 --- tests/test_chronicle_bundle_slim.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/test_chronicle_bundle_slim.py b/tests/test_chronicle_bundle_slim.py index a0f0fbb8..7613c362 100644 --- a/tests/test_chronicle_bundle_slim.py +++ b/tests/test_chronicle_bundle_slim.py @@ -202,6 +202,8 @@ def test_slim_bundle_leaves_no_pruned_ledger_db_open(tmp_path): 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( @@ -211,10 +213,19 @@ def test_slim_bundle_leaves_no_pruned_ledger_db_open(tmp_path): 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: - gc.enable() + 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): From f2526f035e979fd41bc1e2dad9b3b17e2e90f33d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 00:49:25 -0500 Subject: [PATCH 5/5] Build the NZ and BE bundle examples in a fresh mktemp directory with --slim Main added these examples after this branch forked, so the merge left them on shared /tmp paths with --replace, right below the advice against that. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bfad53c5..8ab87ce8 100644 --- a/README.md +++ b/README.md @@ -326,8 +326,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 +345,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