diff --git a/changelog.d/1035-capital-gains-control-concept.fixed.md b/changelog.d/1035-capital-gains-control-concept.fixed.md new file mode 100644 index 0000000000..0e190d99d2 --- /dev/null +++ b/changelog.d/1035-capital-gains-control-concept.fixed.md @@ -0,0 +1 @@ +Rebase Historic Table 2 capital-gains rows only onto the Table 1.4 Schedule D taxable-net-gain control, the concept `capital_gains_gross` measures. Feed order no longer picks the control: congressional-district and Historic Table 2 rows (Form 1040 line 7, gain or loss) never qualify, a tie between matched records refuses the compile, and a line-7 row with no usable control is dropped instead of shipping as a level. On the pinned feed the 51 `national_state` state return-count targets move from 29,599,604 (2.39x the national target) to 12,289,836 (microcosm#1035). diff --git a/changelog.d/1038-cd-capital-gains-shares.fixed.md b/changelog.d/1038-cd-capital-gains-shares.fixed.md new file mode 100644 index 0000000000..cd9ac24eb3 --- /dev/null +++ b/changelog.d/1038-cd-capital-gains-shares.fixed.md @@ -0,0 +1 @@ +On the `full` target surface, congressional-district capital-gains rows now enter as shares of the district file's own US row scaled to the Table 1.4 Schedule D control, as Historic Table 2 rows do; the file's US row retires, and every capital-gains share row names its denominator in `soi_share_total_source_record_id`. On the pinned feed the district file's states and districts each move from 29,845,710 returns (2.41x the national target) and $1,522.2B (1.198x) to 12,392,020 and $1,270.9B, and no congressional-district family sums past its national target on `full` (microcosm#1038). diff --git a/changelog.d/1038-cd-source-column-exclusions.fixed.md b/changelog.d/1038-cd-source-column-exclusions.fixed.md new file mode 100644 index 0000000000..dc49547865 --- /dev/null +++ b/changelog.d/1038-cd-source-column-exclusions.fixed.md @@ -0,0 +1 @@ +The US fiscal-target compiler drops congressional-district SOI facts read from an IRS column their measure id does not mean, through a new reviewed register keyed by (measure id, IRS column), `US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`: N18425/A18425 (state and local income taxes, Schedule A line 5a) published as the limited SALT deduction, and N85530/A85530 (additional Medicare tax, Form 8959 line 24) published as the premium tax credit. It replaces the hard-coded congressional-district PTC-amount check, refuses a listed district fact that names no column, and appears in the exclusion receipt and the release coverage report. On the pinned feed the full surface loses the 976 district SALT specs, which summed to 1.98x the national target, and the 488 district PTC-return specs (microcosm#1038). diff --git a/changelog.d/us-restamped-source-vintage-aging.fixed.md b/changelog.d/us-restamped-source-vintage-aging.fixed.md new file mode 100644 index 0000000000..590ebb08a7 --- /dev/null +++ b/changelog.d/us-restamped-source-vintage-aging.fixed.md @@ -0,0 +1 @@ +Read restamped Chronicle facts at their data year. The pinned US feed stamps five packages' pinned files as ty2023: 26,893 facts from the TY2020 W-2 table and the TY2022 congressional-district (PolicyEngine/chronicle#117), state and IRA tables. The compile detects a restamp either by its registered file digest or by a `raw_r2_key` year earlier than its period. It refuses the compile unless a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry matches. If one matches, aging starts from the data year. It also refuses where a restamp would outrank newer truthful data in latest-vintage selection, or would sit in an aging growth index. A rebased restamp is admitted only as a share of a restamped total of the same package, stamp and data year (`soi_share_total_source_record_id`): its share is read at the data year and its aging still starts at the control's period. On the pinned feed (`51aa40f`) the `national_state` W-2 Box 7 tips amount target moves from $28.28B, aged from 2023, to $34.29B, chained from TY2020. The surface keeps 6,102 targets, and its registry moves from `e1f9906bf0e0` to `61f5cac06310`. On the full surface, 13,176 congressional-district-file dollar targets age from TY2022 under the current series policy: the measures on the AGI series move +3.05% and net capital gains -23.9%. diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index db5f92adc5..c3fec3c67c 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -79,6 +79,24 @@ their role is `soi_fiscal_distribution`, so `totals` is unchanged: | **Admin specs** | **4,380** | **760** | **31,474** | With the 487 population marginals `state` now calibrates to 4,867 targets. + +**Since microcosm#1038** the compiler drops the district file's facts read +from the wrong IRS column (`US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS` in +`us_runtime/fiscal_targets.py`): the SALT rows read from N18425/A18425 +(state and local income taxes) and the premium-tax-credit rows read from +N85530/A85530 (additional Medicare tax). `state` and `state_cd` keep their +counts. `totals` loses the 487 district-file premium-tax-credit return rows, +and `full` loses those and the 974 district-file SALT rows. Both also lose +the Historic Table 2 rows of those measures that the crosswalk had copied to +the nine at-large districts (18 in `totals`, 36 in `full`): the crosswalk +copies a state row to an at-large district only for a measure that the +district file carries. Measured on the `41b2fb2` feed on 25 November 2026: + +| Family | `state` | `totals` | `full` | +|---|---:|---:|---:| +| `irs_soi` | 4,227 | 102 | 29,824 | +| **Admin specs** | **4,380** | **255** | **29,977** | + The rest of this section describes the 2026-09-22 measurement. The 487 population marginals (51 states and 436 congressional districts) are @@ -104,8 +122,12 @@ congressional-district file. The feed-gated test ### What `totals` contains, and what it does not -All 607 SOI specs that `totals` keeps are ACA premium tax credit measures (547 -returns, 60 amounts), 454 of them at congressional-district geography. +All 607 SOI specs that `totals` kept on 2026-09-22 are ACA premium tax credit +measures (547 returns, 60 amounts), 454 of them at congressional-district +geography. Since microcosm#1038 it keeps 120 (60 returns and 60 amounts, +all Historic Table 2: the 51 states and the 9 at-large district copies), 18 +of them at district geography: the 487 district-file return rows read +N85530, additional Medicare tax, not the premium tax credit. `_soi_target_role` in `us_runtime/fiscal_targets.py` gives named roles only to country-level all-income-range facts, the all-income-range PTC measures and the W-2 tip items; every other SOI fact gets `soi_fiscal_distribution`, @@ -199,8 +221,11 @@ district rows, are mostly 1.00 to 1.10. chained SOI and CBO series (about 1.120). The smallest amount factor, 1.03, is that aging ratio alone. Correcting the district file's stamp (#1030) would remove the aging part only. -- **Two factors reflect known level differences:** taxable interest (2.35 to - 2.70, the Table 4.3 rebase) and capital-gains amounts (0.77 to 1.00). +- **Taxable interest reflects a known level difference** (2.35 to 2.70, the + Table 4.3 rebase). Capital-gains factors sit near 1: since microcosm#1038 + (#1040) both files' capital-gains rows are shares of the same Table 1.4 + control (amounts 0.93 to 1.20, median 0.98; before, 0.77 to 1.00; returns + 0.98 to 1.00). - **The largest single-state factors** were on qualified and ordinary dividends (Hawaii, 2.68 and 2.17), tax-exempt interest (Utah, 1.43) and rental income (New York, 0.72), where the two tables disagree about one @@ -292,8 +317,8 @@ bridged state row records its sibling and bridge factor. | Rows | Specs on the pinned feed | Why | |---|---:|---| -| District-file `limited_state_local_taxes_*`, both geographies | 974 | Column A18425/N18425 is state and local income taxes, not the limited SALT deduction (microcosm#1038) | -| District-file `premium_tax_credit_returns`, both geographies | 487 | Column N85530 is the additional Medicare tax, not the premium tax credit (microcosm#1038) | +| District-file `limited_state_local_taxes_*`, both geographies | 974 | Column A18425/N18425 is state and local income taxes, not the limited SALT deduction (microcosm#1038). Since #1038 the compiler drops them first; `STATE_CD_DEFECTIVE_CD_FILE_MEASURES` stays as a second fence | +| District-file `premium_tax_credit_returns`, both geographies | 487 | Column N85530 is the additional Medicare tax, not the premium tax credit (microcosm#1038); dropped first by the compiler, as above | | District `tax_filer_individual_count` | 436 | No state parent in either vintage, so it could not nest in a bound state target | | District rows of states with one district on the 117th plan (AK, DE, DC, MT, ND, SD, VT, WY) | 459 | The SOI file has no sub-state rows there. These rows are the state total copied, or for Montana split by population, so they carry no district information | | Historic Table 2 rows copied to at-large districts | 360 | The same copies from the other vintage | @@ -301,12 +326,14 @@ bridged state row records its sibling and bridge factor. | District rows of the four out-of-band rebase blocks | 34 | The factor band (above) | | Bridged state rows whose sibling ratio is out of band | 4 | The factor band (above) | -PR #1040 (awaiting a ruling) excludes the same SALT and PTC columns in the -compiler and rescales the district file's capital-gains rows by one national -factor. `state_cd` already takes district capital gains as within-state -shares of Historic Table 2, which a national factor does not move, so their -level changes only when Historic Table 2's own capital-gains rows do -(#1036). +Since microcosm#1038 the compiler excludes the same SALT and PTC columns +(`US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`, #1224) and rescales the +district file's capital-gains rows by one national factor per measure +(#1040). `state_cd` takes district capital gains as within-state shares of +Historic Table 2, which a national factor does not move, so their level +changes only when Historic Table 2's own capital-gains rows do (#1036). Its +capital-gains rebase factors move by the reciprocal of that factor, and no +factor-band verdict or contract count changes. North Carolina's district rows are bound. Before #1043 the packaged 117th→119th crosswalk was built from NC's 2016 plan rather than the 2019 plan @@ -558,7 +585,10 @@ record one of the four modes, before any release directory exists. calibrate stage's peak is the artifact write. - A checkpoint written before the sparse matrix (measures as dense H5 columns) is refused by `--stage calibrate`; re-run `--stage materialize`. -- To reproduce the 2026-09-22 hours rebuild (#974), pass `--soi-mode totals`. +- To reproduce the 2026-09-22 hours rebuild (#974), pass `--soi-mode totals` + on a compiler from before microcosm#1038; after it, `totals` no longer + carries the 487 district-file premium-tax-credit return rows that run + calibrated to. To reproduce a build that ran as `full` after `b7922b089`, pass `--soi-mode full`. - A checkpoint materialized under an earlier default records its own mode and diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 0f04cb794b..94d3c4e1c0 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -555,6 +555,47 @@ compiled register goes from 32,867 to 32,843 targets, and the count, the only change: 32,842 compiled targets and 5,694 in `national_state` (`d315c75804ef`). +**Erratum (27 September 2026, microcosm#1035).** Row order changed too. The +new feed is sorted by the re-derived `aggregate_fact_key`s, and the +capital-gains rebase kept the first of two equal-period controls. The +congressional-district US row (TY2022 data stamped ty2023) now sorted ahead of +Table 1.4 ty2023. It took over the returns control and raised the 51 Historic +Table 2 state return counts from 12,289,836 to 29,599,604. The control is now +chosen by concept and period alone +([us-soi-capital-gains-concepts.md](us-soi-capital-gains-concepts.md)). The +counts are unchanged and `national_state` is `65e4dde11c83` on this feed. On +the 2026-10-04 `51aa40f` re-pin, whose capital-gains cells are identical, the +same 60 return counts move and `national_state` goes from `e1f9906bf0e0` to +`882f4764a248` at 6,102 targets. + +**Follow-up (microcosm#1038).** On the `full` surface, the +congressional-district file's capital-gains rows are shares of its US row +scaled to the same control, and the US row retires (#1040). The package's +four mislabeled columns are dropped (#1224): N18425/A18425 (state and local +income taxes), read as the limited SALT deduction, and N85530/A85530 +(additional Medicare tax), read as the premium tax credit. On the `51aa40f` +feed that leaves 31,784 compiled targets, all of them on `full` +(`6e1ac91262bc`). `national_state` keeps its 6,102 targets and values and +moves from `882f4764a248` to `84504a7afd57` only because its 102 Historic +Table 2 capital-gains rows now name their share denominator in +`soi_share_total_source_record_id`. + +**On the `41b2fb2` feed** (25 November 2026), with microcosm#1035, #1038 and +#1030 merged together, the release compile keeps 31,748 targets (`full` +`4cc4cfb7a147`, from 33,250 at `bf021cdc9749`), and `national_state` keeps +6,102 at `4dfe25b1238a` (from `c698e70d33ce`). + +- Besides the 1,466 specs above, 36 Historic Table 2 SALT and + premium-tax-credit rows leave `full`. The crosswalk copies a state row to an + at-large district only for a measure that the district file carries. Once + the mislabeled columns are dropped before the crosswalk, the district file + carries no SALT or premium-tax-credit rows, so the copies of those measures + for the nine at-large districts go too. Each copy repeated its state row. +- In `national_state`, 52 values move. The 51 Historic Table 2 state + net-capital-gains return counts move ×0.415203: they sum to 12,289,836 + against the national Table 1.4 target of 12,392,020, from 29,599,604. The + W-2 Box 7 tips amount moves from $28,280,884,269 to $34,287,530,779. + The labelled feed exposed one latent defect in microcosm, fixed in this change: `apply_us_medicaid_enrollment_substitutions` built Rhode Island's substituted spec by cloning a neighbouring state's spec and kept that state's @@ -565,6 +606,143 @@ and target id, and the register entry carries a reviewed `state_name` (`_geography_fallback_label` is UK-only, so the label cannot be derived from the FIPS code). +## Restamped packages + +Five Chronicle packages in this feed restamp their data: 26,893 observation +facts carry a later period than their publisher file describes. A Chronicle +package can pin one file with `artifact.artifact_year` and still render +`{year}` into its period, record ids and vintage from the build year. The +scope builds these five at 2023, so each emits its pinned file as `ty2023`. +PolicyEngine/chronicle#117 reported the congressional-district case in July. +microcosm#1030 found the other four, and PolicyEngine/chronicle#292 (merged +2026-09-28) refuses these builds at source. The `51aa40f` pin is `c5e5bf8` +plus one package, so it still carries all five. + +| Package | File | Data year | Facts stamped ty2023 | +|---|---|---|---| +| `soi-congressional-district-2022` | `22incd.csv` | TY2022 | 26,880 | +| `soi-w2-statistics-2020` | `20in04w2all.xlsx` | TY2020 | 5 | +| `soi-state-2022` | `22in54us.xlsx` | TY2022 | 4 | +| `soi-ira-roth-contributions-2022` | `22in06ira.xlsx` | TY2022 | 2 | +| `soi-ira-traditional-contributions-2022` | `22in05ira.xlsx` | TY2022 | 2 | + +The data years come from the files themselves: the title cells ("Tax Year +2020", "Tax Year 2022"), cell-for-cell equality with the ty2020 W-2 twins, +and the TY2022 county file for the congressional-district data. + +**When it started.** The previous pin already carried 26,891 of these facts: +- every congressional-district, state and IRA row; +- the ty2023 W-2 taxpayer count, 401(k) and Roth 401(k) rows. + +The 2026-09-18 re-pin added the other two: the ty2023 tips amount and return +count. These are the "W-2 Social Security tips for 2023 (2)" cells listed +under [What moved and what did not](#what-moved-and-what-did-not). Before +them, the only tips amount was the ty2020 row, which would have aged on the +chained SOI wages bridge from 2020. The previous pin cannot compile on main, +so that is read from the code, not observed. The restamped row won +latest-vintage selection and aged on the direct CBO ratio from 2023, +reaching $28.28B at 2024 instead of the $34.29B it gets aged from its data +year. + +**What the compile does** (`us_runtime/source_vintage.py`). Two rules detect a +restamp: +- the fact's `source.source_sha256` is a registered file and its period is + after that file's data year; +- its `source.raw_r2_key` names an earlier year than its period. + +Each detected fact must match a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry, +or the compile refuses. For matching specs, the readings that aging and the +period contract use move to the data year: +- `source_period`; +- `uprating_to_period`, for specs rebased onto a restamped control; +- `uprating_from_period`, for a restamped row rebased as a share of a + restamped total of the same package, stamp and data year (the total its + rebase names in `soi_share_total_source_record_id`). + +A share's `uprating_to_period`, where its aging starts, stays at the control's +period. The stamp cancels in row / total, and the level and its period are +the control's. Starting the aging at the data year instead would apply the +control's growth from the data year to its own period twice: for the +congressional-district capital-gains shares that microcosm#1040 proposes, +x0.761. Any other rebased restamp refuses the compile: one with no named +total, a truthful total, or a total from another package, stamp or data year. + +The stamp is kept in `source_vintage_stamped_period` (and, for a share's +reading period, `uprating_from_period_vintage_stamped_period`). Values and +target names do not change. Two readings still see the stamp, because moving them would +change which fact wins: +- **Latest-vintage selection.** The compile refuses where a restamp would + outrank a truthful fact dated after its data year. +- **The choice of a rebase control.** + +A restamped fact inside an aging growth index is refused outright. + +The key-year rule is exact for single-year IRS files. A multi-year release +keyed by its publication year can carry later columns: BEA's 2024-keyed +`SAINC.zip` has a 2025 column. A truthful build of such a column needs a +`US_LATER_PERIOD_OBSERVATION_EXEMPTIONS` entry. + +**On this feed** (`51aa40f`), compiled as the release does: + +- **`national_state`** keeps 6,102 targets, and its registry moves from + `e1f9906bf0e0` to `61f5cac06310`. On `c5e5bf8`, before the 408 state + AGI-band rows, it moved from `d315c75804ef` to `884bc45ef335` at 5,694; every + figure below is the same on both feeds. + - One value moves: the W-2 Box 7 tips amount, from $28,280,884,269 to + $34,287,530,779 (+21.2%). + - 53 specs change metadata only: 51 Historic Table 2 net-capital-gains + return counts rebased onto the congressional-district US row, and the two + `state_2022` counts. Counts do not age. + - The 51 rebased counts now read `uprating_from_period` and + `uprating_to_period` 2022: a same-year rescale of TY2022 shares onto the + TY2022 CD file's total. +- **Full surface.** 13,176 congressional-district-file dollar targets age from + TY2022 instead of 2023. + - The 23 measures that age on the CBO AGI series (AGI, income tax, the EITC + amounts, taxable interest, dividends, pensions, SALT and the rest) move + +3.05%. + - Net capital gains move -23.9%, because the SOI Table 1.4 chain records + their TY2022 to TY2023 fall. + - Qualified dividends (+8.4%) and Schedule C and partnership income (-0.5%) + move mostly because their series changes: with no SOI bridge for them, the + aging model falls back to the AGI chain from 2022. + - These are changes relative to aging from the data year under the current + series policy, not realized growth. Taxable interest rose ×2.35 from + TY2022 to TY2023 in Table 1.4, far above the AGI link (#117). +- **Metadata only.** + - 13,614 count specs change `source_period`: 13,612 CD-file counts plus the + two `state_2022` counts above. + - 9 more rebased counts are CD-classified and full-surface only. +- **No target.** The 401(k), Roth 401(k), IRA, `state_2022` AGI and EITC + amount rows compile none. + +`test_pinned_feed_restamp_register_matches_the_feed` checks the register +against this feed in both directions. It runs where the feed is present and +skips in CI. A re-pin on a Chronicle commit that stamps truthfully leaves +entries that match nothing, and the test fails until they are deleted. At that +re-pin the scope moves these pairs to their data years (`ty2022`, and `ty2020` +for W-2). IRS has also published TY2023 Historic Table 2 and IRA tables, which +would give true `ty2023` facts. + +Two things needed a decision before that re-pin: + +- **The Historic Table 2 capital-gains returns control.** The CD US row won a + same-period tie on feed order. Stamped truthfully, it would lose to Table + 1.4 ty2023, which counts returns with a taxable net gain (a different + population), and the 51 `national_state` counts would fall 58.5%. The 51 + state counts summed to 2.39× the national Table 1.4 target of the same + compiled variable. Since microcosm#1036 (decision d468) the control is + chosen by concept: no restamped row is a capital-gains control, and the + 60 control corrections above are gone. +- **`SOI_CONGRESSIONAL_DISTRICT_RECORD_SET_ID`**, which names the `ty2023` + record set. This one is still open. + +One mis-stamp runs the other way and is out of reach of both rules. +`bea-regional-state-personal-income-components-2024` reads the 2024 column +under a `cy2023` stamp (416 facts). No target compiles from it, but +`bea_regional.state_wages_salaries` is a deferred parity family. Activating it +before chronicle#292 would calibrate 2024 wages as cy2023. + ## The consumer artifact is refused at this commit `chronicle build-consumer-artifact` validates every row against diff --git a/docs/us-fact-to-target.md b/docs/us-fact-to-target.md index 58a2f26304..24bf605988 100644 --- a/docs/us-fact-to-target.md +++ b/docs/us-fact-to-target.md @@ -337,6 +337,19 @@ should calibrate, add its id to `US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES` with a reason. `us_source_coverage.json`'s `fiscal_target_exclusion_receipt` lists the ids each rule dropped or allowed in a release. +A fact whose package reads the wrong IRS column for its measure id is a +different defect: every fact read from that column is wrong, at every +geography and vintage, while the same measure read from the right column is +fine. `US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS` is keyed by (measure id, +`layout.source_column_id`) for these, so a package corrected to read the +right column passes untouched; its receipt rule is +`source_column_concept_exclusion` (microcosm#1038). Check the column against +the IRS documentation guide before adding an entry, and list a column there +only when it carries another concept. A column that is a component or a +superset of the measure's concept (the district file's line 8a mortgage +interest under `interest_paid_deduction_*`, its line 7 capital gains) needs a +share-or-drop decision instead. + ## 5. Add a reform-coverage probe Probes are **generated data**: author them in diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md new file mode 100644 index 0000000000..7569150b0d --- /dev/null +++ b/docs/us-soi-capital-gains-concepts.md @@ -0,0 +1,267 @@ +# SOI capital-gains concepts and the rebase control + +`capital_gains_gross` targets come from three IRS SOI products that count +different populations under the same measure ids (`net_capital_gains_returns`, +`net_capital_gains_amount`). This page records what each one counts, which +one the model measures, and how `fiscal_targets.py` combines them +(microcosm#1035). + +## What each table counts + +| Source | Columns | What it counts | +|---|---|---| +| Table 1.4 (`23in14ar.xls`) | col 37 / 38, "Sales of capital assets reported on Form 1040, Schedule D: Taxable net gain" | Schedule D returns that net to a gain, and that gain | +| Table 1.4 | col 39 / 40, "Taxable net loss" | Schedule D returns that net to a loss, and the loss after the $3,000 limit | +| Table 1.4 | col 35 / 36, "Capital gain distributions reported on Form 1040" | Returns that report only distributions, without Schedule D | +| Historic Table 2 (`22in55cmcsv.csv`), congressional-district file (`22incd.csv`) | N01000 / A01000 | "Number of returns with net capital gain (less loss)" and its amount, at Form 1040 line 7 (both documentation guides) | + +Line 7 carries a Schedule D gain, a loss-limited Schedule D loss, or +distributions reported without Schedule D (2022 Form 1040 instructions, line +7, Exception 1). Columns 35, 37 and 39 are disjoint: Table 1.3 row 18, "Sales +of capital assets net gain", equals col 35 + col 37 exactly in TY2022 and +TY2023. + +N01000 is the union of the three Table 1.4 populations: + +| Tax year | HT2 US N01000 | Table 1.4 col 35 + 37 + 39 | Difference | HT2 A01000 vs col 36 + 38 − 40 | +|---|---:|---:|---:|---:| +| 2020 | 29,008,620 | 29,003,885 | +0.016% | −0.63% | +| 2021 | 32,996,180 | 33,076,998 | −0.244% | −0.29% | +| 2022 | 30,465,850 | 30,461,045 | +0.016% | −0.17% | +| 2023 | 29,481,840 | 29,434,188 | +0.162% | −0.28% | + +In TY2022, col 37 (12,915,122) is 42.4% of N01000. The amounts are close +(A01000 is 1.4% below col 38), because distributions and capped losses are +small in dollars. The counts differ by 2.36x. + +The congressional-district file covers a subset of HT2: it leaves out +territories, APO/FPO and foreign addresses and returns without a matched ZIP +code. Its US N01000 is 98.0% of HT2's. + +## What the model measures + +`capital_gains_gross` maps to PE-US `capital_gains`, which is short-term plus +long-term gains, i.e. Schedule D before the loss limit. Distributions reported +without Schedule D are the separate `non_sch_d_capital_gains`, with its own +Table 1.4 col 35 target. The SOI materializer counts a tax unit when the +unit's summed `capital_gains` is positive and sums its positive part, so the +count is col 37 and the sum is col 38. The Build P release met col 37 at +12,391,446 against 12,392,020. + +No released record has negative capital gains, so the model has no Schedule D +loss returns. An N01000 count therefore has no model counterpart at any +level. + +## How the targets combine + +- **Controls.** Only a family registered with the model's concept + (`_SOI_CAPITAL_GAINS_FAMILY_CONCEPTS`, today Table 1.4 alone) can supply the + national level, and the latest national all-AGI fact not after the build + period wins. HT2 and congressional-district rows never do, whatever their + period stamp. Two different records at the winning period raise + `AmbiguousSoiCapitalGainsControlError`, so feed order never decides. +- **Historic Table 2 rows** enter only as shares. Each state row is its share + of the HT2 US total, scaled to the control, landed at the control's period, + and tagged `soi_source_concept = form_1040_line_7_net_gain_or_loss` and + `soi_control_concept = schedule_d_taxable_net_gain`. A row with no control + at or after its own period is dropped, because a line-7 level would be a + 2.36x mismatch. The HT2 national all-AGI rows retire because the control's + own row owns the national concept. +- **Congressional-district rows** are not controls either, and their own + targets (on the `full` surface only) enter the same way: each state and + district row is its share of the congressional-district file's US row, + scaled to the control and tagged with the same two concept keys, and the + file's US row retires (microcosm#1038, below). Every share row names its + denominator, the HT2 or congressional-district US row, in + `soi_share_total_source_record_id`. + +The share step assumes that each state's share of line-7 returns equals its +share of Schedule D gain returns. No IRS state product publishes a gain-only +count, so this cannot be checked directly. AGI composition is one measurable +source of difference: weighting each state's HT2 N01000 by AGI class with +Table 1.4's gain share per class would move TY2022 state targets by −2.9% (WV) +to +4.3% (DC), with a median absolute change of 1.6% and no state beyond 5%. + +## How the returns control drifted + +The rebase used to keep the first fact among equal-period candidates. The +July pin listed Table 1.4 ty2023 first, so Build P rebased the 51 state +return counts onto 12,392,020 (factor 0.406751165649407; states summing to +12,289,836). The September re-pin (`consumer_facts_us_c5e5bf8`) sorts rows by +`aggregate_fact_key`, a content hash. There, the congressional-district US row +sorts first; it carries TY2022 data stamped ty2023 (PolicyEngine/chronicle#117). +It became the control (factor 0.97964), and the states summed to 29,599,604, +2.39x the national target of the same model quantity on the same surface. The +amount control happened to stay on Table 1.4, but reversing the feed would +have moved it to the congressional-district row (factor 0.92455 instead of +0.77190). + +## Effect on the pinned feed + +Compiled at 2024 with target aging and the packaged congressional-district +crosswalk, then narrowed to `national_state`: + +| Targets | Before | After | +|---|---:|---:| +| 51 HT2 state return counts, sum | 29,599,604 | 12,289,836 | +| California | 3,774,052 | 1,566,997 | +| Texas | 2,108,705 | 875,540 | +| Florida | 2,093,099 | 869,060 | +| New York | 1,974,435 | 819,791 | +| National Table 1.4 return count (unchanged) | 12,392,020 | 12,392,020 | +| `national_state` registry | `d315c75804ef` | `65e4dde11c83` | + +- All 60 HT2 return-count specs move by the same factor, 0.415202720927. That + is the 51 state rows plus 9 congressional-district proxies, which are on + `full` only. +- The 60 matching amount specs keep their values and gain only the two + concept keys. +- No spec enters or leaves either surface, which keeps 32,842 compiled and + 5,694 on `national_state`. +- The state return counts are back at the Build P values; California's + 1,566,996.66 equals the July scorecard's. + +On the 2026-10-04 `51aa40f` re-pin (#940), whose capital-gains cells are +identical, the same 60 values move by the same factor and the same 60 amount +specs gain only the concept keys: 33,250 compiled, 6,102 on +`national_state`, which goes from `e1f9906bf0e0` to `882f4764a248` (full +`f5bd921d6b21` to `f09571684885`). + +`test_pinned_feed_no_soi_state_family_sums_past_its_national_target` holds +the invariant across all 63 SOI state families on the surface. + +## Congressional-district rows on the full surface (microcosm#1038) + +The release tool's default `--target-surface` is `full`, which also carries +the congressional-district file's rows: a US row, 51 state rows and 436 +current districts per measure. Before microcosm#1038 they compiled as line-7 +levels onto `capital_gains_gross`. On the pinned feed, their states and their +districts each summed to 29,845,710 returns, 2.41x the national Table 1.4 +target of 12,392,020 on the same surface. Their amounts summed to $1,522.2B +against $1,270.9B, 1.198x. The amount gap is mostly the file's TY2022 data +stamped ty2023 and aged from 2023. The count gap is the concept. + +There were two ways to fix this. Option (a) rebases the rows as shares, like +the HT2 rows. Option (b) drops them with a reviewed exclusion. Microcosm#1038 +takes (a): + +- **The share assumption is already the HT2 one.** Each district's share of + line-7 returns stands in for its share of Schedule D gain returns. AGI + composition is the measurable source of difference. Reweighting each of the + 428 numbered districts' N01000 by AGI class with Table 1.4's per-class gain + share moves its share by a median 2.1% (95th percentile 4.7%, largest + CA-18 +9.7%). Amounts move by a median 0.5% (95th percentile 2.4%). +- **Dropping the rows would discard a much larger signal.** District + capital-gains incidence varies far more than state incidence. N01000 per + return runs from 8.3% to 31.5% between the 5th and 95th percentile + districts, against 13.7% to 23.4% across states. Within a state, the + district share left over after the district's AGI distribution has a log + standard deviation of 0.227 for counts and 0.223 for amounts. The + AGI-composition error of the share proxy is 0.024 and 0.009. +- **The rebased return counts agree with the HT2 state rows among the + tightest of the pairs on `full`; the amounts are the loosest pair.** Both files' state rows + stay on `full`. Each of the 45 measures they share pairs two state targets + for every state. After dividing out each pair's common offset (coverage and + aging, which differ by measure), the capital-gains return counts differ by + a median 0.4% and at most 1.4%. The capital-gains amounts differ by a + median 1.8% and up to 28% (Montana), 18% (West Virginia) and 17% + (Mississippi): the widest 95th percentile of the 45 pairs. The cause is item + suppression in the congressional-district file's A01000; Montana's is 32.5% + below HT2's at the state level. Other pairs have worse single states (the + qualified-dividends amount pair: Hawaii, −58%). + +**The two families split the control differently.** The congressional-district +file has no rows for other areas (territories, APO/FPO and foreign +addresses), so its US row equals the sum of its 51 states, and its rebased +states and districts each sum to the control itself. HT2's US row includes +other areas, so its rebased states sum to 99.2% of the control for returns +and 98.0% for amounts. In aggregate, then, the congressional-district +capital-gains targets sit above the matching HT2 shares, by 0.8% for returns +and 2.1% for amounts; state by state they scatter around that (Montana's +amount is 0.73x HT2's, below it, because of the suppression above). This is accepted, not corrected. The model has +households in the 50 states and DC only, and the national Table 1.4 row on +the same surface already asks them for the whole control; the other-area +part of HT2's split is a share no model household can carry. The +alternative, scaling the district file by HT2's 51-state share of its own US +row, would mix the two families' totals in one factor. + +**Vintage.** A share divides a row by the US row of the same package, so the +package's period stamp cancels. The value lands at the control's period +(2023) and ages from there. It is the same whether 22incd.csv is stamped +ty2023, as on the pinned feed, or truthfully at 2022 +(`test_congressional_district_capital_gains_ignore_the_package_stamp`). + +microcosm#1030 corrects restamped facts to age from their data year, but it +refuses any restamped fact that was rebased, so as written it refuses every +compile that carries these rows. It must admit a share whose +`soi_share_total_source_record_id` is a restamp of the same package and +stamp: move `source_period` and `uprating_from_period` to the data year, +and leave `uprating_to_period` at the control's period. Starting the aging at +2022 instead would apply the Table 1.4 2022-to-2023 fall twice (x0.761). +Whichever of the two changes merges second runs its CI on a merge ref that +contains the first; the stamp test above then fails until that narrowing is +in place. + +### Effect on the pinned feed + +Release compile at 2024 on the `51aa40f` feed, as above. "Before" is #1036 on +main; "after" adds microcosm#1038's changes, including the column exclusions +below (#1224), which remove 1,464 of the 1,466 specs: + +| `full` surface | Before | After | +|---|---:|---:| +| Congressional-district capital-gains returns, states and districts (each sum) | 29,845,710 | 12,392,020 | +| Congressional-district capital-gains amounts, states and districts (each sum) | $1,522.19B | $1,270.86B | +| California returns / amount | 3,808,930 / $214.08B | 1,581,478 / $178.73B | +| New York returns / amount | 2,015,540 / $127.96B | 836,858 / $106.83B | +| Compiled targets, all on `full` | 33,250 (`f09571684885`) | 31,784 (`6e1ac91262bc`) | +| `national_state` targets | 6,102 (`882f4764a248`) | 6,102 (`84504a7afd57`) | + +On the `41b2fb2` feed, merged with microcosm#1030, the compile keeps 31,748 +targets (`4cc4cfb7a147`) and `national_state` 6,102 (`4dfe25b1238a`). +[us-chronicle-feed-repin.md](us-chronicle-feed-repin.md) ("Follow-up +(microcosm#1038)") explains the 36 more rows that leave `full`. + +- The 974 congressional-district capital-gains rows move by one factor per + measure: 0.415202720927 for returns and 0.834893818418 for amounts. +- The two US rows retire. +- The Historic Table 2 rows keep their values. The 120 of them (102 on + `national_state`) gain only `soi_share_total_source_record_id`, which is + the whole `national_state` change. + +### Two mislabeled columns in the same package + +On the same surface, Chronicle's `congressional_district_2022` package reads +four IRS columns under measure ids whose concept they do not carry. Of the +package's 56 measures, 50 have a twin in a Historic Table 2 package, and +these four are the only ones that read a different column from their twin: + +| Measure id | Congressional-district column | Doc-guide definition | Column the measure means | +|---|---|---|---| +| `limited_state_local_taxes_returns` / `_amount` | N18425 / A18425 | State and local income taxes (Schedule A line 5a) | N18460 / A18460, limited state and local taxes (line 5e) | +| `premium_tax_credit_returns` / `_amount` | N85530 / A85530 | Additional Medicare tax (Form 8959 line 24) | N85770 / A85770, total premium tax credit | + +The SALT amount rows summed to 1.98x their national target on `full`. The +premium-tax-credit amount was already dropped by a hard-coded check, but the +returns rows compiled as `assigned_aca_ptc` recipients. + +`US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS` in `fiscal_targets.py` now drops +all four, keyed by (measure id, `layout.source_column_id`). It lists them in +the release's exclusion receipt. A corrected package that reads the right +columns passes untouched. A congressional-district fact of a listed measure +that names no column refuses the compile, so a feed schema change cannot +quietly lift the exclusion. + +Of the six measures with no HT2 twin, `interest_paid_deduction_*` reads +N19300 / A19300, mortgage interest paid (Schedule A line 8a), while +`interest_deduction` is the line 10 total (lines 8a-8c and investment +interest on line 9; A19300 is 85.6% of it in the TY2022 US row). That is a +component of the concept, as N01000 is a superset of capital gains, not a +different concept, so it is left out of the register. Whether those rows +should ship as shares of a national line 10 control or be dropped is a +separate decision. It also governs the `state_cd` surface, which bridges +them onto the HT2 basis. + +`test_pinned_feed_no_congressional_district_family_sums_past_its_national_target` +holds the invariant for every congressional-district family on `full`. + diff --git a/packages/microcosm-build/src/microcosm/build/us/target_parity_manifest.json b/packages/microcosm-build/src/microcosm/build/us/target_parity_manifest.json index 800e82c14e..8df9fec8c5 100644 --- a/packages/microcosm-build/src/microcosm/build/us/target_parity_manifest.json +++ b/packages/microcosm-build/src/microcosm/build/us/target_parity_manifest.json @@ -494,7 +494,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -505,7 +505,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -516,7 +516,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -527,7 +527,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -538,7 +538,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -549,7 +549,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -560,7 +560,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -571,7 +571,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -582,7 +582,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -593,7 +593,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -604,7 +604,7 @@ "status": "reviewed_exclusion", "classification": "off_by_default", "reason": "Federal Student Aid loan portfolio tables (chronicle#347). The location, age and debt-size tables bind only in a build that carries the imputed federal student loan balance columns (microcosm#1357: student_loan_targets=True, set by the release tool's --scf-education-debt), and the loan-type, repayment-plan and summary tables stay diagnostic there too; the default compile, which this manifest describes, turns none of them into a target.", - "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 33,250 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", + "evidence": "compile_us_fiscal_target_registry(age_targets=True) + apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: 31,748 targets, none from the feed's 461 ed_fsa facts; sample fact ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", "fence": { "origin": "microcosm#1074 (re-pin to chronicle#347's packages): a source new to the feed, bound as an opt-in family by microcosm#1357. This re-pin did not search the retired us-data pipeline for a student loan portfolio target.", "purpose": "a default build has no federal student loan balance columns, so it cannot materialize these targets; the opt-in keeps a default build and a --scf-education-debt build from failing each other on the one-surface contract.", @@ -655,7 +655,7 @@ }, "irs_soi.congressional_district_2022": { "status": "compiled", - "note": "One US target surface: national, state, and congressional-district facts compile for every calibrated artifact. Geography is a constraint; artifact record count changes only L0, never target membership. There is no local-versus-national surface. Congressional-district rows inform shape while national and state actuals retain control ownership." + "note": "One US target surface: national, state, and congressional-district facts compile for every calibrated artifact. Geography is a constraint; artifact record count changes only L0, never target membership. There is no local-versus-national surface. Congressional-district rows inform shape while national and state actuals retain control ownership. Its capital-gains rows ship as shares of its own US row scaled to the national Table 1.4 control, and that US row retires (microcosm#1038); facts it reads from the wrong IRS column are excluded (US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS)." }, "irs_soi.filing_season_week47": { "status": "compiled" diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py index e0c5613bc3..8eef459947 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py @@ -306,6 +306,7 @@ US_FISCAL_TARGET_LEDGER_REFERENCES, US_FISCAL_TARGET_REFERENCES, US_FISCAL_TARGET_REGISTRY, + US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS, US_FISCAL_TARGET_SPECS, US_FISCAL_TARGET_SUPPORT_EXCLUSIONS, US_JCT_TAX_EXPENDITURE_REFORMS, @@ -1210,6 +1211,7 @@ "US_FISCAL_TARGET_SUPPORT_EXCLUSIONS", "US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS", "US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES", + "US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS", "US_FISCAL_TARGET_COVERAGE_REQUIREMENTS", "US_FISCAL_TARGET_LEDGER_REFERENCES", "US_JCT_TAX_EXPENDITURE_REFORMS", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py index 3d92cfa4c3..fd0516cf15 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py @@ -34,6 +34,13 @@ apply_fsa_student_loan_plan, plan_fsa_student_loan_targets, ) +from microcosm.build.us_runtime.source_vintage import ( + RestampShadowsNewerVintageError, + SourceVintageCorrection, + apply_source_vintage_corrections, + check_restamps_stay_out_of_aging_indexes, + source_vintage_corrections, +) from microcosm.build.us_runtime.target_aging import ( age_us_dollar_targets, enforce_period_contract, @@ -51,6 +58,7 @@ from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_POSTAL __all__ = [ + "AmbiguousSoiCapitalGainsControlError", "US_FISCAL_MACRO_REALISM_BANDS", "US_FISCAL_TARGET_REGISTRY", "US_FISCAL_TARGET_SPECS", @@ -60,6 +68,7 @@ "US_FISCAL_TARGET_SUPPORT_EXCLUSIONS", "US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS", "US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES", + "US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS", "US_FISCAL_LEDGER_PARITY_REGISTRY", "US_FISCAL_LEDGER_PARITY_REPORT", "US_JCT_TAX_EXPENDITURE_REFORMS", @@ -916,6 +925,74 @@ def _us_hierarchy_seed( # every vintage. US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES: dict[str, str] = {} +# Reviewed source-column concept exclusions (microcosm#1038). Each entry is an +# IRS column that a Chronicle package publishes under a measure id whose +# concept the column does not carry, so no fact read from that column +# compiles, whatever its package, geography or vintage, and a package +# corrected to read the right column passes untouched. The key is (measure_id, +# layout.source_column_id) because the IRS column is the definition. The +# congressional-district documentation guide (22incddocguide.docx) defines: +# +# - N18425/A18425 as "State and local income taxes" (Schedule A line 5a) and +# N18460/A18460 as "Limited state and local taxes" (line 5e). salt_deduction, +# like the Historic Table 2 rows of these measure ids, is the limited line 5e +# deduction. +# - N85530/A85530 as "Additional Medicare tax" (Form 8959 line 24) and +# N85770/A85770 as "Total premium tax credit" (Form 8962 line 24; the guide +# prints "8926:24"). N85770/A85770 is what the Historic Table 2 rows of +# these measure ids read and what assigned_aca_ptc measures. The amount was +# dropped before by a hard-coded congressional-district check; the returns +# row compiled as premium-tax-credit recipients. A package corrected to read +# N85770/A85770 compiles as assigned_aca_ptc targets with no further gate, +# which is intended: those columns are the premium tax credit. +# +# Chronicle's congressional_district_2022 package reads these four columns +# under the limited_state_local_taxes_* and premium_tax_credit_* measure ids; +# the 46 other measures it shares with a Historic Table 2 package read the +# same column there. Of the six it has alone, interest_paid_deduction_* reads +# N19300/A19300, "Mortgage interest paid" (Schedule A line 8a), while +# interest_deduction is the line 10 total (lines 8a-8c plus investment +# interest on line 9; 8a is 85.6% of it in the TY2022 US row). That is a +# component of the measure's concept, not another concept, so it is not +# listed here: like the line 7 capital-gains rows, it needs a share-or-drop +# decision of its own, which also binds the state_cd surface's itemized +# bridge. +# A congressional-district fact of a listed measure that carries no +# layout.source_column_id refuses the compile, so a feed schema change cannot +# silently lift the exclusion. +US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS: dict[tuple[str, str], str] = { + ("limited_state_local_taxes_returns", "N18425"): ( + "N18425 counts returns with state and local income taxes (Schedule A " + "line 5a), not returns with the limited state and local tax deduction " + "(line 5e, N18460). Chronicle's congressional_district_2022 package " + "reads it under this measure id: TY2022 US 10,842,580 returns against " + "14,777,040 for N18460 in the same file and 14,968,720 in Historic " + "Table 2." + ), + ("limited_state_local_taxes_amount", "A18425"): ( + "A18425 is state and local income taxes before the $10,000 limit " + "(Schedule A line 5a), not the limited deduction (line 5e, A18460) " + "salt_deduction measures. Chronicle's congressional_district_2022 " + "package reads it under this measure id: TY2022 US $250.4B against " + "$121.2B for A18460 in the same file, so on the full surface the " + "congressional-district rows summed to 1.98x the national Historic " + "Table 2 target." + ), + ("premium_tax_credit_returns", "N85530"): ( + "N85530 counts returns with additional Medicare tax (Form 8959 line 24), " + "not returns with the premium tax credit (Form 8962 line 24, N85770) " + "assigned_aca_ptc measures. Chronicle's congressional_district_2022 " + "package reads it under this measure id: TY2022 US 6,848,330 returns " + "against 7,713,000 for N85770 in the same file." + ), + ("premium_tax_credit_amount", "A85530"): ( + "A85530 is additional Medicare tax (Form 8959 line 24), not the premium " + "tax credit (Form 8962 line 24, A85770). Chronicle's " + "congressional_district_2022 package reads it under this measure id: " + "TY2022 US $14.2B against $53.1B for A85770 in the same file." + ), +} + @dataclass(frozen=True) class SimpleTaxExpenditureReform: @@ -1080,7 +1157,7 @@ def compile_us_fiscal_target_registry( so the release tool sets this with ``--scf-education-debt``; otherwise the facts are inert. """ - materialized_facts = tuple(facts) + materialized_facts = _without_source_column_concept_exclusions(tuple(facts)) if congressional_district_vintage_crosswalk is not None: materialized_facts = translate_congressional_district_facts_to_current_vintage( materialized_facts, @@ -1091,10 +1168,17 @@ def compile_us_fiscal_target_registry( if student_loan_targets else None ) + # Restamped Chronicle facts (a pinned artifact labelled with a later + # build year, PolicyEngine/chronicle#117). Refuses a restamp that is not + # in the reviewed register, or one an aging index would read at its stamp. + restamps = source_vintage_corrections(materialized_facts) + if age_targets: + check_restamps_stay_out_of_aging_indexes(materialized_facts, restamps) references = ( *_dynamic_us_fiscal_target_references( materialized_facts, target_period=target_period, + restamps=restamps, ), *_references_for_target_period( US_JCT_TAX_EXPENDITURE_TARGET_REFERENCES, @@ -1136,6 +1220,10 @@ def compile_us_fiscal_target_registry( "target_period": target_period, }, ) + # From here on restamped facts are read at their data year: aging starts + # from it and the period contract checks it. Selection and the rebase + # controls above still saw the stamp. + registry = apply_source_vintage_corrections(registry, restamps) if age_targets: # Final nominal transform: age dollar amounts from their source period # to the build period on the fully within-surface-aligned registry @@ -1174,6 +1262,10 @@ def us_fiscal_target_exclusion_receipt( vintage included (dropped). - ``m_chip_state_chip_enrollment``: CMS CHIP enrollment facts for an ``_M_CHIP_STATE_FIPS`` state, at every period (dropped). + - ``source_column_concept_exclusion``: SOI facts read from an IRS column + that ``US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`` lists for their + measure id, at every vintage, as the feed carries them, before the + congressional-district crosswalk (dropped). - ``allowlisted_vintage_bypass``: facts latest-vintage selection activates at ``target_period`` that are another vintage of an excluded cell and carry a reviewed ``US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES`` entry @@ -1184,7 +1276,13 @@ def us_fiscal_target_exclusion_receipt( it raises on a vintage bypass nobody reviewed. """ - materialized_facts = tuple(facts) + raw_facts = tuple(facts) + source_column = { + _source_record_id(fact) + for fact in raw_facts + if _is_source_column_concept_exclusion(fact) and _source_record_id(fact) + } + materialized_facts = _without_source_column_concept_exclusions(raw_facts) if congressional_district_vintage_crosswalk is not None: materialized_facts = translate_congressional_district_facts_to_current_vintage( materialized_facts, @@ -1228,6 +1326,22 @@ def us_fiscal_target_exclusion_receipt( "entries": sorted(US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS), "source_record_ids": sorted(all_vintage), }, + "source_column_concept_exclusion": { + "action": "dropped", + "scope": "SOI facts read from a listed column under a listed " + "measure id, every vintage", + "entries": [ + { + "measure_id": measure_id, + "source_column_id": source_column_id, + "reason": reason, + } + for (measure_id, source_column_id), reason in sorted( + US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS.items() + ) + ], + "source_record_ids": sorted(source_column), + }, "m_chip_state_chip_enrollment": { "action": "dropped", "scope": "CMS CHIP enrollment rows for these states, every period", @@ -1556,44 +1670,105 @@ class _SoiTotalControl: period_key: tuple[int, int, str] +#: What an SOI record-set family's ``net_capital_gains_*`` columns count, read +#: from the published IRS workbooks and documentation guides, TY2020-TY2023 +#: (microcosm#1035): +#: +#: - Table 1.4 cols 37/38, "Sales of capital assets reported on Form 1040, +#: Schedule D: Taxable net gain", cover Schedule D returns that net to a +#: gain. Returns reporting only capital gain distributions on Form 1040 +#: (col 35) and Schedule D loss returns (col 39) are outside them: Table 1.3 +#: row 18 "Sales of capital assets net gain" equals col 35 + col 37 exactly. +#: - Historic Table 2 and the congressional-district file carry N01000/A01000, +#: which both documentation guides define as "Number of returns with net +#: capital gain (less loss)" / "Net capital gain (less loss) amount" at Form +#: 1040 line 7: a Schedule D gain, a loss-limited Schedule D loss, or +#: distributions only. HT2 US N01000 equals Table 1.4 col 35 + col 37 + +#: col 39 within 0.25% in each of TY2020-TY2023, and is 2.36x col 37 in +#: TY2022. Its amount, net of losses, is 1.4% below col 38 in TY2022. +#: +#: A family absent from this register has no reviewed concept and is never a +#: capital-gains control. A registered family whose concept is not the +#: model's supplies shares only (``_soi_capital_gains_share_family``). +_SOI_SCHEDULE_D_TAXABLE_NET_GAIN = "schedule_d_taxable_net_gain" +_SOI_FORM_1040_LINE_7_NET_GAIN_OR_LOSS = "form_1040_line_7_net_gain_or_loss" +_SOI_CAPITAL_GAINS_FAMILY_CONCEPTS: dict[str, str] = { + "table_1_4": _SOI_SCHEDULE_D_TAXABLE_NET_GAIN, + "historic_table_2": _SOI_FORM_1040_LINE_7_NET_GAIN_OR_LOSS, + "congressional_district": _SOI_FORM_1040_LINE_7_NET_GAIN_OR_LOSS, +} +#: The concept ``capital_gains_gross`` measures. It is the positive part of +#: PE-US ``capital_gains`` (short-term plus long-term, i.e. Schedule D, before +#: the loss limit); distributions reported without Schedule D are the separate +#: ``non_sch_d_capital_gains``. Its indicator therefore counts Table 1.4 col 37 +#: returns and its sum is col 38; a line-7 count, which also counts losses and +#: distributions-only returns, is a different population. (PE-US allows +#: negative gains, but the Build P release data carries no tax unit with a +#: net loss, so it could not reach a line-7 count at any level.) +_SOI_CAPITAL_GAINS_MODEL_CONCEPT = _SOI_SCHEDULE_D_TAXABLE_NET_GAIN + + +class AmbiguousSoiCapitalGainsControlError(ValueError): + """Two different concept-matched records tie for one capital-gains control.""" + + def _rebase_stale_soi_capital_gains_distributions( registry: TargetRegistry, facts: tuple[object, ...], *, target_period: int | str, ) -> TargetRegistry: - """Use stale SOI capital-gains rows as shares, not hard old-year totals.""" + """Use line-7 capital-gains rows as shares of a Table 1.4 level. + + Historic Table 2 and congressional-district rows count Form 1040 line 7 + (gain or loss), a population ``capital_gains_gross`` cannot measure, so + they never ship as levels. Each one ships as its share of its own family's + national total at its own period (an HT2 row of the HT2 US row, a + congressional-district state or district row of that file's US row), + scaled to the concept-matched control of ``_soi_capital_gains_active_totals`` + at or after that period, and declares the bridge in ``soi_source_concept`` + / ``soi_control_concept``. Without such a control or a nonzero national + row of its own family the row is dropped, never shipped as a line-7 level. + Each family's national all-AGI row retires because the control's own row + owns the national concept. + + One factor per family, quantity and period scales a family's state and + district rows alike, so the district-to-state hierarchy reconciliation that + runs next sees the same proportions. The congressional-district file's + states sum exactly to its US row, so on the full surface its states and + its districts each sum to the control. Before this, they shipped as + line-7 levels, 2.41x the Table 1.4 return count (microcosm#1038). + """ controls = _soi_capital_gains_active_totals( facts, target_period=target_period, ) - stale_national_totals = _soi_capital_gains_stale_national_totals(facts) + share_totals = _soi_capital_gains_share_national_totals(facts) specs: list[TargetSpec] = [] for spec in registry.specs: kind = _soi_capital_gains_kind(spec) - if kind is None or not _is_stale_soi_historic_capital_gains_spec(spec): + family = _soi_capital_gains_share_family_from_spec(spec) if kind else None + if kind is None or family is None: specs.append(spec) continue key = _soi_capital_gains_control_key_from_spec(spec) control = controls.get(key) - source_total = stale_national_totals.get((*key, spec.metadata["source_period"])) - if control is None: - specs.append(spec) - continue - if source_total in (None, 0): - continue - if not _period_not_before( + source_total = share_totals.get((family, *key, spec.metadata["source_period"])) + if control is None or not _period_not_before( control.period_key, _period_key_from_value(spec.metadata["source_period"]) ): - specs.append(spec) + continue + if source_total is None or source_total.value == 0: + # Unanchored: a share needs its own family's national row. Never + # divided by another family's total, never shipped as a level. continue if _is_national_all_agi_spec(spec): continue - factor = control.value / source_total + factor = control.value / source_total.value specs.append( replace( spec, @@ -1610,6 +1785,11 @@ def _rebase_stale_soi_capital_gains_distributions( "uprating_index_source_record_id": control.source_record_id, "uprating_factor": _format_float(factor), "stale_distribution_rebased_to_active_total": "true", + "soi_source_concept": _SOI_CAPITAL_GAINS_FAMILY_CONCEPTS[family], + "soi_control_concept": _SOI_CAPITAL_GAINS_MODEL_CONCEPT, + # The share's denominator: this family's own national + # row, from the same release as the row itself. + "soi_share_total_source_record_id": source_total.source_record_id, }, ) ) @@ -1621,13 +1801,26 @@ def _soi_capital_gains_active_totals( *, target_period: int | str, ) -> dict[tuple[str, str, str], _SoiTotalControl]: + """The capital-gains control per (measure, filing status, universe). + + Only a national full-AGI fact whose family counts what + ``capital_gains_gross`` measures qualifies, so HT2 and + congressional-district rows never do, whatever their period stamp. The + latest qualifying period not after the build period wins, and the choice + depends on the fact set alone: two different candidates at the winning + period (different records, or one record with different values or period + labels) refuse the compile. Feed order used to break that tie, and the + September re-pin, which re-sorted the feed by content hash, handed the + returns control to the congressional-district US row (microcosm#1035). + """ controls: dict[tuple[str, str, str], _SoiTotalControl] = {} + tied: dict[tuple[str, str, str], set[tuple[str, float, str]]] = {} target_period_key = _period_key_from_value(target_period) for fact in facts: key = _soi_capital_gains_control_key_from_fact(fact) if key is None: continue - if _is_stale_soi_historic_capital_gains_fact(fact): + if _soi_capital_gains_concept(fact) != _SOI_CAPITAL_GAINS_MODEL_CONCEPT: continue period_key = _period_key(fact) if not _not_after_target_period(period_key, target_period_key): @@ -1641,25 +1834,108 @@ def _soi_capital_gains_active_totals( source_record_id=source_record_id, period_key=period_key, ) + identity = (source_record_id, candidate.value, candidate.source_period) current = controls.get(key) - if current is None or _prefer_candidate( - candidate.period_key, - current.period_key, - target_period_key=target_period_key, - ): + if current is not None and period_key[:2] == current.period_key[:2]: + tied[key].add(identity) + continue + if current is None or period_key[:2] > current.period_key[:2]: controls[key] = candidate + tied[key] = {identity} + ambiguous = { + key: sorted(candidates) + for key, candidates in tied.items() + if len(candidates) > 1 + } + if ambiguous: + raise AmbiguousSoiCapitalGainsControlError( + "SOI capital-gains control is ambiguous: different candidates tie at " + f"the latest period for {ambiguous}. Deduplicate them upstream; " + "feed order must not pick a rebase control (microcosm#1035)." + ) return controls -def _soi_capital_gains_stale_national_totals( +def _soi_capital_gains_concept(fact: object) -> str | None: + """The reviewed IRS concept of a capital-gains fact's family, if any.""" + return _SOI_CAPITAL_GAINS_FAMILY_CONCEPTS.get( + _soi_record_set_family(_str_at(fact, "layout", "record_set_id")) + ) + + +def _soi_capital_gains_share_family(record_set_id: str) -> str | None: + """The family of a capital-gains row that may ship only as a share. + + A registered family whose columns count something other than what + ``capital_gains_gross`` measures (Historic Table 2 and the + congressional-district file, both Form 1040 line 7) supplies shares, never + levels. The model's own family and unregistered families return ``None``. + """ + family = _soi_record_set_family(record_set_id) + concept = _SOI_CAPITAL_GAINS_FAMILY_CONCEPTS.get(family) + if concept is None or concept == _SOI_CAPITAL_GAINS_MODEL_CONCEPT: + return None + return family + + +def _soi_capital_gains_share_family_from_spec(spec: TargetSpec) -> str | None: + if spec.family != "irs_soi": + return None + return _soi_capital_gains_share_family( + spec.metadata.get("ledger_layout_record_set_id", "") + ) + + +class AmbiguousSoiCapitalGainsShareTotalError(ValueError): + """One share family carries two different national totals for one period.""" + + +@dataclass(frozen=True) +class _SoiShareTotal: + value: float + source_record_id: str + + +def _soi_capital_gains_share_national_totals( facts: tuple[object, ...], -) -> dict[tuple[str, str, str, str], float]: - totals: dict[tuple[str, str, str, str], float] = {} +) -> dict[tuple[str, str, str, str, str], _SoiShareTotal]: + """Each share family's national all-AGI total, the denominator of its shares. + + Keyed by (family, measure, filing status, universe, period), so an HT2 row + divides by the HT2 US row and a congressional-district row by that file's + US row, never by another family's. Two different values under one key + refuse the compile instead of letting feed order pick the denominator; + equal values under two record ids keep the smaller id, so the named + denominator does not depend on feed order either. Congressional-district + packages of different boundary vintages for one tax year share the + ``congressional_district`` family, so their US rows must agree or the + compile refuses. + """ + totals: dict[tuple[str, str, str, str, str], _SoiShareTotal] = {} for fact in facts: key = _soi_capital_gains_control_key_from_fact(fact) - if key is None or not _is_stale_soi_historic_capital_gains_fact(fact): + if key is None: + continue + family = _soi_capital_gains_share_family( + _str_at(fact, "layout", "record_set_id") + ) + if family is None: continue - totals[(*key, str(_period_value(fact)))] = _numeric_value(fact) + source_record_id = _source_record_id(fact) + if not source_record_id: + continue + total_key = (family, *key, str(_period_value(fact))) + candidate = _SoiShareTotal(_numeric_value(fact), source_record_id) + current = totals.get(total_key) + if current is not None and current.value != candidate.value: + raise AmbiguousSoiCapitalGainsShareTotalError( + "SOI capital-gains share family has two national totals for " + f"{total_key}: {current.value!r} ({current.source_record_id}) " + f"and {candidate.value!r} ({candidate.source_record_id}). " + "Deduplicate them upstream." + ) + if current is None or candidate.source_record_id < current.source_record_id: + totals[total_key] = candidate return totals @@ -1677,22 +1953,6 @@ def _soi_capital_gains_kind_from_measure(measure_id: str) -> str | None: return None -def _is_stale_soi_historic_capital_gains_spec(spec: TargetSpec) -> bool: - if spec.family != "irs_soi": - return False - if _soi_capital_gains_kind(spec) is None: - return False - return ".historic_table_2." in spec.metadata.get("ledger_layout_record_set_id", "") - - -def _is_stale_soi_historic_capital_gains_fact(fact: object) -> bool: - if _source_name(fact) != "irs_soi": - return False - if _soi_capital_gains_kind_from_measure(_measure_id(fact)) is None: - return False - return ".historic_table_2." in _str_at(fact, "layout", "record_set_id") - - def _soi_capital_gains_control_key_from_fact( fact: object, ) -> tuple[str, str, str] | None: @@ -2764,8 +3024,13 @@ def _dynamic_us_fiscal_target_references( facts: tuple[object, ...], *, target_period: int | str, + restamps: Mapping[str, SourceVintageCorrection] | None = None, ) -> tuple[LedgerTargetReference, ...]: - selected = _latest_dynamic_target_references(facts, target_period=target_period) + selected = _latest_dynamic_target_references( + facts, + target_period=target_period, + restamps=restamps, + ) _check_exclusion_vintage_scope(source_record_id for source_record_id, _ in selected) return tuple(reference for _, reference in selected) @@ -2774,6 +3039,7 @@ def _latest_dynamic_target_references( facts: Iterable[object], *, target_period: int | str, + restamps: Mapping[str, SourceVintageCorrection] | None = None, ) -> tuple[tuple[str, LedgerTargetReference], ...]: """Select one fact per model target shape: the latest eligible period. @@ -2782,6 +3048,11 @@ def _latest_dynamic_target_references( the one family selected by vintage rather than per key: every eligible vintage is a candidate, and :func:`_with_one_state_agi_band_vintage` keeps one per state and measure (microcosm#940). + + Selection compares stamped periods. With ``restamps`` (the compile's + :func:`source_vintage_corrections`), it refuses a key where a restamped + fact competes with a truthful fact dated after the restamp's data year: + the stamp would pick the older data (microcosm#1030 review). """ facts = tuple(facts) @@ -2820,6 +3091,12 @@ def _latest_dynamic_target_references( reference, ) ) + if restamps: + _refuse_restamps_that_shadow_newer_vintages( + candidates, + restamps, + target_period_key=_period_key_from_value(target_period), + ) keys_with_positive_observations = { key for key, _, value, _, _ in candidates if value > 0 } @@ -2857,6 +3134,68 @@ def _latest_dynamic_target_references( ) +def _refuse_restamps_that_shadow_newer_vintages( + candidates: Iterable[ + tuple[tuple[str, ...], tuple[int, int, str], float, str, object] + ], + restamps: Mapping[str, SourceVintageCorrection], + *, + target_period_key: tuple[int, int, str], +) -> None: + """Refuse a restamped candidate that would outrank newer truthful data. + + A TY2020 cell stamped 2023 beats a truthful TY2021 fact of the same + target shape on the stamp alone, and the newer data would drop silently. + A truthful fact dated from the year after the restamp's data year up to + its stamp is shadowed; only candidates eligible at the target period + count. None exists on the pinned feed: the ty2020 W-2 twins sit at the + data year, not after it. State AGI bands carry their period in the + selection key and compete as whole vintages per state and measure + (microcosm#940), so they are compared at that grain. + """ + + eligible = [ + (_restamp_shadow_key(key, reference), period_key, source_record_id) + for key, period_key, _, source_record_id, reference in candidates + if _not_after_target_period(period_key, target_period_key) + ] + restamped_keys: dict[tuple[str, ...], list[SourceVintageCorrection]] = {} + for key, _, source_record_id in eligible: + restamp = restamps.get(source_record_id) + if restamp is not None: + restamped_keys.setdefault(key, []).append(restamp) + if not restamped_keys: + return + conflicts: list[str] = [] + for key, period_key, source_record_id in eligible: + if source_record_id in restamps or not period_key[0]: + continue + year = period_key[1] // 100 + for restamp in restamped_keys.get(key, ()): + if restamp.data_year < year <= restamp.stamped_year: + conflicts.append( + f"{restamp.source_record_id} ({restamp.label}) would outrank " + f"{source_record_id} ({year})" + ) + if conflicts: + raise RestampShadowsNewerVintageError(tuple(sorted(conflicts))) + + +def _restamp_shadow_key(key: tuple[str, ...], reference: object) -> tuple[str, ...]: + """The key two candidates must share for one to shadow the other. + + Latest-vintage selection compares candidates per key. A state AGI band's + key ends in its period, and :func:`_with_one_state_agi_band_vintage` then + keeps one whole vintage per state and measure, so a restamped band can + displace a truthful band of another period and other bounds. + """ + + metadata = getattr(reference, "metadata", None) or {} + if metadata.get(_SOI_STATE_AGI_BAND_REBASE_FLAG) == "true": + return ("state_agi_band", *_state_agi_band_key(metadata)) + return key + + def _exclusion_vintage_bypasses( source_record_ids: Iterable[str], ) -> dict[str, tuple[str, ...]]: @@ -3013,6 +3352,56 @@ def _period_free_source_record_id(source_record_id: str) -> str: return _normalized_record_set_id(source_record_id) +class MissingSoiSourceColumnError(ValueError): + """A congressional-district fact of a listed measure names no IRS column.""" + + +def _is_source_column_concept_exclusion(fact: object) -> bool: + """Whether an SOI fact reads a column its measure id does not mean. + + A congressional-district fact of a measure the register lists must name + its column: without one the exclusion could not tell a mislabeled column + from a corrected one, so the compile refuses instead of guessing. + """ + if _source_name(fact) != "irs_soi": + return False + measure_id = _measure_id(fact) + if measure_id not in { + measure for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS + }: + return False + column = _str_at(fact, "layout", "source_column_id") + if not column: + # Any congressional-district package, whatever its data vintage: the + # same family match as every other district guard (microcosm#1244). + if _is_soi_congressional_district_record_set(fact): + raise MissingSoiSourceColumnError( + f"{_source_record_id(fact)} is a congressional-district " + f"{measure_id} fact with no layout.source_column_id, so " + "US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS cannot tell which " + "IRS column it reads (microcosm#1038)." + ) + return False + return (measure_id, column) in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS + + +def _without_source_column_concept_exclusions( + facts: tuple[object, ...], +) -> tuple[object, ...]: + """Drop facts read from a listed column, before the district crosswalk. + + The crosswalk sums several source districts into one current district and + keeps one contributor's layout, so the column check must see each source + fact: afterwards an excluded contribution could inherit a corrected + column, and a fact with no column could hide behind one that has it. + Raises ``MissingSoiSourceColumnError`` for a listed district fact with no + column. + """ + return tuple( + fact for fact in facts if not _is_source_column_concept_exclusion(fact) + ) + + def _is_all_vintage_support_exclusion(source_record_id: str) -> bool: return _period_free_source_record_id(source_record_id) in ( _period_free_source_record_ids(US_FISCAL_TARGET_ALL_VINTAGE_SUPPORT_EXCLUSIONS) @@ -3076,18 +3465,6 @@ def _is_soi_congressional_district_record_set(fact: object) -> bool: ) -def _is_soi_cd_premium_tax_credit_amount_conflict( - fact: object, *, measure_id: str -) -> bool: - # The SOI CD A85530 amount is not the same gross annual PTC control used by - # assigned_aca_ptc. Keep Historic Table 2 national/state PTC amount controls - # until Ledger has an explicit CD reconciliation for this concept. - return ( - measure_id == "premium_tax_credit_amount" - and _is_soi_congressional_district_record_set(fact) - ) - - def _is_period_token(value: str) -> bool: normalized = value.lower().replace("-", "_") if normalized.startswith("month"): @@ -3154,6 +3531,8 @@ def _reference_from_ledger_fact( return None if _is_all_vintage_support_exclusion(source_record_id): return None + if _is_source_column_concept_exclusion(fact): + return None source_name = _source_name(fact) if source_name == "irs_soi": return _soi_reference_from_fact( @@ -3216,8 +3595,6 @@ def _soi_reference_from_fact( and geography_level != "congressional_district" ): return None - if _is_soi_cd_premium_tax_credit_amount_conflict(fact, measure_id=measure_id): - return None variable = SOI_AMOUNT_MEASURE_VARIABLES.get(measure_id) is_count = False if variable is None: @@ -3988,9 +4365,11 @@ def _references_for_target_period( def _soi_target_role(fact: object, measure_id: str) -> str: # W-2 item facts (generic "amount" measure id, layout-routed via the # form_w2_item override) get a named role so target aging can pin them - # to the wages series: tips are a W-2 wage component, and the feed's - # TY2020 vintage needs the SOI wages actuals as its chain bridge into - # the CBO projection years (microcosm#451 item 3). + # to the wages series: tips are a W-2 wage component, and the data are + # TY2020 (the newest IRS W-2 table), so the SOI wages actuals are the + # chain bridge into the CBO projection years (microcosm#451 item 3). + # The feed's ty2023 rows restamp the same TY2020 cells; source_vintage + # reads them at 2020 before aging. if ( measure_id == "amount" and _str_at(fact, "layout", "groupby_dimension") diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py new file mode 100644 index 0000000000..3540f78f70 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py @@ -0,0 +1,607 @@ +"""Read restamped Chronicle facts at the year their data describes. + +A Chronicle source package can pin one publisher artifact with +``artifact.artifact_year`` while still rendering ``{year}`` into its period, +record ids and vintage labels from the build year. Built with a later +``--year``, it re-labels the pinned file's values as that year: the same +cells, the same bytes, a later period. The US feed pinned at Chronicle +``c5e5bf8`` carries five such packages, all built at 2023 by +``us/chronicle_feed_scope.json`` (the congressional-district case is +PolicyEngine/chronicle#117; microcosm#1030 found the other four). For example, +the ty2023 W-2 Box 7 tips amount is cell D13 of the TY2020 workbook +``20in04w2all.xlsx``, byte for byte the same as its ty2020 twin. + +Chronicle owns the fix: it records each fact's publisher reference period +(Chronicle ``AGENTS.md``), and PolicyEngine/chronicle#292 stops the restamp. +Until the feed is re-pinned on that fix, microcosm reads these facts at their +data year where aging and the period contract read a period: the +``source_period`` aging starts from +(:mod:`~microcosm.build.us_runtime.target_aging`), the +``uprating_to_period`` a spec inherits from a restamped rebase control, and +the ``uprating_from_period`` of a restamped row rebased as a share of its own +package's total. Values and target names do not change. Two readings still +see the stamp, by design, because moving them would change which fact wins: + +- Latest-vintage selection. It refuses the compile if a restamp would outrank + a truthful fact dated after the restamp's data year + (:class:`RestampShadowsNewerVintageError`). +- The choice of a rebase control. A restamped control keeps a selection its + stamp won; only the period its specs inherit moves. + +The aging bridge indexes must not contain a restamped fact at all +(:func:`check_restamps_stay_out_of_aging_indexes`). + +Detection has two rules, and each detected restamp must match a reviewed +:data:`US_RESTAMPED_SOURCE_PACKAGES` entry (same package, stamped period and +data year) or the compile refuses (:class:`UnreviewedRestampError`): + +- **Content.** A fact whose ``source.source_sha256`` is a registered file and + whose period is after that file's data year. This holds whatever shape the + storage key takes. +- **Structure.** An observation whose ``source.raw_r2_key`` + (``raw/////``) names an earlier year + than its period. Chronicle copies that key from the manifest entry it read, + and the entry is keyed by the pinned artifact year, but the key string is + authored and not validated at ``c5e5bf8`` (chronicle#227). For a + single-year IRS file this year is the data year, so the rule is exact + there. A multi-year release keyed by its publication year can hold later + columns: BEA's 2024-keyed ``SAINC.zip`` has a 2025 column. Once Chronicle + builds such a column truthfully, the rule flags it. Register it in + :data:`US_LATER_PERIOD_OBSERVATION_EXEMPTIONS` after reading the file. + +Out of reach of both rules: a package that reads a *later* column than its +stamp. ``bea-regional-state-personal-income-components-2024`` stamps CY2024 +BEA state income as cy2023, 416 facts. No target compiles from it today, but +``bea_regional.state_wages_salaries`` is a deferred parity family ("a real +us-data target"). Activating it before chronicle#292 would calibrate 2024 +wages as cy2023. + +The register is reviewed against the pinned feed +(``test_pinned_feed_restamp_register_matches_the_feed``, which runs where the +feed is present and skips in CI). After a re-pin on a Chronicle commit that +stamps truthfully, an entry matches nothing and that test fails until the +entry is deleted. An entry the content rule still matches is still needed. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, replace +from types import MappingProxyType + +from microcosm.build.us_runtime.target_aging import ( + _cbo_projection_series, + _period_year, + _soi_national_chain_series, +) +from microcosm.calibrate import TargetRegistry, TargetSpec + +__all__ = [ + "US_LATER_PERIOD_OBSERVATION_EXEMPTIONS", + "US_RESTAMPED_SOURCE_PACKAGES", + "LaterPeriodObservationExemption", + "RestampShadowsNewerVintageError", + "RestampedAgingIndexError", + "RestampedSourcePackage", + "SourceVintageCorrection", + "UnreviewedRestampError", + "apply_source_vintage_corrections", + "check_restamps_stay_out_of_aging_indexes", + "detect_restamped_facts", + "fact_artifact_year", + "source_vintage_corrections", +] + + +@dataclass(frozen=True) +class RestampedSourcePackage: + """A reviewed Chronicle package whose feed stamp postdates its data. + + Attributes: + package_id: The package segment of ``source.raw_r2_key``. + data_year: The year the pinned publisher file describes. It must equal + the artifact year in ``raw_r2_key`` where the key parses. + stamped_periods: The periods the pinned feed stamps on it. + source_file: The pinned publisher file, for the reader. + source_sha256: The pinned file's digest (``source.source_sha256``), + which the content rule matches. + reason: Why the stamp is wrong, with the evidence. + """ + + package_id: str + data_year: int + stamped_periods: frozenset[int] + source_file: str + source_sha256: str + reason: str + + +@dataclass(frozen=True) +class LaterPeriodObservationExemption: + """A reviewed package whose truthful observations postdate its key year. + + For example, a multi-year release keyed by its publication year that also + carries a later data column. Facts from the package at ``periods`` are not + restamps. + """ + + package_id: str + periods: frozenset[int] + reason: str + + +def _restamped( + package_id: str, + data_year: int, + source_file: str, + source_sha256: str, + reason: str, + *, + stamped_periods: Iterable[int] = (2023,), +) -> tuple[str, RestampedSourcePackage]: + return package_id, RestampedSourcePackage( + package_id=package_id, + data_year=data_year, + stamped_periods=frozenset(stamped_periods), + source_file=source_file, + source_sha256=source_sha256, + reason=reason, + ) + + +# Reviewed against consumer_facts_us_c5e5bf8.jsonl (Chronicle c5e5bf8, sha256 +# b8543739...): these are the 26,893 facts both rules detect. Each data year +# was confirmed from the file itself (title cell or content match), not from +# Chronicle labels. "Newest" claims were checked on irs.gov on 2026-09-25. +US_RESTAMPED_SOURCE_PACKAGES: Mapping[str, RestampedSourcePackage] = MappingProxyType( + dict( + ( + _restamped( + "soi-w2-statistics-2020", + 2020, + "20in04w2all.xlsx", + "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f", + "IRS SOI Form W-2 statistics Table 4.B, titled 'Tax Year 2020'. " + "The ty2023 tips return_count, taxpayer_count and amount share " + "their source cells, bytes and values with the ty2020 twins; " + "the ty2023 401(k) and designated Roth 401(k) amounts are cells " + "D22 and D41 of the same table. As of 2026-09-25 TY2020 is the " + "newest W-2 table on irs.gov.", + ), + _restamped( + "soi-congressional-district-2022", + 2022, + "22incd.csv", + "137522878af78d624cfddc0e17cd36ae76a21b7bed166c7bb96ad3243a18a668", + "IRS SOI congressional district data for tax year 2022 (the " + "newest CD release as of 2026-09-25). The single-district " + "states match the TY2022 county file (for example WY N1 " + "280,740), and the US taxable interest is 92.7% of TY2022 " + "Table 1.4 against 39.4% of TY2023 (PolicyEngine/chronicle#117).", + ), + _restamped( + "soi-state-2022", + 2022, + "22in54us.xlsx", + "5e58050449c07c2e941f280c60d597784047f02ee1fa93dc1aed64fc1ea493f6", + "IRS SOI Historic Table 2 US totals, titled 'Tax Year 2022'.", + ), + _restamped( + "soi-ira-roth-contributions-2022", + 2022, + "22in06ira.xlsx", + "c1fb0894cb09d2486be4510b7e6ce0b8597787725b928ab8813f577d9fb13183", + "IRS SOI IRA Table 6 (Roth contributions), titled 'Tax Year 2022'.", + ), + _restamped( + "soi-ira-traditional-contributions-2022", + 2022, + "22in05ira.xlsx", + "31ce9dd2fe631b336170af339bd7e9de86901cd20dbfd4cb8fb1c9a1d55cd90f", + "IRS SOI IRA Table 5 (traditional contributions), titled " + "'Tax Year 2022'.", + ), + ) + ) +) + +# None on the pinned feed: no package there observes a year after its key. +US_LATER_PERIOD_OBSERVATION_EXEMPTIONS: Mapping[ + str, LaterPeriodObservationExemption +] = MappingProxyType({}) + + +@dataclass(frozen=True) +class SourceVintageCorrection: + """One restamped fact read at its data year.""" + + source_record_id: str + package_id: str + stamped_year: int + data_year: int + fact_key: str = "" + + @property + def label(self) -> str: + return ( + f"{self.package_id}: stamped {self.stamped_year}, " + f"data year {self.data_year}" + ) + + +class UnreviewedRestampError(ValueError): + """A fact is stamped later than its source file's year without review. + + Either the Chronicle feed restamped a package nobody reviewed, or a + reviewed package now carries a different stamp or data year. Read the + publisher file. Then add or amend the :data:`US_RESTAMPED_SOURCE_PACKAGES` + entry (a restamp), add a :data:`US_LATER_PERIOD_OBSERVATION_EXEMPTIONS` + entry (a truthful later observation), or fix the stamp in Chronicle and + re-pin. + """ + + def __init__(self, problems: tuple[str, ...]) -> None: + self.problems = problems + super().__init__( + f"{len(problems)} fact(s) carry a period later than their source " + "file's year without a matching reviewed " + f"US_RESTAMPED_SOURCE_PACKAGES entry: {_preview(problems)}" + ) + + +class RestampShadowsNewerVintageError(ValueError): + """A restamped fact would outrank a newer truthful fact in selection.""" + + def __init__(self, conflicts: tuple[str, ...]) -> None: + self.conflicts = conflicts + super().__init__( + f"{len(conflicts)} restamped fact(s) would win latest-vintage " + "selection over a truthful fact dated after the restamp's data " + "year, and drop the newer data. Re-pin on a Chronicle commit that " + f"stamps truthfully, or exclude the restamp: {_preview(conflicts)}" + ) + + +class RestampedAgingIndexError(ValueError): + """A restamped fact would feed an aging growth index at its stamp.""" + + def __init__(self, record_ids: tuple[str, ...]) -> None: + self.record_ids = record_ids + super().__init__( + f"{len(record_ids)} restamped fact(s) sit in a target-aging growth " + "index (the CBO projection series or the national SOI chain), " + "which reads fact periods as stamped. Every chained factor through " + f"that year would use the wrong level: {_preview(record_ids)}" + ) + + +def fact_artifact_year(fact: object) -> tuple[str, int] | None: + """``(package_id, year)`` from a fact's ``source.raw_r2_key``. + + Chronicle copies the key from the manifest entry it read, and a pinned + package's entry is keyed by its ``artifact_year``. The key is an authored + string, so this reads a label, not a validated fact. Returns ``None`` when + the key is absent or not ``raw////...``. + """ + + key = _str_at(fact, "source", "raw_r2_key") + parts = key.split("/") + if len(parts) < 5 or parts[0] != "raw" or not parts[2]: + return None + year = parts[3] + if not (year.isdigit() and len(year) == 4): + return None + return parts[2], int(year) + + +def detect_restamped_facts( + facts: Iterable[object], + *, + register: Mapping[str, RestampedSourcePackage] = US_RESTAMPED_SOURCE_PACKAGES, + exemptions: Mapping[ + str, LaterPeriodObservationExemption + ] = US_LATER_PERIOD_OBSERVATION_EXEMPTIONS, +) -> tuple[tuple[object, str, int, int], ...]: + """Every observation fact stamped later than its source file's year. + + Returns ``(fact, package_id, file_year, stamped_year)`` tuples. The file + year is the ``raw_r2_key`` year where the key parses, else the registered + data year. Two rules flag a fact (see the module docstring): its + ``source_sha256`` is a registered file and its period is after that + file's data year, or its key names an earlier year than its period. + + A publisher projection (``assertion == "source_projection"``) is exempt: + a 2025 JCT score of FY2027 legitimately describes a later year. A + projection that Chronicle types as an observation is flagged like a + restamp, so the compile refuses until Chronicle types it + ``source_projection``. + """ + + by_sha = {entry.source_sha256: entry for entry in register.values()} + detected: list[tuple[object, str, int, int]] = [] + for fact in facts: + if _str_at(fact, "assertion") not in ("", "observation"): + continue + stamped_year = _period_year(_at(fact, "period", "value")) + if stamped_year is None: + continue + artifact = fact_artifact_year(fact) + entry = by_sha.get(_str_at(fact, "source", "source_sha256")) + if entry is not None and stamped_year > entry.data_year: + file_year = artifact[1] if artifact is not None else entry.data_year + detected.append((fact, entry.package_id, file_year, stamped_year)) + continue + if artifact is None: + continue + package_id, artifact_year = artifact + if artifact_year >= stamped_year: + continue + exemption = exemptions.get(package_id) + if exemption is not None and stamped_year in exemption.periods: + continue + detected.append((fact, package_id, artifact_year, stamped_year)) + return tuple(detected) + + +def source_vintage_corrections( + facts: Iterable[object], + *, + register: Mapping[str, RestampedSourcePackage] = US_RESTAMPED_SOURCE_PACKAGES, + exemptions: Mapping[ + str, LaterPeriodObservationExemption + ] = US_LATER_PERIOD_OBSERVATION_EXEMPTIONS, +) -> Mapping[str, SourceVintageCorrection]: + """Map each restamped fact's ``source_record_id`` to its correction. + + Raises: + UnreviewedRestampError: A detected restamp has no register entry, or + its stamp or file year disagrees with the entry. + ValueError: One source record id is detected twice with different + stamps or data years. + """ + + corrections: dict[str, SourceVintageCorrection] = {} + problems: list[str] = [] + for fact, package_id, file_year, stamped_year in detect_restamped_facts( + facts, register=register, exemptions=exemptions + ): + source_record_id = _source_record_id(fact) + entry = register.get(package_id) + if entry is None: + problems.append( + f"{source_record_id} ({package_id}: artifact {file_year}, " + f"stamped {stamped_year}; no register entry)" + ) + continue + if stamped_year not in entry.stamped_periods: + problems.append( + f"{source_record_id} ({package_id}: stamped {stamped_year}, " + f"register reviews {sorted(entry.stamped_periods)})" + ) + continue + if file_year != entry.data_year: + problems.append( + f"{source_record_id} ({package_id}: artifact {file_year}, " + f"register data year {entry.data_year})" + ) + continue + correction = SourceVintageCorrection( + source_record_id=source_record_id, + package_id=package_id, + stamped_year=stamped_year, + data_year=entry.data_year, + fact_key=_fact_key(fact), + ) + existing = corrections.get(source_record_id) + if existing is not None and existing != correction: + raise ValueError( + f"Restamped source record {source_record_id!r} appears with " + f"two corrections: {existing.label} vs {correction.label}." + ) + corrections[source_record_id] = correction + if problems: + raise UnreviewedRestampError(tuple(sorted(problems))) + return MappingProxyType(corrections) + + +def check_restamps_stay_out_of_aging_indexes( + facts: Iterable[object], + corrections: Mapping[str, SourceVintageCorrection], +) -> None: + """Refuse a restamped fact in an aging growth index. + + ``_cbo_projection_series`` and ``_soi_national_chain_series`` index facts + by their stamped period, and every chained aging factor through that year + reads them. None is restamped on the pinned feed: the chain draws on + Table 1.1 and Table 1.4, and the projections are CBO's. + """ + + if not corrections: + return + facts = tuple(facts) + indexed = { + record_id + for index in (_cbo_projection_series(facts), _soi_national_chain_series(facts)) + for by_year in index.values() + for _, record_id in by_year.values() + } + restamped = tuple(sorted(indexed & set(corrections))) + if restamped: + raise RestampedAgingIndexError(restamped) + + +def apply_source_vintage_corrections( + registry: TargetRegistry, + corrections: Mapping[str, SourceVintageCorrection], +) -> TargetRegistry: + """Point the aging and period-contract readings at the data year. + + Two readings move: + + - A spec backed by a restamped fact: ``source_period`` becomes the data + year. That is where target aging starts and what the period contract + checks. ``source_vintage_stamped_period`` keeps the feed's stamp, and + ``ledger_fact_period`` is left as stamped. + - A spec rebased onto a restamped control: ``uprating_to_period`` and + ``uprating_index_source_period`` become the control's data year. Aging + starts a rebased spec from ``uprating_to_period``, so a dollar spec + rebased onto a TY2022 total must not be aged as if it were TY2023. + - A restamped spec rebased as a share of a restamped total of the same + package, stamp and data year (its ``soi_share_total_source_record_id``): + ``uprating_from_period`` also becomes the data year. The stamp cancels + in the share and the level is the control's, so ``uprating_to_period``, + where aging starts, stays the control's period. Starting it at the data + year instead would apply the control's growth from the data year to its + own period twice. + + Values are never touched here. The one number that moves afterwards is the + aging factor, computed from the corrected period. + + Raises: + ValueError: A restamped fact reaches a spec in a way the correction + cannot vouch for: at a period other than its stamp (a fiscal-year + comparable period), as a rebased spec that is not a share of a + restamped total of its own package, stamp and data year, as one + member of a multi-fact spec, or inside a pooled uprating index. + """ + + if not corrections: + return registry + corrected_fact_keys = { + correction.fact_key + for correction in corrections.values() + if correction.fact_key + } + specs: list[TargetSpec] = [] + for spec in registry.specs: + metadata = dict(spec.metadata) + changed = False + members = _member_fact_keys(metadata) + if len(members) > 1 and not corrected_fact_keys.isdisjoint(members): + raise ValueError( + f"Target {spec.name!r} aggregates several facts, and some are " + "restamped; its source period is its representative's, so the " + "correction cannot vouch for it. Review it." + ) + backing = corrections.get(metadata.get("ledger_source_record_id", "")) + if backing is not None: + if _period_year(metadata.get("ledger_fact_period")) != backing.stamped_year: + raise ValueError( + f"Target {spec.name!r} is backed by restamped fact " + f"{backing.source_record_id!r} ({backing.label}) at period " + f"{metadata.get('ledger_fact_period')!r}, not its stamp; " + "review how the period was compared." + ) + if "uprating_factor" in metadata: + # A rebased restamp is admitted only as a within-package share: + # value = row / total x control, where the rebase names its + # total (soi_share_total_source_record_id) and the total is a + # restamp of the same package at the same stamp. The stamp then + # cancels in the share, the level and its period are the + # control's, and aging keeps starting at uprating_to_period. + # Only the share's own data year (uprating_from_period) moves. + share_total_id = metadata.get("soi_share_total_source_record_id", "") + share_total = corrections.get(share_total_id) + if ( + share_total is None + or ( + share_total.package_id, + share_total.stamped_year, + share_total.data_year, + ) + != (backing.package_id, backing.stamped_year, backing.data_year) + or _period_year(metadata.get("uprating_from_period")) + not in (backing.stamped_year, backing.data_year) + ): + raise ValueError( + f"Target {spec.name!r} is backed by restamped fact " + f"{backing.source_record_id!r} ({backing.label}) and was " + "rebased, but not as a share of a restamped total of the " + f"same package, stamp and data year (share total " + f"{share_total_id!r}, uprating_from_period " + f"{metadata.get('uprating_from_period')!r}); review the " + "rebase before correcting its period." + ) + metadata["uprating_from_period"] = str(backing.data_year) + metadata["uprating_from_period_vintage_stamped_period"] = str( + backing.stamped_year + ) + metadata["source_period"] = str(backing.data_year) + metadata["source_vintage_stamped_period"] = str(backing.stamped_year) + metadata["source_vintage_correction"] = backing.label + changed = True + for control_id in _split_ids( + metadata.get("uprating_index_source_record_ids", "") + ): + if control_id in corrections: + # A pooled index (the EITC AGI-group uprating) mixes several + # controls under one period; none is restamped today. + raise ValueError( + f"Target {spec.name!r} is uprated by a multi-source " + f"index that includes restamped fact {control_id!r} " + f"({corrections[control_id].label}); review it." + ) + control = corrections.get(metadata.get("uprating_index_source_record_id", "")) + if control is not None and ( + _period_year(metadata.get("uprating_index_source_period")) + == control.stamped_year + ): + metadata["uprating_to_period"] = str(control.data_year) + metadata["uprating_index_source_period"] = str(control.data_year) + metadata["uprating_index_source_vintage_stamped_period"] = str( + control.stamped_year + ) + metadata["uprating_index_source_vintage_correction"] = control.label + changed = True + specs.append(replace(spec, metadata=metadata) if changed else spec) + return TargetRegistry(specs, country=registry.country) + + +def _member_fact_keys(metadata: Mapping[str, str]) -> tuple[str, ...]: + payload = metadata.get("ledger_member_fact_keys", "") + if not payload: + return () + return tuple(str(key) for key in json.loads(payload)) + + +def _split_ids(value: object) -> tuple[str, ...]: + return tuple(part for part in str(value or "").split(",") if part) + + +def _preview(items: tuple[str, ...]) -> str: + suffix = "" if len(items) <= 5 else f"; +{len(items) - 5} more" + return "; ".join(items[:5]) + suffix + + +def _fact_key(fact: object) -> str: + # Mirrors ledger_targets._fact_key, the key multi-fact specs record. + return ( + _str_at(fact, "aggregate_fact_key") + or _str_at(fact, "fact_key") + or _str_at(fact, "legacy_fact_key") + or _source_record_id(fact) + ) + + +def _source_record_id(fact: object) -> str: + return _str_at(fact, "source_record_id") or _str_at( + fact, "lineage", "source_record_id" + ) + + +def _at(obj: object, *path: str) -> object: + current: object = obj + for key in path: + if current is None: + return None + if isinstance(current, dict): + current = current.get(key) + else: + current = getattr(current, key, None) + return current + + +def _str_at(obj: object, *path: str) -> str: + value = _at(obj, *path) + return "" if value is None else str(value) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_aging.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_aging.py index 4625f82a38..43ea26d1c0 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_aging.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_aging.py @@ -148,7 +148,9 @@ "nipa_proprietors_income": "net_business_income", # W-2 Box 7 social security tips (microcosm#451 item 3): tips are a wage # component, and the fact's TY2020 vintage predates the CBO projection - # span, so the wages series' SOI actuals provide the chained bridge. + # span, so the wages series' SOI actuals provide the chained bridge. The + # feed's ty2023 tips row is the same TY2020 cell restamped; source_vintage + # sets its source_period back to 2020 so it takes this chain too. "w2_social_security_tips_total": "wages_and_salaries", } diff --git a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py index 7133755f4b..8451f6c4a2 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_transport_evidence_kernels.py @@ -152,6 +152,9 @@ # microcosm#1074: us_runtime.fiscal_targets imports the FSA student # loan targets. "microcosm.build.us_runtime.fsa_student_loan_targets", + # microcosm#1030: us_runtime.fiscal_targets imports the source-vintage + # corrections for restamped Chronicle facts. + "microcosm.build.us_runtime.source_vintage", # microcosm#1585: the US keyed draws call # stochastic_assignment.stable_identity_uniforms. "microcosm.build.stochastic_assignment", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index fd5998bdcf..fc25b2ef43 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -3734,6 +3734,27 @@ def test_pinned_feed_soi_surfaces_match_their_contracts() -> None: } assert {spec.metadata["ledger_geography_level"] for spec in soi} == {"state"} assert {spec.name for spec in state_specs} <= set(full_by_name) + # The compiler drops the district file's SALT and premium-tax-credit facts + # read from the wrong IRS column (microcosm#1038), so `totals` keeps only + # the 51 states' Historic Table 2 premium-tax-credit rows, returns and + # amounts, and `full` 29,824 SOI specs. With no such district rows left, + # the crosswalk no longer copies those Historic Table 2 rows to the nine + # at-large districts (each copy repeated its state row). + totals_soi = [spec for spec in totals_registry.specs if spec.family == "irs_soi"] + assert len(totals_soi) == 102 + assert {spec.metadata["ledger_geography_level"] for spec in totals_soi} == { + "state" + } + assert {spec.metadata["source_measure_id"] for spec in totals_soi} == { + "premium_tax_credit_returns", + "premium_tax_credit_amount", + } + assert not [ + spec.name + for spec in totals_soi + if ".congressional_district_" in spec.metadata["ledger_layout_record_set_id"] + ] + assert sum(spec.family == "irs_soi" for spec in full_registry.specs) == 29_824 assert not [ spec diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_targets.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_targets.py index 41993679b9..532da89e22 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_targets.py @@ -109,10 +109,14 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: groupby_value_id="hi_01", geography_id="5001700US1501", ), - _soi_congressional_district_fact( + # The pinned feed reads the CD PTC measures from A85530, additional + # Medicare tax, so they never compile (source-column exclusion). + _cd_column_fact( "premium_tax_credit_amount", - 90_000_000, + "A85530", + value=90_000_000, groupby_value_id="hi_01", + geography_level="congressional_district", geography_id="5001700US1501", ), _soi_congressional_district_fact( @@ -127,10 +131,14 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: groupby_value_id="hi_01", geography_id="5001700US1501", ), - _soi_congressional_district_fact( + # The pinned feed reads it from N19300 (line 8a mortgage interest, a + # component of the line 10 deduction), which is not excluded. + _cd_column_fact( "interest_paid_deduction_returns", - 23_456, + "N19300", + value=23_456, groupby_value_id="hi_01", + geography_level="congressional_district", geography_id="5001700US1501", ), _soi_congressional_district_fact( @@ -166,9 +174,10 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: geography_level="state", geography_id="0400000US15", ), - _soi_congressional_district_fact( + _cd_column_fact( "premium_tax_credit_amount", - 180_000_000, + "A85530", + value=180_000_000, groupby_value_id="hi_total", geography_level="state", geography_id="0400000US15", @@ -232,6 +241,12 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: assert qbi.metadata["base_variable"] == "qualified_business_income_deduction" assert qbi.value == 2_000_000_000 + interest_returns = by_measure["interest_paid_deduction_returns"] + assert interest_returns.metadata["measure_mode"] == "indicator_sum" + assert interest_returns.metadata["base_variable"] == "interest_deduction" + assert interest_returns.metadata["itemized_only"] == "true" + assert interest_returns.value == 23_456 + qbi_returns = by_measure["qualified_business_income_deduction_returns"] assert qbi_returns.metadata["measure_mode"] == "indicator_sum" assert ( @@ -239,12 +254,6 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: ) assert qbi_returns.value == 12_345 - interest_returns = by_measure["interest_paid_deduction_returns"] - assert interest_returns.metadata["measure_mode"] == "indicator_sum" - assert interest_returns.metadata["base_variable"] == "interest_deduction" - assert interest_returns.metadata["itemized_only"] == "true" - assert interest_returns.value == 23_456 - charitable_returns = by_measure["charitable_returns"] assert charitable_returns.metadata["measure_mode"] == "indicator_sum" assert charitable_returns.metadata["base_variable"] == "charitable_deduction" @@ -736,12 +745,14 @@ def test_exclusion_vintage_scope_registers_are_consistent() -> None: def test_exclusion_receipt_lists_the_ids_each_rule_acts_on(monkeypatch) -> None: - """One synthetic feed exercises all four rules. The M-CHIP and all-vintage + """One synthetic feed exercises all five rules. The M-CHIP and all-vintage rules list every vintage the feed carries (both CMS months even though a 2024 build selects only 2024-12), exact-key hits land under - reviewed_exclusion, and the allowlisted bypass is the fact selection - activates. The receipt is plain JSON.""" - synthetic, expected = _four_rule_synthetic_feed(monkeypatch) + reviewed_exclusion, the source-column rule lists the facts read from a + listed column and not the one read from the right column, and the + allowlisted bypass is the fact selection activates. The receipt is plain + JSON.""" + synthetic, expected = _exclusion_rule_synthetic_feed(monkeypatch) facts = [*packaged_reference_facts(), *synthetic] receipt = us_fiscal_target_exclusion_receipt(facts, target_period=2024) @@ -752,6 +763,7 @@ def test_exclusion_receipt_lists_the_ids_each_rule_acts_on(monkeypatch) -> None: assert {name: rule["action"] for name, rule in rules.items()} == { "reviewed_exclusion": "dropped", "all_vintage_reviewed_exclusion": "dropped", + "source_column_concept_exclusion": "dropped", "m_chip_state_chip_enrollment": "dropped", "allowlisted_vintage_bypass": "allowed", } @@ -763,11 +775,236 @@ def test_exclusion_receipt_lists_the_ids_each_rule_acts_on(monkeypatch) -> None: assert rules["m_chip_state_chip_enrollment"]["state_fips"] == sorted( _M_CHIP_STATE_FIPS ) + assert [ + (entry["measure_id"], entry["source_column_id"]) + for entry in rules["source_column_concept_exclusion"]["entries"] + ] == sorted(US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS) + + +def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: + """A congressional-district fact labelled limited_state_local_taxes but read + from N18425/A18425 (state and local income taxes, Schedule A line 5a), or + labelled premium_tax_credit but read from N85530 (additional Medicare + tax), never compiles, at any geography; the same measures read from + A18460 and N85770, the columns a corrected package would read, compile + (microcosm#1038).""" + mislabeled = [ + _cd_column_fact("limited_state_local_taxes_returns", "N18425"), + _cd_column_fact("limited_state_local_taxes_amount", "A18425"), + _cd_column_fact( + "limited_state_local_taxes_returns", + "N18425", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ), + ] + corrected = _cd_column_fact( + "limited_state_local_taxes_amount", + "A18460", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + medicare = _cd_column_fact("premium_tax_credit_returns", "N85530") + ptc = _cd_column_fact( + "premium_tax_credit_returns", + "N85770", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + # The amount twin too: the removed record-set check dropped every + # district PTC amount; the register keeps A85770, the premium tax credit. + ptc_amount = _cd_column_fact( + "premium_tax_credit_amount", + "A85770", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + mislabeled = [*mislabeled, medicare] + facts = [*packaged_reference_facts(), *mislabeled, corrected, ptc, ptc_amount] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + + compiled = {spec.metadata["ledger_source_record_id"] for spec in registry.specs} + assert not compiled & {fact["lineage"]["source_record_id"] for fact in mislabeled} + assert corrected["lineage"]["source_record_id"] in compiled + assert ptc["lineage"]["source_record_id"] in compiled + assert ptc_amount["lineage"]["source_record_id"] in compiled + rule = us_fiscal_target_exclusion_receipt(facts)["rules"][ + "source_column_concept_exclusion" + ] + assert rule["source_record_ids"] == sorted( + fact["lineage"]["source_record_id"] for fact in mislabeled + ) + + +def test_source_column_exclusions_name_the_columns_their_guides_define() -> None: + """Each entry's reason names its own column and what its measure id means, + as 22incddocguide.docx defines them: N18425/A18425 (state and local income + taxes, Schedule A line 5a) stand in for the limited deduction N18460/A18460 + (line 5e) and N85530/A85530 (additional Medicare tax) for the premium tax + credit N85770/A85770.""" + right_columns = { + ("limited_state_local_taxes_returns", "N18425"): "N18460", + ("limited_state_local_taxes_amount", "A18425"): "A18460", + ("premium_tax_credit_returns", "N85530"): "N85770", + ("premium_tax_credit_amount", "A85530"): "A85770", + } + assert set(US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS) == set(right_columns) + for key, reason in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS.items(): + measure_id, column = key + assert column in reason + # Counts read N columns and amounts read A columns. + assert column[0] == ("N" if measure_id.endswith("_returns") else "A") + assert right_columns[key] in reason + assert right_columns[key][0] == column[0] + + +def test_source_column_exclusion_refuses_a_district_fact_without_a_column() -> None: + """A congressional-district fact of a listed measure that names no IRS + column refuses the compile and the receipt, because the register could not + tell a mislabeled column from a corrected one. A Historic Table 2 fact of + the same measure without a column (the US package publishes none) still + compiles.""" + unnamed = _soi_congressional_district_fact( + "limited_state_local_taxes_amount", + 250_000_000.0, + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + ht2 = _soi_capital_gains_fact( + 2022, + source_record_id=( + "irs_soi.ty2022.historic_table_2.us.all.limited_state_local_taxes_amount" + ), + measure_id="limited_state_local_taxes_amount", + value=122_000_000_000.0, + ) + reference = packaged_reference_facts() + + for facts in ([*reference, unnamed], [*reference, ht2, unnamed]): + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + compile_us_fiscal_target_registry(facts, allow_unaged_dollar_targets=True) + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + us_fiscal_target_exclusion_receipt(facts) + registry = compile_us_fiscal_target_registry( + [*reference, ht2], allow_unaged_dollar_targets=True + ) + assert ht2["lineage"]["source_record_id"] in { + spec.metadata["ledger_source_record_id"] for spec in registry.specs + } + + +#: Two Hawaii source districts merged into one current district, so the +#: crosswalk sums them under one contributor's layout. +_HI_MERGE_CROSSWALK = [ + { + "source_geography_id": "5001700US1501", + "target_geography_id": "5001900US1501", + "weight": 1.0, + }, + { + "source_geography_id": "5001700US1502", + "target_geography_id": "5001900US1501", + "weight": 1.0, + }, +] + + +def _hi_salt_district_fact(number: int, column: str | None, value: float): + if column is None: + return _soi_congressional_district_fact( + "limited_state_local_taxes_amount", + value, + groupby_value_id=f"hi_0{number}", + geography_id=f"5001700US150{number}", + ) + return _cd_column_fact( + "limited_state_local_taxes_amount", + column, + value=value, + groupby_value_id=f"hi_0{number}", + geography_level="congressional_district", + geography_id=f"5001700US150{number}", + ) + + +@pytest.mark.parametrize( + "columns", + [("A18460", "A18425"), ("A18425", "A18460")], + ids=["kept-first", "excluded-first"], +) +def test_source_column_exclusion_runs_before_the_crosswalk_merges(columns) -> None: + """The crosswalk sums source districts into one current district under one + contributor's layout, so the column check runs on each source fact first. + In either order the A18425 contribution never reaches the merged target, + which carries only the A18460 district's value, and the receipt names the + excluded source fact (#1224 review).""" + facts = [ + _hi_salt_district_fact(number, column, value) + for number, column, value in zip((1, 2), columns, (100.0, 200.0), strict=True) + ] + feed = [*packaged_reference_facts(), *facts] + + registry = compile_us_fiscal_target_registry( + feed, + congressional_district_vintage_crosswalk=_HI_MERGE_CROSSWALK, + allow_unaged_dollar_targets=True, + ) + receipt = us_fiscal_target_exclusion_receipt( + feed, congressional_district_vintage_crosswalk=_HI_MERGE_CROSSWALK + ) + + merged = [ + spec.value + for spec in registry.specs + if spec.metadata.get("source_measure_id") == "limited_state_local_taxes_amount" + and spec.metadata.get("ledger_geography_level") == "congressional_district" + ] + assert merged == [100.0 if columns[0] == "A18460" else 200.0] + excluded = next(f for f in facts if f["layout"]["source_column_id"] == "A18425") + assert receipt["rules"]["source_column_concept_exclusion"]["source_record_ids"] == [ + excluded["lineage"]["source_record_id"] + ] + + +@pytest.mark.parametrize( + "columns", + [("A18460", None), (None, "A18460"), ("A18425", None), (None, "A18425")], +) +def test_missing_column_refuses_before_the_crosswalk_merges(columns) -> None: + """A district fact of a listed measure with no column refuses in any merge + order: the crosswalk cannot hide it behind a contributor that has one, nor + behind an excluded one (#1224 review).""" + feed = [ + *packaged_reference_facts(), + *( + _hi_salt_district_fact(number, column, 100.0) + for number, column in zip((1, 2), columns, strict=True) + ), + ] + + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + compile_us_fiscal_target_registry( + feed, + congressional_district_vintage_crosswalk=_HI_MERGE_CROSSWALK, + allow_unaged_dollar_targets=True, + ) + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + us_fiscal_target_exclusion_receipt( + feed, congressional_district_vintage_crosswalk=_HI_MERGE_CROSSWALK + ) def test_exclusion_receipt_is_complete_for_any_subfeed(monkeypatch) -> None: """Invariant (receipt completeness): each rule lists exactly the facts it - drops or allows. For any subset of the four-rule synthetic feed, each rule + drops or allows. For any subset of the five-rule synthetic feed, each rule lists exactly the full feed's ids for that rule that the subset carries. Hypothesis is a workspace dependency; the wheels job installs no test extras, so it skips there.""" @@ -775,7 +1012,7 @@ def test_exclusion_receipt_is_complete_for_any_subfeed(monkeypatch) -> None: from hypothesis import given, settings from hypothesis import strategies as st - synthetic, expected = _four_rule_synthetic_feed(monkeypatch) + synthetic, expected = _exclusion_rule_synthetic_feed(monkeypatch) ids = [fiscal_targets._source_record_id(fact) for fact in synthetic] reference = packaged_reference_facts() @@ -861,9 +1098,12 @@ def check(years: list[int], reviewed: bool) -> None: def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> None: """On the pinned feed the receipt names the 40 M-CHIP CHIP ids (20 states - x 2 CMS months), the 16 other-income ids (ty2020-ty2023) and the ty2020 - and ty2023 tips return counts, and allows no vintage bypass (decision - d179).""" + x 2 CMS months), the 16 other-income ids (ty2020-ty2023), the ty2020 and + ty2023 tips return counts, and the 1,920 congressional-district SALT and + premium-tax-credit facts read from the wrong IRS column, as the feed + carries them before the district crosswalk (480 per measure: the US row, + 51 states, 428 source districts), and allows no vintage bypass (decision + d179, microcosm#1038).""" _, _, receipt = pinned_feed_national_state_surface rules = receipt["rules"] m_chip_ids = rules["m_chip_state_chip_enrollment"]["source_record_ids"] @@ -888,15 +1128,37 @@ def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> No ] ) assert rules["allowlisted_vintage_bypass"]["source_record_ids"] == [] + column_ids = rules["source_column_concept_exclusion"]["source_record_ids"] + assert all(".congressional_district_2022." in i for i in column_ids) + assert { + measure: sum( + f".{measure}" in source_record_id for source_record_id in column_ids + ) + for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS + } == {measure: 480 for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} + assert len(column_ids) == 4 * 480 def test_pinned_feed_national_state_surface_restores_the_fences( pinned_feed_national_state_surface, ) -> None: - """The release surface on the pinned feed: 33,250 compiled targets after - Medicaid substitution, 6,102 national_state targets at registry - c698e70d33ce, 32 CHIP rows none of them for an M-CHIP state, no - other-income row and no tips return count. The hierarchy value ranks + """The release surface on the pinned feed: 31,748 compiled + targets after Medicaid substitution (the full surface, at 4cc4cfb7a147), + 6,102 national_state targets at registry 4dfe25b1238a, 32 CHIP rows none + of them for an M-CHIP state, no other-income row and no tips return count. + Three changes took it from 33,250 compiled (full bf021cdc9749) and + national_state c698e70d33ce, at the same national_state count: + microcosm#1035 chooses the capital-gains control by concept and period, + which returns the 51 Historic Table 2 state return counts to Table 1.4 + shares; microcosm#1038 drops the congressional-district capital-gains US + rows and the congressional-district SALT and premium-tax-credit rows read + from the wrong IRS column, all on the full surface, and names the + denominator (soi_share_total_source_record_id) on the 102 Historic Table 2 + capital-gains rows of national_state; microcosm#1030 reads the restamped + W-2 tips amount at TY2020. The district file no longer carries SALT or + premium-tax-credit district rows, so the crosswalk no longer copies the + 36 Historic Table 2 rows of those measures to the nine at-large + districts; they repeated their state rows. The hierarchy value ranks (each group-by value's row in its source table, which the version hashes) moved it from 3aa2a0830e7d; microcosm#1343 moved the version from 3fad14f85468 by re-pinning to a feed that gives three @@ -911,11 +1173,16 @@ def test_pinned_feed_national_state_surface_restores_the_fences( 5,694 at d315c75804ef on the c5e5bf8 feed; before microcosm#956 it was 32,867 / 5,719 at d5f9d854fe11, and before decision d179 dropped the ty2020 tips return count it was 32,843 / 5,695 at 386fac439e77 - (docs/us-chronicle-feed-repin.md).""" + (docs/us-chronicle-feed-repin.md, docs/us-soi-capital-gains-concepts.md).""" + from microcosm.calibrate import TargetRegistry + registry, surface, _ = pinned_feed_national_state_surface - assert len(registry.specs) == 33_250 + assert len(registry.specs) == 31_748 + builder = _load_repo_tool("build_us_fiscal_refresh_release") + full, _ = builder._select_target_surface(registry.specs, "full") + assert TargetRegistry(full, country="us").version == "4cc4cfb7a147" assert len(surface.specs) == 6_102 - assert surface.version == "c698e70d33ce" + assert surface.version == "4dfe25b1238a" chip = [ spec for spec in surface.specs @@ -1033,6 +1300,431 @@ def test_pinned_feed_eitc_child_total_rows_count_each_split_once( assert sum(spec.value for spec in bins) == pytest.approx(active, rel=1e-12) +def test_pinned_feed_no_district_target_reads_an_excluded_column( + pinned_feed_national_state_surface, +) -> None: + """No congressional-district SALT or premium-tax-credit target compiles on + the pinned feed: every district-file fact of those measures reads a + listed column. Before microcosm#1038 the 488 SALT amount specs summed to + 1.98x the national Historic Table 2 target on the full surface (A18425, + state and local income taxes) and 488 premium-tax-credit return specs + counted additional-Medicare-tax payers (N85530).""" + registry, _, _ = pinned_feed_national_state_surface + excluded = {measure for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} + assert not [ + spec.name + for spec in registry.specs + if spec.metadata.get("source_measure_id") in excluded + and ".congressional_district_" + in spec.metadata.get("ledger_layout_record_set_id", "") + ] + # The Historic Table 2 rows of the same measures still compile. + assert { + spec.metadata["source_measure_id"] + for spec in registry.specs + if spec.metadata.get("source_measure_id") in excluded + and ".historic_table_2." in spec.metadata.get("ledger_layout_record_set_id", "") + } == excluded + + +def test_pinned_feed_capital_gains_rows_take_the_table_1_4_level( + pinned_feed_national_state_surface, +) -> None: + """The 51 Historic Table 2 state capital-gains rows take their level from + Table 1.4 ty2023, the concept capital_gains_gross measures, and not from + the congressional-district US row that shares its period stamp and sorts + first in the feed (microcosm#1035). The return counts sum to 12,289,836, + 99.2% of the national 12,392,020 target, as in the Build P release; with + the CD row as control they summed to 29,599,604.""" + _, surface, _ = pinned_feed_national_state_surface + expected = { + "net_capital_gains_returns": ( + "irs_soi.ty2023.table_1_4.all.net_capital_gains_returns", + "0.406751165649407", + 12_289_835.97216556, + ), + "net_capital_gains_amount": ( + "irs_soi.ty2023.table_1_4.all.net_capital_gains_amount", + "0.771900044145164", + None, + ), + } + for measure, (control_id, factor, total) in expected.items(): + rows = [ + spec + for spec in surface.specs + if ".historic_table_2.state_broad." in spec.name + and spec.metadata.get("source_measure_id") == measure + ] + assert len(rows) == 51 + national = next(spec for spec in surface.specs if spec.name == control_id) + for spec in rows: + assert spec.metadata["uprating_index_source_record_id"] == control_id + assert spec.metadata["soi_share_total_source_record_id"] == ( + f"irs_soi.ty2022.historic_table_2.us.all.{measure}" + ) + assert spec.metadata["uprating_factor"] == factor + assert spec.metadata["soi_source_concept"] == ( + "form_1040_line_7_net_gain_or_loss" + ) + assert spec.metadata["soi_control_concept"] == ( + "schedule_d_taxable_net_gain" + ) + state_total = sum(spec.value for spec in rows) + assert state_total < national.value + if total is not None: + assert math.isclose(state_total, total, rel_tol=1e-12) + + +def test_pinned_feed_no_soi_state_family_sums_past_its_national_target( + pinned_feed_national_state_surface, +) -> None: + """Invariant: the states partition the nation (HT2 state rows omit only + other areas and Puerto Rico), so on national_state no SOI state family may + sum past every national target of the same model quantity and filters. + Before microcosm#1035 the capital_gains_gross return counts, one of the 63 + compared families, summed to 2.39x theirs. Some quantities still carry + both a stale HT2 US row and a newer Table 1.x row, a few percent apart, so + the bound is the larger of them.""" + _, surface, _ = pinned_feed_national_state_surface + quantity = _soi_quantity + + national: dict[tuple[object, ...], list[float]] = {} + states: dict[tuple[object, ...], float] = {} + for spec in surface.specs: + if spec.family != "irs_soi": + continue + if spec.metadata.get("state_fips"): + states[quantity(spec)] = states.get(quantity(spec), 0.0) + spec.value + else: + national.setdefault(quantity(spec), []).append(spec.value) + compared = {key: total for key, total in states.items() if key in national} + assert len(compared) == 63 + assert { + key[:2]: total / max(national[key]) + for key, total in compared.items() + if total > max(national[key]) + } == {} + + +def _soi_quantity(spec) -> tuple[object, ...]: + """The model quantity and filters an SOI target constrains.""" + metadata = spec.metadata + return ( + metadata.get("variable"), + metadata.get("measure_mode"), + metadata.get("agi_lower_bound"), + metadata.get("agi_upper_bound"), + metadata.get("filing_status"), + metadata.get("soi_return_universe", "all_returns"), + metadata.get("itemized_only"), + tuple( + sorted( + (key, value) + for key, value in metadata.items() + if key.startswith("ledger_filter_") + ) + ), + ) + + +def _is_congressional_district_file_spec(spec) -> bool: + return ( + fiscal_targets._soi_record_set_family( + spec.metadata.get("ledger_layout_record_set_id", "") + ) + == "congressional_district" + ) + + +def test_pinned_feed_congressional_district_capital_gains_take_the_table_1_4_level( + pinned_feed_national_state_surface, +) -> None: + """On the full surface the congressional-district file's 51 state and 436 + district capital-gains rows per measure are shares of that file's US row + times the Table 1.4 ty2023 level, and the US row retires + (microcosm#1038). The states, and the districts, each sum to the national + target: 12,392,020 returns, where the line-7 levels summed to 29,845,710 + (2.41x), and the aged Table 1.4 amount, where they summed to $1,522.2B + (1.198x).""" + registry, _, _ = pinned_feed_national_state_surface + specs = {spec.name: spec for spec in registry.specs} + for measure, control_id, cd_us_id, total in ( + ( + "net_capital_gains_returns", + "irs_soi.ty2023.table_1_4.all.net_capital_gains_returns", + f"{_CG_CD_RECORD_SET}.us.net_capital_gains_returns", + 12_392_020.0, + ), + ( + "net_capital_gains_amount", + "irs_soi.ty2023.table_1_4.all.net_capital_gains_amount", + f"{_CG_CD_RECORD_SET}.us.net_capital_gains_amount", + None, + ), + ): + rows = [ + spec + for spec in registry.specs + if spec.metadata.get("source_measure_id") == measure + and _is_congressional_district_file_spec(spec) + ] + levels: dict[str, list] = {} + for spec in rows: + levels.setdefault(spec.metadata["ledger_geography_level"], []).append(spec) + assert {level: len(group) for level, group in levels.items()} == { + "state": 51, + "congressional_district": 436, + } + assert cd_us_id not in specs + national = specs[control_id] + factors = {spec.metadata["uprating_factor"] for spec in rows} + assert len(factors) == 1 + for spec in rows: + assert spec.metadata["uprating_index_source_record_id"] == control_id + assert spec.metadata["soi_share_total_source_record_id"] == cd_us_id + assert spec.metadata["soi_source_concept"] == ( + "form_1040_line_7_net_gain_or_loss" + ) + assert spec.metadata["soi_control_concept"] == ( + "schedule_d_taxable_net_gain" + ) + for level in ("state", "congressional_district"): + level_total = sum(spec.value for spec in levels[level]) + assert math.isclose(level_total, national.value, rel_tol=1e-12) + if total is not None: + assert math.isclose(level_total, total, rel_tol=1e-12) + + +def test_pinned_feed_no_congressional_district_family_sums_past_its_national_target( + pinned_feed_national_state_surface, +) -> None: + """Invariant: the congressional-district file covers a subset of returns + (no Puerto Rico or other areas, ZIP-unmatched returns dropped), so on the + full surface none of its families (its US row, its states, or its + districts) may sum past every national non-district target of the same + model quantity and filters. Before microcosm#1038 three of 38 compared + families did: capital-gains returns at 2.41x, the SALT amount at 1.98x + (read from the uncapped income-tax column A18425) and the capital-gains + amount at 1.198x. + + The band is two-sided. Coverage (0.92-0.99 of Historic Table 2) and one + year less of aging keep every compared family above 0.85 of its national + target on this feed (lowest: the taxable Social Security amount, 0.855), + so a family below that has lost rows or reads another concept; each + compared family must also keep its state and district rows. 35 of the 52 + families have a national comparator on this surface; the rest (EITC by + children, charitable, interest paid, QBI deduction, taxable interest, + filer individuals) are compared under other keys or not at all.""" + registry, _, _ = pinned_feed_national_state_surface + builder = _load_repo_tool("build_us_fiscal_refresh_release") + full, _ = builder._select_target_surface(registry.specs, "full") + + national: dict[tuple[object, ...], list[float]] = {} + district_file: dict[tuple[object, ...], dict[str, float]] = {} + for spec in full: + if spec.family != "irs_soi": + continue + level = spec.metadata.get("ledger_geography_level") + if _is_congressional_district_file_spec(spec): + sums = district_file.setdefault(_soi_quantity(spec), {}) + sums[level] = sums.get(level, 0.0) + spec.value + elif level == "country": + national.setdefault(_soi_quantity(spec), []).append(spec.value) + compared = {key: sums for key, sums in district_file.items() if key in national} + assert (len(district_file), len(compared)) == (52, 35) + assert not [ + key[:2] + for key, sums in compared.items() + if not {"state", "congressional_district"} <= set(sums) + ] + assert { + (key[:2], level): round(total / max(national[key]), 4) + for key, sums in compared.items() + for level, total in sums.items() + if not 0.85 * max(national[key]) <= total <= max(national[key]) * (1 + 1e-9) + } == {} + + +_W2_TIPS_AMOUNT = ( + "irs_soi.ty{year}.form_w2_social_security_tips.box_7_social_security_tips.amount" +) + + +def test_pinned_feed_restamp_register_matches_the_feed(pinned_feed_facts) -> None: + """Every observation fact the pinned feed stamps later than its artifact's + year belongs to a reviewed register entry, with that entry's stamp and + data year, and every entry still matches the feed. A re-pin on a + Chronicle commit that fixes the stamp (chronicle#117) fails here until + the stale entries are deleted.""" + from collections import Counter + + from microcosm.build.us_runtime.source_vintage import ( + US_RESTAMPED_SOURCE_PACKAGES, + detect_restamped_facts, + source_vintage_corrections, + ) + + detected = detect_restamped_facts(pinned_feed_facts) + assert Counter(package_id for _, package_id, _, _ in detected) == { + "soi-congressional-district-2022": 26_880, + "soi-w2-statistics-2020": 5, + "soi-state-2022": 4, + "soi-ira-roth-contributions-2022": 2, + "soi-ira-traditional-contributions-2022": 2, + } + assert set(US_RESTAMPED_SOURCE_PACKAGES) == { + package_id for _, package_id, _, _ in detected + } + for fact, package_id, artifact_year, stamped_year in detected: + entry = US_RESTAMPED_SOURCE_PACKAGES[package_id] + assert artifact_year == entry.data_year + assert stamped_year in entry.stamped_periods + # Both detection rules agree on every row: the key names the file's + # year and the digest is the registered file. + assert fact["source"]["raw_r2_key"].split("/")[2:4] == [ + package_id, + str(entry.data_year), + ] + assert fact["source"]["source_sha256"] == entry.source_sha256 + assert len(source_vintage_corrections(pinned_feed_facts)) == 26_893 + + +def test_pinned_feed_w2_tips_amount_ages_from_tax_year_2020( + pinned_feed_facts, pinned_feed_national_state_surface +) -> None: + """The route-A tips target is the ty2023 row, which is the TY2020 cell + restamped. It ages from 2020 on the chained SOI wages bridge, so it + equals what its honest ty2020 twin would compile to. Aged from the stamp + (the direct 2023 CBO ratio) it was $28.28B, 17.5% lower.""" + from microcosm.build.us_runtime.target_aging import ( + _cbo_projection_series, + _soi_national_chain_series, + ) + + _, surface, _ = pinned_feed_national_state_surface + spec = _aged_spec_by_source_record_id(surface, _W2_TIPS_AMOUNT.format(year=2023)) + wages = _cbo_projection_series(pinned_feed_facts)["wages_and_salaries"] + soi_wages = _soi_national_chain_series(pinned_feed_facts)["wages_and_salaries"] + factor = (soi_wages[2023][0] / soi_wages[2020][0]) * ( + wages[2024][0] / wages[2023][0] + ) + assert spec.metadata["ledger_fact_period"] == "2023" + assert spec.metadata["source_period"] == "2020" + assert spec.metadata["source_vintage_stamped_period"] == "2023" + assert spec.metadata["aging_factor_source"].startswith( + "chained:irs_soi.ty2023.table_1_4.all.wages_salaries_amount+" + ) + assert float(spec.metadata["aging_factor"]) == pytest.approx(factor, rel=1e-12) + assert spec.value == pytest.approx(26_786_522_000 * factor, rel=1e-12) + assert spec.value == pytest.approx(34_287_530_779, abs=1) + + +def test_pinned_feed_corrects_the_translated_congressional_district_specs( + pinned_feed_national_state_surface, +) -> None: + """Most corrections land on congressional-district facts that the vintage + crosswalk re-keys (``current_cd.*``). Detection runs on the translated + facts, so every translated spec carries the correction, and the dollar + ones age on the chained bridge from TY2022.""" + from collections import Counter + + registry, _, _ = pinned_feed_national_state_surface + corrected = Counter( + ( + spec.metadata["source_vintage_correction"].split(":")[0], + ".current_cd." in spec.metadata["ledger_source_record_id"], + spec.metadata["aging_factor_source"].startswith("chained:"), + ) + for spec in registry.specs + if "source_vintage_correction" in spec.metadata + ) + # microcosm#1038 drops the district file's SALT and premium-tax-credit rows + # and its capital-gains US rows, so fewer corrected specs remain. + assert corrected == { + ("soi-congressional-district-2022", True, True): 10_900, + ("soi-congressional-district-2022", True, False): 11_772, + ("soi-congressional-district-2022", False, True): 1_300, + ("soi-congressional-district-2022", False, False): 1_350, + ("soi-state-2022", False, False): 2, + ("soi-w2-statistics-2020", False, True): 1, + } + # Every corrected congressional-district spec reads TY2022, except an + # aged share (microcosm#1040), whose source_period records where its + # aging starts: the control's period. + assert all( + spec.metadata["source_period"] == "2022" + or ( + "uprating_factor" in spec.metadata + and spec.metadata["source_period"] == spec.metadata["uprating_to_period"] + ) + for spec in registry.specs + if spec.metadata.get("source_vintage_correction", "").startswith( + "soi-congressional-district-2022" + ) + ) + # No spec is rebased onto a restamped control: since microcosm#1035 the + # Historic Table 2 capital-gains return counts take the Table 1.4 control, + # not the congressional-district US row. The 974 district capital-gains + # shares of microcosm#1038 are admitted restamped shares. + assert not [ + spec.name + for spec in registry.specs + if "uprating_index_source_vintage_correction" in spec.metadata + ] + assert ( + sum( + "uprating_from_period_vintage_stamped_period" in spec.metadata + for spec in registry.specs + ) + == 974 + ) + + +def test_pinned_feed_rebased_specs_read_restamped_inputs_at_their_data_year( + pinned_feed_facts, pinned_feed_national_state_surface +) -> None: + """Every spec rebased onto a restamped control inherits the control's data + year, and every restamped spec that was rebased is a share of a restamped + total of its own package, stamp and data year: its share is read at the + data year while aging still starts at the control's period. On this feed + the 60 Historic Table 2 capital-gains return counts rebase onto the + congressional-district US row (TY2022 stamped ty2023) and land at 2022; + counts never age, so no value moves. The test names no control, so it + holds whichever control the capital-gains rebase picks, including a + concept rule that never picks the district row (microcosm#1036), and with + district rows rebased as shares of that row (microcosm#1040).""" + from microcosm.build.us_runtime.source_vintage import source_vintage_corrections + + registry, _, _ = pinned_feed_national_state_surface + corrections = source_vintage_corrections(pinned_feed_facts) + rebased = [spec for spec in registry.specs if "uprating_factor" in spec.metadata] + assert rebased + for spec in rebased: + metadata = spec.metadata + control = corrections.get(metadata.get("uprating_index_source_record_id", "")) + if control is None: + assert "uprating_index_source_vintage_correction" not in metadata + else: + assert metadata["uprating_to_period"] == str(control.data_year) + assert metadata["uprating_index_source_period"] == str(control.data_year) + assert metadata["uprating_index_source_vintage_stamped_period"] == str( + control.stamped_year + ) + if "source_vintage_correction" not in metadata: + assert "uprating_from_period_vintage_stamped_period" not in metadata + continue + total = corrections[metadata["soi_share_total_source_record_id"]] + assert metadata["source_vintage_correction"] == total.label + assert metadata["uprating_from_period"] == str(total.data_year) + assert metadata["uprating_from_period_vintage_stamped_period"] == str( + total.stamped_year + ) + assert ( + metadata["uprating_to_period"] == metadata["uprating_index_source_period"] + ) + + def test_reviewed_zero_support_facts_are_not_active_targets() -> None: excluded_source_record_id = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." @@ -4140,66 +4832,999 @@ def test_stale_soi_capital_gains_without_source_total_is_dropped() -> None: assert state_record_id not in source_record_ids -def test_cross_period_soi_taxable_interest_agi_slice_without_total_is_dropped() -> None: - source_record_id = ( - "irs_soi.ty2022.historic_table_2.us.200k_to_500k.taxable_interest_amount" - ) - registry = compile_us_fiscal_target_registry( - [ - *packaged_reference_facts(), - _soi_taxable_interest_fact( - 2022, - source_record_id=source_record_id, - value=21_000_000_000, - income_range="200k_to_500k", - lower=200_000, - upper=500_000, - ), - ], - target_period=2024, - allow_unaged_dollar_targets=True, - ) - - assert source_record_id not in {spec.name for spec in registry.specs} +_CG_T14_RETURNS = "irs_soi.ty2023.table_1_4.all.net_capital_gains_returns" +_CG_T14_AMOUNT = "irs_soi.ty2023.table_1_4.all.net_capital_gains_amount" +_CG_CD_RECORD_SET = "irs_soi.ty2023.congressional_district_2022.all_returns" +_CG_HT2_CA_RETURNS = ( + "irs_soi.ty2022.historic_table_2.state_broad.ca.all.net_capital_gains_returns" +) +_CG_HT2_CA_AMOUNT = ( + "irs_soi.ty2022.historic_table_2.state_broad.ca.all.net_capital_gains_amount" +) -def test_cross_period_soi_eitc_decomposition_uses_latest_source_backed_total() -> None: - source_record_id = ( - "irs_soi.ty2023.table_2_5.eitc_by_agi_children.one_qualifying_child." - "25k_to_30k.eitc_total" - ) - registry = compile_us_fiscal_target_registry( - [ - *packaged_reference_facts(), - _soi_eitc_total_fact( - 2023, - measure_id="total_earned_income_credit_amount", - value=66_270_000_000, - ), - *_soi_eitc_child_total_facts( - 2023, - measure_id="eitc_total", - values={"all_qualifying_children": 66_270_000_000}, - ), - _soi_eitc_filing_season_total_fact( - measure_id="total_earned_income_credit_amount", - value=69_041_649_000, +def _capital_gains_ht2_facts() -> list[dict[str, object]]: + """TY2022 Historic Table 2 line-7 rows: US 100 / 1,000 and CA 25 / 250.""" + return [ + _soi_capital_gains_fact( + 2022, + source_record_id=( + "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_returns" ), - _soi_eitc_child_fact( - 2023, - source_record_id=source_record_id, - measure_id="eitc_total", - value=66_270_000, + measure_id="net_capital_gains_returns", + value=100.0, + ), + _soi_capital_gains_fact( + 2022, + source_record_id=( + "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_amount" ), - ], - target_period=2024, - allow_unaged_dollar_targets=True, - ) - - spec = {spec.name: spec for spec in registry.specs}[source_record_id] - assert spec.value == 69_041_649 - assert spec.metadata["uprating_index"] == "total_eitc_amount" - assert spec.metadata["uprating_index_source_period"] == "2024" + value=1_000.0, + ), + _soi_capital_gains_fact( + 2022, + source_record_id=_CG_HT2_CA_RETURNS, + measure_id="net_capital_gains_returns", + geography_level="state", + geography_id="0400000US06", + value=25.0, + ), + _soi_capital_gains_fact( + 2022, + source_record_id=_CG_HT2_CA_AMOUNT, + geography_level="state", + geography_id="0400000US06", + value=250.0, + ), + ] + + +def _capital_gains_cd_us_facts() -> list[dict[str, object]]: + """The congressional-district file's US row: TY2022 line-7 data stamped + ty2023, as on the pinned feed (PolicyEngine/chronicle#117).""" + return [ + _soi_capital_gains_fact( + 2023, + source_record_id=f"{_CG_CD_RECORD_SET}.us.net_capital_gains_returns", + measure_id="net_capital_gains_returns", + layout_record_set_id=_CG_CD_RECORD_SET, + value=98.0, + ), + _soi_capital_gains_fact( + 2023, + source_record_id=f"{_CG_CD_RECORD_SET}.us.net_capital_gains_amount", + layout_record_set_id=_CG_CD_RECORD_SET, + value=925.0, + ), + ] + + +def _capital_gains_t14_facts() -> list[dict[str, object]]: + """Table 1.4 ty2023 Schedule D taxable net gain: 40 returns / 800.""" + return [ + _soi_capital_gains_fact( + 2023, + source_record_id=_CG_T14_RETURNS, + measure_id="net_capital_gains_returns", + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=40.0, + ), + _soi_capital_gains_fact( + 2023, + source_record_id=_CG_T14_AMOUNT, + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=800.0, + ), + ] + + +@pytest.mark.parametrize("cd_first", [True, False], ids=["cd-first", "t14-first"]) +def test_capital_gains_controls_are_table_1_4_in_either_feed_order( + cd_first: bool, +) -> None: + """A congressional-district US row that shares Table 1.4's period never + becomes the control, whichever comes first in the feed (microcosm#1035). + On the pinned feed it sorted first and set the HT2 state returns rows at + 2.39x the national Table 1.4 target of the same model quantity.""" + cd, t14 = _capital_gains_cd_us_facts(), _capital_gains_t14_facts() + facts = [ + *packaged_reference_facts(), + *_capital_gains_ht2_facts(), + *(cd + t14 if cd_first else t14 + cd), + ] + + controls = fiscal_targets._soi_capital_gains_active_totals( + tuple(facts), target_period=2024 + ) + assert {key[0]: control.source_record_id for key, control in controls.items()} == { + "net_capital_gains_returns": _CG_T14_RETURNS, + "net_capital_gains_amount": _CG_T14_AMOUNT, + } + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + specs = {spec.metadata["ledger_source_record_id"]: spec for spec in registry.specs} + ca_returns = specs[_CG_HT2_CA_RETURNS] + ca_amount = specs[_CG_HT2_CA_AMOUNT] + assert ca_returns.value == 10.0 + assert ca_returns.metadata["uprating_factor"] == "0.4" + assert ca_returns.metadata["uprating_index_source_record_id"] == _CG_T14_RETURNS + assert ca_amount.value == 200.0 + assert ca_amount.metadata["uprating_index_source_record_id"] == _CG_T14_AMOUNT + for spec in (ca_returns, ca_amount): + # The bridge is declared: the row supplies a line-7 share, the level + # comes from the Schedule D concept capital_gains_gross measures. + assert spec.metadata["soi_source_concept"] == ( + "form_1040_line_7_net_gain_or_loss" + ) + assert spec.metadata["soi_control_concept"] == "schedule_d_taxable_net_gain" + + +def test_capital_gains_rows_without_a_concept_matched_control_are_dropped() -> None: + """With only a congressional-district row stamped later, no control + exists, and a line-7 HT2 row cannot stand as a capital_gains_gross level.""" + facts = [ + *packaged_reference_facts(), + *_capital_gains_ht2_facts(), + *_capital_gains_cd_us_facts(), + ] + + assert ( + fiscal_targets._soi_capital_gains_active_totals( + tuple(facts), target_period=2024 + ) + == {} + ) + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + source_record_ids = { + spec.metadata["ledger_source_record_id"] for spec in registry.specs + } + assert _CG_HT2_CA_RETURNS not in source_record_ids + assert _CG_HT2_CA_AMOUNT not in source_record_ids + + +def test_capital_gains_rows_whose_control_predates_them_are_dropped() -> None: + """A control older than the HT2 row would reverse its period, so the row + drops rather than ship its line-7 level.""" + facts = [ + *packaged_reference_facts(), + *_capital_gains_ht2_facts(), + _soi_capital_gains_fact( + 2021, + source_record_id="irs_soi.ty2021.table_1_4.all.net_capital_gains_returns", + measure_id="net_capital_gains_returns", + layout_record_set_id="irs_soi.ty2021.table_1_4", + value=41.0, + ), + ] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + source_record_ids = { + spec.metadata["ledger_source_record_id"] for spec in registry.specs + } + assert _CG_HT2_CA_RETURNS not in source_record_ids + + +def test_capital_gains_control_refuses_two_matched_records_at_one_period() -> None: + duplicate = _soi_capital_gains_fact( + 2023, + source_record_id="irs_soi.ty2023.table_1_4.all_returns.net_capital_gains_returns", + measure_id="net_capital_gains_returns", + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=41.0, + ) + facts = (*_capital_gains_t14_facts(), duplicate) + + for ordered in (facts, tuple(reversed(facts))): + with pytest.raises( + fiscal_targets.AmbiguousSoiCapitalGainsControlError, + match="all_returns.net_capital_gains_returns", + ): + fiscal_targets._soi_capital_gains_active_totals(ordered, target_period=2024) + # The same record twice is one candidate, not a tie. + same = (*_capital_gains_t14_facts(), *_capital_gains_t14_facts()) + assert ( + len(fiscal_targets._soi_capital_gains_active_totals(same, target_period=2024)) + == 2 + ) + + +def _t14_returns_fact(period: object, *, record_id: str, value: float) -> dict: + fact = _soi_capital_gains_fact( + 2023, + source_record_id=record_id, + measure_id="net_capital_gains_returns", + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=value, + ) + fact["period"] = {**fact["period"], "value": period} + return fact + + +@pytest.mark.parametrize( + "rival", + [ + # One record id carrying two values: order would pick the value. + {"period": 2023, "record_id": _CG_T14_RETURNS, "value": 41.0}, + # Another record at the same period under an equivalent label. + { + "period": "tax_year_2023", + "record_id": "irs_soi.ty2023.table_1_4.v2.net_capital_gains_returns", + "value": 40.0, + }, + ], + ids=["same-id-other-value", "equivalent-period-label"], +) +def test_capital_gains_control_refuses_any_ambiguous_candidate(rival) -> None: + control = _t14_returns_fact(2023, record_id=_CG_T14_RETURNS, value=40.0) + other = _t14_returns_fact( + rival["period"], record_id=rival["record_id"], value=rival["value"] + ) + for ordered in ((control, other), (other, control)): + with pytest.raises(fiscal_targets.AmbiguousSoiCapitalGainsControlError): + fiscal_targets._soi_capital_gains_active_totals(ordered, target_period=2024) + + +def test_capital_gains_tie_at_a_superseded_period_is_not_ambiguous() -> None: + """Only a tie at the winning period matters: a later control supersedes + an older tie, in any order.""" + older = ( + _t14_returns_fact(2022, record_id="irs_soi.ty2022.table_1_4.a", value=1.0), + _t14_returns_fact(2022, record_id="irs_soi.ty2022.table_1_4.b", value=2.0), + ) + latest = _t14_returns_fact(2023, record_id=_CG_T14_RETURNS, value=40.0) + for ordered in ((*older, latest), (latest, *older), (older[0], latest, older[1])): + (control,) = fiscal_targets._soi_capital_gains_active_totals( + ordered, target_period=2024 + ).values() + assert (control.source_record_id, control.value) == (_CG_T14_RETURNS, 40.0) + + +@pytest.mark.parametrize( + ("record_set_id", "family"), + [ + ("irs_soi.ty2023.table_1_4", "table_1_4"), + ("irs_soi.table_1_4", "table_1_4"), + ("irs_soi.ty2022.historic_table_2.us", "historic_table_2"), + ("irs_soi.ty2022.historic_table_2.state_broad", "historic_table_2"), + (_CG_CD_RECORD_SET, "congressional_district"), + ( + "irs_soi.ty2024.congressional_district_2024.all_returns", + "congressional_district", + ), + ("irs_soi.congressional_district_2022.all_returns", "congressional_district"), + ("irs_soi.ty2023.table_4_3.all_returns_excluding_dependents", "table_4_3"), + ("irs_soi.ty2023", ""), + ("cbo.revenue_projection.ty2023", ""), + ("", ""), + ], +) +def test_soi_record_set_family_drops_period_and_data_vintage( + record_set_id: str, family: str +) -> None: + assert fiscal_targets._soi_record_set_family(record_set_id) == family + + +def test_capital_gains_control_is_order_free_latest_and_concept_matched() -> None: + """Property (microcosm#1035): for any set of national capital-gains facts + and any build period, the control per measure is the latest Table 1.4 + fact not after the build period, whatever the feed order, and no + Historic Table 2, congressional-district or unreviewed-family fact is ever + chosen. With no such Table 1.4 fact there is no control.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + record_sets = { + "table_1_4": "irs_soi.ty{period}.table_1_4", + "historic_table_2": "irs_soi.ty{period}.historic_table_2.us", + "congressional_district": ( + "irs_soi.ty{period}.congressional_district_2022.all_returns" + ), + "unreviewed": "irs_soi.ty{period}.table_4_3", + } + measures = ("net_capital_gains_returns", "net_capital_gains_amount") + candidate = st.tuples( + st.sampled_from(sorted(record_sets)), + st.integers(min_value=2018, max_value=2027), + st.sampled_from(measures), + st.floats(min_value=1.0, max_value=1e12, allow_nan=False), + ) + + @settings(max_examples=300, deadline=None) + @given( + st.lists(candidate, max_size=14, unique_by=lambda item: item[:3]), + st.integers(min_value=2019, max_value=2026), + st.randoms(use_true_random=False), + ) + def check(candidates, target_period, rng) -> None: + facts = [ + _soi_capital_gains_fact( + period, + source_record_id=( + f"{record_sets[family].format(period=period)}.us.{measure}" + ), + measure_id=measure, + layout_record_set_id=record_sets[family].format(period=period), + value=value, + ) + for family, period, measure, value in candidates + ] + shuffled = list(facts) + rng.shuffle(shuffled) + + controls = fiscal_targets._soi_capital_gains_active_totals( + tuple(facts), target_period=target_period + ) + assert controls == fiscal_targets._soi_capital_gains_active_totals( + tuple(shuffled), target_period=target_period + ) + chosen = {key[0]: control for key, control in controls.items()} + for measure in measures: + eligible = [ + (period, value) + for family, period, candidate_measure, value in candidates + if family == "table_1_4" + and candidate_measure == measure + and period <= target_period + ] + if not eligible: + assert measure not in chosen + continue + period, value = max(eligible) + control = chosen[measure] + assert control.source_period == str(period) + assert control.value == value + assert control.source_record_id == ( + f"irs_soi.ty{period}.table_1_4.us.{measure}" + ) + + check() + + +def test_rebased_capital_gains_states_never_outgrow_their_control() -> None: + """Property: whatever the HT2 state rows and national total, rebased + state rows keep their HT2 shares and so sum to the control times the + states' share of the HT2 nation; when the HT2 states sum to at most the + HT2 nation, they sum to at most the control.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + states = (("ca", "06"), ("ny", "36"), ("tx", "48")) + + @settings(max_examples=25, deadline=None) + @given( + st.lists( + st.integers(min_value=1, max_value=10_000_000), + min_size=len(states), + max_size=len(states), + ), + st.integers(min_value=0, max_value=5_000_000), + st.integers(min_value=1, max_value=50_000_000), + ) + def check(state_values, other_areas, control_value) -> None: + national = sum(state_values) + other_areas + facts = [ + *packaged_reference_facts(), + _soi_capital_gains_fact( + 2022, + source_record_id=( + "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_returns" + ), + measure_id="net_capital_gains_returns", + value=float(national), + ), + *( + _soi_capital_gains_fact( + 2022, + source_record_id=( + "irs_soi.ty2022.historic_table_2.state_broad." + f"{postal}.all.net_capital_gains_returns" + ), + measure_id="net_capital_gains_returns", + geography_level="state", + geography_id=f"0400000US{fips}", + value=float(value), + ) + for (postal, fips), value in zip(states, state_values, strict=True) + ), + _soi_capital_gains_fact( + 2023, + source_record_id=_CG_T14_RETURNS, + measure_id="net_capital_gains_returns", + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=float(control_value), + ), + ] + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + rebased = [ + spec + for spec in registry.specs + if ".historic_table_2.state_broad." in spec.name + and spec.metadata.get("source_measure_id") == "net_capital_gains_returns" + ] + assert len(rebased) == len(states) + total = sum(spec.value for spec in rebased) + assert math.isclose( + total, control_value * sum(state_values) / national, rel_tol=1e-12 + ) + assert total <= control_value * (1 + 1e-12) + + check() + + +def _capital_gains_cd_package_facts( + *, + us: tuple[float, float] = (98.0, 925.0), + hawaii: tuple[float, float] = (4.0, 40.0), + districts: tuple[tuple[float, float], ...] = ((1.5, 10.0), (2.5, 30.0)), +) -> list[dict[str, object]]: + """A congressional-district package's line-7 rows, stamped ty2023 like the + pinned feed: the US row, Hawaii, and Hawaii's two districts, each as + (returns, amount).""" + facts = [] + for index, measure in enumerate( + ("net_capital_gains_returns", "net_capital_gains_amount") + ): + facts.append( + _soi_congressional_district_fact( + measure, + us[index], + groupby_value_id="us", + geography_level="country", + geography_id="0100000US", + ) + ) + facts.append( + _soi_congressional_district_fact( + measure, + hawaii[index], + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + ) + for number, values in enumerate(districts, start=1): + facts.append( + _soi_congressional_district_fact( + measure, + values[index], + groupby_value_id=f"hi_0{number}", + geography_id=f"5001700US150{number}", + ) + ) + return facts + + +def _congressional_district_capital_gains_specs(registry) -> dict[str, object]: + return { + spec.name: spec + for spec in registry.specs + if spec.metadata.get("source_measure_id") + in {"net_capital_gains_returns", "net_capital_gains_amount"} + and ".congressional_district_" in spec.metadata["ledger_layout_record_set_id"] + } + + +def test_congressional_district_capital_gains_rows_are_shares_of_table_1_4() -> None: + """The congressional-district file's N01000/A01000 count Form 1040 line 7, + like Historic Table 2, so its state and district rows ship as shares of + that file's own US row times the Table 1.4 level; the US row retires + (microcosm#1038). On the pinned feed they shipped as line-7 levels, and + the US returns row was 2.41x the Table 1.4 target of the same model + quantity on the full surface.""" + facts = [ + *packaged_reference_facts(), + *_capital_gains_ht2_facts(), + *_capital_gains_cd_package_facts(), + *_capital_gains_t14_facts(), + ] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + + cd = _congressional_district_capital_gains_specs(registry) + assert not [ + name + for name, spec in cd.items() + if spec.metadata["ledger_geography_level"] == "country" + ] + for measure, control_id, control, cd_us, hawaii, districts in ( + ("net_capital_gains_returns", _CG_T14_RETURNS, 40.0, 98.0, 4.0, (1.5, 2.5)), + ("net_capital_gains_amount", _CG_T14_AMOUNT, 800.0, 925.0, 40.0, (10.0, 30.0)), + ): + factor = control / cd_us + state = cd[f"{_CG_CD_RECORD_SET}.hi_total.{measure}"] + children = [cd[f"{_CG_CD_RECORD_SET}.hi_0{n}.{measure}"] for n in (1, 2)] + assert math.isclose(state.value, hawaii * factor, rel_tol=1e-12) + for child, raw in zip(children, districts, strict=True): + assert math.isclose(child.value, raw * factor, rel_tol=1e-12) + # One factor scales the state and its districts, so the hierarchy + # reconciliation that follows leaves the proportions alone. + assert child.metadata["hierarchy_reconciliation_factor"] == "1" + for spec in (state, *children): + assert spec.metadata["uprating_factor"] == fiscal_targets._format_float( + factor + ) + assert spec.metadata["uprating_index_source_record_id"] == control_id + assert spec.metadata["soi_source_concept"] == ( + "form_1040_line_7_net_gain_or_loss" + ) + assert spec.metadata["soi_control_concept"] == ( + "schedule_d_taxable_net_gain" + ) + + # Historic Table 2 rows keep dividing by the HT2 US row (100 / 1,000), not + # by the congressional-district US row. + specs = {spec.metadata["ledger_source_record_id"]: spec for spec in registry.specs} + assert specs[_CG_HT2_CA_RETURNS].value == 10.0 + assert specs[_CG_HT2_CA_AMOUNT].value == 200.0 + + +#: The pinned feed's 22incd.csv: TY2022 data that Chronicle stamps ty2023 +#: (PolicyEngine/chronicle#117). A source-vintage correction keys on these. +_CD_2022_SOURCE_SHA256 = ( + "137522878af78d624cfddc0e17cd36ae76a21b7bed166c7bb96ad3243a18a668" +) + + +def _capital_gains_cd_package_at(stamp: int) -> list[dict[str, object]]: + """The congressional-district capital-gains rows of + ``_capital_gains_cd_package_facts``, stamped ``stamp``, carrying the + pinned 22incd.csv's digest and raw key.""" + record_set_id = f"irs_soi.ty{stamp}.congressional_district_2022.all_returns" + facts = [] + for fact in _capital_gains_cd_package_facts(): + row = fact["layout"]["groupby_value_id"] + measure = fact["layout"]["measure_id"] + restamped = _dynamic_ledger_fact( + source_record_id=f"{record_set_id}.{row}.{measure}", + source_name="irs_soi", + measure_id=measure, + value=fact["value"], + period_value=stamp, + geography_level=fact["geography"]["level"], + geography_id=fact["geography"]["id"], + dimensions={"income_range": "all", "filing_status": "all"}, + layout_record_set_id=record_set_id, + groupby_dimension="irs_soi.congressional_district", + groupby_value_id=row, + ) + restamped["source"].update( + { + "source_file": "22incd.csv", + "source_sha256": _CD_2022_SOURCE_SHA256, + "raw_r2_key": ( + "raw/irs_soi/soi-congressional-district-2022/2022/" + f"{_CD_2022_SOURCE_SHA256}/22incd.csv" + ), + "vintage": f"tax_year_{stamp}", + } + ) + facts.append(restamped) + return facts + + +def test_congressional_district_capital_gains_ignore_the_package_stamp() -> None: + """Differential: a congressional-district capital-gains row is its share of + the same package's US row times the Table 1.4 level, so the package's + period stamp cancels. Compiled and aged to 2024, the package stamped + ty2023, as on the pinned feed, gives exactly the values of the same package + stamped truthfully at 2022, and its amounts age from the control's 2023 + period on the CBO net-capital-gain ratio, not from 2022. The facts carry + the pinned file's digest and raw key, so a source-vintage correction that + recognises the restamp sees them: it must leave these values alone + (microcosm#1030, microcosm#1038).""" + cbo = [ + _cbo_income_source_projection_fact(2023, "net_capital_gain", value=981.4e9), + _cbo_income_source_projection_fact(2024, "net_capital_gain", value=1290.9e9), + ] + compiled = {} + for stamp in (2023, 2022): + registry = compile_us_fiscal_target_registry( + [ + *packaged_reference_facts(), + *_capital_gains_cd_package_at(stamp), + *_capital_gains_t14_facts(), + *cbo, + ], + target_period=2024, + age_targets=True, + allow_unaged_dollar_targets=True, + ) + compiled[stamp] = { + ( + spec.metadata["source_measure_id"], + spec.metadata["ledger_geography_id"], + ): (spec) + for spec in _congressional_district_capital_gains_specs(registry).values() + } + + assert set(compiled[2023]) == set(compiled[2022]) + assert len(compiled[2023]) == 6 + ratio = 1290.9e9 / 981.4e9 + for key, spec in compiled[2023].items(): + truthful = compiled[2022][key] + assert math.isclose(spec.value, truthful.value, rel_tol=1e-12), key + assert spec.metadata["uprating_to_period"] == "2023" + if key[0] == "net_capital_gains_amount": + for aged in (spec, truthful): + assert math.isclose( + float(aged.metadata["aging_factor"]), ratio, rel_tol=1e-12 + ) + share = {"0400000US15": 40.0, "5001700US1501": 10.0}.get(key[1], 30.0) + assert math.isclose( + spec.value, share / 925.0 * 800.0 * ratio, rel_tol=1e-12 + ) + + +def test_congressional_district_capital_gains_rows_without_a_control_are_dropped() -> ( + None +): + """Without a Schedule D control no congressional-district capital-gains row + compiles: the file's line-7 counts are never a capital_gains_gross level.""" + facts = [*packaged_reference_facts(), *_capital_gains_cd_package_facts()] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + + assert _congressional_district_capital_gains_specs(registry) == {} + + +def test_capital_gains_share_row_without_its_family_total_is_dropped() -> None: + """A congressional-district row with a Schedule D control but no US row of + its own family has no defined share: it is dropped, never divided by the + Historic Table 2 US row and never shipped as a line-7 level. The HT2 rows + beside it keep their own denominator (microcosm#1038).""" + facts = [ + *packaged_reference_facts(), + *( + fact + for fact in _capital_gains_cd_package_facts() + if fact["layout"]["groupby_value_id"] != "us" + ), + *_capital_gains_ht2_facts(), + *_capital_gains_t14_facts(), + ] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + + assert _congressional_district_capital_gains_specs(registry) == {} + specs = {spec.metadata["ledger_source_record_id"]: spec for spec in registry.specs} + assert specs[_CG_HT2_CA_RETURNS].value == 10.0 + assert specs[_CG_HT2_CA_RETURNS].metadata["soi_share_total_source_record_id"] == ( + "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_returns" + ) + + +def test_capital_gains_share_family_refuses_two_national_totals() -> None: + """Two different national totals for one share family, quantity and period + refuse the compile: feed order must not pick a share denominator.""" + rival = _soi_congressional_district_fact( + "net_capital_gains_returns", + 99.0, + groupby_value_id="us_rival", + geography_level="country", + geography_id="0100000US", + ) + facts = [ + *packaged_reference_facts(), + *_capital_gains_cd_package_facts(), + *_capital_gains_t14_facts(), + rival, + ] + + with pytest.raises(fiscal_targets.AmbiguousSoiCapitalGainsShareTotalError): + fiscal_targets._soi_capital_gains_share_national_totals(tuple(facts)) + with pytest.raises(fiscal_targets.AmbiguousSoiCapitalGainsShareTotalError): + compile_us_fiscal_target_registry(facts, allow_unaged_dollar_targets=True) + + +@pytest.mark.parametrize("twin_first", [True, False], ids=["twin-first", "us-first"]) +def test_capital_gains_share_denominator_is_order_free(twin_first: bool) -> None: + """Two records carrying the same national total for one share family are + not ambiguous, and the denominator a share row names is the smaller + record id whichever comes first in the feed.""" + twin = _soi_congressional_district_fact( + "net_capital_gains_returns", + 98.0, + groupby_value_id="us_twin", + geography_level="country", + geography_id="0100000US", + ) + package = _capital_gains_cd_package_facts() + facts = [ + *packaged_reference_facts(), + *((twin, *package) if twin_first else (*package, twin)), + *_capital_gains_t14_facts(), + ] + + registry = compile_us_fiscal_target_registry( + facts, allow_unaged_dollar_targets=True + ) + + hawaii = _congressional_district_capital_gains_specs(registry)[ + f"{_CG_CD_RECORD_SET}.hi_total.net_capital_gains_returns" + ] + assert hawaii.metadata["soi_share_total_source_record_id"] == min( + f"{_CG_CD_RECORD_SET}.us.net_capital_gains_returns", + f"{_CG_CD_RECORD_SET}.us_twin.net_capital_gains_returns", + ) + assert math.isclose(hawaii.value, 4.0 * 40.0 / 98.0, rel_tol=1e-12) + + +@pytest.mark.parametrize( + ("record_set_id", "family"), + [ + ("irs_soi.ty2022.historic_table_2.state_broad.ca", "historic_table_2"), + ( + "irs_soi.ty2023.congressional_district_2022.all_returns", + "congressional_district", + ), + ( + "irs_soi.ty2024.congressional_district_2024.all_returns", + "congressional_district", + ), + ("irs_soi.ty2023.table_1_4", None), + ("irs_soi.ty2023.itemized_all_returns", None), + ("bea.cy2023.regional", None), + ], +) +def test_capital_gains_share_families_are_the_line_7_families( + record_set_id: str, family: str | None +) -> None: + """Only a registered family whose concept is not the model's supplies + shares: Table 1.4 is the model's own concept and an unregistered family + has no reviewed concept.""" + assert fiscal_targets._soi_capital_gains_share_family(record_set_id) == family + + +def test_congressional_district_capital_gains_shares_conserve_the_control() -> None: + """Property: whatever the congressional-district package, the Table 1.4 + level and the feed order, no congressional-district capital-gains row + ships at the country level or without the Schedule D bridge; each state + row is its share of the file's US row times the control; each state's + districts sum to that state row; and the states, and the districts, sum + to the control times the states' share of the US row, so never past the + control. Historic Table 2 rows drawn beside them divide by their own US + row, and every row names the denominator it used. The order is part of the + draw, so the result is order-free.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + # Two-district states and one single-district state, whose source row is + # the state total only (22incd.csv carries no district row for them). + two_district_states = (("hi", "15"), ("id", "16"), ("me", "23")) + at_large = ("vt", "50") + measure = "net_capital_gains_returns" + values = st.integers(min_value=1, max_value=10_000_000) + + @settings(max_examples=25, deadline=None) + @given( + districts=st.lists( + st.tuples(values, values), + min_size=len(two_district_states), + max_size=len(two_district_states), + ), + state_excess=st.lists( + st.integers(min_value=0, max_value=1_000_000), + min_size=len(two_district_states), + max_size=len(two_district_states), + ), + at_large_value=values, + other_areas=st.integers(min_value=0, max_value=50_000_000), + control=values, + ht2=st.tuples(values, values), + order=st.randoms(use_true_random=False), + ) + def check( + districts, state_excess, at_large_value, other_areas, control, ht2, order + ): + ht2_state, ht2_rest = ht2 + ht2_us_id = "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_returns" + ht2_state_id = ( + "irs_soi.ty2022.historic_table_2.state_broad.hi.all." + "net_capital_gains_returns" + ) + facts = [ + _soi_capital_gains_fact( + 2022, + source_record_id=ht2_us_id, + measure_id=measure, + value=float(ht2_state + ht2_rest), + ), + _soi_capital_gains_fact( + 2022, + source_record_id=ht2_state_id, + measure_id=measure, + geography_level="state", + geography_id="0400000US15", + layout_record_set_id="irs_soi.ty2022.historic_table_2.state_broad.hi", + value=float(ht2_state), + ), + ] + state_values = {} + for (postal, fips), pair, excess in zip( + two_district_states, districts, state_excess, strict=True + ): + state_values[fips] = float(sum(pair) + excess) + facts.append( + _soi_congressional_district_fact( + measure, + state_values[fips], + groupby_value_id=f"{postal}_total", + geography_level="state", + geography_id=f"0400000US{fips}", + ) + ) + for number, value in enumerate(pair, start=1): + facts.append( + _soi_congressional_district_fact( + measure, + float(value), + groupby_value_id=f"{postal}_0{number}", + geography_id=f"5001700US{fips}0{number}", + ) + ) + state_values[at_large[1]] = float(at_large_value) + facts.append( + _soi_congressional_district_fact( + measure, + float(at_large_value), + groupby_value_id=f"{at_large[0]}_total", + geography_level="state", + geography_id=f"0400000US{at_large[1]}", + ) + ) + cd_us = sum(state_values.values()) + other_areas + facts.append( + _soi_congressional_district_fact( + measure, + cd_us, + groupby_value_id="us", + geography_level="country", + geography_id="0100000US", + ) + ) + facts.append( + _soi_capital_gains_fact( + 2023, + source_record_id=_CG_T14_RETURNS, + measure_id=measure, + layout_record_set_id="irs_soi.ty2023.table_1_4", + value=float(control), + ) + ) + order.shuffle(facts) + registry = compile_us_fiscal_target_registry( + [*packaged_reference_facts(), *facts], allow_unaged_dollar_targets=True + ) + + hawaii_ht2 = next( + spec + for spec in registry.specs + if spec.metadata["ledger_source_record_id"] == ht2_state_id + ) + assert math.isclose( + hawaii_ht2.value, + ht2_state * control / (ht2_state + ht2_rest), + rel_tol=1e-12, + ) + assert hawaii_ht2.metadata["soi_share_total_source_record_id"] == ht2_us_id + + cd = _congressional_district_capital_gains_specs(registry).values() + by_level: dict[str, list] = {} + for spec in cd: + by_level.setdefault(spec.metadata["ledger_geography_level"], []).append( + spec + ) + assert spec.metadata["soi_control_concept"] == ( + "schedule_d_taxable_net_gain" + ) + assert spec.metadata["uprating_index_source_record_id"] == _CG_T14_RETURNS + assert spec.metadata["soi_share_total_source_record_id"] == ( + f"{_CG_CD_RECORD_SET}.us.{measure}" + ) + assert set(by_level) == {"state", "congressional_district"} + assert len(by_level["state"]) == len(state_values) + assert len(by_level["congressional_district"]) == 2 * len(two_district_states) + + factor = control / cd_us + for spec in by_level["state"]: + raw = state_values[spec.metadata["state_fips"]] + assert math.isclose(spec.value, raw * factor, rel_tol=1e-12) + state_by_fips = { + spec.metadata["state_fips"]: spec.value for spec in by_level["state"] + } + district_totals: dict[str, float] = {} + for spec in by_level["congressional_district"]: + fips = spec.metadata["state_fips"] + district_totals[fips] = district_totals.get(fips, 0.0) + spec.value + for fips, total in district_totals.items(): + assert math.isclose(total, state_by_fips[fips], rel_tol=1e-12) + + expected = control * sum(state_values.values()) / cd_us + states_total = sum(state_by_fips.values()) + assert math.isclose(states_total, expected, rel_tol=1e-12) + assert states_total <= control * (1 + 1e-12) + assert sum(district_totals.values()) <= control * (1 + 1e-12) + + check() + + +def test_cross_period_soi_taxable_interest_agi_slice_without_total_is_dropped() -> None: + source_record_id = ( + "irs_soi.ty2022.historic_table_2.us.200k_to_500k.taxable_interest_amount" + ) + registry = compile_us_fiscal_target_registry( + [ + *packaged_reference_facts(), + _soi_taxable_interest_fact( + 2022, + source_record_id=source_record_id, + value=21_000_000_000, + income_range="200k_to_500k", + lower=200_000, + upper=500_000, + ), + ], + target_period=2024, + allow_unaged_dollar_targets=True, + ) + + assert source_record_id not in {spec.name for spec in registry.specs} + + +def test_cross_period_soi_eitc_decomposition_uses_latest_source_backed_total() -> None: + source_record_id = ( + "irs_soi.ty2023.table_2_5.eitc_by_agi_children.one_qualifying_child." + "25k_to_30k.eitc_total" + ) + registry = compile_us_fiscal_target_registry( + [ + *packaged_reference_facts(), + _soi_eitc_total_fact( + 2023, + measure_id="total_earned_income_credit_amount", + value=66_270_000_000, + ), + *_soi_eitc_child_total_facts( + 2023, + measure_id="eitc_total", + values={"all_qualifying_children": 66_270_000_000}, + ), + _soi_eitc_filing_season_total_fact( + measure_id="total_earned_income_credit_amount", + value=69_041_649_000, + ), + _soi_eitc_child_fact( + 2023, + source_record_id=source_record_id, + measure_id="eitc_total", + value=66_270_000, + ), + ], + target_period=2024, + allow_unaged_dollar_targets=True, + ) + + spec = {spec.name: spec for spec in registry.specs}[source_record_id] + assert spec.value == 69_041_649 + assert spec.metadata["uprating_index"] == "total_eitc_amount" + assert spec.metadata["uprating_index_source_period"] == "2024" assert spec.metadata["uprating_index_source_record_id"] == ( "irs_soi.ty2024.filing_season_week47.eitc_all_returns." "earned_income_credit.total_earned_income_credit_amount" @@ -4698,6 +6323,256 @@ def test_age_targets_chains_w2_tips_through_soi_wages_bridge() -> None: assert abs(spec.value - 26_786_522_000 * expected_factor) < 1.0 +def _w2_tips_chain_facts(*, tips_year: int, raw_r2_key: str | None = None): + """Tips amount plus the SOI wages bridge and CBO wages projections.""" + tips = _dynamic_ledger_fact( + source_record_id=_W2_TIPS_AMOUNT.format(year=tips_year), + source_name="irs_soi", + measure_id="amount", + value=26_786_522_000, + period_value=tips_year, + layout_record_set_id=f"irs_soi.ty{tips_year}.form_w2_social_security_tips", + groupby_dimension="irs_soi.form_w2_item", + groupby_value_id="box_7_social_security_tips", + ) + tips["assertion"] = "observation" + if raw_r2_key is not None: + tips["source"]["raw_r2_key"] = raw_r2_key + wages = [ + _dynamic_ledger_fact( + source_record_id=f"irs_soi.ty{year}.table_1_4.all.wages_salaries_amount", + source_name="irs_soi", + measure_id="wages_salaries_amount", + value=value, + period_value=year, + dimensions={"income_range": "all", "filing_status": "all"}, + layout_record_set_id=f"irs_soi.ty{year}.table_1_4", + groupby_dimension="us:statutes/26/62#adjusted_gross_income", + groupby_value_id="all", + ) + for year, value in ((2020, 8_416_495_535_000), (2023, 10_000_000_000_000)) + ] + return [ + *packaged_reference_facts(), + tips, + *wages, + _cbo_income_source_projection_fact( + 2023, "wages_and_salaries", value=10_200_000_000_000 + ), + _cbo_income_source_projection_fact( + 2024, "wages_and_salaries", value=10_700_000_000_000 + ), + ] + + +_W2_RAW_R2_KEY = ( + "raw/irs_soi/soi-w2-statistics-2020/2020/" + "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f/" + "20in04w2all.xlsx" +) + + +def test_age_targets_reads_a_restamped_w2_tips_amount_at_its_data_year() -> None: + # chronicle#117: the feed's ty2023 tips amount is the TY2020 workbook + # cell stamped 2023. Its raw key names the 2020 artifact, so it must age + # exactly as its honest ty2020 twin does (differential), not from 2023. + restamped = compile_us_fiscal_target_registry( + _w2_tips_chain_facts(tips_year=2023, raw_r2_key=_W2_RAW_R2_KEY), + target_period=2024, + age_targets=True, + ) + honest = compile_us_fiscal_target_registry( + _w2_tips_chain_facts(tips_year=2020, raw_r2_key=_W2_RAW_R2_KEY), + target_period=2024, + age_targets=True, + ) + spec = _aged_spec_by_source_record_id(restamped, _W2_TIPS_AMOUNT.format(year=2023)) + twin = _aged_spec_by_source_record_id(honest, _W2_TIPS_AMOUNT.format(year=2020)) + assert spec.metadata["source_period"] == "2020" + assert spec.metadata["ledger_fact_period"] == "2023" + assert spec.metadata["source_vintage_correction"] == ( + "soi-w2-statistics-2020: stamped 2023, data year 2020" + ) + assert spec.metadata["aging_factor_source"].startswith("chained:") + assert spec.metadata["aging_factor"] == twin.metadata["aging_factor"] + assert spec.value == twin.value + assert "source_vintage_correction" not in twin.metadata + + # Without the raw key there is no evidence of the restamp, and the fact + # ages from its stamp on the direct CBO ratio. + unkeyed = compile_us_fiscal_target_registry( + _w2_tips_chain_facts(tips_year=2023), + target_period=2024, + age_targets=True, + ) + direct = _aged_spec_by_source_record_id(unkeyed, _W2_TIPS_AMOUNT.format(year=2023)) + assert direct.metadata["source_period"] == "2023" + assert direct.value == pytest.approx( + 26_786_522_000 * 10_700_000_000_000 / 10_200_000_000_000 + ) + + +def test_restamp_shadow_guard_compares_state_agi_bands_per_state_and_measure() -> None: + """State AGI bands keep their period in the selection key and compete as + whole vintages per state and measure (microcosm#940), so the guard compares + them at that grain: a band vintage restamped 2024 from 2022 data shadows a + truthful 2023 vintage of the same state and measure, whatever the bounds. + Another state, or an unflagged row with a period-free key, is untouched.""" + from types import SimpleNamespace + + from microcosm.build.us_runtime.source_vintage import ( + RestampShadowsNewerVintageError, + SourceVintageCorrection, + ) + + def band(state_fips: str) -> SimpleNamespace: + return SimpleNamespace( + metadata={ + fiscal_targets._SOI_STATE_AGI_BAND_REBASE_FLAG: "true", + "state_fips": state_fips, + "source_measure_id": "return_count", + } + ) + + restamps = {"restamped": SourceVintageCorrection("restamped", "pkg", 2024, 2022)} + restamped = (("ca", "500k_plus", "2024"), (1, 202499, "2024"), 1.0, "restamped") + truthful = (("ca", "1m_plus", "2023"), (1, 202399, "2023"), 1.0, "truthful") + target = (1, 202499, "2024") + with pytest.raises(RestampShadowsNewerVintageError, match="truthful"): + fiscal_targets._refuse_restamps_that_shadow_newer_vintages( + [(*restamped, band("06")), (*truthful, band("06"))], + restamps, + target_period_key=target, + ) + for other in (band("36"), None): + fiscal_targets._refuse_restamps_that_shadow_newer_vintages( + [(*restamped, band("06")), (*truthful, other)], + restamps, + target_period_key=target, + ) + + +def test_compile_refuses_a_restamp_that_would_outrank_newer_data() -> None: + # A truthful TY2021 tips fact would lose latest-vintage selection to the + # TY2020 cell stamped 2023; the compile refuses rather than drop it. + from microcosm.build.us_runtime.source_vintage import ( + RestampShadowsNewerVintageError, + ) + + newer = _dynamic_ledger_fact( + source_record_id=_W2_TIPS_AMOUNT.format(year=2021), + source_name="irs_soi", + measure_id="amount", + value=30_000_000_000, + period_value=2021, + layout_record_set_id="irs_soi.ty2021.form_w2_social_security_tips", + groupby_dimension="irs_soi.form_w2_item", + groupby_value_id="box_7_social_security_tips", + ) + facts = [ + *_w2_tips_chain_facts(tips_year=2023, raw_r2_key=_W2_RAW_R2_KEY), + newer, + ] + with pytest.raises(RestampShadowsNewerVintageError, match="ty2021"): + compile_us_fiscal_target_registry(facts, target_period=2024, age_targets=True) + # A truthful fact at the stamp year itself is shadowed too (the tie-break, + # not the data, would decide), and one after the target period is not a + # candidate at all. + at_stamp = dict(newer, value=31_000_000_000) + at_stamp["lineage"] = { + "source_record_id": _W2_TIPS_AMOUNT.format(year=2023) + "_truthful" + } + at_stamp["period"] = {"type": "calendar_year", "value": 2023} + for key in ("aggregate_fact_key", "semantic_fact_key", "legacy_fact_key"): + at_stamp[key] = str(newer[key]).replace("2021", "2023truthful") + with pytest.raises(RestampShadowsNewerVintageError, match="2023"): + compile_us_fiscal_target_registry( + [ + *_w2_tips_chain_facts(tips_year=2023, raw_r2_key=_W2_RAW_R2_KEY), + at_stamp, + ], + target_period=2024, + age_targets=True, + ) + # Selection eligibility applies first: at target 2022 neither the 2023 + # restamp nor the 2023 truthful fact is a candidate. + from microcosm.build.us_runtime.source_vintage import SourceVintageCorrection + + restamp = SourceVintageCorrection("restamped", "pkg", 2023, 2020) + candidates = [ + (("key",), (1, 202399, "2023"), 1.0, "restamped", None), + (("key",), (1, 202399, "2023"), 1.0, "truthful", None), + ] + fiscal_targets._refuse_restamps_that_shadow_newer_vintages( + candidates, + {"restamped": restamp}, + target_period_key=(1, 202299, "2022"), + ) + with pytest.raises(RestampShadowsNewerVintageError, match="truthful"): + fiscal_targets._refuse_restamps_that_shadow_newer_vintages( + candidates, + {"restamped": restamp}, + target_period_key=(1, 202499, "2024"), + ) + + # The honest twin at the data year is not newer data: no refusal. + twin = dict(newer, value=26_786_522_000) + twin["lineage"] = {"source_record_id": _W2_TIPS_AMOUNT.format(year=2020)} + twin["period"] = {"type": "calendar_year", "value": 2020} + twin["layout"] = dict( + newer["layout"], record_set_id="irs_soi.ty2020.form_w2_social_security_tips" + ) + for key in ("aggregate_fact_key", "semantic_fact_key", "legacy_fact_key"): + twin[key] = str(newer[key]).replace("2021", "2020twin") + compile_us_fiscal_target_registry( + [*_w2_tips_chain_facts(tips_year=2023, raw_r2_key=_W2_RAW_R2_KEY), twin], + target_period=2024, + age_targets=True, + ) + + +def test_compile_refuses_a_restamp_in_an_aging_index_only_when_aging( + monkeypatch, +) -> None: + # No registered restamp sits in the chain today; force one to prove the + # compile runs the check before aging, and skips it when not aging. + from microcosm.build.us_runtime.source_vintage import ( + RestampedAgingIndexError, + SourceVintageCorrection, + ) + + chain_id = "irs_soi.ty2023.table_1_4.all.wages_salaries_amount" + monkeypatch.setattr( + fiscal_targets, + "source_vintage_corrections", + lambda facts: { + chain_id: SourceVintageCorrection(chain_id, "soi-t14-2022", 2023, 2022) + }, + ) + facts = _w2_tips_chain_facts(tips_year=2020) + with pytest.raises(RestampedAgingIndexError, match=chain_id): + compile_us_fiscal_target_registry(facts, target_period=2024, age_targets=True) + compile_us_fiscal_target_registry( + facts, + target_period=2024, + age_targets=False, + allow_unaged_dollar_targets=True, + ) + + +def test_compile_refuses_an_unreviewed_restamp() -> None: + from microcosm.build.us_runtime.source_vintage import UnreviewedRestampError + + facts = _w2_tips_chain_facts( + tips_year=2023, + raw_r2_key=_W2_RAW_R2_KEY.replace( + "soi-w2-statistics-2020/2020", "soi-w2-statistics-2021/2021" + ), + ) + with pytest.raises(UnreviewedRestampError, match="soi-w2-statistics-2021"): + compile_us_fiscal_target_registry(facts, target_period=2024, age_targets=True) + + def test_ssa_ssi_age_band_counts_bind_as_person_age_indicator_targets() -> None: # microcosm#470: the SSA SSI Monthly age-band recipient counts bind as # national indicator counts of engine ssi receipt sliced by the fact's diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_soi_congressional_district_vintage.py b/packages/microcosm-build/tests/engine_free/us/test_us_soi_congressional_district_vintage.py index ed94d40e1e..3bb644695c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_soi_congressional_district_vintage.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_soi_congressional_district_vintage.py @@ -7,7 +7,9 @@ meets the same guards with no code change: - ``fiscal_targets``: a district aggregate never keys a taxable-interest - rebase control (microcosm#489) and the district PTC amount never compiles; + rebase control (microcosm#489), a district fact of a measure the column + register lists must name its IRS column, and the district PTC amount, + read from A85530, never compiles (microcosm#1038); - ``release_target_parity``: the red line still requires the CD family compiled, and now requires every declared CD vintage compiled; - ``tools/build_us_target_parity_manifest.py``: the one-surface note still @@ -105,8 +107,9 @@ def _cd_fact( groupby_value_id: str = "hi_01", geography_level: str = "congressional_district", geography_id: str = "5001700US1501", + source_column_id: str | None = None, ) -> dict[str, object]: - return _dynamic_ledger_fact( + fact = _dynamic_ledger_fact( source_record_id=f"{record_set_id}.{groupby_value_id}.{measure_id}", source_name="irs_soi", measure_id=measure_id, @@ -119,6 +122,9 @@ def _cd_fact( groupby_dimension="irs_soi.congressional_district", groupby_value_id=groupby_value_id, ) + if source_column_id is not None: + fact["layout"]["source_column_id"] = source_column_id + return fact def _is_cd(record_set_id: str) -> bool: @@ -127,9 +133,25 @@ def _is_cd(record_set_id: str) -> bool: ) -def _ptc_conflict(record_set_id: str, measure_id: str) -> bool: - return fiscal_targets._is_soi_cd_premium_tax_credit_amount_conflict( - {"layout": {"record_set_id": record_set_id}}, measure_id=measure_id +def _column_excluded( + record_set_id: str, measure_id: str, source_column_id: str | None = None +) -> bool: + """Whether the column register drops this SOI fact (microcosm#1038). + + Raises ``MissingSoiSourceColumnError`` for a district fact of a listed + measure that names no column.""" + layout = {"record_set_id": record_set_id} + if source_column_id is not None: + layout["source_column_id"] = source_column_id + return fiscal_targets._is_source_column_concept_exclusion( + { + "observed_measure": { + "source_name": "irs_soi", + "source_measure_id": measure_id, + }, + "layout": layout, + "lineage": {"source_record_id": f"{record_set_id}.us.{measure_id}"}, + } ) @@ -191,11 +213,19 @@ def test_district_record_set_is_matched_by_family( record_set_id: str, is_cd: bool ) -> None: """Any IRS SOI district file, at any data vintage and with or without a - period token, is a CD record set, and its PTC amount conflicts; no other - family or source is, and no other measure conflicts.""" + period token, is a CD record set, and its PTC amount must name its IRS + column; no other family or source is. The column register drops the PTC + amount read from A85530 and keeps the one read from A85770, whatever the + record set.""" assert _is_cd(record_set_id) is is_cd - assert _ptc_conflict(record_set_id, "premium_tax_credit_amount") is is_cd - assert not _ptc_conflict(record_set_id, "premium_tax_credit_returns") + assert _column_excluded(record_set_id, "premium_tax_credit_amount", "A85530") + assert not _column_excluded(record_set_id, "premium_tax_credit_amount", "A85770") + if is_cd: + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + _column_excluded(record_set_id, "premium_tax_credit_amount") + else: + assert not _column_excluded(record_set_id, "premium_tax_credit_amount") + assert not _column_excluded(record_set_id, "return_count") if is_cd: assert _interest_control_key(record_set_id) is None @@ -205,9 +235,10 @@ def test_district_guards_hold_at_every_vintage() -> None: bare year, month, ``YYYY_MM``; district data vintage 1990-2099; any trailing segments): - - a district file is a CD record set, its PTC amount conflicts, and it - never keys a taxable-interest control, while its Table 1.4 twin keys one - and does not conflict; + - a district file is a CD record set, its PTC amount must name its IRS + column and is dropped when the column is A85530, and it never keys a + taxable-interest control, while its Table 1.4 twin keys one and needs + no column; - no other SOI family and no other source is a CD record set; - differential against the pinned literal this replaced: every id ``.congressional_district_2022.`` matched still matches, and the two @@ -293,14 +324,17 @@ def check(token, vintage, rest, other_family, other_source) -> None: assert fiscal_targets._soi_record_set_family(cd) == "congressional_district" assert _is_cd(cd) - assert _ptc_conflict(cd, "premium_tax_credit_amount") + with pytest.raises(fiscal_targets.MissingSoiSourceColumnError): + _column_excluded(cd, "premium_tax_credit_amount") + assert _column_excluded(cd, "premium_tax_credit_amount", "A85530") + assert not _column_excluded(cd, "premium_tax_credit_amount", "A85770") cd_all_returns = record_set("irs_soi", token, district_family, ["all_returns"]) assert _interest_control_key(cd_all_returns) is None twin = record_set("irs_soi", token, "table_1_4", ["all_returns"]) twin_key = _interest_control_key(twin) assert twin_key is not None assert (twin_key[0], twin_key[2]) == ("taxable_interest_amount", "all_returns") - assert not _ptc_conflict(twin, "premium_tax_credit_amount") + assert not _column_excluded(twin, "premium_tax_credit_amount") assert fiscal_targets._soi_record_set_family(other) == other_family assert not _is_cd(other) @@ -404,9 +438,10 @@ def test_district_taxable_interest_never_controls_the_rebase( @CD_RECORD_SETS def test_district_ptc_amount_never_compiles(cd_record_set: str) -> None: - """The district A85530 amount is not the gross annual PTC that - ``assigned_aca_ptc`` measures, so no district PTC amount compiles at any - vintage, while the file's other district and state-total rows do.""" + """The district file reads its PTC amount from A85530, additional + Medicare tax, which is not the gross annual PTC that ``assigned_aca_ptc`` + measures (microcosm#1038). The column register drops it at any vintage, + while the file's other district and state-total rows compile.""" facts = [ *packaged_reference_facts(), _cd_fact(cd_record_set, "return_count", 100_000), @@ -418,7 +453,12 @@ def test_district_ptc_amount_never_compiles(cd_record_set: str) -> None: geography_id="5001700US1502", ), _cd_fact(cd_record_set, "adjusted_gross_income", 10_000_000_000), - _cd_fact(cd_record_set, "premium_tax_credit_amount", 90_000_000), + _cd_fact( + cd_record_set, + "premium_tax_credit_amount", + 90_000_000, + source_column_id="A85530", + ), _cd_fact( cd_record_set, "return_count", @@ -434,6 +474,7 @@ def test_district_ptc_amount_never_compiles(cd_record_set: str) -> None: groupby_value_id="hi_total", geography_level="state", geography_id="0400000US15", + source_column_id="A85530", ), ] registry = compile_us_fiscal_target_registry( @@ -686,7 +727,9 @@ def test_pinned_feed_district_match_is_unchanged_fact_by_fact() -> None: """On the pinned feed the family match decides exactly as the ``.congressional_district_2022.`` literal it replaced, fact by fact, so neither guard moves a target. It also agrees with the release tools' - vintage-free spec prefix on every SOI fact's record-set spec id.""" + vintage-free spec prefix on every SOI fact's record-set spec id. The + column register drops district facts only, and every district PTC + amount (microcosm#1038).""" tool = _load_tool("build_us_target_parity_manifest") feed_path = tool.DEFAULT_FEED_PATH if not feed_path.exists(): @@ -707,9 +750,10 @@ def test_pinned_feed_district_match_is_unchanged_fact_by_fact() -> None: record_set_id ) measure_id = fiscal_targets._measure_id(fact) - assert fiscal_targets._is_soi_cd_premium_tax_credit_amount_conflict( - fact, measure_id=measure_id - ) is (is_cd and measure_id == "premium_tax_credit_amount") + excluded = fiscal_targets._is_source_column_concept_exclusion(fact) + assert is_cd or not excluded, record_set_id + if is_cd and measure_id == "premium_tax_credit_amount": + assert excluded, fiscal_targets._source_record_id(fact) spec_id = fiscal_targets._str_at(fact, "layout", "record_set_spec_id") if fiscal_targets._source_name(fact) == "irs_soi" and spec_id: assert spec_id.startswith("irs_soi.congressional_district_") is is_cd diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_source_vintage.py b/packages/microcosm-build/tests/engine_free/us/test_us_source_vintage.py new file mode 100644 index 0000000000..6b7a666c40 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_source_vintage.py @@ -0,0 +1,935 @@ +"""Restamped Chronicle facts are read at their data year (chronicle#117). + +The compile-level cases (a restamped W-2 tips amount ageing from TY2020, the +refusals of an unreviewed or shadowing restamp) and the pinned-feed register +check live in ``test_us_fiscal_targets.py`` beside the other W-2 aging tests. +""" + +from __future__ import annotations + +import dataclasses +import json + +import pytest + +from microcosm.build.us_runtime.source_vintage import ( + US_LATER_PERIOD_OBSERVATION_EXEMPTIONS, + US_RESTAMPED_SOURCE_PACKAGES, + LaterPeriodObservationExemption, + RestampedAgingIndexError, + RestampedSourcePackage, + SourceVintageCorrection, + UnreviewedRestampError, + apply_source_vintage_corrections, + check_restamps_stay_out_of_aging_indexes, + detect_restamped_facts, + fact_artifact_year, + source_vintage_corrections, +) +from microcosm.calibrate import TargetRegistry, TargetSpec + +_W2 = "soi-w2-statistics-2020" +_W2_SHA = US_RESTAMPED_SOURCE_PACKAGES[_W2].source_sha256 +_OTHER_SHA = "0" * 64 +_TIPS_2023 = ( + "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.amount" +) + + +def _raw_key(package_id: str, artifact_year: int | str, file: str = "f.xlsx") -> str: + return f"raw/irs_soi/{package_id}/{artifact_year}/{_OTHER_SHA}/{file}" + + +def _fact( + source_record_id: str, + *, + period: int | str, + raw_r2_key: str | None, + assertion: str | None = "observation", + sha: str | None = None, +) -> dict[str, object]: + source: dict[str, object] = {} + if raw_r2_key is not None: + source["raw_r2_key"] = raw_r2_key + if sha is not None: + source["source_sha256"] = sha + fact: dict[str, object] = { + "aggregate_fact_key": f"ledger.aggregate_fact.v2:{source_record_id}@{period}", + "lineage": {"source_record_id": source_record_id}, + "period": {"type": "tax_year", "value": period}, + "source": source, + } + if assertion is not None: + fact["assertion"] = assertion + return fact + + +def _spec(name: str, value: float = 1.0, **metadata: str) -> TargetSpec: + return TargetSpec( + name=name, + entity="tax_unit", + value=value, + measure="tip_income", + period=2024, + source="test", + family="irs_soi", + metadata=metadata, + ) + + +def _entry(package_id: str, data_year: int, *stamps: int, sha: str = "s"): + return RestampedSourcePackage( + package_id, data_year, frozenset(stamps), "f.xlsx", sha, "reason" + ) + + +def test_fact_artifact_year_reads_the_raw_key_package_and_year() -> None: + assert fact_artifact_year( + _fact("x", period=2023, raw_r2_key=_raw_key(_W2, 2020)) + ) == (_W2, 2020) + for key in ( + None, + "", + "raw/irs_soi", + f"raw/irs_soi/{_W2}/source_capture/{_OTHER_SHA}/f.xlsx", + f"raw/irs_soi/{_W2}/20/{_OTHER_SHA}/f.xlsx", + f"staged/irs_soi/{_W2}/2020/{_OTHER_SHA}/f.xlsx", + f"raw/irs_soi//2020/{_OTHER_SHA}/f.xlsx", + ): + assert fact_artifact_year(_fact("x", period=2023, raw_r2_key=key)) is None + + +def test_detect_restamped_facts_flags_only_observations_stamped_after_their_data() -> ( + None +): + facts = [ + _fact("restamp", period=2023, raw_r2_key=_raw_key(_W2, 2020)), + _fact("legacy", period=2023, raw_r2_key=_raw_key(_W2, 2020), assertion=None), + _fact("same_year", period=2020, raw_r2_key=_raw_key(_W2, 2020)), + # A 2024 release carrying cy2023 rows is the ordinary direction. + _fact("later_release", period=2023, raw_r2_key=_raw_key("bea-nipa", 2024)), + # A publisher's projection of a later year is not a restamp. + _fact( + "projection", + period=2027, + raw_r2_key=_raw_key("jct-obbba", 2025), + assertion="source_projection", + ), + _fact("no_key", period=2023, raw_r2_key=None), + _fact("month_label", period="2024-12", raw_r2_key=_raw_key("cms", 2026)), + ] + detected = detect_restamped_facts(facts) + assert [row[0]["lineage"]["source_record_id"] for row in detected] == [ + "restamp", + "legacy", + ] + assert {row[1:] for row in detected} == {(_W2, 2020, 2023)} + + +def test_the_content_rule_detects_a_registered_file_under_any_key_shape() -> None: + # A Chronicle key-layout change (for example a country segment) must not + # hide a registered restamp: the pinned file's digest still names it. + moved_key = f"raw/us/irs_soi/{_W2}/2020/{_W2_SHA}/20in04w2all.xlsx" + detected = detect_restamped_facts( + [ + _fact(_TIPS_2023, period=2023, raw_r2_key=moved_key, sha=_W2_SHA), + _fact("no_key", period=2023, raw_r2_key=None, sha=_W2_SHA), + # At its data year the registered file is stamped truthfully. + _fact("honest", period=2020, raw_r2_key=None, sha=_W2_SHA), + ] + ) + assert [(row[0]["lineage"]["source_record_id"], *row[1:]) for row in detected] == [ + (_TIPS_2023, _W2, 2020, 2023), + ("no_key", _W2, 2020, 2023), + ] + assert len(source_vintage_corrections([row[0] for row in detected])) == 2 + + +def test_a_reviewed_exemption_admits_a_truthful_later_observation() -> None: + # BEA's 2024-keyed SAINC.zip carries a 2025 column; once Chronicle builds + # it truthfully, the structural rule alone would flag it. + fact = _fact( + "bea_regional.cy2025.x", period=2025, raw_r2_key=_raw_key("bea-sainc", 2024) + ) + assert detect_restamped_facts([fact]) + exemptions = { + "bea-sainc": LaterPeriodObservationExemption( + "bea-sainc", frozenset({2025}), "multi-year release" + ) + } + assert not detect_restamped_facts([fact], exemptions=exemptions) + assert not source_vintage_corrections([fact], exemptions=exemptions) + # The exemption covers its reviewed periods only. + later = _fact( + "bea_regional.cy2026.x", period=2026, raw_r2_key=_raw_key("bea-sainc", 2024) + ) + assert detect_restamped_facts([later], exemptions=exemptions) + assert US_LATER_PERIOD_OBSERVATION_EXEMPTIONS == {} + + +def test_register_entries_describe_one_earlier_year_each() -> None: + assert set(US_RESTAMPED_SOURCE_PACKAGES) == { + "soi-w2-statistics-2020", + "soi-congressional-district-2022", + "soi-state-2022", + "soi-ira-roth-contributions-2022", + "soi-ira-traditional-contributions-2022", + } + digests = [entry.source_sha256 for entry in US_RESTAMPED_SOURCE_PACKAGES.values()] + assert len(set(digests)) == len(digests) + for package_id, entry in US_RESTAMPED_SOURCE_PACKAGES.items(): + assert entry.package_id == package_id + assert entry.stamped_periods + assert all(stamp > entry.data_year for stamp in entry.stamped_periods) + # IRS SOI file names lead with the two-digit tax year (20in04w2all). + assert int(entry.source_file[:2]) == entry.data_year % 100 + assert package_id.endswith(str(entry.data_year)) + assert len(entry.source_sha256) == 64 + assert entry.reason + + +def test_corrections_map_each_registered_restamp_to_its_data_year() -> None: + corrections = source_vintage_corrections( + [ + _fact(_TIPS_2023, period=2023, raw_r2_key=_raw_key(_W2, 2020)), + _fact( + "irs_soi.ty2020.form_w2_social_security_tips.x.amount", + period=2020, + raw_r2_key=_raw_key(_W2, 2020), + ), + ] + ) + assert dict(corrections) == { + _TIPS_2023: SourceVintageCorrection( + source_record_id=_TIPS_2023, + package_id=_W2, + stamped_year=2023, + data_year=2020, + fact_key=f"ledger.aggregate_fact.v2:{_TIPS_2023}@2023", + ) + } + + +@pytest.mark.parametrize( + ("package_id", "artifact_year", "period", "reason"), + [ + ("soi-unreviewed-2021", 2021, 2023, "no register entry"), + (_W2, 2020, 2024, r"register reviews \[2023\]"), + (_W2, 2019, 2023, "register data year 2020"), + ], +) +def test_an_unreviewed_restamp_is_refused( + package_id: str, artifact_year: int, period: int, reason: str +) -> None: + with pytest.raises(UnreviewedRestampError, match=reason) as raised: + source_vintage_corrections( + [_fact("x", period=period, raw_r2_key=_raw_key(package_id, artifact_year))] + ) + assert len(raised.value.problems) == 1 + + +def test_a_registered_file_under_a_key_naming_another_year_is_refused() -> None: + fact = _fact(_TIPS_2023, period=2023, raw_r2_key=_raw_key(_W2, 2021), sha=_W2_SHA) + with pytest.raises(UnreviewedRestampError, match="register data year 2020"): + source_vintage_corrections([fact]) + + +def test_one_record_with_two_different_corrections_is_refused() -> None: + register = {"a": _entry("a", 2020, 2023, 2024)} + with pytest.raises(ValueError, match="two corrections"): + source_vintage_corrections( + [ + _fact("x", period=2023, raw_r2_key=_raw_key("a", 2020)), + _fact("x", period=2024, raw_r2_key=_raw_key("a", 2020)), + ], + register=register, + ) + + +def _chain_fact(year: int) -> dict[str, object]: + return { + "lineage": { + "source_record_id": f"irs_soi.ty{year}.table_1_4.all.wages_salaries_amount" + }, + "period": {"type": "tax_year", "value": year}, + "value": 1e13, + "geography": {"level": "country"}, + "layout": { + "record_set_id": f"irs_soi.ty{year}.table_1_4", + "groupby_value_id": "all", + }, + "observed_measure": { + "source_name": "irs_soi", + "source_measure_id": "wages_salaries_amount", + }, + } + + +def test_a_restamped_fact_in_an_aging_chain_index_is_refused() -> None: + # A pinned TY2022 Table 1.4 stamped 2023 would stand in for the TY2023 + # wages level in every chained factor that pivots on 2023. + chain = [_chain_fact(2020), _chain_fact(2023)] + restamped_id = "irs_soi.ty2023.table_1_4.all.wages_salaries_amount" + correction = SourceVintageCorrection(restamped_id, "soi-t14-2022", 2023, 2022) + with pytest.raises(RestampedAgingIndexError, match=restamped_id): + check_restamps_stay_out_of_aging_indexes(chain, {restamped_id: correction}) + check_restamps_stay_out_of_aging_indexes(chain, {_TIPS_2023: _CORRECTION}) + check_restamps_stay_out_of_aging_indexes(chain, {}) + + +def test_a_restamped_fact_in_the_cbo_projection_index_is_refused() -> None: + projection_id = ( + "cbo.revenue_projection.ty2023.income_by_source.wages_and_salaries." + "projected_amount" + ) + projection = { + "assertion": "source_projection", + "lineage": {"source_record_id": projection_id}, + "period": {"type": "tax_year", "value": 2023}, + "value": 1e13, + "layout": { + "record_set_id": "cbo.revenue_projection.ty2023.income_by_source", + "groupby_dimension": "cbo.income_source", + "groupby_value_id": "wages_and_salaries", + }, + "observed_measure": { + "source_name": "cbo", + "source_measure_id": "projected_amount", + }, + } + correction = SourceVintageCorrection(projection_id, "cbo-2026-02", 2023, 2022) + with pytest.raises(RestampedAgingIndexError, match="cbo.revenue_projection"): + check_restamps_stay_out_of_aging_indexes( + [projection], {projection_id: correction} + ) + + +_CORRECTION = SourceVintageCorrection( + _TIPS_2023, _W2, 2023, 2020, fact_key="ledger.aggregate_fact.v2:tips" +) + + +def test_apply_moves_only_the_backing_facts_source_period() -> None: + registry = TargetRegistry( + [ + _spec( + "restamped", + 28.0, + ledger_source_record_id=_TIPS_2023, + ledger_fact_period="2023", + source_period="2023", + ), + _spec( + "other", + 5.0, + ledger_source_record_id="irs_soi.ty2023.table_1_4.all.x", + ledger_fact_period="2023", + source_period="2023", + ), + ], + country="us", + ) + corrected = { + spec.name: spec + for spec in apply_source_vintage_corrections( + registry, {_TIPS_2023: _CORRECTION} + ).specs + } + restamped = corrected["restamped"] + assert restamped.value == 28.0 + assert restamped.metadata["source_period"] == "2020" + assert restamped.metadata["ledger_fact_period"] == "2023" + assert restamped.metadata["source_vintage_stamped_period"] == "2023" + assert restamped.metadata["source_vintage_correction"] == ( + "soi-w2-statistics-2020: stamped 2023, data year 2020" + ) + assert corrected["other"] == registry.specs[1] + + +def test_apply_refuses_a_backed_spec_compared_at_another_period() -> None: + # A fiscal-year fact is compared at its coverage start year, which can + # differ from the stamp the correction was made for; fail closed. + spec = _spec( + "fiscal", + ledger_source_record_id=_TIPS_2023, + ledger_fact_period="2022", + source_period="2023", + ) + with pytest.raises(ValueError, match="not its stamp"): + apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), {_TIPS_2023: _CORRECTION} + ) + + +def test_apply_moves_a_rebased_specs_control_period_to_the_controls_data_year() -> None: + # The pinned feed's case while the capital-gains control is chosen by + # period: Historic Table 2 counts rebased onto the congressional-district + # US row. microcosm#1036 chooses the control by concept, which never picks + # that row; the branch still covers any restamped control. + control_id = ( + "irs_soi.ty2023.congressional_district_2022.all_returns.us." + "net_capital_gains_returns" + ) + control = SourceVintageCorrection( + control_id, "soi-congressional-district-2022", 2023, 2022 + ) + spec = _spec( + "irs_soi.ty2022.historic_table_2.state_broad.ca.all.net_capital_gains_returns", + 3_774_052.0, + ledger_source_record_id=( + "irs_soi.ty2022.historic_table_2.state_broad.ca.all." + "net_capital_gains_returns" + ), + ledger_fact_period="2022", + source_period="2022", + uprating_factor="0.97964474977721", + uprating_from_period="2022", + uprating_to_period="2023", + uprating_index_source_period="2023", + uprating_index_source_record_id=control_id, + ) + (corrected,) = apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), {control_id: control} + ).specs + assert corrected.value == spec.value + assert corrected.metadata["uprating_factor"] == "0.97964474977721" + assert corrected.metadata["uprating_to_period"] == "2022" + assert corrected.metadata["uprating_index_source_period"] == "2022" + assert corrected.metadata["uprating_index_source_vintage_stamped_period"] == "2023" + assert corrected.metadata["source_period"] == "2022" + + +_CD = "soi-congressional-district-2022" +_CD_RECORD_SET = "irs_soi.ty2023.congressional_district_2022.all_returns" +_CD_NJ_AMOUNT = f"{_CD_RECORD_SET}.nj_total.net_capital_gains_amount" +_CD_US_AMOUNT = f"{_CD_RECORD_SET}.us.net_capital_gains_amount" +_T14_AMOUNT = "irs_soi.ty2023.table_1_4.all.net_capital_gains_amount" +_CD_CORRECTIONS = { + record_id: SourceVintageCorrection(record_id, _CD, 2023, 2022) + for record_id in (_CD_NJ_AMOUNT, _CD_US_AMOUNT) +} + + +def _cd_share_spec(**overrides: str) -> TargetSpec: + """A congressional-district row rebased as a share of the same package's + US row times the Table 1.4 control, as microcosm#1040 compiles it. The + rebase runs before the correction, so it reads the stamp, 2023.""" + metadata = { + "ledger_source_record_id": _CD_NJ_AMOUNT, + "ledger_fact_period": "2023", + "source_period": "2023", + "uprating_factor": "0.834893818418", + "uprating_from_period": "2023", + "uprating_to_period": "2023", + "uprating_index_source_period": "2023", + "uprating_index_source_record_id": _T14_AMOUNT, + "soi_share_total_source_record_id": _CD_US_AMOUNT, + } + metadata.update(overrides) + return _spec(_CD_NJ_AMOUNT, 38_463_637_000.0, **metadata) + + +def test_apply_admits_a_share_of_a_restamped_total_of_the_same_package() -> None: + """Row and total come from one restamped file, so the stamp cancels in the + share; the level is the truthful Table 1.4 control's. Only the share's own + period moves to the data year. ``uprating_to_period``, where aging starts, + stays at the control's 2023: moved to 2022 it would age the control's + TY2022-to-TY2023 change a second time (x0.761 for net capital gains).""" + spec = _cd_share_spec() + (corrected,) = apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), _CD_CORRECTIONS + ).specs + assert corrected.value == spec.value + assert corrected.metadata["uprating_factor"] == "0.834893818418" + assert corrected.metadata["source_period"] == "2022" + assert corrected.metadata["source_vintage_stamped_period"] == "2023" + assert corrected.metadata["uprating_from_period"] == "2022" + assert corrected.metadata["uprating_from_period_vintage_stamped_period"] == "2023" + assert corrected.metadata["uprating_to_period"] == "2023" + assert corrected.metadata["uprating_index_source_period"] == "2023" + assert "uprating_index_source_vintage_correction" not in corrected.metadata + assert corrected.metadata["ledger_fact_period"] == "2023" + again = apply_source_vintage_corrections( + TargetRegistry([corrected], country="us"), _CD_CORRECTIONS + ) + assert again.specs == (corrected,) + + +def test_an_admitted_share_ages_exactly_as_its_truthfully_stamped_twin() -> None: + """Differential: one congressional-district share compiled from the + package stamped ty2023 (then corrected) and from the package stamped + truthfully at 2022 (nothing to correct) ages to the same value, from the + control's 2023 period on the direct CBO 2024/2023 ratio, and passes the + period contract. Starting it at the data year instead chains the Table 1.4 + TY2022-to-TY2023 change onto a level that already carries it.""" + from microcosm.build.us_runtime.target_aging import ( + age_us_dollar_targets, + find_period_contract_violations, + ) + from test_support.microcosm_build.us_fiscal_targets import ( + _cbo_income_source_projection_fact, + _dynamic_ledger_fact, + ) + + aging_facts = ( + _cbo_income_source_projection_fact(2023, "net_capital_gain", value=981.4e9), + _cbo_income_source_projection_fact(2024, "net_capital_gain", value=1290.9e9), + *( + _dynamic_ledger_fact( + source_record_id=f"irs_soi.ty{year}.table_1_4.all.net_capital_gains_amount", + source_name="irs_soi", + measure_id="net_capital_gains_amount", + value=value, + period_value=year, + layout_record_set_id=f"irs_soi.ty{year}.table_1_4", + ) + for year, value in ((2022, 1_400.0e9), (2023, 1_065.2e9)) + ), + ) + dollars = {"measure_mode": "sum", "source_measure_id": "net_capital_gains_amount"} + stamped = _cd_share_spec(**dollars) + truthful_set = "irs_soi.ty2022.congressional_district_2022.all_returns" + truthful = _cd_share_spec( + **dollars, + ledger_source_record_id=f"{truthful_set}.nj_total.net_capital_gains_amount", + ledger_fact_period="2022", + source_period="2022", + uprating_from_period="2022", + soi_share_total_source_record_id=f"{truthful_set}.us.net_capital_gains_amount", + ) + + def aged(spec, corrections): + registry = apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), corrections + ) + registry = age_us_dollar_targets(registry, aging_facts, target_period=2024) + assert not find_period_contract_violations(registry, target_period=2024) + (result,) = registry.specs + return result + + from_stamp = aged(stamped, _CD_CORRECTIONS) + from_truth = aged(truthful, {}) + ratio = 1290.9e9 / 981.4e9 + for spec in (from_stamp, from_truth): + assert spec.metadata["source_period"] == "2023" + assert spec.metadata["aging_factor_source"] == ( + "cbo.revenue_projection.ty2024.income_by_source.net_capital_gain." + "projected_amount" + ) + assert float(spec.metadata["aging_factor"]) == pytest.approx(ratio, rel=1e-12) + assert ( + from_stamp.value + == from_truth.value + == pytest.approx(38_463_637_000.0 * ratio, rel=1e-12) + ) + + wrong = aged( + dataclasses.replace( + truthful, + metadata={**truthful.metadata, "uprating_to_period": "2022"}, + ), + {}, + ) + assert wrong.value / from_truth.value == pytest.approx(1_065.2 / 1_400.0, rel=1e-12) + + +@pytest.mark.parametrize( + ("overrides", "corrections"), + [ + pytest.param( + {"soi_share_total_source_record_id": None}, + _CD_CORRECTIONS, + id="no-share-total", + ), + pytest.param( + { + "soi_share_total_source_record_id": ( + "irs_soi.ty2022.historic_table_2.us.all.net_capital_gains_amount" + ) + }, + _CD_CORRECTIONS, + id="truthful-share-total", + ), + pytest.param( + {}, + { + **_CD_CORRECTIONS, + _CD_US_AMOUNT: SourceVintageCorrection( + _CD_US_AMOUNT, "soi-state-2022", 2023, 2022 + ), + }, + id="share-total-from-another-package", + ), + pytest.param( + {}, + { + **_CD_CORRECTIONS, + _CD_US_AMOUNT: SourceVintageCorrection(_CD_US_AMOUNT, _CD, 2024, 2022), + }, + id="share-total-at-another-stamp", + ), + pytest.param( + {}, + { + **_CD_CORRECTIONS, + _CD_US_AMOUNT: SourceVintageCorrection(_CD_US_AMOUNT, _CD, 2023, 2021), + }, + id="share-total-of-another-data-year", + ), + pytest.param( + {"uprating_from_period": "2021"}, + _CD_CORRECTIONS, + id="share-read-at-another-period", + ), + pytest.param( + {"uprating_from_period": None}, + _CD_CORRECTIONS, + id="no-uprating-from-period", + ), + ], +) +def test_apply_refuses_a_rebased_restamp_that_is_not_a_same_package_share( + overrides: dict[str, str | None], + corrections: dict[str, SourceVintageCorrection], +) -> None: + """A rebased restamp is admitted only as a share of a restamped total of + its own package, stamp and data year, read at the stamp or the data year. + Any other rebase (a missing or truthful denominator, a mixed-vintage share, + another reading period) mixes vintages the correction cannot vouch for.""" + spec = _cd_share_spec() + metadata = dict(spec.metadata) + for key, value in overrides.items(): + if value is None: + metadata.pop(key) + else: + metadata[key] = value + spec = dataclasses.replace(spec, metadata=metadata) + with pytest.raises(ValueError, match="was rebased, but not as a share"): + apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), corrections + ) + + +def test_apply_refuses_a_restamped_fact_that_was_rebased_without_a_share() -> None: + spec = _spec( + "restamped", + ledger_source_record_id=_TIPS_2023, + ledger_fact_period="2023", + source_period="2023", + uprating_factor="1.1", + uprating_from_period="2023", + uprating_to_period="2023", + ) + with pytest.raises(ValueError, match="was rebased"): + apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), {_TIPS_2023: _CORRECTION} + ) + + +def test_apply_refuses_a_pooled_uprating_index_with_a_restamped_member() -> None: + spec = _spec( + "pooled", + ledger_source_record_id="irs_soi.ty2022.table_2_5.x", + ledger_fact_period="2022", + uprating_index_source_record_ids=f"irs_soi.ty2024.a,{_TIPS_2023}", + ) + with pytest.raises(ValueError, match="multi-source index"): + apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), {_TIPS_2023: _CORRECTION} + ) + + +def test_apply_refuses_a_multi_fact_spec_with_a_restamped_member() -> None: + # The spec's source period is its representative's; a restamped member + # that is not the representative would go uncorrected. + spec = _spec( + "summed", + ledger_source_record_id="irs_soi.ty2023.representative", + ledger_fact_period="2023", + ledger_member_fact_keys=json.dumps( + ["ledger.aggregate_fact.v2:representative", _CORRECTION.fact_key] + ), + ) + with pytest.raises(ValueError, match="aggregates several facts"): + apply_source_vintage_corrections( + TargetRegistry([spec], country="us"), {_TIPS_2023: _CORRECTION} + ) + + +def _vintage(correction: SourceVintageCorrection) -> tuple[str, int, int]: + return correction.package_id, correction.stamped_year, correction.data_year + + +def test_correction_invariants_hold_for_generated_registries() -> None: + """For any registry and any corrections, the correction refuses exactly + when a restamped spec was rebased other than as a share of a restamped + total of its own package, stamp and data year, read at the stamp or the + data year. Otherwise: values, names, periods and order never move; the + correction is idempotent; a spec changes if and only if it is backed by, + or rebased onto, a corrected fact at its stamped period; every moved + period lands on that fact's data year; ``uprating_from_period`` moves only + for an admitted share and ``uprating_to_period`` only for a restamped + control. Hypothesis is a workspace dependency; the wheels job installs no + test extras, so it skips there.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + record_ids = [f"irs_soi.ty2023.r{i}" for i in range(5)] + years = st.integers(2015, 2026) + # A few fixed vintages make same-package shares and near misses common; + # the free draw keeps any package, stamp and data year in play. + vintages = st.one_of( + # The last three each differ from the first in exactly one of + # package, stamp and data year. + st.sampled_from( + [ + ("pkg_a", 2023, 2022), + ("pkg_a", 2024, 2022), + ("pkg_b", 2023, 2022), + ("pkg_a", 2023, 2020), + ] + ), + st.tuples(st.sampled_from(["pkg_a", "pkg_b"]), years).flatmap( + lambda pair: st.tuples( + st.just(pair[0]), st.just(pair[1]), st.integers(2010, pair[1] - 1) + ) + ), + ) + + @st.composite + def cases(draw, mode): + # mode "free" draws shares at random, so most calls with a rebased + # restamp refuse. "well_formed" gives each rebased restamp a total of + # its own vintage, so the call is admitted and the admitted-share + # invariants get exercised. "near_miss" gives it exactly one defect, so + # each comparison the admission makes is tested alone. + corrections = {} + # A small pool per case makes the free mode's totals often match the + # row's vintage or miss it narrowly, and keeps mixed packages, stamps + # and data years among the corrections. + pool = draw(st.lists(vintages, min_size=1, max_size=3)) + for record_id in draw(st.sets(st.sampled_from(record_ids))): + package_id, stamped, data = draw(st.sampled_from(pool)) + corrections[record_id] = SourceVintageCorrection( + record_id, package_id, stamped, data + ) + + def period_near(record_id): + # Bias toward the correction's own stamp and data year, which the + # branches under test compare against. + correction = corrections.get(record_id) + if correction is None: + return draw(years) + return draw( + st.one_of( + years, + st.sampled_from([correction.stamped_year, correction.data_year]), + ) + ) + + def share(record_id): + # The share keys of a rebase. + correction = corrections.get(record_id) + if mode == "free" or correction is None: + keys = {} + if draw(st.integers(0, 4)): + keys["uprating_from_period"] = str(period_near(record_id)) + if draw(st.integers(0, 4)): + keys["soi_share_total_source_record_id"] = draw( + st.sampled_from( + sorted({*record_ids, *corrections}) + + ["irs_soi.ty2023.truthful"] + ) + ) + return keys + # A total of its own, restamped at the row's vintage, read at the + # stamp or the data year (well-formed). A near miss changes exactly + # one of these: the total's package, stamp or data year, or the + # reading period (another year, or none). + package_id, stamped, data = _vintage(correction) + reading = draw( + st.sampled_from([correction.stamped_year, correction.data_year]) + ) + if mode == "near_miss": + component = draw( + st.sampled_from(["package", "stamp", "data", "reading"]) + ) + if component == "package": + package_id = "pkg_b" if package_id == "pkg_a" else "pkg_a" + elif component == "stamp": + stamped += 1 + elif component == "data": + data -= 1 + else: + reading = draw( + st.sampled_from( + [ + None, + correction.data_year - 1, + correction.stamped_year + 1, + ] + ) + ) + total_id = f"irs_soi.ty2023.total{len(corrections)}" + corrections[total_id] = SourceVintageCorrection( + total_id, package_id, stamped, data + ) + keys = {"soi_share_total_source_record_id": total_id} + if reading is not None: + keys["uprating_from_period"] = str(reading) + return keys + + specs = [] + for index in range(draw(st.integers(0, 8))): + record_id = draw(st.sampled_from(record_ids)) + # A backed spec is always compared at its fact's stamp; the + # mismatch case is refused (tested above). + fact_period = ( + corrections[record_id].stamped_year + if record_id in corrections + else draw(years) + ) + metadata = { + "ledger_source_record_id": record_id, + "ledger_fact_period": str(fact_period), + "source_period": str(draw(years)), + } + if draw(st.booleans()): + control_id = draw(st.sampled_from(record_ids)) + metadata["uprating_index_source_record_id"] = control_id + metadata["uprating_index_source_period"] = str(period_near(control_id)) + metadata["uprating_to_period"] = metadata[ + "uprating_index_source_period" + ] + if draw(st.booleans()): + metadata["uprating_factor"] = "0.5" + metadata.update(share(record_id)) + specs.append( + _spec( + f"spec{index}", + draw(st.floats(0, 1e12, allow_nan=False)), + **metadata, + ) + ) + return specs, corrections + + def backed(spec, corrections): + return spec.metadata["ledger_source_record_id"] in corrections + + def rebased(spec, corrections): + correction = corrections.get( + spec.metadata.get("uprating_index_source_record_id", "") + ) + return correction is not None and str(correction.stamped_year) == ( + spec.metadata.get("uprating_index_source_period") + ) + + def admitted_share(spec, corrections): + backing = corrections[spec.metadata["ledger_source_record_id"]] + total = corrections.get( + spec.metadata.get("soi_share_total_source_record_id", "") + ) + return ( + total is not None + and _vintage(total) == _vintage(backing) + and spec.metadata.get("uprating_from_period") + in (str(backing.stamped_year), str(backing.data_year)) + ) + + def refused(spec, corrections): + return ( + backed(spec, corrections) + and "uprating_factor" in spec.metadata + and not admitted_share(spec, corrections) + ) + + @settings(max_examples=500, deadline=None) + @given(st.sampled_from(["free", "well_formed", "near_miss"]).flatmap(cases)) + def check(case): + specs, corrections = case + registry = TargetRegistry(specs, country="us") + if any(refused(spec, corrections) for spec in specs): + with pytest.raises(ValueError, match="was rebased, but not as a share"): + apply_source_vintage_corrections(registry, corrections) + return + once = apply_source_vintage_corrections(registry, corrections) + twice = apply_source_vintage_corrections(once, corrections) + assert once.specs == twice.specs + assert [spec.name for spec in once.specs] == [spec.name for spec in specs] + for before, after in zip(specs, once.specs, strict=True): + assert after.value == before.value + assert after.period == before.period + assert ( + after.metadata["ledger_fact_period"] + == (before.metadata["ledger_fact_period"]) + ) + is_backed = backed(before, corrections) + is_rebased = rebased(before, corrections) + assert (after != before) == (is_backed or is_rebased) + if is_backed: + correction = corrections[before.metadata["ledger_source_record_id"]] + assert after.metadata["source_period"] == str(correction.data_year) + else: + assert ( + after.metadata["source_period"] + == (before.metadata["source_period"]) + ) + if is_backed and "uprating_factor" in before.metadata: + assert after.metadata["uprating_from_period"] == str( + correction.data_year + ) + else: + assert after.metadata.get("uprating_from_period") == ( + before.metadata.get("uprating_from_period") + ) + if is_rebased: + correction = corrections[ + before.metadata["uprating_index_source_record_id"] + ] + assert after.metadata["uprating_to_period"] == str(correction.data_year) + else: + assert after.metadata.get("uprating_to_period") == ( + before.metadata.get("uprating_to_period") + ) + + check() + + +def test_detection_matches_its_two_rules_for_generated_facts() -> None: + """A fact is detected exactly when it is an observation (or carries no + assertion) and either its digest is a registered file stamped after that + file's data year, or its raw key parses to a year before its period.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + @settings(max_examples=400, deadline=None) + @given( + artifact_year=st.integers(2000, 2030), + period=st.one_of( + st.integers(2000, 2030), + st.integers(2000, 2030).map(lambda year: f"{year}-12"), + st.integers(2000, 2030).map(lambda year: f"ty{year}"), + ), + assertion=st.sampled_from([None, "observation", "source_projection"]), + keyed=st.booleans(), + registered_file=st.booleans(), + ) + def check(artifact_year, period, assertion, keyed, registered_file): + fact = _fact( + "x", + period=period, + raw_r2_key=_raw_key("some-package", artifact_year) if keyed else None, + assertion=assertion, + sha=_W2_SHA if registered_file else None, + ) + period_year = int(str(period).removeprefix("ty")[:4]) + observation = assertion != "source_projection" + by_content = registered_file and period_year > 2020 + by_key = keyed and artifact_year < period_year + assert bool(detect_restamped_facts([fact])) == ( + observation and (by_content or by_key) + ) + + check() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 44664623b6..aed0807d45 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -426,6 +426,9 @@ "snap_take_up.py", "source_coverage.py", "source_runtime.py", + # Restamped-fact period correction over compiled target specs + # (chronicle#117); reads Ledger facts only, no population treatment. + "source_vintage.py", "sources.py", "spine_agreement.py", "spine_assembly.py", diff --git a/test_support/microcosm_build/us_fiscal_targets.py b/test_support/microcosm_build/us_fiscal_targets.py index a76de7b803..776628d0d8 100644 --- a/test_support/microcosm_build/us_fiscal_targets.py +++ b/test_support/microcosm_build/us_fiscal_targets.py @@ -18,6 +18,7 @@ US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, US_FISCAL_TARGET_EXCLUSION_VINTAGE_BYPASSES, US_FISCAL_TARGET_REFERENCES, + US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS, US_FISCAL_TARGET_SUPPORT_EXCLUSIONS, US_JCT_TAX_EXPENDITURE_REFORMS, US_NONNEGATIVE_SOURCE_OUTPUTS, @@ -194,12 +195,37 @@ def _w2_tips_return_count_fact(tax_year: int) -> dict[str, object]: ) -def _four_rule_synthetic_feed(monkeypatch): +def _cd_column_fact( + measure_id: str, + source_column_id: str, + *, + groupby_value_id: str = "us", + geography_level: str = "country", + geography_id: str = "0100000US", + value: float = 1_000_000.0, +) -> dict[str, object]: + """A congressional-district fact read from IRS column ``source_column_id``, + as every pinned-feed fact records in ``layout.source_column_id``.""" + fact = _soi_congressional_district_fact( + measure_id, + value, + groupby_value_id=groupby_value_id, + geography_level=geography_level, + geography_id=geography_id, + ) + fact["layout"]["source_column_id"] = source_column_id + return fact + + +def _exclusion_rule_synthetic_feed(monkeypatch): """Synthetic facts that exercise every receipt rule, and each rule's ids. The register holds no bypass since d179, so this reviews a synthetic one: a taxable-interest cell excluded at ty2023 with its ty2020 vintage - allowlisted. + allowlisted. The congressional-district SALT facts read the income-tax + column N18425/A18425 that the pinned feed labels as the limited deduction, + and one reads N18460, the column a corrected package would read, which + must compile. """ tanf = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." @@ -251,8 +277,30 @@ def _four_rule_synthetic_feed(monkeypatch): ) ), ] + salt_excluded = [ + _cd_column_fact("limited_state_local_taxes_returns", "N18425"), + _cd_column_fact("limited_state_local_taxes_amount", "A18425"), + _cd_column_fact( + "limited_state_local_taxes_amount", + "A18425", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ), + ] + salt_kept = _cd_column_fact( + "limited_state_local_taxes_returns", + "N18460", + groupby_value_id="hi_total", + geography_level="state", + geography_id="0400000US15", + ) + facts = [*facts, *salt_excluded, salt_kept] expected = { "reviewed_exclusion": sorted([tanf, interest_excluded]), + "source_column_concept_exclusion": sorted( + fact["lineage"]["source_record_id"] for fact in salt_excluded + ), "all_vintage_reviewed_exclusion": sorted( [ *( @@ -289,26 +337,33 @@ def _load_repo_tool(name: str): @pytest.fixture(scope="module") -def pinned_feed_national_state_surface(): - """Compile the pinned feed as the release does: compile, Medicaid - substitutions, then ``--target-surface national_state``.""" +def pinned_feed_facts(): + """The pinned Chronicle feed's facts, digest-checked against the pin.""" feed_path = _load_repo_tool("build_us_target_parity_manifest").DEFAULT_FEED_PATH if not feed_path.exists(): pytest.skip(f"pinned feed not present at {feed_path}") from microcosm.build.ledger_artifact import load_ledger_consumer_artifact + from microcosm.build.us_runtime.chronicle_feed import load_us_chronicle_feed + + return load_ledger_consumer_artifact( + feed_path, + expected_facts_sha256=load_us_chronicle_feed().facts_sha256, + expected_manifest_sha256=None, + ).facts + + +@pytest.fixture(scope="module") +def pinned_feed_national_state_surface(pinned_feed_facts): + """Compile the pinned feed as the release does: compile, Medicaid + substitutions, then ``--target-surface national_state``.""" from microcosm.build.us_runtime import ( apply_us_medicaid_enrollment_substitutions, default_congressional_district_vintage_crosswalk_path, load_congressional_district_vintage_crosswalk, ) - from microcosm.build.us_runtime.chronicle_feed import load_us_chronicle_feed from microcosm.calibrate import TargetRegistry - facts = load_ledger_consumer_artifact( - feed_path, - expected_facts_sha256=load_us_chronicle_feed().facts_sha256, - expected_manifest_sha256=None, - ).facts + facts = pinned_feed_facts crosswalk = load_congressional_district_vintage_crosswalk( default_congressional_district_vintage_crosswalk_path() ) diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index e0d212a6e0..6d2244b120 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -125,6 +125,7 @@ SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, SOI_VARIABLE_MAP, US_FISCAL_TARGET_COVERAGE_REQUIREMENTS, + US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS, US_FISCAL_TARGET_SUPPORT_EXCLUSIONS, US_JCT_TAX_EXPENDITURE_REFORMS, US_MEDICAID_ENROLLMENT_TARGET_TABLE, @@ -19640,6 +19641,16 @@ def _certify_us_build( US_FISCAL_TARGET_SUPPORT_EXCLUSIONS.items() ) ] + coverage["fiscal_target_source_column_exclusions"] = [ + { + "measure_id": measure_id, + "source_column_id": source_column_id, + "reason": reason, + } + for (measure_id, source_column_id), reason in sorted( + US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS.items() + ) + ] coverage[US_FISCAL_TARGET_EXCLUSION_RECEIPT_KEY] = fiscal_target_exclusion_receipt if fsa_target_receipt is not None: coverage[US_FSA_STUDENT_LOAN_TARGET_RECEIPT_KEY] = fsa_target_receipt diff --git a/tools/build_us_target_parity_manifest.py b/tools/build_us_target_parity_manifest.py index f9bd2da00e..d7c200255b 100644 --- a/tools/build_us_target_parity_manifest.py +++ b/tools/build_us_target_parity_manifest.py @@ -154,7 +154,7 @@ def _fence(origin: str, purpose: str, verdict_basis: str) -> dict[str, str]: "this manifest describes, turns none of them into a target.", "compile_us_fiscal_target_registry(age_targets=True) + " "apply_us_medicaid_enrollment_substitutions on the 41b2fb2b feed: " - "33,250 targets, none from the feed's 461 ed_fsa facts; sample fact " + "31,748 targets, none from the feed's 461 ed_fsa facts; sample fact " "ed_fsa.portfolio_by_location.2026_03_31.ar.borrowers", _fence( origin=( @@ -659,7 +659,10 @@ def _fence(origin: str, purpose: str, verdict_basis: str) -> dict[str, str]: "artifact record count changes only L0, never target membership. " "There is no local-versus-national surface. " "Congressional-district rows inform shape while national and state " - "actuals retain control ownership." + "actuals retain control ownership. Its capital-gains rows ship as shares " + "of its own US row scaled to the national Table 1.4 control, and that US " + "row retires (microcosm#1038); facts it reads from the wrong IRS column " + "are excluded (US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS)." ), } diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 90e1d057d5..74fc9f352c 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -50,8 +50,10 @@ STATE_CD_VINTAGE_RULE = "state_cd.historic_table_2_level_cd_file_shares.v1" #: District-file measures that read the wrong IRS column (microcosm#1038). -#: PR #1040 excludes the same columns in the compiler; until it lands this -#: register keeps them off the ``state_cd`` surface at both geographies. +#: The compiler's ``US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`` drops these +#: facts by (measure id, IRS column) before this surface sees them; this +#: register stays as a second fence on the ``state_cd`` surface, at both +#: geographies, and records the reason in the receipt. STATE_CD_DEFECTIVE_CD_FILE_MEASURES: Mapping[str, str] = { "limited_state_local_taxes_amount": ( "22incd.csv column A18425 is state and local income taxes (Schedule A "