Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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-head-to-head-shared-pool.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The US head-to-head scorer (`tools/score_us_release_head_to_head.py`) runs its `--workers` slices on the shared worker pool instead of `ProcessPoolExecutor`, so the repository has one worker-pool implementation. `--worker-max-slices` now works on every supported Python: the scorer no longer refuses it on interpreters where `ProcessPoolExecutor` could hang replacing a worker. A slice whose worker dies (for example, killed by the operating system for its memory) runs once more in a fresh worker before the run stops with the slice's label; the scorer's own 20 GiB memory check, and any other error raised while scoring a slice, still stop the run at once. Each failed attempt is printed on stderr. Scorecards are unchanged.
1 change: 1 addition & 0 deletions changelog.d/us-post-export-rule-modules.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
US post-export scoring removes the variable modules that each reform's tax-benefit system build adds to `sys.modules`, which policyengine-core never removes, once the reform's consumer opens its next reform or finishes, or the scorer closes. On the eight-household guard fixture the modules held about 0.04 GiB per reform pass, about 4 GiB over a full build's 98 reform passes (estimate). `EngineVariableModuleScope` in `microcosm.build.us_runtime.engine_lifecycle` is the explicit open/close form of `temporary_engine_variable_modules` that this uses; a scope left unclosed does nothing when garbage-collected. Scored values are unchanged.
1 change: 1 addition & 0 deletions changelog.d/us-shared-worker-pool.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`microcosm.build.worker_pool` runs independent units of household-batched work, such as policyengine-us passes over household batches, in spawned worker processes and returns their results in unit order, so callers join them in the order one process would use and get byte-identical outputs. Each worker runs the caller's initializer once, so start-up data such as a frame crosses once per worker; a worker can be replaced after a set number of units; a thread in the parent stops a worker whose memory footprint (resident plus compressed or swapped-out pages) goes over a per-worker cap; a unit whose worker dies, goes over the cap or raises `MemoryError` runs again in a fresh worker, up to a set number of attempts; and optional environment variables are set in each worker as it starts, before it imports anything. The caller sets the worker count and the cap. `test_support/microcosm_build/worker_pool_identity.py` adds a test helper that runs a pooled computation at several worker counts and requires byte-identical results.
10 changes: 7 additions & 3 deletions docs/evidence/us-h2h-memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,13 @@ imports, unrelated paths, and the shared default system when imported lazily.
It restores pre-existing entries if Core reused a discarded system's id.
The returned slice contains no live engine objects.

`--worker-max-slices K` additionally passes `max_tasks_per_child=K` to the spawn
executor. The default remains no recycling. An explicit K also uses the pool
with `--workers 1`. Task submission and ordered reduction remain unchanged.
`--worker-max-slices K` additionally replaces each spawned worker after K
slices. The scorer first did this with `ProcessPoolExecutor`'s
`max_tasks_per_child=K`; it now runs its slices on the shared worker pool
(`microcosm.build.worker_pool`), which replaces workers itself and so works on
every supported Python. The default remains no replacement. An explicit K also
uses the pool with `--workers 1`. Task order and ordered reduction remain
unchanged.

## Measurement method

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,166 @@
from __future__ import annotations

import sys
import threading
import weakref
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from types import ModuleType
from typing import Any

__all__ = ["release_engine_simulation", "temporary_engine_variable_modules"]
__all__ = [
"EngineVariableModuleScope",
"release_engine_simulation",
"temporary_engine_variable_modules",
]


def _loaded_variables_dir() -> str | Path | None:
engine = sys.modules.get("policyengine_us")
system_cls = getattr(engine, "CountryTaxBenefitSystem", None)
return getattr(system_cls, "variables_dir", None)


def _registrations(directory: Path | None) -> dict[str, ModuleType]:
"""Core's per-system variable-module registrations under ``directory``."""
found = {}
for name, module in tuple(sys.modules.items()):
parts = name.split("_", 2)
if (
len(parts) != 3
or not parts[0].isdigit()
or not parts[1].removeprefix("-").isdigit()
or not isinstance(module, ModuleType)
):
continue
filename = getattr(module, "__file__", None)
if not isinstance(filename, str):
continue
path = Path(filename).absolute()
if parts[2] == path.stem and (
directory is None or path.is_relative_to(directory)
):
found[name] = module
return found


# Scopes opened and not yet closed, oldest first, as weak references: a scope
# dropped without closing stops counting once it is collected.
_OPEN_SCOPES: list[weakref.ref[EngineVariableModuleScope]] = []
# Reentrant: a garbage collection that frees a suspended
# ``temporary_engine_variable_modules`` scope runs its ``close`` in whichever
# thread is running, possibly one that holds this lock inside ``open``.
_OPEN_SCOPES_LOCK = threading.RLock()


class EngineVariableModuleScope:
"""Remove Core's variable-module registrations made between open and close.

The explicit form of :func:`temporary_engine_variable_modules`, for a scope
that spans several calls: post-export scoring builds a reform's system on
the reform's first key and closes the scope when its consumer moves on. A
suspended context manager would run its cleanup whenever the garbage
collector closed it, at an arbitrary later moment, and remove modules a
later scope registered and still uses. A scope left unclosed here does
nothing when collected; its modules simply stay registered, as they would
without it. ``close`` does nothing the second time.

Scopes may close in any order. A registration belongs to the most recently
opened scope that is still open when it is made: a scope that closes
removes what was registered since it opened, except what was registered
after a later, still-open scope opened, which that scope removes when it
closes. An entry that existed when the scope opened is put back only if
the scope is the latest open one and the entry is still registered (Core
reused a dead system's id and overwrote it); otherwise the later scope,
whose snapshot holds it too, decides.
"""

