Repository navigation
Shared worker pool for household-batched policyengine-us work (1.4 · 1) - #1726
Merged
Merged
Conversation
…le removal Tests for microcosm.build.worker_pool (spawned workers, the initializer's state sent once per worker, worker replacement after a unit limit, a per-worker memory cap, re-running a unit whose worker died, ran out of memory or went over its cap, results in unit order, a per-worker environment) and for a 1-vs-N byte-identity helper. The head-to-head scorer's parallel tests now expect the shared pool and run worker replacement on every interpreter. Post-export scoring tests expect each reform's policyengine-core rule modules to be removed once its consumer opens the next reform or finishes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A post-export reform's rule modules must be removed when its consumer moves on, which spans several calls. A suspended temporary_engine_variable_modules generator would run its cleanup whenever the garbage collector closed it and could remove a later scope's modules. These tests expect an explicit scope that does nothing when dropped unclosed, and one open reform per post-export scorer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…post-export rule modules microcosm.build.worker_pool runs units of household-batched work in spawned worker processes it starts and tracks itself: the initializer's state is sent once per worker, workers can be replaced after K units with never more than the worker count alive, a parent thread stops a worker over its memory cap (resident plus compressed or swapped-out pages), a unit whose worker dies, goes over the cap or raises MemoryError runs again in a fresh worker up to max_attempts, results come back in unit order within a bounded window, and optional environment variables are set in each worker as it starts. The worker_pool_identity test helper requires byte-identical results at 1 and N workers. The head-to-head scorer's --workers slices run on the pool, so its ProcessPoolExecutor code and its Python-version refusal of --worker-max-slices go away. Post-export scoring opens an EngineVariableModuleScope (the explicit form of temporary_engine_variable_modules) when it builds a reform's system, and closes it when the scorer hands out its next reform, the consumer finishes or the scorer closes, removing the ~6,000 variable modules policyengine-core registers per system and never removes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pool: the memory cap while a worker starts, resuming a closed pool's map, a worker that will not exit after being stopped, an unclosed pool's workers, busy workers whose parent is killed, a map whose results were all taken, units and results that cannot be unpickled, memory one unit leaves behind, environment values that cannot be encoded, exit statuses collected elsewhere, and functions defined where workers cannot import them. Scorer: its own 20 GiB check stays fatal in a worker, a failed worker start names the artifact, and failed attempts are reported on stderr. Identity helper: structured dtypes, masked arrays, scalar and integer subclasses, bytes types and pandas categories and index names. Rule-module scopes may close out of order, and closing one scorer keeps another's open reform modules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pool: a worker start no longer holds the lock the memory thread needs; a map resumed after close raises; a worker that has not exited 10 s after being told to stop is killed; the memory thread and the finalizer share state with the pool, not the pool itself, so an unclosed pool is collected and kills its workers; workers exit when their parent dies; the last result finishes the map; units and results that cannot be unpickled stop the run with their label; a worker over its cap when it returns a result is replaced before its next unit; environment values are checked for encoding and set inside the restore block; dispatch no longer counts every unsent unit on each pass; exits are seen through each worker's exit pipe, so an exit status collected elsewhere is noticed; workers are killed through a pidfd on Linux; functions in a __main__ that spawn cannot import are refused. Scorer: its own 20 GiB check stays fatal in a worker, a failed worker start names the artifact, and failed attempts are reported on stderr. Module scopes may close out of order; the identity helper keeps dtypes with their fields, array and scalar types, masks and pandas metadata. The h2h memory evidence README describes worker replacement on the shared pool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A finished map's generator must not end a running map's turn; the pool must close cleanly from inside its memory thread while that thread holds the lock; a memory reading taken before a worker's current unit must not kill it; workers must use pipes; an idle worker must get its next unit while the caller holds a result; a handed-back result must not be kept while map waits; a stopped worker must be killed at its deadline between maps; a refused kill must not raise; the memory poll interval must be one a thread can wait for. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each map holds a token for its turn, so a finished map's generator closed late cannot end a later map's turn; the shared lock is reentrant and close() skips joining the memory thread from inside it, so a garbage collection there can close the pool; the memory thread records how many units a worker had been sent when it read the worker's memory and kills only if no new unit was sent since; it also kills stopped workers at their deadline between maps; workers use two one-way pipes instead of a socket pair; the main loop takes in finished work and hands out units before yielding a result it holds; map drops each result after yielding it; the poll interval must be one a thread can wait for; a result-time cap kill no longer makes the wait spin; kills the operating system refuses are given up on, not raised; shutdown closes pidfds and reaps under the lock. The docstring states the interpreter-lock limit of the parent-death exit and where process IDs can still be reused on macOS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ings The identity helper must encode equal structured arrays with object fields equally, keep categories beyond what a dtype's repr shows, MultiIndex level dtypes, nullable missing values, attrs and DatetimeIndex frequencies, and name NaN keys, frame cells and 0-d arrays. A module scope freed by a garbage collection while another scope holds the lock in the same thread must not hang. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
canonical_result_bytes encodes structured arrays and records field by field (never raw bytes with padding or object addresses), categoricals by their categories, order and codes, MultiIndex levels with their codes, extension arrays with their missing entries apart from NaN, attrs and DatetimeIndex frequencies; _first_difference compares mapping keys by their bytes, descends into DataFrame columns and Series positions, and names a 0-d array by its place. The module scopes' lock is reentrant and closing iterates a copy of the open scopes, so a scope a garbage collection frees mid-open cannot hang. The NaN-against-missing test builds its NaN with an explicit mask: pandas 3 turns NaN into a missing value when converting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A unit whose worker dies while receiving it is charged an attempt; a worker that dies while receiving its start-up data is a failed start, not the end of the run; a units iterable that raises leaves the pool usable; close() returns when its thread holds the pool's lock; handing back a result frees its place for an idle worker at once; busy workers exit when their parent is killed even while a child the parent forked holds copies of its pipe ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Start-up data goes over each worker's own pipe after its process starts, so a worker that dies while reading it is an ordinary failed start (and is reaped), and workers started together import at once. A unit is assigned and its attempt counted under the lock before it is written, and never to a killed worker, so a worker dying mid-send is charged and a reading taken before the unit cannot kill for it. map() reads its units before taking its turn, takes the turn under the lock and releases it on any failure. close() no longer joins the memory thread, and report() builds its result outside the lock. A held result frees its window place before units are handed out. Workers also exit when their parent process ID changes, for a parent whose forked child holds copies of the parent-death pipe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The identity helper must keep a Series subclass's _metadata and an ndarray subclass's attributes (such as weights and enum classes), numpy record and scalar types, encode equal MultiIndexes equally however they were built, and refuse pandas values it cannot encode with its own TypeError. A closing module scope must not put back a module another scope removed, nor replace a module a later, still-open scope registered under the same name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
canonical_result_bytes encodes what a pandas subclass lists in _metadata and what an ndarray subclass keeps in its instance dictionary (MicroSeries weights, an EnumArray's enum class), classes and enum members by name, numpy scalar types and dtype character codes, a MultiIndex by each level's values, and refuses pandas values it cannot encode with its own TypeError. A closing module scope leaves entries from its snapshot to a later open scope, and puts one back only while it is still registered, so it never restores a module another scope removed or replaces one a later scope registered under a reused name. The docstring states which scope a registration belongs to. The scorer's changelog entry says only a worker death runs a slice again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the Linux CI runners a fresh worker holds about 0.5 GiB once it has imported microcosm.build (torch and pandas), so the fixed 512 MiB cap killed workers while they started and test_a_worker_over_its_memory_cap_is_stopped_ and_its_unit_run_again failed on both engine-free legs. A module fixture now measures an idle worker's peak, and each cap test sets its cap 256 MiB above it and allocates 768 MiB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
marked this pull request as ready for review
November 25, 2026 14:21
On the engine-free (3.13) runner the test process, an hour into the run and holding 3.2 GB, showed the same footprint before and after allocating 256 MiB: its C allocator can hand out a freed block that is already resident. The test now reads a fresh child process before and after it allocates, and checks the reading is None once the child has exited. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
engine-free (3.14) and engine-uk (3.14) stopped after 18 s, before any test ran, with "No server is currently available to service your request" while fetching a release. Jobs cannot be re-run while their workflow run is still in progress, so this empty commit starts a new run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22
reviewed
Nov 25, 2026
juaristi22
left a comment
Collaborator
There was a problem hiding this comment.
Reviewed at 1828a1e96. The pool does what the description says, the head-to-head scorecards and the post-export scores don't move, and the branch merges cleanly with main. One thing before merge.
What I checked
- I probed the pool on invented units (macOS arm64, Python 3.14):
- 40 units with random delays on 3 workers, each replaced after 2 units: the results came back in unit order and byte-identical to a sequential run, over 21 worker starts with never more than 3 alive.
- A worker killed with SIGKILL in the middle of a unit: the unit ran again in a fresh worker, the results were unchanged, and the report named SIGKILL.
- A unit that raised
ValueError: the run stopped at once with the unit's label and the worker's traceback, and the pool closed. - A worker over its memory cap (idle at about 220 MiB, a cap 300 MiB above that, a unit holding 600 MiB): it was killed, the unit ran again, and the run stopped naming the cap. Units under the cap ran normally.
worker_environmentwas already set when the worker imported its modules, and the parent's environment was restored. Withmax_units_ahead=4and a slow first unit, only the first 4 units started before it finished. With the parent killed in the middle of a unit, both workers were gone within 0.2 s.
- No consumer asks a finished reform for another key. The coverage smoke and reform validation (including the stacked OBBBA states) turn each reform into totals before they open the next, the demographics and holdout consumers score only the baseline, and the probe and sweep tools call the same consumers.
- For one scope at a time, which is how the head-to-head scorer uses it,
temporary_engine_variable_modulesremoves and restores exactly what it did before. - The branch merges cleanly with current
main, which hasn't changed the post-export consumers, the scorer orengine_lifecycle.pysince your base. The merged release tool keeps #1697's matrix drop beside this branch's reform lifecycle.
Before merge
- Let CI finish on this head. engine-us passed at
b780d8587, includingtest_reform_passes_leave_no_rule_modules_behind_and_score_the_same, and onlytest_worker_pool.pyhas changed since. engine-free failed there intest_process_memory_bytes_sees_this_process_grow, which47bf7bb0brewrote.
Checked
- All 63 tests in
test_worker_pool.pypass locally, and so do the first 100 of the 107 engine-free tests intest_us_post_export_scoring.py,test_us_release_slice_memory.pyandtest_us_release_head_to_head_scorer.py, including the five worker set-ups oftest_spawned_workers_score_identically_to_sequential_cli. The last 7 scorer tests were still running when I posted. - I didn't rerun the engine test or the post-export memory figures.
anth-volk
added a commit
that referenced
this pull request
Nov 25, 2026
Conflicts resolved by keeping both sides: - _BatchedPostExportReform keeps main's finished-reform refusal and its removal of each reform's rule modules, and this branch's prefetch, which scores several keys of one reform in one pass; - the scorer keeps main's open-reform tracking and this branch's registered baseline plans; - the test helper _scorer takes both baseline_plans and variables_dir; - both branches' new tests are kept. The slow pre-OBBBA test reads the shared pass's values before opening the next reform, since opening it now finishes the earlier one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
added a commit
that referenced
this pull request
Nov 25, 2026
Brings in the shared worker pool (#1726), whose post-export scorer finishes a reform when the consumer opens the next one and refuses further keys from it. No conflicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
added a commit
that referenced
this pull request
Nov 25, 2026
Since the shared worker pool (#1726), the post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it further keys. The test's consumer opened all three reformed simulations before asking any, so the scored half of test_reform_requests_follow_the_order_of_first_asks raised on main. Its consumer now asks each reformed simulation for all its keys before opening the next, and still covers a repeated key, a simulation asked two keys, and an unasked simulation that keeps its number. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
added a commit
that referenced
this pull request
Nov 25, 2026
…ext opens The post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it any further key (#1726). A consumer that goes back to an earlier reformed simulation passes today's dry run and fails only in certification's scoring, after the export. The test expects the dry run to refuse it, for a key the simulation already asked and for a new one, and checks that the scorer refuses the same consumer. It fails on this commit: the dry run does not raise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
anth-volk
added a commit
that referenced
this pull request
Nov 25, 2026
The post-export scorer finishes a reformed simulation when the consumer opens the next one and refuses it any further key (#1726). The dry run's recorders now share its list of opened reforms, and a reformed simulation's recorder raises once a later one is open, so a consumer that goes back to an earlier reformed simulation fails the release's plan before the export instead of certification's scoring after it. No shipped consumer does; the recorded outputs' pinned digests are unchanged. The docs and changelog say so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22
added a commit
that referenced
this pull request
Nov 25, 2026
…he SPI forest release and the shared SIPP read (#931) Main took seven pull requests since cac12ab: #1724 (each kernel reads read-only views of its inputs instead of a deep copy), #1690 (the SPI stage-2 forests freed before each later fit), #1686 (the SIPP person file read once for its five donor tables), #1697 (release tools free large objects after their last use), #1726 (a shared worker pool), #1660 (the County Files ACS donor patch) and #1707 (New Zealand's geography layer labels). No feed or engine pin moves, so no file is re-pinned. Four files conflicted, all pins that both sides moved: the US spec-engine seed map and seed protocol, the UK loader and US spec pins, and the US F0 coverage report. Each is computed on the merged tree, and the coverage report is regenerated (--check passes; 41/41 inventory checks). Two of main's new tests needed this branch's code reviewed. - #1724's scan for writes into shared buffers finds np.add.at in two weight folds of the identity tool: _pre_split_household_weights, which this branch changed, and _pre_high_value_household_weights, which it added. Both write into the copy of the household weights that _pre_residential_household_weights makes and _pre_clone_fold and the folds pass along, so both findings are reviewed with their digests, and the helpers the reasons rest on take theirs, _pre_clone_fold included. - #1690's SPI forest-release test froze origin/main's SPI output and receipts; this branch's keyed draws move them, as the test foresees. The macOS arm64 digests are recorded from this code. Linux x86_64's need a recording under Docker, which this machine lacks, so those two tests skip there and the same-run checks still run. The owner-manager rule rewrites owned_company_carries_on_property_business after the draw, as it does the trade flag, and on the synthetic fixture's draws it moves one drawn person, so the flag joins the targets rewritten after the draw. Checks: main's changed tests, the pin tests and the kernel-binding test pass (1,931, then the shared-buffer scan's 99 and the SPI forest-release test's 48 after the two reviews), and so does the H2 clone-first test at one and four clones (34). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 25, 2026
This was referenced Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Tracker task 1.4 · 1 of project 15 (US build memory, CPU and run time).
Summary
microcosm.build.worker_pool, for household-batched policyengine-us work. Later tasks move their callers onto it: post-export scoring (2.3 · 1), target compilation (2.3 · 3), the population-wide input runs (2.3 · 4), local-area materialize (2.5 · 1) and the planner that sizes workers from the memory budget (2.6 · 2).The pool
WorkerPool(settings, initializer=..., initargs=..., unit_function=..., describe_unit=...).pool.map(units)yieldsunit_function(state, unit)for each unit, in unit order.spawn). The parent starts and tracks its own processes, with two one-way pipes to each, instead of usingProcessPoolExecutor. That's what lets it tell which unit a dead worker held and run that unit again.initializer(*initargs)runs once in each worker, and its return value is thestateevery unit in that worker receives.initargsare pickled and sent over the worker's own pipe once per worker start, after its process has started. So a frame passed there crosses once per worker, not once per unit.ProcessPoolExecutoreach start waited for the previous worker's imports: 36–44 s per start in Register the US head-to-head scorer as a Modal stage for the d844 run #1190's evidence.max_attemptsfailed starts in a row stop the run.max_units_per_workerreplaces a worker after K units. The replacement starts only after the old worker has exited, so no more thanworkersprocesses are ever alive.ProcessPoolExecutor, which the pool doesn't use.memory_cap_bytes, a thread in the parent reads each worker's memory everymemory_poll_secondsand kills a worker over the cap.VmRSS + VmSwap); on macOS, the physical footprint, which counts compressed pages.MemoryError. It gets up tomax_attemptsattempts in all (default 2).pool.report()lists every failed attempt and its cause, the worker starts, the most workers alive at once and the peak memory read.max_units_aheadunits (default twiceworkers), counted from the oldest result not yet handed back, are running or waiting with a result. That bounds what the parent holds while it waits for a slow unit.mapdrops each result once it has handed it back.worker_environmentsets environment variables in each worker as it starts, before it imports anything.close()never waits for the memory thread, which stops at its next poll. So a garbage collection that closes an abandoned map or the pool can't deadlock, whichever thread it runs in, and even while that thread holds the lock.pidfd), so a kill can't reach a different process that has been given the same process ID.multiprocessing.Process.startreaps every exited child of the parent outside that lock, including during the pool's own worker starts, and so doesmultiprocessing.active_children(). That leaves a window of microseconds in which a worker's process ID could be reused before a kill lands.SIGCHLDset toSIG_IGN) is still noticed, through its exit pipe.The 1-vs-N byte-identity helper is
test_support/microcosm_build/worker_pool_identity.py.assert_identical_across_worker_counts(run, worker_counts=(1, N))runsrun(workers)at each count and compares canonical bytes, then names the first place that differs.attrsand aDatetimeIndex's frequency. A MultiIndex compares by each level's values, so equal ones built differently match._metadata(aMicroSeries' weights) and anndarraysubclass's attributes (anEnumArray's enum class).0.0against-0.0, NaNs with different bits,int32againstint64,Trueagainstnp.True_, and twoMicroSerieswith different weights all count as different.TypeError, rather than being compared some approximate way.The head-to-head scorer
--workersslices run on the shared pool. The scorer'sProcessPoolExecutorcode and its Python-version refusal of--worker-max-slicesare removed.2cfe3043d, so its planned d844 run is unaffected. If Register the US head-to-head scorer as a Modal stage for the d844 run #1190 moves to a newermain, its go/no-go estimate, which modelsProcessPoolExecutor's on-demand worker starts, needs re-checking: the shared pool starts its workers itself, up to the worker count.Post-export rule modules
sys.modulesfor every system it builds and never removes them.temporary_engine_variable_modulesremoves them; the head-to-head scorer already uses it.EngineVariableModuleScopeis an explicit open/close form of the helper, andtemporary_engine_variable_modulesnow uses it. A scope left unclosed does nothing when collected.salt_refund_income_neutralizationleaves a whole copy of the rules and parameters alive (about 1.3 GiB). Follow-up task 1.4 · 5 investigates it.Tests
Only the tests this PR adds or changes were run, each by node ID. No full suite was run.
engine_free/shared/test_worker_pool.py: all 52 test functions (59 cases), 59 passed.engine_free/us/test_us_release_slice_memory.py: the 7 new tests, which passed.engine_lifecycle.pythat this PR doesn't change; both passed.engine_free/us/test_us_release_head_to_head_scorer.py: the 7 changed or new tests, includingtest_spawned_workers_score_identically_to_sequential_cli(about 11 minutes here).engine_free/us/test_us_post_export_scoring.py: the 6 new tests.engine_workflow/us/test_us_post_export_scoring.py::test_reform_passes_leave_no_rule_modules_behind_and_score_the_same.tools/ci_test_plan.py verify,ruff checkandruff format --checkon the changed files pass, and the branch merges cleanly withorigin/mainatcac12ab01.b780d8587sets each cap test's cap 256 MiB above an idle worker's measured peak.Review rounds
Pool: 8 findings, all reproduced, 4 of them only by forcing the order in which threads run. They included:
close()ran under the lock;All are fixed. Six have a failing test committed first; two (two threads starting a map at the same moment, and a reading charged to the next unit in a microsecond gap) are fixed by holding the lock and have no test.
Integrations: no defects in the scorer or post-export scoring. Seven findings: three in the identity helper (subclass state, MultiIndex slices, numpy scalar types and unencodable pandas values), three module-scope edge cases no shipped code reaches, and one inaccurate changelog sentence.
Known limits
microcosm.build, because the worker's entry point is in this module. That includes torch and pandas: about 3.6 s and 220 MiB on the Mac, before the initializer runs. Task 1.5 · 1 (import torch only where it's used) reduces this. Callers' workers importmicrocosm.buildanyway.maphands out units before it yields a result, but not while the caller is working on that result. A caller that does slow work between results leaves those workers idle. The head-to-head scorer's work between results is small.Not in this PR
worker_environmentonly passes through values a caller supplies.🤖 Generated with Claude Code