Skip to content

Keep loaded roles and IDs through subsample without backing variables - #622

Draft
MaxGhenis wants to merge 5 commits into
masterfrom
fix/subsample-preserve-roles
Draft

MaxGhenis wants to merge 5 commits into
masterfrom
fix/subsample-preserve-roles

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Simulation.subsample() rebuilds the simulation from a person-level frame. Before this change, the frame could omit structural fields that had no backing variable. The loader uses those fields to identify people, group them into households, and assign roles. Missing role columns could cause the reload to assign the default role to every member, or raise when the default was absent or at capacity. Missing ID columns could also make the rebuild fail. policyengine_core/simulations/simulation.py:1119, :3688.

The case was found during review of PolicyEngine/policyengine-core#595.

Before and after

The country template example removes person_household_role, sets default_role = "first_parent", and loads memberships [0, 0, 0, 1] and roles [first_parent, child, child, first_parent]. It then runs subsample(n=2, seed=0). tests/core/test_subsample_explicit_roles.py:57.

| Stage | First parents per household | Children per household |
|---|---|
| Original load | [1, 1] | [2, 0] |
| Historical subsample on 1cccc278e | [3, 1] | [0, 0] |
| Historical subsample with #595 applied | Capacity ValueError | Rebuild interrupted |
| Subsample with this PR | [1, 1] | [2, 0] |

With no backing ID variables, the array tests load people [100, 101, 102] with memberships [10, 10, 20]. Both samples and a fresh load of the sampled flat file retain those labels. tests/core/test_subsample_explicit_roles.py:397.

Changes

  • The rebuild includes loaded person IDs, membership IDs, and roles for fields without recorded inputs. Fields without a backing variable use the __eternity suffix. The sampled flat file uses its membership labels as group IDs. policyengine_core/simulations/simulation.py:3688, :1216, :3870.
  • String role columns carry loaded keys. An unmatched member receives a key outside the entity’s flattened keys, so it reloads unmatched even if the entity defines "" as a role. policyengine_core/simulations/simulation.py:3752.
  • Integer role columns carry flattened slot indices. Two slots can share a key and keep separate counts. When a detached role’s key identifies one slot, it resolves to that slot. policyengine_core/simulations/simulation.py:3725.
  • The loader tracks the structural columns it reads. It leaves those columns out of ignored-column warnings and still reports genuinely unknown columns and unused period-suffixed columns. policyengine_core/simulations/simulation.py:1161, :1284, tests/core/test_subsample_explicit_roles.py:329, :341.

Invariants

Recorded structural inputs take precedence over the loaded values and can change the roles or household partition that the sample uses. For flat files, the loader takes the first matching column in dataset order. Subsampling exports recorded periods in sorted order, so the reload can select a different period. For example, a source with its 2025 role column before its 2024 column loads the 2025 roles and can rebuild with the 2024 roles. policyengine_core/simulations/simulation.py:1124, :3458, :3651, tests/core/test_subsample_explicit_roles.py:253, :264.

  1. Roles. Where the rebuild uses loaded roles, it carries matched keys and leaves unmatched members unmatched. Integer reconstruction preserves the individual flattened slots. policyengine_core/simulations/simulation.py:3725, :3752.
  2. Whole households. Sampling keeps all rows associated with each selected household in the exported data. When the export uses loaded memberships, those rows form whole source households. policyengine_core/simulations/simulation.py:3708, :3810.
  3. Role counts. With the same members and role assignments, nb_persons(role) returns the same counts. The integer regression checks this with two adult slots. tests/core/test_subsample_explicit_roles.py:205.
  4. Defaults and backing variables. The structural fallback works with or without backing variables. The tests cover bounded, unbounded, unmatched, and absent defaults, and both entity-specific and generic role columns. tests/core/test_subsample_explicit_roles.py:96.
  5. Repeat sampling. The tests check role preservation over repeated samples and membership labels after repeated samples from both array formats. tests/core/test_subsample_explicit_roles.py:116, :397.
  6. Integer reconstruction errors. When there is no recorded integer role input and a member’s slot cannot be identified, subsampling raises ValueError before replacing the dataset or populations. policyengine_core/simulations/simulation.py:3737, tests/core/test_subsample_explicit_roles.py:153.
  7. Warnings. Ignored-column warnings omit the columns the loader consumes for structure. tests/core/test_subsample_explicit_roles.py:304, :316, :379.

