Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
7433ac0
Free large release-tool objects after their last use
anth-volk Nov 17, 2026
ccc5e9d
Add changelog fragment for freeing release-tool objects
anth-volk Nov 17, 2026
4dc6d71
Tighten the release-tool freeing tests after review
anth-volk Nov 17, 2026
5201753
Keep the matrix-dropping helper out of the attested solver modules
anth-volk Nov 17, 2026
2837a79
Strengthen the release-tool freeing tests after the second review
anth-volk Nov 19, 2026
86169f7
Free base_frame and release_engine by rebinding after the rebase
anth-volk Nov 19, 2026
8d3dd02
Test the export check's error paths with the shadow armed
anth-volk Nov 19, 2026
83e7345
Say where the coverage cache is read again after the clear
anth-volk Nov 19, 2026
c249e9d
Close the gaps the fourth review found in the freeing tests
anth-volk Nov 19, 2026
fcc3015
Follow tool classes and pin the smoke's only path in the freeing tests
anth-volk Nov 19, 2026
c3fb2d8
Let the matrix scan accept size reads and report file lines
anth-volk Nov 19, 2026
f5cdedc
Keep every definition of a tool name and skip annotations in the scans
anth-volk Nov 19, 2026
ef9204f
Follow every tool class _main names in the freeing scans
anth-volk Nov 19, 2026
7eac9d5
Start the freeing scans from all classes and stored functions of _main
anth-volk Nov 19, 2026
4aab639
Follow returned closures and stored functions anywhere _main reaches
anth-volk Nov 19, 2026
b26559a
Follow results kept for later instead of every closure factory
anth-volk Nov 19, 2026
7532828
Count calibrate.dropped_matrix among the modules the gate bindings reach
anth-volk Nov 19, 2026
a199f86
Expect the release engine freed after the written-file check
anth-volk Nov 19, 2026
479cad5
Free the release engine after the written-file check
anth-volk Nov 19, 2026
b784581
Merge main (47c644c15) into the release-tool freeing branch
anth-volk Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/release-free-after-last-use.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The US national build (`tools/build_us_fiscal_refresh_release.py`) frees large objects once nothing reads them, instead of keeping them until `_main` returns. It deletes the ACS predictor-join result once its receipt is taken, passes each of the nine donor-table loader calls straight into its imputation stage, releases `base_frame` after the export input-mass check, loads the export reference frame inside that check (`_record_export_input_mass_gate`, which also holds the check's shadow evaluation and its error handling), and releases `release_engine` once the written H5's stored-input check has run. After the solve it replaces each constraint matrix, the refit's and, under L0 selection, the selection's over the full frame, with its shape and nonzero count through the new `microcosm.calibrate.without_constraint_matrix`; the calibration diagnostics' target surface reads only those two numbers, and any later use that needs the entries raises `ConstraintMatrixDroppedError` (the placeholder is `DroppedConstraintMatrix`). After the start-up check of the release input-coverage manifest it clears the module's cached PolicyEngine-US parameter system (`clear_installed_list_parameter_baseline_cache`), so the build no longer keeps that system through the source stages and the calibration. Written outputs are unchanged.
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"ReleaseInputCoverageManifest",
"assert_release_input_coverage_manifest_current",
"check_resolved_list_edit_target",
"clear_installed_list_parameter_baseline_cache",
"installed_list_parameter_baseline",
"list_parameter_baseline",
"list_parameter_pieces",
Expand Down Expand Up @@ -654,7 +655,8 @@ def check_resolved_list_edit_target(
def _installed_parameter_stages() -> tuple[Mapping[str, str], Any]:
"""The installed engine's first breakpoints at its first reform pass.

Builds one PolicyEngine-US system per process with a reform that records
Builds one PolicyEngine-US system per process (again after
:func:`clear_installed_list_parameter_baseline_cache`) with a reform that records
each leaf parameter's first breakpoint the first time the system applies
it (before backdating), and returns those with the finished system's
parameter tree, which the baseline lists are read from.
Expand All @@ -678,11 +680,23 @@ def apply(self) -> None:
return first_breakpoints, system.parameters


def clear_installed_list_parameter_baseline_cache() -> None:
"""Drop the system :func:`installed_list_parameter_baseline` caches.

The cache keeps a reformed PolicyEngine-US system's parameter tree until
the process exits or this is called. A long run that needs it only at
start-up calls this afterwards; the next call to
:func:`installed_list_parameter_baseline` builds the system again.
"""
_installed_parameter_stages.cache_clear()


def installed_list_parameter_baseline(path: str, edit: ListParameterEdit) -> list[str]:
"""The installed PolicyEngine-US baseline list an edit resolves against.

Builds one tax-benefit system per process (see
``_installed_parameter_stages``). Besides :func:`list_parameter_baseline`
``_installed_parameter_stages``), or again after
:func:`clear_installed_list_parameter_baseline_cache`. Besides :func:`list_parameter_baseline`
on its finished parameter tree, the edit must start after the list's
first breakpoint at the system's first reform pass, so the system the
scorer builds applies the edit to the same baseline it resolved on.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2235,3 +2235,57 @@ def test_route_variable_cannot_regress_to_reviewed_exclusion(

with pytest.raises(ValueError, match=column):
assert_release_input_coverage_manifest_current(manifest=demoted)


def test_clearing_the_installed_parameter_cache_frees_the_cached_system(
monkeypatch,
) -> None:
"""The release tool clears the cache after its start-up check, so the
tax-benefit system the check built is not kept for the whole run; the next
caller builds it again. The real cached function runs, on stand-ins for the
engine packages."""
import gc
import sys
import types
import weakref

class ParameterTree:
"""A stand-in for the reformed system's parameter tree."""

trees_built: list[weakref.ref] = []

class CountryTaxBenefitSystem:
def __init__(self, reform=()):
self.parameters = ParameterTree()
trees_built.append(weakref.ref(self.parameters))

class Reform:
"""A stand-in for policyengine-core's reform base class."""

engine = types.ModuleType("policyengine_us")
engine.CountryTaxBenefitSystem = CountryTaxBenefitSystem
core = types.ModuleType("policyengine_core")
reforms = types.ModuleType("policyengine_core.reforms")
reforms.Reform = Reform
core.reforms = reforms
monkeypatch.setitem(sys.modules, "policyengine_us", engine)
monkeypatch.setitem(sys.modules, "policyengine_core", core)
monkeypatch.setitem(sys.modules, "policyengine_core.reforms", reforms)
cached = coverage_module._installed_parameter_stages
cached.cache_clear()
try:
first = cached()
assert cached() is first
del first
gc.collect()
assert len(trees_built) == 1 and trees_built[0]() is not None

coverage_module.clear_installed_list_parameter_baseline_cache()
gc.collect()

assert trees_built[0]() is None
cached()
assert len(trees_built) == 2
finally:
# No stand-in system stays cached for a later test.
cached.cache_clear()
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@
BINDING_MODULES_ADDED_AFTER_BASE = frozenset(
[
"microcosm.calibrate.hierarchy_labels",
# The microcosm.calibrate package's __init__ imports dropped_matrix,
# which replaces a calibration result's constraint matrices with
# their shape and nonzero count once the release no longer needs
# their entries.
"microcosm.calibrate.dropped_matrix",
"microcosm.diagnostics.catalogs",
# microcosm#1490: microcosm.fit exports its categorical classifier,
# held-out scores and keyed donors, so a binding that imports the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14843,7 +14843,7 @@ def test_gate_evidence_files_are_the_files_their_gates_write() -> None:
and node.func.id
in {
"us_release_input_coverage_gate",
"_export_input_mass_gate",
"_record_export_input_mass_gate",
"_record_qrf_tail_concentration_gate",
"us_reform_coverage_smoke_gate",
"_record_stored_inputs_gate_evidence",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import weakref
from collections.abc import Iterator

from microcosm.calibrate import DroppedConstraintMatrix
from test_support.microcosm_build.us_post_export_scoring import *


Expand Down Expand Up @@ -1377,6 +1378,7 @@ def test_main_drops_the_calibration_frames_before_the_export(builder) -> None:
assert [value for _, value in later_bindings] == [
"_without_calibrated_frames(result, "
"export_frame=export_frame if ladder_outcome is not None else None)",
"without_constraint_matrix(result)",
]
assert all(deleted < lineno < write_call for lineno, _ in later_bindings)
export_bindings = [
Expand Down Expand Up @@ -1466,6 +1468,8 @@ def check_write(frame, path, *, period):
cleaned = namespace["result"]
if not full_pool:
assert cleaned.selection.frame is None
assert isinstance(cleaned.selection.problem.matrix, DroppedConstraintMatrix)
assert isinstance(cleaned.problem.matrix, DroppedConstraintMatrix)
assert cleaned.frame is (frame if exact_k else None)
if exact_k:
outcome = namespace["ladder_outcome"]
Expand Down
Loading
Loading