Skip to content

Free large US release-build objects after their last use - #1697

Merged
anth-volk merged 20 commits into
mainfrom
claude/release-free-after-last-use-eb46b7
Nov 25, 2026
Merged

anth-volk merged 20 commits into
mainfrom
claude/release-free-after-last-use-eb46b7

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

The US national build, tools/build_us_fiscal_refresh_release.py::_main, is one function of several thousand lines, so every local it binds stays alive until it returns. Several of those locals are full frames (2–3.5 GB each) or the calibration's constraint matrices (about 0.25–1 GB). This PR frees each one once nothing reads it:

  • ACS predictor-join result. _main keeps its receipt and deletes the result straight away. Its .frame would otherwise keep the post-join frame alive after the next stage rebinds base_frame.
  • The nine donor tables. Each load_*_donor(...) call is now a keyword argument of its with_us_* stage call, so no local holds the table once the stage returns. The order of the loader calls and the telemetry stages is unchanged.
  • base_frame. Rebound to None right after the export input-mass check, its last reader. It is rebound rather than deleted because many shadow_gate lambdas in _main read it (US: use the shared Microcosm modules where no output changes #1585's shadow evaluation), and ruff reports a lambda's read of a name the function deletes later as an undefined name (F821). Every one of those lambdas runs before the rebinding.
  • The export reference frame. Loaded inside the new _record_export_input_mass_gate, so the frame is a local of that function and is freed when the check returns or raises. Like _record_qrf_tail_concentration_gate, the function holds all of main's code for this check, in the same order: the reference's sha256 into export_input_mass_reference, the load, the shadow_gate call around the unchanged _export_input_mass_gate, and the exception handling (shadow_not_run when the reference did not load, the same failure line under earlier failures, a re-raise otherwise).
  • release_engine. Rebound to None once the written H5's stored-input check has recorded its result, for the same reason as base_frame. That check stays right after the H5 write, as test_us_stored_input_register requires, and reads only column names and the module-level PolicyEngine-US system. The engine is then freed for the rest of the build: the export audit, the calibration NPZ and the build record.
  • Constraint matrices. New microcosm.calibrate.without_constraint_matrix(result), in the new module microcosm/calibrate/dropped_matrix.py, replaces each CalibrationProblem.matrix with a DroppedConstraintMatrix that keeps only shape and nnz: the refit's matrix and, for an L0RefitResult, the selection's matrix over the full frame. _main calls it right after _without_calibrated_frames, before ladder_outcome is rebound, so neither name keeps the matrix. Later code reads only the shape and nonzero count (target_surface_payload), which stay correct; the build record (_us_build_record) reads the diagnostics, the targets and the losses. Any use that needs the entries raises ConstraintMatrixDroppedError (products, slicing, np.asarray, len, the CSR arrays, CalibrationProblem.estimates; encode_problem raises ValueError from it). Nothing reports a zero nonzero count. Objects of other types, such as the SimpleNamespace results the release tool's end-to-end tests pass through _main, are returned unchanged, as _without_calibrated_frames already does.
  • Release input-coverage cache. clear_installed_list_parameter_baseline_cache() (in release_input_coverage.py) runs right after assert_release_input_coverage_manifest_current(). The functools.cache it clears holds a reformed PolicyEngine-US system's parameter tree, which would otherwise stay alive through the source stages and calibration.

Nothing in the build reads the cache after the start-up check; the scoring plan's dry run records requests only and builds no reform. The reform-coverage smoke, the cache's other reader, runs at certification (tools/certify_us_national_build.py), a separate process that builds its own system as it did before this change.

The helper lives in a new module so that the attested solver sources (microcosm.calibrate.solve and .matrix, hashed by the calibrate.adam@1 kernel, the spec-engine seed digests and the transport evidence contracts) do not change: tools/repin_us_spec_engine_contracts.py --check and tools/spec_engine_coverage.py --check exit 0, and test_acceptance_h_parity.py::test_h1_kernel_parity and test_spec_engine_loader.py::test_semantic_hash_has_golden_vector_and_surface_separation pass without repinning.

Outputs

No computation changes. The H5 is written from the same export_frame, and the calibration NPZ, the diagnostics and the target surface come from the same weights, diagnostics and problem fields. test_dropping_the_constraint_matrix_leaves_the_written_calibration_unchanged writes from a result without its matrices and checks that nothing raises and that the NPZ arrays (names, dtypes, values), the diagnostics payload's JSON, the target surface and the in-sample fit equal those of the original, for a single-solve result and an L0-refit result. Of these, only the target surface reads the matrix (its shape and nonzero count); the rest show that no writer needs it. The calibrate tests check the same for diagnostics_payload and target_surface_payload. No checkpoint format changes.

Tests

Red first, then green, each run by node ID. Independent reviewers then tried to break the change and the tests over several rounds, using mutated copies of the tool. Every defect they found is fixed and covered by a test.

New:

  • packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py:
    • syntax-tree checks of _main for each del or rebinding to None (one top-level statement, after every read and binding, before the next point that matters);
    • the donor loaders as stage arguments;
    • no other name, container, copy, loop variable or stored argument keeps a freed object (a list of reviewed exceptions);
    • no load_us_frame call or reference-frame local in _main;
    • the matrix drop placed after the solves, before the target-surface reads and before ladder_outcome is rebound. No tool code that can run after the drop reads a matrix's entries. That covers _main's later statements and the tool functions, classes and module variables they name, followed transitively. It also covers objects, function values and results bound before the drop and used after it. Reading shape and nnz is allowed;
    • the cache clear placed right after the start-up check. Nothing that can run after it in the build refills the cache. The reform-coverage smoke is reached only through the scoring plan's request-recording run, and no real post-export scorer is reached.
    • It also executes slices of _main's statements with weak references that must be dead afterwards: the ACS join statements, and the matrix-drop statements with real dense and L0-refit results.
    • It checks that _record_export_input_mass_gate frees its reference when the check returns, when it raises, and when it records its error under earlier failures, and that it keeps neither the export frame nor base_frame.
    • With the national scope's shadow evaluation switched on, as on every real run, it checks that the shadow's evaluation receives the loaded reference and keeps none of the three frames. For a reference that does not load and for a check that raises, with and without earlier failures, it checks the same order and records as main. The sha256 is recorded first. Under earlier failures the same failure line is appended; otherwise the error propagates. The shadow records a raised check once, and a reference that did not load as not run only when the build goes on. No case records a verdict difference.
    • It runs the output-equality test above.
  • packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py, five tests:
    • the matrix and its CSR arrays are freed while the shape, nonzero count, target surface and diagnostics payload are kept, for single-solve and L0-refit results whose matrices store fewer entries than they have cells;
    • the kept count is the stored-entry count (nnz, explicit zeros included);
    • every use that needs the entries raises;
    • other objects pass through unchanged.
  • packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py: clearing the cache frees the cached system, and the next call builds it again.

Updated:

  • test_us_post_export_scoring.py::test_main_drops_the_calibration_frames_before_the_export expects the new result = without_constraint_matrix(result) binding.
  • ::test_main_has_no_calibrated_target_frame_at_the_export_write now also checks that the matrices are dropped when the H5 is written.
  • test_us_fiscal_refresh_builder.py::test_gate_evidence_files_are_the_files_their_gates_write names the new check function.

Existing tests run against the change:

  • test_us_fiscal_refresh_builder.py::test_main_writes_diagnostics_before_post_calibration_gate_failure (every mode, through builder.main());
  • ::test_release_calibration_diagnostics_match_the_published_json_schema;
  • test_us_fiscal_refresh_gate_shadow.py::test_every_degraded_mode_handler_records_a_gate_kept_from_running and test_us_battery_bindings.py::test_every_entry_is_wired_at_a_site_calling_its_gate, which read the tool's shadow sites;
  • the early-refusal builder.main() tests;
  • the export input-mass check tests;
  • test_us_release_base_input_invariant.py::test_release_calls_to_base_stages_are_pinned;
  • the existing del target_frame tests.

Not changed here (follow-ups)

  • pool_frame keeps the validated pool frame alive for the whole run on the pool and exact-k paths, because later code only tests pool_frame is None.
  • selection_candidate_frame keeps the pre-selection frame alive on the frozen-support selection path.
  • Out of scope for this task: computing _engine_input_variables() once, splitting _main into per-phase functions, and parsing the SIPP CSV once.

No release run was made: the change was checked only with the tests above.

🤖 Generated with Claude Code

anth-volk and others added 19 commits November 20, 2026 00:28
The US release tool's _main is one long function, so every local stays
alive until it returns. Free the objects it no longer reads:

- delete the ACS predictor-join result once its receipt is taken, so its
  frame does not outlive the next stage's rebinding of base_frame;
- pass the nine donor-table loader calls straight into their stages;
- delete base_frame after the export input-mass check, its last reader;
- load the export reference frame inside a new
  _export_input_mass_gate_with_reference_h5, so it is freed when the check
  returns or raises;
- delete release_engine after the H5 write;
- replace each calibration constraint matrix (the refit's and, under L0,
  the selection's) with its shape and nonzero count through a new
  microcosm.calibrate.without_constraint_matrix; any later use that needs
  the entries raises ConstraintMatrixDroppedError;
- clear the installed-parameter cache in release_input_coverage after the
  start-up check, through clear_installed_list_parameter_baseline_cache.

Outputs are unchanged: the target surface, diagnostics payload and
calibration NPZ arrays written from a result without its matrices equal
those of the original.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Pin the statements in _main that bind another name or container to a
  freed object, so a new alias cannot keep one alive past its del.
- Check the reference-loading check with pytest.raises, and compare the
  reference by identity through the loader instead of weak-reference
  identity.
- Check that no donor loader is cached, that nothing refills the
  input-coverage cache before the post-export scorer, and that the tool
  never reads .matrix or calls .estimates.
- Exercise the real cached _installed_parameter_stages on stand-in engine
  modules.
- Show the release calibration_diagnostics.json is byte-identical with and
  without the constraint matrix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
microcosm.calibrate.solve and .matrix are attested sources: the
calibrate.adam@1 kernel hash, the spec-engine seed digests and the
transport evidence contracts hash their bytes, so editing them moves those
pins. The helper changes no solve, so it moves to a new module,
microcosm/calibrate/dropped_matrix.py, and solve.py and matrix.py are back
to main's bytes. The repin and coverage --check runs exit 0, and the H1
kernel parity and spec-engine loader hash tests pass unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Give the matrix-dropping tests a sparse constraint matrix (a renter
  target) and a stored explicit zero, so a recorded cell count or a
  count of nonzero values would fail them.
- Widen the alias check to conditional and boolean expressions,
  container calls, dataclasses.replace, getattr, augmented assignment,
  loop and with targets, and storing method calls, with a test of each.
- Restrict the matrix-read scan to the statements after the drop and the
  tool functions they reach with the calibration result.
- Match cache-filling calls made through a module attribute.
- Accept SciPy's encoding error whether or not it is chained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main now evaluates the export input-mass check through shadow_gate, and
many shadow-gate lambdas in _main read base_frame and release_engine.
Ruff reports a lambda's read of a name that the function deletes later
as an undefined name, so _main rebinds both names to None instead; the
lambdas all run before the rebinding.

The export check's reference load, its shadow_gate call and its
degraded-mode handling move together into _record_export_input_mass_gate
(as _record_qrf_tail_concentration_gate does for the QRF tail check), so
the reference frame stays local to that function. A new test arms the
national shadow and checks that the shadow's evaluation gets the loaded
reference and does not keep it. The engine test now checks that the
release directly follows the H5 write, since post-export scoring moved
to _certify_us_build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Run the export input-mass check with the national shadow armed and an
  earlier failure on record, once with a reference that does not load
  and once with a check that raises. Check the sha256, the failure line,
  the shadow's outcome and that it records no verdict difference.
- Hold the export and base stand-in frames only through weak
  references, so the export-check tests see if the check keeps either.
- Widen the alias check to copies, functools.partial, setattr, every
  argument of dataclasses.replace and default arguments of nested
  functions and lambdas.
- Follow tool functions passed any part of the calibration result, and
  follow the tool functions _main calls after the cache clear, so a
  call made through a helper is seen too.
- Report surviving CSR arrays by index rather than comparing a list of
  arrays to None.
- Describe certification as a separate process in the changelog fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reform-coverage smoke now runs at certification, in its own process,
so nothing in the build rebuilds the cached system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Count a lambda as holding its default arguments wherever it is kept,
  so one passed straight to shadow_gate is not flagged; keep flagging a
  nested def, which a local holds.
- Add the remaining container calls, annotated and walrus assignments,
  and harmless counter-examples of the newer forms to the alias
  self-test.
- Follow tool functions used as values as well as called ones, count
  the reform-coverage smoke functions as cache fillers, and expect only
  the scoring plan's request-recording call; read getattr(..., "matrix")
  as a matrix read.
- Run the export check's error paths with the shadow armed on a clean
  run too, and give the parametrized cases plain ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Follow module-level classes of the tool as well as functions, and
  start the matrix-read scan from every definition _main names after
  the drop, so a read through a method or functools.partial is seen.
- In the cache test, expect the reform-coverage smoke call only in
  _reform_coverage_smoke_consumer, reached only through the scoring
  plan's consumers, and the real consumer scorer not at all; compare
  called names rather than call text.
- Cover dict literals, the other storing methods, keyword-only lambda
  defaults and the refit and selection attributes in the alias
  self-test.
- Make three comments say what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Accept reads of a dropped matrix's shape and nnz, which the
  placeholder keeps, and report each other read with its definition and
  file line number; the scans take _main's later statements from the
  file's own syntax tree.
- Count module-level variables as definitions, so a table of tool
  functions brings in what it names.
- In the cache test, match every reference to a cache-filling function,
  not only calls, and require that no real post-export scorer is reached
  instead of pinning which functions name the consumers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Record every module-level statement that defines or rebinds a name,
  so a later rebinding cannot hide a function's body from the scans.
- Do not follow names used only in type annotations.
- Restore the check that only the scoring plan names the post-export
  consumers, with a note on how to add a caller that only lists them,
  and check that the real scorer names exist in the tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An object built before the matrix drop or the cache clear, such as the
build's progress reporter, can run its methods afterwards; the scans
now start from every tool class _main names as well as from what its
later statements name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Take the tool classes from everything _main reaches, not only those it
names itself, so a reporter built through a helper is followed; and add
each tool function _main uses as a value, which a local can hold until
after the drop or the cache clear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A function that _main calls before the matrix drop or the cache clear
can hand back a tool function or a closure that runs afterwards, as
_post_export_consumers and _reform_validation_consumer do. The scans now
also start from every tool function used as a value anywhere _main
reaches, and from every reached function that returns a lambda or a
function it defines (not one that only passes a lambda to a call, as to
shadow_gate).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Scanning every reached function that returns a closure failed on
harmless pre-drop helpers. The scans now follow what a call before the
point names only when _main binds its result to a local that it reads
after the point, and take function values from _main only. A closure,
function or object built before the drop and used after it is still
followed; one built, used and deleted before the drop is not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The microcosm.calibrate package's __init__ now imports dropped_matrix,
so the transport gate bindings' identity holds one more module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stored-input test holds the written H5's stored-input check right
after the H5 write, so the release of release_engine moves to just after
that check's result is recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_us_stored_input_register holds the written H5's stored-input check
right after the H5 write, so release_engine is rebound to None once that
check's result is recorded instead of between the two. The check reads
only column names and the module-level PolicyEngine-US system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk requested a review from juaristi22 November 24, 2026 14:17

@juaristi22 juaristi22 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 479cad5bb. Dropping the constraint matrices cannot change a calibration output. Every solve finishes, and the export frame takes the calibrated weights, before without_constraint_matrix runs, and nothing after it reads a matrix's entries. One thing before merge, and one note.

What I checked

  • After the drop, result reaches seven consumers. They read the weights, initial weights, diagnostics, final loss, n_nonzero, skipped targets and problem.targets; target_surface_payload reads only shape and nnz. write_calibration_diagnostics goes through diagnostics_payload, which reads target_vector and targets. Nothing in the tool or in diagnostics.py reads the entries.
  • Only result and ladder_outcome hold the problem, and ExactKLadderCalibration keeps one result, so rebinding both frees the matrices.
  • A missed read would stop the build rather than change a number. The placeholder raises on products, np.asarray, len, bool, attribute probes and estimates(), and shadow_gate re-raises.
  • On an invented 3,700 × 300,000 CSR matrix with 19.8 million stored entries (227 MiB), swapping in the placeholder and dropping the last reference freed all of it.

Before merge

  1. Coordinate with #1683, which also edits tools/build_us_fiscal_refresh_release.py: whichever merges second resolves the conflict there.

Note

  • The next US national build would help measure the saving, which isn't measured yet, and would show _main passing the drop with a real calibration result. No test does that: the end-to-end tests pass SimpleNamespace results, which without_constraint_matrix returns unchanged. This needn't hold up the merge.

Checked

  • 980 of 989 tests pass locally (macOS arm64, Python 3.14). They include the 20 in test_us_release_frees_after_last_use.py, the new test_diagnostics.py cases, test_solve.py, and the calibrate parity and spec-engine pins without repinning; the 9 skips need the US engine, the pinned Chronicle feed or microdf.

Resolves the one conflict #1683 brought: the import block at the top of
test_us_post_export_scoring.py keeps main's weakref and Iterator imports
and this branch's DroppedConstraintMatrix import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk merged commit ac7ab99 into main Nov 25, 2026
12 checks passed
@anth-volk
anth-volk deleted the claude/release-free-after-last-use-eb46b7 branch November 25, 2026 14:00
anth-volk added a commit that referenced this pull request Nov 25, 2026
main's #1697 loads each donor table inside its stage's call, so no local
keeps it. This branch builds the five SIPP donors inline from the shared
December rows, so the merged _main keeps both: the SCF donor loaded inline,
the shared read once, and each SIPP donor built in its stage's call.

#1697's test_main_passes_each_donor_table_straight_into_its_stage now covers
the five build_sipp_2023_*_donor calls in place of the removed loaders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 25, 2026
Takes #1697 (free release-tool objects after their last use) and #1690 (UK
SPI stage-1 reference forests), so the engine-free job tests the same tree
as main plus this branch. No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 25, 2026
…he SPI forest release and the shared SIPP read (#931)

Main took seven pull requests since cac12ab: #1724 (each kernel reads
read-only views of its inputs instead of a deep copy), #1690 (the SPI
stage-2 forests freed before each later fit), #1686 (the SIPP person file
read once for its five donor tables), #1697 (release tools free large
objects after their last use), #1726 (a shared worker pool), #1660 (the
County Files ACS donor patch) and #1707 (New Zealand's geography layer
labels). No feed or engine pin moves, so no file is re-pinned.

