Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
5544900
Add failing tests for pooled post-export scoring
anth-volk Nov 26, 2026
bd0dbfa
Score post-export requests in the shared worker pool
anth-volk Nov 26, 2026
2b046b5
Add failing tests for pooled post-export scoring as the default
anth-volk Nov 26, 2026
ee45d49
Make pooled post-export scoring certification's default
anth-volk Nov 26, 2026
78a7387
Add failing tests for review round 1 of pooled post-export scoring
anth-volk Nov 26, 2026
0ed588a
Fix review round 1 of pooled post-export scoring
anth-volk Nov 26, 2026
d757040
Add a failing test for Route A exporting MICROCOSM_POST_EXPORT_WORKERS
anth-volk Nov 26, 2026
d77e4e4
Export MICROCOSM_POST_EXPORT_WORKERS from Route A's settings
anth-volk Nov 26, 2026
839acb1
Add failing tests for review round 2 of pooled post-export scoring
anth-volk Nov 26, 2026
669b00f
Fix review round 2 of pooled post-export scoring
anth-volk Nov 26, 2026
b81cd6c
Add failing tests for review round 3 of pooled post-export scoring
anth-volk Nov 26, 2026
bcf9863
Fix review round 3 of pooled post-export scoring
anth-volk Nov 26, 2026
1f9bc17
Re-pin the post-export plan record's digest for the raised method label
anth-volk Nov 27, 2026
5a46f0c
Merge remote-tracking branch 'origin/main' into claude/pooled-post-ex…
anth-volk Nov 27, 2026
829c58e
Expect PostExportPoolStoppedError after a pool that could not start
anth-volk Nov 27, 2026
29cd5da
Test that the US export sampler can leave named columns out and keeps…
anth-volk Nov 27, 2026
bf9d93d
Let the US export sampler leave named columns out and keep the export…
anth-volk Nov 27, 2026
879f11e
Test that the export probe takes the held-out reports from the releas…
anth-volk Nov 27, 2026
c366eb3
Take the export probe's held-out reports from the release tool
anth-volk Nov 27, 2026
274dbde
Merge main (household batch helpers moved to household_batches) into …
anth-volk Nov 27, 2026
9882103
Test that pooled post-export scoring runs every baseline pass in the …
anth-volk Nov 27, 2026
62978a9
Run every pooled baseline pass in the certifying process before the p…
anth-volk Nov 27, 2026
6eed915
Test review round 1's findings on baseline passes in the certifying p…
anth-volk Nov 27, 2026
3ad85e7
Fix review round 1 on baseline passes in the certifying process
anth-volk Nov 27, 2026
b0cd785
Test review round 2's findings on kept baseline errors and probe rows
anth-volk Nov 27, 2026
a476328
Fix review round 2 on kept baseline errors, probe rows and docs
anth-volk Nov 27, 2026
620e6af
Test that a merged baseline pass stopped by a termination stops scoring
anth-volk Nov 27, 2026
ce2c33c
Fix review round 3: stop at once when a termination ends the merged pass
anth-volk Nov 27, 2026
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-export-sampler-drop-column.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`tools/sample_us_export_households.py --drop-column NAME` (repeatable) leaves a stored column out of the subsample, so the current post-export stages can run on a published export that stores a column a later export contract refuses. It refuses a name no table stores, the household weight and the id and membership columns; the post-write check expects exactly those columns to be absent, and the receipt lists them under `output.dropped_columns`. The subsample now takes the name of the `--export` path as given rather than of the file a link resolves to (a Hugging Face cache snapshot's blob, named by its hash), and a subsample that would replace that link is refused.
1 change: 1 addition & 0 deletions changelog.d/us-pooled-post-export-scoring.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
US certification scores post-export stages in the shared worker pool by default (`_PooledPostExportScorer`), with tracker decision 1.4 · 6's settings: `MICROCOSM_POST_EXPORT_WORKERS` unset or `auto` starts at most min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers and refuses, before the build is placed, a machine with no room for one; a positive number starts that many, and `serial` scores in the certifying process as before; each worker is replaced after 2 units and capped at max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers). Every baseline pass runs in the certifying process with the serial scorer's code, when the first stage opens and before any worker starts: the merged pass, and, if it raises, every stage's own pass, each stage then served its values or its error (Anthony's decision of 27 November, after the 5% export probe showed one 2,000-household batch's baseline pass going over the 5.25 GiB worker cap). The pool then runs one unit per reformed simulation, holding its recorded passes, and each post-export stage runs in the certifying process over the results, refusing any request, or any reform, its engine-free dry run did not record; the smoke check's and reform validation's builders mark each reform with the description it was built from. A unit that fails on every attempt fails the stage that asks for it, and the pool goes on with the rest in fresh workers; a worker refuses a release tool whose bytes differ from the certifying process's. Every output file and both manifests' consumer records are byte-identical to the serial scorer's; the manifests' `post_export_scoring` block records how scoring ran under `execution`, as run metadata. `POST_EXPORT_SCORING_METHOD` is raised once, to `household_batched_written_h5_v2`, for the merged baseline sweeps and pooled scoring (decision 1.1 · 1), so a build recorded with the earlier label is certified with the code it was built with. A changed batch file stops pooled scoring's baseline passes instead of falling back to per-stage passes, the held-out reports stop certification when the pool fails, and `tools/probe_us_post_export.py` registers every stage's baseline plan and the held-out reports' (certification's shared baseline pass), taking the held-out reports from the release tool's `_post_export_holdout_consumers`, can score in the pool and writes each pass's time and memory to `passes.jsonl`, naming the process that ran it; its household row map reads one batch file at a time.
5 changes: 4 additions & 1 deletion docs/agent-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,10 @@ tier's `releases/<release>/`, runs only
`microcosm-publish-release-build --preflight-only`, which checks the build
offline, and leaves publication to Max.

The US fiscal-refresh builder scores its written H5 in household batches.
The US fiscal-refresh builder scores its written H5 in household batches,
with the reform passes in the shared worker pool unless
`MICROCOSM_POST_EXPORT_WORKERS=serial`
(see [the release build rule](us-release-build-rule.md#post-export-scoring)).
Alongside its out-of-sample reports, it writes
`us_ssi_social_security_holdout.json`: the household-weighted share of SSI
recipients also receiving Social Security at ages 18–64 and 65+, compared with
Expand Down
145 changes: 135 additions & 10 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,18 +492,143 @@ one Microsimulation over the whole file.
- `_record_post_export_request_descriptors` runs the same dry run and returns
every request, baseline and reform, as a picklable `PostExportRequest`
(`microcosm.build.us_runtime.post_export_requests`), which a process started
with `spawn` can unpickle; the release itself still takes only the baseline
plans and reform-pass counts. A `prefetch` of several keys of one reformed
simulation is one pass, and its keys follow in ascending period order, as
the scorer computes them. A reform request holds
with `spawn` can unpickle, and the reform passes the scorer runs for them.
A `prefetch` of several keys of one reformed simulation is one pass, and its
keys follow in ascending period order, as the scorer computes them. A reform request holds
the description its stage builds the reform from: the smoke probe, the
reform-validation spec, or a cumulative OBBBA state's parameter changes. The
dry run builds no reform, and refuses a reform it cannot describe or pickle.
It also refuses a key asked of a reformed simulation after its stage opened
the next one: the scorer finishes a reformed simulation when the next opens
and refuses it further keys, so the plan fails before the export instead.
Nothing records the descriptors; the guard sweep below rebuilds each reform
from its descriptor in the worker that scores it.
Nothing records the descriptors in a file; pooled scoring (next item) and
the guard sweep below rebuild each reform from its descriptor in the worker
that scores it.
- Certification scores the reform passes in the shared worker pool by
default (`_PooledPostExportScorer`, `microcosm.build.worker_pool`), after
running the baseline passes itself, and the stages run afterwards in the
certifying process, over the results. The worker
settings are tracker decision 1.4 · 6's, until task 2.6 · 2's planner
replaces them (`plan_post_export_workers` in
`microcosm.build.us_runtime.post_export_pool`):
- `MICROCOSM_POST_EXPORT_WORKERS` unset, blank or `auto`: at most
min(usable cores − 1, ⌊(0.75 × memory − 3 GiB) ÷ 5 GiB⌋) workers, at
least one. Usable cores are the CPUs the process may run on, limited by a
cgroup CPU quota; memory is the machine's, limited by a cgroup memory
limit (`microcosm.build.host_resources`). 0.75 is decision 1.1 · 2's
budget, 3 GiB the certifying process's planned peak and 5 GiB one
worker's. On a machine under about 10.7 GiB that leaves no room for one
worker, and certification refuses before it places the build or loads
the H5.
- A positive whole number: that many workers (`1` is one worker, a process
of its own), whatever the formula gives; `serial`: every pass in the
certifying process, as before. Anything else stops certification at the
same point.
- Each worker is replaced after 2 units and capped at
max(5 GiB, (0.75 × memory − 3 GiB) ÷ workers) of memory footprint; a
worker over its cap is killed and its unit runs again in a fresh worker.
No more workers start than a pool run has units.
- Certification prints the plan: the workers, the planned peak beside the
budget and each worker's cap. `tools/probe_us_post_export.py` reads the
same setting the same way.
- Every baseline pass runs in the certifying process, with the serial
scorer's own code, when the first stage opens and before any worker
starts (Anthony's decision of 27 November). First the shared baseline
pass. If it raises (`MemoryError` included), every stage's own baseline
pass runs next, in the order the stages run, where the serial scorer runs
each one when its stage opens; a stage whose own pass raised gets that
error when it opens, with the original traceback as a note, and the
exceptions it was raised from or while handling, so the build's run
outcome still reads them (out of memory). A changed batch file, or an
error raised while the build is being interrupted or terminated, in the
shared pass or a stage's own, stops scoring at once. Each batch engine is released before
the next is built, so no baseline engine is held in the certifying
process while workers run.
- After a failed shared pass this differs from the serial scorer in time
and memory, not in values: every stage's own pass runs when the first
stage opens (the export probe's held-out reports' too, which it never
opens), so the build telemetry and the probe count them all under that
stage, and a stage whose own pass failed gets its error only after the
other stages' own passes have run. Every stage's own values are held
until that stage opens or the scorer closes; a key several stages plan
is held once per stage.
- The pool then runs one unit per reformed simulation, holding all of that
simulation's recorded passes over every batch, in the order the stages
run: a worker builds the reform's rules once per unit, as the serial
scorer builds them once per reformed simulation. A build whose stages
open no reform starts no pool.
- Why: the worker cap is sized for reform passes. In the pooled export
probe on a 5% sample of a published file (27 November), a baseline pass
over one batch of 2,000 households went over the 5.25 GiB cap on every
attempt, the shared pass at 5.37 and 5.38 GiB and the smoke's own pass
at 5.43 and 5.34 GiB, while the reform passes peaked at 1.35 to 2.00
GiB. Certification's batches are up to 5,000 households.
- A worker reads each batch from the scorer's batch file, refusing one that
changed, and scores it with the serial scorer's own code
(`_score_post_export_batches`): one engine per batch, keys in ascending
period order, the population-aggregate refusal in a pass over more than
one batch, and the baseline-branch refusal and the behavioral-response
check of a reform pass.
- A failure in a worker comes back with the unit's results. The certifying
process raises it when the stage asks for that pass, where the serial
scorer would have raised, as an error with the worker's exception's class
name and message, so a held-out report that records the error records the
same text. A changed batch file raises `PostExportBatchFileError`. A unit
that failed on every attempt (its worker ran out of memory, went over its
cap or died) raises `WorkerPoolUnitError` in the stage that asks for it,
even when it failed while workers were still running an earlier stage's
units, and the pool goes on with the other units in fresh workers. The
shared pool stops a run at such a failure, so the units then in flight,
the one due among them, start again in the fresh pool. When the pool's
workers cannot start, the first request that needs them raises the
pool's `WorkerPoolError` and every later one `PostExportPoolStoppedError`;
a stage's baseline values, scored in the certifying process, are still
served. When the pool cannot be built at all, the first stage's opening
raises that error and every later stage is refused with
`PostExportPoolStoppedError`, as after a changed batch file. Each of
these stops certification, the held-out reports included, where the
serial scorer, which has no memory cap, may have finished: the first
stage's error is the pool's or the batch file's own, and every later one
is a `WorkerPoolError`.
- Each stage then runs as in the serial path and builds its own reforms (the
smoke records each list edit's resolved lists from its own). Its baseline
is served its recorded plan, and each reformed simulation its recorded
passes in order. Each stage's own builders mark every reform they build
with the description they built it from, and each reformed simulation
must be opened with the reform the dry run recorded at that place. A
stage that asks for anything else is refused, so a stage whose requests
depended on the values it got back cannot be served values scored for a
different request or another reform. Each key's per-batch values are
joined in batch order, so every output, both manifests' consumer records
and the smoke's scoring record are byte-identical to the serial scorer's.
- Workers inherit the certifying process's environment, thread variables
included, unless the pool settings set others, and each is given the
process's policyengine-us lock-check record
(`MICROCOSM_ENGINE_ABI_LOCK_CHECK_RECORD`), so its import of the release
tool skips the lock-file check. A worker spawned from certification runs
certification's script again as `__mp_main__`, which imports the release
tool; that is the import the worker needs, so it runs once per worker
start. A worker refuses to start with a release tool whose bytes differ
from the certifying process's, so a tool file changed during a run cannot
mix two versions' results (the microcosm packages are not checked).
- The manifests' `post_export_scoring` block records how scoring ran under
`execution`: `{"mode": "serial"}`, or the pool's settings, how the worker
count was chosen, the plan's memory and core readings, the number of
reform units, each baseline pass run in the certifying process (its
label, keys, wall and CPU time, and error if it raised), that process's
memory footprint when the workers started, why the shared pass fell back
if it did, and the report of every pool the scorer ran
(worker starts, failed attempts, peak worker memory). That record is run
metadata, outside every output comparison (decision 1.1 · 1).
- The 5 GiB per worker comes from reform passes (1.4 · 6's one-batch check
peaked at about 3.5-4.7 GiB over two reform passes of 2,000 households).
The plan's 3 GiB for the certifying process applies while workers run,
after its baseline engines are released; its peak during the baseline
passes is the serial scorer's, with no worker running. Neither figure
has been measured at certification's 5,000-household batches, and freed
memory is not always returned to the system. The execution record
reports the process's footprint when the workers start, so a run shows
how it compares with the 3 GiB; nothing checks it or changes the plan.
- Each batch engine keeps policyengine-us's projection of the release year to
its last CPI-U year (2035), because the plans request keys in later years
(reform validation reaches past 2025). The build's own simulations hold
Expand Down Expand Up @@ -590,10 +715,10 @@ counts and the scored H5 digest.
Run this fixture sweep before R4's full-export timing steps, and repeat it
after a probe, spec or engine-lock change before starting a release.
R4's existing full-export rehearsal times the smoke and validation
baseline plans plus three selected reform passes (`tools/probe_us_post_export.py`
still scores each stage's baseline plan in a pass of its own, which the release
no longer does); it does not cover every
reform and does not replace this sweep.
baseline plans plus three selected reform passes; it does not cover every
reform and does not replace this sweep. `tools/probe_us_post_export.py`
registers every stage's baseline plan and the two held-out reports', as
certification does, so its baseline is certification's shared pass.

`calibration_diagnostics.json` records the plan under `build.post_export_scoring`
(method, batch size, batch count, each stage's baseline keys and periods), and
Expand Down
129 changes: 129 additions & 0 deletions packages/microcosm-build/src/microcosm/build/host_resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""How much memory and how many CPU cores this process may use.

Builds size their worker pools from the machine they run on (decision 1.1 · 2:
a budget of 75% of memory, and only the cores the process may use). These two
readings are what that sizing starts from:

- :func:`usable_cores`: the CPUs this process may run on
(``os.process_cpu_count()``, which follows the CPU affinity mask, so
``taskset`` and container cpusets, and ``PYTHON_CPU_COUNT``), limited by a
cgroup CPU quota rounded up (cgroup v2 ``cpu.max``, v1 ``cpu.cfs_quota_us``
over ``cpu.cfs_period_us``). These are ``joblib.cpu_count()``'s rules
without ``LOKY_MAX_CPU_COUNT``, which the release tool fills with its
thread count.
- :func:`total_memory_bytes`: the machine's physical memory, limited by a
cgroup memory limit (v2 ``memory.max``, v1 ``memory.limit_in_bytes``), as a
container such as Modal's is limited.

The cgroup files are read from ``/sys/fs/cgroup`` on Linux only; a file that is
absent or cannot be read as a limit sets none. Pooled post-export scoring
(tracker task 1.4 · 7) uses these; task 1.8 · 1 adds the budget options on top.
"""

from __future__ import annotations

import math
import os
import sys
from pathlib import Path

__all__ = ["total_memory_bytes", "usable_cores"]

_DEFAULT_CGROUP_ROOT = Path("/sys/fs/cgroup")


def _cgroup_root(cgroup_root: Path | None) -> Path | None:
if cgroup_root is not None:
return Path(cgroup_root)
if sys.platform.startswith("linux"):
return _DEFAULT_CGROUP_ROOT
return None


def _read(path: Path) -> str | None:
try:
return path.read_text().strip()
except OSError:
return None


def _cpu_quota(root: Path) -> float | None:
"""The cgroup CPU quota in CPUs, or ``None`` for none."""
text = _read(root / "cpu.max")
if text is not None:
fields = text.split()
if len(fields) == 2 and fields[0] != "max":
try:
quota, period = int(fields[0]), int(fields[1])
except ValueError:
return None
if quota > 0 and period > 0:
return quota / period
return None
quota_text = _read(root / "cpu" / "cpu.cfs_quota_us")
period_text = _read(root / "cpu" / "cpu.cfs_period_us")
if quota_text is None or period_text is None:
return None
try:
quota, period = int(quota_text), int(period_text)
except ValueError:
return None
if quota > 0 and period > 0:
return quota / period
return None


def usable_cores(
*, cpu_count: int | None = None, cgroup_root: Path | None = None
) -> int:
"""The CPU cores this process may use, at least one.

``cpu_count`` replaces ``os.process_cpu_count()``, and ``cgroup_root`` the
cgroup directory, for tests.
"""
if cpu_count is None:
cpu_count = os.process_cpu_count() or 1
cores = max(1, int(cpu_count))
root = _cgroup_root(cgroup_root)
if root is not None:
quota = _cpu_quota(root)
if quota is not None:
cores = min(cores, max(1, math.ceil(quota)))
return cores


def _memory_limit(root: Path) -> int | None:
"""The cgroup memory limit in bytes, or ``None`` for none."""
for relative in ("memory.max", "memory/memory.limit_in_bytes"):
text = _read(root / relative)
if text is None:
continue
try:
limit = int(text)
except ValueError:
# cgroup v2 writes "max" for no limit.
return None
return limit if limit > 0 else None
return None


def total_memory_bytes(
*, physical_memory_bytes: int | None = None, cgroup_root: Path | None = None
) -> int:
"""The memory this process's machine or container has, in bytes.

``physical_memory_bytes`` replaces the machine's physical memory
(``SC_PHYS_PAGES`` pages of ``SC_PAGE_SIZE`` bytes, the same as
``hw.memsize`` on macOS), and ``cgroup_root`` the cgroup directory, for
tests. A cgroup v1 limit of "no limit" is a number near ``2**63``, which
the physical memory then bounds.
"""
if physical_memory_bytes is None:
physical_memory_bytes = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
total = int(physical_memory_bytes)
root = _cgroup_root(cgroup_root)
if root is not None:
limit = _memory_limit(root)
if limit is not None:
total = min(total, limit)
return total
Loading
Loading