Skip to content

Keep the US post-export scorer's household batches in files, not memory - #1751

Merged
anth-volk merged 6 commits into
mainfrom
claude/post-export-h5-path-only-ffc90b
Nov 26, 2026
Merged

anth-volk merged 6 commits into
mainfrom
claude/post-export-h5-path-only-ffc90b

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

Summary

US post-export scoring (_HouseholdBatchedPostExportScorer in tools/build_us_fiscal_refresh_release.py, run by certification) loaded the written H5 once and kept every household batch frame in memory until it closed. That memory was held for the whole of certification:

  • 0.385 GiB measured on the published 57,240-household national file;
  • about 2.1 GiB estimated for a 352,932-household national export, from its row counts and widths.

Now the scorer writes each batch to its own file. The process that scores holds no frame of the written H5 between batches: only the H5's path and digest, and each batch file's path and digest.

Scored values are unchanged, and POST_EXPORT_SCORING_METHOD is unchanged.

What changes

  • Opening the scorer: it still loads the H5 once, bound to its SHA-256, selects the household batches and runs _assert_post_export_batching_premises. Then _PostExportBatchFiles pickles each batch to its own file, records the SHA-256 of the bytes written, and the frames are freed.
  • Reading a batch: _batches() returns that object. Indexing it reads one batch back. The file's bytes must hash to the recorded digest before they are unpickled, so only bytes this process wrote are loaded. A file that changed or cannot be read raises PostExportBatchFileError.
  • _score: it reads each batch by position and drops the frame once the batch engine is built. The engine holds its own copy of the data. The loop no longer uses enumerate, because enumerate keeps its last item and would keep the previous batch's frame alive while the next file is read.
  • Held-out reports: the SSI and Medicare IRMAA writers record a measurement they cannot make as "unavailable". They now re-raise PostExportBatchFileError, so a refused batch file stops certification in every stage.
  • Where the files go:
    • Each scorer makes its own uniquely named directory (post-export-batches-*) inside batch_parent, or inside the system's temporary directory when none is given.
    • A weakref.finalize removes that directory, and the parent if the scorer made it and it is empty, when the scorer closes, is freed or the interpreter exits.
    • Certification passes batch_parent=<--out>/post_export_batches.
    • _place_build_for_certification removes post-export-batches-* directories left there by a killed attempt, and keeps anything else.
  • Why pickle: the repository's frame checkpoint format needs h5py, which the engine-free CI job does not install. Pickle round-trips pandas and numpy data exactly, and the shared worker pool (Shared worker pool for household-batched policyengine-us work (1.4 · 1) #1726) already pickles frames.
  • Unchanged:
    • the binding of the scored bytes to the H5's SHA-256;
    • _assert_post_export_batching_premises;
    • the batch-order join in _concatenate_post_export_parts;
    • the refusals that use US_POPULATION_AGGREGATE_VARIABLES and POST_EXPORT_BASELINE_BRANCH_READERS;
    • the manifests' post_export_scoring block.

Results are unchanged

  • Engine-workflow test (test_batches_read_from_their_files_equal_the_written_h5s_batches): each batch read back from its file equals that batch of a fixture H5 written by the engine's own writer, as the scorer selected it in memory before. That covers the schema, tables, dtypes, index, every numeric column byte for byte, object values and types, weights and weight kinds, strata, link tables, the record of weight changes, and metadata.
  • Engine-free tests: a frame with negative zero, NaN, 32-bit integers, booleans and strings gives the same comparison, and the values scored from the files equal those of the in-memory batches byte for byte.
  • Published national H5 (local check, not a test): all 29 batches of 2,000 households read back identical.

Memory, disk and time

Measured on the published national file (57,240 households, 29 batches of 2,000):

  • Memory: the 0.385 GiB of batch frames are no longer held. While the scorer opens, the whole frame and all batch frames still exist at once, as before.
  • Disk: 0.386 GiB of batch files, removed at close. For a national export, about 2.1–2.5 GiB (estimate), about the size of the export H5. Route A's certify stage already requires 45 GiB free beside the build before it starts.
  • Time:
    • Opening the scorer takes 2.8–3.2 s, against 2.3 s before.
    • Reading one batch takes about 8 ms (median).
    • Over the national stage's roughly 17,900 batch runs, reading adds about 3 minutes in total (estimate), against 25–51 h for the stage.

Tests

Red-green:

  • e332ad11e, d2d87ab1c and fc61fe40f add the tests and fail on the commits before them.
  • 120a69537, 755099456 and 65538ee0a make them pass.

Run locally, each by node ID:

  • the 15 tests in packages/microcosm-build/tests/engine_free/us/test_us_post_export_batch_files.py (one parametrized test has two cases);
  • packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py::test_main_and_writers_never_build_a_whole_pool_simulation, changed: it now pins batch_parent= in certification's scorer call;
  • packages/microcosm-build/tests/engine_workflow/us/test_us_post_export_scoring.py::test_batches_read_from_their_files_equal_the_written_h5s_batches.

Other existing tests were not run locally; CI runs them. The second reviewer read them and predicted none fail. That includes:

  • the probe's HouseholdRowMap(self.scorer._batches(), ...);
  • the stand-in WrittenH5Scorer;
  • the tests that index or unpack scorer._batches().