Four files conflicted, all pins that both sides moved: the US spec-engine
seed map and seed protocol, the UK loader and US spec pins, and the US F0
coverage report. Each is computed on the merged tree, and the coverage
report is regenerated (--check passes; 41/41 inventory checks).

Two of main's new tests needed this branch's code reviewed.
- #1724's scan for writes into shared buffers finds np.add.at in two
  weight folds of the identity tool: _pre_split_household_weights, which
  this branch changed, and _pre_high_value_household_weights, which it
  added. Both write into the copy of the household weights that
  _pre_residential_household_weights makes and _pre_clone_fold and the
  folds pass along, so both findings are reviewed with their digests, and
  the helpers the reasons rest on take theirs, _pre_clone_fold included.
- #1690's SPI forest-release test froze origin/main's SPI output and
  receipts; this branch's keyed draws move them, as the test foresees. The
  macOS arm64 digests are recorded from this code. Linux x86_64's need a
  recording under Docker, which this machine lacks, so those two tests
  skip there and the same-run checks still run. The owner-manager rule
  rewrites owned_company_carries_on_property_business after the draw, as
  it does the trade flag, and on the synthetic fixture's draws it moves one
  drawn person, so the flag joins the targets rewritten after the draw.

Checks: main's changed tests, the pin tests and the kernel-binding test
pass (1,931, then the shared-buffer scan's 99 and the SPI forest-release
test's 48 after the two reviews), and so does the H2 clone-first test at
one and four clones (34).

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.

2 participants