def __init__(self, variables_dir: str | Path | None = None) -> None:
self._variables_dir = variables_dir
self._previous: dict[str, ModuleType] | None = None
self._closed = False

def open(self) -> EngineVariableModuleScope:
"""Take the snapshot of registrations that ``close`` keeps."""
if self._previous is not None or self._closed:
raise RuntimeError("An engine variable module scope opens only once.")
initial_directory = self._variables_dir or _loaded_variables_dir()
directory = (
None if initial_directory is None else Path(initial_directory).absolute()
)
with _OPEN_SCOPES_LOCK:
self._previous = _registrations(directory)
_OPEN_SCOPES.append(weakref.ref(self))
return self

def _first_later_open_scope_snapshot(self) -> dict[str, ModuleType] | None:
"""The snapshot of the oldest scope opened after this one and still open."""
later = False
snapshot = None
# A copy: a close that a garbage collection runs from in here may change
# the list.
for reference in tuple(_OPEN_SCOPES):
scope = reference()
if scope is self:
later = True
elif (
later
and snapshot is None
and scope is not None
and scope._previous is not None
):
snapshot = scope._previous
_OPEN_SCOPES[:] = [
reference
for reference in _OPEN_SCOPES
if reference() is not None and reference() is not self
]
return snapshot

def close(self) -> None:
"""Remove the registrations made since ``open``, except the shared system's."""
with _OPEN_SCOPES_LOCK:
previous, self._previous = self._previous, None
if self._closed or previous is None:
self._closed = True
return
self._closed = True
later_snapshot = self._first_later_open_scope_snapshot()
self._remove_since(previous, later_snapshot)

def _remove_since(
self,
previous: dict[str, ModuleType],
later_snapshot: dict[str, ModuleType] | None,
) -> None:
final_directory = self._variables_dir or _loaded_variables_dir()
if final_directory is None:
return
# The first slice may import the engine lazily. Its newly built shared
# default system remains live for every later simulation; retain those
# registrations along with the entry snapshot.
engine = sys.modules.get("policyengine_us")
simulation_cls = getattr(engine, "Microsimulation", None)
shared_system = getattr(
simulation_cls, "default_tax_benefit_system_instance", None
)
shared_prefix = f"{id(shared_system)}_"
for name in _registrations(Path(final_directory).absolute()):
if name in previous:
if later_snapshot is not None:
# A later open scope's snapshot holds it too; it decides.
continue
current = sys.modules.get(name)
# Not if another scope removed it meanwhile (a garbage
# collection can close one in the middle of this loop).
if current is not None and current is not previous[name]:
sys.modules[name] = previous[name]
elif later_snapshot is not None and name not in later_snapshot:
# Registered after a still-open later scope opened.
continue
elif shared_system is None or not name.startswith(shared_prefix):
sys.modules.pop(name, None)


@contextmanager
Expand All @@ -59,60 +212,15 @@ def temporary_engine_variable_modules(

The default discovers an already imported US engine, so importing this
helper remains engine-free. An explicit directory supports stand-ins.
Use only around a completed slice whose engine objects do not escape.
Use only around a completed slice whose engine objects do not escape; for
a scope that spans calls, use :class:`EngineVariableModuleScope`.
"""

def loaded_variables_dir():
engine = sys.modules.get("policyengine_us")
system_cls = getattr(engine, "CountryTaxBenefitSystem", None)
return getattr(system_cls, "variables_dir", None)

initial_directory = variables_dir or loaded_variables_dir()
directory = (
None if initial_directory is None else Path(initial_directory).absolute()
)

def registrations(directory: Path | None) -> dict[str, ModuleType]:
found = {}
for name, module in tuple(sys.modules.items()):
parts = name.split("_", 2)
if (
len(parts) != 3
or not parts[0].isdigit()
or not parts[1].removeprefix("-").isdigit()
or not isinstance(module, ModuleType)
):
continue
filename = getattr(module, "__file__", None)
if not isinstance(filename, str):
continue
path = Path(filename).absolute()
if parts[2] == path.stem and (
directory is None or path.is_relative_to(directory)
):
found[name] = module
return found

previous = registrations(directory)
scope = EngineVariableModuleScope(variables_dir).open()
try:
yield
finally:
final_directory = variables_dir or loaded_variables_dir()
if final_directory is not None:
# The first slice may import the engine lazily. Its newly built
# shared default system remains live for every later simulation;
# retain those registrations along with the entry snapshot.
engine = sys.modules.get("policyengine_us")
simulation_cls = getattr(engine, "Microsimulation", None)
shared_system = getattr(
simulation_cls, "default_tax_benefit_system_instance", None
)
shared_prefix = f"{id(shared_system)}_"
for name in registrations(Path(final_directory).absolute()):
if name in previous:
sys.modules[name] = previous[name]
elif shared_system is None or not name.startswith(shared_prefix):
del sys.modules[name]
scope.close()


#: Instance attributes whose only post-mortem job is to keep big object
Expand Down
Loading
Loading