Review

Two rounds of adversarial review.

  • Round 1 found three defects, each fixed with a test first:
    • Cleanup removed whatever was at a fixed path, so a scorer freed late could remove a newer scorer's live files.
    • The previous batch's frame stayed alive while the next file was read.
    • The held-out reports turned a refused batch file into "unavailable".
  • Round 2 found nothing serious. Its reviewer broke the code on purpose in a scratch copy to check that the tests catch it. It found:
    • placement removed the whole parent directory, now fixed;
    • one test passed for the wrong reason, and the batch comparison missed link tables, metadata and the record of weight changes, both now fixed.

Known limits

  • Two certifications of one --out at once remove each other's batch files. Running them at once was already unsupported, because placement also removes the other run's release-directory files.
  • Files left by a killed probe or sweep: tools/probe_us_post_export.py and tools/sweep_us_post_export_scoring.py keep their batch files in the system's temporary directory. A process killed without running its exit handlers leaves them there: SIGKILL, or the sweep's os._exit when a worker passes 7 GiB. Only certification removes an earlier attempt's files.
  • A single batch (no --maximum-microsim-batch-size, or a file no larger than one batch): while opening, and while reading each pass, the process briefly holds the pickled bytes beside the frame. That is still below the whole-file engine that follows.
  • The probe's smoke analysis (HouseholdRowMap) reads every batch back at once, as many frames as the scorer held before.

Overlap with #1722 and #1725

Both change this scorer. git merge-tree with each branch, as of their current heads, merges without conflicts.

#1725's _baseline_for calls self._batches() only to check that the scorer is open. It wraps the merged baseline pass in except Exception and then lets each consumer score its own plan. Whichever of the two PRs merges second should add except PostExportBatchFileError: raise before that handler. Without it, a refused batch file still stops certification, but one pass later and after a log message saying each consumer will score its own plan.

Deployment and environment variables

No CI workflow, Dockerfile, Terraform or Modal code changes, and no environment variable is read or added.

🤖 Generated with Claude Code

anth-volk and others added 6 commits November 26, 2026 00:05
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
…iew 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 <noreply@anthropic.com>
…ound 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 <noreply@anthropic.com>
@anth-volk
anth-volk marked this pull request as ready for review November 26, 2026 19:01
@anth-volk
anth-volk merged commit c585965 into main Nov 26, 2026
12 checks passed
@anth-volk
anth-volk deleted the claude/post-export-h5-path-only-ffc90b branch November 26, 2026 19:02
juaristi22 added a commit that referenced this pull request Nov 27, 2026
…the e4d46c93 feed and the new CI caps (#931)

Main took six pull requests since 4b78a9b: #1736 (LCFS spending drawn as
a budget and a donor's mix, with a decile receipt beside ONS Family
Spending, the UK feed re-pinned to Chronicle e4d46c93, and register
renewals), #1779 (the CI caps from the slowest legs of 19 to 26 Nov), #1772
(a batch file's error skips the fallback), #1767 (New Zealand declares its
receipt's take-up cap), #1751 (the US post-export H5 path) and #1723 (US QRF
identity tests). The engine lock does not move.

Eight files conflicted.
- uk_runtime/lcfs_consumption.py: main's receipt imports and the clip's
  docstring, which now names the mix donor and keeps this branch's count of
  distinct source households over every clone. Main's new decile and
  range-step receipts count the frame's support in distinct source
  households (source_household_id), so on the clone-first spine a source
  household's clones count once.
- uk_runtime/graph_kernels.py: the LCFS stage keeps this branch's full list
  under the derived binding rule and adds microcosm.fit.donors, which main's
  draw computes through.
- uk_runtime/calibration_run.py: main added the LCFS decile gate to the spine
  gate scope, which this branch keeps in gate_scopes.py; the gate goes there.
- .github/workflows/test.yml: main's caps and their basis, and this branch's
  note on the after-merge job's cap.
- The gate contract pins, the coverage manifest and the H2 fixture are
  recomputed on the merged tree.

The feed. Main moved the UK feed from Chronicle 15040ea5 to e4d46c93 and
recorded that every 15040ea5 row is byte-identical there, the 487 new rows
being ONS Family Spending. This branch's own Scottish Band D facts take the
new pin stamps with their 32 rows unchanged, as main's re-pin did for its
vendored resources; the local membership takes main's feed label and DESNZ
keys beside this branch's two UC seat deferrals. The vendor tool's check
against the e4d46c93 artifact did not run here, which lacks that artifact.

Checks: with policyengine-uk hidden, as in CI's engine-free job, the
tests main's six pull requests change, the LCFS, consumption, Band D,
vendoring and feed tests, the UK graph's binding rules, the nesting,
stage health, battery, contract, gate and coverage tests (2,245 pass;
the vendoring test that rebuilds the vendored resources from a local copy
of the pinned feed refuses this machine's 15040ea5 copy, as it should, and
skips in CI, which has none); the US coverage report and pins (--check);
CI's test plan verify; and on the engine, H2 parity, the UK graph, the
consumption resources and the release input coverage (56 pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant