From 22ea523955cb8d3e47c80b96c45ff8f745776c5a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 25 Sep 2026 18:10:00 -0400 Subject: [PATCH 01/30] Read restamped Chronicle facts at their data year before aging The pinned US Chronicle feed (c5e5bf8) stamps five packages' pinned files as ty2023: the TY2020 W-2 table and the TY2022 congressional-district, state and IRA tables, 26,893 facts (PolicyEngine/chronicle#117). Target aging started from the stamp, so the route-A W-2 Box 7 tips amount aged 2023->2024 on the direct CBO ratio ($28.28B) instead of 2020->2024 on the chained SOI wages bridge ($34.29B), and the full-surface congressional-district dollar targets aged one link short. source_vintage detects an observation fact whose raw_r2_key artifact year precedes its period, requires a reviewed US_RESTAMPED_SOURCE_PACKAGES entry for it (the compile refuses otherwise), and moves source_period, and uprating_to_period for specs rebased onto a restamped control, to the data year before aging. Values, names and vintage selection are unchanged. On the pinned feed national_state keeps 5,695 targets (registry 386fac439e77 -> a3547c5322da) and only the tips amount moves. Co-Authored-By: Claude Opus 5.5 --- ...us-restamped-source-vintage-aging.fixed.md | 1 + docs/us-chronicle-feed-repin.md | 68 +++ .../build/us_runtime/fiscal_targets.py | 20 +- .../build/us_runtime/source_vintage.py | 385 ++++++++++++++++ .../build/us_runtime/target_aging.py | 4 +- .../tests/test_us_fiscal_targets.py | 229 +++++++++- .../tests/test_us_source_vintage.py | 424 ++++++++++++++++++ 7 files changed, 1115 insertions(+), 16 deletions(-) create mode 100644 changelog.d/us-restamped-source-vintage-aging.fixed.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py create mode 100644 packages/microcosm-build/tests/test_us_source_vintage.py 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..0a2982862b --- /dev/null +++ b/changelog.d/us-restamped-source-vintage-aging.fixed.md @@ -0,0 +1 @@ +Read restamped Chronicle facts at their data year (PolicyEngine/chronicle#117). 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, state and IRA tables. The compile now detects an observation fact stamped later than its source artifact's year. It refuses the fact unless a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry matches, and otherwise ages it from the data year. On the pinned feed the `national_state` W-2 Box 7 tips amount target moves from $28.28B, aged from 2023, to $34.29B, chained from TY2020. That surface keeps 5,695 targets, and its registry moves from `386fac439e77` to `a3547c5322da`. On the full surface, 13,176 congressional-district-file dollar targets age from TY2022: AGI-default measures +3.05%, net capital gains -23.9%. diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index a983a3e46b..f400a74034 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -175,6 +175,74 @@ 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). + +| 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 evidence is in 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. The "W-2 Social +Security tips for 2023 (2)" cells listed under +[What moved and what did not](#what-moved-and-what-did-not) are two of +them. The previous pin carried the tips amount only at ty2020, so adding the +ty2023 row switched the tips target from aging on the chained SOI wages +bridge from 2020 to the direct CBO ratio from 2023. That aged it 17.5% too +low ($28.28B instead of $34.29B at 2024). + +The compile reads these facts at their data year +(`us_runtime/source_vintage.py`). An observation fact whose +`source.raw_r2_key` names an artifact year earlier than its period is a +restamp. Each one must match a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry, +or the compile refuses. For the matching specs, `source_period` becomes the +data year, and so does `uprating_to_period` when a spec is rebased onto a +restamped control. The stamp is kept in `source_vintage_stamped_period`. +Values, names and latest-vintage selection do not change; aging then starts +from the data year. On this feed: + +- `national_state` still has 5,695 targets, and the registry moves from + `386fac439e77` to `a3547c5322da`. One value moves: the W-2 Box 7 tips + amount, from $28,280,884,269 to $34,287,530,779. The 51 Historic Table 2 + net-capital-gains return counts rebased onto the congressional-district US + row, and the two `state_2022` counts, change metadata only; counts do not + age. +- On the full surface, the 13,176 congressional-district-file dollar targets + age from 2022. The AGI-default measures move by +3.05%, net capital gains + by -23.9%, qualified dividends by +8.4% and business income by -0.5%. + Before the correction those targets were off by the inverse of these moves: + -3.0%, +31.4%, -7.8% and +0.5%. +- The 401(k), Roth 401(k) and IRA rows compile no target. + +`test_pinned_feed_restamp_register_matches_the_feed` checks the register +against this feed in both directions. A re-pin on a Chronicle commit that +stops the restamp leaves entries that match nothing, and that 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). Two things need a decision first: + +- The Historic Table 2 capital-gains returns control. Today the CD US row + wins a same-period tie. Stamped truthfully, it would lose to Table 1.4 + ty2023, which counts a different return population, and 51 + `national_state` targets would fall 58.5%. +- `SOI_CONGRESSIONAL_DISTRICT_RECORD_SET_ID`, which names the `ty2023` record + set. + +One more mis-stamp runs the other way and is out of reach of the +artifact-year rule. `bea-regional-state-personal-income-components-2024` +reads the 2024 column of its CSV under a `cy2023` stamp (416 facts). No +target compiles from it; its families are parity-manifest exclusions. + ## The consumer artifact is refused at this commit `chronicle build-consumer-artifact` validates every row against 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 d29c4567f1..10e207c839 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 @@ -28,6 +28,10 @@ from microcosm.build.us_runtime.congressional_district_vintage import ( translate_congressional_district_facts_to_current_vintage, ) +from microcosm.build.us_runtime.source_vintage import ( + apply_source_vintage_corrections, + source_vintage_corrections, +) from microcosm.build.us_runtime.target_aging import ( age_us_dollar_targets, enforce_period_contract, @@ -1046,6 +1050,14 @@ def compile_us_fiscal_target_registry( "target_period": target_period, }, ) + # Restamped Chronicle facts (a pinned artifact labelled with the build + # year, PolicyEngine/chronicle#117) are read at their data year from here + # on: aging starts from it and the period contract checks it. Refuses a + # restamp that is not in the reviewed register. + registry = apply_source_vintage_corrections( + registry, + source_vintage_corrections(materialized_facts), + ) if age_targets: # Final nominal transform: age dollar amounts from their source period # to the build period on the fully within-surface-aligned registry @@ -3405,9 +3417,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..fec3d3dfae --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py @@ -0,0 +1,385 @@ +"""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 ``--year`` later +than the artifact year, it re-labels the pinned file's values as the build +year: the same cells, the same bytes, a later period +(PolicyEngine/chronicle#117). The US feed pinned at Chronicle ``c5e5bf8`` +carries five such packages, all built at 2023 by +``us/chronicle_feed_scope.json``. 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, and +a pinned file cannot describe a later year. Until the feed is re-pinned on a +Chronicle commit that stops the restamp, microcosm reads these facts at their +data year wherever a period drives a number. That covers the ``source_period`` +the aging model starts from (:mod:`~microcosm.build.us_runtime.target_aging`) +and the ``uprating_to_period`` a rebased spec inherits from a restamped +control. The values, the target names and the fact that wins latest-vintage +selection are unchanged. The correction moves only the period that aging and +the period contract read, and it records the stamped period next to it. + +Detection is structural. An observation fact whose ``source.raw_r2_key`` +(``raw/////``) names an +artifact year earlier than its own period cannot be a truthful stamp, because a +publication cannot describe a year after its own data year. Each detected +restamp must match a reviewed :data:`US_RESTAMPED_SOURCE_PACKAGES` entry, with +the same package, stamped period and data year, or the compile refuses. The +register is reviewed against the pinned feed +(``test_pinned_feed_restamp_register_matches_the_feed``). A re-pin that fixes +the stamp leaves an entry matching nothing, and that test then fails until the +entry is deleted. + +Out of reach of the structural rule: a package that reads a *later* column +than its stamped period. ``bea-regional-state-personal-income-components-2024`` +stamps CY2024 BEA state income as cy2023. Its raw key year (2024) is later than +its period, as for every legitimate multi-year release. Microcosm does not +compile those facts (they are parity-manifest ``reviewed_exclusion`` +families), so no entry is needed. The fix is Chronicle's, as a year-selecting +package. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, replace +from types import MappingProxyType + +from microcosm.build.us_runtime.target_aging import _period_year +from microcosm.calibrate import TargetRegistry, TargetSpec + +__all__ = [ + "US_RESTAMPED_SOURCE_PACKAGES", + "RestampedSourcePackage", + "SourceVintageCorrection", + "UnreviewedRestampError", + "apply_source_vintage_corrections", + "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 artifact describes. It must + equal the artifact year in ``raw_r2_key``. + stamped_periods: The periods the pinned feed stamps on it. + source_file: The pinned publisher file, for the reader. + reason: Why the stamp is wrong, with the evidence. + """ + + package_id: str + data_year: int + stamped_periods: frozenset[int] + source_file: str + reason: str + + +def _restamped( + package_id: str, + data_year: int, + source_file: 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, + reason=reason, + ) + + +# Reviewed against consumer_facts_us_c5e5bf8.jsonl (Chronicle c5e5bf8, sha256 +# b8543739...): every observation fact whose raw_r2_key artifact year precedes +# its period is one of these 26,893 facts. Each data year was confirmed from +# the file itself (title cell or content match), not from Chronicle labels. +US_RESTAMPED_SOURCE_PACKAGES: Mapping[str, RestampedSourcePackage] = MappingProxyType( + dict( + ( + _restamped( + "soi-w2-statistics-2020", + 2020, + "20in04w2all.xlsx", + "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. TY2020 is still the newest W-2 " + "table IRS publishes.", + ), + _restamped( + "soi-congressional-district-2022", + 2022, + "22incd.csv", + "IRS SOI congressional district data for tax year 2022, the " + "newest CD release. 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", + "IRS SOI Historic Table 2 US totals, titled 'Tax Year 2022'.", + ), + _restamped( + "soi-ira-roth-contributions-2022", + 2022, + "22in06ira.xlsx", + "IRS SOI IRA Table 6 (Roth contributions), titled 'Tax Year 2022'.", + ), + _restamped( + "soi-ira-traditional-contributions-2022", + 2022, + "22in05ira.xlsx", + "IRS SOI IRA Table 5 (traditional contributions), titled " + "'Tax Year 2022'.", + ), + ) + ) +) + + +@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 + + @property + def label(self) -> str: + return ( + f"{self.package_id}: stamped {self.stamped_year}, " + f"data year {self.data_year}" + ) + + +class UnreviewedRestampError(ValueError): + """An observation fact is stamped later than its artifact's year. + + 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, or fix the stamp in Chronicle + and re-pin. + """ + + def __init__(self, problems: tuple[str, ...]) -> None: + self.problems = problems + preview = "; ".join(problems[:5]) + suffix = "" if len(problems) <= 5 else f"; +{len(problems) - 5} more" + super().__init__( + f"{len(problems)} observation fact(s) carry a period later than " + "their source artifact's year without a matching reviewed " + f"US_RESTAMPED_SOURCE_PACKAGES entry: {preview}{suffix}" + ) + + +def fact_artifact_year(fact: object) -> tuple[str, int] | None: + """``(package_id, artifact_year)`` from a fact's ``source.raw_r2_key``. + + Chronicle copies the key from the manifest entry it read, and that entry is + keyed by the pinned ``artifact_year``. Returns ``None`` when the key is + absent or does not have the ``raw////...`` shape. + """ + + 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], +) -> tuple[tuple[object, str, int, int], ...]: + """Every observation fact stamped later than its artifact's year. + + Returns ``(fact, package_id, artifact_year, stamped_year)`` tuples. 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 detected like a restamp, so its + compile refuses until Chronicle types it ``source_projection``. + """ + + detected: list[tuple[object, str, int, int]] = [] + for fact in facts: + if _str_at(fact, "assertion") not in ("", "observation"): + continue + artifact = fact_artifact_year(fact) + if artifact is None: + continue + stamped_year = _period_year(_at(fact, "period", "value")) + if stamped_year is None: + continue + package_id, artifact_year = artifact + if artifact_year < stamped_year: + 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, +) -> 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 artifact 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, artifact_year, stamped_year in detect_restamped_facts(facts): + source_record_id = _str_at(fact, "lineage", "source_record_id") + entry = register.get(package_id) + if entry is None: + problems.append( + f"{source_record_id} ({package_id}: artifact {artifact_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 artifact_year != entry.data_year: + problems.append( + f"{source_record_id} ({package_id}: artifact {artifact_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, + ) + 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 apply_source_vintage_corrections( + registry: TargetRegistry, + corrections: Mapping[str, SourceVintageCorrection], +) -> TargetRegistry: + """Point every period read from a restamped fact at its data year. + + Two readings move: + + - A spec backed by a restamped fact: ``source_period`` becomes the data + year, which 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. + + Values are never touched here. The one number that moves is the aging + factor, computed afterwards from the corrected period. + """ + + if not corrections: + return registry + specs: list[TargetSpec] = [] + for spec in registry.specs: + metadata = dict(spec.metadata) + changed = False + backing = corrections.get(metadata.get("ledger_source_record_id", "")) + if backing is not None and _stamp_matches( + metadata.get("ledger_fact_period"), backing + ): + if "uprating_factor" in metadata: + # No restamped fact is itself rebased today. If one ever is, + # the rebase ran on the stamped period and needs review + # before its aging start can be corrected. + raise ValueError( + f"Target {spec.name!r} is backed by restamped fact " + f"{backing.source_record_id!r} ({backing.label}) and was " + "rebased; review the rebase before correcting its period." + ) + 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 _stamp_matches( + metadata.get("uprating_index_source_period"), control + ): + 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 _stamp_matches(period: object, correction: SourceVintageCorrection) -> bool: + return _period_year(period) == correction.stamped_year + + +def _split_ids(value: object) -> tuple[str, ...]: + return tuple(part for part in str(value or "").split(",") if part) + + +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 c422e9f5e2..015778cee4 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 @@ -133,7 +133,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/test_us_fiscal_targets.py b/packages/microcosm-build/tests/test_us_fiscal_targets.py index fcfea7f9a3..055f0ada28 100644 --- a/packages/microcosm-build/tests/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/test_us_fiscal_targets.py @@ -864,26 +864,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() ) @@ -935,13 +942,15 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) -> None: """The release surface on the pinned feed: 32,843 compiled targets after Medicaid substitution, 5,695 national_state targets at registry - 386fac439e77, 32 CHIP rows none of them for an M-CHIP state, and no + a3547c5322da, 32 CHIP rows none of them for an M-CHIP state, and no other-income row. Before microcosm#956 it was 32,867 / 5,719 at - d5f9d854fe11 (docs/us-chronicle-feed-repin.md erratum).""" + d5f9d854fe11 (docs/us-chronicle-feed-repin.md erratum). Reading the + restamped W-2 tips amount at TY2020 moved the registry from 386fac439e77 + and changed no count.""" registry, surface, _ = pinned_feed_national_state_surface assert len(registry.specs) == 32_843 assert len(surface.specs) == 5_695 - assert surface.version == "386fac439e77" + assert surface.version == "a3547c5322da" chip = [ spec for spec in surface.specs @@ -957,6 +966,100 @@ def test_pinned_feed_national_state_surface_restores_the_fences( assert not [spec.name for spec in surface.specs if "other_income" in spec.name] +_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 _, 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 + 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_capital_gains_returns_control_reads_its_data_year( + pinned_feed_national_state_surface, +) -> None: + """The Historic Table 2 net-capital-gains return counts rebase onto the + congressional-district file's US row, which is TY2022 data stamped + ty2023. The rebase lands them at the control's data year, 2022; the + counts never age, so no value moves. Which control those rows should use + is a separate concept question: the Table 1.4 ty2023 row counts a + different return population.""" + _, surface, _ = pinned_feed_national_state_surface + control_id = ( + "irs_soi.ty2023.congressional_district_2022.all_returns.us." + "net_capital_gains_returns" + ) + rebased = [ + spec + for spec in surface.specs + if spec.metadata.get("uprating_index_source_record_id") == control_id + ] + assert len(rebased) == 51 + for spec in rebased: + assert spec.metadata["uprating_to_period"] == "2022" + assert spec.metadata["uprating_index_source_vintage_stamped_period"] == "2023" + assert spec.metadata["uprating_factor"] == "0.97964474977721" + assert spec.metadata["aging_factor_source"] == "not_dollar_amount" + + def test_reviewed_zero_support_facts_are_not_active_targets() -> None: excluded_source_record_id = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." @@ -4800,6 +4903,108 @@ 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_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/test_us_source_vintage.py b/packages/microcosm-build/tests/test_us_source_vintage.py new file mode 100644 index 0000000000..77104ec161 --- /dev/null +++ b/packages/microcosm-build/tests/test_us_source_vintage.py @@ -0,0 +1,424 @@ +"""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 +refusal of an unreviewed 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 pytest + +from microcosm.build.us_runtime.source_vintage import ( + US_RESTAMPED_SOURCE_PACKAGES, + RestampedSourcePackage, + SourceVintageCorrection, + UnreviewedRestampError, + apply_source_vintage_corrections, + detect_restamped_facts, + fact_artifact_year, + source_vintage_corrections, +) +from microcosm.calibrate import TargetRegistry, TargetSpec + +_SHA = "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f" + + +def _raw_key(package_id: str, artifact_year: int | str, file: str = "f.xlsx") -> str: + return f"raw/irs_soi/{package_id}/{artifact_year}/{_SHA}/{file}" + + +def _fact( + source_record_id: str, + *, + period: int | str, + raw_r2_key: str | None, + assertion: str | None = "observation", +) -> dict[str, object]: + fact: dict[str, object] = { + "lineage": {"source_record_id": source_record_id}, + "period": {"type": "tax_year", "value": period}, + "source": {} if raw_r2_key is None else {"raw_r2_key": raw_r2_key}, + } + 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, + ) + + +_W2 = "soi-w2-statistics-2020" +_TIPS_2023 = ( + "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.amount" +) + + +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/{_SHA}/f.xlsx", + f"raw/irs_soi/{_W2}/20/{_SHA}/f.xlsx", + f"staged/irs_soi/{_W2}/2020/{_SHA}/f.xlsx", + f"raw/irs_soi//2020/{_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_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", + } + 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 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, + ) + } + + +@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_one_record_with_two_different_corrections_is_refused() -> None: + register = { + "a": RestampedSourcePackage("a", 2020, frozenset({2023, 2024}), "20a", "r"), + } + 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, + ) + + +_CORRECTION = SourceVintageCorrection(_TIPS_2023, _W2, 2023, 2020) + + +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", + ), + # Same id at another stamp is not the corrected fact. + _spec( + "other_stamp", + 7.0, + ledger_source_record_id=_TIPS_2023, + ledger_fact_period="2024", + source_period="2024", + ), + ], + 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" + ) + for name in ("other", "other_stamp"): + assert corrected[name] == {spec.name: spec for spec in registry.specs}[name] + + +def test_apply_moves_a_rebased_specs_control_period_to_the_controls_data_year() -> None: + 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" + + +def test_apply_refuses_a_restamped_fact_that_was_itself_rebased() -> None: + spec = _spec( + "restamped", + ledger_source_record_id=_TIPS_2023, + ledger_fact_period="2023", + source_period="2023", + uprating_factor="1.1", + 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_correction_invariants_hold_for_generated_registries() -> None: + """For any registry and any corrections: 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; + and every moved period lands on that fact's data year. 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) + + @st.composite + def cases(draw): + corrections = {} + for record_id in draw(st.sets(st.sampled_from(record_ids))): + stamped = draw(years) + data = draw(st.integers(2010, stamped - 1)) + corrections[record_id] = SourceVintageCorrection( + record_id, "pkg", stamped, data + ) + specs = [] + for index in range(draw(st.integers(0, 8))): + metadata = { + "ledger_source_record_id": draw(st.sampled_from(record_ids)), + "ledger_fact_period": str(draw(years)), + "source_period": str(draw(years)), + } + if draw(st.booleans()): + metadata["uprating_index_source_record_id"] = draw( + st.sampled_from(record_ids) + ) + metadata["uprating_index_source_period"] = str(draw(years)) + metadata["uprating_to_period"] = metadata[ + "uprating_index_source_period" + ] + specs.append( + _spec( + f"spec{index}", + draw(st.floats(0, 1e12, allow_nan=False)), + **metadata, + ) + ) + return specs, corrections + + def backed(spec, corrections): + correction = corrections.get(spec.metadata["ledger_source_record_id"]) + return ( + correction is not None + and str(correction.stamped_year) == (spec.metadata["ledger_fact_period"]) + ) + + 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") + ) + + @settings(max_examples=300, deadline=None) + @given(cases()) + def check(case): + specs, corrections = case + # A backed spec that is also rebased is refused by design; the + # generator does not set uprating_factor, so none is refused here. + registry = TargetRegistry(specs, country="us") + 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_rebased: + correction = corrections[ + before.metadata["uprating_index_source_record_id"] + ] + assert after.metadata["uprating_to_period"] == str(correction.data_year) + + check() + + +def test_detection_matches_the_artifact_year_rule_for_generated_facts() -> None: + """A fact is detected exactly when it is an observation (or carries no + assertion), its raw key parses, and its artifact year precedes its + period year.""" + pytest.importorskip("hypothesis") + from hypothesis import given, settings + from hypothesis import strategies as st + + @settings(max_examples=300, 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(), + ) + def check(artifact_year, period, assertion, keyed): + fact = _fact( + "x", + period=period, + raw_r2_key=_raw_key(_W2, artifact_year) if keyed else None, + assertion=assertion, + ) + period_year = int(str(period).removeprefix("ty")[:4]) + expected = ( + keyed and assertion != "source_projection" and artifact_year < period_year + ) + assert bool(detect_restamped_facts([fact])) == expected + + check() From 251a48e16621ef635a94af286da5189ddf6c963f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 25 Sep 2026 18:15:05 -0400 Subject: [PATCH 02/30] Classify source_vintage.py as a non-population US runtime module Co-Authored-By: Claude Opus 5.5 --- packages/microcosm-build/tests/test_us_spine_blindness.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/microcosm-build/tests/test_us_spine_blindness.py b/packages/microcosm-build/tests/test_us_spine_blindness.py index a18f026f5c..5c0b4fe780 100644 --- a/packages/microcosm-build/tests/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/test_us_spine_blindness.py @@ -305,6 +305,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", From c429ab59cfaeed46b0c557dffb9a03671f964667 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 27 Sep 2026 04:10:00 -0400 Subject: [PATCH 03/30] Detect restamps by file digest and refuse the readings that still see the stamp Round-1 review of #1030 (correctness and claims lenses): - Detect a registered restamp by its file sha256 as well as by the raw_r2_key year, so a storage-key layout change cannot hide it, and add a reviewed exemption register for truthful later observations (a multi-year release keyed by its publication year). - Refuse a restamp that would outrank a truthful fact dated after its data year in latest-vintage selection, and one that sits in an aging growth index; both still read the stamp. - Fail closed where the correction cannot vouch for a spec: a comparable period that differs from the stamp, a multi-fact spec with a restamped member. - Re-pin after merging #1029: national_state keeps 5,694 targets and moves from d315c75804ef to 884bc45ef335; only the tips amount value moves. - Correct the docs and changelog: #117 covers the CD file only, most restamps predate the 2026-09-18 re-pin, and the full-surface moves are relative to data-year aging under the current series policy. Co-Authored-By: Claude Opus 5.5 --- ...us-restamped-source-vintage-aging.fixed.md | 2 +- docs/us-chronicle-feed-repin.md | 152 ++++--- .../build/us_runtime/fiscal_targets.py | 77 +++- .../build/us_runtime/source_vintage.py | 373 +++++++++++++----- .../tests/test_us_fiscal_targets.py | 53 ++- .../tests/test_us_source_vintage.py | 214 +++++++--- 6 files changed, 671 insertions(+), 200 deletions(-) diff --git a/changelog.d/us-restamped-source-vintage-aging.fixed.md b/changelog.d/us-restamped-source-vintage-aging.fixed.md index 0a2982862b..da28f71c5f 100644 --- a/changelog.d/us-restamped-source-vintage-aging.fixed.md +++ b/changelog.d/us-restamped-source-vintage-aging.fixed.md @@ -1 +1 @@ -Read restamped Chronicle facts at their data year (PolicyEngine/chronicle#117). 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, state and IRA tables. The compile now detects an observation fact stamped later than its source artifact's year. It refuses the fact unless a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry matches, and otherwise ages it from the data year. On the pinned feed the `national_state` W-2 Box 7 tips amount target moves from $28.28B, aged from 2023, to $34.29B, chained from TY2020. That surface keeps 5,695 targets, and its registry moves from `386fac439e77` to `a3547c5322da`. On the full surface, 13,176 congressional-district-file dollar targets age from TY2022: AGI-default measures +3.05%, net capital gains -23.9%. +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. On the pinned feed 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 5,694 targets, and its registry moves from `d315c75804ef` to `884bc45ef335`. 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-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 67263a3967..8d3a28ee05 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -187,8 +187,10 @@ 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). +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 fixes the +stamp at source. | Package | File | Data year | Facts stamped ty2023 | |---|---|---|---| @@ -198,56 +200,106 @@ scope builds these five at 2023, so each emits its pinned file as `ty2023` | `soi-ira-roth-contributions-2022` | `22in06ira.xlsx` | TY2022 | 2 | | `soi-ira-traditional-contributions-2022` | `22in05ira.xlsx` | TY2022 | 2 | -The evidence is in 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. The "W-2 Social -Security tips for 2023 (2)" cells listed under -[What moved and what did not](#what-moved-and-what-did-not) are two of -them. The previous pin carried the tips amount only at ty2020, so adding the -ty2023 row switched the tips target from aging on the chained SOI wages -bridge from 2020 to the direct CBO ratio from 2023. That aged it 17.5% too -low ($28.28B instead of $34.29B at 2024). - -The compile reads these facts at their data year -(`us_runtime/source_vintage.py`). An observation fact whose -`source.raw_r2_key` names an artifact year earlier than its period is a -restamp. Each one must match a reviewed `US_RESTAMPED_SOURCE_PACKAGES` entry, -or the compile refuses. For the matching specs, `source_period` becomes the -data year, and so does `uprating_to_period` when a spec is rebased onto a -restamped control. The stamp is kept in `source_vintage_stamped_period`. -Values, names and latest-vintage selection do not change; aging then starts -from the data year. On this feed: - -- `national_state` still has 5,695 targets, and the registry moves from - `386fac439e77` to `a3547c5322da`. One value moves: the W-2 Box 7 tips - amount, from $28,280,884,269 to $34,287,530,779. The 51 Historic Table 2 - net-capital-gains return counts rebased onto the congressional-district US - row, and the two `state_2022` counts, change metadata only; counts do not - age. -- On the full surface, the 13,176 congressional-district-file dollar targets - age from 2022. The AGI-default measures move by +3.05%, net capital gains - by -23.9%, qualified dividends by +8.4% and business income by -0.5%. - Before the correction those targets were off by the inverse of these moves: - -3.0%, +31.4%, -7.8% and +0.5%. -- The 401(k), Roth 401(k) and IRA rows compile no target. +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. + +The stamp is kept in `source_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**, compiled as the release does: + +- **`national_state`** keeps 5,694 targets, and its registry moves from + `d315c75804ef` to `884bc45ef335`. + - 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. A re-pin on a Chronicle commit that -stops the restamp leaves entries that match nothing, and that 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). Two things need a decision first: - -- The Historic Table 2 capital-gains returns control. Today the CD US row - wins a same-period tie. Stamped truthfully, it would lose to Table 1.4 - ty2023, which counts a different return population, and 51 - `national_state` targets would fall 58.5%. -- `SOI_CONGRESSIONAL_DISTRICT_RECORD_SET_ID`, which names the `ty2023` record - set. - -One more mis-stamp runs the other way and is out of reach of the -artifact-year rule. `bea-regional-state-personal-income-components-2024` -reads the 2024 column of its CSV under a `cy2023` stamp (416 facts). No -target compiles from it; its families are parity-manifest exclusions. +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 need a decision before that re-pin: + +- **The Historic Table 2 capital-gains returns control.** The CD US row wins 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%. Today the + 51 state counts sum to 2.39× the national Table 1.4 target of the same + compiled variable. +- **`SOI_CONGRESSIONAL_DISTRICT_RECORD_SET_ID`**, which names the `ty2023` + record set. + +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 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 c5f7b08dd8..b9b173f327 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 @@ -29,10 +29,14 @@ translate_congressional_district_facts_to_current_vintage, ) 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 ( + _period_year, age_us_dollar_targets, enforce_period_contract, ) @@ -1019,10 +1023,16 @@ def compile_us_fiscal_target_registry( materialized_facts, congressional_district_vintage_crosswalk, ) + # 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) + 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, @@ -1055,14 +1065,10 @@ def compile_us_fiscal_target_registry( "target_period": target_period, }, ) - # Restamped Chronicle facts (a pinned artifact labelled with the build - # year, PolicyEngine/chronicle#117) are read at their data year from here - # on: aging starts from it and the period contract checks it. Refuses a - # restamp that is not in the reviewed register. - registry = apply_source_vintage_corrections( - registry, - source_vintage_corrections(materialized_facts), - ) + # 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 @@ -2302,8 +2308,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) @@ -2312,13 +2323,20 @@ 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. Returns ``(source_record_id, reference)`` pairs so the exclusion vintage guard and receipt can see which fact won each key. + + 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) candidates: list[ tuple[ tuple[str, ...], @@ -2343,6 +2361,8 @@ def _latest_dynamic_target_references( reference, ) ) + if restamps: + _refuse_restamps_that_shadow_newer_vintages(candidates, facts, restamps) keys_with_positive_observations = { key for key, _, value, _, _ in candidates if value > 0 } @@ -2376,6 +2396,45 @@ def _latest_dynamic_target_references( ) +def _refuse_restamps_that_shadow_newer_vintages( + candidates: Iterable[tuple[tuple[str, ...], object, float, str, object]], + facts: Iterable[object], + restamps: Mapping[str, SourceVintageCorrection], +) -> 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. + None exists on the pinned feed: the ty2020 W-2 twins sit at the data + year, not after it. + """ + + candidates = tuple(candidates) + restamped_keys: dict[tuple[str, ...], list[SourceVintageCorrection]] = {} + for key, _, _, source_record_id, _ in candidates: + restamp = restamps.get(source_record_id) + if restamp is not None: + restamped_keys.setdefault(key, []).append(restamp) + if not restamped_keys: + return + years = { + _source_record_id(fact): _period_year(_period_value(fact)) for fact in facts + } + conflicts: list[str] = [] + for key, _, _, source_record_id, _ in candidates: + if source_record_id in restamps: + continue + year = years.get(source_record_id) + for restamp in restamped_keys.get(key, ()): + if year is not None and 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 _exclusion_vintage_bypasses( source_record_ids: Iterable[str], ) -> dict[str, tuple[str, ...]]: 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 index fec3d3dfae..4d07c82eba 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py @@ -2,60 +2,92 @@ 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 ``--year`` later -than the artifact year, it re-labels the pinned file's values as the build -year: the same cells, the same bytes, a later period -(PolicyEngine/chronicle#117). The US feed pinned at Chronicle ``c5e5bf8`` -carries five such packages, all built at 2023 by -``us/chronicle_feed_scope.json``. 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, and -a pinned file cannot describe a later year. Until the feed is re-pinned on a -Chronicle commit that stops the restamp, microcosm reads these facts at their -data year wherever a period drives a number. That covers the ``source_period`` -the aging model starts from (:mod:`~microcosm.build.us_runtime.target_aging`) -and the ``uprating_to_period`` a rebased spec inherits from a restamped -control. The values, the target names and the fact that wins latest-vintage -selection are unchanged. The correction moves only the period that aging and -the period contract read, and it records the stamped period next to it. - -Detection is structural. An observation fact whose ``source.raw_r2_key`` -(``raw/////``) names an -artifact year earlier than its own period cannot be a truthful stamp, because a -publication cannot describe a year after its own data year. Each detected -restamp must match a reviewed :data:`US_RESTAMPED_SOURCE_PACKAGES` entry, with -the same package, stamped period and data year, or the compile refuses. The -register is reviewed against the pinned feed -(``test_pinned_feed_restamp_register_matches_the_feed``). A re-pin that fixes -the stamp leaves an entry matching nothing, and that test then fails until the -entry is deleted. - -Out of reach of the structural rule: a package that reads a *later* column -than its stamped period. ``bea-regional-state-personal-income-components-2024`` -stamps CY2024 BEA state income as cy2023. Its raw key year (2024) is later than -its period, as for every legitimate multi-year release. Microcosm does not -compile those facts (they are parity-manifest ``reviewed_exclusion`` -families), so no entry is needed. The fix is Chronicle's, as a year-selecting -package. +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`), and the +``uprating_to_period`` a spec inherits from a restamped rebase control. 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. On the pinned feed, the congressional- + district US ``net_capital_gains_returns`` row wins a period-2023 tie over + Table 1.4 only because of its stamp. + +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 _period_year +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", @@ -68,10 +100,12 @@ class RestampedSourcePackage: Attributes: package_id: The package segment of ``source.raw_r2_key``. - data_year: The year the pinned publisher artifact describes. It must - equal the artifact year in ``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. """ @@ -79,6 +113,21 @@ class RestampedSourcePackage: 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 @@ -86,6 +135,7 @@ def _restamped( package_id: str, data_year: int, source_file: str, + source_sha256: str, reason: str, *, stamped_periods: Iterable[int] = (2023,), @@ -95,14 +145,15 @@ def _restamped( 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...): every observation fact whose raw_r2_key artifact year precedes -# its period is one of these 26,893 facts. Each data year was confirmed from -# the file itself (title cell or content match), not from Chronicle labels. +# 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( ( @@ -110,39 +161,44 @@ def _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. TY2020 is still the newest W-2 " - "table IRS publishes.", + "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", - "IRS SOI congressional district data for tax year 2022, the " - "newest CD release. 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).", + "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'.", ), @@ -150,6 +206,11 @@ def _restamped( ) ) +# 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: @@ -159,6 +220,7 @@ class SourceVintageCorrection: package_id: str stamped_year: int data_year: int + fact_key: str = "" @property def label(self) -> str: @@ -169,32 +231,58 @@ def label(self) -> str: class UnreviewedRestampError(ValueError): - """An observation fact is stamped later than its artifact's year. + """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, or fix the stamp in Chronicle - and re-pin. + 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 - preview = "; ".join(problems[:5]) - suffix = "" if len(problems) <= 5 else f"; +{len(problems) - 5} more" super().__init__( - f"{len(problems)} observation fact(s) carry a period later than " - "their source artifact's year without a matching reviewed " - f"US_RESTAMPED_SOURCE_PACKAGES entry: {preview}{suffix}" + 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, artifact_year)`` from a fact's ``source.raw_r2_key``. + """``(package_id, year)`` from a fact's ``source.raw_r2_key``. - Chronicle copies the key from the manifest entry it read, and that entry is - keyed by the pinned ``artifact_year``. Returns ``None`` when the key is - absent or does not have the ``raw////...`` shape. + 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") @@ -209,29 +297,50 @@ def fact_artifact_year(fact: object) -> tuple[str, int] | None: 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 artifact's year. - - Returns ``(fact, package_id, artifact_year, stamped_year)`` tuples. 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 detected like a restamp, so its - compile refuses until Chronicle types it ``source_projection``. + """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 - artifact = fact_artifact_year(fact) - if artifact is None: - 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: - detected.append((fact, package_id, artifact_year, stamped_year)) + 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) @@ -239,24 +348,29 @@ 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 artifact year disagrees with the entry. + 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, artifact_year, stamped_year in detect_restamped_facts(facts): - source_record_id = _str_at(fact, "lineage", "source_record_id") + 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 {artifact_year}, " + f"{source_record_id} ({package_id}: artifact {file_year}, " f"stamped {stamped_year}; no register entry)" ) continue @@ -266,9 +380,9 @@ def source_vintage_corrections( f"register reviews {sorted(entry.stamped_periods)})" ) continue - if artifact_year != entry.data_year: + if file_year != entry.data_year: problems.append( - f"{source_record_id} ({package_id}: artifact {artifact_year}, " + f"{source_record_id} ({package_id}: artifact {file_year}, " f"register data year {entry.data_year})" ) continue @@ -277,6 +391,7 @@ def source_vintage_corrections( 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: @@ -290,16 +405,42 @@ def source_vintage_corrections( 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 every period read from a restamped fact at its data year. + """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, which is where target aging starts and what the period contract + 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 @@ -307,20 +448,43 @@ def apply_source_vintage_corrections( 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. - Values are never touched here. The one number that moves is the aging - factor, computed afterwards from the corrected period. + 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 spec that was itself rebased, 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 and _stamp_matches( - metadata.get("ledger_fact_period"), backing - ): + 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: # No restamped fact is itself rebased today. If one ever is, # the rebase ran on the stamped period and needs review @@ -346,8 +510,9 @@ def apply_source_vintage_corrections( f"({corrections[control_id].label}); review it." ) control = corrections.get(metadata.get("uprating_index_source_record_id", "")) - if control is not None and _stamp_matches( - metadata.get("uprating_index_source_period"), control + 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) @@ -360,14 +525,38 @@ def apply_source_vintage_corrections( return TargetRegistry(specs, country=registry.country) -def _stamp_matches(period: object, correction: SourceVintageCorrection) -> bool: - return _period_year(period) == correction.stamped_year +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: diff --git a/packages/microcosm-build/tests/test_us_fiscal_targets.py b/packages/microcosm-build/tests/test_us_fiscal_targets.py index b789936243..8feef030df 100644 --- a/packages/microcosm-build/tests/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/test_us_fiscal_targets.py @@ -1186,7 +1186,7 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) -> None: """The release surface on the pinned feed: 32,842 compiled targets after Medicaid substitution, 5,694 national_state targets at registry - REGISTRY_VERSION, 32 CHIP rows none of them for an M-CHIP state, no + 884bc45ef335, 32 CHIP rows none of them for an M-CHIP state, no other-income row and no tips return count. Before microcosm#956 it was 32,867 / 5,719 at d5f9d854fe11; before decision d179 dropped the ty2020 tips return count it was 32,843 / 5,695 at 386fac439e77; and before the @@ -1195,7 +1195,7 @@ def test_pinned_feed_national_state_surface_restores_the_fences( registry, surface, _ = pinned_feed_national_state_surface assert len(registry.specs) == 32_842 assert len(surface.specs) == 5_694 - assert surface.version == "REGISTRY_VERSION" + assert surface.version == "884bc45ef335" chip = [ spec for spec in surface.specs @@ -1252,10 +1252,17 @@ def test_pinned_feed_restamp_register_matches_the_feed(pinned_feed_facts) -> Non assert set(US_RESTAMPED_SOURCE_PACKAGES) == { package_id for _, package_id, _, _ in detected } - for _, package_id, artifact_year, stamped_year 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 @@ -5255,6 +5262,46 @@ def test_age_targets_reads_a_restamped_w2_tips_amount_at_its_data_year() -> None ) +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) + + # 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_an_unreviewed_restamp() -> None: from microcosm.build.us_runtime.source_vintage import UnreviewedRestampError diff --git a/packages/microcosm-build/tests/test_us_source_vintage.py b/packages/microcosm-build/tests/test_us_source_vintage.py index 77104ec161..955a17e04e 100644 --- a/packages/microcosm-build/tests/test_us_source_vintage.py +++ b/packages/microcosm-build/tests/test_us_source_vintage.py @@ -1,31 +1,42 @@ """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 -refusal of an unreviewed restamp) and the pinned-feed register check live in -``test_us_fiscal_targets.py`` beside the other W-2 aging tests. +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 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 -_SHA = "1178d77618cc1d2f873506909eeec660f36e3599854f31337f9dcaec6cfc442f" +_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}/{_SHA}/{file}" + return f"raw/irs_soi/{package_id}/{artifact_year}/{_OTHER_SHA}/{file}" def _fact( @@ -34,11 +45,18 @@ def _fact( 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": {} if raw_r2_key is None else {"raw_r2_key": raw_r2_key}, + "source": source, } if assertion is not None: fact["assertion"] = assertion @@ -58,10 +76,10 @@ def _spec(name: str, value: float = 1.0, **metadata: str) -> TargetSpec: ) -_W2 = "soi-w2-statistics-2020" -_TIPS_2023 = ( - "irs_soi.ty2023.form_w2_social_security_tips.box_7_social_security_tips.amount" -) +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: @@ -72,10 +90,10 @@ def test_fact_artifact_year_reads_the_raw_key_package_and_year() -> None: None, "", "raw/irs_soi", - f"raw/irs_soi/{_W2}/source_capture/{_SHA}/f.xlsx", - f"raw/irs_soi/{_W2}/20/{_SHA}/f.xlsx", - f"staged/irs_soi/{_W2}/2020/{_SHA}/f.xlsx", - f"raw/irs_soi//2020/{_SHA}/f.xlsx", + 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 @@ -107,6 +125,42 @@ def test_detect_restamped_facts_flags_only_observations_stamped_after_their_data 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) + 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", @@ -115,6 +169,8 @@ def test_register_entries_describe_one_earlier_year_each() -> None: "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 @@ -122,6 +178,7 @@ def test_register_entries_describe_one_earlier_year_each() -> None: # 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 @@ -142,6 +199,7 @@ def test_corrections_map_each_registered_restamp_to_its_data_year() -> None: package_id=_W2, stamped_year=2023, data_year=2020, + fact_key=f"ledger.aggregate_fact.v2:{_TIPS_2023}@2023", ) } @@ -164,10 +222,14 @@ def test_an_unreviewed_restamp_is_refused( 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": RestampedSourcePackage("a", 2020, frozenset({2023, 2024}), "20a", "r"), - } + register = {"a": _entry("a", 2020, 2023, 2024)} with pytest.raises(ValueError, match="two corrections"): source_vintage_corrections( [ @@ -178,7 +240,40 @@ def test_one_record_with_two_different_corrections_is_refused() -> None: ) -_CORRECTION = SourceVintageCorrection(_TIPS_2023, _W2, 2023, 2020) +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, {}) + + +_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: @@ -198,14 +293,6 @@ def test_apply_moves_only_the_backing_facts_source_period() -> None: ledger_fact_period="2023", source_period="2023", ), - # Same id at another stamp is not the corrected fact. - _spec( - "other_stamp", - 7.0, - ledger_source_record_id=_TIPS_2023, - ledger_fact_period="2024", - source_period="2024", - ), ], country="us", ) @@ -223,8 +310,22 @@ def test_apply_moves_only_the_backing_facts_source_period() -> None: assert restamped.metadata["source_vintage_correction"] == ( "soi-w2-statistics-2020: stamped 2023, data year 2020" ) - for name in ("other", "other_stamp"): - assert corrected[name] == {spec.name: spec for spec in registry.specs}[name] + 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: @@ -289,6 +390,23 @@ def test_apply_refuses_a_pooled_uprating_index_with_a_restamped_member() -> None ) +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 test_correction_invariants_hold_for_generated_registries() -> None: """For any registry and any corrections: values, names, periods and order never move; the correction is idempotent; a spec changes if and only if @@ -314,9 +432,17 @@ def cases(draw): ) 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": draw(st.sampled_from(record_ids)), - "ledger_fact_period": str(draw(years)), + "ledger_source_record_id": record_id, + "ledger_fact_period": str(fact_period), "source_period": str(draw(years)), } if draw(st.booleans()): @@ -337,11 +463,7 @@ def cases(draw): return specs, corrections def backed(spec, corrections): - correction = corrections.get(spec.metadata["ledger_source_record_id"]) - return ( - correction is not None - and str(correction.stamped_year) == (spec.metadata["ledger_fact_period"]) - ) + return spec.metadata["ledger_source_record_id"] in corrections def rebased(spec, corrections): correction = corrections.get( @@ -355,8 +477,6 @@ def rebased(spec, corrections): @given(cases()) def check(case): specs, corrections = case - # A backed spec that is also rebased is refused by design; the - # generator does not set uprating_factor, so none is refused here. registry = TargetRegistry(specs, country="us") once = apply_source_vintage_corrections(registry, corrections) twice = apply_source_vintage_corrections(once, corrections) @@ -389,15 +509,15 @@ def check(case): check() -def test_detection_matches_the_artifact_year_rule_for_generated_facts() -> None: +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), its raw key parses, and its artifact year precedes its - period year.""" + 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=300, deadline=None) + @settings(max_examples=400, deadline=None) @given( artifact_year=st.integers(2000, 2030), period=st.one_of( @@ -407,18 +527,22 @@ def test_detection_matches_the_artifact_year_rule_for_generated_facts() -> None: ), assertion=st.sampled_from([None, "observation", "source_projection"]), keyed=st.booleans(), + registered_file=st.booleans(), ) - def check(artifact_year, period, assertion, keyed): + def check(artifact_year, period, assertion, keyed, registered_file): fact = _fact( "x", period=period, - raw_r2_key=_raw_key(_W2, artifact_year) if keyed else None, + 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]) - expected = ( - keyed and assertion != "source_projection" and artifact_year < period_year + 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) ) - assert bool(detect_restamped_facts([fact])) == expected check() From 94f055a6d69f22ee19fed4cc6a7a43722315bd49 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 27 Sep 2026 04:26:54 -0400 Subject: [PATCH 04/30] Close the round-2 review's test gaps and tighten the shadow guard - Pin that the CD-crosswalk-translated specs carry the correction (23,980 translated, 11,772 of them chained dollar targets; 26,791 direct and 60 rebased corrections on the pinned feed). - Test the compile's aging-index check (it runs only when aging), the CBO projection branch, an exemption's period bound, and the shadow guard's stamp-year bound. - The shadow guard now reads each candidate's own period key and considers only candidates eligible at the target period, so it cannot refuse a compile over facts selection would drop anyway. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/fiscal_targets.py | 43 ++++--- .../tests/test_us_fiscal_targets.py | 111 ++++++++++++++++++ .../tests/test_us_source_vintage.py | 32 +++++ 3 files changed, 169 insertions(+), 17 deletions(-) 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 b9b173f327..6bf86c3098 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 @@ -36,7 +36,6 @@ source_vintage_corrections, ) from microcosm.build.us_runtime.target_aging import ( - _period_year, age_us_dollar_targets, enforce_period_contract, ) @@ -1027,7 +1026,8 @@ def compile_us_fiscal_target_registry( # 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) - check_restamps_stay_out_of_aging_indexes(materialized_facts, restamps) + if age_targets: + check_restamps_stay_out_of_aging_indexes(materialized_facts, restamps) references = ( *_dynamic_us_fiscal_target_references( materialized_facts, @@ -2336,7 +2336,6 @@ def _latest_dynamic_target_references( the stamp would pick the older data (microcosm#1030 review). """ - facts = tuple(facts) candidates: list[ tuple[ tuple[str, ...], @@ -2362,7 +2361,11 @@ def _latest_dynamic_target_references( ) ) if restamps: - _refuse_restamps_that_shadow_newer_vintages(candidates, facts, 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 } @@ -2397,36 +2400,42 @@ def _latest_dynamic_target_references( def _refuse_restamps_that_shadow_newer_vintages( - candidates: Iterable[tuple[tuple[str, ...], object, float, str, object]], - facts: Iterable[object], + 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. - None exists on the pinned feed: the ty2020 W-2 twins sit at the data - year, not after it. + 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. """ - candidates = tuple(candidates) + eligible = [ + candidate + for candidate in candidates + if _not_after_target_period(candidate[1], target_period_key) + ] restamped_keys: dict[tuple[str, ...], list[SourceVintageCorrection]] = {} - for key, _, _, source_record_id, _ in candidates: + 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 - years = { - _source_record_id(fact): _period_year(_period_value(fact)) for fact in facts - } conflicts: list[str] = [] - for key, _, _, source_record_id, _ in candidates: - if source_record_id in restamps: + for key, period_key, _, source_record_id, _ in eligible: + if source_record_id in restamps or not period_key[0]: continue - year = years.get(source_record_id) + year = period_key[1] // 100 for restamp in restamped_keys.get(key, ()): - if year is not None and restamp.data_year < year <= restamp.stamped_year: + if restamp.data_year < year <= restamp.stamped_year: conflicts.append( f"{restamp.source_record_id} ({restamp.label}) would outrank " f"{source_record_id} ({year})" diff --git a/packages/microcosm-build/tests/test_us_fiscal_targets.py b/packages/microcosm-build/tests/test_us_fiscal_targets.py index 8feef030df..48f9fb8190 100644 --- a/packages/microcosm-build/tests/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/test_us_fiscal_targets.py @@ -1296,6 +1296,49 @@ def test_pinned_feed_w2_tips_amount_ages_from_tax_year_2020( 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 + ) + assert corrected == { + ("soi-congressional-district-2022", True, True): 11_772, + ("soi-congressional-district-2022", True, False): 12_208, + ("soi-congressional-district-2022", False, True): 1_404, + ("soi-congressional-district-2022", False, False): 1_404, + ("soi-state-2022", False, False): 2, + ("soi-w2-statistics-2020", False, True): 1, + } + assert all( + spec.metadata["source_period"] == "2022" + for spec in registry.specs + if spec.metadata.get("source_vintage_correction", "").startswith( + "soi-congressional-district-2022" + ) + ) + assert ( + sum( + "uprating_index_source_vintage_correction" in spec.metadata + for spec in registry.specs + ) + == 60 + ) + + def test_pinned_feed_capital_gains_returns_control_reads_its_data_year( pinned_feed_national_state_surface, ) -> None: @@ -5285,6 +5328,45 @@ def test_compile_refuses_a_restamp_that_would_outrank_newer_data() -> None: ] 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) @@ -5302,6 +5384,35 @@ def test_compile_refuses_a_restamp_that_would_outrank_newer_data() -> None: ) +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 diff --git a/packages/microcosm-build/tests/test_us_source_vintage.py b/packages/microcosm-build/tests/test_us_source_vintage.py index 955a17e04e..181676e242 100644 --- a/packages/microcosm-build/tests/test_us_source_vintage.py +++ b/packages/microcosm-build/tests/test_us_source_vintage.py @@ -158,6 +158,11 @@ def test_a_reviewed_exemption_admits_a_truthful_later_observation() -> None: } 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 == {} @@ -271,6 +276,33 @@ def test_a_restamped_fact_in_an_aging_chain_index_is_refused() -> None: 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" ) From 0f343249fd9a53816f336b9d34b811f38b650727 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 27 Sep 2026 04:55:28 -0400 Subject: [PATCH 05/30] Choose the capital-gains rebase control by concept and period, not feed order Historic Table 2 and congressional-district N01000 count Form 1040 line 7 returns (gain, loss-limited loss or distributions only); Table 1.4 col 37, the population capital_gains_gross measures, counts Schedule D gain returns only. The rebase control is now the latest Table 1.4 fact not after the build period, CD and HT2 rows never qualify, a tie between matched records refuses the compile, and a line-7 row without a usable control is dropped instead of shipping as a level. Rebased rows declare the bridge in soi_source_concept / soi_control_concept. On the pinned feed the 51 national_state HT2 state return counts go from 29,599,604 (2.39x the national 12,392,020 target) back to Build P's 12,289,836; amounts keep their values. national_state registry d315c75804ef -> 65e4dde11c83 (microcosm#1035). Co-Authored-By: Claude Opus 5.5 --- ...035-capital-gains-control-concept.fixed.md | 1 + docs/us-chronicle-feed-repin.md | 10 + docs/us-soi-capital-gains-concepts.md | 120 +++++ .../build/us_runtime/fiscal_targets.py | 139 ++++- .../tests/test_us_fiscal_targets.py | 484 +++++++++++++++++- 5 files changed, 728 insertions(+), 26 deletions(-) create mode 100644 changelog.d/1035-capital-gains-control-concept.fixed.md create mode 100644 docs/us-soi-capital-gains-concepts.md 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/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 14aee6d60c..8bf63b09cf 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -171,6 +171,16 @@ 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`. + 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 diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md new file mode 100644 index 0000000000..841d6fdf85 --- /dev/null +++ b/docs/us-soi-capital-gains-concepts.md @@ -0,0 +1,120 @@ +# 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. Their own targets, which + are on the `full` surface only, are not reconciled here. + +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 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. + +`test_pinned_feed_no_soi_state_family_sums_past_its_national_target` holds +the invariant across all 63 SOI state families on the surface. 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 1cf1d0ec54..4b5334f83c 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 @@ -45,6 +45,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", @@ -1471,13 +1472,62 @@ 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. +_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. The model carries no Schedule D loss returns, +#: so a line-7 count has no model counterpart 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 Historic Table 2 capital-gains rows as shares of a Table 1.4 level. + + HT2 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 the HT2 national total, scaled to the + concept-matched control of ``_soi_capital_gains_active_totals`` at or after + its own period, and declares the bridge in ``soi_source_concept`` / + ``soi_control_concept``. Without such a control, the row is dropped. The + national all-AGI HT2 rows retire because the control's own row owns the + national concept. + """ controls = _soi_capital_gains_active_totals( facts, @@ -1494,15 +1544,11 @@ def _rebase_stale_soi_capital_gains_distributions( 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( + 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 in (None, 0): continue if _is_national_all_agi_spec(spec): @@ -1525,6 +1571,8 @@ 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_FORM_1040_LINE_7_NET_GAIN_OR_LOSS, + "soi_control_concept": _SOI_CAPITAL_GAINS_MODEL_CONCEPT, }, ) ) @@ -1536,13 +1584,25 @@ 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 records at the winning + period 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_record_ids: dict[tuple[str, str, str], set[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): @@ -1550,22 +1610,59 @@ def _soi_capital_gains_active_totals( source_record_id = _source_record_id(fact) if not source_record_id: continue - candidate = _SoiTotalControl( - value=_numeric_value(fact), - source_period=str(_period_value(fact)), - source_record_id=source_record_id, - period_key=period_key, - ) current = controls.get(key) - if current is None or _prefer_candidate( - candidate.period_key, - current.period_key, - target_period_key=target_period_key, - ): - controls[key] = candidate + if current is not None and period_key[:2] == current.period_key[:2]: + tied_record_ids[key].add(source_record_id) + continue + if current is None or period_key[:2] > current.period_key[:2]: + controls[key] = _SoiTotalControl( + value=_numeric_value(fact), + source_period=str(_period_value(fact)), + source_record_id=source_record_id, + period_key=period_key, + ) + tied_record_ids[key] = {source_record_id} + ambiguous = { + key: sorted(record_ids) + for key, record_ids in tied_record_ids.items() + if len(record_ids) > 1 + } + if ambiguous: + raise AmbiguousSoiCapitalGainsControlError( + "SOI capital-gains control is ambiguous: different records 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_record_set_family(record_set_id: str) -> str: + """An SOI record set's table family, without period or data vintage. + + ``irs_soi.ty2023.table_1_4`` is ``table_1_4``, + ``irs_soi.ty2022.historic_table_2.state_broad`` is ``historic_table_2`` and + ``irs_soi.ty2023.congressional_district_2022.all_returns`` is + ``congressional_district``. + """ + parts = record_set_id.split(".") + if parts[0] != "irs_soi": + return "" + rest = parts[2:] if len(parts) > 1 and _is_period_token(parts[1]) else parts[1:] + if not rest: + return "" + family = rest[0] + if family.startswith("congressional_district"): + return "congressional_district" + return family + + +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_stale_national_totals( facts: tuple[object, ...], ) -> dict[tuple[str, str, str, str], float]: diff --git a/packages/microcosm-build/tests/test_us_fiscal_targets.py b/packages/microcosm-build/tests/test_us_fiscal_targets.py index 3559eb8451..97b1d992a4 100644 --- a/packages/microcosm-build/tests/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/test_us_fiscal_targets.py @@ -1179,15 +1179,16 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) -> None: """The release surface on the pinned feed: 32,842 compiled targets after Medicaid substitution, 5,694 national_state targets at registry - d315c75804ef, 32 CHIP rows none of them for an M-CHIP state, no + 65e4dde11c83, 32 CHIP rows none of them for an M-CHIP state, no other-income row and no tips return count. 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).""" + 32,867 / 5,719 at d5f9d854fe11, before decision d179 dropped the ty2020 + tips return count it was 32,843 / 5,695 at 386fac439e77, and before + microcosm#1035 moved the capital-gains control back to Table 1.4 it was + d315c75804ef at the same counts (docs/us-chronicle-feed-repin.md).""" registry, surface, _ = pinned_feed_national_state_surface assert len(registry.specs) == 32_842 assert len(surface.specs) == 5_694 - assert surface.version == "d315c75804ef" + assert surface.version == "65e4dde11c83" chip = [ spec for spec in surface.specs @@ -1214,6 +1215,101 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) +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["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 + + def quantity(spec) -> tuple[object, ...]: + 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_") + ) + ), + ) + + 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 test_reviewed_zero_support_facts_are_not_active_targets() -> None: excluded_source_record_id = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." @@ -4506,6 +4602,384 @@ def test_stale_soi_capital_gains_without_source_total_is_dropped() -> None: assert state_record_id not in source_record_ids +_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 _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" + ), + 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" + ), + 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 + ) + + +@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 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" From 6ebfcf7f4f90bc30fbea63cddb40eff67ed97f2d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 27 Sep 2026 05:22:06 -0400 Subject: [PATCH 06/30] Refuse any ambiguous capital-gains control; qualify two claims (#1036 review) The chooser now treats one record id carrying two values or period labels at the winning period as ambiguous too, so no feed order can pick the value. Tests cover that, an equivalent period label, and a tie at a superseded period. The model-concept comment scopes "no loss returns" to the Build P release data, and the doc's AGI-mix median is the median absolute change. Co-Authored-By: Claude Opus 5.5 --- docs/us-soi-capital-gains-concepts.md | 2 +- .../build/us_runtime/fiscal_targets.py | 39 +++++++------- .../tests/test_us_fiscal_targets.py | 51 +++++++++++++++++++ 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md index 841d6fdf85..4475329c53 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -75,7 +75,7 @@ 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 of 1.6% and no state beyond 5%. +to +4.3% (DC), with a median absolute change of 1.6% and no state beyond 5%. ## How the returns control drifted 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 4b5334f83c..acd4751ddb 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 @@ -1502,8 +1502,10 @@ class _SoiTotalControl: #: 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. The model carries no Schedule D loss returns, -#: so a line-7 count has no model counterpart at any level. +#: 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 @@ -1590,13 +1592,14 @@ def _soi_capital_gains_active_totals( ``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 records at the winning - period refuse the compile. Feed order used to break that tie, and the + 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_record_ids: dict[tuple[str, str, str], set[str]] = {} + 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) @@ -1610,26 +1613,28 @@ def _soi_capital_gains_active_totals( source_record_id = _source_record_id(fact) if not source_record_id: continue + candidate = _SoiTotalControl( + value=_numeric_value(fact), + source_period=str(_period_value(fact)), + 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 not None and period_key[:2] == current.period_key[:2]: - tied_record_ids[key].add(source_record_id) + tied[key].add(identity) continue if current is None or period_key[:2] > current.period_key[:2]: - controls[key] = _SoiTotalControl( - value=_numeric_value(fact), - source_period=str(_period_value(fact)), - source_record_id=source_record_id, - period_key=period_key, - ) - tied_record_ids[key] = {source_record_id} + controls[key] = candidate + tied[key] = {identity} ambiguous = { - key: sorted(record_ids) - for key, record_ids in tied_record_ids.items() - if len(record_ids) > 1 + key: sorted(candidates) + for key, candidates in tied.items() + if len(candidates) > 1 } if ambiguous: raise AmbiguousSoiCapitalGainsControlError( - "SOI capital-gains control is ambiguous: different records tie at " + "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)." ) diff --git a/packages/microcosm-build/tests/test_us_fiscal_targets.py b/packages/microcosm-build/tests/test_us_fiscal_targets.py index 97b1d992a4..d6508f4840 100644 --- a/packages/microcosm-build/tests/test_us_fiscal_targets.py +++ b/packages/microcosm-build/tests/test_us_fiscal_targets.py @@ -4804,6 +4804,57 @@ def test_capital_gains_control_refuses_two_matched_records_at_one_period() -> No ) +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"), [ From 011a63b1ad45da8364d7e463fabf327c76d757b9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 27 Sep 2026 17:02:20 -0400 Subject: [PATCH 07/30] Rebase congressional-district capital gains onto Table 1.4; drop mislabeled CD columns (#1038) On the full target surface the congressional-district file's capital-gains rows compiled as Form 1040 line-7 levels onto capital_gains_gross (Schedule D gain): its states and districts each summed to 29,845,710 returns, 2.41x the Table 1.4 target, and $1,522.2B, 1.198x. They now enter as shares of the file's own US row scaled to the Table 1.4 control, as Historic Table 2 rows do since #1036; the US row retires and every share row names its denominator in soi_share_total_source_record_id. The same package reads N18425/A18425 (state and local income taxes) as the limited SALT deduction and N85530/A85530 (additional Medicare tax) as the premium tax credit. US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS drops facts by (measure id, IRS column), replaces the hard-coded CD PTC-amount check, and is listed in the exclusion receipt and the release coverage report. On the pinned feed: 31,376 compiled targets (was 32,842), no CD-file family past its national target on full (was 3), national_state values and membership unchanged (version moves only for the new provenance key). Co-Authored-By: Claude Opus 5.5 --- .../1038-cd-capital-gains-shares.fixed.md | 1 + docs/us-chronicle-feed-repin.md | 11 + docs/us-soi-capital-gains-concepts.md | 109 ++- .../microcosm/build/us_runtime/__init__.py | 2 + .../build/us_runtime/fiscal_targets.py | 239 ++++-- .../engine_free/us/test_us_fiscal_targets.py | 742 +++++++++++++++++- .../microcosm_build/us_fiscal_targets.py | 52 +- tools/build_us_fiscal_refresh_release.py | 11 + 8 files changed, 1069 insertions(+), 98 deletions(-) create mode 100644 changelog.d/1038-cd-capital-gains-shares.fixed.md 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..07af399c0b --- /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 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. Every capital-gains share row names its denominator in `soi_share_total_source_record_id`. A new reviewed source-column exclusion, `US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`, drops congressional-district facts read from IRS columns their measure id does not mean: 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. It replaces the hard-coded congressional-district PTC-amount check and is listed in the exclusion receipt. On the pinned feed, the congressional-district capital-gains 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/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 907fbefc79..8d2dab4ced 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -181,6 +181,17 @@ 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`. +**Follow-up (27 September 2026, microcosm#1038).** On the `full` surface, +the congressional-district file's capital-gains rows are now shares of its US +row scaled to the same control, and the US row retires. The package's four +mislabeled columns are dropped: 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. That leaves 31,376 compiled targets, all of them on +`full` (`059dc56d78db`). `national_state` keeps its 5,694 targets and values. +It moves to `47dce807b412` only because its 102 Historic Table 2 +capital-gains rows now name their share denominator in +`soi_share_total_source_record_id`. + 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 diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md index 4475329c53..784cdecd72 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -67,8 +67,13 @@ level. 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. Their own targets, which - are on the `full` surface only, are not reconciled here. +- **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 @@ -118,3 +123,103 @@ crosswalk, then narrowed to `national_state`: `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 rows agree with the HT2 state rows about as well as other + pairs on `full` already do.** The congressional-district and HT2 state + return counts for capital gains differ by a median 0.6% (95th percentile + 2.1%). The `return_count` pair differs by 1.6% (2.4%). + - Amounts differ more: a median 2.8% (95th percentile 15.4%, Montana + −27.0%). The cause is item suppression in the congressional-district + file's A01000. Montana's is 32.5% below HT2's at the state level. That is + still inside the qualified-dividends amount pair, 11.6% (21.7%). + +The congressional-district file has no rows for other areas, so its US row +equals the sum of its 51 states. The rebased states and districts therefore +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. + +**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. Before it merges with this change, +that refusal must admit a share whose `soi_share_total_source_record_id` is a +restamp of the same package, 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). + +### Effect on the pinned feed + +Release compile at 2024, as above: + +| `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` | 32,842 (`e02123644d42`) | 31,376 (`059dc56d78db`) | +| `national_state` targets | 5,694 (`65e4dde11c83`) | 5,694 (`47dce807b412`) | + +- 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`. + +### 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. They are +the only differences between its column mapping and the Historic Table 2 +package's (all 56 measures compared): + +| 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. + +`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_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py index 74e4757cba..ac03bb85c4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py @@ -291,6 +291,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, @@ -1165,6 +1166,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 acd4751ddb..6487592936 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 @@ -55,6 +55,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", @@ -854,6 +855,61 @@ 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. +# +# Chronicle's congressional_district_2022 package reads these four columns +# under the limited_state_local_taxes_* and premium_tax_credit_* measure ids; +# every other measure it shares with Historic Table 2 reads the same column. +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: @@ -1090,6 +1146,9 @@ 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 (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 @@ -1108,6 +1167,7 @@ def us_fiscal_target_exclusion_receipt( ) reviewed: set[str] = set() all_vintage: set[str] = set() + source_column: set[str] = set() m_chip: set[str] = set() for fact in materialized_facts: source_record_id = _source_record_id(fact) @@ -1117,6 +1177,8 @@ def us_fiscal_target_exclusion_receipt( all_vintage.add(source_record_id) elif source_record_id in US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: reviewed.add(source_record_id) + elif _is_source_column_concept_exclusion(fact): + source_column.add(source_record_id) elif _source_name(fact) == "cms_medicaid": reference = _reference_from_ledger_fact(fact, target_period=target_period) if reference is not None and _is_m_chip_state_chip_enrollment( @@ -1144,6 +1206,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", @@ -1490,7 +1568,8 @@ class _SoiTotalControl: #: 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. +#: 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] = { @@ -1519,44 +1598,54 @@ def _rebase_stale_soi_capital_gains_distributions( *, target_period: int | str, ) -> TargetRegistry: - """Use Historic Table 2 capital-gains rows as shares of a Table 1.4 level. - - HT2 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 the HT2 national total, scaled to the - concept-matched control of ``_soi_capital_gains_active_totals`` at or after - its own period, and declares the bridge in ``soi_source_concept`` / - ``soi_control_concept``. Without such a control, the row is dropped. The - national all-AGI HT2 rows retire because the control's own row owns the - national concept. + """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 family total, the row + is dropped. 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"])) + 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"]) ): continue - if source_total in (None, 0): + if source_total is None or source_total.value == 0: continue if _is_national_all_agi_spec(spec): continue - factor = control.value / source_total + factor = control.value / source_total.value specs.append( replace( spec, @@ -1573,8 +1662,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_FORM_1040_LINE_7_NET_GAIN_OR_LOSS, + "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, }, ) ) @@ -1668,15 +1760,76 @@ def _soi_capital_gains_concept(fact: object) -> str | None: ) -def _soi_capital_gains_stale_national_totals( +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. + """ + 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 @@ -1694,22 +1847,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: @@ -2622,6 +2759,16 @@ def _period_free_source_record_id(source_record_id: str) -> str: return _normalized_record_set_id(source_record_id) +def _is_source_column_concept_exclusion(fact: object) -> bool: + """Whether an SOI fact reads a column its measure id does not mean.""" + if _source_name(fact) != "irs_soi": + return False + return ( + _measure_id(fact), + _str_at(fact, "layout", "source_column_id"), + ) in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS + + 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) @@ -2656,18 +2803,6 @@ def _is_soi_congressional_district_record_set(fact: object) -> bool: return ".congressional_district_2022." in record_set_id -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"): @@ -2734,6 +2869,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( @@ -2791,8 +2928,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: 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 cc7037cc82..64d27d4180 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 @@ -107,10 +107,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( @@ -164,9 +168,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", @@ -734,12 +739,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) @@ -750,6 +757,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", } @@ -761,11 +769,92 @@ 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", + ) + mislabeled = [*mislabeled, medicare] + facts = [*packaged_reference_facts(), *mislabeled, corrected, ptc] + + 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 + 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 the column 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 + assert right_columns[key] in reason + # Counts read N columns and amounts read A columns. + assert ( + column[0] + == right_columns[key][0] + == ("N" if measure_id.endswith("_returns") else "A") + ) 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.""" @@ -773,7 +862,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() @@ -859,9 +948,11 @@ 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,952 congressional-district SALT and + premium-tax-credit facts read from the wrong IRS column (488 per measure + after the district crosswalk: the US row, 51 states, 436 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"] @@ -886,23 +977,44 @@ 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: 488 for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} + assert len(column_ids) == 4 * 488 def test_pinned_feed_national_state_surface_restores_the_fences( pinned_feed_national_state_surface, ) -> None: - """The release surface on the pinned feed: 32,842 compiled targets after - Medicaid substitution, 5,694 national_state targets at registry - 65e4dde11c83, 32 CHIP rows none of them for an M-CHIP state, no - other-income row and no tips return count. Before microcosm#956 it was - 32,867 / 5,719 at d5f9d854fe11, before decision d179 dropped the ty2020 - tips return count it was 32,843 / 5,695 at 386fac439e77, and before - microcosm#1035 moved the capital-gains control back to Table 1.4 it was - d315c75804ef at the same counts (docs/us-chronicle-feed-repin.md).""" + """The release surface on the pinned feed: 31,376 compiled targets after + Medicaid substitution (the full surface, at 059dc56d78db), 5,694 + national_state targets at registry 47dce807b412, 32 CHIP rows none of them + for an M-CHIP state, no other-income row and no tips return count. Before + microcosm#956 it was 32,867 / 5,719 at d5f9d854fe11, before decision d179 + dropped the ty2020 tips return count it was 32,843 / 5,695 at + 386fac439e77, before microcosm#1035 moved the capital-gains control back + to Table 1.4 it was d315c75804ef at the same counts, and before + microcosm#1038 it was 32,842 compiled at 65e4dde11c83 (full e02123644d42): + that change drops 1,466 congressional-district specs (the two + capital-gains US rows and the SALT and premium-tax-credit rows read from + the wrong column) and moves national_state only by one provenance key, + soi_share_total_source_record_id, on the 102 Historic Table 2 + capital-gains rows (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) == 32_842 + assert len(registry.specs) == 31_376 + builder = _load_repo_tool("build_us_fiscal_refresh_release") + full, _ = builder._select_target_surface(registry.specs, "full") + assert TargetRegistry(full, country="us").version == "059dc56d78db" assert len(surface.specs) == 5_694 - assert surface.version == "65e4dde11c83" + assert surface.version == "47dce807b412" chip = [ spec for spec in surface.specs @@ -962,6 +1074,9 @@ def test_pinned_feed_capital_gains_rows_take_the_table_1_4_level( 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" @@ -986,25 +1101,7 @@ def test_pinned_feed_no_soi_state_family_sums_past_its_national_target( 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 - - def quantity(spec) -> tuple[object, ...]: - 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_") - ) - ), - ) + quantity = _soi_quantity national: dict[tuple[object, ...], list[float]] = {} states: dict[tuple[object, ...], float] = {} @@ -1024,6 +1121,133 @@ def quantity(spec) -> tuple[object, ...]: } == {} +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. 35 of today's 52 families have a national comparator; + the rest (EITC by children, charitable, interest paid, QBI, taxable + interest, filer individuals) have none on this surface.""" + 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 { + (key[:2], level): total / max(national[key]) + for key, sums in compared.items() + for level, total in sums.items() + if total > max(national[key]) * (1 + 1e-9) + } == {} + + def test_reviewed_zero_support_facts_are_not_active_targets() -> None: excluded_source_record_id = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." @@ -4556,6 +4780,440 @@ def check(state_values, other_areas, control_value) -> None: 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_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. 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, + order=st.randoms(use_true_random=False), + ) + def check(districts, state_excess, at_large_value, other_areas, control, order): + facts = [] + 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 + ) + + 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 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" diff --git a/test_support/microcosm_build/us_fiscal_targets.py b/test_support/microcosm_build/us_fiscal_targets.py index 7f83264f18..4cb6fb7a44 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, @@ -160,12 +161,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." @@ -217,8 +243,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( [ *( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index e421049cfc..7cc40f2614 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -86,6 +86,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, @@ -14687,6 +14688,16 @@ def _main(argv: Sequence[str] | None = None) -> None: 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 write_us_source_coverage_diagnostics( coverage, release_dir / "us_source_coverage.json" From a17db0f15279ace288a804b6c3786e0735e27f21 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 08:35:02 -0400 Subject: [PATCH 08/30] Exclude the CD interest-paid column and fail closed on missing columns and totals (#1040 review) The congressional-district package reads interest_paid_deduction_* from N19300/A19300, Schedule A line 8a mortgage interest, while interest_deduction is the line 10 total; add both to US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS. A congressional-district fact of a listed measure with no layout.source_column_id now refuses (MissingSoiSourceColumnError) instead of compiling unchecked, and a capital-gains share row that has a control but no national total of its own family refuses (MissingSoiCapitalGainsShareTotalError) instead of dropping silently. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/fiscal_targets.py | 85 +++++++++++++-- .../engine_free/us/test_us_fiscal_targets.py | 103 ++++++++++++++---- 2 files changed, 155 insertions(+), 33 deletions(-) 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 6487592936..d56dfda0cb 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 @@ -873,10 +873,20 @@ def _us_hierarchy_seed( # 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. +# - N19300/A19300 as "Mortgage interest paid" (Schedule A line 8a). The +# interest deduction interest_deduction measures is line 10: lines 8a-8c +# plus investment interest (line 9). The file carries 8b, 8c and 9 as +# separate columns and no line 10 total. # -# Chronicle's congressional_district_2022 package reads these four columns -# under the limited_state_local_taxes_* and premium_tax_credit_* measure ids; -# every other measure it shares with Historic Table 2 reads the same column. +# Chronicle's congressional_district_2022 package reads these six columns +# under the limited_state_local_taxes_*, premium_tax_credit_* and +# interest_paid_deduction_* measure ids. Of its other 50 measures, the 46 it +# shares with a Historic Table 2 package read the same column there, and the +# other four (charitable contributions A19700, qualified business income +# deduction A04475) match their doc-guide definitions. +# 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 " @@ -908,6 +918,22 @@ def _us_hierarchy_seed( "congressional_district_2022 package reads it under this measure id: " "TY2022 US $14.2B against $53.1B for A85770 in the same file." ), + ("interest_paid_deduction_returns", "N19300"): ( + "N19300 counts returns with home mortgage interest reported on Form " + "1098 (Schedule A line 8a), not returns with the interest deduction " + "(line 10: lines 8a-8c and investment interest on line 9) " + "interest_deduction measures. Chronicle's congressional_district_2022 " + "package reads it under this measure id: TY2022 US 11,352,500 " + "returns; the file has no line 10 column." + ), + ("interest_paid_deduction_amount", "A19300"): ( + "A19300 is home mortgage interest reported on Form 1098 (Schedule A " + "line 8a), one part of the line 10 interest deduction " + "interest_deduction measures. Chronicle's congressional_district_2022 " + "package reads it under this measure id: TY2022 US $140.1B, 85.6% of " + "lines 8a-8c and 9 ($163.7B, A19300 + A19500 + A19530 + A19570) in " + "the same file." + ), } @@ -1607,9 +1633,10 @@ def _rebase_stale_soi_capital_gains_distributions( 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 family total, the row - is dropped. Each family's national all-AGI row retires because the - control's own row owns the national concept. + / ``soi_control_concept``. Without such a control the row is dropped; with + a control but no family total its share is undefined and the compile + refuses. 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 @@ -1640,7 +1667,13 @@ def _rebase_stale_soi_capital_gains_distributions( ): continue if source_total is None or source_total.value == 0: - continue + raise MissingSoiCapitalGainsShareTotalError( + f"SOI capital-gains row {spec.name!r} has a control but its " + f"{family} family has no nonzero national all-AGI total for " + f"{key} at {spec.metadata['source_period']}, so its share is " + "undefined; a line-7 row must never ship as a level " + "(microcosm#1038)." + ) if _is_national_all_agi_spec(spec): continue @@ -1787,6 +1820,10 @@ class AmbiguousSoiCapitalGainsShareTotalError(ValueError): """One share family carries two different national totals for one period.""" +class MissingSoiCapitalGainsShareTotalError(ValueError): + """A share-family row has a control but no national total of its own.""" + + @dataclass(frozen=True) class _SoiShareTotal: value: float @@ -2759,14 +2796,38 @@ 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.""" + """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 - return ( - _measure_id(fact), - _str_at(fact, "layout", "source_column_id"), - ) in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS + 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: + if ( + _soi_record_set_family(_str_at(fact, "layout", "record_set_id")) + == "congressional_district" + ): + 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 _is_all_vintage_support_exclusion(source_record_id: str) -> bool: 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 64d27d4180..5b2354811b 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 @@ -129,10 +129,14 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: groupby_value_id="hi_01", geography_id="5001700US1501", ), - _soi_congressional_district_fact( + # N19300 is line 8a mortgage interest, not the line 10 interest + # deduction the measure id means, so it never compiles either. + _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( @@ -190,7 +194,9 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: if spec.metadata.get("ledger_geography_level") == "congressional_district" ] assert not any( - source_id.endswith("premium_tax_credit_amount") + source_id.endswith( + ("premium_tax_credit_amount", "interest_paid_deduction_returns") + ) and ".congressional_district_2022." in source_id for source_id in source_ids ) @@ -198,7 +204,7 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: assert any( "hi_total.adjusted_gross_income" in source_id for source_id in source_ids ) - assert len(cd_specs) == 11 + assert len(cd_specs) == 10 by_measure = { spec.metadata["source_measure_id"]: spec for spec in cd_specs @@ -242,12 +248,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" @@ -828,28 +828,68 @@ def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: def test_source_column_exclusions_name_the_columns_their_guides_define() -> None: - """Each entry's reason names its own column and the column 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.""" + """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), N85530/A85530 (additional Medicare tax) for the premium tax + credit N85770/A85770, and N19300/A19300 (line 8a mortgage interest) for the + line 10 interest deduction, which the file has no column for.""" 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", + ("interest_paid_deduction_returns", "N19300"): None, + ("interest_paid_deduction_amount", "A19300"): None, } 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 - assert right_columns[key] in reason # Counts read N columns and amounts read A columns. - assert ( - column[0] - == right_columns[key][0] - == ("N" if measure_id.endswith("_returns") else "A") - ) + assert column[0] == ("N" if measure_id.endswith("_returns") else "A") + right_column = right_columns[key] + if right_column is None: + assert "line 10" in reason + else: + assert right_column in reason + assert right_column[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 + } def test_exclusion_receipt_is_complete_for_any_subfeed(monkeypatch) -> None: @@ -5000,6 +5040,27 @@ def test_congressional_district_capital_gains_rows_without_a_control_are_dropped assert _congressional_district_capital_gains_specs(registry) == {} +def test_capital_gains_share_row_without_its_family_total_refuses() -> None: + """A congressional-district row with a Schedule D control but no US row of + its own has no defined share. The compile refuses instead of dropping it + silently or letting another family's total stand in (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(), + ] + + with pytest.raises( + fiscal_targets.MissingSoiCapitalGainsShareTotalError, match="hi_total" + ): + compile_us_fiscal_target_registry(facts, allow_unaged_dollar_targets=True) + + 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.""" From 4e86ec3580e3e40ef501ac60fa1c16834143742f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 08:52:54 -0400 Subject: [PATCH 09/30] Re-pin #1036 on the 51aa40f feed after merging main main re-pinned the US Chronicle feed to 51aa40f (#940), whose capital-gains cells are identical to c5e5bf8's. Compiled there, this change still moves the same 60 Historic Table 2 return counts by 0.415202720927 and adds the concept keys to the 60 amount specs; national_state goes from e1f9906bf0e0 to 882f4764a248 at 6,102 targets (full f5bd921d6b21 to f09571684885). Co-Authored-By: Claude Opus 5.5 --- docs/us-chronicle-feed-repin.md | 5 ++++- docs/us-soi-capital-gains-concepts.md | 6 ++++++ .../tests/engine_free/us/test_us_fiscal_targets.py | 4 ++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 0c4787e508..400a897b6f 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -210,7 +210,10 @@ 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`. +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. The labelled feed exposed one latent defect in microcosm, fixed in this change: `apply_us_medicaid_enrollment_substitutions` built Rhode Island's diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md index 4475329c53..feefc5d3e8 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -116,5 +116,11 @@ crosswalk, then narrowed to `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. 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 e7656ce424..aaed3a00a3 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 @@ -895,7 +895,7 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) -> None: """The release surface on the pinned feed: 33,250 compiled targets after Medicaid substitution, 6,102 national_state targets at registry - PENDING_1036_NS, 32 CHIP rows none of them for an M-CHIP state, no + 882f4764a248, 32 CHIP rows none of them for an M-CHIP state, no other-income row and no tips return count. microcosm#1035 moved it from e1f9906bf0e0 at the same counts by choosing the capital-gains control by concept and period, which returns the 51 Historic Table 2 state return @@ -911,7 +911,7 @@ def test_pinned_feed_national_state_surface_restores_the_fences( registry, surface, _ = pinned_feed_national_state_surface assert len(registry.specs) == 33_250 assert len(surface.specs) == 6_102 - assert surface.version == "PENDING_1036_NS" + assert surface.version == "882f4764a248" chip = [ spec for spec in surface.specs From 278535485fcca3c9815e4f315c23ffef513f0410 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 09:00:39 -0400 Subject: [PATCH 10/30] Drop congressional-district SALT and PTC facts read from the wrong IRS column (#1038) Chronicle's congressional_district_2022 package reads limited_state_local_taxes_* from N18425/A18425 (state and local income taxes, Schedule A line 5a) and premium_tax_credit_* from N85530/A85530 (additional Medicare tax, Form 8959 line 24); Historic Table 2 reads N18460/A18460 and N85770/A85770. A reviewed register keyed by (measure id, IRS column), US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS, drops those facts at every geography and vintage, refuses a listed district fact that names no column, and is listed in the exclusion receipt and the release coverage report. It replaces the hard-coded district PTC-amount check. On the pinned 51aa40f feed: 1,464 district specs leave the full surface (976 SALT, which summed to 1.98x the national target, and 488 PTC returns); national_state is byte-identical (e1f9906bf0e0); full f5bd921d6b21 -> f38dbd749180. Co-Authored-By: Claude Opus 5.5 --- .../1038-cd-source-column-exclusions.fixed.md | 1 + docs/us-acs-local-soi-target-surface.md | 43 +++- docs/us-fact-to-target.md | 13 ++ .../microcosm/build/us_runtime/__init__.py | 2 + .../build/us_runtime/fiscal_targets.py | 139 ++++++++++-- .../engine_free/us/test_us_fiscal_targets.py | 212 ++++++++++++++++-- .../microcosm_build/us_fiscal_targets.py | 52 ++++- tools/build_us_fiscal_refresh_release.py | 11 + tools/us_acs_local_cd_surface.py | 6 +- 9 files changed, 430 insertions(+), 49 deletions(-) create mode 100644 changelog.d/1038-cd-source-column-exclusions.fixed.md 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/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index e072362569..80fcd27bb6 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -79,6 +79,20 @@ 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` are +unchanged. `totals` loses the 487 district-file premium-tax-credit return +rows and `full` loses those and the 974 district-file SALT rows: + +| Family | `state` | `totals` | `full` | +|---|---:|---:|---:| +| `irs_soi` | 4,227 | 120 | 29,860 | +| **Admin specs** | **4,380** | **273** | **30,013** | + The rest of this section describes the 2026-09-22 measurement. The 487 population marginals (51 states and 436 congressional districts) are @@ -104,8 +118,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`, @@ -292,8 +310,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 +319,12 @@ 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`). PR #1040 (awaiting a ruling) +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). 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 @@ -556,7 +574,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-fact-to-target.md b/docs/us-fact-to-target.md index e4ae417a8d..af5b185b75 100644 --- a/docs/us-fact-to-target.md +++ b/docs/us-fact-to-target.md @@ -204,6 +204,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/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py index 74e4757cba..ac03bb85c4 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/__init__.py @@ -291,6 +291,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, @@ -1165,6 +1166,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 7df8db9b95..d600667cd2 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 @@ -55,6 +55,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", @@ -877,6 +878,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: @@ -1114,6 +1183,9 @@ 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 (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 @@ -1132,6 +1204,7 @@ def us_fiscal_target_exclusion_receipt( ) reviewed: set[str] = set() all_vintage: set[str] = set() + source_column: set[str] = set() m_chip: set[str] = set() for fact in materialized_facts: source_record_id = _source_record_id(fact) @@ -1141,6 +1214,8 @@ def us_fiscal_target_exclusion_receipt( all_vintage.add(source_record_id) elif source_record_id in US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: reviewed.add(source_record_id) + elif _is_source_column_concept_exclusion(fact): + source_column.add(source_record_id) elif _source_name(fact) == "cms_medicaid": reference = _reference_from_ledger_fact(fact, target_period=target_period) if reference is not None and _is_m_chip_state_chip_enrollment( @@ -1168,6 +1243,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", @@ -2916,6 +3007,38 @@ 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 boundary vintage. + if ".congressional_district_" in _str_at(fact, "layout", "record_set_id"): + 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 _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) @@ -2950,18 +3073,6 @@ def _is_soi_congressional_district_record_set(fact: object) -> bool: return ".congressional_district_2022." in record_set_id -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"): @@ -3028,6 +3139,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( @@ -3085,8 +3198,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: 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 3cd976bac3..a53b624516 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", @@ -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,125 @@ 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", + ) + mislabeled = [*mislabeled, medicare] + facts = [*packaged_reference_facts(), *mislabeled, corrected, ptc] + + 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 + 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 + } 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 +901,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 +987,11 @@ 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,952 congressional-district SALT and + premium-tax-credit facts read from the wrong IRS column (488 per measure + after the district crosswalk: the US row, 51 states, 436 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 +1016,27 @@ 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: 488 for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} + assert len(column_ids) == 4 * 488 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 - e1f9906bf0e0, 32 CHIP rows none of them for an M-CHIP state, no - other-income row and no tips return count. microcosm#1206 moved the + """The release surface on the pinned feed: 31,786 compiled + targets after Medicaid substitution (the full surface, at f38dbd749180), + 6,102 national_state targets at registry e1f9906bf0e0, 32 CHIP rows none + of them for an M-CHIP state, no other-income row and no tips return count. + microcosm#1038 dropped the 1,464 congressional-district SALT and + premium-tax-credit specs read from the wrong IRS column, all on the full + surface, from 33,250 (full f5bd921d6b21). microcosm#1206 moved the version from f96be9f41781 by binding the Part B premium target to gross_medicare_part_b_premium_if_enrolled; the counts are unchanged. The 408 state AGI-band rows of @@ -905,8 +1045,13 @@ def test_pinned_feed_national_state_surface_restores_the_fences( 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).""" + from microcosm.calibrate import TargetRegistry + registry, surface, _ = pinned_feed_national_state_surface - assert len(registry.specs) == 33_250 + assert len(registry.specs) == 31_786 + builder = _load_repo_tool("build_us_fiscal_refresh_release") + full, _ = builder._select_target_surface(registry.specs, "full") + assert TargetRegistry(full, country="us").version == "f38dbd749180" assert len(surface.specs) == 6_102 assert surface.version == "e1f9906bf0e0" chip = [ @@ -935,6 +1080,33 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) +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_reviewed_zero_support_facts_are_not_active_targets() -> None: excluded_source_record_id = ( "hhs_acf_tanf.fy2024.cash_assistance.ar." diff --git a/test_support/microcosm_build/us_fiscal_targets.py b/test_support/microcosm_build/us_fiscal_targets.py index f3c4f5c83c..1fe88d05bc 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, @@ -160,12 +161,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." @@ -217,8 +243,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( [ *( diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 6b64ce7059..35e639ec18 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -92,6 +92,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, @@ -15847,6 +15848,16 @@ def _main(argv: Sequence[str] | None = None) -> int | None: 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 write_us_source_coverage_diagnostics( coverage, release_dir / "us_source_coverage.json" diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index edd37055fa..1348e0e4fc 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 " From d1614b2f5cc62be163c2b3ddb13f4e87b333ad7c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 09:07:39 -0400 Subject: [PATCH 11/30] Address the #1040 review; re-pin on the 51aa40f feed; align the column exclusions with #1224 Review (review-1040.md) follow-ups: - Interest paid stays out of US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS: N19300 (line 8a mortgage interest) is a component of the line 10 deduction, not another concept, and it feeds state_cd's itemized bridge; its share-or-drop decision is a separate chip. The register comment, docs and claims now say 50 of the package's 56 measures have a Historic Table 2 twin. - A share row with no national row of its own family is dropped, as the established rule and test_stale_soi_capital_gains_without_source_total_is_dropped require; the pinned invariant is now two-sided (every compared district family keeps its state and district rows and sits in (0.85, 1] of its national target), so a vanished or partial family fails. - The CD-vs-HT2 tilt (0.8% returns, 2.1% amounts) is stated plainly; the amount agreement is reported on the demeaned comparison with the worst states named. - The Hypothesis property draws Historic Table 2 rows alongside and checks each family divides by, and names, its own US row; comments on CD boundary vintages sharing a family and on a corrected PTC package. The SALT/PTC column exclusions are now #1224 (a bug fix that lands on its own); this branch carries them byte-identical until it merges. Pins on the 51aa40f feed: 31,784 compiled (full 6e1ac91262bc), national_state 6,102 at 84504a7afd57. Co-Authored-By: Claude Opus 5.5 --- .../1038-cd-capital-gains-shares.fixed.md | 2 +- .../1038-cd-source-column-exclusions.fixed.md | 1 + docs/us-acs-local-soi-target-surface.md | 43 ++++-- docs/us-chronicle-feed-repin.md | 19 +-- docs/us-fact-to-target.md | 13 ++ docs/us-soi-capital-gains-concepts.md | 84 +++++++---- .../build/us_runtime/fiscal_targets.py | 74 ++++------ .../engine_free/us/test_us_fiscal_targets.py | 136 +++++++++++++----- tools/us_acs_local_cd_surface.py | 6 +- 9 files changed, 242 insertions(+), 136 deletions(-) create mode 100644 changelog.d/1038-cd-source-column-exclusions.fixed.md diff --git a/changelog.d/1038-cd-capital-gains-shares.fixed.md b/changelog.d/1038-cd-capital-gains-shares.fixed.md index 07af399c0b..cd9ac24eb3 100644 --- a/changelog.d/1038-cd-capital-gains-shares.fixed.md +++ b/changelog.d/1038-cd-capital-gains-shares.fixed.md @@ -1 +1 @@ -On the `full` target surface, congressional-district capital-gains rows now enter as shares of the 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. Every capital-gains share row names its denominator in `soi_share_total_source_record_id`. A new reviewed source-column exclusion, `US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`, drops congressional-district facts read from IRS columns their measure id does not mean: 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. It replaces the hard-coded congressional-district PTC-amount check and is listed in the exclusion receipt. On the pinned feed, the congressional-district capital-gains 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). +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/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index e072362569..80fcd27bb6 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -79,6 +79,20 @@ 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` are +unchanged. `totals` loses the 487 district-file premium-tax-credit return +rows and `full` loses those and the 974 district-file SALT rows: + +| Family | `state` | `totals` | `full` | +|---|---:|---:|---:| +| `irs_soi` | 4,227 | 120 | 29,860 | +| **Admin specs** | **4,380** | **273** | **30,013** | + The rest of this section describes the 2026-09-22 measurement. The 487 population marginals (51 states and 436 congressional districts) are @@ -104,8 +118,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`, @@ -292,8 +310,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 +319,12 @@ 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`). PR #1040 (awaiting a ruling) +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). 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 @@ -556,7 +574,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 e0bb63d9a2..644645937f 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -212,15 +212,16 @@ 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`. -**Follow-up (27 September 2026, microcosm#1038).** On the `full` surface, -the congressional-district file's capital-gains rows are now shares of its US -row scaled to the same control, and the US row retires. The package's four -mislabeled columns are dropped: 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. That leaves 31,376 compiled targets, all of them on -`full` (`059dc56d78db`). `national_state` keeps its 5,694 targets and values. -It moves to `47dce807b412` only because its 102 Historic Table 2 -capital-gains rows now name their share denominator in +**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`. The labelled feed exposed one latent defect in microcosm, fixed in this diff --git a/docs/us-fact-to-target.md b/docs/us-fact-to-target.md index e4ae417a8d..af5b185b75 100644 --- a/docs/us-fact-to-target.md +++ b/docs/us-fact-to-target.md @@ -204,6 +204,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 index 784cdecd72..71ea372072 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -152,20 +152,31 @@ takes (a): 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 rows agree with the HT2 state rows about as well as other - pairs on `full` already do.** The congressional-district and HT2 state - return counts for capital gains differ by a median 0.6% (95th percentile - 2.1%). The `return_count` pair differs by 1.6% (2.4%). - - Amounts differ more: a median 2.8% (95th percentile 15.4%, Montana - −27.0%). The cause is item suppression in the congressional-district - file's A01000. Montana's is 32.5% below HT2's at the state level. That is - still inside the qualified-dividends amount pair, 11.6% (21.7%). - -The congressional-district file has no rows for other areas, so its US row -equals the sum of its 51 states. The rebased states and districts therefore -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. +- **The rebased return counts agree with the HT2 state rows as well as any + pair 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. Every congressional-district capital-gains target +therefore sits above the matching HT2 share, by 0.8% for returns and 2.1% +for amounts in aggregate. 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 @@ -174,15 +185,21 @@ 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. Before it merges with this change, -that refusal must admit a share whose `soi_share_total_source_record_id` is a -restamp of the same package, 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). +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, as above: +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 | |---|---:|---:| @@ -190,21 +207,22 @@ Release compile at 2024, as above: | 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` | 32,842 (`e02123644d42`) | 31,376 (`059dc56d78db`) | -| `national_state` targets | 5,694 (`65e4dde11c83`) | 5,694 (`47dce807b412`) | +| Compiled targets, all on `full` | 33,250 (`f09571684885`) | 31,784 (`6e1ac91262bc`) | +| `national_state` targets | 6,102 (`882f4764a248`) | 6,102 (`84504a7afd57`) | - 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`. + `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. They are -the only differences between its column mapping and the Historic Table 2 -package's (all 56 measures compared): +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 | |---|---|---|---| @@ -218,7 +236,19 @@ 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. +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_runtime/fiscal_targets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py index 8aff6578ea..c3f50779f8 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 @@ -896,18 +896,21 @@ def _us_hierarchy_seed( # 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. -# - N19300/A19300 as "Mortgage interest paid" (Schedule A line 8a). The -# interest deduction interest_deduction measures is line 10: lines 8a-8c -# plus investment interest (line 9). The file carries 8b, 8c and 9 as -# separate columns and no line 10 total. +# 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 six columns -# under the limited_state_local_taxes_*, premium_tax_credit_* and -# interest_paid_deduction_* measure ids. Of its other 50 measures, the 46 it -# shares with a Historic Table 2 package read the same column there, and the -# other four (charitable contributions A19700, qualified business income -# deduction A04475) match their doc-guide definitions. +# 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. @@ -942,22 +945,6 @@ def _us_hierarchy_seed( "congressional_district_2022 package reads it under this measure id: " "TY2022 US $14.2B against $53.1B for A85770 in the same file." ), - ("interest_paid_deduction_returns", "N19300"): ( - "N19300 counts returns with home mortgage interest reported on Form " - "1098 (Schedule A line 8a), not returns with the interest deduction " - "(line 10: lines 8a-8c and investment interest on line 9) " - "interest_deduction measures. Chronicle's congressional_district_2022 " - "package reads it under this measure id: TY2022 US 11,352,500 " - "returns; the file has no line 10 column." - ), - ("interest_paid_deduction_amount", "A19300"): ( - "A19300 is home mortgage interest reported on Form 1098 (Schedule A " - "line 8a), one part of the line 10 interest deduction " - "interest_deduction measures. Chronicle's congressional_district_2022 " - "package reads it under this measure id: TY2022 US $140.1B, 85.6% of " - "lines 8a-8c and 9 ($163.7B, A19300 + A19500 + A19530 + A19570) in " - "the same file." - ), } @@ -1658,10 +1645,10 @@ def _rebase_stale_soi_capital_gains_distributions( 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 the row is dropped; with - a control but no family total its share is undefined and the compile - refuses. Each family's national all-AGI row retires because the control's - own row owns the national 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 @@ -1692,13 +1679,9 @@ def _rebase_stale_soi_capital_gains_distributions( ): continue if source_total is None or source_total.value == 0: - raise MissingSoiCapitalGainsShareTotalError( - f"SOI capital-gains row {spec.name!r} has a control but its " - f"{family} family has no nonzero national all-AGI total for " - f"{key} at {spec.metadata['source_period']}, so its share is " - "undefined; a line-7 row must never ship as a level " - "(microcosm#1038)." - ) + # 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 @@ -1845,10 +1828,6 @@ class AmbiguousSoiCapitalGainsShareTotalError(ValueError): """One share family carries two different national totals for one period.""" -class MissingSoiCapitalGainsShareTotalError(ValueError): - """A share-family row has a control but no national total of its own.""" - - @dataclass(frozen=True) class _SoiShareTotal: value: float @@ -1865,7 +1844,10 @@ def _soi_capital_gains_share_national_totals( 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. + 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: @@ -3212,10 +3194,8 @@ def _is_source_column_concept_exclusion(fact: object) -> bool: return False column = _str_at(fact, "layout", "source_column_id") if not column: - if ( - _soi_record_set_family(_str_at(fact, "layout", "record_set_id")) - == "congressional_district" - ): + # Any congressional-district package, whatever its boundary vintage. + if ".congressional_district_" in _str_at(fact, "layout", "record_set_id"): raise MissingSoiSourceColumnError( f"{_source_record_id(fact)} is a congressional-district " f"{measure_id} fact with no layout.source_column_id, so " 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 9de16ee6cf..a995f2ed3b 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 @@ -131,8 +131,8 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: groupby_value_id="hi_01", geography_id="5001700US1501", ), - # N19300 is line 8a mortgage interest, not the line 10 interest - # deduction the measure id means, so it never compiles either. + # 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", "N19300", @@ -196,9 +196,7 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: if spec.metadata.get("ledger_geography_level") == "congressional_district" ] assert not any( - source_id.endswith( - ("premium_tax_credit_amount", "interest_paid_deduction_returns") - ) + source_id.endswith("premium_tax_credit_amount") and ".congressional_district_2022." in source_id for source_id in source_ids ) @@ -206,7 +204,7 @@ def test_soi_congressional_district_targets_are_always_compiled() -> None: assert any( "hi_total.adjusted_gross_income" in source_id for source_id in source_ids ) - assert len(cd_specs) == 10 + assert len(cd_specs) == 11 by_measure = { spec.metadata["source_measure_id"]: spec for spec in cd_specs @@ -243,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 ( @@ -833,16 +837,13 @@ 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), N85530/A85530 (additional Medicare tax) for the premium tax - credit N85770/A85770, and N19300/A19300 (line 8a mortgage interest) for the - line 10 interest deduction, which the file has no column for.""" + (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", - ("interest_paid_deduction_returns", "N19300"): None, - ("interest_paid_deduction_amount", "A19300"): None, } assert set(US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS) == set(right_columns) for key, reason in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS.items(): @@ -850,12 +851,8 @@ def test_source_column_exclusions_name_the_columns_their_guides_define() -> None assert column in reason # Counts read N columns and amounts read A columns. assert column[0] == ("N" if measure_id.endswith("_returns") else "A") - right_column = right_columns[key] - if right_column is None: - assert "line 10" in reason - else: - assert right_column in reason - assert right_column[0] == column[0] + 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: @@ -1033,12 +1030,12 @@ def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> No def test_pinned_feed_national_state_surface_restores_the_fences( pinned_feed_national_state_surface, ) -> None: - """The release surface on the pinned feed: PENDING_MINE_COMPILED compiled + """The release surface on the pinned feed: 31,784 compiled targets after Medicaid substitution (the full surface, at - PENDING_MINE_FULL), 6,102 national_state targets at registry - PENDING_MINE_NS, 32 CHIP rows none of them for an M-CHIP state, no + 6e1ac91262bc), 6,102 national_state targets at registry + 84504a7afd57, 32 CHIP rows none of them for an M-CHIP state, no other-income row and no tips return count. microcosm#1038 took it from - 33,250 compiled (full PENDING_1036_FULL) and PENDING_1036_NS: it drops + 33,250 compiled (full f09571684885) and 882f4764a248: it drops the congressional-district capital-gains US rows and the congressional-district SALT, premium-tax-credit and interest-paid rows read from the wrong IRS column, all on the full surface, and moves @@ -1058,12 +1055,12 @@ def test_pinned_feed_national_state_surface_restores_the_fences( from microcosm.calibrate import TargetRegistry registry, surface, _ = pinned_feed_national_state_surface - assert len(registry.specs) == PENDING_MINE_COMPILED_INT + assert len(registry.specs) == 31_784 builder = _load_repo_tool("build_us_fiscal_refresh_release") full, _ = builder._select_target_surface(registry.specs, "full") - assert TargetRegistry(full, country="us").version == "PENDING_MINE_FULL" + assert TargetRegistry(full, country="us").version == "6e1ac91262bc" assert len(surface.specs) == 6_102 - assert surface.version == "PENDING_MINE_NS" + assert surface.version == "84504a7afd57" chip = [ spec for spec in surface.specs @@ -1269,9 +1266,16 @@ def test_pinned_feed_no_congressional_district_family_sums_past_its_national_tar 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. 35 of today's 52 families have a national comparator; - the rest (EITC by children, charitable, interest paid, QBI, taxable - interest, filer individuals) have none on this surface.""" + 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") @@ -1289,11 +1293,16 @@ def test_pinned_feed_no_congressional_district_family_sums_past_its_national_tar 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): total / max(national[key]) + (key[:2], level): round(total / max(national[key]), 4) for key, sums in compared.items() for level, total in sums.items() - if total > max(national[key]) * (1 + 1e-9) + if not 0.85 * max(national[key]) <= total <= max(national[key]) * (1 + 1e-9) } == {} @@ -5049,10 +5058,11 @@ def test_congressional_district_capital_gains_rows_without_a_control_are_dropped assert _congressional_district_capital_gains_specs(registry) == {} -def test_capital_gains_share_row_without_its_family_total_refuses() -> None: +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 has no defined share. The compile refuses instead of dropping it - silently or letting another family's total stand in (microcosm#1038).""" + 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(), *( @@ -5064,10 +5074,16 @@ def test_capital_gains_share_row_without_its_family_total_refuses() -> None: *_capital_gains_t14_facts(), ] - with pytest.raises( - fiscal_targets.MissingSoiCapitalGainsShareTotalError, match="hi_total" - ): - compile_us_fiscal_target_registry(facts, allow_unaged_dollar_targets=True) + 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: @@ -5159,7 +5175,9 @@ def test_congressional_district_capital_gains_shares_conserve_the_control() -> N 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. The order is part of the draw, so the result is order-free.""" + 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 @@ -5186,10 +5204,35 @@ def test_congressional_district_capital_gains_shares_conserve_the_control() -> N 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, order): - facts = [] + 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 @@ -5247,6 +5290,18 @@ def check(districts, state_excess, at_large_value, other_areas, control, order): [*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: @@ -5257,6 +5312,9 @@ def check(districts, state_excess, at_large_value, other_areas, control, order): "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) diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index edd37055fa..1348e0e4fc 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 " From a4e24cd08a1f6a313716262f0bf7a90d4448da54 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 09:28:19 -0400 Subject: [PATCH 12/30] Pin the ACS-local totals and full SOI counts after the column exclusion Measured with state_admin_specs on the pinned 51aa40f feed: --soi-mode totals keeps 120 SOI specs (the Historic Table 2 premium-tax-credit rows only) and full 29,860, as docs/us-acs-local-soi-target-surface.md states. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_release_tool.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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 4024b3a260..c948e928ab 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 @@ -956,6 +956,22 @@ 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 Historic Table 2 premium-tax-credit rows (51 states and 9 at-large + # district copies, returns and amounts) and `full` 29,860 SOI specs. + totals_soi = [spec for spec in totals_registry.specs if spec.family == "irs_soi"] + assert len(totals_soi) == 120 + 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_860 assert not [ spec From 90ad595a648bc2c0ce379595a3d749193cb43365 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 09:28:22 -0400 Subject: [PATCH 13/30] Pin the ACS-local SOI counts; record state_cd's capital-gains factors under the share rebase The ACS-local contract test pins totals at 120 SOI specs and full at 29,860 (identical to #1224). With the district file's capital-gains rows as shares of the Table 1.4 control, state_cd's capital-gains amount rebase factors move from 0.77-1.00 to 0.93-1.20 (median 0.98); its counts and factor-band verdicts are unchanged (measured on the pinned 51aa40f feed). Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-soi-target-surface.md | 17 +++++++++++------ .../us/test_us_acs_local_release_tool.py | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index 80fcd27bb6..3f5b7fdcf0 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -217,8 +217,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 @@ -320,11 +323,13 @@ bridged state row records its sibling and bridge factor. | Bridged state rows whose sibling ratio is out of band | 4 | The factor band (above) | Since microcosm#1038 the compiler excludes the same SALT and PTC columns -(`US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`). PR #1040 (awaiting a ruling) -rescales the district file's capital-gains rows by one national factor. -`state_cd` already takes district capital gains as within-state shares of +(`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). +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 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 4024b3a260..c948e928ab 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 @@ -956,6 +956,22 @@ 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 Historic Table 2 premium-tax-credit rows (51 states and 9 at-large + # district copies, returns and amounts) and `full` 29,860 SOI specs. + totals_soi = [spec for spec in totals_registry.specs if spec.family == "irs_soi"] + assert len(totals_soi) == 120 + 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_860 assert not [ spec From bab55cb97d195dd4b1ad14d9b1bf9ca02b3a3bac Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:17:31 -0400 Subject: [PATCH 14/30] Admit a rebased restamp only as a share of its own package's restamped total apply_source_vintage_corrections refused every restamped fact that carried uprating_factor. A congressional-district capital-gains row rebased as a share of the same package's US row times the Table 1.4 control (microcosm#1040) is such a fact, so #1030 plus #1040 refused every pinned compile. A rebased restamp is now admitted only when the total its rebase names in soi_share_total_source_record_id is a restamp of the same package, stamp and data year, and its uprating_from_period is the stamp or the data year. The stamp then cancels in the share and the level is the control's: source_period and uprating_from_period move to the data year, and uprating_to_period, where aging starts, stays at the control's period. Moving it would age the control's data-year-to-control-period change twice (x0.761 for CD capital gains). A missing, truthful or mixed-vintage total still refuses. The module docstring no longer says the CD row wins the capital-gains control tie: a restamped control keeps the selection its stamp won, which holds whichever rule picks the control. Tests: an admitted same-package share (and its idempotence), seven refusals (no total, truthful total, another package, stamp or data year, another reading period, no reading period), and the Hypothesis property now draws uprating_factor, uprating_from_period and share totals across packages and vintages, with the exact refusal oracle. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/source_vintage.py | 65 +++-- .../engine_free/us/test_us_source_vintage.py | 237 ++++++++++++++++-- 2 files changed, 271 insertions(+), 31 deletions(-) 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 index 4d07c82eba..3540f78f70 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/source_vintage.py @@ -16,17 +16,17 @@ 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`), and the -``uprating_to_period`` a spec inherits from a restamped rebase control. Values -and target names do not change. Two readings still see the stamp, by design, -because moving them would change which fact wins: +(: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. On the pinned feed, the congressional- - district US ``net_capital_gains_returns`` row wins a period-2023 tie over - Table 1.4 only because of its stamp. +- 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`). @@ -447,6 +447,13 @@ def apply_source_vintage_corrections( ``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. @@ -454,8 +461,9 @@ def apply_source_vintage_corrections( 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 spec that was itself rebased, as one member - of a multi-fact spec, or inside a pooled uprating index. + 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: @@ -486,13 +494,38 @@ def apply_source_vintage_corrections( "review how the period was compared." ) if "uprating_factor" in metadata: - # No restamped fact is itself rebased today. If one ever is, - # the rebase ran on the stamped period and needs review - # before its aging start can be corrected. - raise ValueError( - f"Target {spec.name!r} is backed by restamped fact " - f"{backing.source_record_id!r} ({backing.label}) and was " - "rebased; review the rebase before correcting its period." + # 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) 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 index 181676e242..82f9aa32ca 100644 --- 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 @@ -7,6 +7,7 @@ from __future__ import annotations +import dataclasses import json import pytest @@ -394,13 +395,147 @@ def test_apply_moves_a_rebased_specs_control_period_to_the_controls_data_year() assert corrected.metadata["source_period"] == "2022" -def test_apply_refuses_a_restamped_fact_that_was_itself_rebased() -> None: +_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,) + + +@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"): @@ -440,28 +575,57 @@ def test_apply_refuses_a_multi_fact_spec_with_a_restamped_member() -> None: def test_correction_invariants_hold_for_generated_registries() -> None: - """For any registry and any corrections: 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; - and every moved period lands on that fact's data year. Hypothesis is a - workspace dependency; the wheels job installs no test extras, so it - skips there.""" + """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 shared vintages make same-package shares common; the free draw + # keeps mixed packages, stamps and data years in play. + vintages = st.one_of( + st.sampled_from( + [("pkg_a", 2023, 2022), ("pkg_a", 2024, 2022), ("pkg_b", 2023, 2022)] + ), + 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): corrections = {} for record_id in draw(st.sets(st.sampled_from(record_ids))): - stamped = draw(years) - data = draw(st.integers(2010, stamped - 1)) + package_id, stamped, data = draw(vintages) corrections[record_id] = SourceVintageCorrection( - record_id, "pkg", stamped, data + 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]), + ) ) + specs = [] for index in range(draw(st.integers(0, 8))): record_id = draw(st.sampled_from(record_ids)) @@ -478,13 +642,20 @@ def cases(draw): "source_period": str(draw(years)), } if draw(st.booleans()): - metadata["uprating_index_source_record_id"] = draw( - st.sampled_from(record_ids) - ) - metadata["uprating_index_source_period"] = str(draw(years)) + 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" + if draw(st.integers(0, 4)): + metadata["uprating_from_period"] = str(period_near(record_id)) + if draw(st.integers(0, 4)): + metadata["soi_share_total_source_record_id"] = draw( + st.sampled_from([*record_ids, "irs_soi.ty2023.truthful"]) + ) specs.append( _spec( f"spec{index}", @@ -505,11 +676,35 @@ def rebased(spec, corrections): spec.metadata.get("uprating_index_source_period") ) - @settings(max_examples=300, deadline=None) + 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 (total.package_id, total.stamped_year, total.data_year) + == (backing.package_id, backing.stamped_year, backing.data_year) + 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(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 @@ -532,11 +727,23 @@ def check(case): 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() From 9ab6781559922fa9c4b35839b2bd1ecd7c611c76 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:17:32 -0400 Subject: [PATCH 15/30] Re-pin #1030 on the 51aa40f feed; make the rebase-control test order-free On the 51aa40f feed (main since #940) main + #1030 compiles 33,250 targets, 6,102 on national_state at 61f5cac06310 (main: e1f9906bf0e0). Every other #1030 figure is unchanged from c5e5bf8: one national_state value moves (the W-2 tips amount, $28,280,884,269 -> $34,287,530,779), 53 specs change metadata only, 13,176 CD-file dollar targets age from TY2022, the corrected spec counter is 11,772/12,208/1,404/1,404/2/1 and 60 specs carry a control correction. test_pinned_feed_capital_gains_returns_control_reads_its_data_year named the CD US row as the control, which microcosm#1036 makes impossible. It becomes test_pinned_feed_rebased_specs_read_restamped_inputs_at_their_data_year: every spec rebased onto a restamped control reads its data year, and every rebased restamp is a same-package share whose aging still starts at the control's period, whichever control the compile picks. The counter test also pins that main compiles no restamped share. Docs and changelog: the share reading, the new hashes, chronicle#292's merge, and #1036 as the open control question (d468). Co-Authored-By: Claude Opus 5.5 --- ...us-restamped-source-vintage-aging.fixed.md | 2 +- docs/us-chronicle-feed-repin.md | 30 +++++-- .../engine_free/us/test_us_fiscal_targets.py | 81 ++++++++++++------- 3 files changed, 78 insertions(+), 35 deletions(-) diff --git a/changelog.d/us-restamped-source-vintage-aging.fixed.md b/changelog.d/us-restamped-source-vintage-aging.fixed.md index da28f71c5f..590ebb08a7 100644 --- a/changelog.d/us-restamped-source-vintage-aging.fixed.md +++ b/changelog.d/us-restamped-source-vintage-aging.fixed.md @@ -1 +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. On the pinned feed 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 5,694 targets, and its registry moves from `d315c75804ef` to `884bc45ef335`. 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%. +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-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 955c01ecd6..9124fb05f4 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -220,8 +220,9 @@ 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 fixes the -stamp at source. +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 | |---|---|---|---| @@ -259,7 +260,18 @@ 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_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`. Values and target names do not change. Two readings still see the stamp, because moving them would @@ -275,10 +287,12 @@ 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**, compiled as the release does: +**On this feed** (`51aa40f`), compiled as the release does: -- **`national_state`** keeps 5,694 targets, and its registry moves from - `d315c75804ef` to `884bc45ef335`. +- **`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 @@ -322,7 +336,9 @@ Two things need a decision before that re-pin: 1.4 ty2023, which counts returns with a taxable net gain (a different population), and the 51 `national_state` counts would fall 58.5%. Today the 51 state counts sum to 2.39× the national Table 1.4 target of the same - compiled variable. + compiled variable. microcosm#1036 (decision d468) chooses the control by + concept instead; no restamped row is then a capital-gains control, and the + 60 control corrections above go away. - **`SOI_CONGRESSIONAL_DISTRICT_RECORD_SET_ID`**, which names the `ty2023` record set. 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 a56e69f728..6231e73795 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 @@ -895,9 +895,11 @@ def test_pinned_feed_national_state_surface_restores_the_fences( ) -> None: """The release surface on the pinned feed: 33,250 compiled targets after Medicaid substitution, 6,102 national_state targets at registry - e1f9906bf0e0, 32 CHIP rows none of them for an M-CHIP state, no - other-income row and no tips return count. microcosm#1206 moved the - version from f96be9f41781 by binding the Part B premium target to + 61f5cac06310, 32 CHIP rows none of them for an M-CHIP state, no + other-income row and no tips return count. Reading the restamped W-2 tips + amount at TY2020 (microcosm#1030) moved the version from e1f9906bf0e0 + with the counts unchanged. microcosm#1206 moved it from f96be9f41781 by + binding the Part B premium target to gross_medicare_part_b_premium_if_enrolled; the counts are unchanged. The 408 state AGI-band rows of microcosm#940 (51 states x 4 bands x 2 measures) took it from 32,842 / @@ -908,7 +910,7 @@ def test_pinned_feed_national_state_surface_restores_the_fences( registry, surface, _ = pinned_feed_national_state_surface assert len(registry.specs) == 33_250 assert len(surface.specs) == 6_102 - assert surface.version == "e1f9906bf0e0" + assert surface.version == "61f5cac06310" chip = [ spec for spec in surface.specs @@ -1043,6 +1045,9 @@ def test_pinned_feed_corrects_the_translated_congressional_district_specs( "soi-congressional-district-2022" ) ) + # The 60 Historic Table 2 capital-gains return counts rebased onto the + # congressional-district US row (51 of them on national_state), and no + # restamped share: no compile on main rebases a restamped row. assert ( sum( "uprating_index_source_vintage_correction" in spec.metadata @@ -1050,33 +1055,55 @@ def test_pinned_feed_corrects_the_translated_congressional_district_specs( ) == 60 ) + assert not [ + spec.name + for spec in registry.specs + if "uprating_from_period_vintage_stamped_period" in spec.metadata + ] -def test_pinned_feed_capital_gains_returns_control_reads_its_data_year( - pinned_feed_national_state_surface, +def test_pinned_feed_rebased_specs_read_restamped_inputs_at_their_data_year( + pinned_feed_facts, pinned_feed_national_state_surface ) -> None: - """The Historic Table 2 net-capital-gains return counts rebase onto the - congressional-district file's US row, which is TY2022 data stamped - ty2023. The rebase lands them at the control's data year, 2022; the - counts never age, so no value moves. Which control those rows should use - is a separate concept question: the Table 1.4 ty2023 row counts a - different return population.""" - _, surface, _ = pinned_feed_national_state_surface - control_id = ( - "irs_soi.ty2023.congressional_district_2022.all_returns.us." - "net_capital_gains_returns" - ) - rebased = [ - spec - for spec in surface.specs - if spec.metadata.get("uprating_index_source_record_id") == control_id - ] - assert len(rebased) == 51 + """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: - assert spec.metadata["uprating_to_period"] == "2022" - assert spec.metadata["uprating_index_source_vintage_stamped_period"] == "2023" - assert spec.metadata["uprating_factor"] == "0.97964474977721" - assert spec.metadata["aging_factor_source"] == "not_dollar_amount" + 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: From f87844fa8ee94833ff6af00df6ac81f94c1369e4 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:29:44 -0400 Subject: [PATCH 16/30] Make the source-vintage property reach admitted shares at volume The extended generator drew each correction's vintage independently, so a same-package, same-stamp, same-data-year share total was rare and almost every call with a rebased restamp refused: 13 admitted shares in 500 examples. Each case now draws a small vintage pool, and half the cases are well-formed (every rebased restamp is a valid share), which leaves the other half to exercise the exact refusal oracle. Measured over 500 examples: 100 admitted shares (plus their idempotent second pass), 34 refused calls, 122 control corrections. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_source_vintage.py | 65 +++++++++++++++---- 1 file changed, 53 insertions(+), 12 deletions(-) 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 index 82f9aa32ca..37a9eb81cb 100644 --- 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 @@ -574,6 +574,10 @@ def test_apply_refuses_a_multi_fact_spec_with_a_restamped_member() -> None: ) +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 @@ -591,8 +595,8 @@ def test_correction_invariants_hold_for_generated_registries() -> None: record_ids = [f"irs_soi.ty2023.r{i}" for i in range(5)] years = st.integers(2015, 2026) - # A few shared vintages make same-package shares common; the free draw - # keeps mixed packages, stamps and data years in play. + # A few fixed vintages make same-package shares common; the free draw + # keeps any package, stamp and data year in play. vintages = st.one_of( st.sampled_from( [("pkg_a", 2023, 2022), ("pkg_a", 2024, 2022), ("pkg_b", 2023, 2022)] @@ -605,10 +609,16 @@ def test_correction_invariants_hold_for_generated_registries() -> None: ) @st.composite - def cases(draw): + def cases(draw, well_formed): + # well_formed: every restamped spec that is rebased is a valid share, + # so the call is admitted and the admitted-share invariants get + # exercised; otherwise shares are free and most calls refuse. corrections = {} + # A small pool per case makes same-vintage totals common and keeps + # mixed packages, stamps and data years among them. + 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(vintages) + package_id, stamped, data = draw(st.sampled_from(pool)) corrections[record_id] = SourceVintageCorrection( record_id, package_id, stamped, data ) @@ -626,6 +636,17 @@ def period_near(record_id): ) ) + def same_vintage_totals(record_id): + # Other corrections of the row's own package, stamp and data year. + backing = corrections.get(record_id) + if backing is None: + return [] + return [ + other + for other, correction in corrections.items() + if other != record_id and _vintage(correction) == _vintage(backing) + ] + specs = [] for index in range(draw(st.integers(0, 8))): record_id = draw(st.sampled_from(record_ids)) @@ -648,14 +669,35 @@ def period_near(record_id): metadata["uprating_to_period"] = metadata[ "uprating_index_source_period" ] - if draw(st.booleans()): + same = same_vintage_totals(record_id) + restamped = record_id in corrections + if draw(st.booleans()) and not (well_formed and restamped and not same): metadata["uprating_factor"] = "0.5" - if draw(st.integers(0, 4)): - metadata["uprating_from_period"] = str(period_near(record_id)) - if draw(st.integers(0, 4)): + if same and well_formed: + # A well-formed share: a same-vintage total, read at + # the stamp or the data year. + correction = corrections[record_id] metadata["soi_share_total_source_record_id"] = draw( - st.sampled_from([*record_ids, "irs_soi.ty2023.truthful"]) + st.sampled_from(same) + ) + metadata["uprating_from_period"] = str( + draw( + st.sampled_from( + [correction.stamped_year, correction.data_year] + ) + ) ) + else: + if draw(st.integers(0, 4)): + metadata["uprating_from_period"] = str( + period_near(record_id) + ) + if draw(st.integers(0, 4)): + metadata["soi_share_total_source_record_id"] = draw( + st.sampled_from( + [*same, *record_ids, "irs_soi.ty2023.truthful"] + ) + ) specs.append( _spec( f"spec{index}", @@ -683,8 +725,7 @@ def admitted_share(spec, corrections): ) return ( total is not None - and (total.package_id, total.stamped_year, total.data_year) - == (backing.package_id, backing.stamped_year, backing.data_year) + and _vintage(total) == _vintage(backing) and spec.metadata.get("uprating_from_period") in (str(backing.stamped_year), str(backing.data_year)) ) @@ -697,7 +738,7 @@ def refused(spec, corrections): ) @settings(max_examples=500, deadline=None) - @given(cases()) + @given(st.one_of(cases(well_formed=False), cases(well_formed=True))) def check(case): specs, corrections = case registry = TargetRegistry(specs, country="us") From 6031a1cdfbdd51e2c6c1b41d1f9e81203edc2bf8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:33:17 -0400 Subject: [PATCH 17/30] Prove an admitted share ages exactly as its truthfully stamped twin Differential at the value level, inside #1030: one congressional-district capital-gains share built from the package stamped ty2023 (then corrected) and from the package stamped truthfully at 2022 ages to the same value, from the control's 2023 period on the direct CBO 2024/2023 ratio, and passes the period contract. Starting the aging at the data year instead multiplies by the Table 1.4 TY2022-to-TY2023 ratio a second time; the test pins that contrast. Before this, the aging start was checked only through metadata. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_source_vintage.py | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) 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 index 37a9eb81cb..c828de5a61 100644 --- 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 @@ -451,6 +451,84 @@ def test_apply_admits_a_share_of_a_restamped_total_of_the_same_package() -> None 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"), [ From b6adb8f257c212687bfd51a01b6524ea4c682808 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:36:02 -0400 Subject: [PATCH 18/30] Let the source-vintage property catch a share total of another data year Every fixed vintage in the generator had data year 2022, so a mutant that stopped comparing the share total's data year survived the property and was caught only by the parametrized refusal. The pool gains ("pkg_a", 2023, 2020), so each kind of near miss (package, stamp, data year) is common. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_source_vintage.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) 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 index c828de5a61..1a8c33da49 100644 --- 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 @@ -673,11 +673,18 @@ def test_correction_invariants_hold_for_generated_registries() -> None: 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 common; the free draw - # keeps any package, stamp and data year in play. + # 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, 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( From 5f273b42c3a9653634fb8267287b9e86f6cbb7b0 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:52:09 -0400 Subject: [PATCH 19/30] Draw near-miss share totals directly in the source-vintage property A total that differs from the row's vintage in exactly one of package, stamp and data year was reachable only in the free mode and rarely alone in its call, so mutants that dropped one of those comparisons survived the property (the parametrized refusals still caught them). The generator now has three modes: free, well-formed (every rebased restamp is a valid share) and near-miss (each rebased restamp names a one-component near miss). Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_source_vintage.py | 94 +++++++++++-------- 1 file changed, 55 insertions(+), 39 deletions(-) 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 index 1a8c33da49..54a7f1739e 100644 --- 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 @@ -694,13 +694,15 @@ def test_correction_invariants_hold_for_generated_registries() -> None: ) @st.composite - def cases(draw, well_formed): - # well_formed: every restamped spec that is rebased is a valid share, - # so the call is admitted and the admitted-share invariants get - # exercised; otherwise shares are free and most calls refuse. + def cases(draw, mode): + # mode "free" draws shares at random, so most calls with a rebased + # restamp refuse. "well_formed" rebases a restamped row only as a valid + # share, so the call is admitted and the admitted-share invariants get + # exercised. "near_miss" names a total whose vintage differs from the + # row's in exactly one of package, stamp and data year. corrections = {} - # A small pool per case makes same-vintage totals common and keeps - # mixed packages, stamps and data years among them. + # A small pool per case makes same-vintage totals and near misses + # common, and keeps mixed packages, stamps and data years among them. 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)) @@ -721,17 +723,55 @@ def period_near(record_id): ) ) - def same_vintage_totals(record_id): - # Other corrections of the row's own package, stamp and data year. + def totals_differing_in(record_id, count): + # Other corrections whose vintage differs from the row's in + # exactly ``count`` of package, stamp and data year. backing = corrections.get(record_id) if backing is None: return [] return [ other for other, correction in corrections.items() - if other != record_id and _vintage(correction) == _vintage(backing) + if other != record_id + and sum( + mine != theirs + for mine, theirs in zip( + _vintage(backing), _vintage(correction), strict=True + ) + ) + == count ] + def share(record_id): + # The share keys of a rebase, or None to leave the row unrebased. + 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( + [ + *totals_differing_in(record_id, 0), + *record_ids, + "irs_soi.ty2023.truthful", + ] + ) + ) + return keys + totals = totals_differing_in(record_id, 0 if mode == "well_formed" else 1) + if not totals: + return None + return { + "soi_share_total_source_record_id": draw(st.sampled_from(totals)), + "uprating_from_period": str( + draw( + st.sampled_from([correction.stamped_year, correction.data_year]) + ) + ), + } + specs = [] for index in range(draw(st.integers(0, 8))): record_id = draw(st.sampled_from(record_ids)) @@ -754,35 +794,11 @@ def same_vintage_totals(record_id): metadata["uprating_to_period"] = metadata[ "uprating_index_source_period" ] - same = same_vintage_totals(record_id) - restamped = record_id in corrections - if draw(st.booleans()) and not (well_formed and restamped and not same): - metadata["uprating_factor"] = "0.5" - if same and well_formed: - # A well-formed share: a same-vintage total, read at - # the stamp or the data year. - correction = corrections[record_id] - metadata["soi_share_total_source_record_id"] = draw( - st.sampled_from(same) - ) - metadata["uprating_from_period"] = str( - draw( - st.sampled_from( - [correction.stamped_year, correction.data_year] - ) - ) - ) - else: - if draw(st.integers(0, 4)): - metadata["uprating_from_period"] = str( - period_near(record_id) - ) - if draw(st.integers(0, 4)): - metadata["soi_share_total_source_record_id"] = draw( - st.sampled_from( - [*same, *record_ids, "irs_soi.ty2023.truthful"] - ) - ) + if draw(st.booleans()): + keys = share(record_id) + if keys is not None: + metadata["uprating_factor"] = "0.5" + metadata.update(keys) specs.append( _spec( f"spec{index}", @@ -823,7 +839,7 @@ def refused(spec, corrections): ) @settings(max_examples=500, deadline=None) - @given(st.one_of(cases(well_formed=False), cases(well_formed=True))) + @given(st.sampled_from(["free", "well_formed", "near_miss"]).flatmap(cases)) def check(case): specs, corrections = case registry = TargetRegistry(specs, country="us") From c54d744dca3775f6ed57553e19208a617d7965d7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:53:29 -0400 Subject: [PATCH 20/30] Let the pinned CD period check hold under #1040's aged shares On a local merge of #1040, the 487 congressional-district capital-gains amount shares are admitted and aged from the control's 2023 period, and aging records that start in source_period. The counter test's "every corrected CD spec reads 2022" now allows exactly that case (a rebased spec whose source_period is its uprating_to_period), so a later merge re-pins only counts. Measured on #1040 + this branch: all 974 shares keep #1040's values. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_fiscal_targets.py | 7 +++++++ 1 file changed, 7 insertions(+) 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 6231e73795..1607698efe 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 @@ -1038,8 +1038,15 @@ def test_pinned_feed_corrects_the_translated_congressional_district_specs( ("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" From 2755e7530e99e0df39f2ffc9259a5cbce9b53af7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 10:55:53 -0400 Subject: [PATCH 21/30] Note which feed case the control-correction unit test models Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_source_vintage.py | 4 ++++ 1 file changed, 4 insertions(+) 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 index 54a7f1739e..814a5b52a7 100644 --- 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 @@ -362,6 +362,10 @@ def test_apply_refuses_a_backed_spec_compared_at_another_period() -> None: 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" From c04a81eba26408362380b0e0575b75bb188bbc37 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 11:06:30 -0400 Subject: [PATCH 22/30] Build each property share's total explicitly in the well-formed and near-miss modes Hypothesis favours one-vintage pools, so a well-formed or near-miss partner often did not exist and the admitted-share count swung from 13 to 64 per 500 examples between runs; two mutants (stamp not compared, missing total admitted) survived the property alone. Each rebased restamp in those modes now gets a total of its own: at the row's vintage (well-formed) or one component off (near-miss). Two runs: 55 and 124 admitted shares, 64 and 44 refused calls, 129 and 116 control corrections. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_source_vintage.py | 67 ++++++++----------- 1 file changed, 28 insertions(+), 39 deletions(-) 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 index 814a5b52a7..90ae1cc7a9 100644 --- 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 @@ -700,13 +700,14 @@ def test_correction_invariants_hold_for_generated_registries() -> None: @st.composite def cases(draw, mode): # mode "free" draws shares at random, so most calls with a rebased - # restamp refuse. "well_formed" rebases a restamped row only as a valid - # share, so the call is admitted and the admitted-share invariants get - # exercised. "near_miss" names a total whose vintage differs from the - # row's in exactly one of package, stamp and data year. + # 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 a total whose vintage + # differs in exactly one of package, stamp and data year. corrections = {} - # A small pool per case makes same-vintage totals and near misses - # common, and keeps mixed packages, stamps and data years among them. + # 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)) @@ -727,27 +728,8 @@ def period_near(record_id): ) ) - def totals_differing_in(record_id, count): - # Other corrections whose vintage differs from the row's in - # exactly ``count`` of package, stamp and data year. - backing = corrections.get(record_id) - if backing is None: - return [] - return [ - other - for other, correction in corrections.items() - if other != record_id - and sum( - mine != theirs - for mine, theirs in zip( - _vintage(backing), _vintage(correction), strict=True - ) - ) - == count - ] - def share(record_id): - # The share keys of a rebase, or None to leave the row unrebased. + # The share keys of a rebase. correction = corrections.get(record_id) if mode == "free" or correction is None: keys = {} @@ -756,19 +738,28 @@ def share(record_id): if draw(st.integers(0, 4)): keys["soi_share_total_source_record_id"] = draw( st.sampled_from( - [ - *totals_differing_in(record_id, 0), - *record_ids, - "irs_soi.ty2023.truthful", - ] + sorted({*record_ids, *corrections}) + + ["irs_soi.ty2023.truthful"] ) ) return keys - totals = totals_differing_in(record_id, 0 if mode == "well_formed" else 1) - if not totals: - return None + # A total of its own, restamped at the row's vintage (well-formed) + # or at a vintage that differs in exactly one component. + package_id, stamped, data = _vintage(correction) + if mode == "near_miss": + component = draw(st.sampled_from(["package", "stamp", "data"])) + if component == "package": + package_id = "pkg_b" if package_id == "pkg_a" else "pkg_a" + elif component == "stamp": + stamped += 1 + else: + data -= 1 + total_id = f"irs_soi.ty2023.total{len(corrections)}" + corrections[total_id] = SourceVintageCorrection( + total_id, package_id, stamped, data + ) return { - "soi_share_total_source_record_id": draw(st.sampled_from(totals)), + "soi_share_total_source_record_id": total_id, "uprating_from_period": str( draw( st.sampled_from([correction.stamped_year, correction.data_year]) @@ -799,10 +790,8 @@ def share(record_id): "uprating_index_source_period" ] if draw(st.booleans()): - keys = share(record_id) - if keys is not None: - metadata["uprating_factor"] = "0.5" - metadata.update(keys) + metadata["uprating_factor"] = "0.5" + metadata.update(share(record_id)) specs.append( _spec( f"spec{index}", From ca040d70ee7f3b97fbd9abb27dc68abd63d80aae Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 11:07:42 -0400 Subject: [PATCH 23/30] Name the share reading period's stamp key in the restamp docs Co-Authored-By: Claude Opus 5.5 --- docs/us-chronicle-feed-repin.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 9124fb05f4..b30271be7e 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -273,8 +273,9 @@ 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`. Values and target names -do not change. Two readings still see the stamp, because moving them would +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. From d3a62535043da60ed63f2663b3e19d3cb3c70666 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 11:41:12 -0400 Subject: [PATCH 24/30] Run the column exclusion before the district crosswalk; address the #1040 re-review nits From the #1224 review (P2/P3), carried here byte-identical: the congressional-district crosswalk sums source districts under the first contributor's layout, so US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS and the missing-column refusal now run on each source fact before translation, in the compile and the receipt (which therefore lists 4 x 480 source ids); tests cover mixed-column merges in both orders, every missing-column order, and a corrected A85770 PTC amount. From the #1040 re-review (APPROVE WITH NITS): the doc says the return counts agree among the tightest pairs (ninth of 45 by median gap) and that the CD-over-HT2 tilt holds in aggregate (Montana's amount is 0.73x); the congressional-district parity-manifest note names the capital-gains shares, the retired US row and the column exclusions. Co-Authored-By: Claude Opus 5.5 --- docs/us-soi-capital-gains-concepts.md | 11 +- .../build/us/target_parity_manifest.json | 2 +- .../build/us_runtime/fiscal_targets.py | 33 ++++- .../engine_free/us/test_us_fiscal_targets.py | 126 +++++++++++++++++- tools/build_us_target_parity_manifest.py | 5 +- 5 files changed, 157 insertions(+), 20 deletions(-) diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md index bea1ea2e5d..b945d54081 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -158,8 +158,8 @@ takes (a): 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 as well as any - pair on `full`; the amounts are the loosest pair.** Both files' state rows +- **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 @@ -175,9 +175,10 @@ 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. Every congressional-district capital-gains target -therefore sits above the matching HT2 share, by 0.8% for returns and 2.1% -for amounts in aggregate. This is accepted, not corrected. The model has +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 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 6de4b30b49..7b4654ff2e 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 @@ -523,7 +523,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/fiscal_targets.py b/packages/microcosm-build/src/microcosm/build/us_runtime/fiscal_targets.py index c3f50779f8..ccb186955b 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 @@ -1103,7 +1103,7 @@ def compile_us_fiscal_target_registry( auditable waiver instead of raising; every waived target carries ``period_contract_waiver`` metadata in diagnostics. """ - 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, @@ -1186,7 +1186,8 @@ def us_fiscal_target_exclusion_receipt( ``_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 (dropped). + 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 @@ -1197,7 +1198,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, @@ -1205,7 +1212,6 @@ def us_fiscal_target_exclusion_receipt( ) reviewed: set[str] = set() all_vintage: set[str] = set() - source_column: set[str] = set() m_chip: set[str] = set() for fact in materialized_facts: source_record_id = _source_record_id(fact) @@ -1215,8 +1221,6 @@ def us_fiscal_target_exclusion_receipt( all_vintage.add(source_record_id) elif source_record_id in US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: reviewed.add(source_record_id) - elif _is_source_column_concept_exclusion(fact): - source_column.add(source_record_id) elif _source_name(fact) == "cms_medicaid": reference = _reference_from_ledger_fact(fact, target_period=target_period) if reference is not None and _is_m_chip_state_chip_enrollment( @@ -3206,6 +3210,23 @@ def _is_source_column_concept_exclusion(fact: object) -> bool: 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) 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 215b0f5773..21cbceadfc 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 @@ -814,8 +814,17 @@ def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: 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] + facts = [*packaged_reference_facts(), *mislabeled, corrected, ptc, ptc_amount] registry = compile_us_fiscal_target_registry( facts, allow_unaged_dollar_targets=True @@ -825,6 +834,7 @@ def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: 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" ] @@ -891,6 +901,107 @@ def test_source_column_exclusion_refuses_a_district_fact_without_a_column() -> N } +#: 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 five-rule synthetic feed, each rule @@ -988,10 +1099,11 @@ 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), the ty2020 and - ty2023 tips return counts, and the 1,952 congressional-district SALT and - premium-tax-credit facts read from the wrong IRS column (488 per measure - after the district crosswalk: the US row, 51 states, 436 districts), and - allows no vintage bypass (decision d179, microcosm#1038).""" + 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"] @@ -1023,8 +1135,8 @@ def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> No f".{measure}" in source_record_id for source_record_id in column_ids ) for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS - } == {measure: 488 for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} - assert len(column_ids) == 4 * 488 + } == {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( diff --git a/tools/build_us_target_parity_manifest.py b/tools/build_us_target_parity_manifest.py index 0b8548ebe3..ade3f8b4aa 100644 --- a/tools/build_us_target_parity_manifest.py +++ b/tools/build_us_target_parity_manifest.py @@ -537,7 +537,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)." ), } From 4bcf9cc1c083340a197652a89330081bf36e55fe Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 12:38:35 -0400 Subject: [PATCH 25/30] Give the property's near misses a bad reading period too A rebased restamp with a valid total but a reading period that is neither the stamp nor the data year (or none) arose only in the free mode, so a mutant that skipped that check was caught by the property in one sweep run and not in another. The near-miss mode now draws exactly one defect among package, stamp, data year and reading period. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_source_vintage.py | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) 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 index 90ae1cc7a9..6b7a666c40 100644 --- 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 @@ -702,8 +702,8 @@ 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 a total whose vintage - # differs in exactly one of package, stamp and data year. + # 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 @@ -743,29 +743,42 @@ def share(record_id): ) ) return keys - # A total of its own, restamped at the row's vintage (well-formed) - # or at a vintage that differs in exactly one component. + # 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"])) + 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 - else: + 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 ) - return { - "soi_share_total_source_record_id": total_id, - "uprating_from_period": str( - draw( - st.sampled_from([correction.stamped_year, correction.data_year]) - ) - ), - } + 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))): From 03ceca6adf5cca1818caea27f097a874fea01e36 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 12:46:26 -0400 Subject: [PATCH 26/30] Compare state AGI bands per state and measure in the restamp shadow guard Round-3 review (GPT-6.1 Sol) noted a dormant gap from the merge with #940: a state AGI band's selection key ends in its period, and one whole vintage is then kept per state and measure, so the shadow guard, which compared candidates per key, could not see a restamped band vintage displacing a truthful band vintage of another period or other bounds. The guard now compares flagged bands at the grain selection uses. No restamped package on the pinned feed carries band rows, so no compile changes; the new unit test fails on the previous guard. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/fiscal_targets.py | 29 +++++++++++--- .../engine_free/us/test_us_fiscal_targets.py | 40 +++++++++++++++++++ 2 files changed, 63 insertions(+), 6 deletions(-) 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 0e7db0ef47..7d780289db 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 @@ -2810,23 +2810,25 @@ def _refuse_restamps_that_shadow_newer_vintages( 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. + 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 = [ - candidate - for candidate in candidates - if _not_after_target_period(candidate[1], target_period_key) + (_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: + 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: + 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 @@ -2840,6 +2842,21 @@ def _refuse_restamps_that_shadow_newer_vintages( 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, ...]]: 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 1607698efe..a17fefdba0 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 @@ -4863,6 +4863,46 @@ def test_age_targets_reads_a_restamped_w2_tips_amount_at_its_data_year() -> None ) +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 47b590f3836ae175fca803c92e693d470b8c5aed Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 12 Oct 2026 13:40:34 -0400 Subject: [PATCH 27/30] Run the column exclusion before the district crosswalk merges source districts (#1224 review) The congressional-district vintage crosswalk sums several source districts into one current district under the first contributor's layout, so a check after translation could see an excluded contribution under a corrected column, or a missing column hidden behind a present one. The source-column exclusion and the missing-column refusal now run on each fact as the feed carries it, before translation, in the compile and in the receipt, which therefore lists source ids (4 x 480 on the pinned feed). Tests cover mixed-column merges in both orders and every missing-column order (the old post-crosswalk check fails four of the six), and a corrected A85770 PTC amount, which must compile. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/fiscal_targets.py | 33 ++++- .../engine_free/us/test_us_fiscal_targets.py | 126 +++++++++++++++++- 2 files changed, 146 insertions(+), 13 deletions(-) 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 d600667cd2..a395b64b06 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 @@ -1102,7 +1102,7 @@ def compile_us_fiscal_target_registry( auditable waiver instead of raising; every waived target carries ``period_contract_waiver`` metadata in diagnostics. """ - 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, @@ -1185,7 +1185,8 @@ def us_fiscal_target_exclusion_receipt( ``_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 (dropped). + 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 @@ -1196,7 +1197,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, @@ -1204,7 +1211,6 @@ def us_fiscal_target_exclusion_receipt( ) reviewed: set[str] = set() all_vintage: set[str] = set() - source_column: set[str] = set() m_chip: set[str] = set() for fact in materialized_facts: source_record_id = _source_record_id(fact) @@ -1214,8 +1220,6 @@ def us_fiscal_target_exclusion_receipt( all_vintage.add(source_record_id) elif source_record_id in US_FISCAL_TARGET_SUPPORT_EXCLUSIONS: reviewed.add(source_record_id) - elif _is_source_column_concept_exclusion(fact): - source_column.add(source_record_id) elif _source_name(fact) == "cms_medicaid": reference = _reference_from_ledger_fact(fact, target_period=target_period) if reference is not None and _is_m_chip_state_chip_enrollment( @@ -3039,6 +3043,23 @@ def _is_source_column_concept_exclusion(fact: object) -> bool: 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) 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 a53b624516..80696fca29 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 @@ -814,8 +814,17 @@ def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: 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] + facts = [*packaged_reference_facts(), *mislabeled, corrected, ptc, ptc_amount] registry = compile_us_fiscal_target_registry( facts, allow_unaged_dollar_targets=True @@ -825,6 +834,7 @@ def test_source_column_exclusion_drops_only_the_mislabeled_column() -> None: 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" ] @@ -891,6 +901,107 @@ def test_source_column_exclusion_refuses_a_district_fact_without_a_column() -> N } +#: 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 five-rule synthetic feed, each rule @@ -988,10 +1099,11 @@ 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), the ty2020 and - ty2023 tips return counts, and the 1,952 congressional-district SALT and - premium-tax-credit facts read from the wrong IRS column (488 per measure - after the district crosswalk: the US row, 51 states, 436 districts), and - allows no vintage bypass (decision d179, microcosm#1038).""" + 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"] @@ -1023,8 +1135,8 @@ def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> No f".{measure}" in source_record_id for source_record_id in column_ids ) for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS - } == {measure: 488 for measure, _ in US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS} - assert len(column_ids) == 4 * 488 + } == {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( From a86a7af104f97de7a65f42066ce1c334d9c29d8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:02:53 +0000 Subject: [PATCH 28/30] Align the merged PRs with main's #1244 district guards #1244 merged after these PRs were last updated, and made every district guard match the record-set family at any data vintage. Three items did not show as text conflicts: - fiscal_targets.py: remove #1036's second copy of _soi_record_set_family. main has had the same function, byte for byte, since #1244. - fiscal_targets.py: the column register's missing-column refusal (#1224) now finds a district fact by family, as every other district guard does, instead of by the ".congressional_district_" substring. - test_us_soi_congressional_district_vintage.py: #1224 and #1040 delete _is_soi_cd_premium_tax_credit_amount_conflict, which #1244's tests called. The tests now check the column register: a district PTC amount must name its IRS column, the A85530 column is dropped at any vintage, and A85770 is kept. The compile test gives its PTC facts the A85530 column, as the pinned feed does. Co-Authored-By: Claude Opus 5.5 --- .../build/us_runtime/fiscal_targets.py | 25 +----- ...t_us_soi_congressional_district_vintage.py | 88 ++++++++++++++----- 2 files changed, 69 insertions(+), 44 deletions(-) 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 9a3dcad370..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 @@ -1856,26 +1856,6 @@ def _soi_capital_gains_active_totals( return controls -def _soi_record_set_family(record_set_id: str) -> str: - """An SOI record set's table family, without period or data vintage. - - ``irs_soi.ty2023.table_1_4`` is ``table_1_4``, - ``irs_soi.ty2022.historic_table_2.state_broad`` is ``historic_table_2`` and - ``irs_soi.ty2023.congressional_district_2022.all_returns`` is - ``congressional_district``. - """ - parts = record_set_id.split(".") - if parts[0] != "irs_soi": - return "" - rest = parts[2:] if len(parts) > 1 and _is_period_token(parts[1]) else parts[1:] - if not rest: - return "" - family = rest[0] - if family.startswith("congressional_district"): - return "congressional_district" - return family - - 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( @@ -3392,8 +3372,9 @@ def _is_source_column_concept_exclusion(fact: object) -> bool: return False column = _str_at(fact, "layout", "source_column_id") if not column: - # Any congressional-district package, whatever its boundary vintage. - if ".congressional_district_" in _str_at(fact, "layout", "record_set_id"): + # 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 " 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 From 79a3c3e9e7cdc38d4e6ed0d650e5179b42d45b90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:31:10 +0000 Subject: [PATCH 29/30] Re-pin the SOI corrections on the 41b2fb2 feed The four PRs were pinned on the 51aa40f feed. On the 41b2fb2 feed that main pins, compiled as the release does: - Compile: 31,748 targets (full 4cc4cfb7a147), from 33,250 (bf021cdc9749). - national_state: 6,102 targets at 4dfe25b1238a, from c698e70d33ce. 52 values move. The 51 Historic Table 2 state net-capital-gains return counts move x0.415203: their sum goes from 29,599,604 to 12,289,836, against the national Table 1.4 target of 12,392,020. The W-2 Box 7 tips amount moves from $28,280,884,269 to $34,287,530,779. - ACS local state: the same 4,380 specs, and the same 51 return counts move. state_cd: the same 26,425 specs; its contract test passes unchanged. - ACS local totals: 102 SOI specs, from 607. full: 29,824, from 31,321. #1224 and #1040 pinned 31,786 and 31,784 compiled targets, and 120 and 29,860 local SOI specs. Their last commits run the column exclusion before the district crosswalk, and the crosswalk copies a state row to an at-large district only for a measure that the district file carries. So the 36 Historic Table 2 SALT and premium-tax-credit rows copied to the nine at-large districts no longer compile (18 of them in totals). Each repeated its state row, and no production surface uses them. The pins and docs now say so. #1030's counter takes the values that its PR body gives for a merge with #1040: 10,900 / 11,772 / 1,300 / 1,350 / 2 / 1. No spec is rebased onto a restamped control, and the 974 district capital-gains shares are admitted restamped shares. Docs: the 41b2fb2 measurement in us-chronicle-feed-repin.md, us-acs-local-soi-target-surface.md and us-soi-capital-gains-concepts.md. The parity manifest's ed_fsa evidence now says 31,748 targets, regenerated with tools/build_us_target_parity_manifest.py. Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-soi-target-surface.md | 14 ++-- docs/us-chronicle-feed-repin.md | 32 ++++++--- docs/us-soi-capital-gains-concepts.md | 5 ++ .../build/us/target_parity_manifest.json | 22 +++--- .../us/test_us_acs_local_release_tool.py | 13 ++-- .../engine_free/us/test_us_fiscal_targets.py | 69 ++++++++++--------- tools/build_us_target_parity_manifest.py | 2 +- 7 files changed, 96 insertions(+), 61 deletions(-) diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index b562f9b6b7..c3fec3c67c 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -84,14 +84,18 @@ With the 487 population marginals `state` now calibrates to 4,867 targets. 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` are -unchanged. `totals` loses the 487 district-file premium-tax-credit return -rows and `full` loses those and the 974 district-file SALT rows: +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 | 120 | 29,860 | -| **Admin specs** | **4,380** | **273** | **30,013** | +| `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. diff --git a/docs/us-chronicle-feed-repin.md b/docs/us-chronicle-feed-repin.md index 2877bf646a..94d3c4e1c0 100644 --- a/docs/us-chronicle-feed-repin.md +++ b/docs/us-chronicle-feed-repin.md @@ -580,6 +580,22 @@ 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 @@ -708,18 +724,18 @@ 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 need a decision before that re-pin: +Two things needed a decision before that re-pin: -- **The Historic Table 2 capital-gains returns control.** The CD US row wins a +- **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%. Today the - 51 state counts sum to 2.39× the national Table 1.4 target of the same - compiled variable. microcosm#1036 (decision d468) chooses the control by - concept instead; no restamped row is then a capital-gains control, and the - 60 control corrections above go away. + 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. + 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 diff --git a/docs/us-soi-capital-gains-concepts.md b/docs/us-soi-capital-gains-concepts.md index b945d54081..7569150b0d 100644 --- a/docs/us-soi-capital-gains-concepts.md +++ b/docs/us-soi-capital-gains-concepts.md @@ -217,6 +217,11 @@ below (#1224), which remove 1,464 of the 1,466 specs: | 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. 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 4b6dc495a4..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.", 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 065e4c5687..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 @@ -3736,10 +3736,15 @@ def test_pinned_feed_soi_surfaces_match_their_contracts() -> None: 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 Historic Table 2 premium-tax-credit rows (51 states and 9 at-large - # district copies, returns and amounts) and `full` 29,860 SOI specs. + # 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) == 120 + 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", @@ -3749,7 +3754,7 @@ def test_pinned_feed_soi_surfaces_match_their_contracts() -> None: 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_860 + 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 f9f499e71b..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 @@ -1142,21 +1142,23 @@ def test_pinned_feed_exclusion_receipt(pinned_feed_national_state_surface) -> No def test_pinned_feed_national_state_surface_restores_the_fences( pinned_feed_national_state_surface, ) -> None: - """The release surface on the pinned feed: 31,784 compiled - targets after Medicaid substitution (the full surface, at - 6e1ac91262bc), 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. microcosm#1038 took it from - 33,250 compiled: it drops the congressional-district capital-gains US - rows and (#1224) the congressional-district SALT and premium-tax-credit - rows read from the wrong IRS column, all on the full surface, and moves - national_state only by one provenance key, soi_share_total_source_record_id, - on the 102 Historic Table 2 capital-gains rows. microcosm#1035 moved the - national_state version at the same counts by choosing the capital-gains - control by concept and period, which returns the 51 Historic Table 2 state - return counts to Table 1.4 shares. Reading the restamped W-2 tips - amount at TY2020 (microcosm#1030) moved the national_state version - with the counts unchanged. 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 @@ -1175,12 +1177,12 @@ def test_pinned_feed_national_state_surface_restores_the_fences( from microcosm.calibrate import TargetRegistry registry, surface, _ = pinned_feed_national_state_surface - assert len(registry.specs) == 31_784 + 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 == "6e1ac91262bc" + 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 @@ -1637,11 +1639,13 @@ def test_pinned_feed_corrects_the_translated_congressional_district_specs( 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): 11_772, - ("soi-congressional-district-2022", True, False): 12_208, - ("soi-congressional-district-2022", False, True): 1_404, - ("soi-congressional-district-2022", False, False): 1_404, + ("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, } @@ -1659,21 +1663,22 @@ def test_pinned_feed_corrects_the_translated_congressional_district_specs( "soi-congressional-district-2022" ) ) - # The 60 Historic Table 2 capital-gains return counts rebased onto the - # congressional-district US row (51 of them on national_state), and no - # restamped share: no compile on main rebases a restamped row. + # 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_index_source_vintage_correction" in spec.metadata + "uprating_from_period_vintage_stamped_period" in spec.metadata for spec in registry.specs ) - == 60 + == 974 ) - assert not [ - spec.name - for spec in registry.specs - if "uprating_from_period_vintage_stamped_period" in spec.metadata - ] def test_pinned_feed_rebased_specs_read_restamped_inputs_at_their_data_year( diff --git a/tools/build_us_target_parity_manifest.py b/tools/build_us_target_parity_manifest.py index eecdd79e0d..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=( From 006afbedc8c2f36e7757b152f950fcdfa521c103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:07:44 +0000 Subject: [PATCH 30/30] List source_vintage among the modules the gate bindings reach engine-free failed at 79a3c3e9e: test_the_batterys_binding_identity_adds_only_the_leaf_and_its_imports counted 249 modules, not 248. #1030 makes us_runtime.fiscal_targets import us_runtime.source_vintage, so the gate bindings reach one more module. Add it to BINDING_MODULES_ADDED_AFTER_BASE with its reason. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/shared/test_transport_evidence_kernels.py | 3 +++ 1 file changed, 3 insertions(+) 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",