Repository navigation
Store the UI start month as a dataset input instead of hashing person_id - #10447
Conversation
is_receiving_unemployment_compensation placed each person's months of unemployment compensation by hashing person_id (splitmix64 mod 12) inside the formula. That is an engine-time draw, which policyengine-core#500 rules out and core#519's static check cannot see. - Add the unemployment_compensation_start_month input (Person, YEAR, 1-12, 0 = not supplied). The dataset build assigns and stores it. - The formula reads the stored month. A data-built simulation whose dataset stores it for some people but not others raises an error naming it. - Transitional: a dataset that does not store it at all (the current default Populace build) still hashes person_id, exactly as before, until the default dataset carries the column. - Household situations keep today's start months through a fixed table by household position. A supplied person_id no longer picks the month. - Add tests/code_health/test_no_engine_time_randomness.py: an AST scan of the package for draws, samples and entity hashes, with a ratchet that lists this transitional hash and must shrink to zero. - Add a differential test: on one dataset, storing the start month gives exactly the retired formula's results in every month and year. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The engine-time randomness guard now resolves names through each scope's own import bindings (so `from numpy import random as r; r.random()` is caught and a local variable called `random` is not), reports the unshadowed builtin hash() only, recognises pandas `.sample(...)` calls by their sampling arguments, and keys RATCHET and EXEMPT by (file, enclosing function or class, kind) with exact occurrence counts. An extra occurrence fails, and an entry that allows more than it matches is stale. A new check confirms the model never imports the offline TAXSIM tools that EXEMPT lists. policyengine-core stores int variables as int32, so the differential test's large ids now stay below 2**31, and a new test asserts the engine sees the dataset's person ids unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds an exhaustive check over the 156 combinations of start month (1-12) and months of receipt (0-12): receipt covers exactly that many calendar months, starting in the start month and wrapping into January. The expected block is built by counting months forward, independently of the formula's modular comparison. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Situation defaults follow household member position
(members_position), so supplied person_id values, reversed or tied,
no longer reorder them. New YAML cases cover reversed IDs, tied IDs,
reversed IDs across axis copies, and positions restarting in each
household.
A data-built simulation tells an absent column from a present one by
input_variables, not by an all-zero sentinel. A column that is stored,
or set after construction, must be complete for the year, so an
all-zero column now raises instead of falling back to the hash.
New differential tests: an all-zero column raises; a column set after
construction is used, and a partial one raises; a simulation built the
way policyengine.py's input-table adapter builds one keeps the retired
household-position months without the column and follows the dataset's
months with it.
The guard now:
- resolves assignment aliases and default arguments;
- follows star imports, of package modules (with __all__) and of numpy
and core's model_api;
- applies comprehension and class-body scoping, and lambdas;
- reports any use of the unshadowed builtin hash;
- counts each use of a hash library or pandas hashing ("hash use"),
each use of a top-level function that draws ("draw helper call",
a fixed point over the package with relative imports resolved), and
literal importlib/__import__ imports;
- catches augmented-assignment and numpy-function forms of xorshift
and id modulo, and getattr with a literal name.
It parses the package once per session. RATCHET adds the two calls
that reach the transitional hash, so RATCHET_CEILING is 7; EXEMPT adds
the two reviewed SHA-256 uses.
Docs, changelog and CLAUDE.md now describe the transitional fallback and
the guard's coverage accurately. The TRANSITIONAL comment names the
part-2 prerequisites: national and ACS local-area releases that store
the column, and policyengine.py's input-table adapter declaring that its
populations come from a dataset.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A data-built simulation decides whether it holds the start month from the holder's input periods on its own branch (get_input_periods), not from the input_variables snapshot. A column set after construction, or one a parent branch holds, counts as supplied, and a column of zeros supplied in any of these ways raises. A reform that neutralizes the column leaves it unsupplied, so the retired hash applies there. New tests: zeros set after construction raise; a branch with zeros raises while its parent keeps its months; a branch reads its parent's column; a neutralizing reform keeps the retired months. A dataset reform's baseline also drops inputs the reform neutralizes, filed as policyengine-core#632. The guard now resolves each name to everything it may refer to where it is used. Bindings in an if, loop, try, with or match, and uses that come before a binding, also reach the next scope out; nested scopes skip enclosing class bodies; global and nonlocal redirect bindings; eager comprehension iterables and same-line statements see the bindings made so far; a walrus in a comprehension binds outside it to the value read inside. Named imports and re-exports are followed across the package, star imports bind __all__ (literal lists and tuples, +, +=, append, extend, insert; anything else exports every name) or the public names, in any analysis order, cycles included. EXTERNAL_EXPORTS replaces STAR_EXPORTS and covers named imports from numpy and core's model_api. Literal dynamic imports read name, package, fromlist and level, positional or keyword. Every reproduction from the r2 review is now found, and the package scan is still clean. Docs and the changelog say a dataset that supplies the column must give every person a month. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard resolves a nonlocal name to the nearest enclosing function that makes it local, wherever in that function's body the binding sits, skipping class bodies. It computes each function's locals statically: parameters, names bound outside nested scopes, imports, except and match captures, and walrus targets in its comprehensions, less names a global or nonlocal statement sends elsewhere. Before, a nonlocal went to the nearest enclosing function even when that function doesn't bind the name, which hid a draw on a module imported two functions out. Named-import resolution no longer memoises a result cut short by an import cycle, so a module's findings no longer depend on the order the package is analysed in. A new test runs every analysis order. A new data test pins core's carry rule for the start month: an input applies to its own year and later years, never earlier ones, so a year before the first input reads the default 0 and raises naming the column. Mutation testing kills all 12 guard mutants and all 5 presence mutants. The unmutated runs pass (117 and 19 tests) at 1.0 GB and 2.2 GB peak resident memory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… deletions - subsample drops calculated start-month defaults before core reloads every value the simulation holds as an input (policyengine-core#633), so a missing column stays missing and a stored one stays stored. - A walrus in a lambda body binds in the lambda; one in a lambda default binds where the comprehension's walrus would. Comprehension loop variables follow Python 3.11. - An attribute of a package module, or of a module EXTERNAL_EXPORTS maps, is what that module binds under the name, and a substituted name is expanded only past what it replaced. `from base import name` binds base.name and leaves the rest to that expansion. - del and the end of an except clause count as deletions, so a builtin can come back into view. - A function body reads the scopes around it as of its def, and every later deletion counts. - A lookup cut by the depth limit is recorded, and the package scan fails if any is. - Tests for each, including order independence where a kept partial result would hide a draw. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answers GPT-6.1 Sol's review r4 of this PR and item 2 of its review r5 of APPROACH.md. - Subsample on a branch (r4 P2 1). Core's subsample exports every period a holder knows, inherited calculated ones included, and reloads them as inputs. r5 deleted only the simulation's own calculated values first, so a branch whose parent had calculated the default came back with a supplied column of zeros. pe-us now overrides `_get_exportable_input_periods`: a presence-tested input goes out only for the periods it is an input on this branch or one it inherits from. Tests cover a column absent, inherited and set on a branch. - A function's `del` of a global (r4 P2 2). It runs whenever the function is called, so after the def it may come between any binding and any use; the guard now treats it that way. - Unfinished bindings (r4 P3 3). A class body, a decorated function and a lambda may run before the statement creating them binds its names, so code inside them no longer takes those bindings as sure. - Annotations of a nested function (APPROACH r5 item 2) count toward the enclosing function's locals, as decorators and defaults already did. - The PEP 709 comment now says comprehensions other than generator expressions (r4 P3 4). - Tests: a stored start-month column with missing values raises naming it; neutralising a stored column on a live simulation raises. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…inty Answers GPT-6.1 Sol's PR review r5 and item 1 of its r6 review of the cross-country approach. Changes only the guard. - An annotation is read as code that may run any time after its statement starts, seeing a class body around it, with every later deletion counting. That covers both ways Python may evaluate it: with its statement (up to 3.13) and whenever the annotations are read (3.14 defers them, PEP 649). Covers function argument and return annotations, methods, and module and class AnnAssigns. - An annotation alone binds no value in a module or class body, so `hash: int` no longer hides the builtin (Sol r5 P2). In a function it still makes the name local. - A star import may bind a name an earlier or removed __all__ held, which an import cycle can see (Sol r5 P3), and is sure to bind only names the final __all__ holds and the module surely binds. A conditional or deleted binding, __all__.remove and a built __all__ now look further out. - A use no longer takes as sure a binding its own statement makes, so a multi-line assignment, default or class base reads the old binding. - A lambda no longer needs its own unfinished span: its body is part of its statement, which the use-statement rule covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answers GPT-6.1 Sol's PR review r6 and items 2-3 of its r7 review of the cross-country approach. Changes the guard and one comment in spm.py. - A global or nonlocal statement now applies in the code nested in its scope, as CPython passes declarations down: nested functions, lambdas, comprehensions and class bodies, and a class body's annotations, but not code nested in a class body. r7's annotation scope had dropped an enclosing global (Sol r6 P2); a nested body, lambda, comprehension or class body under a function's global missed it too. - A star import in an import cycle may see its module part-run, before it binds a name or sets __all__ (Sol r6 P3). Where the module, while it runs, may import the importing one, the star import may bind any public name the module binds and binds none surely. Cycles follow every import in a module (even in a function), literal dynamic imports and the packages an import starts; the packages around a module have started before it. No star import in pe-us sits in such a cycle. - A later-line assignment target is tested, so a statement span cut to its first line fails (Sol r6 P3). - Code Python runs when it is used is read as of then, with any later deletion counting: a generator expression's body, and (PEP 695, 3.12+) type-parameter bounds and defaults and type alias values, read like annotations. A type statement binds its alias's name, and a walrus in a generator expression binds around it. Each case is tested on the Python versions whose syntax it needs. - The docstring says the own-statement rule also reports a walrus earlier in the same statement, and a type parameter's own name is not taken as bound; both err toward reporting. - A private name that only an earlier __all__ lists is tested in a cycle; r8's cycle rule exports every public name, so the earlier-__all__ test no longer protected that path. - spm.py: the subsample override's comment says which cores it is for. Core before 3.33.1 exports calculated values from subsample (policyengine-core#633); from 3.33.1 subsample rebuilds from recorded inputs and doesn't call the override (policyengine-core#573). pe-us locks core 3.32.27 and policyengine.py bundles 3.33.3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answers review r7 of this PR and items P2-2 to P2-4 and P3-7 of review r8 of the cross-country approach. Opus 5.5 ran both, since no Codex lane was free. Changes the guard, one comment in spm.py and pr.yaml. - A class body that binds a name anywhere (an annotation alone or a del counts) reads it from its namespace, then the module and builtins, never from a function around it. The guard fell through to the enclosing function and took its binding as sure, so a reform-factory class that annotates lib read the module's numpy unflagged. What the body evaluates (annotations, method defaults and annotations, type-parameter bounds and type values) now reads the same way. - A walrus that may not run binds nothing surely: in a comprehension's later iterables, conditions and element, after the first operand of and, or or a chained comparison, in a branch of a conditional expression, and in an assert, which python -O drops. - Import cycles also run through the submodules a star import of a package loads (those its __all__ may name, or all of them where __all__ is built otherwise) and through any call whose literal arguments name a module as a dynamic import would, under any name. No star import in pe-us sits in a cycle. - pr.yaml: the lint job, which installs the locked core, also runs the start-month tests. Every test job resolves the latest compatible core, where subsample never reaches spm.py's export override. - spm.py: the override's comment says that from 3.33.1 it changes only to_input_dataframe and to_input_dict with include_computed_variables=True. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A literal __import__ whose fromlist holds "*" (a list, tuple, set or string; positional or keyword; relative or under another name) loads what a static star import of that package would, so its submodules are cycle edges. The packages around a module have run before it, and so have the modules they imported as they ran, but the module's code may call their functions: imports in their functions, lambdas, generator expressions, annotations, type parameters and type values are cycle edges too. Imports are split by when they may run to tell the two apart. In pe-us, five lazy imports in four functions (system.py, data/ economic_assumptions.py, tools/per_capita_uprating.py) now put 156 of 6,829 star imports in a possible cycle; that only widens what they may bind, and the package scan's counts are unchanged. The module docstring names changed package search paths and import hooks among the limits. Answers Sol's PR review r8 (findings 1 and 2) and Sol's APPROACH review r9 P2-2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…obals Another module may have loaded a module, so code can reach it as an attribute of its package without importing it, and call its functions. Each name, attribute chain, getattr with a literal name, sys.modules read with a literal key, and literal dynamic import now names the paths its first name may: what the module's imports and assignments bind it to (to a fixpoint, so x = x.sub resolves), the submodules a star import of a package binds, and in a package's __init__ its own submodules. Each branch of a conditional expression, and or or counts, and so does a walrus. Only paths that may lead to a package module are kept. These paths are cycle edges, split by when they may run. A star import of a package loads each dotted __all__ entry with the packages on the way, and a computed __all__ may name any module below the package. A relative __import__ resolves against the package its globals give, as Python reads them: __package__, else __spec__, else __name__ and __path__. import_module resolves against a literal package or __name__. Anything computed reads as the module's own package, and a missing package imports nothing. In pe-us the package scan is clean, references add no cycle edge, and 156 of 6,829 star imports are still in a possible cycle. The docstring's limits now name bindings other than an import or a plain assignment. Answers Sol's PR review r9 (the P2 and both P3s). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main added tools/social_security_preflight.py (#10400), which checks a stored dataset's SHA-256 before a Social Security reform is scored, as system.py checks the default dataset's. Its hashlib import and _file_sha256 are exempt like system.py's, so the calls that reach _file_sha256 are no draw helper calls. The package scan of this head is clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main raised pe-us's core floor to 3.33.1 (#10400). From 3.33.1 core's subsample rebuilds from recorded inputs and never calls spm.py's _get_exportable_input_periods override (policyengine-core#573), so the override only changed to_input_dataframe and to_input_dict with include_computed_variables=True, which nothing calls. It goes, with PRESENCE_TESTED_INPUTS. section_911's call passes include_computed_variables=False and is unaffected. The lint job's start-month step ran the tests on the locked core because that core's subsample reached the override. The lock is now 3.33.2, so it no longer does; the PR test job's microsimulation group runs the same file on the latest core. The step goes. The subsample tests stay: a calculated default must still not come back as a supplied column. They pass, with the other start-month tests, on cores 3.33.1, 3.33.2 and 3.33.12. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y wins in globals; dict fromlists
Answers Sol PR review r10's three guard P3s:
- analyse() now passes the module's name to _dynamic_imports, as the
import graph already did, so import_module('..taxsim', __name__) in
policyengine_us.tools.helper names policyengine_us.tools.taxsim for the
offline-import check, not policyengine_us.taxsim.
- A dict literal given as __import__'s globals keeps the last value of a
repeated key, as the dict Python builds does, and only then reads a None
value as absent ({'__package__': 'pkg', '__package__': None, ...} falls
through to __name__).
- A dict literal fromlist is read by its keys, as Python iterates it.
Adds a test that reference paths stay within the known paths and the names
the rules read, which bounds the binding fixpoint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answers Sol PR review r11's guard P3: Python iterates an __import__
fromlist, so a literal * entry of a list, tuple or set and a literal **
entry of a dict give their own items in its place. The guard dropped them,
so __import__('numpy', fromlist={**{'random': None}}) went unreported, and
a fromlist of {**{'*': None}} loaded no star submodules in the import graph.
- _iterated() reads a literal fromlist as Python iterates it, recursing
through * and ** entries; computed parts give nothing, as before.
- _dict_entries() reads a dict literal's literal ** dicts in place, so a
globals dict built with one resolves its package as Python does. Only a
computed key or ** entry falls back to the module's own globals; a
constant key that is not a string no longer forces that fallback.
Tests: three stochastic-import rows, three star-load layouts and an empty
** control, and six relative-import table rows, each checked against real
__import__ on CPython 3.11 to 3.14.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Answers Sol PR review r12's P3: the r14 cases unpacked one level only, so
a reader that flattened one level would have passed them. Adds rows whose
unpacked entries nest: fromlist={**{**{'random': None}}} and
fromlist=[*[*('random',)]] report the stochastic import, and three
relative-import table rows ({**{**{'x': 0}}}, [*[*['x']]] and globals
{**{**{'__package__': 'pkg.o'}}}), checked against real __import__ on
CPython 3.11 to 3.14. No code or existing test changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
r15's mutation run left one mutant alive, "sys.modules.get names nothing": the fallback reads any call's literal first argument as an import, so the old rows passed. It also names the top package, as __import__ returns it, so an attribute of the result reaches a sibling module that sys.modules never would. Rows for `[]` and `get` pin that. No code changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Case 24 of medicaid_community_engagement_pass_through_eligible.yaml and Cases 20 and 23 of is_snap_work_registration_exempt_non_age.yaml set person_id: 1 to start a block in February. The situation path reads the household position instead, so CI failed Case 24 and Case 20 once this PR left draft. Case 23 kept passing, but its block then covered January, so it no longer tested the applicant prong. All three now supply the month. Test that presence reads the inputs the simulation holds. Main's #9698 made pe-us's set_input record later inputs in input_variables, so r16's mutation run left "presence from the input_variables snapshot" alive. The list still keeps a deleted input's name and misses a write through the holder, and the new tests pin both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SNAP work requirements README said the start month hashes from a supplied person_id, and comments in two YAML files named a hash key. They now state what the model does: a dataset stores the month, one without the column still hashes person_id for now, and a household situation supplies the month or follows the person's position in the household. The README also lists the new input among the data-dependent ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard's docstring now says it looks for draws and not for the clock (#2875). The comments on the splitmix64 and Universal Credit entries say which constants the scan recognises, which entries reach the hash and how Simulation.__init__ applies the modifier. Two test rows follow PolicyEngine/policyengine-us#10447 at 221f2fe44, and a changelog fragment records the guard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PR Review: Store the UI start month as a dataset input instead of hashing person_idSummaryThe PR adds a stored input,
The PR also adds a code-health guard, I checked the behavior against main and it holds:
One should-level gap stays open. Two new terms in the formula have no test: the CriticalNone. Should address
Suggestions
Verified correctPosition table and converted YAML cases
Situation path matches main
Data-built path without the column matches main
Supplied column and validation errors
Variable definition and readers
Hand-checks. months = ceil(weeks × 12 / 52); January position = (0 − (start − 1)) mod 12; the person receives when position < months.
Microsimulation data test
Guard on CI and on the merged tree
Other checks
Axiom line assessment
CI statusAll 36 checks pass at 221f2fe (run 41978849728, 2026-11-05), re-checked just now; the head is unchanged. That run tested the merge with main as it stood on 2026-11-05. Later main commits are covered by the merged-tree guard run above. Branch statusThe branch is 24 commits ahead of main and 54 behind.
Verdict: REQUEST_CHANGES |
DTrim99
left a comment
There was a problem hiding this comment.
Requesting changes per the review above: 0 critical, 1 should (the negative half of the start-month range check and the position % 12 wrap are unpinned; a parametrized -1 case and a 13-member YAML case are given), 6 suggestions. Behavior matches main and the guard passes on the merged tree.
policyengine_us/parameters/gov/usda/snap/work_requirements/README.md: Keep the stored start-month documentation and main's Microcosm names and links. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Reject fractional and out-of-range months before integer conversion. Cover the thirteenth household position, person-specific receipt, and receipt recalculation after a root cache refresh. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Keep the package allowlists and package checks together. Recognize literal string formatting, specific checksums, and direct returns from class hash methods. Allow the SHA-256 checksum in the offline federal tax history generator. Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
A month stored by a dump restore or a reform now raises the named error, and a neutralized household input is ignored with Core's warning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-written for Max, by Claude Code for Max Ghenis. Both terms named here have tests at 2c9a04f: test_out_of_range_start_month_raises_naming_it includes a -1 case, and is_receiving_unemployment_compensation.yaml has the thirteenth-household-member case. A Codex review at that head closed the remaining findings.
|
Agent-written for Max, by Claude Code for Max Ghenis. Merge record for
|
Agent-written for Max, by Claude Code and a Codex cloud task for Max Ghenis; no person has reviewed it yet.
Why
CPS ASEC reports annual unemployment compensation and weeks unemployed. The model can use a stored input to place the receipt block within the calendar year.
What changes
Add the annual person input
unemployment_compensation_start_month. Dataset inputs must provide whole months from 1 through 12 for every person when the column is present. A missing dataset column keeps the legacy hash.Household situations use a supplied month or the member's household position. The 13th position starts the sequence again in January.
The code-health check detects recognized engine-time draws. Its scanner is now in
_engine_draw_scan.py, and the package allowlists stay with the package checks.Receipt checks each annual value it reads, including one that a restored dump or a reform’s formula stores, and raises the named range error for anything other than a whole month from 0 through 12. In a household situation, zero selects the month for the person’s household position. Zero in a recorded dataset column raises the missing-month error.
A neutralized
unemployment_compensation_start_monthignores household inputs with core’s warning. The input check does not run on them.Invariants
drop_computed_arrays()before recalculating.Plan
Add the column to the pinned national and local-area Microcosm builds, verify receipt through the adapter, and update adapter provenance before retiring the hash.
Tests
CI runs the start-month tests, the scanner tests, the package randomness guard and the five YAML files that read the receipt rule. The start-month tests now include a month stored without the input check, a month a reform calculates, and neutralized scalar and axis inputs. These four cases have not been run elsewhere.
axiom: n/a: engine and data plumbing; the SNAP exemption rule (7 CFR 273.7(b)(1)(v)) is unchanged.
🤖 Generated with Claude Code