Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/us-pinned-rules-copy-release.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Free the copy of the rules that policyengine-us 2.2.1 keeps for New York's pre-2024 credit formulas when an engine simulation is released, so a post-export pass that scores 2024 state income tax no longer leaves about 1.3 GiB of rules and parameters alive.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
- ``self.calc = self.calculate`` stores a bound method on the instance — a
guaranteed self-cycle on every simulation.

policyengine-us 2.2.1 adds one more holder: the module-level cache of rules
pinned to earlier federal law that New York's credit formulas fill, whose
entries keep the engine they were made in (see :func:`_drop_pinned_rule_copies`).

Cyclic graphs are invisible to the builder's cheap per-batch ``gc.collect(0)``
once anything promotes them past generation 0, and CPython throttles full
collections against the build's multi-GB long-lived heap — the measured result
Expand Down Expand Up @@ -241,6 +245,103 @@ def _sever_existing_attribute(target: Any, name: str) -> None:
pass


#: The policyengine-us module whose ``_PINNED_TBS_CACHE`` holds the systems
#: that New York's credit formulas pin to earlier federal rules.
_PINNED_RULES_MODULE = "policyengine_us.tools.pinned_tbs"


#: How many ``parent_branch`` links :func:`_made_in_released_simulation`
#: follows from the simulation a pinned copy was made in. policyengine-us formulas
#: branch at most a few levels deep; the bound only guards against a cycle.
_MAXIMUM_BRANCH_DEPTH = 64


def _made_in_released_simulation(clone: Any, simulations: list[Any]) -> bool:
"""Whether ``clone`` was made in one of ``simulations`` or a branch of one.

Core's ``TaxBenefitSystem.clone`` copies the ``simulation`` attribute, so a
pinned copy names the simulation its lookup ran in. That may be a branch a
formula has already removed from ``branches`` (policyengine-us's marginal
tax rate formula makes a branch for each of its first
``marginal_tax_rate_adults`` adults, computes household income in it and
deletes it), which the release walk never reaches; its ``parent_branch``
still leads to the simulation it was made from.

An attribute read that raises (a dead weak proxy, or a property of another
engine version) answers ``False``: the entry is left alone.
"""
try:
current = getattr(clone, "simulation", None)
for _ in range(_MAXIMUM_BRANCH_DEPTH):
if current is None:
return False
if any(current is simulation for simulation in simulations):
return True
current = getattr(current, "parent_branch", None)
except Exception:
return False
return False


def _drop_pinned_rule_copies(systems: list[Any], simulations: list[Any]) -> None:
"""Remove the pinned-rules cache entries made in released simulations.

In policyengine-us 2.2.1, New York's pre-2024 child tax credit formulas
(``ny_ctc_pre_2024_eligible`` and ``ny_ctc_pre_2024``, from 2018 except
2025-2027) and its 2021 EITC (``ny_eitc``) recompute federal credits under
earlier rules through ``policyengine_us.tools.pinned_tbs``. A lookup that
misses clones the simulation's whole tax-benefit system and stores
``(weak reference to that system, weak reference to its parameter tree,
clone)`` under the pin's name in the module-level ``_PINNED_TBS_CACHE``.
The clone is held strongly, and core's ``TaxBenefitSystem.clone`` copies
the ``simulation`` attribute into it. So the entry keeps the finished
engine alive and, through the engine's system, that system's parameter
tree, variables and rule modules, until another engine's lookup replaces
the entry: about 1.3 GiB after a reform pass, 0.5 GiB after a baseline
pass.

``systems`` and ``simulations`` are what the release walked. An entry is
removed when its first item is a weak reference to one of ``systems``, or
when its clone was made in one of ``simulations`` or in a branch of one
that a formula removed from ``branches``
(:func:`_made_in_released_simulation`). A lookup reuses an entry only for
the same system object it was pinned from, and each policyengine-us
simulation and branch gets a system object of its own, so no later engine
can reuse a removed entry and no scored value changes. (Were a system
shared by a simulation still running, its next lookup would clone again,
as any miss does.) An entry whose base system is already collected is
still removed when its clone was made in a released simulation. Entries
made elsewhere, dead or not, a missing cache, a cache that is not a dict
and entries without a weak reference first are left alone. The module is
not imported here.

policyengine-us 2.88.6 holds every part of an entry weakly
(PolicyEngine/policyengine-us#10550). Its entries are matched by their
first item the same way, and removing them frees nothing. Remove this
when the US engine pin reaches 2.88.6.
"""
module = sys.modules.get(_PINNED_RULES_MODULE)
cache = getattr(module, "_PINNED_TBS_CACHE", None)
if not (systems or simulations) or not isinstance(cache, dict):
return
for pin_name, entry in tuple(cache.items()):
if not isinstance(entry, tuple) or not entry:
continue
base_reference = entry[0]
if not isinstance(base_reference, weakref.ReferenceType):
continue
base = base_reference()
pinned_from_a_released_system = base is not None and any(
base is system for system in systems
)
clone = entry[2] if len(entry) > 2 else None
if (
pinned_from_a_released_system
or _made_in_released_simulation(clone, simulations)
) and cache.get(pin_name) is entry:
del cache[pin_name]


def release_engine_simulation(simulation: Any) -> None:
"""Release a finished engine simulation's retained state.

Expand All @@ -257,16 +358,23 @@ def release_engine_simulation(simulation: Any) -> None:
- drops dataset/tracer/bound-method attributes that only extend the
graph's lifetime.

Then it removes the entries policyengine-us's pinned-rules cache holds for
copies made in those simulations, or in branches of them that a formula
already removed (:func:`_drop_pinned_rule_copies`).

Safe to call on stubs and doubles: only attributes the object actually
carries are touched. Idempotent.
"""
stack = [simulation]
seen: set[int] = set()
released_systems: list[Any] = []
released_simulations: list[Any] = []
while stack:
current = stack.pop()
if current is None or id(current) in seen:
continue
seen.add(id(current))
released_simulations.append(current)

branches = getattr(current, "branches", None)
if isinstance(branches, dict):
Expand All @@ -288,6 +396,8 @@ def release_engine_simulation(simulation: Any) -> None:
populations.clear()

tax_benefit_system = getattr(current, "tax_benefit_system", None)
if tax_benefit_system is not None:
released_systems.append(tax_benefit_system)
if (
tax_benefit_system is not None
and getattr(tax_benefit_system, "simulation", None) is current
Expand All @@ -299,3 +409,5 @@ def release_engine_simulation(simulation: Any) -> None:

for attribute in _SEVERED_ATTRIBUTES:
_sever_existing_attribute(current, attribute)

_drop_pinned_rule_copies(released_systems, released_simulations)
Loading
Loading