From 987ce0ec0bb21583f6d9846363d52a81b01b2adc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 06:30:00 -0400 Subject: [PATCH 1/2] Speed up the owners' draw reform tests Cloning or materializing a full parameter tree triggers automatic collections that traverse every object the shared country system holds. The full-system tests now pause automatic collection between a full collection at setup and a young-generation collection at teardown, which frees each private system without re-traversing the shared one. The disabled-reform test drops its six mid-test full collections, which released only small simulations. Assertions, properties, examples, max_examples and tolerances are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../owners-draw-test-runtime.changed.md | 1 + .../tests/reforms/test_owners_draw.py | 36 ++++++++++++++----- 2 files changed, 29 insertions(+), 8 deletions(-) create mode 100644 changelog.d/owners-draw-test-runtime.changed.md diff --git a/changelog.d/owners-draw-test-runtime.changed.md b/changelog.d/owners-draw-test-runtime.changed.md new file mode 100644 index 00000000000..e514a17f143 --- /dev/null +++ b/changelog.d/owners-draw-test-runtime.changed.md @@ -0,0 +1 @@ +Speed up the owners' draw reform tests: their full-system tests now pause automatic garbage collection and free each private system with one young-generation collection, leaving every assertion and example unchanged. diff --git a/policyengine_us/tests/reforms/test_owners_draw.py b/policyengine_us/tests/reforms/test_owners_draw.py index a20f8c1e555..084ff704178 100644 --- a/policyengine_us/tests/reforms/test_owners_draw.py +++ b/policyengine_us/tests/reforms/test_owners_draw.py @@ -3,7 +3,8 @@ Dollar examples live in owners_draw.yaml. These tests capture the installed formula classes for fast deterministic and shrinking generated vectors. Public Simulation tests batch households under one private policy per test to exercise -constructor activation, baseline equality, cap preservation and AIME history. +constructor activation, baseline equality, cap preservation and AIME history; +they pause automatic garbage collection while they run (see paused_gc). """ import gc @@ -303,7 +304,7 @@ def test_invalid_policy_settings_fail_explicitly( ) -def test_future_parameter_activation_captures_cap_and_preserves_baseline(): +def test_future_parameter_activation_captures_cap_and_preserves_baseline(paused_gc): years = (2026, 2036, 2037) situation = { "people": { @@ -688,14 +689,36 @@ def test_generated_deduction_tracks_existing_deductible_share( @pytest.fixture -def private_draw_system(): +def paused_gc(): + """Pause automatic collection while a test clones or reads a full tree. + + Every automatic collection traverses all the objects the shared country + system and its parameter views hold, and cloning or materializing a + parameter tree triggers many of them. Setup still starts from a fully + collected heap. With no collection running, nothing leaves the young + generation, so a young collection at teardown frees everything the test + released, its private system included, without traversing the shared + system again. The next test's full collection catches anything an explicit + mid-test collection (Hypothesis's first in a process) promoted. + """ + gc.collect() + gc.disable() + try: + yield + finally: + gc.collect(0) + gc.enable() + + +@pytest.fixture +def private_draw_system(paused_gc): """Keep one independent registry/parameter tree for a complete property. Hypothesis reuses a function fixture across examples intentionally: policy stays fixed, while every example gets new Simulation holders. - A mutable owner releases even pytest's fixture reference after the test. + A mutable owner releases even pytest's fixture reference after the test, + before paused_gc collects it. """ - gc.collect() owner = SimpleNamespace(system=None) try: yield owner @@ -710,7 +733,6 @@ def private_draw_system(): "parameter_fingerprint", ): owner.__dict__.pop(name, None) - gc.collect() SIMULATION_SETTINGS = { @@ -979,7 +1001,6 @@ def test_generated_disabled_reform_matches_public_baseline( finally: _release_simulation_reference(baseline) del baseline - gc.collect() create_owners_draw().apply(policy) assert policy.parameters is root @@ -1012,7 +1033,6 @@ def test_generated_disabled_reform_matches_public_baseline( finally: _release_simulation_reference(disabled) del disabled - gc.collect() finally: # Restore all original variables, including removing added draw names. # A fresh public constructor rebinds entities and holders next example. From 3207cac179858f7c5c087d37518be7db448ec1d1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 03:39:13 -0400 Subject: [PATCH 2/2] Collect each owners' draw example and restore the GC setting paused_gc now yields from _paused_collection. It saves gc.isenabled() on entry, runs a middle-generation collection at exit, and restores the saved setting in a nested finally, so a teardown collection that raises no longer leaves collection off, and a caller that entered with collection off keeps it off. The three simulation properties collect generation 0 when each Hypothesis example ends, passing or failing, so released Simulation cycles no longer pile up while Hypothesis shrinks a failure. Seven lifecycle tests cover both entry settings, a teardown collection error, the per-example collection and the survivors a property keeps. Co-Authored-By: Claude Opus 5.5 --- .../owners-draw-test-runtime.changed.md | 2 +- .../tests/reforms/test_owners_draw.py | 157 ++++++++++++++++-- 2 files changed, 147 insertions(+), 12 deletions(-) diff --git a/changelog.d/owners-draw-test-runtime.changed.md b/changelog.d/owners-draw-test-runtime.changed.md index e514a17f143..efe2bc08fd9 100644 --- a/changelog.d/owners-draw-test-runtime.changed.md +++ b/changelog.d/owners-draw-test-runtime.changed.md @@ -1 +1 @@ -Speed up the owners' draw reform tests: their full-system tests now pause automatic garbage collection and free each private system with one young-generation collection, leaving every assertion and example unchanged. +Speed up the owners' draw reform tests: their full-system tests now pause automatic garbage collection, free each Hypothesis example's released simulations when it ends, and restore the caller's collection setting afterwards, leaving every assertion and example unchanged. diff --git a/policyengine_us/tests/reforms/test_owners_draw.py b/policyengine_us/tests/reforms/test_owners_draw.py index 084ff704178..b1b51eb7819 100644 --- a/policyengine_us/tests/reforms/test_owners_draw.py +++ b/policyengine_us/tests/reforms/test_owners_draw.py @@ -7,11 +7,14 @@ they pause automatic garbage collection while they run (see paused_gc). """ +from contextlib import contextmanager +from functools import wraps import gc from hashlib import sha256 from itertools import chain import pickle from types import SimpleNamespace +import weakref import numpy as np import pytest @@ -688,6 +691,35 @@ def test_generated_deduction_tracks_existing_deductible_share( ) +@contextmanager +def _paused_collection(): + """Pause automatic collection, then restore the setting found on entry.""" + enabled = gc.isenabled() + gc.collect() + gc.disable() + try: + yield + finally: + try: + gc.collect(1) + finally: + if enabled: + gc.enable() + + +def _collect_each_example(test): + """Free what each Hypothesis example released when it ends, pass or fail.""" + + @wraps(test) + def collected(*args, **kwargs): + try: + return test(*args, **kwargs) + finally: + gc.collect(0) + + return collected + + @pytest.fixture def paused_gc(): """Pause automatic collection while a test clones or reads a full tree. @@ -695,19 +727,20 @@ def paused_gc(): Every automatic collection traverses all the objects the shared country system and its parameter views hold, and cloning or materializing a parameter tree triggers many of them. Setup still starts from a fully - collected heap. With no collection running, nothing leaves the young - generation, so a young collection at teardown frees everything the test - released, its private system included, without traversing the shared - system again. The next test's full collection catches anything an explicit - mid-test collection (Hypothesis's first in a process) promoted. + collected heap. Properties free each example's released simulations with + a young collection when the example ends (_collect_each_example), so + shrinking a failure cannot pile them up. Those collections move whatever + survives, such as the private system and every failing example's locals, + which Hypothesis keeps with the exception until the property finishes, + into the middle generation only. A middle-generation collection at + teardown therefore frees everything the test released without traversing + the shared system again. Teardown then restores the collection setting + found on entry, even if that collection raises. The next test's full + collection catches anything an explicit mid-test full collection + (Hypothesis's first in a process) promoted further. """ - gc.collect() - gc.disable() - try: + with _paused_collection(): yield - finally: - gc.collect(0) - gc.enable() @pytest.fixture @@ -735,6 +768,105 @@ def private_draw_system(paused_gc): owner.__dict__.pop(name, None) +# The collection lifecycle needs no country system. These checks skip each +# full collection, which would traverse it, and run the others for real. +class _Cycle: + def __init__(self): + self.self = self + + +@pytest.fixture +def collection_calls(monkeypatch): + enabled = gc.isenabled() + collect = gc.collect + generations = [] + + def young_only(generation=2): + generations.append(generation) + return 0 if generation == 2 else collect(generation) + + monkeypatch.setattr(gc, "collect", young_only) + yield generations + (gc.enable if enabled else gc.disable)() + + +@pytest.mark.parametrize("enabled", [True, False]) +def test_paused_collection_restores_the_entry_setting(collection_calls, enabled): + (gc.enable if enabled else gc.disable)() + with _paused_collection(): + assert collection_calls == [2] + assert not gc.isenabled() + assert gc.isenabled() is enabled + + +@pytest.mark.parametrize("enabled", [True, False]) +def test_paused_collection_restores_the_setting_when_teardown_collection_fails( + collection_calls, monkeypatch, enabled +): + (gc.enable if enabled else gc.disable)() + collect = gc.collect + tearing_down = False + + def fail_at_teardown(*args): + if tearing_down: + raise MemoryError("teardown collection") + return collect(*args) + + monkeypatch.setattr(gc, "collect", fail_at_teardown) + with pytest.raises(MemoryError, match="teardown collection"): + with _paused_collection(): + tearing_down = True + assert gc.isenabled() is enabled + + +@pytest.mark.parametrize("fails", [False, True]) +def test_each_example_frees_the_cycles_it_released(collection_calls, fails): + released = [] + + @_collect_each_example + def generated_example(): + cycle = _Cycle() + released.append(weakref.ref(cycle)) + del cycle + assert not fails + + with _paused_collection(): + if fails: + with pytest.raises(AssertionError): + generated_example() + else: + generated_example() + assert released[0]() is None + + +def test_examples_keep_what_the_property_holds_until_teardown(collection_calls): + owner = SimpleNamespace(kept=None) + failures = [] + + @_collect_each_example + def generated_example(fails): + if owner.kept is None: + owner.kept = _Cycle() + local = _Cycle() + failures.append(weakref.ref(local)) + assert not fails + + with _paused_collection(): + generated_example(False) + kept = weakref.ref(owner.kept) + # Like Hypothesis, hold a failing example's exception and so its locals. + with pytest.raises(AssertionError) as failure: + generated_example(True) + generated_example(False) + assert kept() is owner.kept + assert failures[1]() is not None + assert failures[0]() is None and failures[2]() is None + owner.kept = None + del failure + assert kept() is None + assert failures[1]() is None + + SIMULATION_SETTINGS = { **SETTINGS, "max_examples": 2, @@ -865,6 +997,7 @@ def _parameter_policy_fingerprint(root): (62, 600_000, 250_000, 600_000, 0, 0, 0), ], ) +@_collect_each_example def test_generated_raised_cap_paths_preserve_current_law_room( private_draw_system, reform_variables, route, batch ): @@ -938,6 +1071,7 @@ def apply(self): (85, 100_000, -20_000, 0, 100_000, 40_000, 20_000), ] ) +@_collect_each_example def test_generated_disabled_reform_matches_public_baseline( private_draw_system, reform_variables, batch ): @@ -1054,6 +1188,7 @@ def test_generated_disabled_reform_matches_public_baseline( year=2027, ) @example(amounts=[(0, 0, 0), (0, 0, 100_000), (100_000, 50_000, 100_000)], year=2036) +@_collect_each_example def test_generated_benefit_credit_cap_override_and_historical_lookback( private_draw_system, reform_variables, amounts, year ):