From 3eb9eca5aa3b75d05b2be47de2009984841167c8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 00:45:37 -0500 Subject: [PATCH 1/3] Add Table 1.4's partnership and S corporation legs This recarves the Table 1.4 half of #180 onto main. Eight measures (returns and amounts, with net income and with net loss, for partnerships and for S corporations) read SOI Table 1.4 columns 67-74 in TY2022 and TY2023 and 55-62 in TY2021, and each build checks those column numbers. TY2020 publishes the two legs combined, so a per-measure `years` list scopes the eight measures away from it, and the TY2020 record layout keeps its hash. Microcosm's fiscal target registry already maps these measure ids to the entity leaves from PolicyEngine/microcosm#1258. #180's Form 8960 package stays on its branch: nothing in Microcosm reads it since d1472 closed PolicyEngine/microcosm#722's lane. Co-Authored-By: Claude Opus 5.5 --- .../soi-table-1-4-entity-legs.added.md | 4 + chronicle/source_package.py | 30 ++++ .../irs_soi/table_1_4/source_package.yaml | 145 ++++++++++++++++- tests/test_chronicle_bundle.py | 15 +- tests/test_chronicle_soi_targets.py | 2 +- tests/test_chronicle_source_package.py | 153 +++++++++++++++++- tests/test_chronicle_suite.py | 8 +- 7 files changed, 345 insertions(+), 12 deletions(-) create mode 100644 changelog.d/soi-table-1-4-entity-legs.added.md 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 c2685862..295a4639 100644 --- a/chronicle/source_package.py +++ b/chronicle/source_package.py @@ -2015,6 +2015,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( @@ -3840,6 +3841,35 @@ 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") + if "column_by_year" in payload: + columns = payload["column_by_year"] + for declared_year in years: + if declared_year not in columns and str(declared_year) not in columns: + raise ValueError( + f"{context_label} column_by_year has no entry for " + f"declared year {declared_year}" + ) + 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/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 417382be..39afe870 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -593,7 +593,9 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): # Disability Payment (1,885), Carer Support Payment (282), Child Disability # Payment (81) and Pension Age Disability Payment (66). # SSA's Supplement Tables 7.B3 and 7.B7 add 193 (128 and 65). - "fact_count": 2243268, + # 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": 2243428, # 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 @@ -773,7 +775,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "jct-obbba-revenue-estimates-2025", "jct-tax-expenditures-2024", ] - assert coverage["fact_count"] == 2243268 + assert coverage["fact_count"] == 2243428 assert coverage["counts"]["by_source"] == { "bea": 446, "bfp_economic_outlook": 5, @@ -800,7 +802,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "hmrc": 40025, "ici": 12, "ird": 4362, - "irs_soi": 43963, + "irs_soi": 44123, "isc": 4, "jrc_euromod_be": 90, "kff": 52, @@ -2396,6 +2398,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, @@ -2866,7 +2870,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). @@ -2991,7 +2996,7 @@ def test_build_bundle_writes_merged_consumer_contract(tmp_path): "person": 734519, "return": 16087, "social_protection_scheme": 36, - "tax_unit": 45268, + "tax_unit": 45428, } assert not coverage["duplicates"]["aggregate_fact_keys"] assert len(coverage["duplicates"]["semantic_fact_keys"]) == 3931 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 ec2ab487..01cb7da4 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,103 @@ 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_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 +1334,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 +1350,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, } From 1b8bb0fc1ebc01ecadd11b38f9fd670db2cd9a60 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 01:11:24 -0500 Subject: [PATCH 2/3] Make a measure's years match its per-year maps Review r1 of #437 found that a `years` list could leave out a year that `column_by_year` maps, and the build then dropped the measure at that year without an error. A measure's `years` must now cover exactly the years of every `*_by_year` map it declares, in both directions; two tests pin the two refusals. The bundle test's consumer-facts row count moves with the fact count (2,243,428), and the harness guide documents the per-measure `years` field. Co-Authored-By: Claude Opus 5.5 --- chronicle/source_package.py | 28 ++++++++++++++++++++++---- docs/agent-source-package-harness.md | 14 +++++++++++++ tests/test_chronicle_bundle.py | 2 +- tests/test_chronicle_source_package.py | 23 +++++++++++++++++++++ 4 files changed, 62 insertions(+), 5 deletions(-) diff --git a/chronicle/source_package.py b/chronicle/source_package.py index 295a4639..e4196a2f 100644 --- a/chronicle/source_package.py +++ b/chronicle/source_package.py @@ -3859,14 +3859,34 @@ def _mapping_applies_to_year( 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") - if "column_by_year" in payload: - columns = payload["column_by_year"] + # 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, value in payload.items() + if key.endswith("_by_year") and isinstance(value, dict) + ) + 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] for declared_year in years: - if declared_year not in columns and str(declared_year) not in columns: + if declared_year not in mapped and str(declared_year) not in mapped: raise ValueError( - f"{context_label} column_by_year has no entry for " + 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 diff --git a/docs/agent-source-package-harness.md b/docs/agent-source-package-harness.md index 55670284..dd824759 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -988,6 +988,20 @@ year's column, sheet or rows. A year the file does not cover fails with its own error, such as `No source artifact for year 2027` or a selected-row mismatch. +### 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. + Agents may add new package directories and YAML specs. They should not modify `chronicle.core`, `chronicle.database`, or `chronicle.suite` unless the package cannot be expressed in the current contract and the failure is documented in the build diff --git a/tests/test_chronicle_bundle.py b/tests/test_chronicle_bundle.py index 39afe870..86d836b7 100644 --- a/tests/test_chronicle_bundle.py +++ b/tests/test_chronicle_bundle.py @@ -740,7 +740,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 == 2243268 + assert row_count == 2243428 assert provenance_classes <= { "administrative", "census", diff --git a/tests/test_chronicle_source_package.py b/tests/test_chronicle_source_package.py index 01cb7da4..bdabb778 100644 --- a/tests/test_chronicle_source_package.py +++ b/tests/test_chronicle_source_package.py @@ -270,6 +270,29 @@ def test_record_set_measure_year_scope_requires_every_column_mapping(): 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_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 From b2eb2bc0bc4508fec70bbf9bf889992d86448ec1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 01:18:47 -0500 Subject: [PATCH 3/3] Refuse a non-map per-year value on a scoped measure Review r2 of #437 found two gaps in the year-scope check. A `*_by_year` value that is not a map was skipped, so the build later failed with "No source artifact" and a default bundle would skip Table 1.4. An integer payload key raised AttributeError. The check now refuses the first with a named error and ignores non-string keys. A new test pins string year keys and both refusals, and the harness guide's year-scope section moves ahead of the pinned-artifact section so it no longer sits over unrelated paragraphs. Co-Authored-By: Claude Opus 5.5 --- chronicle/source_package.py | 6 +++--- docs/agent-source-package-harness.md | 28 +++++++++++++------------- tests/test_chronicle_source_package.py | 19 +++++++++++++++++ 3 files changed, 36 insertions(+), 17 deletions(-) diff --git a/chronicle/source_package.py b/chronicle/source_package.py index e4196a2f..19005f0f 100644 --- a/chronicle/source_package.py +++ b/chronicle/source_package.py @@ -3862,15 +3862,15 @@ def _mapping_applies_to_year( # 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, value in payload.items() - if key.endswith("_by_year") and isinstance(value, dict) + 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( diff --git a/docs/agent-source-package-harness.md b/docs/agent-source-package-harness.md index dd824759..4666dc92 100644 --- a/docs/agent-source-package-harness.md +++ b/docs/agent-source-package-harness.md @@ -955,6 +955,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` @@ -988,20 +1002,6 @@ year's column, sheet or rows. A year the file does not cover fails with its own error, such as `No source artifact for year 2027` or a selected-row mismatch. -### 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. - Agents may add new package directories and YAML specs. They should not modify `chronicle.core`, `chronicle.database`, or `chronicle.suite` unless the package cannot be expressed in the current contract and the failure is documented in the build diff --git a/tests/test_chronicle_source_package.py b/tests/test_chronicle_source_package.py index bdabb778..cba16703 100644 --- a/tests/test_chronicle_source_package.py +++ b/tests/test_chronicle_source_package.py @@ -293,6 +293,25 @@ def test_record_set_measure_year_scope_requires_every_header_year(): 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