Skip to content

Move the US engine to policyengine-us 2.145.3 and prepare the Route A national build - #1676

Merged
juaristi22 merged 51 commits into
mainfrom
us-engine-refresh-route-a
Nov 30, 2026
Merged

juaristi22 merged 51 commits into
mainfrom
us-engine-refresh-route-a

Conversation

@juaristi22

@juaristi22 juaristi22 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Moves the US engine to policyengine-us 2.145.3 (core 3.36.1, spm-calculator 1.1.0) and makes main ready for the next US national build through Route A, with the operator runbook in docs/us-national-build-runbook.md.

Base: #1559, #1635, #1664, #1672, #1677 and #1681 have landed on main, and this branch has merged main at 7ff5a26bc (with #1663, #1666 and #1682).

Data improvements this build picks up

Before the build

  • Done: A US build has no tier: certification chooses it, at the build's commit or a later one (#1585 item 11) #1681, María's follow-up to Build a US national release and stop; certify it as a separate step (#1585 item 11, PR 4a) #1672 (rulings 1 and 3), is merged here. The build has no tier, and certification chooses it; certification may run at a later commit only when that commit changes tests, docs, changelog fragments or the standing owners register, so a fix to code needs a new build (runbook section 7).
  • The build comes from this PR's own tree, before it merges: the release build rule asks a change this size for a from-scratch build and certification receipt from its own tree before it merges. The operator builds at this PR's head, pinned by its full SHA, with REQUIRE_ON_MAIN=0 and from a checkout of that commit, and certifies at the same commit, so the PR stays open for fixes. A fix to code after the build means a new build at the new head. The PR then merges with a merge commit, so the built commit lands in main's history.
  • Done: Max's review of A US build has no tier: certification chooses it, at the build's commit or a later one (#1585 item 11) #1681, its four points and its smaller ones, is addressed here (commits 21 and 22), and so are his reviews of this PR at d596fcb60 and bd4ff48a6 (commits 27 and 28). Later review notes that change nothing a build does when it follows the runbook go into the PR that stacks on this one for the local-area path, so the build commit was ba410438e. Its quick check stopped at the base's child-support gate, and commit 31 lowers that gate's floor for each support channel, so the build commit is now 12693b9db, this PR's last commit. The base starts again at that commit: it cannot resume across a code change.
  • The build is assessed before it is certified, one command per step (runbook section 4):
    • The quick check first (about 2 hours): the base, its preflight and the release-gate dry run, with the gate battery shadow on, then a stop. One command reads it with US gates in us/gates.json, run in shadow beside today's gates (#1585 item 11, PR 2 of 4) #1635's pass rules. When it is clean, the operator goes straight on to the build; when it finds something, the evidence comes to María first.
    • Then the build (route_a.sh, about 7 to 9 hours) and its probe (route_a.sh --probe, about 10 hours, against about 48 for certification). The operator sends the run's evidence with the runbook's step 6 command, which collects the logs and records and leaves every data file on the laptop.
    • María assesses them, and the operator certifies with route_a.sh --certify only when she asks.
  • Done: María's rulings of 18 November on hosts, staging and publication (also in the runbook):
    • M1: the base runs locally for now.
    • M2: the build and its certification run on a laptop with enough memory, with the PUF inputs on it.
    • M3: the build and its certification upload progress and diagnostics to staging (ROUTE_A_STAGING=1).
    • M4: Lock the US engine to policyengine-us 2.60.4 #1365 is closed as superseded by this PR.
    • M5: María decides publication and promotion, and coordinates with Max.
  • Only for county files on 2.145.3: ACS local lane: re-review the reviewed-fill consumer register against policyengine-us 2.145.3 #1675.

Commits, in order

  1. Lock. The three US extras pin policyengine-us>=2.145.3,<3 and policyengine-core==3.36.1. uv then resolves one core for both forks, so the UK side moves from 3.34.10 to 3.36.1 too (ruled 17 November). The worker identity pin follows the new uv.lock.
  2. Route A. The driver runs on Linux (stat, df -P), the README has a Linux section, and STOP_BEFORE_RELEASE=1 stops before the release so its gates can be dry-run first.
  3. Take-up. 2.145.3 adds four take-up inputs, left at the engine default (rate_unsourced; everyone eligible takes up, as on 2.2.1). The ABI count moves from 17 to 21.
  4. Engine surface.
    • Social Security: 2.145.3 migrates a stored social_security_<type> to its _reported source, so levers apply (tested in the baseline and under a +10% reform). The adapter treats those names as inputs; columns keep their names.
    • The tax-unit first/second_home_mortgage_interest legs are gone from the engine (pe-us#9605). The PUF chain stops producing them, and the eCPS parity gate records the retired layers.
    • Seven stored-input register entries are now engine inputs and leave the register.
    • The ASEC channel follows the engine default estate_income_would_be_qualified = False.
    • The release copies the base's populace_location_rule onto its H5 (County Files: a proof-of-concept county-calibrated dataset by 23 November #1647).
  5. QRF tail (R7). The tail gate decides at base (pre-calibration) weights and reports the share at final weights in qrf_tail_concentration.json (schema 2) without failing on it. Collectibles gets a q0.999 donor bound.
  6. Frame adapter. The static consumer index reads the 2.145.3 formulas (Lock the US engine to policyengine-us 2.60.4 #1365's index extensions and helper reviews, ported and extended).
  7. SCF 2022 summary extract (The Fed replaced scfp2022s.zip on 2026-10-09, so the pinned SCF 2022 summary extract no longer downloads #1368). The build pins the Fed's republished file and divides its eight dollar columns by the CPI-U-RS ratio 4789/4376 on read; the original file is still read as it is.
  8. Tail dry run. The release's dry run grades the tail register on the base frame, with no calibration shift.
  9. Location attributes after the stored-input check (root attributes only).
  10. Re-pins of the pool engine contracts, engine ABI lock, generated bundle, F0 pins, release input-coverage manifest, year-window tripwires and reform probes, with the tests that pin them.
  11. Docs. The runbook, agent guide, release build rule and changelog fragments.
  12. More re-pins that the retired mortgage leg moves (late-producer counts, pool fixtures, the H3 parity fixture).
  13. ACS local register. Its engine-tier walk tests run only on the reviewed engine (2.2.1); the lane's release gate refuses the installed engine meanwhile. Re-review: ACS local lane: re-review the reviewed-fill consumer register against policyengine-us 2.145.3 #1675.
  14. Core 3.36.1 branch hook. Core 3.36.1's clone binds a copied method to the copy, so the release's batched target and reform materialization stopped with a KeyError. The hook now takes the parent from the call that made the branch, and refuses a simulation copied outside get_branch.
  15. Scenario and workflow tests on 2.145.3. Fifteen scenario tests move their pins with their contracts re-checked. Where the engine changed, the tests follow it: the ACA PTC, SNAP child support in California, the SALT refund probe (19 smoke baselines), the capped educator deduction, HUD gross rent with the utility allowance, and the self-employed health insurance limit.
  16. CI and review follow-ups. The UK spine parity graph re-pinned on core 3.36.1; the ACS stand-in engine; the battery's binding identity; engine-free re-pins the first CI rounds could not reach; the voluntary-filing probe's reason, which now says it measures the pre-take-up credit.
  17. Build a US national release and stop; certify it as a separate step (#1585 item 11, PR 4a) #1672. main merged with the location attributes written before the build record binds the H5, and certification reading them back from the written H5. The runbook now builds, then certifies.
  18. Rulings. The runbook records María's 18 November rulings on hosts, staging and publication (M1 to M5).
  19. A US build has no tier: certification chooses it, at the build's commit or a later one (#1585 item 11) #1681. main merged at cfd5a2a5e, with no conflicts. The location attributes are still written after the written-H5 stored-input check and before the build record binds the H5. A Route A test follows the release stage, which now also accepts a build that failed its gates (exit 3).
  20. Probe, then assess. The runbook probes the build on a 5% household sample (tools/sample_us_export_households.py, tools/probe_us_post_export.py) before María's assessment (certify, build again, or certify as evidence), and certifies only when she asks. The probe leaves out its QRF tail stage, which grades at final weights while the build decides that gate at base weights. S6 stops on a probe failure.
  21. Max's review of A US build has no tier: certification chooses it, at the build's commit or a later one (#1585 item 11) #1681, in the release tool (ea810f35f).
    • The certified tier refuses a failed source-coverage gate before it writes either manifest, as it refuses a failed smoke, so such a build can still be certified as evidence.
    • A failed build's H5 is a --base-h5 only beside an --export-input-mass-reference-h5: without one, the export input-mass gate judges the export against its base.
    • Certification adds every gate failure it finds to certification_failures.json beside the build record, at either tier, and a build that passed its own gates and then failed certification's is no reference until a certification ships it.
    • The build writes build_incomplete.json before its H5 and removes it once its record is written, so an H5 that no record pins is no reference either.
    • A standing evidence owner pattern owns a failure line only from the line's start, so input signal failed: no longer owns every gate ending in those words.
    • The summaries of what a later certifying commit may change name the root conftest.py, LICENSE and Markdown outside the packages' sources, and a publisher test covers version 2 staging blocks in a separately certified build.
  22. One command per step (18667a600).
    • route_a.sh dry-runs the release's gates on the fresh base as a stage of its own before the release starts (ROUTE_A_DRY_RUN=1, the default). A certain failure stops the run in minutes, and a dry run holds only for the release settings it checked.
    • route_a.sh --probe probes an accepted build as two supervised stages under the run directory, and stops.
    • From Max's review: the commit check requires the certification tool and parser on every run, whatever the tier. A rerun to build refuses release settings other than the accepted build's, which it would otherwise keep without a word, and --rebuild sets that build aside, keeping it on disk, to build the release again on the same base.
    • The runbook has one command per step and one command that collects a run's evidence. The README and the settings example follow.
  23. Bind England's PIP at 16–19 and 20–24, and impute UC limited capability for claims without a linked DWP record #1663. main merged at 6d32375b3 (8d33275f8). Only the UK spine graph-parity fixture conflicted. It is main's, with its 56 policyengine-core entries at 3.36.1, as this branch's generator writes them; nothing else in it differs from main's.
  24. Quick check first (6983bad4e). The runbook's first run stops after the base, its preflight and the release-gate dry run, each with the gate battery shadow on. Step 3 reads them with one command, applying US gates in us/gates.json, run in shadow beside today's gates (#1585 item 11, PR 2 of 4) #1635's pass rules, and prints QUICK CHECK CLEAN or what it found. The evidence then goes to María after the build and its probe, after the quick check only when it found something, and at any stop. S3 names the three shadow comparisons.
  25. The receipt from this PR's tree (d596fcb60). The runbook builds at this PR's head, pinned by its full SHA, with REQUIRE_ON_MAIN=0, as the release build rule asks of a change this size before it merges.
  26. Frame: share unchanged tables under copy-on-write, and refuse raw writes into shared buffers #1666 and Fill the QRF leaf array in place and pin quantile-forest 1.4.2 #1682. main merged at 7ff5a26bc (8a48bf6e2). The five pin files that Fill the QRF leaf array in place and pin quantile-forest 1.4.2 #1682's in-place QRF leaf array and the engine refresh both moved conflicted, as Max listed. Each takes this branch's side, and the pins both moved are recomputed on the merged tree: tools/repin_us_spec_engine_contracts.py rewrote the seed digests, the loader's golden vector and the pool tool's spec_sha256, and tools/spec_engine_coverage.py regenerated the F0 report (both --check pass). The worker's lock pin is the merged uv.lock's digest.
  27. Max's review of this PR (bd4ff48a6): five gaps on later or hand-run paths, none on the runbook's.
    • A probe after a failed certification gets the failed build's arguments, its fit and target surface, since the build is no reference.
    • Each attempt in certification_failures.json names the build and its record's digest, so a later build into the same --out inherits none.
    • build_incomplete.json goes down as the build creates its --out, before any file there, its diagnostics included.
    • The certification test reads structure, not line numbers.
    • Route A's rerun guard also compares the digests of what the release read by path: the base H5, the pinned release inputs and the export input-mass reference.
  28. Max's review of bd4ff48a6 (360357c58).
    • The driver runs from the checkout it is started in, and main's has no STOP_BEFORE_RELEASE and no --probe. The commit check now refuses a driver whose files differ from tools/route_a/ at the build commit, and the runbook says to check that commit out first.
    • The input check reads the export input-mass reference before any stage, so a file openssl cannot read stops the run before the base.
    • The certification register's writer keeps what its readers count, and a test runs the rerun guard's comparison.
  29. A test's run root (1382d2d10): the export reference test writes under its own temporary directory.
  30. Shellcheck (ba410438e): the driver's self-check writes its empty value as '', as shellcheck asks; nothing the driver does changes.
  31. Child-support channel floor (12693b9db). The quick check at ba410438e stopped at base stage 011: the PUF tax-detail channel drew a 0.18% nonzero share for child_support_expense, below the 0.002 floor for each support channel. The stage has not changed since the 3 November base, which passed. Its QRF trains on at most 5,000 ASEC people with the default in-sample sign gate, which draws a rare class below its rate, so the share is a noisy draw, and the move to the 2023-2025 ASEC pool changed its training sample. The floor is now 0.001, in the gate and in both gates.json entries; it still refuses a dead channel, and the pooled bands are unchanged. tools/diagnose_us_child_support_gate.py reruns the stage from a base's checkpoint, at the base's seed, further seeds and the cross-fitted sign gate, and never writes to the checkpoints. The battery scope digests and the F0 seed pins move with it.

What changes in outputs

  • The engine itself: 33 variables removed, about 1,660 added since 2.2.1; new default values for tenant_pays_utilities and living_arrangements_allow_for_food_preparation (now True); federal AGI now includes state tax refunds, estate income and taxable disability benefits.
  • Tax-unit roles now come from microunit instead of age ordering (pe-us#9617 measured -$0.94B of 2024 federal income tax on the certified build).
  • The QRF tail gate no longer fails a build for concentration that calibration adds; it reports it.
  • SCF wealth and auto-loan donors: the same values as before, to float precision.

Tests

Touched tests ran locally in an engine-free environment and in a 2.145.3 environment. The engine-free and US engine jobs stop at a process's first failure, so the whole engine-free list and every US scenario and workflow module also ran locally, and the UK H2 parity test ran on core 3.36.1. The full suite runs in CI.

After main was merged at cfd5a2a5e, the 44 engine-free test files that reach the release tool, Route A, the probe, the certify tool, the preflights or the publisher, or that read the changed docs, ran locally: 3,184 tests. One Route A test failed on the release stage's new text; it is fixed in 5c37a801c, and its file passes (118 tests). tools/ci_test_plan.py verify is ok. The engine jobs run in CI.

For commits 21 to 24, the engine-free test files they touch, or that read the changed docs, ran locally. Before the merge, the release tool's builder file (465 tests) ran first. Then 1,058 tests ran in two runs, covering Route A, the probe, its design, the release-gate dry run and preflight, the export tool's source, the spec bundle, the CI test plan, the logbook, the CI integration job, the publisher guard and the release contract. One Route A test failed: it pins the one place that removes ROUTE_A_BUILT.json, and --rebuild now sets that file aside instead. It is fixed in commit 22. After the merge with 6d32375b3, none failed: 930 tests across Route A, its ASEC pool, the Modal stage plans, the CI test plan and the graph acceptance files, and the builder file's 465. tools/ci_test_plan.py verify is ok. The UK spine parity test needs the UK engine, and shellcheck is not installed locally, so CI runs both. Commit 25 changes only the runbook.

After the merge with 7ff5a26bc, 4,182 engine-free tests ran locally, none failing: the spec-engine loader, the US stacked spine, spine blindness and pool H5 files, microcosm-fit's and microcosm-frame's engine-free suites, the graph executor and parity pins, Route A and the release tool's builder file. tools/ci_test_plan.py verify is ok. The re-pinned engine-contract and engine-workflow tests and the US bundle check need the US engine, so CI runs them.

For commit 27, 805 engine-free tests ran locally, none failing: Route A, the probe and its design, the release-gate preflight and dry run, and the release tool's builder file. tools/ci_test_plan.py verify is ok.

For commits 28 and 29, the Route A driver file (146 tests) and the release tool's certification tests (60) ran locally, none failing, and tools/ci_test_plan.py verify is ok. For commit 30, the driver file ran again at ba410438e, none failing; its shellcheck test needs shellcheck, so CI runs it.

For commit 31, the engine-free US and shared directories ran locally. Four tests failed, all pins: the us_base and us_national battery digests, re-pinned in the commit, and two F0 seed pins that the re-pin rewrote while the run was going. Those files, the child-support gate's and the new tool's tests, and the field-usage pins then ran with none failing. On 2.145.3, the pool tool, coverage tool and US spec bundle tests ran with none failing, and tools/repin_us_spec_engine_contracts.py --check and the bundle generator's --check pass.

Follow-ups (not in this PR)

  • The child-support PUF draw: its source is the QRF's rare-class draw, which is addressed in the QRF once the builds have completed (the cross-fitted sign gate). The channel floor's value then comes back for review.
  • Two Route A prefetch defects, worked around on the build laptop: the SCF prefetch ignores $SCF, and the SIPP pin names a Hugging Face revision that is missing.
  • weeks_worked is an input on 2.145.3 (policyengine-us#9660 Part A1). The pool still leaves it out; carrying WKSWORK weeks changes pool outputs, so it is its own change.
  • The Social Security component names stay as stored today; a rename to _reported is possible later.
  • unemployment_compensation_months is a new unemployment-insurance consumer of weeks_unemployed on 2.145.3.
  • The voluntary-filing PTC probe now measures the pre-take-up credit; moving it to a measure households receive is María's call.
  • The post-export probe's QRF tail stage still grades the export at final weights, and its fidelity check compares that with the build's qrf_tail_concentration.json, whose verdict is at base weights since 17 November. The runbook leaves the stage out; moving it to base weights is its own change.

Not settled here

Only a real build settles the risks listed in the runbook's section 6.

🤖 Generated with Claude Code

juaristi22 and others added 17 commits November 17, 2026 19:21
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The three US extras move from policyengine-us 2.2.1 / core 3.32.5 to the
newest release at lock time (2.145.3, 17 Nov), which needs core >=3.36.0
and spm-calculator 1.1. uv then resolves one core for both forks, so the UK
side moves from 3.34.10 to 3.36.1 as well (ruled 17 Nov). Core 3.35-3.36.1
adds a situation hook, an opt-in uprating base mode and a calculate_add
crash fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The driver used BSD stat and a df whose output wraps on Linux, so on a
Linux host every input failed its size check. file_bytes tries GNU stat,
then BSD stat; free_bytes reads df -Pk. The tests no longer shim stat,
so CI's runner exercises the GNU path.

STOP_BEFORE_RELEASE=1 stops after the base, the base preflight and the
release config, so the release's gates can be dry-run on the fresh base
(tools/dry_run_us_release_gates.py, #1042) before the multi-day release
(ruled for the next national build on 17 Nov 2026). The README gains a
Linux section (settings, tmux, systemd) and links the operator runbook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
policyengine-us 2.145.3 adds takes_up_medicare_part_d_if_eligible,
takes_up_csfp_if_eligible, takes_up_school_meals_if_eligible (SPM unit)
and takes_up_ak_permanent_fund_dividend_if_eligible, all defaulting to
true. The take-up mapping must be total over the engine, so each joins the
spec, the contract and the generator as an engine-owned program left at
its default (rate_unsourced, no locked source), as ruled on 17 Nov 2026.
That reproduces 2.2.1, which paid all four programs to every eligible
person. The ABI program count moves from 17 to 21, and each input gets a
battery metric and a take-up operator boundary entry. The engine ABI lock
is regenerated with the other re-pins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Mortgage legs (ruled R16): policyengine-us removed the tax-unit
  first/second_home_mortgage_interest legs (policyengine-us#9605). The PUF
  chain stops producing them; the person-level home_mortgage_interest
  carries the amount. The eCPS parity gate records the two retired
  reference layers instead of grading them (ported from #1365). The late
  transfer surface drops to 71 targets and the stacked surface to 139.
- Stored-input register: seven entries are engine inputs on 2.145.3
  (tax_unit_role_input, parent_1_id, parent_2_id and the four federal
  student loan inputs) and leave it. The pool's build-time simulation
  projection keeps microunit's tax-unit roles (#1027, ruled R14).
- QBI (ruled R10): the base ASEC channel keeps the engine's own
  qualification defaults; estate income now defaults to non-qualified.
- Location (ruled R17): the release copies the base's household-location
  root attributes onto its H5 and records them, so a block_v1 national
  file no longer reads as legacy to ACS staging (#1647).
- OBBBA estate row (ruled R13): noted as zero by construction, since
  estate_tax needs is_deceased, which no release stores.
- IRMAA holdout: the engine falls back to the earliest input year
  (policyengine-us#10106), so a single-year release now has payers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ruled 17 Nov 2026 (R7), the smallest fix for the tail failures of the
19 Oct and 3 Nov national runs:

1. The tail-concentration gate and its per-run register now measure the
   release's base frame at pre-calibration weights, where the QRF draw
   artifact the gate guards (#462) lives. On the 3 Nov base most columns
   that failed at final weights sat at 0.45-0.63 before calibration: the
   excess came from calibration putting weight on few carriers. The share
   at the export's final weights is still measured and reported in
   qrf_tail_concentration.json (schema 2, final_weight_report), and
   decides nothing. The gate shadow reads the same base frame, so both
   verdicts agree. The release dry run's tail margins default to zero,
   since its staged frame is now the release's own verdict.
2. long_term_capital_gains_on_collectibles, the one column above the
   threshold before calibration, gets the weighted donor q0.999 bound that
   non_sch_d_capital_gains has. Tail bounds now also apply to sparse
   snapped amount outputs, lowered onto the donor's snap grid so the snap
   cannot carry a value past them. #481 stays the root fix.

The route A example no longer passes the d490 register, which was measured
at final weights and would now read as stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Static consumer index (B3): ports #1365's index extensions and helper
  reviews and extends them for 2.145.3. Every helper a formula calls is
  reviewed at a code digest (71 reviews: 30 new and 13 re-reviewed since
  #1365). Six general readers cover the sites the index could not read
  (class attributes through get_variable, dict comprehensions, call
  defaults, getattr on parameter nodes, closures passed as arguments,
  helper results passed as arguments), and the digest follows imports
  made inside a helper.
- Generated-variable audit (B2): refreshed to 2.145.3 and spm-calculator
  1.1.0; the 120 generated variables are unchanged.
- Concept mapping (C6): reviewed against 2.145.3, with take-up bindings
  for the four new programs; the coverage golden is regenerated.
- Social Security (R4, revised): pe-us 2.145.3 migrates a stored
  social_security_<type> to its _reported source, so benefit levers apply
  (tested: the same values as storing _reported, in the baseline and
  under a lever reform). The adapter reads the migrated names from the
  installed engine and treats them as storable inputs with their default,
  and refuses a frame that stores both a name and its _reported input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Federal Reserve replaced scfp2022s.zip on 2026-10-09, when it published
the 2025 SCF. The file it serves now states every dollar value in 2025
dollars, and the pinned original is no longer served, so a fresh build
stopped at the SCF wealth stage on the digest check (#1368).

Ruled 17 Nov 2026 (option 2 of #1368): pin the republished file (zip
d4e139c6..., member 6ff73d52..., downloaded from federalreserve.gov on
17 Nov) and convert on read. read_scf_2022_summary_extract identifies the
file by its digest and divides the eight dollar columns Microcosm reads
(liq, stocks, nmmf, bond, networth, wageinc, intdivinc, ssretinc) by the
Fed's CPI-U-RS ratio 4789/4376; sentinel codes keep their value. The
records and weights are the original's: the weighted shares of nonzero,
positive and negative net worth equal the values recorded for the pinned
original. Values equal the original only to float precision. The original
2022-dollar member is still read as it is, so no file is converted twice,
and the reader records which case applied. Both SCF loaders (wealth and
auto loans, whose targets come from the unchanged full file) use it.
Route A's SCF input row moves to the new member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The release decides the QRF tail gate on its base frame at pre-calibration
weights, so its dry run grades the tail register on that same frame with no
calibration or L0-selection shift (support fixed, zero tail-share margins).
The dry-run module keeps its measured default margins (0.35, 0.05, 1.0) for
other callers. The imputation schema admits the collectibles q0.999 bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The release now carries the base's household-location rule onto its H5
after the written file passes the stored-input premise check. The
attributes are root metadata only and move no column, so the verdict holds.
The diagnostics test of the release main path stubs the base-location
reader, since its stub base is not an HDF5 file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Regenerated or re-measured on 2.145.3: the pool engine contracts, the engine
ABI lock, the generated spec bundle and its frozen legacy digests, the F0
coverage pins, the release input-coverage manifest (retired eCPS layers are
no longer required), the primary QRF target-order digest, the year-window
tripwires and the eCPS parity known-gap versions.

Reform probes: the above-the-line deduction list names educator_expense_ald,
and the SALT refund probe scores federal income tax (2.145.3 counts the
refund in gross income; about 29 state lists now read it, both ways).

Test pins follow the engine. Two engine changes shape them:
- 2.145.3 backdates every parameter to 2015 before it applies reforms, so
  the QBI list's first breakpoint at the first reform pass is 2015-01-01.
  The list-edit guard still refuses an edit there; a 2017 edit now holds
  only inside its period.
- Files built on 2.2.1 store the retired tax-unit mortgage-interest legs,
  which the stored-input check now refuses, and tax_unit_role_input is an
  engine input, so it left the register.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/us-national-build-runbook.md gives each stage's commands, environment,
inputs and secrets, time, memory and disk, success check and what to send
back, plus the risks only a real build settles. The agent guide and the
release build rule point to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The retired tax-unit first_home_mortgage_interest leg leaves the post-PUF
transfer (72 to 71 targets, 53 to 52 numeric) and the primary PUF pass
(two outputs and two inputs fewer). The pool fixtures, the late-producer
DAG pins and the operator-ordering doc follow. The H3 post-transfer parity
fixture is regenerated with its tool: its synthetic source gains the four
new take-up columns, and its expected cells do not change. The national
gate-scope digests move with the QRF tail gate's notes. Quote style follows
ruff format in the files the re-pins edited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
acs_local_reviewed_fill_consumers.yaml is reviewed against policyengine-us
2.2.1, and on 2.145.3 the consumer walk differs for 34 of its 59 entries.
The walk tests now run only on the engine the register was reviewed
against. One test checks that the ACS local release gate refuses the
installed engine meanwhile, so no local-area release can use the unreviewed
register. The re-review is microcosm#1675. The national release does not
run this gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since #1635's second round a verdict difference is recorded and printed as a
warning, and the release still finishes. S3 now has the operator read the
us_national comparison file after the release and report a difference, a
shadow error or a missing file with the hand-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@vahid-ahmadi vahid-ahmadi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed write-up. Three CI causes on 4477f5d, all from the engine move rather than flakiness, plus a note on the conflict.

engine-uk (3.13/3.14): H2 spine fixture still on core 3.34.10. test_h2_uk_spine_parity fails at packages/microcosm-graph/tests/engine/uk/test_acceptance_h_parity.py:45 (graph_from_json(uk_spine.json) == graph, differing nodes). Every node in packages/microcosm-graph/tests/fixtures/parity/uk_spine/uk_spine.json records ["policyengine-core","3.34.10"] in numerical_dependencies, and the lock now installs 3.36.1 for the UK side too. It is the only non-changelog file at head that still says 3.34.10. Regenerating the fixture with its tool should clear both UK jobs.

engine-free (3.13/3.14): ACS local packaging test still expects tax_unit_role_input in the register. test_package_records_the_stored_input_gate_bound_to_the_packaged_bytes (packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py:5597) now raises StoredInputRefusalError: stored column 'tax_unit_role_input' ... is not a variable in policyengine-us 2.2.1. f247728 removed the entry from US_STORED_NON_VARIABLE_COLUMNS, but the test's stand-in engine (_PACKAGE_ENGINE, :54-57) is still a 2.2.1 surface without that variable. The fixture still stores the column (:1300, :4091), and the expected gate lists it in registered_non_variables (:5622). One option is to give the stand-in engine tax_unit_role_input (and the 2.145.3 label) and drop it from the expectation. Whichever way it goes, the test should state which engine the ACS lane is graded against while #1675 is open.

engine-us (3.13/3.14): scenario tests pinned to 2.2.1. packages/microcosm-build/tests/engine_scenario/us/test_us_adult_care.py:11 fails with assert '2.145.3' == '2.2.1'. The scenario lane stops at the first failure, so this is only the first. At head, 15 scenario files still assert version("policyengine-us") == "2.2.1" unconditionally: adult_care, disability_benefits, educator_expenses, energy_subsidy, farm_business_income, housing_inputs, other_health_insurance, relationship_inputs, retirement_distributions, sipp_head_start, ssi_disability_criteria, ssi_take_up, voluntary_filing, wic_claim and workers_compensation. Each needs either a re-pin to 2.145.3 with its contract re-checked, like test_us_medicare_take_up.py:59, or an explicit skip if it stays 2.2.1-specific.

Conflict with main. The history is criss-cross (both sides merged #1559's head 826c5eb), so there are two merge bases. A plain recursive git merge origin/main comes out clean, with the result equal to this branch plus #1664's files. Against the single base 5499382 the only conflict is packages/microcosm-build/tests/engine_free/us/test_route_a_driver.py: main keeps the BSD stat() shim and this branch drops it for file_bytes. The branch's side is right. Note that the last CI run tested a merge with 4d287f4, before #1559 reached main, so merging main also gets a run against the current base.

Things that look consistent: the pyproject and uv.lock pins, the take-up contract constraint, the mortgage-leg retirement (_retire_ecps_reference_layers refuses it if the engine disagrees), the base-weight tail gate (export_frame is only a reweight of base_frame), the SCF deflator covering every summary dollar column the two loaders read, the location attributes written before the post-export scorer binds the sha256, and the Route A driver. Its only diff vs main after #1559 is the Linux portability, STOP_BEFORE_RELEASE, the SCF pin and the commented-out d490 register.

Review drafted with AI assistance and checked against the code at 4477f5d.

juaristi22 and others added 6 commits November 18, 2026 11:28
The release's target and reform materialization wraps get_branch to retain
every engine branch until a batch is checked. Core 3.32 copied the parent's
bound wrapper into a clone; core 3.36.1 rebinds it to the copy, so the hook
looked the copy up as its own parent and stopped with a KeyError. The hook
now takes the parent from the call that created or holds the branch, which
works with either behavior, and refuses a wrapper it cannot trace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Version pins move to 2.145.3. Where the engine changed, the tests follow it:
- ACA PTC: a unit that takes up coverage can claim without filing for
  another reason, so the voluntary-filing test uses a unit that does not.
  The probe's reason says so, and the runbook lists its reach as a risk.
- SNAP child support: California now excludes it from gross income.
- SALT refund: the probe scores federal income tax; South Carolina tax no
  longer moves, so the smoke needs 19 baselines, not 20.
- Educator expenses: the ALD list names the capped educator_expense_ald.
- HUD gross rent adds the utility allowance.
- The self-employed health insurance limit subtracts half of SE tax.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lock moves the UK side to core 3.36.1, which each UK graph node
records among its numerical dependencies. Regenerated with
tools/graph_uk_spine_fixture.py; only the core version changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stored-input register follows the locked engine, which defines the
tax-unit role as an input (policyengine-us#9617), so the stand-in engine of
the ACS local release tests defines it too. Its label stays the
reviewed-fill register's engine until that register's re-review (#1675).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…efresh

The only conflict is the us_national gate-scope digests in
test_us_battery_bindings.py: both sides moved them. They are re-measured on
the merged gates.json, which carries #1635's last edits and this branch's
base-weight tail gate note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stand-in engine's note now says it once: the lane's tests model a release
on the reviewed-fill register's engine (2.2.1), and the stored-input register
follows the locked engine (2.145.3), which defines tax_unit_role_input.
Review of #1676 (Vahid).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@juaristi22

Copy link
Copy Markdown
Collaborator Author

Thanks, Vahid. All four points are handled at 61c8fae6a.

  • UK H2 fixture. Regenerated with tools/graph_uk_spine_fixture.py in a UK environment on core 3.36.1. Only the recorded core version changes, and the test passes (6bb6830d5).
  • ACS stand-in. The stand-in engine defines tax_unit_role_input, and the expectation drops it (a25e54c9f). I kept the 2.2.1 label: an autouse fixture makes every lane test report the reviewed-fill register's engine (2.2.1) to the reviewed-fill gate, so a 2.145.3 label would give one simulated release two engines. The stand-in's note now says which engine the lane's tests grade against while ACS local lane: re-review the reviewed-fill consumer register against policyengine-us 2.145.3 #1675 is open (61c8fae6a).
  • Scenario pins. All 15 files are re-pinned with each contract re-checked on 2.145.3 (be8eb1225). Six needed more than the pin:
    • voluntary filing: a unit that takes up ACA coverage now gets the PTC without another reason to file, so the test uses a unit that does not;
    • child support: California excludes it from SNAP gross income;
    • SALT refund: the probe scores federal income tax, South Carolina tax no longer moves, and the smoke needs 19 baselines, not 20;
    • educator expenses: the ALD list names the capped educator_expense_ald;
    • housing: HUD gross rent adds the utility allowance;
    • self-employed health insurance: the earned-income limit now subtracts half of SE tax.
  • Hidden failures. The scenario lane stops at its first failure, so I ran every US scenario and workflow module locally. That found one real crash: core 3.36.1's clone binds a copied method to the copy, so the hook that retains engine branches in batched target and reform materialization stopped with a KeyError. Fixed in dc992cf7c; the batched-materialization and memory workflow modules pass.
  • Main. Merged bcb5cba9d (Pool main's default ASEC years in Route A (d2603) #1559, US gates in us/gates.json, run in shadow beside today's gates (#1585 item 11, PR 2 of 4) #1635, Add the US one-population selection library #1664). The only conflict was the us_national gate-scope digests, re-measured on the merged gates.json (ce509f268). The Route A driver test keeps this branch's side, as you suggested.

@vahid-ahmadi vahid-ahmadi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround. All four earlier points are resolved at 61c8fae6a:

  • The H2 fixture records core 3.36.1 on all 56 nodes.
  • The ACS stand-in defines tax_unit_role_input and the expectation drops it. Keeping the 2.2.1 label is consistent with _the_release_runs_the_reviewed_engine reporting the register's reviewed_against, and the note at test_us_acs_local_release_tool.py:56-61 explains the hybrid.
  • All 15 scenario files are re-pinned.
  • The merge is clean.

engine-free (3.13/3.14): one new module in the battery's binding identity. The only failure (1 failed, 9633 passed) is test_the_batterys_binding_identity_adds_only_the_leaf_and_its_imports, assert 247 == ((198 + 25) + 23).

  • Computed the same way as the test (binding_identity.describe over TRANSPORT_GATE_REGISTRY), the set holds 247 modules at this head and 246 at main bcb5cba9d.
  • The one extra is microcosm.frame.adapters._policyengine_us_helper_reviews, added in 0f51437 and imported by frame/adapters/policyengine_us.py:35 and _policyengine_us_source_index.py:19, both already in the closure.
  • Adding it to BINDING_MODULES_ADDED_AFTER_BASE (packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py:137) with a comment pointing at #1676 should clear both jobs (25 → 26 entries, 247).

Voluntary-filing probe: what it now measures. With takes_up_aca_if_eligible: False (test_us_voluntary_filing.py:37), the test passes because aca_ptc drops from 11,600 to 0.

  • In 2.145.3 the credit a household receives is assigned_aca_ptc = aca_ptc * takes_up_aca_if_eligible, which feeds premium_tax_credit, spm_unit_benefits and healthcare_benefit_value.
  • files_return_for_aca_ptc is true for every unit that takes up a positive credit. So neutralizing would_file_taxes_voluntarily cannot change assigned_aca_ptc for any unit.
    • On this household it is 0 in both runs with take-up off.
    • With take-up on, it is 11,600 in both runs.
  • The probe (tools/build_us_release_input_coverage_manifest.py:1447) still shows that the filing leaf binds into the graph. But its margin is the pre-take-up credit of units that don't enroll, and the reason text says it "removes the credit from otherwise eligible voluntary filers".
  • The engine rule matches 36B(a) and 1.6011-8(a), so this is about the probe's meaning, not a bug. It would help to say in the reason that the margin is pre-take-up aca_ptc, or to move the probe to a measure the leaf still reaches. The runbook already lists the $100M floor as a risk (docs/us-national-build-runbook.md:208).

Branch hook (dc992cf): small test gap. The fix looks right for both clone behaviors:

  • On 3.32 the wrapper's owner is recorded.
  • On 3.36 it falls back to parent, and parent_original.__func__ binds correctly to the child.

The engine-free fake still clones with copy.copy (test_support/microcosm_build/us_batched_target_materialization.py:118), which is the 3.32 behavior. Neither the rebind-to-copy case nor the new RuntimeError is tested outside the engine-workflow lane. A fake clone that rebinds instance methods, plus one refusal test, would keep this from regressing silently.

Things that look consistent:

  • The other five contract changes match 2.145.3 and the law:
    • CA takes the 273.9(c)(17) exclusion.
    • The SALT refund is in federal gross income and SC subtracts it. No other probe needs the state_income_tax baseline, so 19 keys.
    • educator_expense_ald is the 62(a)(2)(D)-capped amount.
    • HUD gross rent includes the utility allowance (24 CFR 5.603).
    • The 162(l) limit nets the attributable half of SE tax (Form 7206).
  • The re-measured us_national gate-scope digests pass on the merged gates.json, whose only change against main is the tail-gate note.

engine-us was still queued at the time of this review.

Review drafted with AI assistance and checked against the code at 61c8fae.

juaristi22 and others added 4 commits November 18, 2026 12:45
…ntity

The policyengine-us 2.145.3 frame adapter keeps the static consumer index's
helper reviews in microcosm.frame.adapters._policyengine_us_helper_reviews,
which the adapter imports, so the gate bindings reach one more module.
The engine-free job's --maxfail=1 stopped before this test in the first CI
round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The engine-free fake can now copy a branch as core 3.36's clone does, binding
copied methods to the copy, and the branch tests run under both clone
behaviors. A simulation copied outside get_branch carries the wrapper
without being recorded; its get_branch now refuses with a clear error (a
KeyError before), and one helper serves that refusal and the parent lookup.
Review of #1676 (Vahid, second round).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The probe still shows the filing leaf binds into the graph, but on 2.145.3 its
margin is the pre-take-up credit (aca_ptc) of voluntary filers who do not take
up coverage: the credit a household receives, assigned_aca_ptc, does not
move. The probe's reason, the runbook risk and the scenario test now say so.
Review of #1676 (Vahid, second round).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The engine-free job stops at its first failure, so a full local run found
six more files on the 2.145.3 lock:
- the engine ABI fakes now follow US_TAKE_UP_PROGRAM_COUNT (21);
- the primary QRF target order holds 64 targets (the mortgage legs left);
- the SALT refund probe is positive on income_tax, and the smoke needs 19
  baselines;
- the release's location-attribute writer is a registered HDF write site
  (root attributes only);
- the legacy pool publication manifest re-pins its checkpoint identity
  (pool_h5 and agreement unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@juaristi22

Copy link
Copy Markdown
Collaborator Author

@MaxGhenis Pavel has certified the build from 12693b9db: microcosm-us-2024-national/populace-us-2024-3b3de63-12693b9db03d-20261127T193416Z. Would you like to inspect it and rule on its promotion?

I've also merged main into this branch, which now ends at d612aaa44. Would you like to review this PR once more before we merge it? Since your last review:

  • 4712f6364 merges main at 1d8b9b8dd. The UK extras now pin policyengine-core 3.34.10, so the UK side keeps main's core under policyengine-uk 2.180.0 while the US side moves to 3.36.1. The branch's core 3.36 fix to the branch recorder moves into household_batches.record_engine_branches (Refuse population aggregates in the US input-stage batch passes and release their engines (1.6 · 2) #1776). Main's pre-OBBBA scoring test (Shard and cache the US release's post-export scoring passes #1595) now marks its estate holder as deceased, since policyengine-us 2.145.3 charges estate tax only to a deceased person. The US pins were regenerated with policyengine-us 2.145.3 installed, in the repinner docstring's order.
  • d612aaa44 makes the child-support diagnosis tool refuse an --out that already exists (a hard link included) or that lies inside the checkpoint folder. It opens the report with mode "x" and checks containment with os.path.samefile, as your review suggested.

CI is running on d612aaa44. GitHub ran no CI on 12693b9db while the branch conflicted with main.

@juaristi22
juaristi22 marked this pull request as ready for review November 30, 2026 00:42
@juaristi22
juaristi22 requested a review from MaxGhenis November 30, 2026 00:42
juaristi22 and others added 3 commits November 30, 2026 01:23
…K label scan (#1676)

CI at d612aaa failed in two tests that came in from main and were written
on policyengine-us 2.2.1, and in a UK guard that the child-support diagnosis
tool from 12693b9 trips. The US engine job stopped each shard at its first
failure, so the rest of the contract-3 shard and the workflow files did not
run there. Here the whole contract-3 shard (52 tests), the reuse workflow
file (8) and the touched engine-free files (563) pass.

- us_household_pass_inputs (#1778) now follows the module-level helpers a
  listed formula calls, and the helpers those call: every function whose
  code is in the engine's source files. policyengine-core loads a variable
  file under a generated module name, so the helpers it defines have no
  policyengine_us module name, and neither the list nor its test's walk
  followed them. 2.145.3 reads charitable donations, the capital gains tax's
  main-rate tax, the self-employed health insurance limit's S-corporation
  wages and the CDCC's earned-income floor in such helpers: the SSI pass
  read one column and the Medicaid pass 20 that the list did not name. The
  behavioral-response measurements stay out, as the test pins.
- The engine-workflow trace allows the ID and membership columns, which
  every household's digest covers and which 2.145.3 reads while it computes
  Medicaid eligibility.
- The contract review of the stage columns is redone on 2.145.3. December
  uncapped_ssi's graph reaches eleven columns the stages between the SSI
  passes write, all through social_security_cola_means_test_withheld, which
  reads nothing while the COLA means test is off (it is in 2023 and 2024).
  is_medicaid_eligible's graph reaches the Medicaid take-up flag, like the
  SNAP one, only through work-requirement formulas that do not apply in
  2024. The graph identities are re-pinned, and the reuse tests' counts
  follow: SSI keeps every household after calibration alone and reruns all
  five once the stages' outputs are written; Medicaid reruns six of seven.
- The UK "<10" scan names tools/diagnose_us_child_support_gate.py, a US tool
  that reads no UK Data Service records, instead of failing on it.

Still failing: test_no_column_an_r2_stage_fills_is_an_agi_input. On 2.145.3
the county AGI pre-check's AGI graph reaches four take-up flags that R2's
stages fill, only through the 2020-only charitable_contributions_ald.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main's test_the_release_s_recorded_post_export_outputs_are_unchanged pins
digests taken on origin/main. This branch re-derives two shipped
reform-coverage probes and the estate-tax row's description for
policyengine-us 2.145.3, which moves the plan, smoke and validation digests.
With origin/main's release_input_coverage_manifest.json and
obbba_reforms.json in place, the test passes on main's pins, so those two
files account for the whole change. engine-free stopped there at 4bce790,
at 74% of its tests (--maxfail=1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main frees base_frame right after the export input-mass check, its last
reader on main, and releases the release engine right after the written
file's stored-input check. This branch's QRF tail-concentration gate takes
its verdict on base_frame (ruled 17 Nov 2026) and runs after the input-mass
check, so on the merged code it was passed None in place of the frame. git
merged the two sides without a conflict; main's
test_us_release_frees_after_last_use found it.

base_frame is now freed right after the tail gate, which keeps the gates'
order (input coverage, input-mass parity, QRF tail concentration, as
test_main_writes_diagnostics_before_post_calibration_gate_failure pins).
Between the two checks the build only writes input_mass_parity.json. The
freeing test expects the release after the tail gate, with the input-mass
check before it. The branch's household-location write moves to just after
the engine release: it writes root attributes only and needs no engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor

Agent-written for Max, by Claude Code for Max Ghenis.

@juaristi22, on making populace-us-2024-3b3de63-12693b9db03d-20261127T193416Z the US default, Max answers "not yet" at this PR's head, f3ec64e0f5. He'll leave the build published, and won't make it current, until three things happen:

  1. Someone merges this PR into main with a merge commit, on green CI. If someone squashes or rebases it, main never contains 12693b9db0, the commit Pavel built from. At f3ec64e0f5, both engine-us jobs fail on test_no_column_an_r2_stage_fills_is_an_agi_input (run 46359479496), and the branch conflicts with main in four files.
  2. Pavel adds the four child-support records that the build's published files lack:
    • a record that the production seed stayed fixed;
    • the diagnosis on the certifying base's checkpoints, with its aggregates;
    • the stop-and-escalate thresholds;
    • the base summary's child_support_signal block, with a one-line known issue.
  3. Someone runs a head-to-head in d844's form, with the scorer Register the US head-to-head scorer as a Modal stage for the d844 run #1190 registers, and the build beats today's default, populace-us-2024-spm-20260915.

Then he'll decide on the promotion. He hasn't answered your request to review this PR again.

juaristi22 and others added 2 commits November 30, 2026 11:49
Four files conflicted, each on pins that both sides moved:
spec_engine/inventory_coverage.py (seed_map, seed_protocol), the minimal
bundle's golden vector in test_spec_engine_loader.py, the US bundle's
spec_sha256 in engine_workflow/us/test_us_multispine_pool_tool.py, and
docs/evidence/spec-engine/us-f0-coverage.json.

#1538 (#931) adds functions to stochastic_assignment, one of the US seed
protocol's attested kernel modules (main's f055c15), and this branch moves
the same pins with policyengine-us 2.145.3. The resolution keeps this
branch's lines, adds a comment line for #931's move, and re-derives the pins
on the merged tree in the repinner's order: --legacy-only, the US bundle
generator (byte-identical), the repinner (a second pass: the coverage tool
test's pins read the coverage report), and tools/spec_engine_coverage.py
(50842/50842 configuration fields, 41/41 inventory checks). Both --check
runs pass. docs/agent-guide.md, test_transport_evidence_kernels.py and
test_uk_receipt_counts.py merged without conflict and keep both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1676)

What failed: on policyengine-us 2.145.3, engine-us's
test_no_column_an_r2_stage_fills_is_an_agi_input (the review of #1660). The
AGI's static closure reaches four of the eight columns that R2's stages fill:
takes_up_medicare_if_eligible, takes_up_ssi_if_eligible,
takes_up_tanf_if_eligible and receives_housing_assistance.

Why: 2.145.3 adds charitable_contributions_ald, the 2020 above-the-line
charitable deduction for non-itemizers (26 U.S.C. 62(a)(22)); 2.2.1 has no
such variable. It reads tax_unit_itemizes, and through it the itemization
graph: medical expenses (Medicare Part B premiums and enrollment, the SSI
Part B buy-in) and SALT (the sales tax income bracket, TANF, Connecticut's
TFA). Its formula returns 0 before reading anything in a year whose
gov.irs.ald.deductions leaves it out, so a 2024 AGI never reads those
columns. The engine's trace of a 2024 AGI computes none of them; a 2020 one
computes tax_unit_itemizes and three of them.

What changes: agi_engine_inputs takes the check's year. It runs each formula
of the AGI's closure as the engine does, on the engine's parameters for that
year (each month for a monthly variable), with a population that refuses
reads. A formula that returns before touching it, or a variable with nothing
in force that year, passes on none of its reads but its defined_for
variable. An error, or a refused read that a formula catches, counts as a
read. The tool names no year and no variable: in 2024, 35 formulas
read nothing, the deduction among them, and the closure's 689 input leaves
become 216, none of them a stage-filled column. In 2020 the
deduction reads, and the four columns are inputs again. household_agi passes
its period.

Tests, in the engine workflow tier: the existing test takes R2's year; the
deduction reads in exactly the years the engine's list names, and in such a
year the AGI reads stage-filled columns; a traced 2024 AGI in Connecticut
computes none of them; and the probe's rules on stand-in formulas (a
defined_for variable kept, a caught refusal and an error counted as reads).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@PavelMakarchuk

Copy link
Copy Markdown
Contributor

Child-support records for build populace-us-2024-3b3de63-12693b9db03d-20261127T193416Z (built and certified at 12693b9db0), answering conditions 2 to 5 of the floor review.

1. Seed. The production seed stayed fixed. The certifying base ran with --seed 0 --location-seed 0 (run-12693b9db03d/base-config.json), the same as the stopped base at ba410438e6 before it. No seed was changed in response to the diagnosis.

2. Diagnosis. tools/diagnose_us_child_support_gate.py at 12693b9db0, defaults, on checkpoint 010_prior_year_income_post_clone.frame.h5, with --out naming a new file outside the run folder. Aggregates only:

Run puf_tax_detail expense share Expense gate
Build seed 0, in-sample sign gate 0.1826% pass
Other seeds 1-4, in-sample: lowest / highest 0.2044% (seed 4) / 0.3990% (seed 3) pass
Seed 0, cross-fitted sign gate 0.4939% pass

Training sample at the build's seed: 5,000 rows, 26 payers, 63 recipients.

Caveat on the checkpoint: the certifying base pruned its frame checkpoints after hashing its H5 (PRUNE_BASE_CHECKPOINTS=1), so the tool ran on the checkpoint of the base that stopped at stage 011 (run-ba410438e6a6). Between ba410438e6 and 12693b9db0 the source changes are only the child-support floor (child_support.py, gates.json), the diagnosis tool, tests and pins; nothing upstream of stage 011 changed, and both bases ran at seed 0. The rerun at seed 0 reproduces the certifying base summary's puf_tax_detail expense share exactly (0.001825728…, 857 positive rows), and the checkpoint files' sha256 were unchanged by the run.

3. Thresholds. None crossed.

Stop-and-escalate check Value Crossed
Rerun at the build's seed reproduces the base summary's puf_tax_detail expense share 0.18257% vs 0.18257% no
Another seed draws a puf_tax_detail expense share under 0.10% lowest 0.2044% no
Base summary asec expense share outside 0.56-0.76% 0.6461% no
Base summary asec expense, asec received or puf_tax_detail received share under 0.20% 0.6461% / 0.9488% / 0.7137% no

4. No threshold was crossed, so there is nothing to escalate.

5. Signal block (from base-out/base_populace_us_2024_puf_support.summary.json):

"child_support_signal": {
 "details": {
  "columns": {
   "child_support_expense": {
    "channels": {
     "asec": {"positive_rows": 2617, "positive_share": 0.006460695864273861, "weighted_total": 8979733727.748613},
     "puf_tax_detail": {"positive_rows": 857, "positive_share": 0.001825728061894438, "weighted_total": 2006391863.2084987}
    },
    "negative": 0, "nonfinite": 0,
    "positive_share": 0.004143211963084149,
    "positive_share_band": [0.003, 0.15],
    "weighted_total": 10986125590.957111
   },
   "child_support_received": {
    "channels": {
     "asec": {"positive_rows": 4562, "positive_share": 0.009487804422012334, "weighted_total": 10457345731.450111},
     "puf_tax_detail": {"positive_rows": 3309, "positive_share": 0.007137478078532721, "weighted_total": 6140280628.262202}
    },
    "negative": 0, "nonfinite": 0,
    "positive_share": 0.00831264125027253,
    "positive_share_band": [0.005, 0.15],
    "weighted_total": 16597626359.712313
   }
  }
 },
 "failures": [],
 "passed": true
}

Known issue: the puf_tax_detail child_support_expense share is 0.18%, 28% of the asec rate (0.65%), caused by the payer model's in-sample sign gate.

The tool's per-income-year shares are left out here, as the review asks. The full diagnosis JSON stays on the build laptop with the run.

@juaristi22
juaristi22 merged commit 0ba5e85 into main Nov 30, 2026
13 checks passed
anth-volk added a commit that referenced this pull request Nov 30, 2026
…coring branch

The one conflict was the recorded plan digest in
test_us_post_export_requests.py, which both sides re-pinned: main for the
2.145.3 probes and specs, this branch for the raised method label. The
merged pin (d7fd707a...) is the record with both; the record with the
earlier label hashes to main's pin (0e105751...), which is now
_PLAN_SHA256_WITH_THE_FIRST_LABEL, so the two differ only by the label.
Every stage output's digest is main's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 30, 2026
Takes #1676 at dc7917f: the child-support channel floor (12693b9,
the national build's commit), main through 0278db1 (#1660 merged,
#1696's thread settings, #1737's final-export carry and the rest), the
policyengine-us 2.145.3 CI fixes and the AGI pre-check's year cut read
from the engine.

Resolutions:
- AGI pre-check: #1676's probe decides which formulas read nothing in
  the check's year. Its population now also stands in for an engine pass
  without a reform, whose simulation has no baseline, so the behavioral
  responses read nothing there; and the closure follows the engine's
  helper functions (#1719's index view). #1719's named lists
  (YEAR_LISTED_DEDUCTIONS, NO_REFORM_UNREAD) go. On policyengine-us
  2.145.3 the 2024 inputs are 218, none of them a column an R2 stage
  fills; in 2020 the charitable deduction still reads them. The report
  records the input count (agi_engine_inputs) in place of
  agi_closure_stops_at. Tests: #1676's probe tests, #1719's engine
  evidence restated for the probe, and an engine-free test of the
  no-reform stand-in. #1719's year-closure fragment goes: #1676's covers
  the same fix.
- Reviewed-fill register and the release-tool test that tracks it:
  #1719's re-review on 2.145.3, which carries #1660's strike_benefits
  entry re-reviewed.
- #1660's files that #1719 had cherry-picked (the two pre-checks, their
  tests and changelog fragment): merged three-way against the picked
  commit f8b1039, so both sides' later changes stay.
- R1, its Modal plan and their tests: both sides' options, #1719's ESI
  waiver and #1660's proof-of-concept default-donor allowance, each
  documented and owned by the Modal runner.
- Release tool: Path is imported at the top for the thread setting;
  MappingProxyType stays for REVIEWED_DONOR_LINEAGES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 30, 2026
Main moved build_us_fiscal_refresh_release's private
_assert_group_entities_nest_in_households to
household_batches.assert_group_entities_nest_in_households. The merge of
#1676 switched materialize_chunked to the shared check but kept
_household_agi's old call, so every county SOI run with more households
than one AGI chunk would stop with an AttributeError at R2's AGI pass,
after the staging load and the SSI/Medicaid pre-pass. The engine-tier
test test_r2s_own_agi_pass_stores_the_soi_rows_agi and the adversarial
review of the merge both found it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 30, 2026
#1676 merged into main as 0ba5e85, so this PR now targets main. The
merge brings main's commits since #1676's last merge of it (0278db1):
the build-folder switch and release publication changes, microcosm-data's
registry, the spec-engine and transport tests, and README. No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Nov 30, 2026
The test workflow runs on pull requests into main only, and #1719 was
pushed while it still targeted #1676's branch, so no run started when it
was retargeted after #1676 merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@juaristi22

Copy link
Copy Markdown
Collaborator Author

One-time head-to-head for the 27 November build, agreed with Max as a lighter stand-in while the head-to-head tooling is redesigned. It compares the new build, populace-us-2024-3b3de63-12693b9db03d-20261127T193416Z (345,942 households), with today's default, populace-us-2024-spm-20260915 (57,240 households). It covers the national and state rows of d844's register and the 11 JCT tax expenditures. No threshold is applied.

In short: on the 5,988 national and state rows, the new build has the lower weighted loss (0.0730 against 0.0780) and more rows within 10% of target (75.7% against 71.1%). Its loss is higher on the 435 national rows (0.0183 against 0.0171). Three IRS measures described below (the number of returns, returns with net capital gains, and rental income) add 0.0021 more to its national loss than to today's default's, which is more than the whole gap. On the 11 JCT rows, the two split 6 to 5, and the new build's mean absolute error is higher (47.3% against 44.2%).

National and state targets (5,988 rows of d844's register)

Today's default New build
Weighted loss (lower is better) 0.0780 0.0730
Rows within 10% of target 71.1% 75.7%
Rows where it is the closer of the two 2,632 3,334

22 rows tie. Split by geography (each side's loss contributions add up to its weighted loss):

Geography Rows Loss: default Loss: new build Within 10%: default Within 10%: new build Closer: default Closer: new build
National 435 0.0171 0.0183 71.3% 78.2% 162 251
State 5,553 0.0609 0.0548 71.1% 75.5% 2,470 3,083

By source family:

Family Basis Rows Loss: default Loss: new build Within 10%: default Within 10%: new build
irs_soi amount 2,287 0.0545 0.0470 43.2% 46.7%
irs_soi count 2,230 0.0132 0.0156 85.7% 93.0%
cms_medicaid count 134 0.0017 0.0023 83.6% 77.6%
census_population count 936 0.0022 0.0021 99.9% 100.0%
federal_reserve amount 1 0.0015 0.0015 100.0% 100.0%
cms_aca count 102 0.0006 0.0012 92.2% 82.4%
bea amount 2 0.0009 0.0009 50.0% 50.0%
state_income_tax amount 44 0.0008 0.0008 56.8% 56.8%
cbo amount 5 0.0008 0.0007 80.0% 100.0%
ssa count 54 0.0006 0.0003 70.4% 96.3%
ssa amount 57 0.0005 0.0002 78.9% 100.0%
usda_snap count 52 0.0003 0.0001 92.3% 98.1%
usda_snap amount 52 0.0002 0.0001 76.9% 96.2%
hhs_acf_tanf amount 30 0.0002 0.0001 50.0% 73.3%
cms_medicare amount 1 0.0000 0.0000 100.0% 100.0%
hhs_acf_liheap count 1 0.0000 0.0000 100.0% 100.0%

Where the new build does worse:

  • Returns with net capital gains: 27.5M against IRS's 12.4M nationally (Table 1.4; today's default has 12.2M), and a median 137% above the state targets. The build compiled its targets at 12693b9db, before Merge four held US SOI target corrections (#1224, #1036, #1040, #1030) on the current feed #1733 (merged 25 November). Merge four held US SOI target corrections (#1224, #1036, #1040, #1030) on the current feed #1733 ships Historic Table 2's capital-gains rows, which count returns with a gain or a loss, as shares of Table 1.4's count instead of as levels. At 12693b9db the state rows still shipped as levels and summed to 29.6M, and the build calibrated to them: its own calibration_diagnostics.json ends at 28.0M against the national 12.4M. No other single row adds as much to its national loss.
  • Rental and royalty income: $243bn against $86bn (today's default has $94bn). Schedule C income is also high in some states, for example Georgia at $29.3bn against $7.9bn. Both are Historic Table 2 "net income (less loss)" columns, which HT2 and CD business, partnership and rental 'net income (less loss)' columns calibrate positive-part model concepts #1228 (open) shows the compiler maps onto model concepts that count something else. The 30 September Route A build showed the same pattern, with rental income at 2.64 times its target.
  • Number of returns: 170.5M against IRS's 159.7M to 160.6M, depending on the table (today's default has 159.9M). The build's calibration ended at 173.6M against its 160.6M target.
  • Taxable interest of itemizers (Table 2.1): $104bn against $166bn (today's default has $152bn).
  • Medicaid and ACA enrollment counts: 77.6% and 82.4% of rows within 10%, against 83.6% and 92.2% for today's default.

Where it does better: state AGI by income size. In the $200k to $500k band, today's default is a median 45% above the state targets (up to 101%) and the new build 17% (13% to 21%), and the new build is closer in 46 of 51 states. It is closer in 36 states in the $500k-and-over band, and on most SSA, SNAP and TANF rows.

With dollar targets aged. d844's form compiles the register with the scorer's defaults, so TY2022 IRS dollar amounts are scored unaged, while the build's calibration ages them to 2024 (AGI by a factor of 1.12). Compiled with age_targets=True instead, 2,200 targets change and the estimates stay the same. The weighted losses are then 0.0419 for today's default and 0.0416 for the new build, 87.0% and 91.9% of rows are within 10%, and the new build is the closer of the two on 3,251 rows against 2,715.

JCT tax expenditures, CY2024

Tax expenditure JCT Today's default New build
State and local tax deduction $21.7bn $22.3bn (+2.7%) $21.3bn (−1.6%)
Medical expense deduction $11.4bn $8.4bn (−26.2%) $6.4bn (−43.7%)
Charitable deduction $60.4bn $61.1bn (+1.1%) $60.4bn (+0.0%)
Mortgage interest deduction $24.8bn $29.7bn (+19.7%) $27.8bn (+12.0%)
Qualified business income deduction $63.1bn $52.9bn (−16.2%) $48.0bn (−23.9%)
Self-employed health insurance deduction $8.4bn $2.2bn (−74.1%) $0.9bn (−89.1%)
HSA deduction $12.2bn $3.1bn (−74.2%) $1.8bn (−85.6%)
Student loan interest deduction $2.4bn $1.2bn (−49.0%) $1.6bn (−33.3%)
Self-employed pension contributions $16.6bn $0.2bn (−98.7%) $0.3bn (−98.0%)
Traditional IRA deduction $16.0bn $0.8bn (−94.8%) $0.9bn (−94.5%)
CDCC and employer child care exclusion $5.6bn $4.0bn (−28.8%) $3.4bn (−38.4%)

The new build is the closer of the two on 6 of the 11 and today's default on 5. The new build's mean absolute error is 47.3%, against 44.2% for today's default. Both are more than 70% below JCT on the self-employed health insurance, HSA, self-employed pension and traditional IRA deductions.

How it was run

  • Register. d844's frozen ledger consumer_facts_us_c5e5bf8.jsonl (sha256 b85437390021777e…), compiled with main's scoring code (Move the US engine to policyengine-us 2.145.3 and prepare the Route A national build #1676's head dc7917fa8; main's 0ba5e85ee changes nothing on the scoring path) under policyengine-us 2.145.3 and policyengine-core 3.36.1, the versions the new build was built and certified with. It compiles to 31,645 specs. Register the US head-to-head scorer as a Modal stage for the d844 run #1190's plan compiled the same ledger to 33,147 at 2cfe3043d under policyengine-us 2.2.1.
  • Surface. Route A's --target-surface national_state selection (_select_target_surface) keeps 5,999 of the 31,645 and drops 25,646 congressional-district rows. Eleven of the 5,999 are the JCT reform specs, compared separately above. The other 5,988 (435 national, 5,553 state) are scored here.
  • Scoring. The official scorer's own functions from tools/score_us_release_head_to_head.py: compile_yardstick, load_artifact, score_loaded_artifact and _comparison_payload. That is the scorer's population repair, _materialize_target_frame on 2,000-household slices with one simulation per slice, and production's capped loss. The loss weights are recomputed on these 5,988 rows by the release's fiscal_target_loss_weights, as a national_state calibration computes them. The repair rescales each dataset's weights to the code's Census 2024 benchmark of 334.2M people: by 0.98272 for today's default (340.08M people before) and 0.98258 for the new build (340.12M).
  • JCT. The new build's values are certification's reform_validation.json rows. They are in-sample: the calibration fit's estimates, from the reform columns the build's target compilation materialized on the frame it then exported. Today's default's values come from the same materializer run on its published H5 under policyengine-us 2.145.3, on its shipped weights (the scorer's repair factor taken back out, so both sides use shipped weights). The JCT figures are the same in the register and in certification.
  • Not scored: the district rows and the by-origin battery.
  • Today's default was certified against policyengine-us 2.2.1. Under 2.145.3, the scorer drops and recomputes the one stored column that is now formula-owned (has_marketplace_health_coverage), and the engine ignores stored columns it no longer defines (Published US releases store would_claim_wic, which policyengine-us 2.x ignores, so WIC take-up is 100% under policyengine.py 6.1.1 #1026).
  • The c5e5bf8 feed has no state rows for returns at $1M+ AGI, which the current coverage requirements name, so neither dataset is scored on them.
  • Each part ran as one process on a laptop: today's default took 777 s on the national and state rows and 5,894 s on the JCT rows, and the new build 4,333 s. Register the US head-to-head scorer as a Modal stage for the d844 run #1190's timing evidence puts the full d844 run at about 74,100 slice-seconds in one process.
  • The per-row results for both datasets are kept locally and can be shared.
The one-time script (score and compare): score_national_state.py
"""One-time national + state head-to-head for the #1676 build (30 Nov 2026).

Scores one artifact on d844's frozen register (`consumer_facts_us_c5e5bf8.jsonl`,
the yardstick #1190's plan pins), cut to the targets Route A's
`--target-surface national_state` keeps (`_select_target_surface`: every
congressional-district-classified row dropped). Everything else is the official
scorer's own code, imported from `tools/score_us_release_head_to_head.py`:
`compile_yardstick`, `load_artifact`, `score_loaded_artifact` (population repair,
`_materialize_target_frame` per 2,000-household slice, `score_targets`, the
production loss), `_assert_identical_scored_contracts` and `_comparison_payload`.

Two parts, each its own process:

* `ns`: the national + state rows except the 11 JCT tax-expenditure reform
  specs; one simulation per household slice.
* `jct`: the 11 JCT reform specs only. Run for the incumbent; the candidate's
  JCT rows are certification's (`reform_validation.json`, the calibration fit).

Loss weights are recomputed on each part's rows with the release's own
`fiscal_target_loss_weights`, as a national_state calibration computes them.
The by-origin battery is not scored (out of the agreed scope).

Usage (from a microcosm checkout with policyengine-us installed):
  python score_national_state.py score --repo R --artifact incumbent --h5 X \
      --ledger-facts L --part ns --out-dir O
  python score_national_state.py compare --out-dir O --candidate-reform-validation RV
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
import time
from pathlib import Path

JCT_PREFIX = "jct.tax_expenditures."
SCOPE_NOTE = (
    "not scored: the one-time comparison covers the national + state fiscal "
    "targets and the JCT rows only"
)


def _import_scorer(repo: Path):
    sys.path.insert(0, str(repo / "tools"))
    import build_us_fiscal_refresh_release as release  # noqa: E402
    import score_us_release_head_to_head as h2h  # noqa: E402

    return release, h2h


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1 << 24), b""):
            digest.update(block)
    return digest.hexdigest()


def _is_jct(spec) -> bool:
    return str(spec.name).startswith(JCT_PREFIX)


def _part_yardstick(release, h2h, full, specs, *, part: str, selection: dict):
    from microcosm.calibrate import TargetRegistry

    registry = TargetRegistry(tuple(specs), country="us")
    weights = release._fiscal_target_loss_weights(registry)
    basis = release._fiscal_target_loss_basis(registry, weights)
    identity = dict(full.identity)
    identity.update(
        {
            "target_count": len(specs),
            "full_register_target_count": len(full.registry.specs),
            "surface": "national_state",
            "surface_selection": selection,
            "part": part,
            "loss_weights": (
                "recomputed on this part's rows with "
                "release._fiscal_target_loss_weights"
            ),
        }
    )
    return h2h.FiscalYardstick(
        registry=registry,
        loss_weights=weights,
        loss_basis=basis,
        identity=identity,
    )


def _yardsticks(release, h2h, ledger_facts: Path):
    full = h2h.compile_yardstick(
        ledger_facts=ledger_facts,
        age_targets=False,
        allow_unaged_dollar_targets=True,
        congressional_district_vintage_crosswalk=(
            release.default_congressional_district_vintage_crosswalk_path()
        ),
    )
    kept, selection = release._select_target_surface(
        full.registry.specs, release.TARGET_SURFACE_NATIONAL_STATE
    )
    jct = [spec for spec in kept if _is_jct(spec)]
    ns = [spec for spec in kept if not _is_jct(spec)]
    all_jct = [spec for spec in full.registry.specs if _is_jct(spec)]
    if len(jct) != 11 or len(all_jct) != 11:
        raise RuntimeError(
            f"Expected 11 JCT specs, found {len(jct)} kept / {len(all_jct)} compiled."
        )
    return full, selection, {
        "ns": _part_yardstick(release, h2h, full, ns, part="ns", selection=selection),
        "jct": _part_yardstick(
            release, h2h, full, jct, part="jct", selection=selection
        ),
    }


def _install_progress(h2h, label: str) -> None:
    original = h2h._score_household_slice
    started = time.time()

    def wrapped(*args, **kwargs):
        slice_started = time.time()
        result = original(*args, **kwargs)
        print(
            f"[{label}] slice {kwargs['slice_index'] + 1}/{kwargs['slice_count']} "
            f"{time.time() - slice_started:.1f}s elapsed {time.time() - started:.0f}s "
            f"peak_rss {h2h._peak_rss_bytes() / 1024**3:.2f} GiB",
            flush=True,
        )
        return result

    h2h._score_household_slice = wrapped


def score(args: argparse.Namespace) -> int:
    release, h2h = _import_scorer(args.repo)
    out_dir = args.out_dir.resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / f"{args.artifact}.{args.part}.json"
    if out_path.exists():
        raise SystemExit(f"{out_path} exists; refusing to overwrite it.")
    started = time.time()
    full, selection, parts = _yardsticks(release, h2h, args.ledger_facts.resolve())
    yardstick = parts[args.part]
    print(
        f"register {len(full.registry.specs)} specs; national_state keeps "
        f"{selection['calibrated_targets']}; part {args.part} scores "
        f"{len(yardstick.registry.specs)}",
        flush=True,
    )
    # The by-origin battery is out of scope: never compute it.
    h2h._terminal_battery_payload = lambda artifact: {
        "status": "not_scored",
        "reason": SCOPE_NOTE,
        "comparisons": {},
    }
    _install_progress(h2h, f"{args.artifact}/{args.part}")
    artifact = h2h.load_artifact(args.h5.absolute())
    payload, contract = h2h.score_loaded_artifact(
        artifact=artifact,
        artifact_name=args.artifact,
        yardstick=yardstick,
        maximum_microsim_batch_size=args.maximum_microsim_batch_size,
    )
    geography = {}
    for spec in yardstick.registry.specs:
        if spec.name in geography:
            raise RuntimeError(f"Duplicate spec name {spec.name}.")
        geography[spec.name] = {
            "level": spec.metadata.get("ledger_geography_level"),
            "scope": spec.metadata.get("geography_scope"),
            "id": spec.metadata.get("ledger_geography_id"),
        }
    record = {
        "artifact": args.artifact,
        "part": args.part,
        "h5": str(args.h5.absolute()),
        "h5_sha256": payload["identity"]["sha256"],
        "geography": geography,
        "yardstick": dict(yardstick.identity),
        "loss_basis": dict(yardstick.loss_basis),
        "payload": payload,
        "contract": [list(item) for item in contract],
        "seconds": round(time.time() - started, 1),
        "peak_rss_gib": round(h2h._peak_rss_bytes() / 1024**3, 3),
        "maximum_microsim_batch_size": args.maximum_microsim_batch_size,
    }
    out_path.write_text(
        json.dumps(record, allow_nan=False, indent=1, sort_keys=True) + "\n"
    )
    fiscal = payload["fiscal"]
    print(
        json.dumps(
            {
                "out": str(out_path),
                "weighted_loss": fiscal["weighted_loss"],
                "fraction_within_10pct": fiscal["fraction_within_10pct"],
                "targets": fiscal["target_count"],
                "seconds": record["seconds"],
                "peak_rss_gib": record["peak_rss_gib"],
            },
            indent=1,
        ),
        flush=True,
    )
    return 0


def _load(out_dir: Path, artifact: str, part: str) -> dict:
    return json.loads((out_dir / f"{artifact}.{part}.json").read_text())


def compare(args: argparse.Namespace) -> int:
    release, h2h = _import_scorer(args.repo)
    out_dir = args.out_dir.resolve()
    incumbent = _load(out_dir, "incumbent", "ns")
    candidate = _load(out_dir, "candidate", "ns")
    if incumbent["yardstick"] != candidate["yardstick"]:
        raise RuntimeError("The two ns runs used different yardsticks.")
    h2h._assert_identical_scored_contracts(
        {
            "incumbent": tuple(tuple(item) for item in incumbent["contract"]),
            "candidate": tuple(tuple(item) for item in candidate["contract"]),
        }
    )
    comparison = h2h._comparison_payload(incumbent["payload"], candidate["payload"])

    # JCT: certification's in-sample rows for the candidate, the incumbent's
    # materialized JCT specs on its shipped weights (repair factor removed so
    # both sides are on shipped weights, as certification's rows are).
    reform_validation = json.loads(args.candidate_reform_validation.read_text())
    candidate_jct = {
        row["id"]: row
        for row in reform_validation["reforms"]
        if row["category"] == "JCT tax expenditure"
    }
    incumbent_jct = _load(out_dir, "incumbent", "jct")
    repair = incumbent_jct["payload"]["normalization_receipts"][
        "base_population_mass_repair"
    ]
    factor = float(repair["factor"]) if repair["applied"] else 1.0
    jct_rows = []
    for row in incumbent_jct["payload"]["fiscal"]["targets"]:
        name = row["name"]
        certified = candidate_jct[name]
        jct_figure = float(certified["jct"]["score"])
        if not math.isclose(float(row["target"]), jct_figure, rel_tol=1e-12):
            raise RuntimeError(
                f"{name}: register target {row['target']} differs from the JCT "
                f"figure certification used, {jct_figure}."
            )
        incumbent_value = float(row["actual"]) / factor
        candidate_value = float(certified["microcosm"]["budget_effect"])
        jct_rows.append(
            {
                "name": name,
                "jct": jct_figure,
                "incumbent": incumbent_value,
                "incumbent_repaired_weights": float(row["actual"]),
                "candidate": candidate_value,
                "incumbent_absolute_relative_error": abs(incumbent_value / jct_figure - 1),
                "candidate_absolute_relative_error": abs(candidate_value / jct_figure - 1),
            }
        )

    levels = candidate["geography"]
    families = {
        row["name"]: f"{row['family']}/{row['value_basis']}"
        for row in candidate["payload"]["fiscal"]["targets"]
    }

    def grouped(key_of) -> dict[str, dict[str, float]]:
        groups: dict[str, dict[str, float]] = {}
        for row in comparison["per_target_absolute_relative_error"]["targets"]:
            group = groups.setdefault(
                key_of(row["name"]),
                {"targets": 0, "candidate_lower": 0, "equal": 0, "incumbent_lower": 0},
            )
            group["targets"] += 1
            lower = row["lower_absolute_relative_error"]
            group[
                {
                    "candidate": "candidate_lower",
                    "incumbent": "incumbent_lower",
                    "equal": "equal",
                }[lower]
            ] += 1
        for role, record in (("incumbent", incumbent), ("candidate", candidate)):
            for row in record["payload"]["fiscal"]["targets"]:
                group = groups[key_of(row["name"])]
                key = f"{role}_loss_contribution"
                group[key] = group.get(key, 0.0) + float(
                    row["weighted_loss_contribution"]
                )
                key = f"{role}_weight_share"
                group[key] = group.get(key, 0.0) + float(row["target_loss_weight_share"])
                key = f"{role}_within_10pct"
                group[key] = group.get(key, 0) + int(
                    abs(float(row["relative_error"])) <= 0.10
                )
        return groups

    summary = {
        "by_geography_level": grouped(lambda name: str(levels[name]["level"])),
        "by_family_basis": grouped(lambda name: families[name]),
        "comparison_counts": {
            key: comparison["per_target_absolute_relative_error"][key]
            for key in ("candidate_lower_count", "equal_count", "incumbent_lower_count")
        },
        "fiscal_weighted_loss": comparison["fiscal_weighted_loss"],
        "fraction_within_10pct": {
            "incumbent": incumbent["payload"]["fiscal"]["fraction_within_10pct"],
            "candidate": candidate["payload"]["fiscal"]["fraction_within_10pct"],
        },
        "population_repair": {
            "incumbent": incumbent["payload"]["normalization_receipts"][
                "base_population_mass_repair"
            ],
            "candidate": candidate["payload"]["normalization_receipts"][
                "base_population_mass_repair"
            ],
        },
        "family_rollup": {
            "incumbent": h2h._family_basis_rollup(incumbent["payload"]["fiscal"]["targets"]),
            "candidate": h2h._family_basis_rollup(candidate["payload"]["fiscal"]["targets"]),
        },
        "jct": jct_rows,
        "jct_incumbent_repair_factor_removed": factor,
    }
    (out_dir / "comparison.json").write_text(
        json.dumps(
            {"comparison": comparison, "summary": summary},
            allow_nan=False,
            indent=1,
            sort_keys=True,
        )
        + "\n"
    )
    print(json.dumps({k: v for k, v in summary.items() if k != "family_rollup"}, indent=1))
    return 0


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    sub = parser.add_subparsers(dest="command", required=True)
    s = sub.add_parser("score")
    s.add_argument("--repo", type=Path, required=True)
    s.add_argument("--artifact", choices=("incumbent", "candidate"), required=True)
    s.add_argument("--h5", type=Path, required=True)
    s.add_argument("--ledger-facts", type=Path, required=True)
    s.add_argument("--part", choices=("ns", "jct"), required=True)
    s.add_argument("--out-dir", type=Path, required=True)
    s.add_argument("--maximum-microsim-batch-size", type=int, default=2000)
    c = sub.add_parser("compare")
    c.add_argument("--repo", type=Path, required=True)
    c.add_argument("--out-dir", type=Path, required=True)
    c.add_argument("--candidate-reform-validation", type=Path, required=True)
    args = parser.parse_args(argv)
    return score(args) if args.command == "score" else compare(args)


if __name__ == "__main__":
    raise SystemExit(main())
The aged-targets sensitivity: aged_sensitivity.py
"""Sensitivity: the same national + state comparison on d844's ledger compiled with
`age_targets=True` (IRS dollar amounts aged to 2024, as the build's calibration ages
them). No new simulation: each spec's estimate depends on its measure, not on its
target value, so the scored estimates are reused and only the targets, the loss
scales (max(|target|, 1)) and the loss weights change.

  python aged_sensitivity.py <repo> <ledger_facts> <out_dir>
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
import score_national_state as m  # noqa: E402


def main(repo: Path, ledger: Path, out_dir: Path) -> None:
    release, h2h = m._import_scorer(repo)
    aged = h2h.compile_yardstick(
        ledger_facts=ledger,
        age_targets=True,
        allow_unaged_dollar_targets=True,
        congressional_district_vintage_crosswalk=(
            release.default_congressional_district_vintage_crosswalk_path()
        ),
    )
    kept, selection = release._select_target_surface(
        aged.registry.specs, release.TARGET_SURFACE_NATIONAL_STATE
    )
    by_name = {spec.name: spec for spec in kept if not m._is_jct(spec)}
    records = {
        role: json.loads((out_dir / f"{role}.ns.json").read_text())
        for role in ("incumbent", "candidate")
    }
    rows = {role: r["payload"]["fiscal"]["targets"] for role, r in records.items()}
    names = [row["name"] for row in rows["incumbent"]]
    if names != [row["name"] for row in rows["candidate"]]:
        raise RuntimeError("The two runs scored different rows.")
    if set(names) != set(by_name):
        raise RuntimeError(
            f"Aged surface differs: {len(set(by_name) - set(names))} extra, "
            f"{len(set(names) - set(by_name))} missing."
        )
    specs = [by_name[name] for name in names]
    for spec, row in zip(specs, rows["incumbent"]):
        if spec.measure is None or str(spec.period) != str(row["period"]):
            raise RuntimeError(f"{spec.name}: period or measure differs.")
    yardstick = m._part_yardstick(
        release, h2h, aged, specs, part="ns-aged", selection=selection
    )
    targets = np.asarray([float(spec.value) for spec in specs], dtype=np.float64)
    scales = np.maximum(np.abs(targets), 1.0)
    aged_payloads = {}
    changed = int(
        np.sum(
            ~np.isclose(
                targets,
                np.asarray([row["target"] for row in rows["incumbent"]]),
                rtol=1e-12,
                atol=0.0,
            )
        )
    )
    for role in ("incumbent", "candidate"):
        estimates = np.asarray([row["actual"] for row in rows[role]], dtype=np.float64)
        aged_rows, aggregate = h2h._fiscal_rows_and_aggregate(
            yardstick=yardstick, estimates=estimates, targets=targets, scales=scales
        )
        aged_payloads[role] = {
            "fiscal": {
                "weighted_loss": aggregate["weighted_loss"],
                "fraction_within_10pct": aggregate["fraction_within_10pct"],
                "targets": aged_rows,
            },
            "terminal_battery": {"status": "not_scored", "comparisons": {}},
        }
    comparison = h2h._comparison_payload(
        aged_payloads["incumbent"], aged_payloads["candidate"]
    )
    counts = comparison["per_target_absolute_relative_error"]
    result = {
        "aged_targets_changed": changed,
        "weighted_loss": comparison["fiscal_weighted_loss"],
        "fraction_within_10pct": {
            role: aged_payloads[role]["fiscal"]["fraction_within_10pct"]
            for role in ("incumbent", "candidate")
        },
        "counts": {
            key: counts[key]
            for key in ("candidate_lower_count", "equal_count", "incumbent_lower_count")
        },
    }
    (out_dir / "aged_sensitivity.json").write_text(
        json.dumps(
            {"summary": result, "comparison": comparison, "payloads": aged_payloads},
            allow_nan=False,
            indent=1,
            sort_keys=True,
        )
        + "\n"
    )
    print(json.dumps(result, indent=1))


if __name__ == "__main__":
    main(Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]))

MaxGhenis added a commit that referenced this pull request Dec 1, 2026
…at was hashed

Review round 2 found that the install helper could lose the old member or
leave the canonical path missing. It moved the cached member aside by its
pre-download digest, wrote a shared .partial name, and renamed twice. Now
installs into a cache directory take an exclusive flock. Under it the helper
removes stale .partial files and re-hashes the canonical member. If that
member already holds the new bytes, it returns. Otherwise it hard-links the
old member to <member>.<full SHA-256>, never overwriting a file of that name.
It writes the new bytes to a unique temporary file, fsyncs it, and replaces
the canonical path with one os.replace.

The readers pass pandas the compression that the file name implies, since a
buffer has no name to infer it from. A fetched summary extract must be the
current reissue. The runbook's Settings block now names a #1676 head that has
taken main with these pins.

This also corrects the first commit's message. The default fetch does not
reuse a cached 6ff73d52 member: it installs the reissue and keeps the old file
beside it. Only an explicit --scf-summary-extract path reads that member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis added a commit that referenced this pull request Dec 1, 2026
#1676 merged into main on 30 November 2026 as merge commit 0ba5e85,
so the Settings block can no longer name its head, and the next build
runs from a main commit that contains these SCF pins. REQUIRE_ON_MAIN
keeps the example's default of 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
juaristi22 added a commit that referenced this pull request Dec 1, 2026
#1719's branch moved 870 commits (main with #1676, and the County Files
changes). Three files conflicted:

- spec_engine/inventory_coverage.py: both comment lists kept. The seed map
  and seed protocol digests are re-pinned for the merged tree with
  tools/repin_us_spec_engine_contracts.py and tools/spec_engine_coverage.py
  (two passes each, then --check), which also move the US spec digest in two
  tests and the F0 coverage report. No draw changes.
- us_runtime/voluntary_filing.py: __all__ keeps this lane's
  impute_us_voluntary_filing_from_tables and drops
  load_sipp_2023_voluntary_filing_donor, which the base replaced with the
  shared SIPP December read (#1686).
- tools/build_us_acs_local_release.py: the SSI and Medicaid pre-pass keeps
  this lane's _prepass_view_contract and takes the base's
  refuse_population_aggregates=True on every view.

Two breaks that git did not flag are fixed here:

- The base removed the release tool's
  _assert_group_entities_nest_in_households and
  _assert_medicaid_claiming_tax_units_local; with the refusal on, the engine
  pass refuses those cases itself. _prepass_view_contract drops its own
  nesting check and its hh_chunk argument, and the ACA pre-pass calls
  _aca_source_tax_unit_table_batched with the same refusal.
- acs_local_voluntary_filing read its donor through the removed
  load_sipp_2023_voluntary_filing_donor. It now reads the file with
  read_sipp_december_person_rows and builds the donor with
  build_sipp_2023_voluntary_filing_donor, the base's route to the same
  bytes.

Tests on this tree: engine-free (32 files, no engine installed) 2017 passed,
6 skipped, 2 failed; engine tier (7 files) 183 passed. The 2 failures are
older than this merge: the pre-pass contract imports policyengine-us when
no cell needs it. The next commit fixes that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DTrim99

DTrim99 commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

SNAP holdouts to go with the head-to-head above, for the promotion call. None of these are calibration targets. Both files run on policyengine-us 2.145.3 at their shipped weights, in January 2026 (annual figures are 12 times January). The benchmarks are FNS counts for fiscal 2026 to date (preliminary, as of 13 November), the FY2024 SNAP QC case records, the asset share in USDA's analysis of the proposed rule, and ASEC 2024.

Today's default (populace-us-2024-spm-20260915) New build (populace-us-2024-3b3de63-12693b9db03d-20261127T193416Z) Benchmark
SNAP households 22.0M 21.0M 20.5M (FNS)
SNAP people 59.2M 53.2M 37.8M (FNS)
People per SNAP household 2.69 2.53 1.86 (QC)
One-person SNAP households 29.7% 31.9% 60.2% (QC)
Recipients failing a federal income test 20.9% 20.4% 9.1% (QC)
Recipients over the asset limit only 19.4% 17.9% 11.5% (USDA)
States where every eligible unit takes up before the solve (#647) 30, with 74% of FNS households 14, with 21%
One-person SPM units at or under 130% of poverty 4.1M 7.3M 11.8M (ASEC)

The new build is closer on every row. Both still miss composition by a wide margin, mostly through one-person households and recipients over the asset limit (#1712; #1835 covers part of it). That gap reaches scores of reforms that turn on composition. Removing broad-based categorical eligibility, as USDA's proposed rule would (91 FR 72454), cuts SNAP by $28.2B a year on today's default, with 8.7M households losing all benefits. On the new build it's $23.2B and 7.6M. USDA's $14.3B and 3.2M are held out. #1714 would put these rows in certification, so the next head-to-head could carry them.

DTrim99 added a commit that referenced this pull request Dec 2, 2026
#1676 merged, so this branch now follows main. Conflicts resolved:

- The report's consumer joins main's _post_export_holdout_consumers registry,
  which every build and the post-export probe read, instead of a line in
  _post_export_consumers.
- Its write step moves inside main's post-export try block, after the
  Medicare IRMAA report, and its writer re-raises scored-file integrity and
  worker-pool errors, as main's two held-out writers now do.
- The fixture engine's SNAP consumer keeps main's scoring return shape.

Main's tests that list the post-export consumers or their files now include
the report, and the pinned post-export plan digests move with the new
consumer (its own output digest is added).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants