Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<source-package>/`. The bundle coverage report
remain nested under `sources/<source-package>/`. `--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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions changelog.d/slim-bundle-intermediates.added.md
Original file line number Diff line number Diff line change
@@ -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.
61 changes: 60 additions & 1 deletion chronicle/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand All @@ -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(
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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"
Expand Down
13 changes: 13 additions & 0 deletions chronicle/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
)


Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down
20 changes: 15 additions & 5 deletions docs/agent-source-package-harness.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>/`.
source-package suite under `sources/<source-package>/`. `--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.
Expand Down
43 changes: 16 additions & 27 deletions tests/test_chronicle_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand Down
Loading
Loading