Tests

Ran with Python 3.13.5 in an editable install.

Command Result
timeout 900 python -m pytest -q -p no:cacheprovider <file> for each of 29 focused files 382 passed
timeout 900 make test-country-template 39 passed
timeout 1500 python -m pytest -q -p no:cacheprovider tests 4,364 passed, 4 skipped, 3 xfailed

All commands in the table exited 0. The focused runs included all subsample modules, default roles, dataset warnings, the simulation builder, role projectors, dump and restore, and the YAML runners. The explicit-role module now has 41 example cases. The two Hypothesis properties run with 200 and 100 generated examples, plus their explicit examples. tests/core/test_subsample_explicit_roles.py, tests/core/test_subsample_explicit_roles_property.py:81, :143.

ruff format --check and ruff check passed on the changed Python files and the PR’s shared role fixture. towncrier check --compare-with origin/master found the .fixed.md fragment. The branch already contains the pinned master tip, and both explicit-role modules passed on the merge-check branch.

The PE-US Core gate and full-sample controls require real-data runs and remain with the maintainer.

axiom: n/a (Core engine infrastructure).

🤖 Generated with Claude Code

MaxGhenis and others added 4 commits October 18, 2026 14:37
subsample rebuilds the simulation from a person-level frame of recorded
inputs plus the structural leaves retain_structure adds. retain_structure
skipped any leaf the tax-benefit system had no variable for, so a system
without person_<entity>_role rebuilt every member with the default role
(silently on master; as a capacity error once #595 lands), and a system
without person_id or person_<entity>_id variables failed to subsample.

retain_structure now carries person IDs, memberships and role keys whether
or not a variable backs them. An integer role variable cannot hold "no
role", so subsample raises before changing anything instead of writing
role index 0. The loader records the columns it reads for structure and
no longer reports them as ignored.

Found in review P3-1 on #595.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For any households of bounded, unbounded and unmatched role keys, person
order, weights, default role, role source and sample, every kept household
is a whole source household whose role counts (by key and nb_persons)
equal the source's, with or without a role variable, through a second
subsample too, and no structural column is reported as ignored. An integer
role variable keeps the roles or raises before changing anything.

Move the household-table oracle into the shared fixture module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clarify structural input precedence during subsampling and cover loaded role keys across dataset formats.

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

Copy link
Copy Markdown
Contributor Author

Agent review for Max, written by Codex and posted by Antigravity for Max Ghenis (exact reviewed head c71bf164cf32e441e9edeccf277d488bd6dbc8bb).

VERDICT: REQUEST_CHANGES
HEAD: c71bf16

Subsampling makes simulations with string household IDs fail to restore from a dump, and the revised role-preservation claim still fails for unbacked integer roles.

Merge base with fetched master was baf74aa5030f88c766654e4c3bde00db7ddc49e2. The review range from 3ad51585dac7bfd9876e71e38851376f7becfd3f contains one commit and no merges. Reviewed with Codex, GPT-6. Reasoning effort was unavailable.

Findings

  • P1 — Sampled dumps with string household IDs cannot be restored. policyengine_core/simulations/simulation.py:1217. I loaded integer person IDs [100, 101, 102] with unbacked memberships ["h10", "h10", "h20"], then ran subsample(n=2, seed=0). The source dump restored with those labels. The sampled population retained the labels as an object-dtype array, and its dump failed to restore with ValueError: Object arrays cannot be loaded when allow_pickle=False. The same sampled dump/restore sequence succeeded at 3ad51585, where the loader produced numeric group IDs. Preserve homogeneous text labels in a pickle-free NumPy dtype and add a sampled dump/restore test. Group ID loader · Dump and restore
  • P1 — The new guarantee overstates preservation of unbacked integer roles. policyengine_core/simulations/simulation.py:3724 and changelog.d/fix-subsample-preserve-roles.fixed.md:1. With flattened slots [adult, adult, child], generic integer role=[0, 1], and no backing role variable, the loaded counts were [[1], [1], [0]]. After subsample(n=1, seed=0), the counts were [[2], [0], [0]] because export wrote two adult keys and the string loader assigned both to the first slot. The behavior also occurred at 3ad51585. The revised changelog and PR description lines 24, 31, 34, and 36 need to make the integer-backing condition explicit if the code keeps this behavior. Alternatively, carry unbacked integer slot identities and add the unbacked variant to the duplicate-slot test. Role export · Role loader
  • P2 — The fresh-load example needs to name the sampled Dataset object. policyengine_core/data/dataset.py:489, PR description line 18. A new Simulation using the same sampled Dataset retained [10, 10, 20]. A new Simulation wrapping its identical frame with default Dataset.from_dataframe got [0, 0, 1]. Clarify that the example reuses the sampled Dataset, which carries the opt-in. Dataset constructor · Fresh-load test

Earlier findings and description checks

Earlier finding Result at this head
Backed integer roles merged distinct slots Closed for the original case. Generic [0, 1] with an integer backing variable kept [[1], [1], [0]]. The prior head produced [[0], [2], [0]]. A detached role with a unique key passed its regression test. A detached duplicate raised ValueError with the dataset and populations intact.
An unmatched member acquired the empty-key role Closed. ["unknown", "child"] stayed [0, "child"] when the entity defined "". The scratch probe also defined "_" and produced the same result. The prior head assigned the empty-key role.
Repeated sampling lost membership labels Closed for both original array formats. Both draws kept people [100, 101, 102] and membership labels [10, 10, 20] in the population and frame. The seeded draw selected [10, 20] once each, and the weights stayed [1, 1]. The prior head reported [0, 0, 1] after the first rebuild and wrote those labels into the second frame.
Recorded inputs contradicted the former universal invariants Closed in the description. Overriding membership with [10, 20] left person [100] at n=1, seed=0. Loading 2025 roles before 2024 selected [first_parent, child] initially and [child, child] after export and reload. Both behaviors reproduced on the prior head and merge base.
Retired changelog guidance Open outside this delta. The guide and period-order behavior were both unaffected by this round. Neither drafted follow-up was worsened.

The original-load parent and child counts were [1, 1] and [2, 0]. I reproduced [3, 1] and [0, 0] on 1cccc278e, the capacity ValueError on ef0f9d5e2c, and the original counts on the reviewed head. The official #595 description confirms that subsample() could “raise the default-role capacity error.” The account of where it was first discovered comes from the PR author. GitHub showed no reviews or comments on #622. The warning tests confirmed that consumed structural columns are omitted and unknown or unused unbacked columns still warn. PR #595 · PR #622

The annual example uses unchanged synthetic template values. January income is 0, which satisfies the threshold value: 500.0. Age 7 satisfies the under-eight condition, and neither person is under six. The parent count falls from one to zero, so the value: 600.0 parenting allowance goes from 600 to 0. The local formula returns nb_children * amount_by_child. At value: 100.0 per child, the count going from one to two gives 100 to 200. The delta changes no policy formula, parameter, or effective date. Parenting formula · Threshold · Parenting amount · Local formula · Local amount

Verification

  • 382 passed across 29 focused files, each run separately with exit 0 in the existing macOS environment with Python 3.13.9 and pytest 9.1.1. The explicit-role file passed all 41 cases, and the property file passed both tests, configured for 200 and 100 generated examples. The shared fixture was exercised by both.
  • The search found 0 YAML files naming the structural variables directly. I ran the three allowance consumer files separately: parenting_allowance.yaml passed 1, local_benefit.yaml passed 2, and test_with_extension.yaml passed 2. The country-template suite passed 39. All exited 0.
  • Five revision probe runs exited 0 and recorded the expected errors as observations. git diff --check, Ruff format, and Ruff lint exited 0. GitHub showed 19 successful checks, including the changelog check. GitHub checks
  • I did not rerun the full tests/ suite, the separate merge-check branch, or Towncrier locally. The real-data checks in Core’s tests/smoke/test_us.py and PE-US’s policyengine_us/tests/microsimulation/test_microsim.py remain with the maintainer. Inferred from the inspected code, the full-sample controls use the ordinary loader, and the inspected PE-US numeric identifiers still map to the same dense group positions after sampling. I found no added failure risk for those paths in this delta. No microdata was read or downloaded. PE-US controls

This branch has not been deployed

No deployments
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.

1 participant