From e332ad11e92865a093ec38391a5f455021372ef0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:05:19 +0400 Subject: [PATCH 1/6] Test that post-export scoring keeps its household batches in files These tests fail on the current scorer, which keeps every household batch frame of the written H5 in memory until it closes: - the open scorer, and a scorer after a pass, reaches no Frame or DataFrame; - each batch is in its own file, read back each time it is scored, and equals the batch selected in memory byte for byte (negative zero, NaN, 32-bit integers, booleans and strings included); - a batch file whose bytes changed, or that is missing, is refused; - closing or dropping the scorer removes its batch files, a given batch directory that exists is refused and left as it was, and a scorer that cannot write its batches leaves no files; - certification gives the scorer a directory in the build's --out and placing the build removes one an earlier attempt left. Two tests pass now and must keep passing: the values scored from the batch files equal those of the in-memory batches, and (engine workflow) each batch read back from a fixture H5 written by the engine's writer equals that batch as the scorer selected it. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_batch_files.py | 335 ++++++++++++++++++ .../us/test_us_post_export_scoring.py | 6 +- .../us/test_us_post_export_scoring.py | 29 ++ .../us_post_export_batch_files.py | 52 +++ 4 files changed, 420 insertions(+), 2 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py create mode 100644 test_support/microcosm_build/us_post_export_batch_files.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py new file mode 100644 index 0000000000..ea32c834d1 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py @@ -0,0 +1,335 @@ +"""The post-export scorer keeps its household batches in files (1.4 · 4). + +``_HouseholdBatchedPostExportScorer`` loads the written H5 once, bound to its +sha256, and splits it into household batches. It writes each batch to its own +file with the file's sha256 recorded, frees the frames, and reads a batch back +from its file each time it scores it. So the process that scores holds the +H5's path and the batch files' paths and digests, and no frame of the written +H5 between batches. These tests run the scorer against the fake engine on a +small nested frame; ``engine_workflow/us/test_us_post_export_scoring.py`` +checks the batches of a fixture H5 written by the engine's own writer. +""" + +from __future__ import annotations + +# Test functions take the imported ``builder`` fixture as a parameter. +# ruff: noqa: F811 +import gc +import pickle +import types +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +from microcosm.frame import Frame, WeightKind, Weights +from microcosm.frame.units import US_SCHEMA +from test_support.microcosm_build.us_post_export_batch_files import assert_same_batch +from test_support.microcosm_build.us_post_export_scoring import ( + _EngineLog, + _fake_engine, + _nested_frame, + _written_h5, + builder, # noqa: F401 - the module-scoped fixture +) + +_AGE_KEY = ("age", 2024, None) + + +def _frame_with_edge_values() -> Frame: + """The nested fixture frame, plus columns whose values a lossy copy would + change: a negative zero and a NaN, 32-bit integers, booleans, strings.""" + + nested = _nested_frame() + tables = {entity: nested.table(entity).copy() for entity in nested.entities} + person = tables["person"] + n_persons = len(person) + person["signed_amount"] = np.resize( + np.asarray([-0.0, 0.0, np.nan, 1.5, -2.25]), n_persons + ) + person["count_32"] = np.arange(n_persons, dtype=np.int32) - 3 + person["is_flagged"] = np.arange(n_persons) % 2 == 0 + person["label"] = pd.Series( + [f"person {index}" for index in range(n_persons)], dtype=object + ) + household = tables["household"] + household["region_name"] = pd.Series( + [f"region {index % 3}" for index in range(len(household))], dtype=object + ) + return Frame( + tables, + US_SCHEMA, + { + "household": Weights( + nested.weights_for("household").values, WeightKind.CALIBRATED + ) + }, + ) + + +def _open_scorer( + builder, + frame: Frame, + tmp_path: Path, + *, + batch_size: int | None = 3, + scored_frames: list | None = None, + **options, +): + """A scorer on ``frame`` (served as the written H5) and the fake engine. + + Every frame the scorer hands an engine is appended to ``scored_frames``. + """ + + def dataset_from_frame(batch_frame): + if scored_frames is not None: + scored_frames.append(batch_frame) + return batch_frame + + return builder._HouseholdBatchedPostExportScorer( + _written_h5(tmp_path), + maximum_microsim_batch_size=batch_size, + microsimulation_cls=_fake_engine(_EngineLog()), + dataset_from_frame=dataset_from_frame, + load_frame=lambda load_path, *, expected_sha256: frame, + **options, + ) + + +def _frames_held_by(root: object) -> list[str]: + """Where a Frame or DataFrame is reachable from ``root``'s attributes. + + Follows attributes, containers and the scorer's own helper objects; stops + at classes, functions and modules, which reach the whole interpreter. + """ + + found: list[str] = [] + visited: set[int] = set() + + def walk(value: object, where: str) -> None: + if id(value) in visited: + return + visited.add(id(value)) + if isinstance(value, (Frame, pd.DataFrame)): + found.append(where) + return + if value is None or isinstance( + value, + ( + str, + bytes, + int, + float, + Path, + type, + types.FunctionType, + types.BuiltinFunctionType, + types.MethodType, + types.ModuleType, + ), + ): + return + if isinstance(value, dict): + for key, item in value.items(): + walk(item, f"{where}[{key!r}]") + return + if isinstance(value, (list, tuple, set, frozenset)): + for index, item in enumerate(value): + walk(item, f"{where}[{index}]") + return + attributes = getattr(value, "__dict__", None) + if isinstance(attributes, dict): + for name, item in attributes.items(): + walk(item, f"{where}.{name}") + + walk(root, "scorer") + return found + + +def _expected_batches(builder, frame: Frame, batch_size: int) -> list[Frame]: + """The batches the scorer selected in memory before 1.4 · 4.""" + + return [ + frame + if len(positions) == frame.n("household") + else builder._select_households_by_position(frame, positions) + for positions in builder._household_position_batches( + frame.n("household"), batch_size + ) + ] + + +def test_the_open_scorer_holds_no_frame_of_the_written_h5(builder, tmp_path) -> None: + scorer = _open_scorer(builder, _frame_with_edge_values(), tmp_path) + try: + assert scorer.n_batches == 3 + assert _frames_held_by(scorer) == [] + scorer._score([_AGE_KEY], label="age") + # A pass reads its batches and keeps none of them. + assert _frames_held_by(scorer) == [] + finally: + scorer.close() + + +def test_each_batch_is_read_from_its_own_file_each_time_it_is_scored( + builder, tmp_path +) -> None: + frame = _frame_with_edge_values() + scored_frames: list[Frame] = [] + scorer = _open_scorer(builder, frame, tmp_path, scored_frames=scored_frames) + try: + assert len(sorted(scorer.batch_directory.iterdir())) == scorer.n_batches + scorer._score([_AGE_KEY], label="first pass") + scorer._score([_AGE_KEY], label="second pass") + finally: + scorer.close() + + expected = _expected_batches(builder, frame, 3) + assert len(scored_frames) == 2 * len(expected) + # Each pass reads every batch from its file again: no frame object is + # served twice (every one is still referenced here, so ids are distinct). + assert len({id(scored) for scored in scored_frames}) == len(scored_frames) + for scored, selected in zip(scored_frames, expected * 2, strict=True): + assert_same_batch(scored, selected) + + +def test_batches_score_the_same_values_as_the_selected_batches( + builder, tmp_path +) -> None: + frame = _frame_with_edge_values() + scorer = _open_scorer(builder, frame, tmp_path / "files") + try: + from_files = scorer._score([_AGE_KEY], label="age")[_AGE_KEY] + finally: + scorer.close() + # The fake engine's ages, over the batches the scorer selected in memory. + engine_cls = _fake_engine(_EngineLog()) + expected_values, expected_weights = [], [] + for selected in _expected_batches(builder, frame, 3): + values, weights = builder._post_export_values_and_weights( + engine_cls(dataset=selected).calculate(*_AGE_KEY), _AGE_KEY + ) + expected_values.append(values) + expected_weights.append(weights) + assert from_files._values.tobytes() == np.concatenate(expected_values).tobytes() + assert from_files._weights.tobytes() == np.concatenate(expected_weights).tobytes() + + +def test_a_batch_file_whose_bytes_changed_is_refused(builder, tmp_path) -> None: + scorer = _open_scorer(builder, _nested_frame(), tmp_path) + try: + first_file = sorted(scorer.batch_directory.iterdir())[0] + first_file.write_bytes(first_file.read_bytes() + b"changed") + with pytest.raises(ValueError, match="SHA-256"): + scorer._score([_AGE_KEY], label="age") + finally: + scorer.close() + + +def test_a_missing_batch_file_is_refused(builder, tmp_path) -> None: + scorer = _open_scorer(builder, _nested_frame(), tmp_path) + try: + sorted(scorer.batch_directory.iterdir())[-1].unlink() + with pytest.raises(FileNotFoundError): + scorer._score([_AGE_KEY], label="age") + finally: + scorer.close() + + +def test_closing_the_scorer_removes_its_batch_files(builder, tmp_path) -> None: + scorer = _open_scorer(builder, _nested_frame(), tmp_path) + directory = scorer.batch_directory + assert directory.is_dir() + scorer.close() + assert not directory.exists() + with pytest.raises(RuntimeError, match="closed"): + scorer._batches() + + +def test_a_scorer_dropped_without_closing_removes_its_batch_files( + builder, tmp_path +) -> None: + scorer = _open_scorer(builder, _nested_frame(), tmp_path) + directory = scorer.batch_directory + assert directory.is_dir() + del scorer + gc.collect() + assert not directory.exists() + + +def test_a_given_batch_directory_holds_the_files_and_is_removed_at_close( + builder, tmp_path +) -> None: + directory = tmp_path / "post_export_batches" + scorer = _open_scorer( + builder, _nested_frame(), tmp_path / "h5", batch_directory=directory + ) + assert scorer.batch_directory == directory + assert len(sorted(directory.iterdir())) == scorer.n_batches + scorer.close() + assert not directory.exists() + + +def test_a_given_batch_directory_that_exists_is_refused_and_kept( + builder, tmp_path +) -> None: + directory = tmp_path / "post_export_batches" + directory.mkdir() + kept = directory / "another_scorers_batch" + kept.write_bytes(b"not this scorer's") + with pytest.raises(FileExistsError): + _open_scorer( + builder, _nested_frame(), tmp_path / "h5", batch_directory=directory + ) + assert kept.read_bytes() == b"not this scorer's" + + +def test_a_scorer_that_cannot_write_its_batches_leaves_no_files( + builder, tmp_path +) -> None: + nested = _nested_frame() + tables = {entity: nested.table(entity).copy() for entity in nested.entities} + # A value pickle cannot write: the first batch's file fails part-written. + tables["household"]["unwritable"] = pd.Series( + [lambda: None for _ in range(len(tables["household"]))], dtype=object + ) + frame = Frame( + tables, + US_SCHEMA, + { + "household": Weights( + nested.weights_for("household").values, WeightKind.CALIBRATED + ) + }, + ) + directory = tmp_path / "post_export_batches" + # Python 3.13 raises AttributeError for a local function, 3.14 + # PicklingError. + with pytest.raises((pickle.PicklingError, AttributeError)): + _open_scorer(builder, frame, tmp_path / "h5", batch_directory=directory) + gc.collect() + assert not directory.exists() + + +def test_certification_removes_an_earlier_attempts_batch_files( + builder, tmp_path +) -> None: + """Certification's batch directory is named for it in the build's + ``--out``; placing the build removes one an earlier, killed attempt left.""" + + release_root = tmp_path / "out" + build_dir = release_root / "build" + build_dir.mkdir(parents=True) + stale = release_root / builder.US_POST_EXPORT_BATCH_DIRECTORY + stale.mkdir() + (stale / "batch-00000.pickle").write_bytes(b"an earlier attempt's batch") + record = SimpleNamespace( + build="fixture-build", + release_root=release_root, + build_dir=build_dir, + payload={"files": {}}, + ) + builder._place_build_for_certification(record, release_root / "releases" / "r") + assert not stale.exists() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index 1febf7e71d..35f87fa617 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -844,9 +844,11 @@ def calls_to(name: str, among=None) -> list[ast.Call]: in (getattr(call.func, "id", None), getattr(call.func, "attr", None)) ] - # The scorer opens on the written H5 with the plan recorded before export. + # The scorer opens on the written H5 with the plan recorded before export, + # keeping its batch files in the build's --out (1.4 · 4). assert [ast.unparse(call) for call in calls_to("_open_post_export_scorer")] == [ - "_open_post_export_scorer(post_export_scoring_plan, dataset_path)" + "_open_post_export_scorer(post_export_scoring_plan, dataset_path, " + "batch_directory=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY)" ] # It opens the file the build wrote, which the record pins by digest # (never a previous run's bytes at the same path, microcosm#443), and diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index d4e2154ee7..26265016a6 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -362,3 +362,32 @@ def close(self) -> None: kept_before, kept_after, kept = score() assert len(kept_after - kept_before) >= 2 * 1_000 assert released == kept + + +def test_batches_read_from_their_files_equal_the_written_h5s_batches( + builder, tmp_path +) -> None: + """Each batch the scorer reads back from its file (1.4 · 4) holds exactly + the rows, columns, dtypes, values and weights of that household batch of a + fixture H5 written by the engine's own writer, as the scorer selected it + in memory before it kept batches in files.""" + from test_support.microcosm_build.us_post_export_batch_files import ( + assert_same_batch, + ) + + path = _write_engine_h5(builder, tmp_path, _GUARD_HOUSEHOLDS) + written = builder._load_frame(path, expected_sha256=builder._sha256(path)) + expected = [ + builder._select_households_by_position(written, positions) + for positions in builder._household_position_batches(written.n("household"), 3) + ] + scorer = builder._HouseholdBatchedPostExportScorer( + path, maximum_microsim_batch_size=3 + ) + try: + batches = scorer._batches() + assert len(batches) == len(expected) == scorer.n_batches >= 2 + for number, selected in enumerate(expected): + assert_same_batch(batches[number], selected) + finally: + scorer.close() diff --git a/test_support/microcosm_build/us_post_export_batch_files.py b/test_support/microcosm_build/us_post_export_batch_files.py new file mode 100644 index 0000000000..7c3ed478e1 --- /dev/null +++ b/test_support/microcosm_build/us_post_export_batch_files.py @@ -0,0 +1,52 @@ +"""Shared checks for the post-export scorer's household batch files. + +The scorer keeps each household batch of the written H5 in its own file and +reads it back each time it scores that batch, so the scoring process holds no +frame of the written H5 between batches. These helpers compare a batch read +back from its file with the batch the scorer selected from the loaded H5. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + +from microcosm.frame import Frame + + +def assert_same_batch(restored: Frame, expected: Frame) -> None: + """``restored`` holds exactly ``expected``'s data. + + Same entities, columns, dtypes and index; numeric, boolean and date + columns equal byte for byte (so the sign of a zero and a NaN's bit pattern + count); object columns equal value by value with the same Python types; + the same weights, weight kinds and strata. + """ + + assert restored.entities == expected.entities + for entity in expected.entities: + restored_table = restored.table(entity) + expected_table = expected.table(entity) + pd.testing.assert_frame_equal(restored_table, expected_table, check_exact=True) + for column in expected_table.columns: + restored_values = restored_table[column].to_numpy() + expected_values = expected_table[column].to_numpy() + if expected_values.dtype.kind == "O": + assert [type(value) for value in restored_values] == [ + type(value) for value in expected_values + ], (entity, column) + else: + assert restored_values.tobytes() == expected_values.tobytes(), ( + entity, + column, + ) + assert restored.weighted_entities == expected.weighted_entities + for entity in expected.weighted_entities: + restored_weights = restored.weights_for(entity) + expected_weights = expected.weights_for(entity) + assert restored_weights.kind == expected_weights.kind, entity + assert ( + np.asarray(restored_weights.values).tobytes() + == np.asarray(expected_weights.values).tobytes() + ), entity + pd.testing.assert_series_equal(restored.strata, expected.strata, check_exact=True) From 120a6953744a38ebaea735138d82eca495ad650f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:18:22 +0400 Subject: [PATCH 2/6] Keep the post-export scorer's household batches in files The scorer loaded the written H5 once and kept every household batch frame in memory until it closed, through the whole of certification: about 0.39 GiB on the published 57,240-household national file and about 2.1 GiB (estimate) on a 352,932-household national export. It still loads the H5 once, bound to its sha256, selects the batches and checks the batching premises. It now pickles each batch to its own file, records the sha256 of the bytes written and frees the frames. _PostExportBatchFiles reads a batch back when it is indexed and refuses a file whose bytes no longer hash to the recorded digest, so only bytes this process wrote are unpickled. _score is unchanged: it iterates _batches() as before, and each batch is read just before its engine is built. The scorer makes its directory new (refusing one that exists) or uses a new temporary one, and removes it when it closes, is freed or the interpreter exits. Certification keeps the files in post_export_batches/ in the build's --out; placing a build for certification removes one a killed attempt left. Scored values are unchanged: unpickling gives back the same tables, dtypes, index, values, weights and strata. POST_EXPORT_SCORING_METHOD is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../us-post-export-batch-files.changed.md | 1 + docs/us-release-build-rule.md | 9 ++ .../us/test_us_post_export_batch_files.py | 5 +- .../us/test_us_post_export_scoring.py | 2 +- .../us/test_us_post_export_scoring.py | 2 +- tools/build_us_fiscal_refresh_release.py | 133 ++++++++++++++++-- 6 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 changelog.d/us-post-export-batch-files.changed.md diff --git a/changelog.d/us-post-export-batch-files.changed.md b/changelog.d/us-post-export-batch-files.changed.md new file mode 100644 index 0000000000..c41e69c2b9 --- /dev/null +++ b/changelog.d/us-post-export-batch-files.changed.md @@ -0,0 +1 @@ +US post-export scoring keeps each household batch of the written H5 in its own file instead of in memory. The scorer still loads the H5 once, bound to its SHA-256, and checks that the batches partition it. It then pickles each batch to a file, records the SHA-256 of the bytes written, frees the frames, and reads each batch back from its file whenever a pass scores it, refusing a file whose bytes changed. The process that scores therefore holds no frame of the H5 between batches: about 0.39 GiB less on the published 57,240-household national file (measured) and about 2.1 GiB less on a 352,932-household national export (estimate), for the whole of certification. Certification keeps the files in `post_export_batches/` in the build's `--out`, which takes about as much disk as the export H5, and the scorer removes them when it closes. Placing a build for certification removes files that a killed attempt left. Scored values are unchanged. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 92645b1559..e311ea4b64 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -436,6 +436,15 @@ one Microsimulation over the whole file. - The scorer loads the written H5 once, binds its SHA-256, and refuses to let the release manifest pin different bytes. +- It then writes each household batch to its own file, recording the SHA-256 + of the bytes written, and frees the frames. Each pass reads every batch back + from its file and refuses one whose bytes changed, so the process that + scores holds no frame of the written H5 between batches. A batch read back + has the same tables, dtypes, values and weights, so scored values are + unchanged. Certification keeps the files in `post_export_batches/` in the + build's `--out`, about as much disk as the export H5 itself, until the + scorer closes; placing a build for certification removes files a killed + attempt left. - It refuses a file whose group units do not each nest in one household, or whose batches do not partition every entity, before any engine exists. - Batches hold at most `--maximum-microsim-batch-size` households (default diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py index ea32c834d1..4717fe4d49 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py @@ -1,4 +1,4 @@ -"""The post-export scorer keeps its household batches in files (1.4 · 4). +"""The post-export scorer keeps its household batches in files. ``_HouseholdBatchedPostExportScorer`` loads the written H5 once, bound to its sha256, and splits it into household batches. It writes each batch to its own @@ -149,7 +149,8 @@ def walk(value: object, where: str) -> None: def _expected_batches(builder, frame: Frame, batch_size: int) -> list[Frame]: - """The batches the scorer selected in memory before 1.4 · 4.""" + """The batches the scorer selected, and held in memory, before it kept + them in files.""" return [ frame diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index 35f87fa617..e9e0cfc91d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -845,7 +845,7 @@ def calls_to(name: str, among=None) -> list[ast.Call]: ] # The scorer opens on the written H5 with the plan recorded before export, - # keeping its batch files in the build's --out (1.4 · 4). + # keeping its household batch files in the build's --out. assert [ast.unparse(call) for call in calls_to("_open_post_export_scorer")] == [ "_open_post_export_scorer(post_export_scoring_plan, dataset_path, " "batch_directory=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY)" diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py index 26265016a6..57be48e016 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py @@ -367,7 +367,7 @@ def close(self) -> None: def test_batches_read_from_their_files_equal_the_written_h5s_batches( builder, tmp_path ) -> None: - """Each batch the scorer reads back from its file (1.4 · 4) holds exactly + """Each batch the scorer reads back from its file holds exactly the rows, columns, dtypes, values and weights of that household batch of a fixture H5 written by the engine's own writer, as the scorer selected it in memory before it kept batches in files.""" diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index ec8896e639..6a1af776bd 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -58,16 +58,19 @@ import importlib.util import json import math +import pickle import platform import re import shlex import shutil import subprocess +import tempfile import time import tomllib import traceback import uuid -from collections.abc import Callable, Iterable, Mapping, Sequence +import weakref +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from contextlib import contextmanager, nullcontext from datetime import UTC, datetime from importlib.resources import files as package_files @@ -5073,7 +5076,11 @@ def _select_households_by_position(frame: Frame, positions: np.ndarray) -> Frame # * the WRITTEN H5 is loaded once (its sha256 bound to the bytes read) and # split once into household batches; every group entity must nest in one # household and the batches must partition every entity, or the scorer -# refuses before any engine exists; +# refuses before any engine exists. Each batch is then written to its own +# file, with the sha256 of its bytes recorded, and the frames are freed; a +# pass reads each batch back from its file and refuses one whose bytes +# changed, so the process that scores holds no frame of the H5 between +# batches (``_PostExportBatchFiles``); # * every construction declares ``spm=US_RELEASE_SPM_SELECTION``; # * a consumer's baseline requests are learned by an engine-free recording # dry run and scored in ONE batch-outer pass, in ascending period order; @@ -5658,6 +5665,78 @@ def _post_export_consumers( return consumers +#: The directory in a build's ``--out`` where certification's post-export +#: scorer keeps its household batch files while it scores. The scorer removes +#: it when it closes or is freed; placing a build for certification removes +#: one an attempt that was killed left (``_place_build_for_certification``). +US_POST_EXPORT_BATCH_DIRECTORY = "post_export_batches" + + +def _new_post_export_batch_directory(batch_directory: Path | None) -> Path: + """A new, empty directory for a scorer's batch files. + + ``batch_directory`` is created and must not exist yet, so a scorer never + writes into, or later removes, a directory it did not make. Without one, + a new temporary directory is made. + """ + if batch_directory is None: + return Path(tempfile.mkdtemp(prefix="microcosm-post-export-batches-")) + directory = Path(batch_directory) + directory.mkdir(parents=True) + return directory + + +class _PostExportBatchFiles(Sequence): + """The written H5's household batches, each kept in its own file. + + Built from the batch frames the scorer selected from the H5 it loaded + once, bound to the H5's sha256: each frame is pickled to its own file in + ``directory`` and the sha256 of the bytes written is recorded. Indexing + reads one batch back as a new frame, which the caller frees once it has + scored the batch, so between batches only the files' paths and digests + are held. A file's bytes must hash to the recorded digest before they are + unpickled, so only bytes this process wrote are loaded and a batch file + that changed is refused. Unpickling gives back the same tables, dtypes, + index, values, weights and strata, so every batch scores the values the + in-memory batch did. (A plain class, for the reason + :class:`_PostExportScoringPlan` gives.) + """ + + def __init__(self, directory: Path, batch_frames: Sequence[Frame]) -> None: + self.directory = Path(directory) + files: list[tuple[Path, str]] = [] + for number, batch_frame in enumerate(batch_frames): + payload = pickle.dumps(batch_frame, protocol=pickle.HIGHEST_PROTOCOL) + path = self.directory / f"batch-{number:05d}.pickle" + path.write_bytes(payload) + files.append((path, hashlib.sha256(payload).hexdigest())) + del payload + self._files = tuple(files) + + def __len__(self) -> int: + return len(self._files) + + def __iter__(self) -> Iterator[Frame]: + # By position, not the Sequence default, which ends at the first + # IndexError: one raised while reading a batch would end the pass + # early, leaving later batches unscored. + for position in range(len(self._files)): + yield self[position] + + def __getitem__(self, position: int) -> Frame: + if isinstance(position, slice): + raise TypeError("Post-export batches are read one at a time.") + path, sha256 = self._files[position] + payload = path.read_bytes() + observed = hashlib.sha256(payload).hexdigest() + if observed != sha256: + raise ValueError( + f"Post-export batch file {path} has SHA-256 {observed}, not the " + f"{sha256} the scorer wrote; the batch is refused." + ) + return pickle.loads(payload) + + class _HouseholdBatchedPostExportScorer: """Scores the written release H5 in household batches (see the block comment above). One instance serves every post-export consumer.""" @@ -5668,6 +5747,7 @@ def __init__( *, maximum_microsim_batch_size: int | None, expected_n_households: int | None = None, + batch_directory: Path | None = None, microsimulation_cls=None, dataset_from_frame=None, load_frame=None, @@ -5700,11 +5780,26 @@ def __init__( ) _assert_post_export_batching_premises(frame, batch_frames) del frame - self._batch_frames: tuple[Frame, ...] | None = batch_frames self.n_batches = len(batch_frames) self.max_batch_households = max( (batch.n("household") for batch in batch_frames), default=0 ) + # The batches go to files in a new directory (``batch_directory``, or + # a temporary one) and the frames are freed; ``_batches()`` reads each + # back when a pass scores it. The directory is removed when the scorer + # closes, is freed or the interpreter exits. + self.batch_directory = _new_post_export_batch_directory(batch_directory) + self._remove_batch_files = weakref.finalize( + self, shutil.rmtree, self.batch_directory, ignore_errors=True + ) + try: + self._batch_frames: _PostExportBatchFiles | None = _PostExportBatchFiles( + self.batch_directory, batch_frames + ) + except BaseException: + self._remove_batch_files() + raise + del batch_frames if microsimulation_cls is None: from policyengine_us import Microsimulation @@ -5795,6 +5890,7 @@ def close(self) -> None: self._finish_open_reform() self._batch_frames = None _collect_family_garbage() + self._remove_batch_files() def _open_reform_for( self, consumer: _PostExportConsumer, reform @@ -5813,7 +5909,8 @@ def _finish_open_reform(self) -> None: if reform is not None: reform.finish() - def _batches(self) -> tuple[Frame, ...]: + def _batches(self) -> _PostExportBatchFiles: + """The batches, each read from its file when it is indexed.""" if self._batch_frames is None: raise RuntimeError("The post-export scorer is closed.") return self._batch_frames @@ -5935,9 +6032,16 @@ def _score( def _open_post_export_scorer( - plan: _PostExportScoringPlan, dataset_path: Path + plan: _PostExportScoringPlan, + dataset_path: Path, + *, + batch_directory: Path | None = None, ) -> _HouseholdBatchedPostExportScorer | None: - """Open the scorer the plan recorded before export, or None if no stage runs.""" + """Open the scorer the plan recorded before export, or None if no stage runs. + + ``batch_directory`` is the new directory the scorer keeps its household + batch files in (a temporary one without it). + """ if plan.error is not None: raise RuntimeError( f"The post-export scoring plan was not built before export: {plan.error}" @@ -5947,6 +6051,7 @@ def _open_post_export_scorer( return _HouseholdBatchedPostExportScorer( dataset_path, maximum_microsim_batch_size=plan.maximum_batch_size, + batch_directory=batch_directory, expected_n_households=plan.n_households, ) @@ -14748,7 +14853,8 @@ def _place_build_for_certification(record: _USBuildRecord, release_dir: Path) -> #568 weight evidence is never copied: the H5 carries the weights. A rerun after a failed certification first removes every file this certification would copy or write, so none of an earlier attempt's - survives. + survives, and the post-export batch files of an attempt that was killed + before its scorer could remove them. """ release_dir.mkdir(parents=True, exist_ok=True) @@ -14764,6 +14870,9 @@ def _place_build_for_certification(record: _USBuildRecord, release_dir: Path) -> "us_ssi_take_up.json", }: (release_dir / name).unlink(missing_ok=True) + stale_batch_files = record.release_root / US_POST_EXPORT_BATCH_DIRECTORY + if stale_batch_files.exists(): + shutil.rmtree(stale_batch_files) build_dir = record.build_dir.resolve() for role, pinned in record.payload["files"].items(): source = (record.release_root / pinned["path"]).resolve() @@ -19503,7 +19612,9 @@ def _certify_us_build( # It loads the written H5 once, binds its sha256 (the manifest must pin # the same bytes), and serves the baseline plans recorded above. post_export_scorer = _open_post_export_scorer( - post_export_scoring_plan, dataset_path + post_export_scoring_plan, + dataset_path, + batch_directory=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, ) # microcosm#368: reform-coverage smoke on the WRITTEN release H5. The column # gate above proves the required keys exist and carry signal; this is the @@ -19658,14 +19769,14 @@ def _certify_us_build( "us_medicare_irmaa_holdout", release_dir / "us_medicare_irmaa_holdout.json", ) - # Every post-export engine stage has run; free the scorer's batch frames. + # Every post-export engine stage has run; remove the scorer's batch files. # The manifest must pin the bytes those stages scored, and both manifests # carry how they were scored (Route A remediation PR-3). post_export_scoring = _post_export_scoring_manifest_block(post_export_scorer) scored_dataset_sha256 = _close_post_export_scorer(post_export_scorer) post_export_scorer = None - # Reads the written H5 without an engine, after the scorer frees its - # batch frames, so it adds no memory on top of them. + # Reads the written H5 without an engine, after the scorer has closed, + # so it adds no memory on top of the scorer's. if telemetry is not None: telemetry.stage( "population_structure_holdout", From d2d87ab1c41e7a729ae1ed7889c0646cb9663b61 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:51:23 +0400 Subject: [PATCH 3/6] Test the post-export batch files' lifetime and refusals (review round 1) These tests fail on the previous commit: - A scorer that was neither closed nor freed must not remove a newer scorer's batch files once its directory's parent was emptied and reused, as placing a build for certification does: each scorer makes its own directory inside a given parent (batch_parent), keeps what the parent already holds, and removes the parent only if it made it. - A pass frees each batch's frame before it reads the next batch's file. - A batch file that changed or cannot be read raises PostExportBatchFileError, and the SSI and Medicare IRMAA held-out reports raise it instead of recording the measurement as unavailable. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_batch_files.py | 151 +++++++++++++++--- .../us/test_us_post_export_scoring.py | 4 +- 2 files changed, 130 insertions(+), 25 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py index 4717fe4d49..2b9c1c2ba2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py @@ -16,7 +16,9 @@ # ruff: noqa: F811 import gc import pickle +import shutil import types +import weakref from pathlib import Path from types import SimpleNamespace @@ -223,7 +225,7 @@ def test_a_batch_file_whose_bytes_changed_is_refused(builder, tmp_path) -> None: try: first_file = sorted(scorer.batch_directory.iterdir())[0] first_file.write_bytes(first_file.read_bytes() + b"changed") - with pytest.raises(ValueError, match="SHA-256"): + with pytest.raises(builder.PostExportBatchFileError, match="SHA-256"): scorer._score([_AGE_KEY], label="age") finally: scorer.close() @@ -233,12 +235,84 @@ def test_a_missing_batch_file_is_refused(builder, tmp_path) -> None: scorer = _open_scorer(builder, _nested_frame(), tmp_path) try: sorted(scorer.batch_directory.iterdir())[-1].unlink() - with pytest.raises(FileNotFoundError): + with pytest.raises(builder.PostExportBatchFileError, match="cannot be read"): scorer._score([_AGE_KEY], label="age") finally: scorer.close() +@pytest.mark.parametrize( + ("writer", "consumer", "filename"), + [ + ( + "_write_ssi_social_security_holdout", + "_ssi_social_security_holdout_consumer", + "us_ssi_social_security_holdout.json", + ), + ( + "_write_medicare_irmaa_holdout", + "_medicare_irmaa_holdout_consumer", + "us_medicare_irmaa_holdout.json", + ), + ], +) +def test_a_holdout_raises_a_refused_batch_file_instead_of_reporting_it( + builder, tmp_path, writer, consumer, filename +) -> None: + """A held-out report records a measurement it cannot make as unavailable; + a batch file that changed or went missing is not such a measurement, and + stops certification as it does in every other post-export stage.""" + + scorer = _open_scorer(builder, _nested_frame(), tmp_path / "h5") + release_dir = tmp_path / "release" + release_dir.mkdir() + try: + first_file = sorted(scorer.batch_directory.iterdir())[0] + first_file.write_bytes(first_file.read_bytes() + b"changed") + with pytest.raises(builder.PostExportBatchFileError): + getattr(builder, writer)( + release_dir=release_dir, + dataset_path=scorer.dataset_path, + release_id="fixture-release", + post_export_scorer=scorer, + baseline_plan=builder._record_post_export_baseline_plan( + getattr(builder, consumer) + ), + ) + finally: + scorer.close() + assert not (release_dir / filename).exists() + + +def test_a_pass_frees_each_batch_before_it_reads_the_next( + builder, tmp_path, monkeypatch +) -> None: + """Between batches the scorer holds no batch frame: the frame read for a + batch is freed (the batch engine holds its own copy of the data) before + the next batch's file is read.""" + + batch_files = builder._PostExportBatchFiles + read_batch = batch_files.__getitem__ + served: list[weakref.ref] = [] + alive_at_each_read: list[int] = [] + + def tracked_read(self, position): + alive_at_each_read.append(sum(ref() is not None for ref in served)) + batch_frame = read_batch(self, position) + # A Frame takes no weak reference; its person table, the same object + # on every call, lives exactly as long as it. + served.append(weakref.ref(batch_frame.table("person"))) + return batch_frame + + monkeypatch.setattr(batch_files, "__getitem__", tracked_read) + scorer = _open_scorer(builder, _nested_frame(), tmp_path) + try: + scorer._score([_AGE_KEY], label="age") + finally: + scorer.close() + assert alive_at_each_read == [0] * scorer.n_batches + + def test_closing_the_scorer_removes_its_batch_files(builder, tmp_path) -> None: scorer = _open_scorer(builder, _nested_frame(), tmp_path) directory = scorer.batch_directory @@ -260,33 +334,61 @@ def test_a_scorer_dropped_without_closing_removes_its_batch_files( assert not directory.exists() -def test_a_given_batch_directory_holds_the_files_and_is_removed_at_close( +def test_a_given_parent_holds_the_scorers_own_directory_until_close( builder, tmp_path ) -> None: - directory = tmp_path / "post_export_batches" + parent = tmp_path / "post_export_batches" scorer = _open_scorer( - builder, _nested_frame(), tmp_path / "h5", batch_directory=directory + builder, _nested_frame(), tmp_path / "h5", batch_parent=parent ) - assert scorer.batch_directory == directory - assert len(sorted(directory.iterdir())) == scorer.n_batches + assert scorer.batch_directory.parent == parent + assert len(sorted(scorer.batch_directory.iterdir())) == scorer.n_batches scorer.close() - assert not directory.exists() + # The scorer made the parent, and removes it once its own directory is gone. + assert not parent.exists() -def test_a_given_batch_directory_that_exists_is_refused_and_kept( +def test_a_given_parent_that_exists_is_kept_with_what_it_holds( builder, tmp_path ) -> None: - directory = tmp_path / "post_export_batches" - directory.mkdir() - kept = directory / "another_scorers_batch" + parent = tmp_path / "post_export_batches" + parent.mkdir() + kept = parent / "another_scorers_batch" kept.write_bytes(b"not this scorer's") - with pytest.raises(FileExistsError): - _open_scorer( - builder, _nested_frame(), tmp_path / "h5", batch_directory=directory - ) + scorer = _open_scorer( + builder, _nested_frame(), tmp_path / "h5", batch_parent=parent + ) + directory = scorer.batch_directory + scorer.close() + assert not directory.exists() assert kept.read_bytes() == b"not this scorer's" +def test_a_scorer_freed_late_leaves_a_newer_scorers_files_in_the_same_parent( + builder, tmp_path +) -> None: + """A scorer that was neither closed nor freed (a failed certification whose + exception is still held) whose parent is then emptied, as placing a build + for certification does, must not remove a newer scorer's files there when + it is finally freed.""" + + parent = tmp_path / "out" / "post_export_batches" + earlier = _open_scorer( + builder, _nested_frame(), tmp_path / "earlier", batch_parent=parent + ) + shutil.rmtree(parent) + newer = _open_scorer( + builder, _nested_frame(), tmp_path / "newer", batch_parent=parent + ) + try: + del earlier + gc.collect() + assert len(sorted(newer.batch_directory.iterdir())) == newer.n_batches + newer._score([_AGE_KEY], label="age") + finally: + newer.close() + + def test_a_scorer_that_cannot_write_its_batches_leaves_no_files( builder, tmp_path ) -> None: @@ -305,27 +407,30 @@ def test_a_scorer_that_cannot_write_its_batches_leaves_no_files( ) }, ) - directory = tmp_path / "post_export_batches" + parent = tmp_path / "post_export_batches" # Python 3.13 raises AttributeError for a local function, 3.14 # PicklingError. with pytest.raises((pickle.PicklingError, AttributeError)): - _open_scorer(builder, frame, tmp_path / "h5", batch_directory=directory) + _open_scorer(builder, frame, tmp_path / "h5", batch_parent=parent) gc.collect() - assert not directory.exists() + assert not parent.exists() def test_certification_removes_an_earlier_attempts_batch_files( builder, tmp_path ) -> None: - """Certification's batch directory is named for it in the build's - ``--out``; placing the build removes one an earlier, killed attempt left.""" + """Certification's scorer keeps its batch directory in a parent named for + it in the build's ``--out``; placing the build removes what an earlier, + killed attempt left there.""" release_root = tmp_path / "out" build_dir = release_root / "build" build_dir.mkdir(parents=True) stale = release_root / builder.US_POST_EXPORT_BATCH_DIRECTORY - stale.mkdir() - (stale / "batch-00000.pickle").write_bytes(b"an earlier attempt's batch") + (stale / "post-export-batches-earlier").mkdir(parents=True) + (stale / "post-export-batches-earlier" / "batch-00000.pickle").write_bytes( + b"an earlier attempt's batch" + ) record = SimpleNamespace( build="fixture-build", release_root=release_root, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index e9e0cfc91d..96491891dc 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -845,10 +845,10 @@ def calls_to(name: str, among=None) -> list[ast.Call]: ] # The scorer opens on the written H5 with the plan recorded before export, - # keeping its household batch files in the build's --out. + # keeping its household batch files in a directory in the build's --out. assert [ast.unparse(call) for call in calls_to("_open_post_export_scorer")] == [ "_open_post_export_scorer(post_export_scoring_plan, dataset_path, " - "batch_directory=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY)" + "batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY)" ] # It opens the file the build wrote, which the record pins by digest # (never a previous run's bytes at the same path, microcosm#443), and From 75509945669e3fdd5dc7c030b2c7551760f6ab9b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:59:25 +0400 Subject: [PATCH 4/6] Fix the post-export batch files' lifetime and refusals (review round 1) - Each scorer makes its own uniquely named directory inside a parent (batch_parent; certification passes --out/post_export_batches), and its cleanup removes only that directory, and the parent once empty if it made it. Before, the cleanup removed whatever was at a fixed path, so a scorer freed late could remove a newer scorer's live files there. - _score reads batches by position and drops each frame once its engine is built. enumerate keeps its last item, so the previous batch's frame was still alive while the next file was read. - A batch file that changed or cannot be read raises PostExportBatchFileError, which the SSI and Medicare IRMAA held-out reports raise instead of recording the measurement as unavailable. Co-Authored-By: Claude Opus 5.5 --- .../us-post-export-batch-files.changed.md | 2 +- docs/us-release-build-rule.md | 17 +-- tools/build_us_fiscal_refresh_release.py | 114 +++++++++++++----- 3 files changed, 95 insertions(+), 38 deletions(-) diff --git a/changelog.d/us-post-export-batch-files.changed.md b/changelog.d/us-post-export-batch-files.changed.md index c41e69c2b9..fff2f693b6 100644 --- a/changelog.d/us-post-export-batch-files.changed.md +++ b/changelog.d/us-post-export-batch-files.changed.md @@ -1 +1 @@ -US post-export scoring keeps each household batch of the written H5 in its own file instead of in memory. The scorer still loads the H5 once, bound to its SHA-256, and checks that the batches partition it. It then pickles each batch to a file, records the SHA-256 of the bytes written, frees the frames, and reads each batch back from its file whenever a pass scores it, refusing a file whose bytes changed. The process that scores therefore holds no frame of the H5 between batches: about 0.39 GiB less on the published 57,240-household national file (measured) and about 2.1 GiB less on a 352,932-household national export (estimate), for the whole of certification. Certification keeps the files in `post_export_batches/` in the build's `--out`, which takes about as much disk as the export H5, and the scorer removes them when it closes. Placing a build for certification removes files that a killed attempt left. Scored values are unchanged. +US post-export scoring keeps each household batch of the written H5 in its own file instead of in memory. The scorer still loads the H5 once, bound to its SHA-256, and checks that the batches partition it. It then pickles each batch to a file, records the SHA-256 of the bytes written, frees the frames, and reads each batch back from its file whenever a pass scores it, freeing it before the next. A file that changed or cannot be read is refused, and the refusal stops certification in every stage, the held-out reports included. The process that scores therefore holds no frame of the H5 between batches: about 0.39 GiB less on the published 57,240-household national file (measured) and about 2.1 GiB less on a 352,932-household national export (estimate), for the whole of certification. Certification's scorer keeps the files in a directory of its own inside `post_export_batches/` in the build's `--out`, which takes about as much disk as the export H5, and removes them when it closes. Placing a build for certification removes files that a killed attempt left. Scored values are unchanged. diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index e311ea4b64..c01045deb5 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -438,13 +438,16 @@ one Microsimulation over the whole file. the release manifest pin different bytes. - It then writes each household batch to its own file, recording the SHA-256 of the bytes written, and frees the frames. Each pass reads every batch back - from its file and refuses one whose bytes changed, so the process that - scores holds no frame of the written H5 between batches. A batch read back - has the same tables, dtypes, values and weights, so scored values are - unchanged. Certification keeps the files in `post_export_batches/` in the - build's `--out`, about as much disk as the export H5 itself, until the - scorer closes; placing a build for certification removes files a killed - attempt left. + from its file, frees it before reading the next, and refuses a file that + changed or cannot be read, so the process that scores holds no frame of the + written H5 between batches. A batch read back has the same tables, dtypes, + values and weights, so scored values are unchanged. A refused batch file + stops certification in every stage, the held-out reports included. +- Certification's scorer keeps the files in a directory of its own inside + `post_export_batches/` in the build's `--out`: about as much disk as the + export H5 itself, until the scorer closes. Placing a build for + certification removes what a killed attempt left there, so two + certifications of one `--out` must not run at once. - It refuses a file whose group units do not each nest in one household, or whose batches do not partition every entity, before any engine exists. - Batches hold at most `--maximum-microsim-batch-size` households (default diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 6a1af776bd..d6fb98685f 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5665,25 +5665,57 @@ def _post_export_consumers( return consumers -#: The directory in a build's ``--out`` where certification's post-export -#: scorer keeps its household batch files while it scores. The scorer removes -#: it when it closes or is freed; placing a build for certification removes -#: one an attempt that was killed left (``_place_build_for_certification``). +#: The directory in a build's ``--out`` in which certification's post-export +#: scorer makes its own directory for its household batch files while it +#: scores. The scorer removes its directory, and this one once empty if it +#: made it, when it closes or is freed; placing a build for certification +#: removes what an attempt that was killed left (``_place_build_for_certification``). US_POST_EXPORT_BATCH_DIRECTORY = "post_export_batches" -def _new_post_export_batch_directory(batch_directory: Path | None) -> Path: - """A new, empty directory for a scorer's batch files. +class PostExportBatchFileError(RuntimeError): + """A post-export batch file changed or cannot be read; the batch is refused. - ``batch_directory`` is created and must not exist yet, so a scorer never - writes into, or later removes, a directory it did not make. Without one, - a new temporary directory is made. + Not a measurement that cannot be made: the held-out reports, which record + those as unavailable, raise this (``_write_ssi_social_security_holdout``, + ``_write_medicare_irmaa_holdout``). """ - if batch_directory is None: - return Path(tempfile.mkdtemp(prefix="microcosm-post-export-batches-")) - directory = Path(batch_directory) - directory.mkdir(parents=True) - return directory + + +def _new_post_export_batch_directory( + batch_parent: Path | None, +) -> tuple[Path, Path | None]: + """A new directory for one scorer's batch files, and the parent it made. + + The directory is new and uniquely named inside ``batch_parent`` (the + system's temporary directory without one), so a scorer only ever removes + files it wrote, even when an earlier scorer used the same parent. The + parent is made if it does not exist, and is then returned, so that the + scorer can remove it again once it is empty. + """ + made_parent = None + if batch_parent is not None: + batch_parent = Path(batch_parent) + try: + batch_parent.mkdir(parents=True) + except FileExistsError: + pass + else: + made_parent = batch_parent + directory = Path(tempfile.mkdtemp(prefix="post-export-batches-", dir=batch_parent)) + return directory, made_parent + + +def _remove_post_export_batch_files(directory: Path, made_parent: Path | None) -> None: + """Remove a scorer's batch directory, and the parent it made once empty.""" + shutil.rmtree(directory, ignore_errors=True) + if made_parent is not None: + try: + made_parent.rmdir() + except OSError: + # Not empty: another scorer's directory, or files someone else + # put there, which this scorer did not write. + pass class _PostExportBatchFiles(Sequence): @@ -5727,10 +5759,16 @@ def __getitem__(self, position: int) -> Frame: if isinstance(position, slice): raise TypeError("Post-export batches are read one at a time.") path, sha256 = self._files[position] - payload = path.read_bytes() + try: + payload = path.read_bytes() + except OSError as error: + raise PostExportBatchFileError( + f"Post-export batch file {path} cannot be read ({error}); the " + "batch is refused." + ) from error observed = hashlib.sha256(payload).hexdigest() if observed != sha256: - raise ValueError( + raise PostExportBatchFileError( f"Post-export batch file {path} has SHA-256 {observed}, not the " f"{sha256} the scorer wrote; the batch is refused." ) @@ -5747,7 +5785,7 @@ def __init__( *, maximum_microsim_batch_size: int | None, expected_n_households: int | None = None, - batch_directory: Path | None = None, + batch_parent: Path | None = None, microsimulation_cls=None, dataset_from_frame=None, load_frame=None, @@ -5784,13 +5822,16 @@ def __init__( self.max_batch_households = max( (batch.n("household") for batch in batch_frames), default=0 ) - # The batches go to files in a new directory (``batch_directory``, or - # a temporary one) and the frames are freed; ``_batches()`` reads each - # back when a pass scores it. The directory is removed when the scorer - # closes, is freed or the interpreter exits. - self.batch_directory = _new_post_export_batch_directory(batch_directory) + # The batches go to files in a new directory of this scorer's own, + # made inside ``batch_parent`` (or the system's temporary directory), + # and the frames are freed; ``_batches()`` reads each back when a pass + # scores it. The directory is removed when the scorer closes, is freed + # or the interpreter exits. + self.batch_directory, made_parent = _new_post_export_batch_directory( + batch_parent + ) self._remove_batch_files = weakref.finalize( - self, shutil.rmtree, self.batch_directory, ignore_errors=True + self, _remove_post_export_batch_files, self.batch_directory, made_parent ) try: self._batch_frames: _PostExportBatchFiles | None = _PostExportBatchFiles( @@ -5997,9 +6038,15 @@ def _score( total=len(batches), outer=outer, ) - for batch, batch_frame in enumerate(batches, start=1): + for batch in range(1, len(batches) + 1): + # Read by position: ``enumerate`` keeps its last item, so the + # previous batch's frame would stay alive while the next is read. + batch_frame = batches[batch - 1] with _automatic_gc_suspended(): simulation = self._construct(batch_frame, reform_system=reform_system) + # The engine holds its own copy of the batch; the frame read + # from the batch's file is freed before the next one is read. + del batch_frame try: known_at_load = _engine_known_periods(simulation, watched) engine = _AscendingPeriodEngine(simulation, label=label) @@ -6035,12 +6082,12 @@ def _open_post_export_scorer( plan: _PostExportScoringPlan, dataset_path: Path, *, - batch_directory: Path | None = None, + batch_parent: Path | None = None, ) -> _HouseholdBatchedPostExportScorer | None: """Open the scorer the plan recorded before export, or None if no stage runs. - ``batch_directory`` is the new directory the scorer keeps its household - batch files in (a temporary one without it). + The scorer keeps its household batch files in a new directory of its own + inside ``batch_parent`` (the system's temporary directory without one). """ if plan.error is not None: raise RuntimeError( @@ -6051,7 +6098,7 @@ def _open_post_export_scorer( return _HouseholdBatchedPostExportScorer( dataset_path, maximum_microsim_batch_size=plan.maximum_batch_size, - batch_directory=batch_directory, + batch_parent=batch_parent, expected_n_households=plan.n_households, ) @@ -11558,6 +11605,9 @@ def _write_ssi_social_security_holdout( maximum_microsim_batch_size=maximum_microsim_batch_size, ) payload["release_id"] = release_id + except PostExportBatchFileError: + # The scored file's integrity, not a measurement: it stops certification. + raise except Exception as error: # Reporting is observational, including an unavailable measurement. # It must not introduce a new release refusal or calibration target. @@ -11589,6 +11639,9 @@ def _write_medicare_irmaa_holdout( maximum_microsim_batch_size=maximum_microsim_batch_size, ) payload["release_id"] = release_id + except PostExportBatchFileError: + # The scored file's integrity, not a measurement: it stops certification. + raise except Exception as error: # Reporting is observational, including an unavailable measurement. # It must not introduce a new release refusal or calibration target. @@ -14854,7 +14907,8 @@ def _place_build_for_certification(record: _USBuildRecord, release_dir: Path) -> rerun after a failed certification first removes every file this certification would copy or write, so none of an earlier attempt's survives, and the post-export batch files of an attempt that was killed - before its scorer could remove them. + before its scorer could remove them. (Two certifications of one ``--out`` + at once are not supported: each removes the other's files.) """ release_dir.mkdir(parents=True, exist_ok=True) @@ -19614,7 +19668,7 @@ def _certify_us_build( post_export_scorer = _open_post_export_scorer( post_export_scoring_plan, dataset_path, - batch_directory=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, + batch_parent=record.release_root / US_POST_EXPORT_BATCH_DIRECTORY, ) # microcosm#368: reform-coverage smoke on the WRITTEN release H5. The column # gate above proves the required keys exist and carry signal; this is the From fc61fe40fe8278a4b9d9933a4a6b1f7707a5168f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:34:04 +0400 Subject: [PATCH 5/6] Test that placement keeps what is not a scorer's batch directory (review round 2) Fails on the previous commit, which removes the whole post_export_batches directory: placing a build for certification must remove only the scorer directories an earlier attempt left there. Also tightens tests that passed for the wrong reason or compared too little: - The unwritable-batch test now keeps the exception, and so the half-made scorer, alive while it checks, so only the scorer's own cleanup can have removed the files (garbage collection ran its finalizer before). - A new test fills the disk on the second batch: neither the part-written file nor the one before it is left. - assert_same_batch also compares the schema, link tables, record of weight changes and metadata. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_post_export_batch_files.py | 42 +++++++++++++++++-- .../us_post_export_batch_files.py | 17 ++++++-- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py index 2b9c1c2ba2..e2a108560a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py @@ -394,7 +394,8 @@ def test_a_scorer_that_cannot_write_its_batches_leaves_no_files( ) -> None: nested = _nested_frame() tables = {entity: nested.table(entity).copy() for entity in nested.entities} - # A value pickle cannot write: the first batch's file fails part-written. + # A value pickle cannot write: pickling the first batch raises before its + # file is written. tables["household"]["unwritable"] = pd.Series( [lambda: None for _ in range(len(tables["household"]))], dtype=object ) @@ -410,9 +411,38 @@ def test_a_scorer_that_cannot_write_its_batches_leaves_no_files( parent = tmp_path / "post_export_batches" # Python 3.13 raises AttributeError for a local function, 3.14 # PicklingError. - with pytest.raises((pickle.PicklingError, AttributeError)): + with pytest.raises((pickle.PicklingError, AttributeError)) as raised: _open_scorer(builder, frame, tmp_path / "h5", batch_parent=parent) - gc.collect() + # The traceback still holds the half-made scorer, so its finalizer has not + # run: the scorer removed its files itself. + assert raised.traceback + assert not parent.exists() + + +def test_a_scorer_whose_disk_fills_leaves_no_part_written_files( + builder, tmp_path, monkeypatch +) -> None: + """A write that fails partway (a full disk) leaves no batch file behind, + neither the part-written one nor those written before it.""" + + write_bytes = Path.write_bytes + batch_writes: list[Path] = [] + + def disk_fills_on_the_second_batch(self, data): + if not self.name.startswith("batch-"): + return write_bytes(self, data) + batch_writes.append(self) + if len(batch_writes) == 2: + write_bytes(self, data[: len(data) // 2]) + raise OSError(28, "No space left on device") + return write_bytes(self, data) + + monkeypatch.setattr(Path, "write_bytes", disk_fills_on_the_second_batch) + parent = tmp_path / "post_export_batches" + with pytest.raises(OSError, match="No space left") as raised: + _open_scorer(builder, _nested_frame(), tmp_path / "h5", batch_parent=parent) + assert raised.traceback + assert len(batch_writes) == 2 assert not parent.exists() @@ -431,6 +461,9 @@ def test_certification_removes_an_earlier_attempts_batch_files( (stale / "post-export-batches-earlier" / "batch-00000.pickle").write_bytes( b"an earlier attempt's batch" ) + # Not a scorer's directory: someone else's, which placement leaves. + kept = stale / "notes.txt" + kept.write_text("not a scorer's") record = SimpleNamespace( build="fixture-build", release_root=release_root, @@ -438,4 +471,5 @@ def test_certification_removes_an_earlier_attempts_batch_files( payload={"files": {}}, ) builder._place_build_for_certification(record, release_root / "releases" / "r") - assert not stale.exists() + assert sorted(path.name for path in stale.iterdir()) == ["notes.txt"] + assert kept.read_text() == "not a scorer's" diff --git a/test_support/microcosm_build/us_post_export_batch_files.py b/test_support/microcosm_build/us_post_export_batch_files.py index 7c3ed478e1..0f6fb5d77a 100644 --- a/test_support/microcosm_build/us_post_export_batch_files.py +++ b/test_support/microcosm_build/us_post_export_batch_files.py @@ -17,12 +17,14 @@ def assert_same_batch(restored: Frame, expected: Frame) -> None: """``restored`` holds exactly ``expected``'s data. - Same entities, columns, dtypes and index; numeric, boolean and date - columns equal byte for byte (so the sign of a zero and a NaN's bit pattern - count); object columns equal value by value with the same Python types; - the same weights, weight kinds and strata. + Same schema, entities, columns, dtypes and index; numeric, boolean and + date columns equal byte for byte (so the sign of a zero and a NaN's bit + pattern count); object columns equal value by value with the same Python + types; the same weights, weight kinds, strata, link tables, record of + weight changes and metadata. """ + assert restored.schema == expected.schema assert restored.entities == expected.entities for entity in expected.entities: restored_table = restored.table(entity) @@ -50,3 +52,10 @@ def assert_same_batch(restored: Frame, expected: Frame) -> None: == np.asarray(expected_weights.values).tobytes() ), entity pd.testing.assert_series_equal(restored.strata, expected.strata, check_exact=True) + assert restored.links == expected.links + for name in expected.links: + pd.testing.assert_frame_equal( + restored.link(name), expected.link(name), check_exact=True + ) + assert restored.mass_log == expected.mass_log + assert dict(restored.metadata) == dict(expected.metadata) From 65538ee0acf7b5f4274b85df1269cf3922bee89f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:35:25 +0400 Subject: [PATCH 6/6] Remove only scorers' batch directories when placing a build (review round 2) Placing a build for certification removed the whole post_export_batches directory, so anything a person had put there went too. It now removes only the directories named post-export-batches-*, which only scorers make, and keeps the rest. Co-Authored-By: Claude Opus 5.5 --- docs/us-release-build-rule.md | 5 +++-- tools/build_us_fiscal_refresh_release.py | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index c01045deb5..96e12f6ab7 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -446,8 +446,9 @@ one Microsimulation over the whole file. - Certification's scorer keeps the files in a directory of its own inside `post_export_batches/` in the build's `--out`: about as much disk as the export H5 itself, until the scorer closes. Placing a build for - certification removes what a killed attempt left there, so two - certifications of one `--out` must not run at once. + certification removes the scorer directories a killed attempt left there + and keeps anything else, so two certifications of one `--out` must not run + at once. - It refuses a file whose group units do not each nest in one household, or whose batches do not partition every entity, before any engine exists. - Batches hold at most `--maximum-microsim-batch-size` households (default diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index d6fb98685f..8f04c7f4e0 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -5669,9 +5669,13 @@ def _post_export_consumers( #: scorer makes its own directory for its household batch files while it #: scores. The scorer removes its directory, and this one once empty if it #: made it, when it closes or is freed; placing a build for certification -#: removes what an attempt that was killed left (``_place_build_for_certification``). +#: removes the scorer directories an attempt that was killed left there +#: (``_place_build_for_certification``). US_POST_EXPORT_BATCH_DIRECTORY = "post_export_batches" +#: The start of the name of each scorer's own batch directory. +_POST_EXPORT_BATCH_DIRECTORY_PREFIX = "post-export-batches-" + class PostExportBatchFileError(RuntimeError): """A post-export batch file changed or cannot be read; the batch is refused. @@ -5702,7 +5706,9 @@ def _new_post_export_batch_directory( pass else: made_parent = batch_parent - directory = Path(tempfile.mkdtemp(prefix="post-export-batches-", dir=batch_parent)) + directory = Path( + tempfile.mkdtemp(prefix=_POST_EXPORT_BATCH_DIRECTORY_PREFIX, dir=batch_parent) + ) return directory, made_parent @@ -14924,9 +14930,13 @@ def _place_build_for_certification(record: _USBuildRecord, release_dir: Path) -> "us_ssi_take_up.json", }: (release_dir / name).unlink(missing_ok=True) - stale_batch_files = record.release_root / US_POST_EXPORT_BATCH_DIRECTORY - if stale_batch_files.exists(): - shutil.rmtree(stale_batch_files) + # Only scorers' own directories: anything else in the parent is kept. + batch_parent = record.release_root / US_POST_EXPORT_BATCH_DIRECTORY + if batch_parent.is_dir(): + for stale_batch_files in batch_parent.glob( + f"{_POST_EXPORT_BATCH_DIRECTORY_PREFIX}*" + ): + shutil.rmtree(stale_batch_files) build_dir = record.build_dir.resolve() for role, pinned in record.payload["files"].items(): source = (record.release_root / pinned["path"]).resolve()