From 7433ac07d38a170c7c918391a4e3623841af5a48 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:31:03 +0400 Subject: [PATCH 01/19] Free large release-tool objects after their last use 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 --- .../us_runtime/release_input_coverage.py | 18 +- .../shared/test_release_input_coverage.py | 38 ++ .../us/test_us_fiscal_refresh_builder.py | 2 +- .../us/test_us_post_export_scoring.py | 4 + .../test_us_release_frees_after_last_use.py | 494 ++++++++++++++++++ .../src/microcosm/calibrate/__init__.py | 6 + .../src/microcosm/calibrate/matrix.py | 90 +++- .../src/microcosm/calibrate/solve.py | 38 +- .../engine_free/shared/test_diagnostics.py | 131 +++++ tools/build_us_fiscal_refresh_release.py | 254 +++++---- 10 files changed, 965 insertions(+), 110 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/release_input_coverage.py b/packages/microcosm-build/src/microcosm/build/us_runtime/release_input_coverage.py index 284c1fe7a1..2adeb4865a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/release_input_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/release_input_coverage.py @@ -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", @@ -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. @@ -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. diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py index fda192239a..9b7d01ae1e 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py @@ -2235,3 +2235,41 @@ 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.""" + import gc + import weakref + + class TaxBenefitSystem: + """A stand-in for the reformed PolicyEngine-US system.""" + + built: list[weakref.ref] = [] + + def build_installed_parameter_stages(): + system = TaxBenefitSystem() + built.append(weakref.ref(system)) + return {}, system + + monkeypatch.setattr( + coverage_module, + "_installed_parameter_stages", + functools.cache(build_installed_parameter_stages), + ) + first = coverage_module._installed_parameter_stages() + assert coverage_module._installed_parameter_stages() is first + del first + gc.collect() + assert built[0]() is not None + + coverage_module.clear_installed_list_parameter_baseline_cache() + gc.collect() + + assert built[0]() is None + coverage_module._installed_parameter_stages() + assert len(built) == 2 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 1323134a5f..c187b3f6f7 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -14837,7 +14837,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", + "_export_input_mass_gate_with_reference_h5", "_record_qrf_tail_concentration_gate", "us_reform_coverage_smoke_gate", "_record_stored_inputs_gate_evidence", 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 deeeb97a7f..9283529bbe 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 @@ -1,6 +1,7 @@ """Tests split from packages/microcosm-build/tests/test_us_post_export_scoring.py.""" # ruff: noqa: F403, F405 +from microcosm.calibrate import DroppedConstraintMatrix from test_support.microcosm_build.us_post_export_scoring import * @@ -1312,6 +1313,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 = [ @@ -1401,6 +1403,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"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py new file mode 100644 index 0000000000..079d7f441e --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -0,0 +1,494 @@ +"""The US release tool's ``_main`` frees large objects after their last use. + +``_main`` is one long function, so a local it never deletes stays alive until +the run ends. These tests read the function's syntax tree, and execute slices +of its statements, to check that each large object is deleted, or never bound +to a local, once nothing reads it. +""" + +# ruff: noqa: F403, F405 +import re +import weakref + +from microcosm.calibrate import DroppedConstraintMatrix +from test_support.microcosm_build.us_post_export_scoring import * + +#: The nine donor-table loaders ``_main`` calls, one per imputation stage. +_DONOR_LOADERS = ( + "load_org_2024_donor", + "load_scf_2022_auto_loan_donor", + "load_scf_2022_financial_asset_donor", + "load_sipp_2023_financial_asset_donor", + "load_sipp_2023_head_start_donor", + "load_sipp_2023_ssi_disability_donor", + "load_sipp_2023_tip_donor", + "load_sipp_2023_vehicle_donor", + "load_sipp_2023_voluntary_filing_donor", +) + + +class _LargeObject: + """A stand-in for a frame or table that a weak reference can follow.""" + + +def _main_function(builder) -> ast.FunctionDef: + _, tree = _function_source(builder, "_main") + (function,) = tree.body + return function + + +def _name_lines(function: ast.AST, name: str, context: type) -> list[int]: + return sorted( + node.lineno + for node in ast.walk(function) + if isinstance(node, ast.Name) + and node.id == name + and isinstance(node.ctx, context) + ) + + +def _deletes(function: ast.FunctionDef, name: str) -> list[ast.Delete]: + return [ + node + for node in ast.walk(function) + if isinstance(node, ast.Delete) + and any( + isinstance(target, ast.Name) and target.id == name + for target in node.targets + ) + ] + + +def _single_top_level_delete(function: ast.FunctionDef, name: str) -> int: + """The index in ``_main``'s body of its one ``del `` statement.""" + (deleted,) = _deletes(function, name) + # A top-level statement runs on every path that reaches it, not only + # inside one branch. + return function.body.index(deleted) + + +def _calls_named(tree: ast.AST, name: str) -> list[ast.Call]: + return [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == name + ] + + +def _execute(statements: list[ast.stmt], namespace: dict, label: str) -> None: + module = ast.Module(body=statements, type_ignores=[]) + exec(compile(module, label, "exec"), namespace) + + +def test_main_keeps_only_the_receipt_of_the_acs_predictor_join(builder) -> None: + """The join result is deleted before the next stage rebinds base_frame.""" + main = _main_function(builder) + deleted_at = _single_top_level_delete(main, "acs_predictor_join_result") + deleted_line = main.body[deleted_at].lineno + reads = _name_lines(main, "acs_predictor_join_result", ast.Load) + assert reads and max(reads) < deleted_line + assert max(_name_lines(main, "acs_predictor_join_result", ast.Store)) < deleted_line + # base_frame names the join's frame until the next stage rebinds it; the + # result must be gone by then, or it keeps that frame alive. + (frame_read,) = [ + node.lineno + for node in ast.walk(main) + if isinstance(node, ast.Assign) + and ast.unparse(node) == "base_frame = acs_predictor_join_result.frame" + ] + next_base_frame_binding = min( + line for line in _name_lines(main, "base_frame", ast.Store) if line > frame_read + ) + assert deleted_line < next_base_frame_binding + # Only the receipt is read later. + assert max(_name_lines(main, "acs_predictor_join_receipt", ast.Load)) > deleted_line + + +def test_main_frees_the_acs_join_frame_once_base_frame_is_rebound(builder) -> None: + """Run ``_main``'s join statements: only base_frame holds the joined frame.""" + main = _main_function(builder) + (join_at,) = [ + index + for index, node in enumerate(main.body) + if isinstance(node, ast.Assign) + and any( + getattr(target, "id", None) == "acs_predictor_join_result" + for target in node.targets + ) + ] + deleted_at = _single_top_level_delete(main, "acs_predictor_join_result") + # The fake hands its only reference to the joined frame to the result. + unjoined = [_LargeObject()] + joined_frame_reference = weakref.ref(unjoined[0]) + receipt = {"enabled": True, "join": {"matched_households": 3}} + + def join_acs_release_predictors(frame, **paths): + return SimpleNamespace(frame=unjoined.pop(), receipt=receipt) + + namespace = { + **vars(builder), + "join_acs_release_predictors": join_acs_release_predictors, + "base_frame": _LargeObject(), + "args": SimpleNamespace( + acs_person_zip=None, + acs_person_sha256=None, + acs_household_zip=None, + acs_household_sha256=None, + ), + "telemetry": None, + } + _execute( + main.body[join_at : deleted_at + 1], namespace, "
" + ) + + assert "acs_predictor_join_result" not in namespace + assert namespace["acs_predictor_join_receipt"] == receipt + assert namespace["base_frame"] is joined_frame_reference() + # The next stage rebinds base_frame to its own output. + namespace["base_frame"] = _LargeObject() + gc.collect() + assert joined_frame_reference() is None + + +def test_main_passes_each_donor_table_straight_into_its_stage(builder) -> None: + """No local holds a donor table, so each is freed when its stage returns.""" + main = _main_function(builder) + parents = { + child: parent + for parent in ast.walk(main) + for child in ast.iter_child_nodes(parent) + } + loader_calls = [ + node + for node in ast.walk(main) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and re.fullmatch(r"load_\w+_donor", node.func.id) + ] + assert sorted(call.func.id for call in loader_calls) == sorted(_DONOR_LOADERS) + for call in loader_calls: + keyword = parents[call] + assert isinstance(keyword, ast.keyword), ast.unparse(call) + stage = parents[keyword] + assert isinstance(stage, ast.Call) + assert isinstance(stage.func, ast.Name) + assert stage.func.id.startswith("with_us_"), ast.unparse(stage.func) + donor_names = { + node.id + for node in ast.walk(main) + if isinstance(node, ast.Name) + and isinstance(node.ctx, ast.Store) + and node.id.endswith("_donor") + } + assert donor_names == set() + + +def test_main_frees_base_frame_after_the_export_input_mass_check(builder) -> None: + """``del base_frame`` follows the check that reads it last.""" + main = _main_function(builder) + deleted_at = _single_top_level_delete(main, "base_frame") + deleted_line = main.body[deleted_at].lineno + check = main.body[deleted_at - 1] + assert isinstance(check, ast.Try) + assert _calls_named(check, "_export_input_mass_gate_with_reference_h5") + assert max(_name_lines(main, "base_frame", ast.Load)) < deleted_line + assert max(_name_lines(main, "base_frame", ast.Store)) < deleted_line + (write,) = [ + node.lineno + for node in ast.walk(main) + if isinstance(node, ast.Call) + and getattr(node.func, "attr", None) == "write_dataset" + ] + assert deleted_line < write + + +def test_main_leaves_the_export_reference_frame_to_its_check(builder) -> None: + """``_main`` binds no reference frame; the check loads it from the path.""" + main = _main_function(builder) + assert _calls_named(main, "load_us_frame") == [] + assert "export_reference_frame" not in { + node.id for node in ast.walk(main) if isinstance(node, ast.Name) + } + assert _calls_named(main, "_export_input_mass_gate") == [] + (call,) = _calls_named(main, "_export_input_mass_gate_with_reference_h5") + keywords = {keyword.arg: ast.unparse(keyword.value) for keyword in call.keywords} + assert keywords["reference_h5"] == "args.export_input_mass_reference_h5" + assert keywords["reference_name"] == "export_reference_name" + + +def _check_options(builder) -> dict[str, object]: + return { + "relative_tolerance": 0.05, + "minimum_reference_total": 1.0, + "reference_name": "reference_populace_us_2024.h5", + "reviewed_exclusions": builder.US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, + } + + +def test_the_export_input_mass_check_frees_its_reference_when_it_returns( + builder, monkeypatch +) -> None: + """The check loads the reference itself and holds it only while it runs.""" + loaded: list[tuple[Path, weakref.ref]] = [] + gate_calls: list[dict[str, object]] = [] + export_frame, base_frame = _LargeObject(), _LargeObject() + verdict = builder.GateResult( + name="export_input_mass_parity", passed=True, details={"checked": True} + ) + + def load_us_frame(path): + reference = _LargeObject() + loaded.append((Path(path), weakref.ref(reference))) + return reference + + def gate(candidate, base, *, reference_frame, **options): + assert candidate is export_frame and base is base_frame + gate_calls.append( + { + "reference_frame": weakref.ref(reference_frame) + if reference_frame is not None + else None, + **options, + } + ) + if options["relative_tolerance"] < 0: + raise RuntimeError("the gate failed") + return verdict + + monkeypatch.setattr(builder, "load_us_frame", load_us_frame) + monkeypatch.setattr(builder, "_export_input_mass_gate", gate) + reference_h5 = Path("reference_populace_us_2024.h5") + + returned = builder._export_input_mass_gate_with_reference_h5( + export_frame, base_frame, reference_h5=reference_h5, **_check_options(builder) + ) + assert returned is verdict + ((loaded_path, reference),) = loaded + assert loaded_path == reference_h5 + assert gate_calls[0]["reference_frame"] is reference + assert { + key: value for key, value in gate_calls[0].items() if key != "reference_frame" + } == (_check_options(builder)) + gc.collect() + assert reference() is None + + # A check that raises frees its reference once the error is handled. + failing = {**_check_options(builder), "relative_tolerance": -1.0} + try: + builder._export_input_mass_gate_with_reference_h5( + export_frame, base_frame, reference_h5=reference_h5, **failing + ) + except RuntimeError as error: + assert str(error) == "the gate failed" + gc.collect() + assert len(loaded) == 2 and loaded[1][1]() is None + + # Without a reference H5 the check compares against base_frame and loads + # nothing. + assert ( + builder._export_input_mass_gate_with_reference_h5( + export_frame, base_frame, reference_h5=None, **_check_options(builder) + ) + is verdict + ) + assert len(loaded) == 2 + assert gate_calls[-1]["reference_frame"] is None + + +def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> None: + """The engine that writes the H5 is deleted before post-export scoring.""" + main = _main_function(builder) + deleted_at = _single_top_level_delete(main, "release_engine") + deleted_line = main.body[deleted_at].lineno + reads = _name_lines(main, "release_engine", ast.Load) + assert reads and max(reads) < deleted_line + (write,) = [ + node + for node in main.body + if isinstance(node, ast.Expr) + and isinstance(node.value, ast.Call) + and getattr(node.value.func, "attr", None) == "write_dataset" + ] + assert ast.unparse(write.value.func.value) == "release_engine" + assert write.lineno < deleted_line + (scorer,) = _calls_named(main, "_open_post_export_scorer") + assert deleted_line < scorer.lineno + + +def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( + builder, +) -> None: + """The matrix goes with the calibrated frames, before ladder_outcome's + result is replaced, so neither name keeps it.""" + main = _main_function(builder) + statements = [ast.unparse(node) for node in main.body] + frames_dropped = next( + index + for index, text in enumerate(statements) + if text.startswith("result = _without_calibrated_frames(") + ) + matrix_dropped = statements.index("result = without_constraint_matrix(result)") + ladder_rebound = next( + index + for index, node in enumerate(main.body) + if isinstance(node, ast.If) + and ast.unparse(node.test) + == "isinstance(ladder_outcome, ExactKLadderCalibration)" + ) + assert frames_dropped < matrix_dropped < ladder_rebound + assert statements[matrix_dropped + 1 : ladder_rebound] == [] + # Every reader of the calibration result comes after the drop. + calibration_calls = [ + node.lineno + for node in ast.walk(main) + if isinstance(node, ast.Call) + and getattr(node.func, "id", None) + in {"calibrate", "calibrate_l0_refit", "calibrate_exact_k_ladder"} + ] + assert calibration_calls + assert max(calibration_calls) < main.body[matrix_dropped].lineno + surface_reads = _calls_named(main, "target_surface_payload") + assert surface_reads + assert all(call.lineno > main.body[matrix_dropped].lineno for call in surface_reads) + + +def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> None: + """The tax-benefit system the start-up check caches is not kept for the run.""" + main = _main_function(builder) + statements = [ast.unparse(node) for node in main.body] + check = statements.index("assert_release_input_coverage_manifest_current()") + assert statements[check + 1] == "clear_installed_list_parameter_baseline_cache()" + assert statements.count("clear_installed_list_parameter_baseline_cache()") == 1 + + +def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( + builder, monkeypatch +) -> None: + """At the export write, each constraint matrix is replaced by its shape and + nonzero count, and the target surface the diagnostics record is unchanged.""" + monkeypatch.setattr(builder, "_assert_no_formula_owned_columns", lambda frame: None) + from microcosm.calibrate import calibrate_l0_refit + + for full_pool in (True, False): + target_frame, targets = _small_calibration_problem() + base_frame = Frame( + { + "person": target_frame.table("person"), + "household": target_frame.table("household").drop(columns="x"), + }, + target_frame.schema, + {"household": target_frame.weights_for("household")}, + ) + result = ( + calibrate(target_frame, targets, epochs=3, mass="conserve", seed=0) + if full_pool + else calibrate_l0_refit( + target_frame, + targets, + epochs=5, + refit_epochs=5, + target_records=20, + seed=0, + ) + ) + expected_surface = builder.target_surface_payload(result) + matrices = [result.problem.matrix] + if not full_pool: + matrices.append(result.selection.problem.matrix) + matrix_references = [weakref.ref(matrix) for matrix in matrices] + del matrices + ladder_outcome = builder.ExactKLadderCalibration( + result=result, + support=np.arange(len(result.weights)), + selected_inclusion_probabilities=np.ones(len(result.weights)), + selection_receipt={}, + refit_baseline_diagnostics={}, + ) + main = _main_function(builder) + statements = [ast.unparse(node) for node in main.body] + start = statements.index("result = without_constraint_matrix(result)") + end = next( + index + for index, node in enumerate(main.body) + if index > start + and isinstance(node, ast.If) + and ast.unparse(node.test) + == "isinstance(ladder_outcome, ExactKLadderCalibration)" + ) + namespace = { + **vars(builder), + "base_frame": base_frame, + "result": result, + "ladder_outcome": ladder_outcome, + } + del result, ladder_outcome + _execute( + main.body[start : end + 1], namespace, "
" + ) + gc.collect() + assert [reference() for reference in matrix_references] == [None] * len( + matrix_references + ) + cleaned = namespace["result"] + assert isinstance(cleaned.problem.matrix, DroppedConstraintMatrix) + if not full_pool: + assert isinstance(cleaned.selection.problem.matrix, DroppedConstraintMatrix) + assert namespace["ladder_outcome"].result is cleaned + assert builder.target_surface_payload(cleaned) == expected_surface + + +@pytest.mark.parametrize("full_pool", [True, False]) +def test_dropping_the_constraint_matrix_leaves_the_written_calibration_unchanged( + builder, tmp_path, full_pool +) -> None: + """The calibration NPZ, the diagnostics payload and the target surface + written from a result without its matrices equal those of the original.""" + from microcosm.calibrate import ( + calibrate_l0_refit, + diagnostics_payload, + without_constraint_matrix, + ) + + target_frame, targets = _small_calibration_problem() + result = ( + calibrate(target_frame, targets, epochs=3, mass="conserve", seed=0) + if full_pool + else calibrate_l0_refit( + target_frame, targets, epochs=5, refit_epochs=5, target_records=20, seed=0 + ) + ) + registry = TargetRegistry( + [ + TargetSpec( + name="x_total@2024", + entity="household", + measure="x", + value=1.0, + source="fixture", + family="fixture", + ) + ], + country="us", + ) + dropped = without_constraint_matrix(result) + + builder._write_npz(tmp_path / "original.npz", result=result, registry=registry) + builder._write_npz(tmp_path / "dropped.npz", result=dropped, registry=registry) + with ( + np.load(tmp_path / "original.npz", allow_pickle=True) as original, + np.load(tmp_path / "dropped.npz", allow_pickle=True) as without_matrix, + ): + assert original.files == without_matrix.files + for name in original.files: + assert original[name].dtype == without_matrix[name].dtype, name + np.testing.assert_array_equal(original[name], without_matrix[name]) + assert json.dumps( + diagnostics_payload(dropped), sort_keys=True, allow_nan=False + ) == json.dumps(diagnostics_payload(result), sort_keys=True, allow_nan=False) + assert builder.target_surface_payload(dropped) == builder.target_surface_payload( + result + ) + assert builder._in_sample_estimates(dropped) == builder._in_sample_estimates(result) + assert builder._in_sample_targets(dropped) == builder._in_sample_targets(result) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py b/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py index c8043cc92b..2ef6c2f0b3 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py @@ -111,6 +111,8 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: ) from microcosm.calibrate.matrix import ( # noqa: E402 - after the compat gate CalibrationProblem, + ConstraintMatrixDroppedError, + DroppedConstraintMatrix, SkippedTarget, build_constraint_matrix, ) @@ -150,6 +152,7 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: rebuild_calibration_result, refit_l0_selection, relative_error_loss, + without_constraint_matrix, ) from microcosm.calibrate.static_aging import ( # noqa: E402 - after the compat gate DemographicProjection, @@ -206,6 +209,8 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: "TARGET_LOSS_ATTRIBUTION_WARNING_CODES", "TARGET_LOSS_BASIS_HASH_ALGORITHM", "CalibrationProblem", + "ConstraintMatrixDroppedError", + "DroppedConstraintMatrix", "CalibrationHierarchy", "CalibrationHierarchySeed", "CalibrationResult", @@ -235,6 +240,7 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: "effective_sample_size", "rebuild_calibration_result", "refit_l0_selection", + "without_constraint_matrix", "diagnostics_payload", "past_cap_census", "relative_error_loss", diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py b/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py index 11aeb35c47..464027b463 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py @@ -38,7 +38,90 @@ from microcosm.calibrate.target import Target, TargetSet from microcosm.frame import Frame, Weights -__all__ = ["CalibrationProblem", "SkippedTarget", "build_constraint_matrix"] +__all__ = [ + "CalibrationProblem", + "ConstraintMatrixDroppedError", + "DroppedConstraintMatrix", + "SkippedTarget", + "build_constraint_matrix", +] + + +class ConstraintMatrixDroppedError(RuntimeError): + """A use of a constraint matrix that was dropped after its solve.""" + + +class DroppedConstraintMatrix: + """The shape and nonzero count of a constraint matrix that was freed. + + :func:`~microcosm.calibrate.solve.without_constraint_matrix` puts one in a + :class:`CalibrationProblem` in place of its CSR matrix once later code + reads only those two numbers, as + :func:`~microcosm.calibrate.diagnostics.target_surface_payload` does. + ``shape`` and ``nnz`` keep the dropped matrix's values, so such a reader + reports the matrix it describes. Every other use of the matrix (a product, + a row slice, a conversion, its stored arrays) raises + :class:`ConstraintMatrixDroppedError`, so no caller computes with an empty + or missing matrix. + """ + + __slots__ = ("nnz", "shape") + + def __init__(self, shape: tuple[int, int], nnz: int) -> None: + self.shape = (int(shape[0]), int(shape[1])) + self.nnz = int(nnz) + + @classmethod + def of(cls, matrix) -> DroppedConstraintMatrix: + """Record ``matrix``'s shape and nonzero count; a record passes through.""" + if isinstance(matrix, cls): + return matrix + return cls(matrix.shape, matrix.nnz) + + def _refuse(self, use: str): + raise ConstraintMatrixDroppedError( + f"The {self.shape[0]} x {self.shape[1]} constraint matrix was dropped " + f"after calibration; only its shape and nonzero count ({self.nnz}) " + f"were kept, so {use} is unavailable." + ) + + def __getattr__(self, name: str): + # Called only for attributes the class lacks. Special-method lookups + # (copy, pickle, numpy's array protocols) see a plain missing + # attribute; so does an unset slot, which only partial construction + # leaves. + if name in type(self).__slots__ or ( + name.startswith("__") and name.endswith("__") + ): + raise AttributeError(name) + self._refuse(f"its {name!r}") + + def __array__(self, *args, **kwargs): + self._refuse("its dense array") + + def __matmul__(self, other): + self._refuse("a matrix product") + + def __rmatmul__(self, other): + self._refuse("a matrix product") + + def __mul__(self, other): + self._refuse("a product") + + def __rmul__(self, other): + self._refuse("a product") + + def __getitem__(self, key): + self._refuse("a row or entry") + + def __iter__(self): + self._refuse("iteration over its rows") + + def __len__(self) -> int: + self._refuse("its length") + + def __repr__(self) -> str: + return f"DroppedConstraintMatrix(shape={self.shape!r}, nnz={self.nnz!r})" @dataclass(frozen=True) @@ -66,6 +149,9 @@ class CalibrationProblem: matrix: The constraint matrix ``A`` as a CSR ``scipy.sparse`` array of shape ``(n_targets, n_weights)``: one row per compiled ``(target, period)``, one column per record of ``weight_entity``. + After :func:`~microcosm.calibrate.solve.without_constraint_matrix` + it is a :class:`DroppedConstraintMatrix`, which keeps only the + shape and the nonzero count. target_vector: The right-hand side ``b`` of length ``n_targets``. Each row is a sum target, so the right-hand side is the target value. names: Row labels (``"name@period"``), aligned to ``matrix`` rows. @@ -81,7 +167,7 @@ class CalibrationProblem: guard; :func:`build_constraint_matrix` never produces one). """ - matrix: sparse.csr_array + matrix: sparse.csr_array | DroppedConstraintMatrix target_vector: np.ndarray names: tuple[str, ...] initial_weights: Weights diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index e55a42a470..09387e1ab1 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -89,7 +89,7 @@ import math import warnings from collections.abc import Callable, Mapping -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace import numpy as np import torch @@ -107,6 +107,7 @@ from microcosm.calibrate.initialization import GateInitialization from microcosm.calibrate.matrix import ( CalibrationProblem, + DroppedConstraintMatrix, SkippedTarget, build_constraint_matrix, ) @@ -119,6 +120,7 @@ "rebuild_calibration_result", "refit_l0_selection", "solve_constraint_system", + "without_constraint_matrix", "default_target_loss_scales", "chi_square_distance", "effective_sample_size", @@ -3037,6 +3039,40 @@ def calibrate( ) +def without_constraint_matrix(result): + """Free a result's constraint matrices, keeping their shapes and nonzero counts. + + A :class:`CalibrationResult` keeps its compiled problem, whose CSR matrix + is the largest object a solve returns. A caller that later reads only the + matrix's shape and nonzero count, as + :func:`~microcosm.calibrate.diagnostics.target_surface_payload` does, + can call this once the matrix's entries are no longer needed. The returned + result's problem holds a + :class:`~microcosm.calibrate.matrix.DroppedConstraintMatrix` with those two + numbers; any later use that needs the entries, such as + :meth:`CalibrationProblem.estimates`, raises + :class:`~microcosm.calibrate.matrix.ConstraintMatrixDroppedError`. Every + other field is the same object as before. + + An :class:`L0RefitResult` has two problems, the selection's over the full + frame and the refit's over the selected support; both are dropped. Any + other object holds no compiled problem and is returned unchanged. + """ + if isinstance(result, L0RefitResult): + return replace( + result, + selection=without_constraint_matrix(result.selection), + refit=without_constraint_matrix(result.refit), + ) + if isinstance(result, CalibrationResult): + problem = result.problem + return replace( + result, + problem=replace(problem, matrix=DroppedConstraintMatrix.of(problem.matrix)), + ) + return result + + def solve_constraint_system( matrix, targets: np.ndarray, diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py index 1d651065e1..c3144b09fa 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py @@ -8,8 +8,10 @@ from __future__ import annotations +import gc import json import logging +import weakref from dataclasses import replace from pathlib import Path from types import SimpleNamespace @@ -22,6 +24,8 @@ TARGET_LOSS_ATTRIBUTION_WARNING_CODES, TARGET_LOSS_BASIS_HASH_ALGORITHM, CalibrationHierarchy, + ConstraintMatrixDroppedError, + DroppedConstraintMatrix, HierarchyCategory, HierarchyDimension, HierarchyGeography, @@ -37,9 +41,12 @@ geography_constants, past_cap_census, score_targets, + without_constraint_matrix, write_calibration_diagnostics, ) from microcosm.calibrate._target_loss_attribution import target_loss_basis_hash +from microcosm.calibrate.artifacts import encode_problem +from microcosm.calibrate.diagnostics import target_surface_payload from microcosm.calibrate.geography_constants import ( UK_GEOGRAPHY_ID_TO_LABEL, UK_WIDE_GEOGRAPHY_IDS, @@ -1216,3 +1223,127 @@ def test_payload_census_from_a_real_solve(feasible_frame) -> None: assert census["final_past_cap"] == census["frozen"] + census["pushed_out"] assert census == past_cap_census(result) json.dumps(payload, allow_nan=False) + + +def _l0_refit_result(feasible_frame): + frame, truths = feasible_frame() + targets = TargetSet( + ( + Target( + name="income", + entity="household", + value=truths["income"] * 1.2, + measure="income", + ), + Target( + name="population", + entity="household", + value=truths["population"], + measure="household_count", + ), + ) + ) + return calibrate_l0_refit( + frame, targets, epochs=40, seed=0, l0_lambda=0.003, mass="conserve" + ) + + +def _matrix_references(problem) -> list[weakref.ref]: + """Weak references to a constraint matrix and each array that stores it.""" + matrix = problem.matrix + return [ + weakref.ref(matrix), + weakref.ref(matrix.data), + weakref.ref(matrix.indices), + weakref.ref(matrix.indptr), + ] + + +def test_dropping_the_constraint_matrix_keeps_its_shape_and_nonzero_count( + feasible_frame, +) -> None: + """The matrix is freed; the target surface and the payload are unchanged.""" + result = _result(feasible_frame, epochs=20) + shape = tuple(result.problem.matrix.shape) + nonzero_count = int(result.problem.matrix.nnz) + assert nonzero_count > 0 + surface = target_surface_payload(result) + payload = diagnostics_payload(result) + references = _matrix_references(result.problem) + + dropped = without_constraint_matrix(result) + del result + gc.collect() + + assert [reference() for reference in references] == [None] * len(references) + assert isinstance(dropped.problem.matrix, DroppedConstraintMatrix) + assert dropped.problem.matrix.shape == shape + assert dropped.problem.matrix.nnz == nonzero_count + assert (dropped.problem.n_targets, dropped.problem.n_weights) == shape + assert target_surface_payload(dropped) == surface + assert diagnostics_payload(dropped) == payload + # Dropping twice keeps the recorded numbers. + again = without_constraint_matrix(dropped) + assert again.problem.matrix.shape == shape + assert again.problem.matrix.nnz == nonzero_count + + +def test_dropping_an_l0_refit_result_drops_the_selection_matrix_too( + feasible_frame, +) -> None: + """Under L0 selection the selection's full-frame matrix is freed as well.""" + result = _l0_refit_result(feasible_frame) + selection_shape = tuple(result.selection.problem.matrix.shape) + selection_nonzero_count = int(result.selection.problem.matrix.nnz) + surface = target_surface_payload(result) + payload = diagnostics_payload(result) + references = [ + *_matrix_references(result.selection.problem), + *_matrix_references(result.refit.problem), + ] + + dropped = without_constraint_matrix(result) + del result + gc.collect() + + assert [reference() for reference in references] == [None] * len(references) + assert dropped.selection.problem.matrix.shape == selection_shape + assert dropped.selection.problem.matrix.nnz == selection_nonzero_count + assert target_surface_payload(dropped) == surface + assert diagnostics_payload(dropped) == payload + + +def test_a_dropped_constraint_matrix_refuses_every_use_that_needs_its_entries( + feasible_frame, +) -> None: + """A later call that needs the matrix raises; it never sees an empty one.""" + dropped = without_constraint_matrix(_result(feasible_frame, epochs=20)) + matrix = dropped.problem.matrix + weights = np.asarray(dropped.weights, dtype=np.float64) + + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + dropped.problem.estimates(weights) + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + matrix @ weights + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + weights @ matrix + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + matrix[0:1] + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + matrix.toarray() + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + _ = matrix.data + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + np.asarray(matrix) + with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): + len(matrix) + # Encoding the problem for an artifact needs every entry. + with pytest.raises(ValueError) as encoding_error: + encode_problem(dropped.problem, entity_ids=list(range(len(weights)))) + assert isinstance(encoding_error.value.__cause__, ConstraintMatrixDroppedError) + + +def test_dropping_the_constraint_matrix_returns_other_objects_unchanged() -> None: + """A stand-in for a result holds no compiled matrix and passes through.""" + stand_in = SimpleNamespace(diagnostics=[], problem=SimpleNamespace(targets=[])) + assert without_constraint_matrix(stand_in) is stand_in diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index f672b84652..63d8f196a0 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -398,6 +398,7 @@ ) from microcosm.build.us_runtime.release_input_coverage import ( REFERENCE_ECPS_LAYER_RENAMES, + clear_installed_list_parameter_baseline_cache, project_ecps_parity_known_gap_names, us_release_input_coverage_signal_counts, ) @@ -443,6 +444,7 @@ calibrate, calibrate_l0_refit, relative_error_loss, + without_constraint_matrix, ) from microcosm.calibrate.diagnostics import ( target_surface_payload, @@ -8635,6 +8637,83 @@ def _ecps_parity_gate( } +def _record_export_input_mass_gate( + export_frame: Frame, + base_frame: Frame, + *, + reference_h5: Path | None, + reference_name: str, + reference_record: dict[str, object], + relative_tolerance: float, + minimum_reference_total: float, + terminal_gate_failures: list[str], +) -> GateResult | None: + """Evaluate :func:`_export_input_mass_gate` against a reference H5 loaded here. + + The reference is a full frame. Loaded in this function, it is freed when + the check returns or raises; a ``del`` in the caller after the check + would be skipped when the load or the check raised. Without a reference + H5 the check compares the export against ``base_frame``. + + The reference's sha256 goes into ``reference_record`` before the load. + Only an evaluation crash escapes: it propagates on an otherwise-clean run, + and under earlier failures it becomes one line in + ``terminal_gate_failures`` and the function returns ``None``. + """ + reference_loaded = False + try: + if reference_h5 is not None: + reference_record["sha256"] = _sha256(reference_h5) + reference_frame = ( + load_us_frame(reference_h5) if reference_h5 is not None else None + ) + reference_loaded = True + # Build H (microcosm#299): the two SOI-identified columns whose true + # target level provably cannot sit inside the live-default reference + # band (estate_income, non_sch_d_capital_gains). miscellaneous_income + # and both mortgage columns are deliberately NOT excluded so the run + # adjudicates their actual gate outcome. See the constant's band-math + # rationale above. + return shadow_gate( + "us_national_export_input_mass", + lambda: _export_input_mass_gate( + export_frame, + base_frame, + relative_tolerance=relative_tolerance, + minimum_reference_total=minimum_reference_total, + reference_frame=reference_frame, + reference_name=reference_name, + reviewed_exclusions=US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, + ), + lambda: EvidenceContext( + frame=export_frame, + artifacts={ + "base_frame": base_frame, + "export_input_mass_reference_frame": reference_frame, + "export_input_mass_reference_name": reference_name, + "export_input_mass_reviewed_exclusions": ( + US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS + ), + }, + ), + ) + except Exception as exc: + # Same degraded-mode contract as the coverage gate in _main. + if not terminal_gate_failures: + raise + if not reference_loaded: + # As for the QRF tail register: the gate never ran. + shadow_not_run( + "us_national_export_input_mass", + f"its reference did not load: {type(exc).__name__}: {exc}", + ) + terminal_gate_failures.append( + "Input mass parity failed: evaluation error under earlier gate " + f"failures: {type(exc).__name__}: {exc}" + ) + return None + + def _export_input_mass_gate( export_frame: Frame, base_frame: Frame, @@ -15531,6 +15610,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # PolicyEngine-US input leaves. A drifted manifest fails here before the # expensive calibration so a stale contract cannot silently narrow coverage. assert_release_input_coverage_manifest_current() + # The check resolves the probes' list edits on a reformed PolicyEngine-US + # system that the module caches for the process. Nothing reads it again + # before the reform-coverage smoke, which builds it again, so it is not + # kept through the source stages and the calibration. + clear_installed_list_parameter_baseline_cache() # Preflight (microcosm#377): no column may be required-to-signal by one # register (seeded/count-calibrated take-up, health nonconstant, coverage # 'required') and excused as absent/degenerate by another (degenerate @@ -16873,6 +16957,9 @@ def _main(argv: Sequence[str] | None = None) -> int | None: ) base_frame = acs_predictor_join_result.frame acs_predictor_join_receipt = dict(acs_predictor_join_result.receipt) + # Only the receipt is read later. The result's frame would otherwise keep + # the post-join frame alive after the next stage rebinds base_frame. + del acs_predictor_join_result if telemetry is not None: telemetry.stage( "acs_predictor_join", @@ -16911,18 +16998,18 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.sipp_vehicle_donor is not None else fetch_sipp_2023_financial_asset_donor() ) - scf_wealth_donor = load_scf_2022_financial_asset_donor(scf_summary_extract_path) - sipp_financial_asset_donor = load_sipp_2023_financial_asset_donor( - sipp_full_donor_path, - expected_sha256=SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, - expected_size_bytes=SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, - ) + # Each donor table below is loaded in its stage's call, so no local keeps + # it once the stage returns. base_frame = with_us_scf_wealth_inputs( base_frame, seed=args.seed, time_period=PERIOD, - scf_donor=scf_wealth_donor, - sipp_donor=sipp_financial_asset_donor, + scf_donor=load_scf_2022_financial_asset_donor(scf_summary_extract_path), + sipp_donor=load_sipp_2023_financial_asset_donor( + sipp_full_donor_path, + expected_sha256=SIPP_2023_FINANCIAL_ASSET_DONOR_SHA256, + expected_size_bytes=SIPP_2023_FINANCIAL_ASSET_DONOR_SIZE_BYTES, + ), ) scf_wealth_gate = shadow_gate( "us_national_scf_wealth", @@ -16962,18 +17049,17 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "sha-pinned full SIPP 2023 donor after SCF assets." ), ) - ssi_disability_donor = load_sipp_2023_ssi_disability_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_SSI_DISABILITY_DONOR_SHA256, - expected_size_bytes=SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, - time_period=PERIOD, - ) base_frame = with_us_ssi_disability_criteria( base_frame, # The retired weighted bootstrap and MicroImpute forest are fixed. seed=42, time_period=PERIOD, - sipp_donor=ssi_disability_donor, + sipp_donor=load_sipp_2023_ssi_disability_donor( + sipp_vehicle_donor_path, + expected_sha256=SIPP_2023_SSI_DISABILITY_DONOR_SHA256, + expected_size_bytes=SIPP_2023_SSI_DISABILITY_DONOR_SIZE_BYTES, + time_period=PERIOD, + ), ) ssi_disability_gate = _shadow_frame_gate( "us_national_ssi_disability_criteria", @@ -17005,16 +17091,15 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "2023 donor." ), ) - head_start_donor = load_sipp_2023_head_start_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_HEAD_START_DONOR_SHA256, - expected_size_bytes=SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, - ) base_frame = with_us_sipp_head_start_input( base_frame, seed=args.seed, time_period=PERIOD, - sipp_donor=head_start_donor, + sipp_donor=load_sipp_2023_head_start_donor( + sipp_vehicle_donor_path, + expected_sha256=SIPP_2023_HEAD_START_DONOR_SHA256, + expected_size_bytes=SIPP_2023_HEAD_START_DONOR_SIZE_BYTES, + ), ) head_start_gate = _shadow_frame_gate( "us_national_sipp_head_start", @@ -17131,15 +17216,14 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.scf_full_extract is not None else fetch_scf_2022_full_extract() ) - scf_auto_loan_donor = load_scf_2022_auto_loan_donor( - scf_summary_extract_path, - scf_full_extract_path, - ) base_frame = with_us_scf_auto_loan_inputs( base_frame, seed=args.seed, time_period=PERIOD, - scf_auto_loan_donor=scf_auto_loan_donor, + scf_auto_loan_donor=load_scf_2022_auto_loan_donor( + scf_summary_extract_path, + scf_full_extract_path, + ), ) scf_auto_loan_gate = _shadow_frame_gate( "us_national_scf_auto_loans", @@ -17190,17 +17274,16 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "sha-pinned full SIPP 2023 donor." ), ) - sipp_vehicle_donor = load_sipp_2023_vehicle_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_VEHICLE_DONOR_SHA256, - expected_size_bytes=SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, - ) base_frame = with_us_sipp_vehicle_inputs( base_frame, # The retired MicroImpute model pins both forests to seed 42. seed=42, time_period=PERIOD, - sipp_donor=sipp_vehicle_donor, + sipp_donor=load_sipp_2023_vehicle_donor( + sipp_vehicle_donor_path, + expected_sha256=SIPP_2023_VEHICLE_DONOR_SHA256, + expected_size_bytes=SIPP_2023_VEHICLE_DONOR_SIZE_BYTES, + ), ) sipp_vehicles_gate = _shadow_frame_gate( "us_national_sipp_vehicles", @@ -17231,16 +17314,15 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "same sha-pinned full SIPP 2023 donor." ), ) - voluntary_filing_donor = load_sipp_2023_voluntary_filing_donor( - sipp_vehicle_donor_path, - expected_sha256=SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, - expected_size_bytes=SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, - ) base_frame = with_us_voluntary_filing_input( base_frame, seed=args.seed, time_period=PERIOD, - sipp_donor=voluntary_filing_donor, + sipp_donor=load_sipp_2023_voluntary_filing_donor( + sipp_vehicle_donor_path, + expected_sha256=SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + expected_size_bytes=SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + ), ) voluntary_filing_gate = _shadow_frame_gate( "us_national_voluntary_filing", @@ -17276,15 +17358,14 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.sipp_tip_donor is not None else fetch_sipp_2023_tip_donor() ) - sipp_tip_donor = load_sipp_2023_tip_donor( - sipp_tip_donor_path, - expected_sha256=SIPP_2023_TIP_DONOR_SHA256, - ) base_frame = with_us_sipp_tip_inputs( base_frame, seed=args.seed, time_period=PERIOD, - sipp_donor=sipp_tip_donor, + sipp_donor=load_sipp_2023_tip_donor( + sipp_tip_donor_path, + expected_sha256=SIPP_2023_TIP_DONOR_SHA256, + ), ) sipp_tips_gate = _shadow_frame_gate( "us_national_sipp_tips", @@ -17321,15 +17402,14 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if args.org_wages_donor is not None else fetch_org_2024_donor() ) - org_wages_donor = load_org_2024_donor( - org_wages_donor_path, - expected_content_sha256=ORG_2024_DONOR_CONTENT_SHA256, - ) base_frame = with_us_org_wages_inputs( base_frame, seed=args.seed, time_period=PERIOD, - org_donor=org_wages_donor, + org_donor=load_org_2024_donor( + org_wages_donor_path, + expected_content_sha256=ORG_2024_DONOR_CONTENT_SHA256, + ), ) org_wages_gate = _shadow_frame_gate( "us_national_org_wages", @@ -18150,6 +18230,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: result, export_frame=export_frame if ladder_outcome is not None else None, ) + # The solves are done. Later code reads only each constraint matrix's + # shape and nonzero count (the target surface in the calibration + # diagnostics), so keep those two numbers and free the matrices: the + # refit's and, under L0 selection, the selection's over the full frame. + result = without_constraint_matrix(result) if isinstance(ladder_outcome, ExactKLadderCalibration): ladder_outcome = dataclasses.replace(ladder_outcome, result=result) if args.scf_education_debt: @@ -18941,62 +19026,21 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "sha256": None, "reference_name": export_reference_name, } - reference_loaded = False - try: - if args.export_input_mass_reference_h5 is not None: - export_input_mass_reference["sha256"] = _sha256( - args.export_input_mass_reference_h5 - ) - export_reference_frame = ( - load_us_frame(args.export_input_mass_reference_h5) - if args.export_input_mass_reference_h5 is not None - else None - ) - reference_loaded = True - # Build H (microcosm#299): the two SOI-identified columns whose true - # target level provably cannot sit inside the live-default reference - # band (estate_income, non_sch_d_capital_gains). miscellaneous_income - # and both mortgage columns are deliberately NOT excluded so the run - # adjudicates their actual gate outcome. See the constant's band-math - # rationale above. - export_input_mass_gate = shadow_gate( - "us_national_export_input_mass", - lambda: _export_input_mass_gate( - export_frame, - base_frame, - relative_tolerance=args.input_mass_relative_tolerance, - minimum_reference_total=args.input_mass_minimum_reference_total, - reference_frame=export_reference_frame, - reference_name=export_reference_name, - reviewed_exclusions=US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, - ), - lambda: EvidenceContext( - frame=export_frame, - artifacts={ - "base_frame": base_frame, - "export_input_mass_reference_frame": export_reference_frame, - "export_input_mass_reference_name": export_reference_name, - "export_input_mass_reviewed_exclusions": ( - US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS - ), - }, - ), - ) - except Exception as exc: - # Same degraded-mode contract as the coverage gate above. - if not terminal_gate_failures: - raise - if not reference_loaded: - # As for the QRF tail register: the gate never ran. - shadow_not_run( - "us_national_export_input_mass", - f"its reference did not load: {type(exc).__name__}: {exc}", - ) - terminal_gate_failures.append( - "Input mass parity failed: evaluation error under earlier gate " - f"failures: {type(exc).__name__}: {exc}" - ) - export_input_mass_gate = None + # The check loads the reference frame itself, so the frame is freed when + # the check returns or raises. + export_input_mass_gate = _record_export_input_mass_gate( + export_frame, + base_frame, + reference_h5=args.export_input_mass_reference_h5, + reference_name=export_reference_name, + reference_record=export_input_mass_reference, + relative_tolerance=args.input_mass_relative_tolerance, + minimum_reference_total=args.input_mass_minimum_reference_total, + terminal_gate_failures=terminal_gate_failures, + ) + # The check above is base_frame's last reader; the export frame and the + # written H5 carry everything later stages read. + del base_frame # A reference the gate never evaluated is still named, but marked so no # reader takes its bytes as what the parity verdict saw. export_input_mass_reference["evaluated"] = export_input_mass_gate is not None @@ -19132,6 +19176,8 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # microcosm#443: #437 dropped this call while inserting the batched raise, # so attempts 13/14 smoke-scored a stale artifact from a prior run. release_engine.write_dataset(export_frame, dataset_path, period=PERIOD) + # The writer was the engine's last use; post-export scoring builds its own. + del release_engine # microcosm#1026: the stored-input gate above graded a model of the # writer's output; the written bytes are graded whatever the gate reached # and must earn the same verdict (no refusal, if the gate could not From ccc5e9dd159da21f3b1e9c1517944bbe68291971 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:32:04 +0400 Subject: [PATCH 02/19] Add changelog fragment for freeing release-tool objects Co-Authored-By: Claude Opus 5.5 --- changelog.d/release-free-after-last-use.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/release-free-after-last-use.changed.md diff --git a/changelog.d/release-free-after-last-use.changed.md b/changelog.d/release-free-after-last-use.changed.md new file mode 100644 index 0000000000..496f0a0e89 --- /dev/null +++ b/changelog.d/release-free-after-last-use.changed.md @@ -0,0 +1 @@ +The US fiscal refresh release (`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, deletes `base_frame` after the export input-mass check, loads the export reference frame inside that check (`_export_input_mass_gate_with_reference_h5`), and deletes `release_engine` after the H5 write. 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 system is not kept through the source stages and the calibration; the reform-coverage smoke builds it once more. Written outputs are unchanged. From 4dc6d71d1741336e519ddf46af50e45e96a82537 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:44:46 +0400 Subject: [PATCH 03/19] Tighten the release-tool freeing tests after review - 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 --- .../shared/test_release_input_coverage.py | 72 ++++--- .../test_us_release_frees_after_last_use.py | 199 +++++++++++++++--- 2 files changed, 208 insertions(+), 63 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py index 9b7d01ae1e..fbd210b5e1 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_release_input_coverage.py @@ -2242,34 +2242,50 @@ def test_clearing_the_installed_parameter_cache_frees_the_cached_system( ) -> 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.""" + 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 TaxBenefitSystem: - """A stand-in for the reformed PolicyEngine-US system.""" - - built: list[weakref.ref] = [] - - def build_installed_parameter_stages(): - system = TaxBenefitSystem() - built.append(weakref.ref(system)) - return {}, system - - monkeypatch.setattr( - coverage_module, - "_installed_parameter_stages", - functools.cache(build_installed_parameter_stages), - ) - first = coverage_module._installed_parameter_stages() - assert coverage_module._installed_parameter_stages() is first - del first - gc.collect() - assert built[0]() is not None - - coverage_module.clear_installed_list_parameter_baseline_cache() - gc.collect() - - assert built[0]() is None - coverage_module._installed_parameter_stages() - assert len(built) == 2 + 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() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 079d7f441e..1a4263b3d7 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -27,10 +27,55 @@ ) +#: Locals of ``_main`` that hold an object this module checks is freed. +_FREED_NAMES = frozenset( + { + "acs_predictor_join_result", + "base_frame", + "ladder_outcome", + "release_engine", + "result", + } +) +#: Attributes through which such a local reaches another large object. +_HOLDING_ATTRIBUTES = frozenset( + {"frame", "matrix", "problem", "refit", "result", "selection"} +) +#: The statements in ``_main`` that bind another name, or a container, to one +#: of those objects or a large part of one, in source order. Any other such +#: binding would keep the object alive after its ``del`` or drop. +_EXPECTED_ALIAS_BINDINGS = ( + # The pre-selection frame on the frozen-support path. It is another object + # than the base_frame deleted after the export check, and outlives it. + "selection_candidate_frame = base_frame", + # The join's frame becomes the working frame; the result is deleted. + "base_frame = acs_predictor_join_result.frame", + # Rebound to the matrix-free result before the export. + "result = ladder_outcome.result", +) + + class _LargeObject: """A stand-in for a frame or table that a weak reference can follow.""" +def _holds_a_freed_object(node: ast.AST) -> bool: + """Whether an expression evaluates to, or contains, a checked object.""" + if isinstance(node, ast.Name): + return node.id in _FREED_NAMES + if isinstance(node, ast.Attribute): + return node.attr in _HOLDING_ATTRIBUTES and _holds_a_freed_object(node.value) + if isinstance(node, ast.Starred): + return _holds_a_freed_object(node.value) + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return any(_holds_a_freed_object(element) for element in node.elts) + if isinstance(node, ast.Dict): + return any( + value is not None and _holds_a_freed_object(value) for value in node.values + ) + return False + + def _main_function(builder) -> ast.FunctionDef: _, tree = _function_source(builder, "_main") (function,) = tree.body @@ -82,6 +127,19 @@ def _execute(statements: list[ast.stmt], namespace: dict, label: str) -> None: exec(compile(module, label, "exec"), namespace) +def test_main_binds_no_other_name_to_a_freed_object(builder) -> None: + """A second name would keep an object alive after its ``del`` or drop.""" + main = _main_function(builder) + bindings = sorted( + (node.lineno, ast.unparse(node)) + for node in ast.walk(main) + if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)) + and node.value is not None + and _holds_a_freed_object(node.value) + ) + assert tuple(statement for _, statement in bindings) == _EXPECTED_ALIAS_BINDINGS + + def test_main_keeps_only_the_receipt_of_the_acs_predictor_join(builder) -> None: """The join result is deleted before the next stage rebinds base_frame.""" main = _main_function(builder) @@ -183,6 +241,9 @@ def test_main_passes_each_donor_table_straight_into_its_stage(builder) -> None: and node.id.endswith("_donor") } assert donor_names == set() + # A cached loader would keep its table for the process, whatever _main does. + for loader in _DONOR_LOADERS: + assert not hasattr(getattr(builder, loader), "cache_info"), loader def test_main_frees_base_frame_after_the_export_input_mass_check(builder) -> None: @@ -245,14 +306,13 @@ def load_us_frame(path): def gate(candidate, base, *, reference_frame, **options): assert candidate is export_frame and base is base_frame - gate_calls.append( - { - "reference_frame": weakref.ref(reference_frame) - if reference_frame is not None - else None, - **options, - } - ) + if reference_frame is None: + reference = None + elif reference_frame is loaded[-1][1](): + reference = "loaded" + else: + reference = "other" + gate_calls.append({"reference": reference, **options}) if options["relative_tolerance"] < 0: raise RuntimeError("the gate failed") return verdict @@ -267,23 +327,22 @@ def gate(candidate, base, *, reference_frame, **options): assert returned is verdict ((loaded_path, reference),) = loaded assert loaded_path == reference_h5 - assert gate_calls[0]["reference_frame"] is reference - assert { - key: value for key, value in gate_calls[0].items() if key != "reference_frame" - } == (_check_options(builder)) + assert gate_calls[0] == {"reference": "loaded", **_check_options(builder)} gc.collect() assert reference() is None # A check that raises frees its reference once the error is handled. failing = {**_check_options(builder), "relative_tolerance": -1.0} - try: + with pytest.raises(RuntimeError, match="the gate failed") as raised: builder._export_input_mass_gate_with_reference_h5( export_frame, base_frame, reference_h5=reference_h5, **failing ) - except RuntimeError as error: - assert str(error) == "the gate failed" + # The traceback holds the check's frame, and so the reference, until the + # error is released, as _main's except clause does at its end. + del raised gc.collect() - assert len(loaded) == 2 and loaded[1][1]() is None + assert len(loaded) == 2 and gate_calls[1]["reference"] == "loaded" + assert loaded[1][1]() is None # Without a reference H5 the check compares against base_frame and loads # nothing. @@ -294,7 +353,7 @@ def gate(candidate, base, *, reference_frame, **options): is verdict ) assert len(loaded) == 2 - assert gate_calls[-1]["reference_frame"] is None + assert gate_calls[-1]["reference"] is None def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> None: @@ -333,13 +392,14 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( ladder_rebound = next( index for index, node in enumerate(main.body) - if isinstance(node, ast.If) + if index > frames_dropped + and isinstance(node, ast.If) and ast.unparse(node.test) == "isinstance(ladder_outcome, ExactKLadderCalibration)" ) assert frames_dropped < matrix_dropped < ladder_rebound assert statements[matrix_dropped + 1 : ladder_rebound] == [] - # Every reader of the calibration result comes after the drop. + # The solves, which need the matrix, run before the drop. calibration_calls = [ node.lineno for node in ast.walk(main) @@ -349,9 +409,15 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( ] assert calibration_calls assert max(calibration_calls) < main.body[matrix_dropped].lineno - surface_reads = _calls_named(main, "target_surface_payload") - assert surface_reads - assert all(call.lineno > main.body[matrix_dropped].lineno for call in surface_reads) + # After the drop, the release tool's own code never reads a matrix's + # entries: nothing in it reads ``.matrix`` or calls ``.estimates``. The + # calibrate package's readers are tested with a dropped matrix there. + tool = ast.parse(Path(builder.__file__).read_text()) + assert [ + f"{node.lineno}: {ast.unparse(node)}" + for node in ast.walk(tool) + if isinstance(node, ast.Attribute) and node.attr in {"matrix", "estimates"} + ] == [] def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> None: @@ -361,26 +427,27 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non check = statements.index("assert_release_input_coverage_manifest_current()") assert statements[check + 1] == "clear_installed_list_parameter_baseline_cache()" assert statements.count("clear_installed_list_parameter_baseline_cache()") == 1 + # Nothing in _main fills the cache again; the reform-coverage smoke, after + # the H5 write, is the next reader. + cleared_line = main.body[check + 1].lineno + for filler in ( + "assert_release_input_coverage_manifest_current", + "resolve_probe_parameter_changes", + "installed_list_parameter_baseline", + "_installed_parameter_stages", + ): + assert all(call.lineno < cleared_line for call in _calls_named(main, filler)) def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( - builder, monkeypatch + builder, ) -> None: - """At the export write, each constraint matrix is replaced by its shape and - nonzero count, and the target surface the diagnostics record is unchanged.""" - monkeypatch.setattr(builder, "_assert_no_formula_owned_columns", lambda frame: None) + """After ``_main``'s drop statements, each constraint matrix is replaced by + its shape and nonzero count, and the target surface is unchanged.""" from microcosm.calibrate import calibrate_l0_refit for full_pool in (True, False): target_frame, targets = _small_calibration_problem() - base_frame = Frame( - { - "person": target_frame.table("person"), - "household": target_frame.table("household").drop(columns="x"), - }, - target_frame.schema, - {"household": target_frame.weights_for("household")}, - ) result = ( calibrate(target_frame, targets, epochs=3, mass="conserve", seed=0) if full_pool @@ -419,7 +486,6 @@ def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( ) namespace = { **vars(builder), - "base_frame": base_frame, "result": result, "ladder_outcome": ladder_outcome, } @@ -492,3 +558,66 @@ def test_dropping_the_constraint_matrix_leaves_the_written_calibration_unchanged ) assert builder._in_sample_estimates(dropped) == builder._in_sample_estimates(result) assert builder._in_sample_targets(dropped) == builder._in_sample_targets(result) + + +def test_dropping_the_constraint_matrix_leaves_the_release_diagnostics_unchanged( + builder, small_frame, tmp_path +) -> None: + """The release's calibration_diagnostics.json, written the way _main writes + it, is byte-identical with and without the constraint matrix.""" + from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + without_constraint_matrix, + ) + + registry = TargetRegistry( + ( + TargetSpec( + name="income", + entity="person", + measure="income", + value=500_000.0, + source="fixture", + hierarchy=CalibrationHierarchy( + provider=HierarchyNode("irs_soi", "IRS Statistics of Income"), + category=HierarchyCategory("irs_soi.income", "Income", "irs_soi"), + geography=HierarchyGeography("0400000US06", "California", "state"), + dimensions=(), + target=HierarchyNode("income", "Income"), + ), + ), + ), + country="us", + ) + result = calibrate(small_frame, registry.to_target_set(), epochs=3, seed=0) + passing_gate = builder.GateResult( + name="passing", passed=True, details={"checked": True} + ) + written = {} + for label, calibrated in ( + ("original", result), + ("dropped", without_constraint_matrix(result)), + ): + release_dir = tmp_path / label + release_dir.mkdir() + outcome = builder._write_release_calibration_diagnostics( + result=calibrated, + target_surface=builder.target_surface_payload(calibrated), + release_dir=release_dir, + registry=registry, + base_dataset_sha256="0" * 64, + compilation={"dropped_target_names": []}, + target_profile_gate=passing_gate, + health_input_gate=passing_gate, + base_population_gate=passing_gate, + support_value_repairs={}, + audit_export_targets=False, + gate_failures=[], + default_dataset={"method": "dense_no_l0", "final_loss": result.final_loss}, + ) + assert outcome.status == "available", outcome + written[label] = (release_dir / "calibration_diagnostics.json").read_bytes() + assert written["dropped"] == written["original"] From 52017535fe66f1c8429bc5554d28223a10c9aea8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:00:40 +0400 Subject: [PATCH 04/19] Keep the matrix-dropping helper out of the attested solver modules 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 --- .../src/microcosm/calibrate/__init__.py | 8 +- .../src/microcosm/calibrate/dropped_matrix.py | 131 ++++++++++++++++++ .../src/microcosm/calibrate/matrix.py | 90 +----------- .../src/microcosm/calibrate/solve.py | 38 +---- 4 files changed, 139 insertions(+), 128 deletions(-) create mode 100644 packages/microcosm-calibrate/src/microcosm/calibrate/dropped_matrix.py diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py b/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py index 2ef6c2f0b3..03c034adf7 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/__init__.py @@ -96,6 +96,11 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: target_surface_payload, write_calibration_diagnostics, ) +from microcosm.calibrate.dropped_matrix import ( # noqa: E402 - after compat gate + ConstraintMatrixDroppedError, + DroppedConstraintMatrix, + without_constraint_matrix, +) from microcosm.calibrate.exact_k import ( # noqa: E402 - after the compat gate assert_exact_k_support, exact_k_design_feasibility, @@ -111,8 +116,6 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: ) from microcosm.calibrate.matrix import ( # noqa: E402 - after the compat gate CalibrationProblem, - ConstraintMatrixDroppedError, - DroppedConstraintMatrix, SkippedTarget, build_constraint_matrix, ) @@ -152,7 +155,6 @@ def _assert_frame_compatible(version: str, required: tuple[int, int]) -> None: rebuild_calibration_result, refit_l0_selection, relative_error_loss, - without_constraint_matrix, ) from microcosm.calibrate.static_aging import ( # noqa: E402 - after the compat gate DemographicProjection, diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/dropped_matrix.py b/packages/microcosm-calibrate/src/microcosm/calibrate/dropped_matrix.py new file mode 100644 index 0000000000..98a2d09bec --- /dev/null +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/dropped_matrix.py @@ -0,0 +1,131 @@ +"""Free a calibration result's constraint matrices once only their size is read. + +A :class:`~microcosm.calibrate.solve.CalibrationResult` keeps its compiled +:class:`~microcosm.calibrate.matrix.CalibrationProblem`, whose CSR matrix is +the largest object a solve returns. A long build that, after its solves, reads +only each matrix's shape and nonzero count, as +:func:`~microcosm.calibrate.diagnostics.target_surface_payload` does, can call +:func:`without_constraint_matrix` to free the matrices. + +The returned result's problem holds a :class:`DroppedConstraintMatrix` in the +``matrix`` field: the same ``shape`` and ``nnz``, so such a reader reports the +matrix it describes, and nothing else. Every use that needs the entries raises +:class:`ConstraintMatrixDroppedError`, so no caller computes with an empty or +missing matrix. The solver modules are untouched: the placeholder only ever +reaches a problem after its solve. +""" + +from __future__ import annotations + +from dataclasses import replace + +from microcosm.calibrate.solve import CalibrationResult, L0RefitResult + +__all__ = [ + "ConstraintMatrixDroppedError", + "DroppedConstraintMatrix", + "without_constraint_matrix", +] + + +class ConstraintMatrixDroppedError(RuntimeError): + """A use of a constraint matrix that was dropped after its solve.""" + + +class DroppedConstraintMatrix: + """The shape and nonzero count of a constraint matrix that was freed. + + ``shape`` and ``nnz`` keep the dropped matrix's values. Every other use of + the matrix (a product, a row slice, a conversion to an array, its length, + iteration, its stored arrays or any other attribute, including a + ``hasattr`` probe for one) raises :class:`ConstraintMatrixDroppedError`. + Copying and pickling work. + """ + + __slots__ = ("nnz", "shape") + + def __init__(self, shape: tuple[int, int], nnz: int) -> None: + self.shape = (int(shape[0]), int(shape[1])) + self.nnz = int(nnz) + + @classmethod + def of(cls, matrix) -> DroppedConstraintMatrix: + """Record ``matrix``'s shape and nonzero count; a record passes through.""" + if isinstance(matrix, cls): + return matrix + return cls(matrix.shape, matrix.nnz) + + def _refuse(self, use: str): + raise ConstraintMatrixDroppedError( + f"The {self.shape[0]} x {self.shape[1]} constraint matrix was dropped " + f"after calibration; only its shape and nonzero count ({self.nnz}) " + f"were kept, so {use} is unavailable." + ) + + def __getattr__(self, name: str): + # Called only for attributes the class lacks. Special-method lookups + # (copy, pickle, numpy's array protocols) see a plain missing + # attribute; so does an unset slot, which only partial construction + # leaves. + if name in type(self).__slots__ or ( + name.startswith("__") and name.endswith("__") + ): + raise AttributeError(name) + self._refuse(f"its {name!r}") + + def __array__(self, *args, **kwargs): + self._refuse("its dense array") + + def __matmul__(self, other): + self._refuse("a matrix product") + + def __rmatmul__(self, other): + self._refuse("a matrix product") + + def __mul__(self, other): + self._refuse("a product") + + def __rmul__(self, other): + self._refuse("a product") + + def __getitem__(self, key): + self._refuse("a row or entry") + + def __iter__(self): + self._refuse("iteration over its rows") + + def __len__(self) -> int: + self._refuse("its length") + + def __repr__(self) -> str: + return f"DroppedConstraintMatrix(shape={self.shape!r}, nnz={self.nnz!r})" + + +def without_constraint_matrix(result): + """Free a result's constraint matrices, keeping their shapes and nonzero counts. + + For a :class:`~microcosm.calibrate.solve.CalibrationResult`, the returned + result's problem holds a :class:`DroppedConstraintMatrix` in place of its + CSR matrix; any later use that needs the entries, such as + :meth:`~microcosm.calibrate.matrix.CalibrationProblem.estimates`, raises + :class:`ConstraintMatrixDroppedError`. Every other field is the same object + as before. + + An :class:`~microcosm.calibrate.solve.L0RefitResult` has two problems, the + selection's over the full frame and the refit's over the selected support; + both are dropped. Any other object holds no compiled problem and is + returned unchanged. + """ + if isinstance(result, L0RefitResult): + return replace( + result, + selection=without_constraint_matrix(result.selection), + refit=without_constraint_matrix(result.refit), + ) + if isinstance(result, CalibrationResult): + problem = result.problem + return replace( + result, + problem=replace(problem, matrix=DroppedConstraintMatrix.of(problem.matrix)), + ) + return result diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py b/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py index 464027b463..11aeb35c47 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/matrix.py @@ -38,90 +38,7 @@ from microcosm.calibrate.target import Target, TargetSet from microcosm.frame import Frame, Weights -__all__ = [ - "CalibrationProblem", - "ConstraintMatrixDroppedError", - "DroppedConstraintMatrix", - "SkippedTarget", - "build_constraint_matrix", -] - - -class ConstraintMatrixDroppedError(RuntimeError): - """A use of a constraint matrix that was dropped after its solve.""" - - -class DroppedConstraintMatrix: - """The shape and nonzero count of a constraint matrix that was freed. - - :func:`~microcosm.calibrate.solve.without_constraint_matrix` puts one in a - :class:`CalibrationProblem` in place of its CSR matrix once later code - reads only those two numbers, as - :func:`~microcosm.calibrate.diagnostics.target_surface_payload` does. - ``shape`` and ``nnz`` keep the dropped matrix's values, so such a reader - reports the matrix it describes. Every other use of the matrix (a product, - a row slice, a conversion, its stored arrays) raises - :class:`ConstraintMatrixDroppedError`, so no caller computes with an empty - or missing matrix. - """ - - __slots__ = ("nnz", "shape") - - def __init__(self, shape: tuple[int, int], nnz: int) -> None: - self.shape = (int(shape[0]), int(shape[1])) - self.nnz = int(nnz) - - @classmethod - def of(cls, matrix) -> DroppedConstraintMatrix: - """Record ``matrix``'s shape and nonzero count; a record passes through.""" - if isinstance(matrix, cls): - return matrix - return cls(matrix.shape, matrix.nnz) - - def _refuse(self, use: str): - raise ConstraintMatrixDroppedError( - f"The {self.shape[0]} x {self.shape[1]} constraint matrix was dropped " - f"after calibration; only its shape and nonzero count ({self.nnz}) " - f"were kept, so {use} is unavailable." - ) - - def __getattr__(self, name: str): - # Called only for attributes the class lacks. Special-method lookups - # (copy, pickle, numpy's array protocols) see a plain missing - # attribute; so does an unset slot, which only partial construction - # leaves. - if name in type(self).__slots__ or ( - name.startswith("__") and name.endswith("__") - ): - raise AttributeError(name) - self._refuse(f"its {name!r}") - - def __array__(self, *args, **kwargs): - self._refuse("its dense array") - - def __matmul__(self, other): - self._refuse("a matrix product") - - def __rmatmul__(self, other): - self._refuse("a matrix product") - - def __mul__(self, other): - self._refuse("a product") - - def __rmul__(self, other): - self._refuse("a product") - - def __getitem__(self, key): - self._refuse("a row or entry") - - def __iter__(self): - self._refuse("iteration over its rows") - - def __len__(self) -> int: - self._refuse("its length") - - def __repr__(self) -> str: - return f"DroppedConstraintMatrix(shape={self.shape!r}, nnz={self.nnz!r})" +__all__ = ["CalibrationProblem", "SkippedTarget", "build_constraint_matrix"] @dataclass(frozen=True) @@ -149,9 +66,6 @@ class CalibrationProblem: matrix: The constraint matrix ``A`` as a CSR ``scipy.sparse`` array of shape ``(n_targets, n_weights)``: one row per compiled ``(target, period)``, one column per record of ``weight_entity``. - After :func:`~microcosm.calibrate.solve.without_constraint_matrix` - it is a :class:`DroppedConstraintMatrix`, which keeps only the - shape and the nonzero count. target_vector: The right-hand side ``b`` of length ``n_targets``. Each row is a sum target, so the right-hand side is the target value. names: Row labels (``"name@period"``), aligned to ``matrix`` rows. @@ -167,7 +81,7 @@ class CalibrationProblem: guard; :func:`build_constraint_matrix` never produces one). """ - matrix: sparse.csr_array | DroppedConstraintMatrix + matrix: sparse.csr_array target_vector: np.ndarray names: tuple[str, ...] initial_weights: Weights diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index 09387e1ab1..e55a42a470 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -89,7 +89,7 @@ import math import warnings from collections.abc import Callable, Mapping -from dataclasses import dataclass, field, replace +from dataclasses import dataclass, field import numpy as np import torch @@ -107,7 +107,6 @@ from microcosm.calibrate.initialization import GateInitialization from microcosm.calibrate.matrix import ( CalibrationProblem, - DroppedConstraintMatrix, SkippedTarget, build_constraint_matrix, ) @@ -120,7 +119,6 @@ "rebuild_calibration_result", "refit_l0_selection", "solve_constraint_system", - "without_constraint_matrix", "default_target_loss_scales", "chi_square_distance", "effective_sample_size", @@ -3039,40 +3037,6 @@ def calibrate( ) -def without_constraint_matrix(result): - """Free a result's constraint matrices, keeping their shapes and nonzero counts. - - A :class:`CalibrationResult` keeps its compiled problem, whose CSR matrix - is the largest object a solve returns. A caller that later reads only the - matrix's shape and nonzero count, as - :func:`~microcosm.calibrate.diagnostics.target_surface_payload` does, - can call this once the matrix's entries are no longer needed. The returned - result's problem holds a - :class:`~microcosm.calibrate.matrix.DroppedConstraintMatrix` with those two - numbers; any later use that needs the entries, such as - :meth:`CalibrationProblem.estimates`, raises - :class:`~microcosm.calibrate.matrix.ConstraintMatrixDroppedError`. Every - other field is the same object as before. - - An :class:`L0RefitResult` has two problems, the selection's over the full - frame and the refit's over the selected support; both are dropped. Any - other object holds no compiled problem and is returned unchanged. - """ - if isinstance(result, L0RefitResult): - return replace( - result, - selection=without_constraint_matrix(result.selection), - refit=without_constraint_matrix(result.refit), - ) - if isinstance(result, CalibrationResult): - problem = result.problem - return replace( - result, - problem=replace(problem, matrix=DroppedConstraintMatrix.of(problem.matrix)), - ) - return result - - def solve_constraint_system( matrix, targets: np.ndarray, From 2837a797edc44d725d8a3d09169d6c0ac1c619d2 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:30:35 +0400 Subject: [PATCH 05/19] Strengthen the release-tool freeing tests after the second review - 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 --- .../test_us_release_frees_after_last_use.py | 190 +++++++++++++++--- .../engine_free/shared/test_diagnostics.py | 71 +++++-- 2 files changed, 220 insertions(+), 41 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 1a4263b3d7..51acb594f3 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -8,6 +8,7 @@ # ruff: noqa: F403, F405 import re +import textwrap import weakref from microcosm.calibrate import DroppedConstraintMatrix @@ -41,17 +42,29 @@ _HOLDING_ATTRIBUTES = frozenset( {"frame", "matrix", "problem", "refit", "result", "selection"} ) -#: The statements in ``_main`` that bind another name, or a container, to one -#: of those objects or a large part of one, in source order. Any other such -#: binding would keep the object alive after its ``del`` or drop. +#: Calls whose result holds their arguments. +_CONTAINER_CALLS = frozenset( + {"SimpleNamespace", "dict", "frozenset", "list", "set", "tuple"} +) +#: Methods that store their arguments in the object they are called on. +_STORING_METHODS = frozenset( + {"add", "append", "extend", "insert", "setdefault", "update"} +) +#: The places in ``_main`` that bind another name, or put a container, a copy +#: or a loop variable, on one of those objects or a large part of one, in +#: source order. Any other would keep the object alive after its ``del`` or +#: drop. _EXPECTED_ALIAS_BINDINGS = ( # The pre-selection frame on the frozen-support path. It is another object - # than the base_frame deleted after the export check, and outlives it. + # than the base_frame deleted after the export check, and this change + # leaves it alive until _main returns (a follow-up). "selection_candidate_frame = base_frame", # The join's frame becomes the working frame; the result is deleted. "base_frame = acs_predictor_join_result.frame", # Rebound to the matrix-free result before the export. "result = ladder_outcome.result", + # The outcome's copy holding the matrix-free result replaces the original. + "ladder_outcome = dataclasses.replace(ladder_outcome, result=result)", ) @@ -59,13 +72,25 @@ class _LargeObject: """A stand-in for a frame or table that a weak reference can follow.""" +def _called_name(call: ast.Call) -> str | None: + if isinstance(call.func, ast.Name): + return call.func.id + if isinstance(call.func, ast.Attribute): + return call.func.attr + return None + + +def _arguments(call: ast.Call) -> list[ast.expr]: + return [*call.args, *(keyword.value for keyword in call.keywords)] + + def _holds_a_freed_object(node: ast.AST) -> bool: """Whether an expression evaluates to, or contains, a checked object.""" if isinstance(node, ast.Name): return node.id in _FREED_NAMES if isinstance(node, ast.Attribute): return node.attr in _HOLDING_ATTRIBUTES and _holds_a_freed_object(node.value) - if isinstance(node, ast.Starred): + if isinstance(node, (ast.Starred, ast.NamedExpr)): return _holds_a_freed_object(node.value) if isinstance(node, (ast.Tuple, ast.List, ast.Set)): return any(_holds_a_freed_object(element) for element in node.elts) @@ -73,9 +98,55 @@ def _holds_a_freed_object(node: ast.AST) -> bool: return any( value is not None and _holds_a_freed_object(value) for value in node.values ) + if isinstance(node, ast.IfExp): + return _holds_a_freed_object(node.body) or _holds_a_freed_object(node.orelse) + if isinstance(node, ast.BoolOp): + return any(_holds_a_freed_object(value) for value in node.values) + if isinstance(node, ast.Call): + name = _called_name(node) + if name in _CONTAINER_CALLS: + return any(_holds_a_freed_object(argument) for argument in _arguments(node)) + if name == "replace": + # dataclasses.replace keeps every field it is not given. + return bool(node.args) and _holds_a_freed_object(node.args[0]) + if name == "getattr" and len(node.args) >= 2: + attribute = node.args[1] + return ( + isinstance(attribute, ast.Constant) + and attribute.value in _HOLDING_ATTRIBUTES + and _holds_a_freed_object(node.args[0]) + ) return False +def _alias_sites(function: ast.FunctionDef) -> list[tuple[int, str]]: + """Where ``function`` makes a checked object reachable another way.""" + sites = [] + for node in ast.walk(function): + if ( + isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.NamedExpr)) + and node.value is not None + and _holds_a_freed_object(node.value) + ): + sites.append((node.lineno, ast.unparse(node))) + elif isinstance(node, (ast.For, ast.comprehension)) and _holds_a_freed_object( + node.iter + ): + sites.append((node.iter.lineno, ast.unparse(node.iter))) + elif isinstance(node, ast.withitem) and _holds_a_freed_object( + node.context_expr + ): + sites.append((node.context_expr.lineno, ast.unparse(node.context_expr))) + elif ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in _STORING_METHODS + and any(_holds_a_freed_object(argument) for argument in _arguments(node)) + ): + sites.append((node.lineno, ast.unparse(node))) + return sorted(sites) + + def _main_function(builder) -> ast.FunctionDef: _, tree = _function_source(builder, "_main") (function,) = tree.body @@ -130,14 +201,31 @@ def _execute(statements: list[ast.stmt], namespace: dict, label: str) -> None: def test_main_binds_no_other_name_to_a_freed_object(builder) -> None: """A second name would keep an object alive after its ``del`` or drop.""" main = _main_function(builder) - bindings = sorted( - (node.lineno, ast.unparse(node)) - for node in ast.walk(main) - if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)) - and node.value is not None - and _holds_a_freed_object(node.value) + sites = _alias_sites(main) + assert tuple(statement for _, statement in sites) == _EXPECTED_ALIAS_BINDINGS + + +def test_the_alias_check_sees_each_way_of_keeping_an_object() -> None: + """Each form below keeps ``base_frame`` or the matrix reachable.""" + keeping = ( + "kept = base_frame if flag else None", + "kept = flag and base_frame", + "kept = SimpleNamespace(frame=base_frame)", + "kept = dataclasses.replace(ladder_outcome, support=support)", + "kept = getattr(result, 'problem')", + "kept = [result.problem.matrix]", + "kept += [release_engine]", + "frames.append(base_frame)", + "for kept in (base_frame,):\n pass", + "with release_engine as kept:\n pass", ) - assert tuple(statement for _, statement in bindings) == _EXPECTED_ALIAS_BINDINGS + harmless = ("total = base_frame.n('household')", "loss = result.final_loss") + for source, expected_sites in ( + *((source, 1) for source in keeping), + *((source, 0) for source in harmless), + ): + function = ast.parse("def _main():\n" + textwrap.indent(source, " ")) + assert len(_alias_sites(function.body[0])) == expected_sites, source def test_main_keeps_only_the_receipt_of_the_acs_predictor_join(builder) -> None: @@ -233,14 +321,6 @@ def test_main_passes_each_donor_table_straight_into_its_stage(builder) -> None: assert isinstance(stage, ast.Call) assert isinstance(stage.func, ast.Name) assert stage.func.id.startswith("with_us_"), ast.unparse(stage.func) - donor_names = { - node.id - for node in ast.walk(main) - if isinstance(node, ast.Name) - and isinstance(node.ctx, ast.Store) - and node.id.endswith("_donor") - } - assert donor_names == set() # A cached loader would keep its table for the process, whatever _main does. for loader in _DONOR_LOADERS: assert not hasattr(getattr(builder, loader), "cache_info"), loader @@ -409,13 +489,56 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( ] assert calibration_calls assert max(calibration_calls) < main.body[matrix_dropped].lineno - # After the drop, the release tool's own code never reads a matrix's - # entries: nothing in it reads ``.matrix`` or calls ``.estimates``. The - # calibrate package's readers are tested with a dropped matrix there. + # After the drop, no tool code that can reach the calibration result reads + # a matrix's entries: neither _main's later statements nor any tool + # function they pass result or ladder_outcome to, followed through the + # tool's own calls, reads ``.matrix`` or calls ``.estimates``. The + # calibrate package's readers run on a dropped matrix in this module's + # output tests and in the calibrate package's tests. + dropped_line = main.body[matrix_dropped].lineno tool = ast.parse(Path(builder.__file__).read_text()) + functions = { + node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) + } + frontier = [ + call.func.id + for call in ast.walk(main) + if isinstance(call, ast.Call) + and call.lineno > dropped_line + and isinstance(call.func, ast.Name) + and call.func.id in functions + and any( + isinstance(argument, ast.Name) + and argument.id in {"result", "ladder_outcome"} + for argument in _arguments(call) + ) + ] + assert { + "_release_gate_failures", + "_write_npz", + "_write_release_calibration_diagnostics", + } <= set(frontier) + reached: set[str] = set() + while frontier: + name = frontier.pop() + if name in reached: + continue + reached.add(name) + frontier.extend( + call.func.id + for call in ast.walk(functions[name]) + if isinstance(call, ast.Call) + and isinstance(call.func, ast.Name) + and call.func.id in functions + ) + later_nodes = [ + node for node in ast.walk(main) if getattr(node, "lineno", 0) > dropped_line + ] + for name in sorted(reached - {"_main"}): + later_nodes.extend(ast.walk(functions[name])) assert [ f"{node.lineno}: {ast.unparse(node)}" - for node in ast.walk(tool) + for node in later_nodes if isinstance(node, ast.Attribute) and node.attr in {"matrix", "estimates"} ] == [] @@ -430,13 +553,20 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non # Nothing in _main fills the cache again; the reform-coverage smoke, after # the H5 write, is the next reader. cleared_line = main.body[check + 1].lineno - for filler in ( + fillers = { "assert_release_input_coverage_manifest_current", "resolve_probe_parameter_changes", "installed_list_parameter_baseline", "_installed_parameter_stages", - ): - assert all(call.lineno < cleared_line for call in _calls_named(main, filler)) + } + # Called by name or through a module attribute. + assert [ + f"{call.lineno}: {ast.unparse(call)}" + for call in ast.walk(main) + if isinstance(call, ast.Call) + and _called_name(call) in fillers + and call.lineno > cleared_line + ] == [] def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( @@ -509,8 +639,10 @@ def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( def test_dropping_the_constraint_matrix_leaves_the_written_calibration_unchanged( builder, tmp_path, full_pool ) -> None: - """The calibration NPZ, the diagnostics payload and the target surface - written from a result without its matrices equal those of the original.""" + """Writing from a result without its matrices raises nothing and gives the + same calibration NPZ arrays, diagnostics payload, target surface and + in-sample fit. Of these, only the target surface reads the matrix (its + shape and nonzero count); the rest show that no reader needs it.""" from microcosm.calibrate import ( calibrate_l0_refit, diagnostics_payload, diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py index c3144b09fa..df1acbcaf4 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py @@ -18,6 +18,7 @@ import numpy as np import pytest +from scipy import sparse from microcosm.calibrate import ( CALIBRATION_DIAGNOSTICS_ASSEMBLY_SCHEMA_VERSION, @@ -1225,9 +1226,10 @@ def test_payload_census_from_a_real_solve(feasible_frame) -> None: json.dumps(payload, allow_nan=False) -def _l0_refit_result(feasible_frame): - frame, truths = feasible_frame() - targets = TargetSet( +def _sparse_targets(truths) -> TargetSet: + """Income on every household and renters on about a third of them, so the + constraint matrix stores fewer entries than it has cells.""" + return TargetSet( ( Target( name="income", @@ -1236,18 +1238,37 @@ def _l0_refit_result(feasible_frame): measure="income", ), Target( - name="population", + name="renters", entity="household", - value=truths["population"], - measure="household_count", + value=truths["renters"] * 1.1, + measure="is_renter", ), ) ) + + +def _sparse_result(feasible_frame): + frame, truths = feasible_frame() + return calibrate(frame, _sparse_targets(truths), epochs=20, seed=0) + + +def _l0_refit_result(feasible_frame): + frame, truths = feasible_frame() return calibrate_l0_refit( - frame, targets, epochs=40, seed=0, l0_lambda=0.003, mass="conserve" + frame, + _sparse_targets(truths), + epochs=40, + seed=0, + l0_lambda=0.003, + mass="conserve", ) +def _assert_sparse(matrix) -> None: + rows, columns = matrix.shape + assert 0 < matrix.nnz < rows * columns + + def _matrix_references(problem) -> list[weakref.ref]: """Weak references to a constraint matrix and each array that stores it.""" matrix = problem.matrix @@ -1263,10 +1284,10 @@ def test_dropping_the_constraint_matrix_keeps_its_shape_and_nonzero_count( feasible_frame, ) -> None: """The matrix is freed; the target surface and the payload are unchanged.""" - result = _result(feasible_frame, epochs=20) + result = _sparse_result(feasible_frame) + _assert_sparse(result.problem.matrix) shape = tuple(result.problem.matrix.shape) nonzero_count = int(result.problem.matrix.nnz) - assert nonzero_count > 0 surface = target_surface_payload(result) payload = diagnostics_payload(result) references = _matrix_references(result.problem) @@ -1293,6 +1314,10 @@ def test_dropping_an_l0_refit_result_drops_the_selection_matrix_too( ) -> None: """Under L0 selection the selection's full-frame matrix is freed as well.""" result = _l0_refit_result(feasible_frame) + _assert_sparse(result.selection.problem.matrix) + _assert_sparse(result.refit.problem.matrix) + refit_shape = tuple(result.refit.problem.matrix.shape) + refit_nonzero_count = int(result.refit.problem.matrix.nnz) selection_shape = tuple(result.selection.problem.matrix.shape) selection_nonzero_count = int(result.selection.problem.matrix.nnz) surface = target_surface_payload(result) @@ -1309,6 +1334,8 @@ def test_dropping_an_l0_refit_result_drops_the_selection_matrix_too( assert [reference() for reference in references] == [None] * len(references) assert dropped.selection.problem.matrix.shape == selection_shape assert dropped.selection.problem.matrix.nnz == selection_nonzero_count + assert dropped.refit.problem.matrix.shape == refit_shape + assert dropped.refit.problem.matrix.nnz == refit_nonzero_count assert target_surface_payload(dropped) == surface assert diagnostics_payload(dropped) == payload @@ -1337,10 +1364,30 @@ def test_a_dropped_constraint_matrix_refuses_every_use_that_needs_its_entries( np.asarray(matrix) with pytest.raises(ConstraintMatrixDroppedError, match="was dropped"): len(matrix) - # Encoding the problem for an artifact needs every entry. - with pytest.raises(ValueError) as encoding_error: + # Encoding the problem for an artifact needs every entry. SciPy reports + # the refusal as its own error raised from this one. + with pytest.raises( + (ConstraintMatrixDroppedError, TypeError, ValueError) + ) as encoding_error: encode_problem(dropped.problem, entity_ids=list(range(len(weights)))) - assert isinstance(encoding_error.value.__cause__, ConstraintMatrixDroppedError) + assert isinstance(encoding_error.value, ConstraintMatrixDroppedError) or isinstance( + encoding_error.value.__cause__, ConstraintMatrixDroppedError + ) + + +def test_a_dropped_matrix_keeps_the_stored_entry_count() -> None: + """``nnz`` is the stored-entry count the target surface records, explicit + zeros included, not the count of nonzero values or of cells.""" + matrix = sparse.csr_array( + (np.array([1.0, 0.0, 2.0]), np.array([0, 2, 1]), np.array([0, 2, 3])), + shape=(2, 4), + ) + assert (matrix.nnz, matrix.count_nonzero()) == (3, 2) + + dropped = DroppedConstraintMatrix.of(matrix) + + assert (dropped.shape, dropped.nnz) == ((2, 4), 3) + assert DroppedConstraintMatrix.of(dropped) is dropped def test_dropping_the_constraint_matrix_returns_other_objects_unchanged() -> None: From 86169f7751377ae52163a0399a18aa573b94671d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:41:01 +0400 Subject: [PATCH 06/19] Free base_frame and release_engine by rebinding after the rebase 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 --- .../us/test_us_fiscal_refresh_builder.py | 2 +- .../test_us_release_frees_after_last_use.py | 236 +++++++++++++----- tools/build_us_fiscal_refresh_release.py | 10 +- 3 files changed, 188 insertions(+), 60 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index c187b3f6f7..15845155f0 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -14837,7 +14837,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_with_reference_h5", + "_record_export_input_mass_gate", "_record_qrf_tail_concentration_gate", "us_reform_coverage_smoke_gate", "_record_stored_inputs_gate_evidence", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 51acb594f3..152bdfe637 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -2,8 +2,8 @@ ``_main`` is one long function, so a local it never deletes stays alive until the run ends. These tests read the function's syntax tree, and execute slices -of its statements, to check that each large object is deleted, or never bound -to a local, once nothing reads it. +of its statements, to check that each large object is deleted, rebound to +``None``, or never bound to a local, once nothing reads it. """ # ruff: noqa: F403, F405 @@ -11,7 +11,10 @@ import textwrap import weakref +from microcosm.build.gate_battery import GateStatus +from microcosm.build.us_runtime.gate_shadow import current_gate_shadow from microcosm.calibrate import DroppedConstraintMatrix +from test_support.microcosm_build.us_gate_shadow import arm_us_tool_gate_shadows from test_support.microcosm_build.us_post_export_scoring import * #: The nine donor-table loaders ``_main`` calls, one per imputation stage. @@ -52,11 +55,11 @@ ) #: The places in ``_main`` that bind another name, or put a container, a copy #: or a loop variable, on one of those objects or a large part of one, in -#: source order. Any other would keep the object alive after its ``del`` or -#: drop. +#: source order. Any other would keep the object alive after ``_main`` frees +#: it. _EXPECTED_ALIAS_BINDINGS = ( # The pre-selection frame on the frozen-support path. It is another object - # than the base_frame deleted after the export check, and this change + # than the base_frame released after the export check, and this change # leaves it alive until _main returns (a follow-up). "selection_candidate_frame = base_frame", # The join's frame becomes the working frame; the result is deleted. @@ -183,6 +186,24 @@ def _single_top_level_delete(function: ast.FunctionDef, name: str) -> int: return function.body.index(deleted) +def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: + """The index in ``_main``'s body of its one `` = None`` statement. + + ``_main`` frees an object that a shadow-gate lambda reads by rebinding its + name to ``None``, because ruff reports a lambda's read of a name deleted + later in the function as a read of an undefined name. + """ + assert _deletes(function, name) == [] + (released,) = [ + node + for node in ast.walk(function) + if isinstance(node, ast.Assign) and ast.unparse(node) == f"{name} = None" + ] + # A top-level statement runs on every path that reaches it, not only + # inside one branch. + return function.body.index(released) + + def _calls_named(tree: ast.AST, name: str) -> list[ast.Call]: return [ node @@ -327,22 +348,23 @@ def test_main_passes_each_donor_table_straight_into_its_stage(builder) -> None: def test_main_frees_base_frame_after_the_export_input_mass_check(builder) -> None: - """``del base_frame`` follows the check that reads it last.""" + """``base_frame = None`` follows the check that reads it last.""" main = _main_function(builder) - deleted_at = _single_top_level_delete(main, "base_frame") - deleted_line = main.body[deleted_at].lineno - check = main.body[deleted_at - 1] - assert isinstance(check, ast.Try) - assert _calls_named(check, "_export_input_mass_gate_with_reference_h5") - assert max(_name_lines(main, "base_frame", ast.Load)) < deleted_line - assert max(_name_lines(main, "base_frame", ast.Store)) < deleted_line + released_at = _single_top_level_release(main, "base_frame") + released_line = main.body[released_at].lineno + check = main.body[released_at - 1] + assert isinstance(check, ast.Assign) + assert _calls_named(check, "_record_export_input_mass_gate") + # Every read, the shadow-gate lambdas' included, comes before the release. + assert max(_name_lines(main, "base_frame", ast.Load)) < released_line + assert max(_name_lines(main, "base_frame", ast.Store)) == released_line (write,) = [ node.lineno for node in ast.walk(main) if isinstance(node, ast.Call) and getattr(node.func, "attr", None) == "write_dataset" ] - assert deleted_line < write + assert released_line < write def test_main_leaves_the_export_reference_frame_to_its_check(builder) -> None: @@ -353,31 +375,38 @@ def test_main_leaves_the_export_reference_frame_to_its_check(builder) -> None: node.id for node in ast.walk(main) if isinstance(node, ast.Name) } assert _calls_named(main, "_export_input_mass_gate") == [] - (call,) = _calls_named(main, "_export_input_mass_gate_with_reference_h5") + (call,) = _calls_named(main, "_record_export_input_mass_gate") keywords = {keyword.arg: ast.unparse(keyword.value) for keyword in call.keywords} - assert keywords["reference_h5"] == "args.export_input_mass_reference_h5" - assert keywords["reference_name"] == "export_reference_name" + assert keywords == { + "reference_h5": "args.export_input_mass_reference_h5", + "reference_name": "export_reference_name", + "reference_record": "export_input_mass_reference", + "relative_tolerance": "args.input_mass_relative_tolerance", + "minimum_reference_total": "args.input_mass_minimum_reference_total", + "terminal_gate_failures": "terminal_gate_failures", + } -def _check_options(builder) -> dict[str, object]: - return { - "relative_tolerance": 0.05, - "minimum_reference_total": 1.0, - "reference_name": "reference_populace_us_2024.h5", - "reviewed_exclusions": builder.US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, - } +#: The result name ``_export_input_mass_gate`` gives, which the gate battery's +#: binding renames to the entry's declared gate. +_EXPORT_CHECK_RESULT_NAME = "input_mass_parity" +#: The options ``_main`` passes the export check, which passes them on to +#: ``_export_input_mass_gate``. +_CHECK_OPTIONS = { + "relative_tolerance": 0.5, + "minimum_reference_total": 1.0, + "reference_name": "reference_populace_us_2024.h5", +} -def test_the_export_input_mass_check_frees_its_reference_when_it_returns( - builder, monkeypatch -) -> None: - """The check loads the reference itself and holds it only while it runs.""" +def _fake_reference_check(builder, monkeypatch, export_frame, base_frame, verdict): + """Stand in ``load_us_frame`` and ``_export_input_mass_gate``. + + Returns the loads, as each path with a weak reference to its frame, and + each call of the gate, with ``reference`` saying which frame it got. + """ loaded: list[tuple[Path, weakref.ref]] = [] gate_calls: list[dict[str, object]] = [] - export_frame, base_frame = _LargeObject(), _LargeObject() - verdict = builder.GateResult( - name="export_input_mass_parity", passed=True, details={"checked": True} - ) def load_us_frame(path): reference = _LargeObject() @@ -399,50 +428,147 @@ def gate(candidate, base, *, reference_frame, **options): monkeypatch.setattr(builder, "load_us_frame", load_us_frame) monkeypatch.setattr(builder, "_export_input_mass_gate", gate) - reference_h5 = Path("reference_populace_us_2024.h5") + return loaded, gate_calls + - returned = builder._export_input_mass_gate_with_reference_h5( - export_frame, base_frame, reference_h5=reference_h5, **_check_options(builder) +def test_the_export_input_mass_check_frees_its_reference_when_it_returns( + builder, monkeypatch, tmp_path +) -> None: + """The check loads the reference itself and holds it only while it runs, + whether it returns, raises, or records its error under earlier failures.""" + export_frame, base_frame = _LargeObject(), _LargeObject() + verdict = builder.GateResult( + name=_EXPORT_CHECK_RESULT_NAME, passed=True, details={"checked": True} + ) + loaded, gate_calls = _fake_reference_check( + builder, monkeypatch, export_frame, base_frame, verdict ) + reference_h5 = tmp_path / "reference_populace_us_2024.h5" + reference_h5.write_bytes(b"reference bytes") + gate_options = { + **_CHECK_OPTIONS, + "reviewed_exclusions": builder.US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, + } + + def check(reference_h5, *, failures, **overrides): + record: dict[str, object] = {"sha256": None} + returned = builder._record_export_input_mass_gate( + export_frame, + base_frame, + reference_h5=reference_h5, + reference_record=record, + terminal_gate_failures=failures, + **{**_CHECK_OPTIONS, **overrides}, + ) + return returned, record + + returned, record = check(reference_h5, failures=[]) assert returned is verdict + assert record["sha256"] == builder._sha256(reference_h5) ((loaded_path, reference),) = loaded assert loaded_path == reference_h5 - assert gate_calls[0] == {"reference": "loaded", **_check_options(builder)} + assert gate_calls[0] == {"reference": "loaded", **gate_options} gc.collect() assert reference() is None - # A check that raises frees its reference once the error is handled. - failing = {**_check_options(builder), "relative_tolerance": -1.0} + # A check that raises on an otherwise-clean run frees its reference once + # the error is handled. with pytest.raises(RuntimeError, match="the gate failed") as raised: - builder._export_input_mass_gate_with_reference_h5( - export_frame, base_frame, reference_h5=reference_h5, **failing - ) + check(reference_h5, failures=[], relative_tolerance=-1.0) # The traceback holds the check's frame, and so the reference, until the - # error is released, as _main's except clause does at its end. + # error is released. del raised gc.collect() assert len(loaded) == 2 and gate_calls[1]["reference"] == "loaded" assert loaded[1][1]() is None + # Under earlier failures the error becomes one more failure line, and the + # reference is freed when the check returns. + failures = ["an earlier gate failed"] + returned, _ = check(reference_h5, failures=failures, relative_tolerance=-1.0) + assert returned is None + assert failures == [ + "an earlier gate failed", + "Input mass parity failed: evaluation error under earlier gate failures: " + "RuntimeError: the gate failed", + ] + gc.collect() + assert len(loaded) == 3 and loaded[2][1]() is None + # Without a reference H5 the check compares against base_frame and loads # nothing. - assert ( - builder._export_input_mass_gate_with_reference_h5( - export_frame, base_frame, reference_h5=None, **_check_options(builder) - ) - is verdict - ) - assert len(loaded) == 2 + returned, record = check(None, failures=[]) + assert returned is verdict and record["sha256"] is None + assert len(loaded) == 3 assert gate_calls[-1]["reference"] is None +def test_the_shadow_sees_the_export_reference_and_does_not_keep_it( + builder, monkeypatch, tmp_path +) -> None: + """Every real run arms the gate battery's shadow, which evaluates the same + check on an evidence context holding the loaded reference. The reference + is still freed when the check returns.""" + arm_us_tool_gate_shadows(monkeypatch) + export_frame, base_frame = _LargeObject(), _LargeObject() + verdict = builder.GateResult( + name=_EXPORT_CHECK_RESULT_NAME, passed=True, details={"checked": True} + ) + loaded, gate_calls = _fake_reference_check( + builder, monkeypatch, export_frame, base_frame, verdict + ) + reference_h5 = tmp_path / "reference_populace_us_2024.h5" + reference_h5.write_bytes(b"reference bytes") + args = SimpleNamespace( + out=tmp_path / "out", + dry_run_gates_report=None, + allow_input_mass_drift=False, + allow_ecps_parity_gaps=False, + allow_input_coverage_gaps=False, + allow_esi_premium_gaps=False, + allow_unpinned_feed=False, + allow_qrf_tail_concentration=False, + evidence_release=False, + input_mass_relative_tolerance=_CHECK_OPTIONS["relative_tolerance"], + input_mass_minimum_reference_total=_CHECK_OPTIONS["minimum_reference_total"], + ) + builder._start_national_gate_shadow(args, release_id="microcosm-us-test") + try: + shadow = current_gate_shadow("us_national_export_input_mass") + assert shadow is not None + returned = builder._record_export_input_mass_gate( + export_frame, + base_frame, + reference_h5=reference_h5, + reference_record={"sha256": None}, + terminal_gate_failures=[], + **_CHECK_OPTIONS, + ) + outcome = shadow.outcome("us_national_export_input_mass") + differences = shadow.differences() + finally: + builder._finish_national_gate_shadow(stopped_at="test teardown") + + assert returned is verdict + # Today's check and the shadow's evaluation each got the loaded frame. + assert [call["reference"] for call in gate_calls] == ["loaded", "loaded"] + assert outcome is not None and outcome.status is GateStatus.PASSED + assert differences == () + ((_, reference),) = loaded + gc.collect() + assert reference() is None + + def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> None: - """The engine that writes the H5 is deleted before post-export scoring.""" + """The engine that writes the H5 is released right after the write, before + the written-file check, the export audit and the calibration NPZ that end + the build.""" main = _main_function(builder) - deleted_at = _single_top_level_delete(main, "release_engine") - deleted_line = main.body[deleted_at].lineno + released_at = _single_top_level_release(main, "release_engine") + released_line = main.body[released_at].lineno + # Every read, the shadow-gate lambdas' included, comes before the release. reads = _name_lines(main, "release_engine", ast.Load) - assert reads and max(reads) < deleted_line + assert reads and max(reads) < released_line (write,) = [ node for node in main.body @@ -451,9 +577,7 @@ def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> Non and getattr(node.value.func, "attr", None) == "write_dataset" ] assert ast.unparse(write.value.func.value) == "release_engine" - assert write.lineno < deleted_line - (scorer,) = _calls_named(main, "_open_post_export_scorer") - assert deleted_line < scorer.lineno + assert released_at == main.body.index(write) + 1 def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 63d8f196a0..3fdb0c5a4c 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -19039,8 +19039,11 @@ def _main(argv: Sequence[str] | None = None) -> int | None: terminal_gate_failures=terminal_gate_failures, ) # The check above is base_frame's last reader; the export frame and the - # written H5 carry everything later stages read. - del base_frame + # written H5 carry everything later stages read. Rebinding the name frees + # the frame. A ``del`` would do the same, but ruff would then report the + # shadow-gate lambdas above, which read the name while they run, as reading + # an undefined name. + base_frame = None # A reference the gate never evaluated is still named, but marked so no # reader takes its bytes as what the parity verdict saw. export_input_mass_reference["evaluated"] = export_input_mass_gate is not None @@ -19177,7 +19180,8 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # so attempts 13/14 smoke-scored a stale artifact from a prior run. release_engine.write_dataset(export_frame, dataset_path, period=PERIOD) # The writer was the engine's last use; post-export scoring builds its own. - del release_engine + # Rebound rather than deleted, as base_frame is above. + release_engine = None # microcosm#1026: the stored-input gate above graded a model of the # writer's output; the written bytes are graded whatever the gate reached # and must earn the same verdict (no refusal, if the gate could not From 8d3dd022baa3070ab0b7ccf7277d0868b901ff3c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:02:20 +0400 Subject: [PATCH 07/19] Test the export check's error paths with the shadow armed - 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 --- .../release-free-after-last-use.changed.md | 2 +- .../test_us_release_frees_after_last_use.py | 362 +++++++++++++----- .../engine_free/shared/test_diagnostics.py | 8 +- 3 files changed, 263 insertions(+), 109 deletions(-) diff --git a/changelog.d/release-free-after-last-use.changed.md b/changelog.d/release-free-after-last-use.changed.md index 496f0a0e89..e7c6fda5c9 100644 --- a/changelog.d/release-free-after-last-use.changed.md +++ b/changelog.d/release-free-after-last-use.changed.md @@ -1 +1 @@ -The US fiscal refresh release (`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, deletes `base_frame` after the export input-mass check, loads the export reference frame inside that check (`_export_input_mass_gate_with_reference_h5`), and deletes `release_engine` after the H5 write. 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 system is not kept through the source stages and the calibration; the reform-coverage smoke builds it once more. Written outputs are unchanged. +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` after the H5 write. 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. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 152bdfe637..8985caf381 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -7,6 +7,7 @@ """ # ruff: noqa: F403, F405 +import contextlib import re import textwrap import weakref @@ -45,9 +46,19 @@ _HOLDING_ATTRIBUTES = frozenset( {"frame", "matrix", "problem", "refit", "result", "selection"} ) -#: Calls whose result holds their arguments. +#: Calls whose result holds their arguments, or a copy of them. _CONTAINER_CALLS = frozenset( - {"SimpleNamespace", "dict", "frozenset", "list", "set", "tuple"} + { + "SimpleNamespace", + "copy", + "deepcopy", + "dict", + "frozenset", + "list", + "partial", + "set", + "tuple", + } ) #: Methods that store their arguments in the object they are called on. _STORING_METHODS = frozenset( @@ -110,8 +121,9 @@ def _holds_a_freed_object(node: ast.AST) -> bool: if name in _CONTAINER_CALLS: return any(_holds_a_freed_object(argument) for argument in _arguments(node)) if name == "replace": - # dataclasses.replace keeps every field it is not given. - return bool(node.args) and _holds_a_freed_object(node.args[0]) + # dataclasses.replace keeps every field it is not given, and + # stores every field it is given. + return any(_holds_a_freed_object(argument) for argument in _arguments(node)) if name == "getattr" and len(node.args) >= 2: attribute = node.args[1] return ( @@ -147,6 +159,23 @@ def _alias_sites(function: ast.FunctionDef) -> list[tuple[int, str]]: and any(_holds_a_freed_object(argument) for argument in _arguments(node)) ): sites.append((node.lineno, ast.unparse(node))) + elif ( + isinstance(node, ast.Call) + and _called_name(node) == "setattr" + and len(node.args) >= 3 + and _holds_a_freed_object(node.args[2]) + ): + sites.append((node.lineno, ast.unparse(node))) + elif ( + isinstance(node, (ast.Lambda, ast.FunctionDef, ast.AsyncFunctionDef)) + and node is not function + and any( + default is not None and _holds_a_freed_object(default) + for default in (*node.args.defaults, *node.args.kw_defaults) + ) + ): + # A default argument lives as long as the function object does. + sites.append((node.lineno, ast.unparse(node.args))) return sorted(sites) @@ -204,6 +233,27 @@ def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: return function.body.index(released) +def _tool_functions_reached( + functions: dict[str, ast.FunctionDef], names: set[str] +) -> set[str]: + """``names`` and every tool function they call by name, transitively.""" + reached: set[str] = set() + frontier = list(names) + while frontier: + name = frontier.pop() + if name in reached: + continue + reached.add(name) + frontier.extend( + call.func.id + for call in ast.walk(functions[name]) + if isinstance(call, ast.Call) + and isinstance(call.func, ast.Name) + and call.func.id in functions + ) + return reached + + def _calls_named(tree: ast.AST, name: str) -> list[ast.Call]: return [ node @@ -239,6 +289,12 @@ def test_the_alias_check_sees_each_way_of_keeping_an_object() -> None: "frames.append(base_frame)", "for kept in (base_frame,):\n pass", "with release_engine as kept:\n pass", + "kept = copy.copy(result)", + "kept = functools.partial(write, result=result)", + "kept = dataclasses.replace(outcome, result=result)", + "setattr(holder, 'frame', base_frame)", + "callbacks.append(lambda frame=base_frame: frame)", + "def later(*, engine=release_engine):\n pass", ) harmless = ("total = base_frame.n('household')", "loss = result.final_loss") for source, expected_sites in ( @@ -387,6 +443,8 @@ def test_main_leaves_the_export_reference_frame_to_its_check(builder) -> None: } +#: The export input-mass check's entry in the national gate battery. +_EXPORT_CHECK_ENTRY = "us_national_export_input_mass" #: The result name ``_export_input_mass_gate`` gives, which the gate battery's #: binding renames to the entry's declared gate. _EXPORT_CHECK_RESULT_NAME = "input_mass_parity" @@ -399,93 +457,139 @@ def test_main_leaves_the_export_reference_frame_to_its_check(builder) -> None: } -def _fake_reference_check(builder, monkeypatch, export_frame, base_frame, verdict): - """Stand in ``load_us_frame`` and ``_export_input_mass_gate``. +class _ReferenceCheckStandIn: + """Stands in for ``load_us_frame`` and ``_export_input_mass_gate``. - Returns the loads, as each path with a weak reference to its frame, and - each call of the gate, with ``reference`` saying which frame it got. + Records each load, as its path and a weak reference to the frame it + returns, and each call of the check, with ``reference`` saying which frame + it got. It holds the export and base frames only through weak references, + so a test can see whether the code under test keeps them. Setting + ``failing`` to ``"load"`` or ``"check"`` makes that step raise. """ - loaded: list[tuple[Path, weakref.ref]] = [] - gate_calls: list[dict[str, object]] = [] - def load_us_frame(path): + def __init__(self, builder, monkeypatch, export_frame, base_frame) -> None: + self.loaded: list[tuple[Path, weakref.ref]] = [] + self.gate_calls: list[dict[str, object]] = [] + self.failing: str | None = None + self.verdict = builder.GateResult( + name=_EXPORT_CHECK_RESULT_NAME, passed=True, details={"checked": True} + ) + self._export_frame = weakref.ref(export_frame) + self._base_frame = weakref.ref(base_frame) + monkeypatch.setattr(builder, "load_us_frame", self.load_us_frame) + monkeypatch.setattr(builder, "_export_input_mass_gate", self.gate) + + def load_us_frame(self, path): + if self.failing == "load": + raise OSError("the reference did not open") reference = _LargeObject() - loaded.append((Path(path), weakref.ref(reference))) + self.loaded.append((Path(path), weakref.ref(reference))) return reference - def gate(candidate, base, *, reference_frame, **options): - assert candidate is export_frame and base is base_frame + def gate(self, candidate, base, *, reference_frame, **options): + assert candidate is self._export_frame() and base is self._base_frame() if reference_frame is None: reference = None - elif reference_frame is loaded[-1][1](): + elif reference_frame is self.loaded[-1][1](): reference = "loaded" else: reference = "other" - gate_calls.append({"reference": reference, **options}) - if options["relative_tolerance"] < 0: + self.gate_calls.append({"reference": reference, **options}) + if self.failing == "check": raise RuntimeError("the gate failed") - return verdict + return self.verdict + + def frames_freed(self) -> bool: + gc.collect() + return self._export_frame() is None and self._base_frame() is None + + +@contextlib.contextmanager +def _armed_national_shadow(builder, monkeypatch, tmp_path): + """Arm the national scope's gate battery shadow, as every real run does.""" + arm_us_tool_gate_shadows(monkeypatch) + args = SimpleNamespace( + out=tmp_path / "out", + dry_run_gates_report=None, + allow_input_mass_drift=False, + allow_ecps_parity_gaps=False, + allow_input_coverage_gaps=False, + allow_esi_premium_gaps=False, + allow_unpinned_feed=False, + allow_qrf_tail_concentration=False, + evidence_release=False, + input_mass_relative_tolerance=_CHECK_OPTIONS["relative_tolerance"], + input_mass_minimum_reference_total=_CHECK_OPTIONS["minimum_reference_total"], + ) + builder._start_national_gate_shadow(args, release_id="microcosm-us-test") + try: + shadow = current_gate_shadow(_EXPORT_CHECK_ENTRY) + assert shadow is not None + yield shadow + finally: + builder._finish_national_gate_shadow(stopped_at="test teardown") - monkeypatch.setattr(builder, "load_us_frame", load_us_frame) - monkeypatch.setattr(builder, "_export_input_mass_gate", gate) - return loaded, gate_calls + +def _reference_h5(tmp_path) -> Path: + path = tmp_path / "reference_populace_us_2024.h5" + path.write_bytes(b"reference bytes") + return path def test_the_export_input_mass_check_frees_its_reference_when_it_returns( builder, monkeypatch, tmp_path ) -> None: """The check loads the reference itself and holds it only while it runs, - whether it returns, raises, or records its error under earlier failures.""" - export_frame, base_frame = _LargeObject(), _LargeObject() - verdict = builder.GateResult( - name=_EXPORT_CHECK_RESULT_NAME, passed=True, details={"checked": True} - ) - loaded, gate_calls = _fake_reference_check( - builder, monkeypatch, export_frame, base_frame, verdict + whether it returns, raises, or records its error under earlier failures. + It keeps neither the export frame nor base_frame.""" + frames = {"export": _LargeObject(), "base": _LargeObject()} + stand_in = _ReferenceCheckStandIn( + builder, monkeypatch, frames["export"], frames["base"] ) - reference_h5 = tmp_path / "reference_populace_us_2024.h5" - reference_h5.write_bytes(b"reference bytes") + reference_h5 = _reference_h5(tmp_path) gate_options = { **_CHECK_OPTIONS, "reviewed_exclusions": builder.US_EXPORT_INPUT_MASS_REVIEWED_EXCLUSIONS, } - def check(reference_h5, *, failures, **overrides): + def check(reference_h5, *, failures): record: dict[str, object] = {"sha256": None} returned = builder._record_export_input_mass_gate( - export_frame, - base_frame, + frames["export"], + frames["base"], reference_h5=reference_h5, reference_record=record, terminal_gate_failures=failures, - **{**_CHECK_OPTIONS, **overrides}, + **_CHECK_OPTIONS, ) return returned, record returned, record = check(reference_h5, failures=[]) - assert returned is verdict + assert returned is stand_in.verdict assert record["sha256"] == builder._sha256(reference_h5) - ((loaded_path, reference),) = loaded + ((loaded_path, reference),) = stand_in.loaded assert loaded_path == reference_h5 - assert gate_calls[0] == {"reference": "loaded", **gate_options} + assert stand_in.gate_calls[0] == {"reference": "loaded", **gate_options} gc.collect() assert reference() is None # A check that raises on an otherwise-clean run frees its reference once # the error is handled. + stand_in.failing = "check" with pytest.raises(RuntimeError, match="the gate failed") as raised: - check(reference_h5, failures=[], relative_tolerance=-1.0) + check(reference_h5, failures=[]) # The traceback holds the check's frame, and so the reference, until the # error is released. del raised gc.collect() - assert len(loaded) == 2 and gate_calls[1]["reference"] == "loaded" - assert loaded[1][1]() is None + assert len(stand_in.loaded) == 2 + assert stand_in.gate_calls[1]["reference"] == "loaded" + assert stand_in.loaded[1][1]() is None # Under earlier failures the error becomes one more failure line, and the # reference is freed when the check returns. failures = ["an earlier gate failed"] - returned, _ = check(reference_h5, failures=failures, relative_tolerance=-1.0) + returned, _ = check(reference_h5, failures=failures) assert returned is None assert failures == [ "an earlier gate failed", @@ -493,70 +597,104 @@ def check(reference_h5, *, failures, **overrides): "RuntimeError: the gate failed", ] gc.collect() - assert len(loaded) == 3 and loaded[2][1]() is None + assert len(stand_in.loaded) == 3 and stand_in.loaded[2][1]() is None # Without a reference H5 the check compares against base_frame and loads # nothing. + stand_in.failing = None returned, record = check(None, failures=[]) - assert returned is verdict and record["sha256"] is None - assert len(loaded) == 3 - assert gate_calls[-1]["reference"] is None + assert returned is stand_in.verdict and record["sha256"] is None + assert len(stand_in.loaded) == 3 + assert stand_in.gate_calls[-1]["reference"] is None + + frames.clear() + assert stand_in.frames_freed() def test_the_shadow_sees_the_export_reference_and_does_not_keep_it( builder, monkeypatch, tmp_path ) -> None: """Every real run arms the gate battery's shadow, which evaluates the same - check on an evidence context holding the loaded reference. The reference - is still freed when the check returns.""" - arm_us_tool_gate_shadows(monkeypatch) - export_frame, base_frame = _LargeObject(), _LargeObject() - verdict = builder.GateResult( - name=_EXPORT_CHECK_RESULT_NAME, passed=True, details={"checked": True} - ) - loaded, gate_calls = _fake_reference_check( - builder, monkeypatch, export_frame, base_frame, verdict - ) - reference_h5 = tmp_path / "reference_populace_us_2024.h5" - reference_h5.write_bytes(b"reference bytes") - args = SimpleNamespace( - out=tmp_path / "out", - dry_run_gates_report=None, - allow_input_mass_drift=False, - allow_ecps_parity_gaps=False, - allow_input_coverage_gaps=False, - allow_esi_premium_gaps=False, - allow_unpinned_feed=False, - allow_qrf_tail_concentration=False, - evidence_release=False, - input_mass_relative_tolerance=_CHECK_OPTIONS["relative_tolerance"], - input_mass_minimum_reference_total=_CHECK_OPTIONS["minimum_reference_total"], + check on an evidence context holding the loaded reference. The reference, + the export frame and base_frame are still freed when the check returns.""" + frames = {"export": _LargeObject(), "base": _LargeObject()} + stand_in = _ReferenceCheckStandIn( + builder, monkeypatch, frames["export"], frames["base"] ) - builder._start_national_gate_shadow(args, release_id="microcosm-us-test") - try: - shadow = current_gate_shadow("us_national_export_input_mass") - assert shadow is not None + with _armed_national_shadow(builder, monkeypatch, tmp_path) as shadow: returned = builder._record_export_input_mass_gate( - export_frame, - base_frame, - reference_h5=reference_h5, + frames["export"], + frames["base"], + reference_h5=_reference_h5(tmp_path), reference_record={"sha256": None}, terminal_gate_failures=[], **_CHECK_OPTIONS, ) - outcome = shadow.outcome("us_national_export_input_mass") + outcome = shadow.outcome(_EXPORT_CHECK_ENTRY) differences = shadow.differences() - finally: - builder._finish_national_gate_shadow(stopped_at="test teardown") - assert returned is verdict + assert returned is stand_in.verdict # Today's check and the shadow's evaluation each got the loaded frame. - assert [call["reference"] for call in gate_calls] == ["loaded", "loaded"] + assert [call["reference"] for call in stand_in.gate_calls] == ["loaded", "loaded"] assert outcome is not None and outcome.status is GateStatus.PASSED assert differences == () - ((_, reference),) = loaded + ((_, reference),) = stand_in.loaded gc.collect() assert reference() is None + frames.clear() + assert stand_in.frames_freed() + + +@pytest.mark.parametrize( + ("failing", "error", "status", "evaluations"), + [ + # The check never ran: the shadow records it as not run. + ("load", "OSError: the reference did not open", GateStatus.EVIDENCE_ABSENT, 0), + # Today's check and the shadow's evaluation both hit the error, which + # the shadow records once, as the same verdict. + ("check", "RuntimeError: the gate failed", GateStatus.FAILED, 2), + ], +) +def test_the_shadow_records_an_export_check_error_under_earlier_failures( + builder, monkeypatch, tmp_path, failing, error, status, evaluations +) -> None: + """Under earlier failures, a reference that does not load or a check that + raises becomes one failure line, after the reference's sha256 is + recorded, and the shadow records it with no verdict difference.""" + frames = {"export": _LargeObject(), "base": _LargeObject()} + stand_in = _ReferenceCheckStandIn( + builder, monkeypatch, frames["export"], frames["base"] + ) + stand_in.failing = failing + reference_h5 = _reference_h5(tmp_path) + record: dict[str, object] = {"sha256": None} + failures = ["an earlier gate failed"] + with _armed_national_shadow(builder, monkeypatch, tmp_path) as shadow: + returned = builder._record_export_input_mass_gate( + frames["export"], + frames["base"], + reference_h5=reference_h5, + reference_record=record, + terminal_gate_failures=failures, + **_CHECK_OPTIONS, + ) + outcome = shadow.outcome(_EXPORT_CHECK_ENTRY) + differences = shadow.differences() + + assert returned is None + assert record["sha256"] == builder._sha256(reference_h5) + assert failures == [ + "an earlier gate failed", + f"Input mass parity failed: evaluation error under earlier gate failures: " + f"{error}", + ] + assert outcome is not None and outcome.status is status + assert differences == () + assert len(stand_in.gate_calls) == evaluations + gc.collect() + assert all(reference() is None for _, reference in stand_in.loaded) + frames.clear() + assert stand_in.frames_freed() def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> None: @@ -624,37 +762,28 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( functions = { node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) } - frontier = [ + receivers = { call.func.id for call in ast.walk(main) if isinstance(call, ast.Call) and call.lineno > dropped_line and isinstance(call.func, ast.Name) and call.func.id in functions + # Passed the result itself or any part of it, such as result.problem. and any( - isinstance(argument, ast.Name) - and argument.id in {"result", "ladder_outcome"} + isinstance(name, ast.Name) and name.id in {"result", "ladder_outcome"} for argument in _arguments(call) + for name in ast.walk(argument) ) - ] + } assert { "_release_gate_failures", "_write_npz", "_write_release_calibration_diagnostics", - } <= set(frontier) - reached: set[str] = set() - while frontier: - name = frontier.pop() - if name in reached: - continue - reached.add(name) - frontier.extend( - call.func.id - for call in ast.walk(functions[name]) - if isinstance(call, ast.Call) - and isinstance(call.func, ast.Name) - and call.func.id in functions - ) + "_us_build_record", + "_assert_export_matches_calibration", + } <= receivers + reached = _tool_functions_reached(functions, receivers) later_nodes = [ node for node in ast.walk(main) if getattr(node, "lineno", 0) > dropped_line ] @@ -674,8 +803,10 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non check = statements.index("assert_release_input_coverage_manifest_current()") assert statements[check + 1] == "clear_installed_list_parameter_baseline_cache()" assert statements.count("clear_installed_list_parameter_baseline_cache()") == 1 - # Nothing in _main fills the cache again; the reform-coverage smoke, after - # the H5 write, is the next reader. + # Nothing in the build fills the cache again: neither _main's later + # statements nor the tool functions they call, followed through the + # tool's own calls. The reform-coverage smoke, the next reader, runs at + # certification, in its own process. cleared_line = main.body[check + 1].lineno fillers = { "assert_release_input_coverage_manifest_current", @@ -683,13 +814,32 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non "installed_list_parameter_baseline", "_installed_parameter_stages", } + tool = ast.parse(Path(builder.__file__).read_text()) + functions = { + node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) + } + later_calls = [ + call + for call in ast.walk(main) + if isinstance(call, ast.Call) and call.lineno > cleared_line + ] + reached = _tool_functions_reached( + functions, + { + call.func.id + for call in later_calls + if isinstance(call.func, ast.Name) and call.func.id in functions + }, + ) + for name in sorted(reached - {"_main"}): + later_calls.extend( + call for call in ast.walk(functions[name]) if isinstance(call, ast.Call) + ) # Called by name or through a module attribute. assert [ f"{call.lineno}: {ast.unparse(call)}" - for call in ast.walk(main) - if isinstance(call, ast.Call) - and _called_name(call) in fillers - and call.lineno > cleared_line + for call in later_calls + if _called_name(call) in fillers ] == [] diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py index df1acbcaf4..f2bd74ce31 100644 --- a/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_diagnostics.py @@ -1296,7 +1296,9 @@ def test_dropping_the_constraint_matrix_keeps_its_shape_and_nonzero_count( del result gc.collect() - assert [reference() for reference in references] == [None] * len(references) + assert [ + index for index, reference in enumerate(references) if reference() is not None + ] == [] assert isinstance(dropped.problem.matrix, DroppedConstraintMatrix) assert dropped.problem.matrix.shape == shape assert dropped.problem.matrix.nnz == nonzero_count @@ -1331,7 +1333,9 @@ def test_dropping_an_l0_refit_result_drops_the_selection_matrix_too( del result gc.collect() - assert [reference() for reference in references] == [None] * len(references) + assert [ + index for index, reference in enumerate(references) if reference() is not None + ] == [] assert dropped.selection.problem.matrix.shape == selection_shape assert dropped.selection.problem.matrix.nnz == selection_nonzero_count assert dropped.refit.problem.matrix.shape == refit_shape From 83e7345630fc0dbae73966984927d53564a2fa2c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:11:49 +0400 Subject: [PATCH 08/19] Say where the coverage cache is read again after the clear 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 --- tools/build_us_fiscal_refresh_release.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 3fdb0c5a4c..a88ee2d3ee 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -15611,9 +15611,10 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # expensive calibration so a stale contract cannot silently narrow coverage. assert_release_input_coverage_manifest_current() # The check resolves the probes' list edits on a reformed PolicyEngine-US - # system that the module caches for the process. Nothing reads it again - # before the reform-coverage smoke, which builds it again, so it is not - # kept through the source stages and the calibration. + # system that the module caches for the process. Nothing in the build reads + # it again (the reform-coverage smoke, its other reader, runs at + # certification, in its own process), so it is not kept through the source + # stages and the calibration. clear_installed_list_parameter_baseline_cache() # Preflight (microcosm#377): no column may be required-to-signal by one # register (seeded/count-calibrated take-up, health nonconstant, coverage From c249e9d7aaad5c5e96e530479fa4778ca5047b92 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:31:46 +0400 Subject: [PATCH 09/19] Close the gaps the fourth review found in the freeing tests - 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 --- .../test_us_release_frees_after_last_use.py | 189 +++++++++++++----- 1 file changed, 137 insertions(+), 52 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 8985caf381..e9b3b96483 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -116,6 +116,14 @@ def _holds_a_freed_object(node: ast.AST) -> bool: return _holds_a_freed_object(node.body) or _holds_a_freed_object(node.orelse) if isinstance(node, ast.BoolOp): return any(_holds_a_freed_object(value) for value in node.values) + if isinstance(node, ast.Lambda): + # A default argument lives as long as the lambda does, so the lambda + # counts as holding it wherever it is kept; one passed straight to a + # call is gone when the call returns. + return any( + default is not None and _holds_a_freed_object(default) + for default in (*node.args.defaults, *node.args.kw_defaults) + ) if isinstance(node, ast.Call): name = _called_name(node) if name in _CONTAINER_CALLS: @@ -167,14 +175,15 @@ def _alias_sites(function: ast.FunctionDef) -> list[tuple[int, str]]: ): sites.append((node.lineno, ast.unparse(node))) elif ( - isinstance(node, (ast.Lambda, ast.FunctionDef, ast.AsyncFunctionDef)) + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node is not function and any( default is not None and _holds_a_freed_object(default) for default in (*node.args.defaults, *node.args.kw_defaults) ) ): - # A default argument lives as long as the function object does. + # A nested function is bound to a local, which keeps its default + # arguments as long as the function object lives. sites.append((node.lineno, ast.unparse(node.args))) return sorted(sites) @@ -236,7 +245,11 @@ def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: def _tool_functions_reached( functions: dict[str, ast.FunctionDef], names: set[str] ) -> set[str]: - """``names`` and every tool function they call by name, transitively.""" + """``names`` and every tool function they name, transitively. + + A function counts whether it is called or used as a value, such as one put + in a mapping of consumers and called through it later. + """ reached: set[str] = set() frontier = list(names) while frontier: @@ -244,16 +257,22 @@ def _tool_functions_reached( if name in reached: continue reached.add(name) - frontier.extend( - call.func.id - for call in ast.walk(functions[name]) - if isinstance(call, ast.Call) - and isinstance(call.func, ast.Name) - and call.func.id in functions - ) + frontier.extend(_tool_functions_named(functions[name], functions)) return reached +def _tool_functions_named( + tree: ast.AST, functions: dict[str, ast.FunctionDef] +) -> set[str]: + return { + node.id + for node in ast.walk(tree) + if isinstance(node, ast.Name) + and isinstance(node.ctx, ast.Load) + and node.id in functions + } + + def _calls_named(tree: ast.AST, name: str) -> list[ast.Call]: return [ node @@ -294,9 +313,27 @@ def test_the_alias_check_sees_each_way_of_keeping_an_object() -> None: "kept = dataclasses.replace(outcome, result=result)", "setattr(holder, 'frame', base_frame)", "callbacks.append(lambda frame=base_frame: frame)", + "kept = lambda frame=base_frame: frame", "def later(*, engine=release_engine):\n pass", + "kept = copy.deepcopy(result)", + "kept = dict(frame=base_frame)", + "kept = list((base_frame,))", + "kept = set([release_engine])", + "kept = tuple([base_frame])", + "kept = frozenset({release_engine})", + "kept: object = base_frame", + "if (kept := base_frame) is not None:\n pass", + ) + harmless = ( + "total = base_frame.n('household')", + "loss = result.final_loss", + # A lambda passed straight to a call is freed when the call returns. + "shadow_gate('x', lambda frame=base_frame: gate(frame), context)", + "kept = copy.copy(settings)", + "setattr(holder, 'frame', other_frame)", + "kept = dataclasses.replace(options, seed=seed)", + "frames.append(base_frame.n('household'))", ) - harmless = ("total = base_frame.n('household')", "loss = result.final_loss") for source, expected_sites in ( *((source, 1) for source in keeping), *((source, 0) for source in harmless), @@ -645,22 +682,28 @@ def test_the_shadow_sees_the_export_reference_and_does_not_keep_it( assert stand_in.frames_freed() +#: Each step the stand-in can make fail: the error it raises, and the line +#: the check appends for it under earlier failures. +_EXPORT_CHECK_ERRORS = { + "load": (OSError, "OSError: the reference did not open"), + "check": (RuntimeError, "RuntimeError: the gate failed"), +} + + @pytest.mark.parametrize( - ("failing", "error", "status", "evaluations"), - [ - # The check never ran: the shadow records it as not run. - ("load", "OSError: the reference did not open", GateStatus.EVIDENCE_ABSENT, 0), - # Today's check and the shadow's evaluation both hit the error, which - # the shadow records once, as the same verdict. - ("check", "RuntimeError: the gate failed", GateStatus.FAILED, 2), - ], + "earlier_failures", [True, False], ids=["earlier-failures", "clean-run"] ) -def test_the_shadow_records_an_export_check_error_under_earlier_failures( - builder, monkeypatch, tmp_path, failing, error, status, evaluations +@pytest.mark.parametrize("failing", ["load", "check"]) +def test_the_shadow_records_an_export_check_error( + builder, monkeypatch, tmp_path, failing, earlier_failures ) -> None: - """Under earlier failures, a reference that does not load or a check that - raises becomes one failure line, after the reference's sha256 is - recorded, and the shadow records it with no verdict difference.""" + """A reference that does not load, or a check that raises, comes after + the reference's sha256 is recorded. Under earlier failures it becomes one + failure line; on an otherwise-clean run it propagates. The shadow records + a check that raised once, as the same verdict as today's, and a reference + that did not load as a check that did not run only when the build goes + on; a build that stops leaves the entry unreached.""" + error_type, error = _EXPORT_CHECK_ERRORS[failing] frames = {"export": _LargeObject(), "base": _LargeObject()} stand_in = _ReferenceCheckStandIn( builder, monkeypatch, frames["export"], frames["base"] @@ -668,9 +711,10 @@ def test_the_shadow_records_an_export_check_error_under_earlier_failures( stand_in.failing = failing reference_h5 = _reference_h5(tmp_path) record: dict[str, object] = {"sha256": None} - failures = ["an earlier gate failed"] - with _armed_national_shadow(builder, monkeypatch, tmp_path) as shadow: - returned = builder._record_export_input_mass_gate( + failures = ["an earlier gate failed"] if earlier_failures else [] + + def check(): + return builder._record_export_input_mass_gate( frames["export"], frames["base"], reference_h5=reference_h5, @@ -678,19 +722,36 @@ def test_the_shadow_records_an_export_check_error_under_earlier_failures( terminal_gate_failures=failures, **_CHECK_OPTIONS, ) + + with _armed_national_shadow(builder, monkeypatch, tmp_path) as shadow: + if earlier_failures: + assert check() is None + else: + with pytest.raises(error_type) as raised: + check() + # The traceback holds the check's frame until it is released. + del raised outcome = shadow.outcome(_EXPORT_CHECK_ENTRY) differences = shadow.differences() - assert returned is None assert record["sha256"] == builder._sha256(reference_h5) - assert failures == [ - "an earlier gate failed", - f"Input mass parity failed: evaluation error under earlier gate failures: " - f"{error}", - ] - assert outcome is not None and outcome.status is status + assert failures == ( + [ + "an earlier gate failed", + "Input mass parity failed: evaluation error under earlier gate " + f"failures: {error}", + ] + if earlier_failures + else [] + ) + if failing == "check": + expected_status = GateStatus.FAILED + else: + expected_status = GateStatus.EVIDENCE_ABSENT if earlier_failures else None + assert (outcome.status if outcome is not None else None) is expected_status assert differences == () - assert len(stand_in.gate_calls) == evaluations + # Today's check and the shadow's evaluation each ran when the load did. + assert len(stand_in.gate_calls) == (2 if failing == "check" else 0) gc.collect() assert all(reference() is None for _, reference in stand_in.loaded) frames.clear() @@ -792,7 +853,14 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( assert [ f"{node.lineno}: {ast.unparse(node)}" for node in later_nodes - if isinstance(node, ast.Attribute) and node.attr in {"matrix", "estimates"} + if (isinstance(node, ast.Attribute) and node.attr in {"matrix", "estimates"}) + or ( + isinstance(node, ast.Call) + and _called_name(node) == "getattr" + and len(node.args) >= 2 + and isinstance(node.args[1], ast.Constant) + and node.args[1].value in {"matrix", "estimates"} + ) ] == [] @@ -813,34 +881,51 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non "resolve_probe_parameter_changes", "installed_list_parameter_baseline", "_installed_parameter_stages", + # The package functions that reach installed_list_parameter_baseline. + "us_reform_coverage_smoke_gate", + "_build_reform", } tool = ast.parse(Path(builder.__file__).read_text()) functions = { node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) } - later_calls = [ - call - for call in ast.walk(main) - if isinstance(call, ast.Call) and call.lineno > cleared_line - ] + later_statements = [node for node in main.body if node.lineno > cleared_line] reached = _tool_functions_reached( functions, - { - call.func.id - for call in later_calls - if isinstance(call.func, ast.Name) and call.func.id in functions - }, + set().union( + *( + _tool_functions_named(statement, functions) + for statement in later_statements + ) + ), ) + calls = [ + ("_main", call) + for statement in later_statements + for call in ast.walk(statement) + if isinstance(call, ast.Call) + ] for name in sorted(reached - {"_main"}): - later_calls.extend( - call for call in ast.walk(functions[name]) if isinstance(call, ast.Call) + calls.extend( + (name, call) + for call in ast.walk(functions[name]) + if isinstance(call, ast.Call) ) - # Called by name or through a module attribute. + # Called by name or through a module attribute. The one call expected is + # the reform-coverage smoke as the post-export scoring plan runs it before + # export, recording requests only, which builds no reform + # (test_us_post_export_scoring.py:: + # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). assert [ - f"{call.lineno}: {ast.unparse(call)}" - for call in later_calls + (function, ast.unparse(call)) + for function, call in calls if _called_name(call) in fillers - ] == [] + ] == [ + ( + "_reform_coverage_smoke_consumer", + "us_reform_coverage_smoke_gate(simulate=simulate, period=PERIOD)", + ) + ] def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( From fcc3015631b718f028d8f9bcfff54244041fb611 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:54:17 +0400 Subject: [PATCH 10/19] Follow tool classes and pin the smoke's only path in the freeing tests - 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 --- .../test_us_release_frees_after_last_use.py | 157 +++++++++++------- 1 file changed, 94 insertions(+), 63 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index e9b3b96483..65a704c393 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -118,8 +118,9 @@ def _holds_a_freed_object(node: ast.AST) -> bool: return any(_holds_a_freed_object(value) for value in node.values) if isinstance(node, ast.Lambda): # A default argument lives as long as the lambda does, so the lambda - # counts as holding it wherever it is kept; one passed straight to a - # call is gone when the call returns. + # counts as holding it wherever it is kept. One passed straight to a + # call that keeps nothing of it, as shadow_gate keeps only the + # verdict, is freed when the call returns. return any( default is not None and _holds_a_freed_object(default) for default in (*node.args.defaults, *node.args.kw_defaults) @@ -242,13 +243,27 @@ def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: return function.body.index(released) -def _tool_functions_reached( - functions: dict[str, ast.FunctionDef], names: set[str] +#: A module-level function or class of the release tool, by name. +_ToolDefinitions = dict[str, ast.FunctionDef | ast.ClassDef] + + +def _tool_definitions(builder) -> _ToolDefinitions: + tool = ast.parse(Path(builder.__file__).read_text()) + return { + node.name: node + for node in tool.body + if isinstance(node, (ast.FunctionDef, ast.ClassDef)) + } + + +def _tool_definitions_reached( + definitions: _ToolDefinitions, names: set[str] ) -> set[str]: - """``names`` and every tool function they name, transitively. + """``names`` and every tool function or class they name, transitively. - A function counts whether it is called or used as a value, such as one put - in a mapping of consumers and called through it later. + A definition counts whether it is called or used as a value, such as a + function put in a mapping of consumers and called through it later. A + class brings in all its methods. """ reached: set[str] = set() frontier = list(names) @@ -257,19 +272,17 @@ def _tool_functions_reached( if name in reached: continue reached.add(name) - frontier.extend(_tool_functions_named(functions[name], functions)) + frontier.extend(_tool_definitions_named(definitions[name], definitions)) return reached -def _tool_functions_named( - tree: ast.AST, functions: dict[str, ast.FunctionDef] -) -> set[str]: +def _tool_definitions_named(tree: ast.AST, definitions: _ToolDefinitions) -> set[str]: return { node.id for node in ast.walk(tree) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) - and node.id in functions + and node.id in definitions } @@ -323,11 +336,21 @@ def test_the_alias_check_sees_each_way_of_keeping_an_object() -> None: "kept = frozenset({release_engine})", "kept: object = base_frame", "if (kept := base_frame) is not None:\n pass", + "kept = {'frame': base_frame}", + "frames.add(base_frame)", + "frames.extend([base_frame])", + "frames.insert(0, base_frame)", + "cache.setdefault('frame', base_frame)", + "cache.update(frame=base_frame)", + "kept = lambda *, frame=base_frame: frame", + "kept = ladder_outcome.result.refit", + "kept = result.selection", ) harmless = ( "total = base_frame.n('household')", "loss = result.final_loss", - # A lambda passed straight to a call is freed when the call returns. + # shadow_gate keeps only the verdict, so its lambda is freed when it + # returns. "shadow_gate('x', lambda frame=base_frame: gate(frame), context)", "kept = copy.copy(settings)", "setattr(holder, 'frame', other_frame)", @@ -702,7 +725,7 @@ def test_the_shadow_records_an_export_check_error( failure line; on an otherwise-clean run it propagates. The shadow records a check that raised once, as the same verdict as today's, and a reference that did not load as a check that did not run only when the build goes - on; a build that stops leaves the entry unreached.""" + on: a build that stops there leaves the entry unreached.""" error_type, error = _EXPORT_CHECK_ERRORS[failing] frames = {"export": _LargeObject(), "base": _LargeObject()} stand_in = _ReferenceCheckStandIn( @@ -814,22 +837,20 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( assert max(calibration_calls) < main.body[matrix_dropped].lineno # After the drop, no tool code that can reach the calibration result reads # a matrix's entries: neither _main's later statements nor any tool - # function they pass result or ladder_outcome to, followed through the - # tool's own calls, reads ``.matrix`` or calls ``.estimates``. The - # calibrate package's readers run on a dropped matrix in this module's - # output tests and in the calibrate package's tests. + # function or class they name, followed through the definitions those + # name, reads ``.matrix`` or calls ``.estimates``. The calibrate package's + # readers run on a dropped matrix in this module's output tests and in the + # calibrate package's tests. dropped_line = main.body[matrix_dropped].lineno - tool = ast.parse(Path(builder.__file__).read_text()) - functions = { - node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) - } + definitions = _tool_definitions(builder) + later_statements = main.body[matrix_dropped + 1 :] receivers = { call.func.id for call in ast.walk(main) if isinstance(call, ast.Call) and call.lineno > dropped_line and isinstance(call.func, ast.Name) - and call.func.id in functions + and call.func.id in definitions # Passed the result itself or any part of it, such as result.problem. and any( isinstance(name, ast.Name) and name.id in {"result", "ladder_outcome"} @@ -844,12 +865,21 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( "_us_build_record", "_assert_export_matches_calibration", } <= receivers - reached = _tool_functions_reached(functions, receivers) + reached = _tool_definitions_reached( + definitions, + set().union( + *( + _tool_definitions_named(statement, definitions) + for statement in later_statements + ) + ), + ) + assert receivers <= reached later_nodes = [ - node for node in ast.walk(main) if getattr(node, "lineno", 0) > dropped_line + node for statement in later_statements for node in ast.walk(statement) ] for name in sorted(reached - {"_main"}): - later_nodes.extend(ast.walk(functions[name])) + later_nodes.extend(ast.walk(definitions[name])) assert [ f"{node.lineno}: {ast.unparse(node)}" for node in later_nodes @@ -872,9 +902,10 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non assert statements[check + 1] == "clear_installed_list_parameter_baseline_cache()" assert statements.count("clear_installed_list_parameter_baseline_cache()") == 1 # Nothing in the build fills the cache again: neither _main's later - # statements nor the tool functions they call, followed through the - # tool's own calls. The reform-coverage smoke, the next reader, runs at - # certification, in its own process. + # statements nor any tool function or class they name, followed through + # the definitions those name. The reform-coverage smoke, the cache's next + # real reader, runs at certification, in its own process; the build + # reaches it only through the scoring plan's request-recording run. cleared_line = main.body[check + 1].lineno fillers = { "assert_release_input_coverage_manifest_current", @@ -885,47 +916,47 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non "us_reform_coverage_smoke_gate", "_build_reform", } - tool = ast.parse(Path(builder.__file__).read_text()) - functions = { - node.name: node for node in tool.body if isinstance(node, ast.FunctionDef) - } + definitions = _tool_definitions(builder) later_statements = [node for node in main.body if node.lineno > cleared_line] - reached = _tool_functions_reached( - functions, + reached = _tool_definitions_reached( + definitions, set().union( *( - _tool_functions_named(statement, functions) + _tool_definitions_named(statement, definitions) for statement in later_statements ) ), ) - calls = [ - ("_main", call) - for statement in later_statements - for call in ast.walk(statement) - if isinstance(call, ast.Call) - ] - for name in sorted(reached - {"_main"}): - calls.extend( - (name, call) - for call in ast.walk(functions[name]) - if isinstance(call, ast.Call) - ) - # Called by name or through a module attribute. The one call expected is - # the reform-coverage smoke as the post-export scoring plan runs it before - # export, recording requests only, which builds no reform - # (test_us_post_export_scoring.py:: - # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). - assert [ - (function, ast.unparse(call)) - for function, call in calls - if _called_name(call) in fillers - ] == [ - ( - "_reform_coverage_smoke_consumer", - "us_reform_coverage_smoke_gate(simulate=simulate, period=PERIOD)", - ) - ] + trees: dict[str, list[ast.AST]] = {"_main": later_statements} + for name in reached - {"_main"}: + trees[name] = [definitions[name]] + + def named_by(target: str) -> set[str]: + """The reached code that names ``target``.""" + return { + name + for name, roots in trees.items() + if any( + target in _tool_definitions_named(root, definitions) for root in roots + ) + } + + # Called by name or through a module attribute. + assert sorted( + (name, _called_name(node)) + for name, roots in trees.items() + for root in roots + for node in ast.walk(root) + if isinstance(node, ast.Call) and _called_name(node) in fillers + ) == [("_reform_coverage_smoke_consumer", "us_reform_coverage_smoke_gate")] + # That consumer is reached only as one of the scoring plan's consumers, + # which the plan runs before export recording requests only, building no + # reform (test_us_post_export_scoring.py:: + # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). The + # function that scores a consumer for real runs at certification. + assert named_by("_reform_coverage_smoke_consumer") == {"_post_export_consumers"} + assert named_by("_post_export_consumers") == {"_record_post_export_scoring_plan"} + assert "_score_post_export_consumer" not in reached def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( From c3fb2d8c99eef43ceeb47e2c0d377d48a184e370 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:14:13 +0400 Subject: [PATCH 11/19] Let the matrix scan accept size reads and report file lines - 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 --- .../test_us_release_frees_after_last_use.py | 112 ++++++++++++------ 1 file changed, 76 insertions(+), 36 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 65a704c393..f3d9399de0 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -243,27 +243,35 @@ def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: return function.body.index(released) -#: A module-level function or class of the release tool, by name. -_ToolDefinitions = dict[str, ast.FunctionDef | ast.ClassDef] +#: A module-level function, class or variable of the release tool, by name, +#: with the statement that defines it. +_ToolDefinitions = dict[str, ast.stmt] def _tool_definitions(builder) -> _ToolDefinitions: + """The release tool's module-level definitions, with file line numbers.""" tool = ast.parse(Path(builder.__file__).read_text()) - return { - node.name: node - for node in tool.body - if isinstance(node, (ast.FunctionDef, ast.ClassDef)) - } + definitions: _ToolDefinitions = {} + for node in tool.body: + if isinstance(node, (ast.FunctionDef, ast.ClassDef)): + definitions[node.name] = node + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + # A variable such as a table of functions brings in what it names. + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + for target in targets: + if isinstance(target, ast.Name): + definitions[target.id] = node + return definitions def _tool_definitions_reached( definitions: _ToolDefinitions, names: set[str] ) -> set[str]: - """``names`` and every tool function or class they name, transitively. + """``names`` and every tool definition they name, transitively. A definition counts whether it is called or used as a value, such as a function put in a mapping of consumers and called through it later. A - class brings in all its methods. + class brings in all its methods, and a variable what its value names. """ reached: set[str] = set() frontier = list(names) @@ -841,14 +849,18 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( # name, reads ``.matrix`` or calls ``.estimates``. The calibrate package's # readers run on a dropped matrix in this module's output tests and in the # calibrate package's tests. - dropped_line = main.body[matrix_dropped].lineno definitions = _tool_definitions(builder) - later_statements = main.body[matrix_dropped + 1 :] + # The same statements as main's, with file line numbers. + assert ( + ast.unparse(definitions["_main"].body[matrix_dropped]) + == (statements[matrix_dropped]) + ) + later_statements = definitions["_main"].body[matrix_dropped + 1 :] receivers = { call.func.id - for call in ast.walk(main) + for statement in later_statements + for call in ast.walk(statement) if isinstance(call, ast.Call) - and call.lineno > dropped_line and isinstance(call.func, ast.Name) and call.func.id in definitions # Passed the result itself or any part of it, such as result.problem. @@ -875,23 +887,42 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( ), ) assert receivers <= reached + trees: dict[str, list[ast.AST]] = {"_main": later_statements} + for name in reached - {"_main"}: + trees[name] = [definitions[name]] later_nodes = [ - node for statement in later_statements for node in ast.walk(statement) + (name, node) + for name, roots in trees.items() + for root in roots + for node in ast.walk(root) ] - for name in sorted(reached - {"_main"}): - later_nodes.extend(ast.walk(definitions[name])) - assert [ - f"{node.lineno}: {ast.unparse(node)}" - for node in later_nodes - if (isinstance(node, ast.Attribute) and node.attr in {"matrix", "estimates"}) - or ( - isinstance(node, ast.Call) - and _called_name(node) == "getattr" - and len(node.args) >= 2 - and isinstance(node.args[1], ast.Constant) - and node.args[1].value in {"matrix", "estimates"} + # The placeholder keeps the matrix's shape and nonzero count. + size_reads = { + id(node.value) + for _, node in later_nodes + if isinstance(node, ast.Attribute) and node.attr in {"shape", "nnz"} + } + assert ( + sorted( + f"{name}, line {node.lineno}: {ast.unparse(node)}" + for name, node in later_nodes + if ( + isinstance(node, ast.Attribute) + and ( + node.attr == "estimates" + or (node.attr == "matrix" and id(node) not in size_reads) + ) + ) + or ( + isinstance(node, ast.Call) + and _called_name(node) == "getattr" + and len(node.args) >= 2 + and isinstance(node.args[1], ast.Constant) + and node.args[1].value in {"matrix", "estimates"} + ) ) - ] == [] + == [] + ) def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> None: @@ -906,7 +937,6 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non # the definitions those name. The reform-coverage smoke, the cache's next # real reader, runs at certification, in its own process; the build # reaches it only through the scoring plan's request-recording run. - cleared_line = main.body[check + 1].lineno fillers = { "assert_release_input_coverage_manifest_current", "resolve_probe_parameter_changes", @@ -917,7 +947,9 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non "_build_reform", } definitions = _tool_definitions(builder) - later_statements = [node for node in main.body if node.lineno > cleared_line] + # The same statements as main's, with file line numbers. + assert ast.unparse(definitions["_main"].body[check + 1]) == statements[check + 1] + later_statements = definitions["_main"].body[check + 2 :] reached = _tool_definitions_reached( definitions, set().union( @@ -941,22 +973,30 @@ def named_by(target: str) -> set[str]: ) } - # Called by name or through a module attribute. + # Named by itself or through a module attribute, called or passed on (as + # to functools.partial or a shadow-gate lambda). assert sorted( - (name, _called_name(node)) + (name, node.id if isinstance(node, ast.Name) else node.attr) for name, roots in trees.items() for root in roots for node in ast.walk(root) - if isinstance(node, ast.Call) and _called_name(node) in fillers + if (isinstance(node, ast.Name) and node.id in fillers) + or (isinstance(node, ast.Attribute) and node.attr in fillers) ) == [("_reform_coverage_smoke_consumer", "us_reform_coverage_smoke_gate")] # That consumer is reached only as one of the scoring plan's consumers, # which the plan runs before export recording requests only, building no # reform (test_us_post_export_scoring.py:: - # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). The - # function that scores a consumer for real runs at certification. + # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). + # Scoring a consumer for real needs the scorer, which only certification + # opens; a build function that names the consumers for another reason, + # such as listing their names, passes as long as it opens no scorer. assert named_by("_reform_coverage_smoke_consumer") == {"_post_export_consumers"} - assert named_by("_post_export_consumers") == {"_record_post_export_scoring_plan"} - assert "_score_post_export_consumer" not in reached + assert { + "_score_post_export_consumer", + "_open_post_export_scorer", + "_HouseholdBatchedPostExportScorer", + "_BatchedPostExportReform", + } & reached == set() def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( From f5cdedcdf42d416578f151052b4c93ff30d1d0eb Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:31:20 +0400 Subject: [PATCH 12/19] Keep every definition of a tool name and skip annotations in the scans - 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 --- .../test_us_release_frees_after_last_use.py | 65 ++++++++++++++----- 1 file changed, 47 insertions(+), 18 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index f3d9399de0..b99ae30787 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -243,9 +243,9 @@ def _single_top_level_release(function: ast.FunctionDef, name: str) -> int: return function.body.index(released) -#: A module-level function, class or variable of the release tool, by name, -#: with the statement that defines it. -_ToolDefinitions = dict[str, ast.stmt] +#: The release tool's module-level functions, classes and variables, by name, +#: each with every statement that defines or rebinds it, in source order. +_ToolDefinitions = dict[str, list[ast.stmt]] def _tool_definitions(builder) -> _ToolDefinitions: @@ -254,16 +254,24 @@ def _tool_definitions(builder) -> _ToolDefinitions: definitions: _ToolDefinitions = {} for node in tool.body: if isinstance(node, (ast.FunctionDef, ast.ClassDef)): - definitions[node.name] = node + definitions.setdefault(node.name, []).append(node) elif isinstance(node, (ast.Assign, ast.AnnAssign)): # A variable such as a table of functions brings in what it names. targets = node.targets if isinstance(node, ast.Assign) else [node.target] for target in targets: if isinstance(target, ast.Name): - definitions[target.id] = node + definitions.setdefault(target.id, []).append(node) return definitions +def _tool_main(definitions: _ToolDefinitions) -> ast.FunctionDef: + """``_main`` as the file defines it, with file line numbers.""" + (main,) = [ + node for node in definitions["_main"] if isinstance(node, ast.FunctionDef) + ] + return main + + def _tool_definitions_reached( definitions: _ToolDefinitions, names: set[str] ) -> set[str]: @@ -272,6 +280,8 @@ def _tool_definitions_reached( A definition counts whether it is called or used as a value, such as a function put in a mapping of consumers and called through it later. A class brings in all its methods, and a variable what its value names. + A name used only in a type annotation is not followed: an annotation + runs nothing. """ reached: set[str] = set() frontier = list(names) @@ -280,14 +290,28 @@ class brings in all its methods, and a variable what its value names. if name in reached: continue reached.add(name) - frontier.extend(_tool_definitions_named(definitions[name], definitions)) + for statement in definitions[name]: + frontier.extend(_tool_definitions_named(statement, definitions)) return reached +def _walk_without_annotations(tree: ast.AST): + """``ast.walk``, skipping argument, return and variable annotations.""" + pending = [tree] + while pending: + node = pending.pop() + yield node + for field, value in ast.iter_fields(node): + if field in {"annotation", "returns"}: + continue + children = value if isinstance(value, list) else [value] + pending.extend(child for child in children if isinstance(child, ast.AST)) + + def _tool_definitions_named(tree: ast.AST, definitions: _ToolDefinitions) -> set[str]: return { node.id - for node in ast.walk(tree) + for node in _walk_without_annotations(tree) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id in definitions @@ -852,10 +876,10 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( definitions = _tool_definitions(builder) # The same statements as main's, with file line numbers. assert ( - ast.unparse(definitions["_main"].body[matrix_dropped]) + ast.unparse(_tool_main(definitions).body[matrix_dropped]) == (statements[matrix_dropped]) ) - later_statements = definitions["_main"].body[matrix_dropped + 1 :] + later_statements = _tool_main(definitions).body[matrix_dropped + 1 :] receivers = { call.func.id for statement in later_statements @@ -889,7 +913,7 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( assert receivers <= reached trees: dict[str, list[ast.AST]] = {"_main": later_statements} for name in reached - {"_main"}: - trees[name] = [definitions[name]] + trees[name] = list(definitions[name]) later_nodes = [ (name, node) for name, roots in trees.items() @@ -948,8 +972,9 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non } definitions = _tool_definitions(builder) # The same statements as main's, with file line numbers. - assert ast.unparse(definitions["_main"].body[check + 1]) == statements[check + 1] - later_statements = definitions["_main"].body[check + 2 :] + main_in_file = _tool_main(definitions) + assert ast.unparse(main_in_file.body[check + 1]) == statements[check + 1] + later_statements = main_in_file.body[check + 2 :] reached = _tool_definitions_reached( definitions, set().union( @@ -961,7 +986,7 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non ) trees: dict[str, list[ast.AST]] = {"_main": later_statements} for name in reached - {"_main"}: - trees[name] = [definitions[name]] + trees[name] = list(definitions[name]) def named_by(target: str) -> set[str]: """The reached code that names ``target``.""" @@ -987,16 +1012,20 @@ def named_by(target: str) -> set[str]: # which the plan runs before export recording requests only, building no # reform (test_us_post_export_scoring.py:: # test_recording_the_smoke_plan_builds_no_reform_and_needs_no_engine). - # Scoring a consumer for real needs the scorer, which only certification - # opens; a build function that names the consumers for another reason, - # such as listing their names, passes as long as it opens no scorer. + # The consumers run for real only at certification. A new build function + # that names _post_export_consumers fails here until it is read: if it + # only lists the consumers (their names, say) and calls none, add it to + # the set below. assert named_by("_reform_coverage_smoke_consumer") == {"_post_export_consumers"} - assert { + assert named_by("_post_export_consumers") == {"_record_post_export_scoring_plan"} + real_scorers = { "_score_post_export_consumer", "_open_post_export_scorer", "_HouseholdBatchedPostExportScorer", "_BatchedPostExportReform", - } & reached == set() + } + assert real_scorers <= definitions.keys() + assert real_scorers & reached == set() def test_main_export_statements_leave_only_the_matrix_shape_and_nonzero_count( From ef9204fc9ea5c6cfc93b60dec3d08d0860578670 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:43:08 +0400 Subject: [PATCH 13/19] Follow every tool class _main names in the freeing scans 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 --- .../test_us_release_frees_after_last_use.py | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index b99ae30787..93455eef84 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -295,6 +295,30 @@ class brings in all its methods, and a variable what its value names. return reached +def _reached_after( + definitions: _ToolDefinitions, later_statements: list[ast.stmt] +) -> set[str]: + """The tool definitions that code after a point in ``_main`` can run. + + These are the definitions ``later_statements`` name, and every tool class + ``_main`` names anywhere, since an object built earlier, such as the + build's progress reporter, can run its methods later. Each is followed + through the definitions it names. + """ + named_later = set().union( + *( + _tool_definitions_named(statement, definitions) + for statement in later_statements + ) + ) + classes = { + name + for name in _tool_definitions_named(_tool_main(definitions), definitions) + if any(isinstance(statement, ast.ClassDef) for statement in definitions[name]) + } + return _tool_definitions_reached(definitions, named_later | classes) + + def _walk_without_annotations(tree: ast.AST): """``ast.walk``, skipping argument, return and variable annotations.""" pending = [tree] @@ -901,15 +925,7 @@ def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( "_us_build_record", "_assert_export_matches_calibration", } <= receivers - reached = _tool_definitions_reached( - definitions, - set().union( - *( - _tool_definitions_named(statement, definitions) - for statement in later_statements - ) - ), - ) + reached = _reached_after(definitions, later_statements) assert receivers <= reached trees: dict[str, list[ast.AST]] = {"_main": later_statements} for name in reached - {"_main"}: @@ -975,15 +991,7 @@ def test_main_clears_the_coverage_cache_after_the_start_up_check(builder) -> Non main_in_file = _tool_main(definitions) assert ast.unparse(main_in_file.body[check + 1]) == statements[check + 1] later_statements = main_in_file.body[check + 2 :] - reached = _tool_definitions_reached( - definitions, - set().union( - *( - _tool_definitions_named(statement, definitions) - for statement in later_statements - ) - ), - ) + reached = _reached_after(definitions, later_statements) trees: dict[str, list[ast.AST]] = {"_main": later_statements} for name in reached - {"_main"}: trees[name] = list(definitions[name]) From 7eac9d504933123945962e378ef06659d57be955 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:58:11 +0400 Subject: [PATCH 14/19] Start the freeing scans from all classes and stored functions of _main 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 --- .../test_us_release_frees_after_last_use.py | 36 +++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 93455eef84..48c944e17e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -300,23 +300,47 @@ def _reached_after( ) -> set[str]: """The tool definitions that code after a point in ``_main`` can run. - These are the definitions ``later_statements`` name, and every tool class - ``_main`` names anywhere, since an object built earlier, such as the - build's progress reporter, can run its methods later. Each is followed - through the definitions it names. + These are the definitions ``later_statements`` name, plus what code + before the point can leave for later. That is every tool class reachable + from ``_main``: an object built earlier, such as the build's progress + reporter, can run its methods after the point. It is also every tool + function ``_main`` uses as a value rather than calling it there. Each is + followed through the definitions it names. """ + main = _tool_main(definitions) named_later = set().union( *( _tool_definitions_named(statement, definitions) for statement in later_statements ) ) + reachable_from_main = _tool_definitions_reached( + definitions, _tool_definitions_named(main, definitions) + ) classes = { name - for name in _tool_definitions_named(_tool_main(definitions), definitions) + for name in reachable_from_main if any(isinstance(statement, ast.ClassDef) for statement in definitions[name]) } - return _tool_definitions_reached(definitions, named_later | classes) + called = { + id(node.func) + for node in _walk_without_annotations(main) + if isinstance(node, ast.Call) + } + functions_as_values = { + node.id + for node in _walk_without_annotations(main) + if isinstance(node, ast.Name) + and isinstance(node.ctx, ast.Load) + and id(node) not in called + and any( + isinstance(statement, ast.FunctionDef) + for statement in definitions.get(node.id, ()) + ) + } + return _tool_definitions_reached( + definitions, named_later | classes | functions_as_values + ) def _walk_without_annotations(tree: ast.AST): From 4aab639f4ac5665e91854e81265e9f782f3ecc87 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:15:15 +0400 Subject: [PATCH 15/19] Follow returned closures and stored functions anywhere _main reaches 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 --- .../test_us_release_frees_after_last_use.py | 68 ++++++++++++++++--- 1 file changed, 60 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index 48c944e17e..cdc8cc2284 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -295,17 +295,55 @@ class brings in all its methods, and a variable what its value names. return reached +def _is_a_function_value(node: ast.AST, nested: set[str]) -> bool: + """Whether an expression is a lambda or a nested function, or a container + or conditional expression holding one. A lambda passed to a call, as to + shadow_gate, is not: the call runs it and returns something else.""" + if isinstance(node, ast.Lambda): + return True + if isinstance(node, ast.Name): + return node.id in nested + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return any(_is_a_function_value(element, nested) for element in node.elts) + if isinstance(node, ast.Dict): + return any(_is_a_function_value(value, nested) for value in node.values) + if isinstance(node, ast.IfExp): + return _is_a_function_value(node.body, nested) or _is_a_function_value( + node.orelse, nested + ) + return False + + +def _returns_a_function(function: ast.FunctionDef) -> bool: + """Whether ``function`` returns a lambda or a function it defines.""" + nested = { + node.name + for node in ast.walk(function) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node is not function + } + return any( + isinstance(node, ast.Return) + and node.value is not None + and _is_a_function_value(node.value, nested) + for node in ast.walk(function) + ) + + def _reached_after( definitions: _ToolDefinitions, later_statements: list[ast.stmt] ) -> set[str]: """The tool definitions that code after a point in ``_main`` can run. These are the definitions ``later_statements`` name, plus what code - before the point can leave for later. That is every tool class reachable - from ``_main``: an object built earlier, such as the build's progress - reporter, can run its methods after the point. It is also every tool - function ``_main`` uses as a value rather than calling it there. Each is - followed through the definitions it names. + before the point can leave for later, anywhere ``_main`` reaches: + - every tool class, since an object built earlier, such as the build's + progress reporter, can run its methods after the point; + - every tool function used as a value rather than called there, which a + local or a returned mapping can hold, as _post_export_consumers does; + - every tool function that returns a closure or a lambda, which can run + later, as _reform_validation_consumer's does. + Each is followed through the definitions it names. """ main = _tool_main(definitions) named_later = set().union( @@ -317,6 +355,9 @@ def _reached_after( reachable_from_main = _tool_definitions_reached( definitions, _tool_definitions_named(main, definitions) ) + roots = [main] + [ + statement for name in reachable_from_main for statement in definitions[name] + ] classes = { name for name in reachable_from_main @@ -324,12 +365,14 @@ def _reached_after( } called = { id(node.func) - for node in _walk_without_annotations(main) + for root in roots + for node in _walk_without_annotations(root) if isinstance(node, ast.Call) } functions_as_values = { node.id - for node in _walk_without_annotations(main) + for root in roots + for node in _walk_without_annotations(root) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and id(node) not in called @@ -338,8 +381,17 @@ def _reached_after( for statement in definitions.get(node.id, ()) ) } + closure_factories = { + name + for name in reachable_from_main + if any( + isinstance(statement, ast.FunctionDef) and _returns_a_function(statement) + for statement in definitions[name] + ) + } return _tool_definitions_reached( - definitions, named_later | classes | functions_as_values + definitions, + named_later | classes | functions_as_values | closure_factories, ) From b26559a37f1225d670247098d2781bee6d2d3926 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:28:27 +0400 Subject: [PATCH 16/19] Follow results kept for later instead of every closure factory 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 --- .../test_us_release_frees_after_last_use.py | 99 ++++++++----------- 1 file changed, 41 insertions(+), 58 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index cdc8cc2284..df3a008eac 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -295,55 +295,25 @@ class brings in all its methods, and a variable what its value names. return reached -def _is_a_function_value(node: ast.AST, nested: set[str]) -> bool: - """Whether an expression is a lambda or a nested function, or a container - or conditional expression holding one. A lambda passed to a call, as to - shadow_gate, is not: the call runs it and returns something else.""" - if isinstance(node, ast.Lambda): - return True - if isinstance(node, ast.Name): - return node.id in nested - if isinstance(node, (ast.Tuple, ast.List, ast.Set)): - return any(_is_a_function_value(element, nested) for element in node.elts) - if isinstance(node, ast.Dict): - return any(_is_a_function_value(value, nested) for value in node.values) - if isinstance(node, ast.IfExp): - return _is_a_function_value(node.body, nested) or _is_a_function_value( - node.orelse, nested - ) - return False - - -def _returns_a_function(function: ast.FunctionDef) -> bool: - """Whether ``function`` returns a lambda or a function it defines.""" - nested = { - node.name - for node in ast.walk(function) - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node is not function - } - return any( - isinstance(node, ast.Return) - and node.value is not None - and _is_a_function_value(node.value, nested) - for node in ast.walk(function) - ) - - def _reached_after( definitions: _ToolDefinitions, later_statements: list[ast.stmt] ) -> set[str]: """The tool definitions that code after a point in ``_main`` can run. These are the definitions ``later_statements`` name, plus what code - before the point can leave for later, anywhere ``_main`` reaches: - - every tool class, since an object built earlier, such as the build's - progress reporter, can run its methods after the point; - - every tool function used as a value rather than called there, which a - local or a returned mapping can hold, as _post_export_consumers does; - - every tool function that returns a closure or a lambda, which can run - later, as _reform_validation_consumer's does. - Each is followed through the definitions it names. + before the point can leave for later: + - every tool class reachable from ``_main``, since an object built + earlier, such as the build's progress reporter, can run its methods + after the point; + - every tool function ``_main`` uses as a value rather than calling it, + which a local can hold until after the point; + - what a call before the point names when ``_main`` binds its result to a + local that it reads after the point, since that result (a closure, a + function or an object) can run then. + Each is followed through the definitions it names, and counts whole: a + matrix read that such a function makes before it returns, while the + matrix is still there, fails the scan too, and belongs in a function of + its own. """ main = _tool_main(definitions) named_later = set().union( @@ -355,9 +325,6 @@ def _reached_after( reachable_from_main = _tool_definitions_reached( definitions, _tool_definitions_named(main, definitions) ) - roots = [main] + [ - statement for name in reachable_from_main for statement in definitions[name] - ] classes = { name for name in reachable_from_main @@ -365,14 +332,12 @@ def _reached_after( } called = { id(node.func) - for root in roots - for node in _walk_without_annotations(root) + for node in _walk_without_annotations(main) if isinstance(node, ast.Call) } functions_as_values = { node.id - for root in roots - for node in _walk_without_annotations(root) + for node in _walk_without_annotations(main) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and id(node) not in called @@ -381,17 +346,35 @@ def _reached_after( for statement in definitions.get(node.id, ()) ) } - closure_factories = { - name - for name in reachable_from_main - if any( - isinstance(statement, ast.FunctionDef) and _returns_a_function(statement) - for statement in definitions[name] - ) + later_nodes = { + id(node) for statement in later_statements for node in ast.walk(statement) } + read_later = { + node.id + for statement in later_statements + for node in ast.walk(statement) + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) + } + kept_for_later: set[str] = set() + for node in ast.walk(main): + if ( + id(node) in later_nodes + or not isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)) + or not isinstance(node.value, ast.Call) + ): + continue + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + bound = { + name.id + for target in targets + for name in ast.walk(target) + if isinstance(name, ast.Name) + } + if bound & read_later: + kept_for_later |= _tool_definitions_named(node.value, definitions) return _tool_definitions_reached( definitions, - named_later | classes | functions_as_values | closure_factories, + named_later | classes | functions_as_values | kept_for_later, ) From 7532828f8fef6f89aa8da74d264f57dfd065b284 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:18:07 +0400 Subject: [PATCH 17/19] Count calibrate.dropped_matrix among the modules the gate bindings reach 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 --- .../engine_free/shared/test_transport_evidence_kernels.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 2a89ce08c5..0f4d60bbca 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -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 From a199f86dd058b7e47fdbdc4410ee59d6d51923aa Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:44:21 +0400 Subject: [PATCH 18/19] Expect the release engine freed after the written-file check 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 --- .../test_us_release_frees_after_last_use.py | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py index df3a008eac..24f20fba67 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_release_frees_after_last_use.py @@ -897,9 +897,15 @@ def check(): def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> None: - """The engine that writes the H5 is released right after the write, before - the written-file check, the export audit and the calibration NPZ that end - the build.""" + """The engine that writes the H5 is released once the written file's + stored-input check has recorded its result, before the export audit and + the calibration NPZ that end the build. + + The release does not sit between the write and that check: the stored-input + test (test_us_stored_input_register) holds the check right after the + write. The check reads only the written file's column names and the + module-level PolicyEngine-US system, so the engine adds nothing to the + memory the check uses.""" main = _main_function(builder) released_at = _single_top_level_release(main, "release_engine") released_line = main.body[released_at].lineno @@ -914,7 +920,16 @@ def test_main_frees_the_release_engine_after_writing_the_dataset(builder) -> Non and getattr(node.value.func, "attr", None) == "write_dataset" ] assert ast.unparse(write.value.func.value) == "release_engine" - assert released_at == main.body.index(write) + 1 + written_file_check = main.body.index(write) + 1 + check_result_recorded = written_file_check + 1 + assert "_written_stored_input_verdict_mismatch" in ast.unparse( + main.body[written_file_check] + ) + assert isinstance(main.body[check_result_recorded], ast.If) + assert ast.unparse(main.body[check_result_recorded].test) == ( + "stored_input_premise_failure is not None" + ) + assert released_at == check_result_recorded + 1 def test_main_drops_the_constraint_matrix_before_rebinding_the_ladder_outcome( From 479cad5bb79a88cdd7dc9b3d7a52dbed7c60b9be Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:48:30 +0400 Subject: [PATCH 19/19] Free the release engine after the written-file check 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 --- changelog.d/release-free-after-last-use.changed.md | 2 +- tools/build_us_fiscal_refresh_release.py | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/changelog.d/release-free-after-last-use.changed.md b/changelog.d/release-free-after-last-use.changed.md index e7c6fda5c9..caf1e32141 100644 --- a/changelog.d/release-free-after-last-use.changed.md +++ b/changelog.d/release-free-after-last-use.changed.md @@ -1 +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` after the H5 write. 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. +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. diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index a88ee2d3ee..4dcb622a35 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -19180,9 +19180,6 @@ def _main(argv: Sequence[str] | None = None) -> int | None: # microcosm#443: #437 dropped this call while inserting the batched raise, # so attempts 13/14 smoke-scored a stale artifact from a prior run. release_engine.write_dataset(export_frame, dataset_path, period=PERIOD) - # The writer was the engine's last use; post-export scoring builds its own. - # Rebound rather than deleted, as base_frame is above. - release_engine = None # microcosm#1026: the stored-input gate above graded a model of the # writer's output; the written bytes are graded whatever the gate reached # and must earn the same verdict (no refusal, if the gate could not @@ -19205,6 +19202,12 @@ def _main(argv: Sequence[str] | None = None) -> int | None: if stored_input_premise_failure is not None: artifact_integrity_failures.append(stored_input_premise_failure) terminal_gate_failures.append(stored_input_premise_failure) + # The writer was the engine's last use; post-export scoring builds its own. + # It is released here, not between the write and the written file's check, + # which stays right after the write; that check reads column names and the + # module-level system only. Rebound rather than deleted, as base_frame is + # above. + release_engine = None # The build ends here (microcosm#1585 item 11, PR 4a). The optional export # audit and the calibration NPZ read the calibration result, which only # this process holds, so they run first. Every later stage scores the