diff --git a/changelog.d/soi-table-1-4-entity-legs.added.md b/changelog.d/soi-table-1-4-entity-legs.added.md new file mode 100644 index 00000000..2527e0c5 --- /dev/null +++ b/changelog.d/soi-table-1-4-entity-legs.added.md @@ -0,0 +1,4 @@ +IRS SOI Table 1.4 now carries the partnership and S corporation net income and +net loss legs (returns and amounts by AGI range) for TY2021 to TY2023. A source +package measure can now declare the years it applies to; TY2020 combines the two +legs, so these eight measures skip it and its record layout keeps its hash. diff --git a/chronicle/source_package.py b/chronicle/source_package.py index a23060e6..6e8809a4 100644 --- a/chronicle/source_package.py +++ b/chronicle/source_package.py @@ -2036,6 +2036,7 @@ def to_record_set_spec(self, year: int) -> SourceRecordSetSpec: measures = tuple( _measure_from_mapping(measure, year=year) for measure in _required(self.payload, "measures", "record_set") + if _mapping_applies_to_year(measure, year=year, context="measure") ) return SourceRecordSetSpec( record_set_id=_render_required_string( @@ -3861,6 +3862,55 @@ def _required(payload: dict[str, Any], key: str, context: str) -> Any: return payload[key] +def _mapping_applies_to_year( + payload: dict[str, Any], + *, + year: int, + context: str, +) -> bool: + """Return whether a declarative mapping applies to the requested year.""" + years = payload.get("years") + if years is None: + return True + identifier = payload.get(f"{context}_id") + context_label = f"{context} {identifier!r}" if identifier else context + if not isinstance(years, list) or not years: + raise ValueError(f"{context_label} years must be a non-empty list") + if any(isinstance(item, bool) or not isinstance(item, int) for item in years): + raise ValueError(f"{context_label} years entries must be integers") + if len(set(years)) != len(years): + raise ValueError(f"{context_label} years entries must be unique") + # Every per-year map must cover exactly the declared years: a map year + # outside ``years`` would drop the mapping at that year without an error. + by_year_keys = sorted( + key for key in payload if isinstance(key, str) and key.endswith("_by_year") + ) + if "column_by_year" in by_year_keys: + by_year_keys.remove("column_by_year") + by_year_keys.insert(0, "column_by_year") + for key in by_year_keys: + mapped = payload[key] + if not isinstance(mapped, dict): + raise ValueError(f"{context_label} {key} must map years to values") + for declared_year in years: + if declared_year not in mapped and str(declared_year) not in mapped: + raise ValueError( + f"{context_label} {key} has no entry for " + f"declared year {declared_year}" + ) + extra = sorted( + str(mapped_year) + for mapped_year in mapped + if str(mapped_year) not in {str(item) for item in years} + ) + if extra: + raise ValueError( + f"{context_label} {key} maps year(s) {', '.join(extra)} " + f"outside its years {years}" + ) + return year in years + + def _year_mapping(files_by_year: dict[Any, Any], year: int) -> dict[str, str]: if year in files_by_year: return files_by_year[year] diff --git a/docs/agent-source-package-harness.md b/docs/agent-source-package-harness.md index d6ebb1b4..0f4cd356 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -965,6 +965,20 @@ where HMRC writes "the" — Chronicle's UK register gives one name where it carries the identifier (chronicle#281), and the bundle warns about the areas it does not carry yet. +### Measures that apply to some years + +A measure may list `years`. A build at one of those years includes it; a build +at any other year compiles the record set without it, so that year's record +layout, and its hash, match a package without the measure. Table 1.4 uses this +for its partnership and S corporation legs, which SOI publishes separately from +TY2021 and combined in TY2020. + +The list must be non-empty and hold unique integers, and every `*_by_year` map +the measure declares (`column_by_year`, `expected_column_header_by_year`) must +cover exactly those years. A `years` entry with no map entry, or a map entry +outside `years`, refuses the build, so a new year added to the maps alone +cannot drop the measure without an error. + ### Pinned artifacts and year labels `artifact.artifact_year` pins the file. A package with `artifact_year: 2022` diff --git a/packages/irs_soi/table_1_4/source_package.yaml b/packages/irs_soi/table_1_4/source_package.yaml index 17c2a0a4..16a56738 100644 --- a/packages/irs_soi/table_1_4/source_package.yaml +++ b/packages/irs_soi/table_1_4/source_package.yaml @@ -1,6 +1,6 @@ schema_version: ledger.source_package.v1 package_id: soi-table-1-4 -label: IRS SOI Publication 1304 Table 1.4 total wages +label: IRS SOI Publication 1304 Table 1.4 income items by AGI class dimension_labels: 'agi_lower_usd': 'Adjusted gross income band lower bound' 'agi_upper_usd': 'Adjusted gross income band upper bound' @@ -883,3 +883,146 @@ record_sets: (PolicyEngine/populace#451 item 2). legal_vintage: tax_year_{year} value_scale: 1000 + # Table 1.4 publishes separate partnership and S corporation legs from + # TY2021 onward. TY2020 combines them, so these measures are deliberately + # scoped away from 2020 rather than duplicating the combined values. + - measure_id: partnership_net_income_returns + label: Returns with partnership net income + ordinal: 29 + years: [2021, 2022, 2023] + column: BP + column_by_year: + 2021: BD + 2022: BP + 2023: BP + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 55 + 2022: 67 + 2023: 67 + concept: irs_soi.returns_with_partnership_net_income + unit: count + aggregation: sum + - measure_id: partnership_net_income_amount + label: Partnership net income + ordinal: 30 + years: [2021, 2022, 2023] + column: BQ + column_by_year: + 2021: BE + 2022: BQ + 2023: BQ + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 56 + 2022: 68 + 2023: 68 + concept: irs_soi.partnership_net_income + unit: usd + aggregation: sum + value_scale: 1000 + - measure_id: partnership_net_loss_returns + label: Returns with partnership net loss + ordinal: 31 + years: [2021, 2022, 2023] + column: BR + column_by_year: + 2021: BF + 2022: BR + 2023: BR + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 57 + 2022: 69 + 2023: 69 + concept: irs_soi.returns_with_partnership_net_loss + unit: count + aggregation: sum + - measure_id: partnership_net_loss_amount + label: Partnership net loss (positive magnitude) + ordinal: 32 + years: [2021, 2022, 2023] + column: BS + column_by_year: + 2021: BG + 2022: BS + 2023: BS + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 58 + 2022: 70 + 2023: 70 + concept: irs_soi.partnership_net_loss + unit: usd + aggregation: sum + value_scale: 1000 + - measure_id: s_corporation_net_income_returns + label: Returns with S corporation net income + ordinal: 33 + years: [2021, 2022, 2023] + column: BT + column_by_year: + 2021: BH + 2022: BT + 2023: BT + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 59 + 2022: 71 + 2023: 71 + concept: irs_soi.returns_with_s_corporation_net_income + unit: count + aggregation: sum + - measure_id: s_corporation_net_income_amount + label: S corporation net income + ordinal: 34 + years: [2021, 2022, 2023] + column: BU + column_by_year: + 2021: BI + 2022: BU + 2023: BU + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 60 + 2022: 72 + 2023: 72 + concept: irs_soi.s_corporation_net_income + unit: usd + aggregation: sum + value_scale: 1000 + - measure_id: s_corporation_net_loss_returns + label: Returns with S corporation net loss + ordinal: 35 + years: [2021, 2022, 2023] + column: BV + column_by_year: + 2021: BJ + 2022: BV + 2023: BV + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 61 + 2022: 73 + 2023: 73 + concept: irs_soi.returns_with_s_corporation_net_loss + unit: count + aggregation: sum + - measure_id: s_corporation_net_loss_amount + label: S corporation net loss (positive magnitude) + ordinal: 36 + years: [2021, 2022, 2023] + column: BW + column_by_year: + 2021: BK + 2022: BW + 2023: BW + expected_column_header_row: 8 + expected_column_header_by_year: + 2021: 62 + 2022: 74 + 2023: 74 + concept: irs_soi.s_corporation_net_loss + unit: usd + aggregation: sum + value_scale: 1000 diff --git a/tests/test_chronicle_bundle.py b/tests/test_chronicle_bundle.py index 7fecc91a..266d407a 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -598,7 +598,9 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): # SSA's Supplement Tables 7.B3 and 7.B7 add 193 (128 and 65). # Historic Table 2's state Schedule 1 line 1 and Schedule A lines 7, 8a # and 14 add 408 (see above). - "fact_count": 2246063, + # IRS SOI Table 1.4's partnership and S corporation net income and loss legs + # add 160 (eight measures in 20 AGI ranges, TY2023). + "fact_count": 2246223, # The same change adds 82,064 geography keys: 46,363 Scottish 2022 # output areas (UV404), 35,673 LSOA-level keys from the DESNZ LSOA # workbooks (Scotland's data zones already exist), the 26 Northern @@ -748,7 +750,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): if row_count == 1: assert row["aggregate_fact_key"].startswith("ledger.aggregate_fact.v2:") assert row["semantic_fact_key"].startswith("ledger.semantic_fact.v2:") - assert row_count == 2246063 + assert row_count == 2246223 assert provenance_classes <= { "administrative", "census", @@ -783,7 +785,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "jct-obbba-revenue-estimates-2025", "jct-tax-expenditures-2024", ] - assert coverage["fact_count"] == 2246063 + assert coverage["fact_count"] == 2246223 assert coverage["counts"]["by_source"] == { "bea": 446, "bfp_economic_outlook": 5, @@ -810,7 +812,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "hmrc": 40025, "ici": 12, "ird": 4362, - "irs_soi": 44371, + "irs_soi": 44531, "isc": 4, "jrc_euromod_be": 90, "kff": 52, @@ -2413,6 +2415,8 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): expected_period_counts[key] = expected_period_counts.get(key, 0) + count # PolicyEngine/microcosm#1418: SPI 2023-24 Table 3.10. expected_period_counts["tax_year:2023"] += 159 + # IRS SOI Table 1.4's partnership and S corporation net income and loss legs, TY2023. + expected_period_counts["tax_year:2023"] += 160 # chronicle#393: the OBR October 2026 EFO packages, by fiscal and calendar year. for key, count in { "calendar_year:2024": 1, @@ -2903,7 +2907,8 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): == 35 ) # SSA's Supplement Tables 7.B3 and 7.B7 add four (two national cells each). - assert coverage["counts"]["by_geography"]["country:0100000US"] == 2120 + # IRS SOI Table 1.4's partnership and S corporation net income and loss legs add 160. + assert coverage["counts"]["by_geography"]["country:0100000US"] == 2280 # 255, less Vintage 2024's state total (chronicle#397), + 16 Census Vintage # 2025 age groups (15 groups and the total), + 6 from SSA's Supplement # Tables 7.B3 (four California cells) and 7.B7 (two), + 8 Historic Table 2 @@ -3034,7 +3039,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "person": 734519, "return": 16087, "social_protection_scheme": 36, - "tax_unit": 45676, + "tax_unit": 45836, } assert not coverage["duplicates"]["aggregate_fact_keys"] assert len(coverage["duplicates"]["semantic_fact_keys"]) == 4135 diff --git a/tests/test_chronicle_soi_targets.py b/tests/test_chronicle_soi_targets.py index b57a808f..b2ecf864 100644 --- a/tests/test_chronicle_soi_targets.py +++ b/tests/test_chronicle_soi_targets.py @@ -127,7 +127,7 @@ def test_build_soi_table_1_4_wage_facts_from_packaged_source(): } assert validate_facts(facts).valid - assert len(facts) == 580 + assert len(facts) == 740 assert ( facts_by_concept_and_range[("irs_soi.returns_with_total_wages", "all")].value == 128_591_050 diff --git a/tests/test_chronicle_source_package.py b/tests/test_chronicle_source_package.py index 0796c141..f47b628c 100644 --- a/tests/test_chronicle_source_package.py +++ b/tests/test_chronicle_source_package.py @@ -26,6 +26,7 @@ SOURCE_PACKAGE_SCHEMA_VERSION, DeclarativeRecordSet, SourceArtifactSpec, + _mapping_applies_to_year, _read_source_artifact_content, _render_string, _source_artifact_cache_path, @@ -220,6 +221,145 @@ def test_source_package_rejects_unknown_schema_and_names_both_epochs(tmp_path): assert schema_pair.chronicle in message +def test_record_set_measure_year_scope_preserves_legacy_layout(): + package_path = REPO_ROOT / "packages" / "irs_soi" / "table_1_4" + package = load_source_package(package_path) + legacy_set = package.build_source_record_set_specs(2020)[0] + current_set = package.build_source_record_set_specs(2023)[0] + legacy_record = package.build_source_record_specs(2020)[0] + + assert len(legacy_set.measures) == 29 + assert len(current_set.measures) == 37 + assert legacy_record.layout is not None + assert legacy_record.layout.record_set_spec_hash == "22ed3e367531f2331f744623" + assert "partnership_net_income_amount" not in { + measure.measure_id for measure in legacy_set.measures + } + assert "partnership_net_income_amount" in { + measure.measure_id for measure in current_set.measures + } + + +@pytest.mark.parametrize( + ("years", "message"), + [ + ([], "non-empty list"), + ("2023", "non-empty list"), + ([2023, "2024"], "must be integers"), + ([True, 2023], "must be integers"), + ([2023, 2023], "must be unique"), + ], +) +def test_record_set_measure_year_scope_rejects_malformed_values(years, message): + source_path = REPO_ROOT / "packages" / "irs_soi" / "table_1_4" + payload = yaml.safe_load((source_path / "source_package.yaml").read_text()) + record_set = payload["record_sets"][0] + record_set["measures"][-1]["years"] = years + + with pytest.raises(ValueError, match=message): + DeclarativeRecordSet(record_set).to_record_set_spec(2020) + + +def test_record_set_measure_year_scope_requires_every_column_mapping(): + source_path = REPO_ROOT / "packages" / "irs_soi" / "table_1_4" + payload = yaml.safe_load((source_path / "source_package.yaml").read_text()) + record_set = payload["record_sets"][0] + record_set["measures"][-1]["years"].append(2024) + + with pytest.raises(ValueError, match="no entry for declared year 2024"): + DeclarativeRecordSet(record_set).to_record_set_spec(2020) + + +def test_record_set_measure_year_scope_refuses_a_by_year_map_beyond_its_years(): + source_path = REPO_ROOT / "packages" / "irs_soi" / "table_1_4" + payload = yaml.safe_load((source_path / "source_package.yaml").read_text()) + record_set = payload["record_sets"][0] + record_set["measures"][-1]["years"].remove(2022) + + with pytest.raises(ValueError, match=r"column_by_year maps year\(s\) 2022"): + DeclarativeRecordSet(record_set).to_record_set_spec(2023) + + +def test_record_set_measure_year_scope_requires_every_header_year(): + source_path = REPO_ROOT / "packages" / "irs_soi" / "table_1_4" + payload = yaml.safe_load((source_path / "source_package.yaml").read_text()) + record_set = payload["record_sets"][0] + del record_set["measures"][-1]["expected_column_header_by_year"][2022] + + with pytest.raises( + ValueError, + match="expected_column_header_by_year has no entry for declared year 2022", + ): + DeclarativeRecordSet(record_set).to_record_set_spec(2023) + + +def test_record_set_measure_year_scope_reads_string_year_keys_and_refuses_bad_maps(): + payload = { + "measure_id": "m", + "years": [2021, 2022], + "column_by_year": {"2021": "A", "2022": "B"}, + 7: "a key the year scope ignores", + } + assert _mapping_applies_to_year(payload, year=2021, context="measure") + assert not _mapping_applies_to_year(payload, year=2020, context="measure") + + payload["column_by_year"]["2023"] = "C" + with pytest.raises(ValueError, match=r"column_by_year maps year\(s\) 2023"): + _mapping_applies_to_year(payload, year=2021, context="measure") + + payload["column_by_year"] = ["A", "B"] + with pytest.raises(ValueError, match="column_by_year must map years to values"): + _mapping_applies_to_year(payload, year=2021, context="measure") + + +def test_record_set_measure_year_scope_is_membership_for_every_small_year_set(): + """For every non-empty set of 2020-2024 and every year 2019-2025, a measure + with ``years`` applies exactly when the year is in the set, and a measure + without ``years`` applies to every year.""" + domain = (2020, 2021, 2022, 2023, 2024) + for mask in range(1, 2 ** len(domain)): + years = [year for bit, year in enumerate(domain) if mask >> bit & 1] + payload = { + "measure_id": "m", + "years": years, + "column_by_year": {year: "A" for year in years}, + } + for year in range(2019, 2026): + assert _mapping_applies_to_year(payload, year=year, context="measure") == ( + year in years + ) + for year in range(2019, 2026): + assert _mapping_applies_to_year( + {"measure_id": "m"}, year=year, context="measure" + ) + + +@pytest.mark.parametrize("year", [2021, 2022, 2023]) +def test_table_1_4_entity_legs_sum_over_income_ranges_to_all_returns(year): + """Each partnership and S corporation leg's 19 AGI ranges add up to its + all-returns row within SOI's rounding: amounts publish in thousands of + dollars (at most $500 per row) and return counts as whole numbers.""" + package = load_source_package(REPO_ROOT / "packages" / "irs_soi" / "table_1_4") + facts = package.build_facts(year, cells=package.build_source_cells(year)) + legs = ( + "partnership_net_income", + "partnership_net_loss", + "s_corporation_net_income", + "s_corporation_net_loss", + ) + by_measure = {} + for fact in facts: + *_, income_range, measure = fact.source_record_id.split(".") + if measure.startswith(legs): + by_measure.setdefault(measure, {})[income_range] = fact.value + assert len(by_measure) == 8 + for measure, by_range in by_measure.items(): + assert len(by_range) == 20, measure + total = by_range.pop("all") + tolerance = 10_000 if measure.endswith("_amount") else 10 + assert abs(sum(by_range.values()) - total) <= tolerance, measure + + def test_hmrc_packages_preserve_provenance_and_definition_year_metadata(): """HMRC facts must retain the axes needed to distinguish source claims.""" hmrc_packages = sorted( @@ -1236,9 +1376,14 @@ def test_source_package_path_builds_valid_soi_table_1_4_facts(): assert package.package_id == "soi-table-1-4" assert len(cells) == 8109 - assert len(facts) == 580 + assert len(facts) == 740 assert validate_facts(facts).valid assert facts[0].source.source_table == "Publication 1304 Table 1.4" + assert facts[0].source.url == "https://www.irs.gov/pub/irs-soi/23in14ar.xls" + assert ( + facts[0].source.source_sha256 + == "b6c1f87fbb5533417e195f6938538e5de09b6a0825a6a54346bf9363a18d96af" + ) assert ( values_by_record["irs_soi.ty2023.table_1_4.all.alimony_received_amount"].value == 6_686_429_000 @@ -1247,6 +1392,54 @@ def test_source_package_path_builds_valid_soi_table_1_4_facts(): values_by_record["irs_soi.ty2023.table_1_4.all.alimony_paid_amount"].value == 7_497_135_000 ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.partnership_net_income_returns" + ].value + == 3_266_345 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.partnership_net_income_amount" + ].value + == 452_077_038_000 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.partnership_net_loss_returns" + ].value + == 2_103_634 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.partnership_net_loss_amount" + ].value + == 168_884_100_000 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.s_corporation_net_income_returns" + ].value + == 4_138_040 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.s_corporation_net_income_amount" + ].value + == 797_450_861_000 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.s_corporation_net_loss_returns" + ].value + == 1_415_974 + ) + assert ( + values_by_record[ + "irs_soi.ty2023.table_1_4.all.s_corporation_net_loss_amount" + ].value + == 89_543_715_000 + ) def test_bea_nipa_total_wages_package_preserves_bea_concept(): diff --git a/tests/test_chronicle_suite.py b/tests/test_chronicle_suite.py index 4e445696..cddbb307 100644 --- a/tests/test_chronicle_suite.py +++ b/tests/test_chronicle_suite.py @@ -366,12 +366,12 @@ def test_build_source_suite_supports_soi_table_1_4(tmp_path): "artifact_count": 1, "agent_acceptance_error_count": 0, "concept_alignment_count": 8, - "constraint_count": 1044, - "consumer_fact_count": 580, - "fact_count": 580, + "constraint_count": 1332, + "consumer_fact_count": 740, + "fact_count": 740, "lineage_coverage": 1.0, "source_cell_count": 8109, - "source_record_count": 580, + "source_record_count": 740, "source_region_count": 1, "source_row_count": 0, }